Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip: dream phases never overwrite a differing file or database body (#6982)
garrytanf8116e6a8097
diff --git a/src/core/cycle/derived-write-through.ts b/src/core/cycle/derived-write-through.tsindex dc3a7fafc2..de1bf55fea 100644--- a/src/core/cycle/derived-write-through.ts+++ b/src/core/cycle/derived-write-through.ts@@ -15,10 +15,15 @@* phase retires has its file removed, so sync cannot bring it back.*/import { execFileSync } from '../spawn.ts';-import { relative } from 'node:path';+import { existsSync, mkdirSync, readFileSync } from 'node:fs';+import { dirname, join, relative } from 'node:path';import type { BrainEngine } from '../engine.ts';+import type { PhaseResult } from '../cycle.ts';+import { atomicWriteFileSync } from '../atomic-write.ts';+import { fileDatabaseDriftFix, replaceableFile } from '../facts/file-body-guard.ts';import { isDbOnly, loadStorageConfig } from '../storage-config.ts';-import { deletePageThrough, resolvePageWriteTarget, writePageThrough } from '../write-through.ts';+import { deletePageThrough, isWriteThroughDisabled, resolvePageWriteTarget, writePageThrough } from '../write-through.ts';+import { urlCloneReadOnly } from '../url-clone.ts';import { gitChildEnv } from '../git-env.ts';export const DERIVED_WRITE_THROUGH_KEYS = {@@ -91,3 +96,54 @@ export async function derivedWriteThrough(await write(rows.map(r => r.slug));return write;}++/** What a dream reverse-write did with one page's file. `held` is its `file_database_drift` entry. */+export type DreamPageFileWrite = { written: true; path: string } | { written: false; held?: string; skipped?: string; error?: string };++/**+ * #6982: write the file of a page the dream cycle wrote in the database (a synthesis or patterns output, the cycle+ * summary) without replacing an edit only the file holds. Nothing is written with `sync.write_through` off, for a clone+ * gbrain owns, or for a declared `storage.db_only` slug: the database is the copy of record. The file is the page's+ * file of record (`resolvePageWriteTarget`: recorded source_path, own-local_path roots); a source with no usable+ * checkout (no root configured, or the root is missing) keeps the caller's brainDir layout (`<brainDir>/<slug>.md`,+ * foreign sources under `.sources/<id>/`). The file is replaced only when `replaceableFile` finds nothing in it the+ * database lacks, and is re-read right before the atomic write, so an edit that lands in between is kept as well.+ *+ * This is the reverse-write's own direct write, not `writePageThrough`: once a subagent's tool write has gone through+ * the coordinator, the checkout carries an owner marker and `writePageThrough` refuses `writer_coordinator_required`,+ * which would leave the file behind the database for the next coordinated write to refuse as drift.+ */+export async function writeDreamPageFile(engine: BrainEngine, brainDir: string, slug: string, sourceId: string,+ opts: { nativeSourceId: string; markdown: string }): Promise<DreamPageFileWrite> {+ if (await isWriteThroughDisabled(engine)) return { written: false, skipped: 'disabled_by_config' };+ if (await urlCloneReadOnly(engine, sourceId)) return { written: false, skipped: 'url_clone' };+ const target = await resolvePageWriteTarget(engine, slug, sourceId);+ if (!target.ok && target.skipped !== 'no_repo_configured' && target.skipped !== 'repo_not_found') return { written: false, skipped: target.skipped };+ try {+ const storage = loadStorageConfig(target.ok ? target.writeRoot : brainDir);+ if (storage && isDbOnly(slug, storage)) return { written: false, skipped: 'db_only' };+ } catch { /* unreadable gbrain.yml: sync reports it */ }+ const filePath = target.ok ? target.filePath+ : sourceId === opts.nativeSourceId ? join(brainDir, `${slug}.md`) : join(brainDir, '.sources', sourceId, `${slug}.md`);+ const check = await replaceableFile(engine, sourceId, slug, filePath);+ if (!check.ok) return { written: false, held: dreamFileDriftToken(slug, sourceId, 'before') };+ if ((existsSync(filePath) ? readFileSync(filePath, 'utf-8') : null) !== check.expectedFileBytes) {+ return { written: false, held: dreamFileDriftToken(slug, sourceId, 'during') };+ }+ mkdirSync(dirname(filePath), { recursive: true });+ atomicWriteFileSync(filePath, opts.markdown);+ return { written: true, path: filePath };+}++/** #6982: the hold entry for a dream page whose file holds an edit the database lacks. */+function dreamFileDriftToken(slug: string, sourceId: string, when: 'before' | 'during'): string {+ return `${slug} (file_database_drift: the file ${when === 'before' ? 'holds an edit the database lacks' : 'changed while the dream cycle wrote it'}, `+ + `so the dream output stays in the database only and the file was not replaced. ${fileDatabaseDriftFix(slug, sourceId)})`;+}++/** A dream phase result with its held page files: listed in `details.file_holds`, and an ok phase warns. */+export function withFileHolds(result: PhaseResult, held: readonly string[]): PhaseResult {+ if (held.length === 0) return result;+ return { ...result, status: result.status === 'ok' ? 'warn' : result.status, details: { ...result.details, file_holds: [...new Set([...((result.details.file_holds as string[] | undefined) ?? []), ...held])] },+ summary: `${result.summary}; ${held.length} page file(s) held because they differ from the database (details.file_holds)` };+}diff --git a/src/core/cycle/dream-taint.ts b/src/core/cycle/dream-taint.tsindex d08426e687..8c31835ddd 100644--- a/src/core/cycle/dream-taint.ts+++ b/src/core/cycle/dream-taint.ts@@ -15,6 +15,7 @@import { resolve, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';import { parseMarkdown } from '../markdown.ts';+import { readStoredBody } from '../facts/file-body-guard.ts';import { declareDerivation, deriveTrust, derivedMaintenanceTransaction, derivedWriteTrust, frontmatterTaint, type DerivationDeclaration } from '../trust/taint.ts';import type { TaintInput, TrustTier, WriteTrust } from '../trust/tier.ts';import { CONVERSATION_PAGE_URI_PREFIX } from './transcript-discovery.ts';@@ -67,10 +68,15 @@ export async function summaryDerivation(engine: BrainEngine, sourceId: string, sreturn { trust, inputs, declaration: declareDerivation(trust, inputs) };}-/** An unmanaged derived page write (the dream summary): putPage at the derivation's tier, lowered, with its input edges. */+/**+ * An unmanaged derived page write (the dream summary): putPage at the derivation's tier, lowered, with its input edges.+ * #6982: a live body it replaces with a different one is kept in page_versions first (putPage itself keeps none).+ */export async function putDerivedPage(engine: BrainEngine, derivation: Derivation, slug: string,page: Parameters<BrainEngine['putPage']>[1], opts: { sourceId: string }): Promise<void> {await derivedMaintenanceTransaction(engine, derivation, async tx => {+ const prior = await readStoredBody(tx, opts.sourceId, slug, true);+ if (prior && (prior.compiled_truth !== page.compiled_truth || (prior.timeline ?? '') !== (page.timeline ?? ''))) await tx.createVersion(slug, opts);const written = await tx.putPage(slug, page, opts);return { result: undefined, rows: [{ table: 'pages' as const, id: Number(written.id), sourceId: opts.sourceId }] };});diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex daed3995f5..88879feea8 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -879,6 +879,7 @@ export async function runExtractFacts(result.phantomsHeldLegacyRows = phantomResult.held_legacy_rows;result.phantomsLockBusy = phantomResult.lock_busy;result.phantomsMorePending = phantomResult.more_pending;+ for (const held of phantomResult.held) result.warnings.push(`phantom_redirect_held: ${held}`);for (const f of phantomResult.failures) result.warnings.push(`phantom_redirect_failed: ${f.key} (${f.code}); retry: ${(f.fix.argv ?? []).join(' ')}`);if (phantomResult.stopped) result.warnings.push(`phantom_redirect_stopped: ${phantomResult.stopped.message.slice(0, 300)}`);diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.tsindex 188072845c..f28ee52c6c 100644--- a/src/core/cycle/patterns.ts+++ b/src/core/cycle/patterns.ts@@ -23,8 +23,6 @@ import { managedPersistenceEnabled } from '../persistence/ownership.ts';* is refused revision_required).*/-import { join, dirname } from 'node:path';-import { mkdirSync, writeFileSync } from 'node:fs';import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../engine.ts';import { boundedBodyPrefixSql } from '../page-window/bounded-lead.ts';@@ -46,6 +44,7 @@ import type { Page, PageType } from '../types.ts';// slot and can deadlock a fully-occupied worker (#2050). synthesize.ts// drains its own children the same way.import { loadAllowedSlugPrefixes, loadOutputRoot, runSubagentsInline } from './synthesize.ts';+import { withFileHolds, writeDreamPageFile } from './derived-write-through.ts';import { stampDreamProvenance } from './dream-provenance.ts';import { probeChatModelWithKey } from '../ai/chat-key-probe.ts';import { normalizeModelId } from '../model-id.ts';@@ -422,10 +421,12 @@ async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, con// #6052: `finalized` leaves out outputs whose managed publication is held (pending or contended); `held` counts them.const { quoteVerify, finalized, held, grounding } = await stampPatternOutputs(engine, maintenance, putPageRefs, appends, submitted, derivation, config, cycleSourceId, cycleDate, opts.signal);+ const fileHolds: string[] = [];const reverseWriteCount = maintenance ? await verifyMaintenanceOutputs(engine, maintenance, finalized)- : await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal);+ : await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal, fileHolds);const details = { reflections_considered: submitted.length, reflections_selected: selected, plan_basis: plan.basis, patterns_written: finalized.length,...(quoteVerify ? { quote_verify: quoteVerify } : {}), reverse_write_count: reverseWriteCount, publish_deferred: held, ...grounding.details,+ ...(fileHolds.length ? { file_holds: fileHolds } : {}),timeline_appends: appends.length, appended_unverified: appendedUnverified, child_outcome: outcome, job_id: job.id };const appendedNote = appends.length > 0 ? `; ${appends.length} timeline entr${appends.length === 1 ? 'y' : 'ies'} appended${quoteVerify ? ' (quote-verified)' : ''}` : '';@@ -471,7 +472,7 @@ async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, con// named nothing; re-running it is exactly the spend bug.await engine.setConfig(keys.evidence, new Date(newestEvidenceMs).toISOString());- return withGroundingStatus(ok(`${writtenRefs.length} pattern page(s) written/updated${appendedNote} (${outcome})`, details), grounding);+ return withFileHolds(withGroundingStatus(ok(`${writtenRefs.length} pattern page(s) written/updated${appendedNote} (${outcome})`, details), grounding), fileHolds);} catch (e) {return failed(makeError('InternalError', 'PATTERNS_PHASE_FAIL',e instanceof Error ? (e.message || 'patterns phase threw') : String(e)));@@ -718,7 +719,7 @@ async function stampPatternOutputs(engine: BrainEngine, maintenance: Maintenancereturn { quoteVerify: pages ? { ...pages, ...(appended ? { timeline_appends: appended } : {}) } : null, finalized, held: heldSlugs.size, grounding };}-type AppendRetry = { report: GroundingReport; stats: { pages: number; entries: number; quarantined: number; repaired: number } };+type AppendRetry = { report: GroundingReport; stats: { pages: number; entries: number; quarantined: number; repaired: number }; fileHolds: string[] };/*** GBRA-130 A-23: ground the timeline appends earlier runs failed to ground (pattern-grounding.ts), each page against@@ -749,11 +750,12 @@ async function retryPendingAppends(engine: BrainEngine, opts: PatternsPhaseOpts,}const report = await finishGroundingRun(engine, run);const rewritten = [...run.appendsResolved.keys()].filter(slug => !heldSlugs.has(slug)).map(slug => ({ slug, source_id: sourceId }));+ const fileHolds: string[] = [];if (rewritten.length) {if (maintenance) await verifyMaintenanceOutputs(engine, maintenance, rewritten);- else await reverseWriteRefs(engine, opts.brainDir, rewritten, sourceId, opts.signal);+ else await reverseWriteRefs(engine, opts.brainDir, rewritten, sourceId, opts.signal, fileHolds);}- return { report, stats };+ return { report, stats, fileHolds };}/**@@ -763,6 +765,10 @@ async function retryPendingAppends(engine: BrainEngine, opts: PatternsPhaseOpts,*/function withAppendRetry(result: PhaseResult, retried: AppendRetry | null): PhaseResult {if (!retried) return result;+ return withFileHolds(withGroundingRetry(result, retried), retried.fileHolds);+}++function withGroundingRetry(result: PhaseResult, retried: AppendRetry): PhaseResult {const { report, stats } = retried;const passGrounded = Array.isArray(result.details.grounding_held);const failed = [...report.details.grounding_failed, ...((result.details.grounding_failed ?? []) as GroundingReport['details']['grounding_failed'])];@@ -1084,12 +1090,17 @@ import { validateSourceId } from '../utils.ts';import { renderTimelineEntry } from '../timeline-write-through.ts';import { materializedMarker } from '../timeline-marker.ts';+/**+ * Reverse-render each pattern page to its markdown file (`writeDreamPageFile`, #6982): a page whose file holds an edit+ * the database lacks keeps that file and its `file_database_drift` entry is pushed to `held`.+ */async function reverseWriteRefs(engine: BrainEngine,brainDir: string,refs: Array<{ slug: string; source_id: string }>,nativeSourceId = 'default',signal?: AbortSignal,+ held?: string[],): Promise<number> {let count = 0;for (const { slug, source_id } of refs) {@@ -1104,18 +1115,15 @@ async function reverseWriteRefs(// getPage/getTags must not reach this ref's file write.throwIfAborted(signal, '[dream] patterns reverse-write');try {- const md = renderPageToMarkdown(page, tags);- // v0.32.8 F6: foreign-source pages land under brainDir/.sources/<id>/<slug>.md- // so same-slug-different-source pages don't collide on disk. Pages belonging- // to the cycle's own source (#1586: brainDir IS that source's checkout —- // legacy 'default' when unscoped) stay at brainDir/<slug>.md so single-source- // brains see no change. `.sources/` is a reserved prefix; walkBrainRepo skips dot-dirs.- const filePath = source_id === nativeSourceId- ? join(brainDir, `${slug}.md`)- : join(brainDir, '.sources', source_id, `${slug}.md`);- mkdirSync(dirname(filePath), { recursive: true });- writeFileSync(filePath, md, 'utf8');- count++;+ // v0.32.8 F6: with no checkout root, foreign-source pages land under+ // brainDir/.sources/<id>/<slug>.md so same-slug-different-source pages+ // don't collide on disk; the cycle's own source (#1586: brainDir IS that+ // source's checkout) stays at brainDir/<slug>.md. `.sources/` is a+ // reserved prefix; walkBrainRepo skips dot-dirs.+ const file = await writeDreamPageFile(engine, brainDir, slug, source_id, { nativeSourceId, markdown: renderPageToMarkdown(page, tags) });+ if (file.written) count++;+ else if (file.held) held?.push(file.held);+ else if (file.error) process.stderr.write(`[dream] reverse-write ${slug}@${source_id} failed: ${file.error}\n`);} catch (e) {const msg = e instanceof Error ? e.message : String(e);process.stderr.write(`[dream] reverse-write ${slug}@${source_id} failed: ${msg}\n`);diff --git a/src/core/cycle/phantom-redirect.ts b/src/core/cycle/phantom-redirect.tsindex bcb44e5b1b..97036c59ac 100644--- a/src/core/cycle/phantom-redirect.ts+++ b/src/core/cycle/phantom-redirect.ts@@ -60,7 +60,8 @@ import { tryAcquireDbLock, syncLockId, type DbLockHandle } from '../db-lock.ts';import { isAborted } from '../abort-check.ts';import { logPhantomEvent, type PhantomOutcome } from '../facts/phantom-audit.ts';import { MOVE_WITHDRAWAL_SUBJECT_SQL } from '../facts/withdrawal-schema.ts';-import { resolvePageWriteTarget } from '../write-through.ts';+import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';+import { fileBodyMatchesStored, fileDatabaseDriftFix, mirrorFileBody, readStoredBody, replaceStoredBody, replaceableFile } from '../facts/file-body-guard.ts';import { recordRenameAlias } from '../page-state/rename-alias.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';@@ -80,6 +81,8 @@ export interface RedirectResult {outcome: RedirectOutcome;/** Canonical slug, populated only on outcome === 'redirected' (incl. dry-run preview). */canonical?: string;+ /** #6982: the `file_database_drift` entry when a file or database body was left in place (with outcome drift, or a kept phantom file). */+ held?: string;}export interface PhantomPassResult {@@ -95,6 +98,8 @@ export interface PhantomPassResult {* them on the deleted phantom. Every other phantom of the source proceeds.*/held_legacy_rows: number;+ /** #6982: `<slug> (file_database_drift: …)` entries for pages whose file or database body the pass left in place, each with its fix. */+ held: string[];/** True iff the pass was skipped wholesale because the writer lock was busy. */lock_busy: boolean;/** True iff live root pages remain after this pass's window; the next pass resumes after the last slug examined. */@@ -136,6 +141,7 @@ export function emptyPhantomPassResult(): PhantomPassResult {no_canonical: 0,not_phantom: 0,held_legacy_rows: 0,+ held: [],lock_busy: false,more_pending: false,failures: [],@@ -221,8 +227,9 @@ async function acquireLockWithRetry(}/**- * Append the phantom's fact rows to the canonical's disk fence, dedup-- * guarded by (claim, valid_from). Atomic via `.tmp` + rename.+ * Append the phantom's fact rows to the canonical's file of record, dedup-+ * guarded by (claim, valid_from), and mirror the file into the canonical's+ * database body. Atomic via `.tmp` + rename.** New rows number from past both the file's and the DB's highest row number* (the DB may hold numbers the file lost), and `superseded by #N` references@@ -231,20 +238,32 @@ async function acquireLockWithRetry(* canonical fence row (a retry after a crash between the disk write and the* DB move finds every row already on disk).*- * The disk write happens BEFORE the DB migration in the redirect handler,- * so if this throws (rename fails, disk full, parse-validation rejects)- * the DB migration won't run and the cycle can retry next run.+ * #6982: the rows are planned on the file only when its body and timeline+ * equal the canonical's database body, so the mirror can only add them. The+ * canonical row is then locked and re-read in a maintenance transaction: when+ * the database body or the file moved since the comparison, nothing is+ * written and the phantom is held (`file_database_drift`). Otherwise the prior+ * body is kept in page_versions, the body is mirrored and stamped with the+ * hash the importer computes for the new file, and the `.tmp` is renamed last.+ * A parse-validation failure throws before any DB state has moved.*/-function appendPhantomFenceRowsToCanonical(+async function mergeIntoCanonicalFile(+ engine: BrainEngine,+ phantomSlug: string,+ canonical: string,+ sourceId: string,canonicalPath: string,phantomFacts: ParsedFact[],dbMaxRowNum: number,-): Map<number, number> {- if (phantomFacts.length === 0) return new Map<number, number>();- const { body: newBody, renumber } = mergePhantomFenceRows(fs.readFileSync(canonicalPath, 'utf-8'), phantomFacts, dbMaxRowNum);- if (newBody === null) return renumber;+): Promise<{ renumber: Map<number, number> } | { held: string }> {+ if (phantomFacts.length === 0) return { renumber: new Map<number, number>() };+ await materializeCanonicalToDisk(engine, canonical, sourceId, canonicalPath);+ const bytes = fs.readFileSync(canonicalPath, 'utf-8');+ const { body: newBody, renumber } = mergePhantomFenceRows(bytes, phantomFacts, dbMaxRowNum);+ const stored = await readStoredBody(engine, sourceId, canonical);+ if (stored && !fileBodyMatchesStored(bytes, canonical, stored)) return { held: canonicalDriftToken(canonical, phantomSlug, sourceId, 'before') };+ if (newBody === null) return { renumber };- // Atomic write: .tmp first, parse-validate, rename.const tmpPath = `${canonicalPath}.tmp`;fs.writeFileSync(tmpPath, newBody, 'utf-8');const reparsed = parseFactsFence(newBody);@@ -254,8 +273,64 @@ function appendPhantomFenceRowsToCanonical(`phantom-redirect: rendered fence failed re-parse: ${reparsed.warnings.join('; ')}`,);}- fs.renameSync(tmpPath, canonicalPath);- return renumber;+ if (!stored) {+ fs.renameSync(tmpPath, canonicalPath);+ return { renumber };+ }+ const parsed = parseMarkdown(newBody, `${canonical}.md`);+ const hash = contentHash({ title: parsed.title, type: parsed.type, compiled_truth: parsed.compiled_truth, timeline: parsed.timeline,+ frontmatter: parsed.frontmatter, tags: await engine.getTags(canonical, { sourceId }) });+ const written = await maintenanceTransaction(engine, async tx => {+ if (fs.readFileSync(canonicalPath, 'utf-8') !== bytes || !await mirrorFileBody(tx, sourceId, canonical, newBody, stored, hash)) return false;+ fs.renameSync(tmpPath, canonicalPath);+ return true;+ });+ if (written) return { renumber };+ fs.rmSync(tmpPath, { force: true });+ return { held: canonicalDriftToken(canonical, phantomSlug, sourceId, 'during') };+}++/**+ * #6982, write-through off: the database is the copy of record, so the+ * phantom's rows merge into the canonical's database body under a row lock,+ * keeping the prior body in page_versions; no file is read or written. A body+ * that moved since it was read holds the phantom.+ */+async function mergeIntoCanonicalBody(+ engine: BrainEngine,+ canonical: Page | null,+ sourceId: string,+ phantomFacts: ParsedFact[],+ dbMaxRowNum: number,+): Promise<{ renumber: Map<number, number> } | { held: string }> {+ const expected = canonical && await readStoredBody(engine, sourceId, canonical.slug);+ if (!canonical || !expected) throw new Error('canonical page is gone');+ const { body, renumber } = mergePhantomFenceRows(expected.compiled_truth ?? '', phantomFacts, dbMaxRowNum);+ if (body === null) return { renumber };+ const written = await maintenanceTransaction(engine, tx =>+ replaceStoredBody(tx, sourceId, canonical.slug, { compiled_truth: body, timeline: expected.timeline ?? '' }, expected));+ return written ? { renumber } : { held: `${canonical.slug} (file_database_drift: the canonical's database body changed while the phantom was redirected, so nothing was written; the next cycle retries)` };+}++/** #6982: the hold entry for a phantom whose canonical file and database body differ (or moved during the redirect). */+function canonicalDriftToken(canonical: string, phantomSlug: string, sourceId: string, when: 'before' | 'during'): string {+ return `${canonical} (file_database_drift: the canonical file and the database body ${when === 'before' ? 'differ' : 'changed while the phantom was redirected'}, `+ + `so the phantom ${phantomSlug} was not redirected and neither copy changed. ${fileDatabaseDriftFix(canonical, sourceId)})`;+}++/** #6982: the hold entry for a phantom whose own file holds content its database row lacks. */+function phantomFileDriftToken(phantomSlug: string, sourceId: string, when: 'before' | 'during'): string {+ return when === 'before'+ ? `${phantomSlug} (file_database_drift: the phantom's file holds content its database row lacks, so it was not redirected and the file was kept. `+ + `gbrain sync --source ${sourceId} imports the file; ask the user before discarding it)`+ : `${phantomSlug} (file_database_drift: the phantom's file changed while it was redirected, so the file was kept. `+ + `gbrain sync --source ${sourceId} imports it again as a page; ask the user whether to keep it or delete the file)`;+}++/** A phantom left in place by a `file_database_drift` hold: audited as drift and reported by the pass. */+function driftHold(phantomSlug: string, sourceId: string, canonical: string, held: string): RedirectResult {+ logPhantomEvent({ phantom_slug: phantomSlug, outcome: 'drift', source_id: sourceId, reason: held.slice(0, 200) });+ return { outcome: 'drift', canonical, held };}/**@@ -572,58 +647,44 @@ export async function tryRedirectPhantom(}// ─── Commit phase (codex #3/#4/#6/#7) ─────────────────────────────- // The canonical file is the page's file of record (recorded source_path,- // own-local_path roots), resolved like every other fence writer. Only a- // brain with no configured root falls back to the pass's brainDir.- const writeTarget = await resolvePageWriteTarget(engine, canonical, sourceId);- if (!writeTarget.ok && writeTarget.skipped !== 'no_repo_configured') {- logPhantomEvent({- phantom_slug: page.slug,- outcome: 'drift',- source_id: sourceId,- reason: `canonical write target unavailable: ${writeTarget.skipped}`,- });- return { outcome: 'drift', canonical };- }- const canonicalPath = writeTarget.ok ? writeTarget.filePath : path.join(brainDir, `${canonical}.md`);+ // #6982: with write-through off the database is the copy of record, so the+ // rows merge into the canonical's database body and no file is written or+ // removed. Otherwise the phantom's file goes only when it holds nothing its+ // row lacks, and the canonical file takes the rows only when it agrees with+ // the canonical's database body.+ const writeThroughOff = await isWriteThroughDisabled(engine);+ const phantomPath = path.join(brainDir, `${page.slug}.md`);+ const phantomFile = writeThroughOff ? null : await replaceableFile(engine, sourceId, page.slug, phantomPath);+ if (phantomFile && !phantomFile.ok) return driftHold(page.slug, sourceId, canonical, phantomFileDriftToken(page.slug, sourceId, 'before'));+const target = await engine.getPage(canonical, { sourceId });if (target) assertInlineBody(target, 'phantom redirect');- await materializeCanonicalToDisk(engine, canonical, sourceId, canonicalPath);-- // Disk-side first: parse phantom's fence and append to canonical's- // disk fence (dedup-guarded). If this throws, no DB state has moved- // and the cycle can retry next run.const phantomFence = parseFactsFence(page.compiled_truth ?? '');const [dbMax] = await engine.executeRaw<{ n: number | string | null }>('SELECT MAX(row_num) AS n FROM facts WHERE source_id = $1 AND source_markdown_slug = $2',[sourceId, canonical],);- const rowMap = appendPhantomFenceRowsToCanonical(canonicalPath, phantomFence.facts, Number(dbMax?.n ?? 0));-- // Codex #7: refresh canonical's compiled_truth + content_hash so the- // next `gbrain sync` sees the canonical as unchanged. We re-parse the- // disk body and recompute the hash with the SHARED canonical helper- // (`utils.ts:contentHash` — the #3694 single formula: ephemeral- // frontmatter keys stripped, tags-key deleted, timeline||''), so the- // idempotency check round-trips byte-for-byte.- const newCanonicalBody = fs.readFileSync(canonicalPath, 'utf-8');- const reparsed = parseMarkdown(newCanonicalBody, `${canonical}.md`);- const canonicalTags = await engine.getTags(canonical, { sourceId });- const newContentHash = contentHash({- title: reparsed.title,- type: reparsed.type,- compiled_truth: reparsed.compiled_truth,- timeline: reparsed.timeline,- frontmatter: reparsed.frontmatter,- tags: canonicalTags,- });- await maintenanceTransaction(engine, tx => tx.refreshPageBody(- canonical,- sourceId,- reparsed.compiled_truth,- reparsed.timeline,- newContentHash,- ));+ let merged: Awaited<ReturnType<typeof mergeIntoCanonicalFile>>;+ if (writeThroughOff) merged = await mergeIntoCanonicalBody(engine, target, sourceId, phantomFence.facts, Number(dbMax?.n ?? 0));+ else {+ // The canonical file is the page's file of record (recorded source_path,+ // own-local_path roots), resolved like every other fence writer. Only a+ // brain with no configured root falls back to the pass's brainDir.+ const writeTarget = await resolvePageWriteTarget(engine, canonical, sourceId);+ if (!writeTarget.ok && writeTarget.skipped !== 'no_repo_configured') {+ logPhantomEvent({+ phantom_slug: page.slug,+ outcome: 'drift',+ source_id: sourceId,+ reason: `canonical write target unavailable: ${writeTarget.skipped}`,+ });+ return { outcome: 'drift', canonical };+ }+ const canonicalPath = writeTarget.ok ? writeTarget.filePath : path.join(brainDir, `${canonical}.md`);+ merged = await mergeIntoCanonicalFile(engine, page.slug, canonical, sourceId, canonicalPath, phantomFence.facts, Number(dbMax?.n ?? 0));+ }+ if ('held' in merged) return driftHold(page.slug, sourceId, canonical, merged.held);+ const rowMap = merged.renumber;// Withdrawals are scoped to the entity; the phantom was the canonical// entity. Moved first, so the withdrawal trigger honors them as the@@ -637,22 +698,28 @@ export async function tryRedirectPhantom(// Round 19/20: soft-delete + unlink. Order matters — softDelete first// so a concurrent sync that observes the phantom .md gone treats it as- // a normal deletion (not a regression).+ // a normal deletion (not a regression). The file is re-read right before+ // the unlink: one that changed since it was compared is kept and reported.await maintenanceTransaction(engine, tx => tx.softDeletePage(page.slug, { sourceId }));- const phantomPath = path.join(brainDir, `${page.slug}.md`);- if (fs.existsSync(phantomPath)) {- try {- fs.unlinkSync(phantomPath);- } catch (err) {- // ENOENT is fine (someone else got there first). Anything else- // is logged but doesn't unwind the redirect — the next sync will- // notice the dangling .md and soft-delete-on-disk-miss it.- const code = (err as NodeJS.ErrnoException).code;- if (code !== 'ENOENT') {- const msg = err instanceof Error ? err.message : String(err);- process.stderr.write(- `[gbrain] phantom-redirect: unlink ${phantomPath} failed (${msg}); cycle continues\n`,- );+ let held: string | undefined;+ if (phantomFile && fs.existsSync(phantomPath)) {+ let current: string | null = null;+ try { current = fs.readFileSync(phantomPath, 'utf-8'); } catch { /* vanished: nothing to remove */ }+ if (current !== null && current !== phantomFile.expectedFileBytes) held = phantomFileDriftToken(page.slug, sourceId, 'during');+ else if (current !== null) {+ try {+ fs.unlinkSync(phantomPath);+ } catch (err) {+ // ENOENT is fine (someone else got there first). Anything else+ // is logged but doesn't unwind the redirect — the next sync will+ // notice the dangling .md and soft-delete-on-disk-miss it.+ const code = (err as NodeJS.ErrnoException).code;+ if (code !== 'ENOENT') {+ const msg = err instanceof Error ? err.message : String(err);+ process.stderr.write(+ `[gbrain] phantom-redirect: unlink ${phantomPath} failed (${msg}); cycle continues\n`,+ );+ }}}}@@ -664,7 +731,7 @@ export async function tryRedirectPhantom(fact_count: migrated,source_id: sourceId,});- return { outcome: 'redirected', canonical };+ return { outcome: 'redirected', canonical, ...(held ? { held } : {}) };}/**@@ -759,6 +826,7 @@ export async function runPhantomRedirectPass(redirectResult = { outcome: 'drift' };}+ if (redirectResult.held) result.held.push(redirectResult.held);switch (redirectResult.outcome) {case 'redirected':result.redirected += 1;diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex 6b4d0793bc..3b9a3e3c4c 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -1,6 +1,7 @@import { observationDateLine, observationDateRule } from '../ai/date-grounding.ts';import { isConsumerDateGroundingOn } from '../facts/extract.ts';import { maintenancePreflight, publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';+import { withFileHolds, writeDreamPageFile } from './derived-write-through.ts';import { deferPublishOrThrow, finishDeferredPostprocess, loadCommittedOutputsOrDefer, postprocessManagedSynthesis, withPostprocessConflicts, withPublishPending, type PostprocessConflict, type RetainedOutput } from './synthesize-postprocess.ts';/*** Synthesize phase (v0.23; #4152 two-stage cascade) — conversation-to-brain@@ -52,7 +53,6 @@ import { deferPublishOrThrow, finishDeferredPostprocess, loadCommittedOutputsOrD*/import type Anthropic from '@anthropic-ai/sdk';-import { writeFileSync, mkdirSync } from 'node:fs';import { randomUUID } from 'node:crypto';import { chat as gatewayChat, validateModelId, type ChatResult } from '../ai/gateway.ts';import { AIConfigError } from '../ai/errors.ts';@@ -1174,15 +1174,17 @@ async function runPhaseSynthesizeInner(if (!maintenance) await stampDreamProvenance(engine, writtenRefs, summaryDate, opts.signal);// Dual-write: reverse-render each DB row → markdown file.+ const fileHolds: string[] = [];const reverseWriteCount = maintenance ? (maintenance.binding ? writtenRefs.length : 0)- : await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal);+ : await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal, fileHolds);const summarySlug = buildDreamSummarySlug(config.outputRoot, summaryDate);const writtenSlugs = writtenRefs.map(r => r.slug);if (SUMMARY_SLUG_RE.test(summarySlug) && !publishPending) {const preserveSummary = maintenance && !writtenRefs.length && await engine.readPageSnapshot(summarySlug, { sourceId: cycleSourceId });- if (!preserveSummary) await writeSummaryPage(engine, opts.brainDir, summarySlug, summaryDate, finalizedRefs.map(r => r.slug), childOutcomes, cycleSourceId, opts.signal, maintenance)- .catch((e: unknown) => { deferPublishOrThrow(e, summarySlug); publishPending++; });+ const summaryHeld = preserveSummary ? undefined : await writeSummaryPage(engine, opts.brainDir, summarySlug, summaryDate, finalizedRefs.map(r => r.slug), childOutcomes, cycleSourceId, opts.signal, maintenance)+ .catch((e: unknown) => { deferPublishOrThrow(e, summarySlug); publishPending++; return undefined; });+ if (summaryHeld) fileHolds.push(summaryHeld);}// #4077: nothing below runs for a cancelled cycle — no phase-end embed@@ -1354,7 +1356,7 @@ async function runPhaseSynthesizeInner(const turnsSamples = childOutcomes.filter((o): o is { jobId: number; status: string; turns: number } => typeof o.turns === 'number',);- return withPostprocessConflicts(postprocessConflicts, withPublishPending(publishPending, ok(`${submittedTranscripts} transcript(s) synthesized in ${(ms / 1000).toFixed(1)}s${deferralSuffix}`, {+ return withFileHolds(withPostprocessConflicts(postprocessConflicts, withPublishPending(publishPending, ok(`${submittedTranscripts} transcript(s) synthesized in ${(ms / 1000).toFixed(1)}s${deferralSuffix}`, {transcripts_discovered: transcripts.length,transcripts_processed: submittedTranscripts,pages_written: writtenSlugs.length,@@ -1421,7 +1423,7 @@ async function runPhaseSynthesizeInner(// child counters + triage pass usage). cost_usd null when unpriced.spend: spendBlock,},- }), postprocessDeferral));+ }), postprocessDeferral)), fileHolds);} catch (e) {return failed(makeError('InternalError', 'SYNTH_PHASE_FAIL', e instanceof Error ? (e.message || 'synthesize phase threw') : String(e),e instanceof OperationError ? e.suggestion : undefined), e instanceof OperationError ? { error_code: e.code } : {});@@ -2975,12 +2977,17 @@ async function collectChildPutPageSlugs(// ── Reverse-write DB rows → markdown files ───────────────────────────+/**+ * Reverse-render each page a child wrote to its markdown file (`writeDreamPageFile`, #6982): a page whose file holds an+ * edit the database lacks keeps that file and its `file_database_drift` entry is pushed to `held`.+ */async function reverseWriteRefs(engine: BrainEngine,brainDir: string,refs: Array<{ slug: string; source_id: string; first_write_at?: Date }>,nativeSourceId = 'default',signal?: AbortSignal,+ held?: string[],): Promise<number> {let count = 0;for (const { slug, source_id, first_write_at } of refs) {@@ -2994,17 +3001,15 @@ async function reverseWriteRefs(// getPage/getTags must not reach this ref's file write.throwIfAborted(signal, '[dream] synthesize reverse-write');try {- const md = isDreamOwnedPage(page, first_write_at) ? renderPageToMarkdown(page, tags) : serializePageToMarkdown(page, tags);- // v0.32.8 F6: foreign-source pages land at brainDir/.sources/<id>/<slug>.md- // so same-slug-different-source pages don't collide. Pages belonging to- // the cycle's own source (#1586: brainDir IS that source's checkout —- // legacy 'default' when unscoped) stay at brainDir/<slug>.md.- const filePath = source_id === nativeSourceId- ? join(brainDir, `${slug}.md`)- : join(brainDir, '.sources', source_id, `${slug}.md`);- mkdirSync(dirname(filePath), { recursive: true });- writeFileSync(filePath, md, 'utf8');- count++;+ // v0.32.8 F6: with no checkout root, foreign-source pages land at+ // brainDir/.sources/<id>/<slug>.md so same-slug-different-source pages+ // don't collide; the cycle's own source (#1586: brainDir IS that+ // source's checkout) stays at brainDir/<slug>.md.+ const markdown = isDreamOwnedPage(page, first_write_at) ? renderPageToMarkdown(page, tags) : serializePageToMarkdown(page, tags);+ const file = await writeDreamPageFile(engine, brainDir, slug, source_id, { nativeSourceId, markdown });+ if (file.written) count++;+ else if (file.held) held?.push(file.held);+ else if (file.error) process.stderr.write(`[dream] reverse-write ${slug}@${source_id} failed: ${file.error}\n`);} catch (e) {// Per-slug failures are non-fatal — phase continues.const msg = e instanceof Error ? e.message : String(e);@@ -3061,6 +3066,11 @@ export function renderPageToMarkdown(page: Page, tags: string[]): string {*/const SUMMARY_LINK_SAMPLE_LIMIT = 20;+/**+ * Write the cycle's summary index page: the database row (the prior body kept in page_versions, `putDerivedPage`),+ * then its file through `writeDreamPageFile` (#6982). Returns the file's `file_database_drift` entry when the file+ * holds an edit the database lacks and was kept.+ */async function writeSummaryPage(engine: BrainEngine,brainDir: string,@@ -3071,7 +3081,7 @@ async function writeSummaryPage(sourceId = 'default',signal?: AbortSignal,maintenance?: MaintenanceAuthority | null,-): Promise<void> {+): Promise<string | undefined> {throwIfAborted(signal, '[dream] synthesize summary');const completed = childOutcomes.filter(c => c.status === 'completed').length;const failed = childOutcomes.length - completed;@@ -3162,13 +3172,14 @@ async function writeSummaryPage(return;}try {- const filePath = join(brainDir, `${summarySlug}.md`);- mkdirSync(dirname(filePath), { recursive: true });- writeFileSync(filePath, fullMarkdown, 'utf8');+ const file = await writeDreamPageFile(engine, brainDir, summarySlug, sourceId, { nativeSourceId: sourceId, markdown: fullMarkdown });+ if (!file.written && file.held) return file.held;+ if (!file.written && file.error) process.stderr.write(`[dream] summary file-write failed: ${file.error}\n`);} catch (e) {const msg = e instanceof Error ? e.message : String(e);process.stderr.write(`[dream] summary file-write failed: ${msg}\n`);}+ return undefined;}// ── Helpers ──────────────────────────────────────────────────────────diff --git a/src/core/facts/file-body-guard.ts b/src/core/facts/file-body-guard.tsindex f09db2fdb1..4d28b1d33d 100644--- a/src/core/facts/file-body-guard.ts+++ b/src/core/facts/file-body-guard.ts@@ -42,21 +42,35 @@ export async function readStoredBody(engine: BrainEngine, sourceId: string, slug}/**- * 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.+ * Inside `tx`: lock the page, and when its stored body is still `expected` (the body the caller compared before+ * planning), keep it in page_versions and store `next`. The row keeps its content_hash unless `hash` is given.+ * 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> {+export async function replaceStoredBody(tx: BrainEngine, sourceId: string, slug: string, next: { compiled_truth: string; timeline: string },+ expected: StoredBody, hash?: string): 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));+ await tx.refreshPageBody(slug, sourceId, next.compiled_truth, next.timeline, hash ?? (page.content_hash || contentHash(page)));return true;}+/**+ * Inside `tx`: `replaceStoredBody` with the body `fileBytes` mirrors. Without `hash` the row keeps its content_hash,+ * so the next sync re-imports and re-chunks the page.+ */+export async function mirrorFileBody(tx: BrainEngine, sourceId: string, slug: string, fileBytes: string, expected: StoredBody, hash?: string): Promise<boolean> {+ return replaceStoredBody(tx, sourceId, slug, mirroredBody(fileBytes, slug), expected, hash);+}++/** The fix sentence of a `file_database_drift` hold: which command settles each side, and when to ask the user. */+export function fileDatabaseDriftFix(slug: string, sourceId: string): string {+ return `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`;+}+/** Page states a checkout file is compared with: the live row, then its newest page_versions rows. */const HISTORY_ROWS = 20;diff --git a/test/cycle-abort.test.ts b/test/cycle-abort.test.tsindex a00875db0a..621e0ca2d6 100644--- a/test/cycle-abort.test.ts+++ b/test/cycle-abort.test.ts@@ -233,7 +233,7 @@ describe('#4077 — synthesize/patterns cooperative-abort threading', () => {expect(postprocess).toBeGreaterThan(-1);expect(src.slice(postprocess, src.indexOf(');', postprocess))).toContain('signal: opts.signal');expect(src).toContain('if (!maintenance) await stampDreamProvenance(engine, writtenRefs, summaryDate, opts.signal)');- expect(src).toContain('reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal)');+ expect(src).toContain('reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal, fileHolds)');});test('patterns sibling threads the same signal through inline drain, wait, and reverse-write', async () => {@@ -242,6 +242,6 @@ describe('#4077 — synthesize/patterns cooperative-abort threading', () => {expect(src).toContain('signal?: AbortSignal');expect(src).toMatch(/runSubagentsInline\([\s\S]{0,240}?opts\.signal/);expect(src).toMatch(/waitForCompletionRenewing\(queue, job\.id, \{[\s\S]*?signal: opts\.signal,/);- expect(src).toContain('reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal)');+ expect(src).toContain('reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal, fileHolds)');});});diff --git a/test/pathological/d5-phantom-canonical-overwrite.test.ts b/test/pathological/d5-phantom-canonical-overwrite.test.tsnew file mode 100644index 0000000000..35c4d2c34a--- /dev/null+++ b/test/pathological/d5-phantom-canonical-overwrite.test.ts@@ -0,0 +1,208 @@+/**+ * D-5 (GBRA-131, #6982): the phantom redirect never mirrors the canonical+ * page's file over a differing database body.+ *+ * Protects: on an unmanaged brain, redirecting a phantom (`alice`) into its+ * canonical page (`people/alice-example`) keeps both copies of the canonical.+ * With `sync.write_through` on, a canonical 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 redirect runs) holds the phantom:+ * the pass reports `file_database_drift` naming the canonical with its fix,+ * neither copy changes and the phantom stays live. With write-through off the+ * database is the copy of record: the phantom's rows merge into the+ * canonical's database body (the prior body kept in page_versions) and no file+ * is written. A canonical whose copies agree takes the rows in both copies and+ * the body it replaces is kept in page_versions.+ * Fails when: the redirect appends to the canonical file and mirrors the whole+ * file over the database body without comparing (the pre-fix refreshPageBody+ * path), which drops the database-only edit with no page_versions row.+ * Seams: an engine proxy whose first transaction after the redirect prepared+ * the canonical write lands a concurrent edit (database or file). 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 { runPhantomRedirectPass, type PhantomPassResult } from '../../src/core/cycle/phantom-redirect.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { parseFactsFence } from '../../src/core/facts-fence.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 { expectUnitNotAborted, pathologicalArms } from './harness.ts';++const SOURCE = 'default';+const CANONICAL = 'people/alice-example';+const PHANTOM = 'alice';+const CLAIM = 'Founded acme-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 redirect ran.';+const CANONICAL_BODY = '# Alice Example\n\nAlice Example works at acme-example.\n';+const PHANTOM_BODY = `# alice\n\n## Facts\n\n<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+| 1 | ${CLAIM} | fact | 1.0 | world | high | 2017-01-01 | | linkedin | |+<!--- gbrain:facts:end -->+`;++interface Brain {+ engine: BrainEngine;+ root: string;+ path(slug: string): string;+ file(slug: string): string;+ body(slug: string): Promise<string>;+ live(slug: string): Promise<boolean>;+ dbEdit(slug: string, paragraph: string): Promise<void>;+ versionsHolding(slug: string, marker: string): Promise<number>;+ pass(engine?: BrainEngine): Promise<PhantomPassResult>;+}++async function withBrain(databaseUrl: string | undefined, run: (b: Brain) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-d5-'));+ try {+ await withEnv({ GBRAIN_HOME: home, GBRAIN_AUDIT_DIR: join(home, 'audit'), 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, body] of [[CANONICAL, 'Alice Example', CANONICAL_BODY], [PHANTOM, 'alice', PHANTOM_BODY]] as const) {+ const page = await engine.putPage(slug, { type: 'person', title, compiled_truth: body, timeline: '', frontmatter: {} });+ await engine.executeRaw('UPDATE pages SET source_path = $1 WHERE id = $2', [`${slug}.md`, page.id]);+ mkdirSync(dirname(path(slug)), { recursive: true });+ writeFileSync(path(slug), body);+ }+ const b: Brain = {+ engine, root, path,+ file: slug => readFileSync(path(slug), 'utf8'),+ body: async slug => (await engine.executeRaw<{ compiled_truth: string }>(+ 'SELECT compiled_truth FROM pages WHERE source_id = $1 AND slug = $2', [SOURCE, slug]))[0]!.compiled_truth,+ live: async slug => (await engine.executeRaw<{ live: boolean }>(+ 'SELECT deleted_at IS NULL AS live FROM pages WHERE source_id = $1 AND slug = $2', [SOURCE, slug]))[0]?.live === true,+ async dbEdit(slug, paragraph) {+ const page = (await engine.getPage(slug, { sourceId: SOURCE }))!;+ await engine.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: SOURCE });+ },+ 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 = $1 AND p.slug = $2 AND v.compiled_truth LIKE '%' || $3 || '%'`, [SOURCE, slug, marker]))[0]!.n),+ pass: (on = engine) => runPhantomRedirectPass(on, root, SOURCE, false),+ };+ await run(b);+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++const claims = (text: string) => parseFactsFence(text).facts.map(f => f.claim);+const heldFor = (result: PhantomPassResult, slug: string) => result.held.filter(h => h.startsWith(`${slug} (file_database_drift`));++/**+ * The engine whose first transaction after the redirect prepared the canonical write (its `.tmp` exists, or the file+ * already carries the phantom's row) runs `before` first: a concurrent edit landing after the redirect compared.+ */+function editsOnceCanonicalPrepared(engine: BrainEngine, file: string, before: () => Promise<void>): BrainEngine {+ let fired = false;+ const prepared = () => existsSync(`${file}.tmp`) || claims(readFileSync(file, 'utf8')).includes(CLAIM);+ 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;+ },+ });+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`D-5 phantom redirect and a canonical database body that differs from its file (${backend})`, () => {+ test('D-5 db-newer, write-through on: the phantom is held with file_database_drift and both canonical copies stay', async () => {+ await withBrain(databaseUrl, async b => {+ await b.dbEdit(CANONICAL, DB_EDIT);+ const [fileBefore, bodyBefore, phantomFile] = [b.file(CANONICAL), await b.body(CANONICAL), b.file(PHANTOM)];+ const result = await expectUnitNotAborted(() => b.pass());+ expect({ redirected: result.redirected, drift: result.skipped_drift }).toEqual({ redirected: 0, drift: 1 });+ const held = heldFor(result, CANONICAL);+ expect({ held: held.length, fix: held.some(h => h.includes('gbrain sync --source default')) }).toEqual({ held: 1, fix: true });+ expect({ body: (await b.body(CANONICAL)) === bodyBefore, file: b.file(CANONICAL) === fileBefore }).toEqual({ body: true, file: true });+ expect({ phantomLive: await b.live(PHANTOM), phantomFile: b.file(PHANTOM) === phantomFile }).toEqual({ phantomLive: true, phantomFile: true });+ });+ }, 180_000);++ test('D-5 file-newer, write-through on: an unimported canonical file edit holds the phantom and the database body is not replaced', async () => {+ await withBrain(databaseUrl, async b => {+ const edited = `${CANONICAL_BODY}\n${FILE_EDIT}\n`;+ writeFileSync(b.path(CANONICAL), edited);+ const bodyBefore = await b.body(CANONICAL);+ const result = await expectUnitNotAborted(() => b.pass());+ expect({ redirected: result.redirected, held: heldFor(result, CANONICAL).length }).toEqual({ redirected: 0, held: 1 });+ expect({ body: (await b.body(CANONICAL)) === bodyBefore, file: b.file(CANONICAL) === edited }).toEqual({ body: true, file: true });+ expect(await b.live(PHANTOM)).toBe(true);+ });+ }, 180_000);++ test('D-5 db-newer, write-through off: the rows merge into the database body, the edit survives and no file changes', async () => {+ await withBrain(databaseUrl, async b => {+ await b.engine.setConfig('sync.write_through', 'false');+ _resetWriteThroughCacheForTest();+ await b.dbEdit(CANONICAL, DB_EDIT);+ const [canonicalFile, phantomFile] = [b.file(CANONICAL), b.file(PHANTOM)];+ const result = await expectUnitNotAborted(() => b.pass());+ expect({ redirected: result.redirected, held: result.held }).toEqual({ redirected: 1, held: [] });+ const body = await b.body(CANONICAL);+ expect({ edit: body.includes(DB_EDIT), fence: claims(body) }).toEqual({ edit: true, fence: [CLAIM] });+ expect({ canonicalFile: b.file(CANONICAL) === canonicalFile, phantomFile: b.file(PHANTOM) === phantomFile }).toEqual({ canonicalFile: true, phantomFile: true });+ expect(await b.versionsHolding(CANONICAL, DB_EDIT)).toBeGreaterThan(0);+ expect(await b.live(PHANTOM)).toBe(false);+ });+ }, 180_000);++ test('D-5 agreeing copies, write-through on: the rows land in the canonical file and database, and the replaced body is kept in page_versions', async () => {+ await withBrain(databaseUrl, async b => {+ const versionsBefore = await b.versionsHolding(CANONICAL, 'works at acme-example');+ const result = await expectUnitNotAborted(() => b.pass());+ expect({ redirected: result.redirected, held: result.held }).toEqual({ redirected: 1, held: [] });+ expect({ file: claims(b.file(CANONICAL)), db: claims(await b.body(CANONICAL)) }).toEqual({ file: [CLAIM], db: [CLAIM] });+ expect(await b.versionsHolding(CANONICAL, 'works at acme-example')).toBe(versionsBefore + 1);+ expect({ phantomLive: await b.live(PHANTOM), phantomFile: existsSync(b.path(PHANTOM)) }).toEqual({ phantomLive: false, phantomFile: false });+ });+ }, 180_000);++ test('D-5 concurrent database edit after the comparison: the edit survives, the canonical file is untouched and the phantom is held', async () => {+ await withBrain(databaseUrl, async b => {+ const fileBefore = b.file(CANONICAL);+ let landed = false;+ const racing = editsOnceCanonicalPrepared(b.engine, b.path(CANONICAL), async () => { await b.dbEdit(CANONICAL, LATE_EDIT); landed = true; });+ const result = await expectUnitNotAborted(() => b.pass(racing));+ expect(landed).toBe(true);+ expect({ edit: (await b.body(CANONICAL)).includes(LATE_EDIT), file: b.file(CANONICAL) === fileBefore, tmp: existsSync(`${b.path(CANONICAL)}.tmp`) })+ .toEqual({ edit: true, file: true, tmp: false });+ expect({ redirected: result.redirected, held: heldFor(result, CANONICAL).length, phantomLive: await b.live(PHANTOM) })+ .toEqual({ redirected: 0, held: 1, phantomLive: true });+ });+ }, 180_000);++ test('D-5 concurrent file edit after the comparison: the editor\'s bytes survive and the database body is not replaced', async () => {+ await withBrain(databaseUrl, async b => {+ const bodyBefore = await b.body(CANONICAL);+ const edited = `${CANONICAL_BODY}\n${LATE_EDIT}\n`;+ let landed = false;+ const racing = editsOnceCanonicalPrepared(b.engine, b.path(CANONICAL), async () => { writeFileSync(b.path(CANONICAL), edited); landed = true; });+ const result = await expectUnitNotAborted(() => b.pass(racing));+ expect(landed).toBe(true);+ expect({ file: b.file(CANONICAL) === edited, body: (await b.body(CANONICAL)) === bodyBefore }).toEqual({ file: true, body: true });+ expect({ redirected: result.redirected, held: heldFor(result, CANONICAL).length, phantomLive: await b.live(PHANTOM) })+ .toEqual({ redirected: 0, held: 1, phantomLive: true });+ });+ }, 180_000);+ });+}diff --git a/test/pathological/d6-phantom-file-unlink.test.ts b/test/pathological/d6-phantom-file-unlink.test.tsnew file mode 100644index 0000000000..2efe26993c--- /dev/null+++ b/test/pathological/d6-phantom-file-unlink.test.ts@@ -0,0 +1,186 @@+/**+ * D-6 (GBRA-131, #6982): the phantom redirect never removes a phantom's file+ * that holds content its database row lacks.+ *+ * Protects: on an unmanaged brain with `sync.write_through` on, a phantom+ * (`alice`) whose checkout file differs from its database row anywhere (prose,+ * timeline or frontmatter, not only the facts fence) is held: the pass reports+ * `file_database_drift` naming the phantom with its fix, nothing is redirected+ * and the file keeps its bytes. A file that changes after the comparison is+ * re-read before the unlink and kept, and the pass reports it. With+ * write-through off the database is the copy of record and the redirect never+ * removes the file. A phantom whose file agrees with its row is removed as+ * before.+ * Fails when: the redirect unlinks the phantom's file after the fence-only+ * drift check (fenceDbDrift), without comparing the rest of the file or+ * re-reading it before the unlink.+ * Seams: an engine proxy that edits the phantom's file inside the transaction+ * that soft-deletes the phantom (after the comparison, before the unlink).+ * 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 { runPhantomRedirectPass, type PhantomPassResult } from '../../src/core/cycle/phantom-redirect.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { parseFactsFence } from '../../src/core/facts-fence.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 { expectUnitNotAborted, pathologicalArms } from './harness.ts';++const SOURCE = 'default';+const CANONICAL = 'people/alice-example';+const PHANTOM = 'alice';+const CLAIM = 'Founded acme-example';+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 redirect ran.';+const CANONICAL_BODY = '# Alice Example\n\nAlice Example works at acme-example.\n';+const PHANTOM_BODY = `# alice\n\n## Facts\n\n<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+| 1 | ${CLAIM} | fact | 1.0 | world | high | 2017-01-01 | | linkedin | |+<!--- gbrain:facts:end -->+`;++interface Brain {+ engine: BrainEngine;+ root: string;+ path(slug: string): string;+ file(slug: string): string;+ body(slug: string): Promise<string>;+ live(slug: string): Promise<boolean>;+ dbEdit(slug: string, paragraph: string): Promise<void>;+ versionsHolding(slug: string, marker: string): Promise<number>;+ pass(engine?: BrainEngine): Promise<PhantomPassResult>;+}++async function withBrain(databaseUrl: string | undefined, run: (b: Brain) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-d6-'));+ try {+ await withEnv({ GBRAIN_HOME: home, GBRAIN_AUDIT_DIR: join(home, 'audit'), 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, body] of [[CANONICAL, 'Alice Example', CANONICAL_BODY], [PHANTOM, 'alice', PHANTOM_BODY]] as const) {+ const page = await engine.putPage(slug, { type: 'person', title, compiled_truth: body, timeline: '', frontmatter: {} });+ await engine.executeRaw('UPDATE pages SET source_path = $1 WHERE id = $2', [`${slug}.md`, page.id]);+ mkdirSync(dirname(path(slug)), { recursive: true });+ writeFileSync(path(slug), body);+ }+ const b: Brain = {+ engine, root, path,+ file: slug => readFileSync(path(slug), 'utf8'),+ body: async slug => (await engine.executeRaw<{ compiled_truth: string }>(+ 'SELECT compiled_truth FROM pages WHERE source_id = $1 AND slug = $2', [SOURCE, slug]))[0]!.compiled_truth,+ live: async slug => (await engine.executeRaw<{ live: boolean }>(+ 'SELECT deleted_at IS NULL AS live FROM pages WHERE source_id = $1 AND slug = $2', [SOURCE, slug]))[0]?.live === true,+ async dbEdit(slug, paragraph) {+ const page = (await engine.getPage(slug, { sourceId: SOURCE }))!;+ await engine.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: SOURCE });+ },+ 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 = $1 AND p.slug = $2 AND v.compiled_truth LIKE '%' || $3 || '%'`, [SOURCE, slug, marker]))[0]!.n),+ pass: (on = engine) => runPhantomRedirectPass(on, root, SOURCE, false),+ };+ await run(b);+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++const claims = (text: string) => parseFactsFence(text).facts.map(f => f.claim);+const heldFor = (result: PhantomPassResult, slug: string) => result.held.filter(h => h.startsWith(`${slug} (file_database_drift`));++/** The engine whose transaction soft-deleting the phantom runs `before` first: an edit landing after the comparison, before the unlink. */+function editsBeforePhantomDelete(engine: BrainEngine, before: () => Promise<void>): BrainEngine {+ let fired = false;+ return new Proxy(engine, {+ get(target, prop) {+ if (prop === 'transaction') return (fn: (tx: BrainEngine) => Promise<unknown>) => target.transaction(tx => fn(new Proxy(tx, {+ get(inner, key) {+ if (key === 'softDeletePage') return async (slug: string, opts: unknown) => {+ if (!fired && slug === PHANTOM) { fired = true; await before(); }+ return inner.softDeletePage(slug, opts as never);+ };+ const value = Reflect.get(inner, key, inner);+ return typeof value === 'function' ? value.bind(inner) : value;+ },+ })));+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`D-6 phantom redirect and a phantom file that differs from its database row (${backend})`, () => {+ test('D-6 file-newer prose: the phantom is held with file_database_drift, its file keeps its bytes and nothing moves', async () => {+ await withBrain(databaseUrl, async b => {+ const edited = `${PHANTOM_BODY}\n${FILE_EDIT}\n`;+ writeFileSync(b.path(PHANTOM), edited);+ const [canonicalFile, canonicalBody] = [b.file(CANONICAL), await b.body(CANONICAL)];+ const result = await expectUnitNotAborted(() => b.pass());+ const held = heldFor(result, PHANTOM);+ expect({ redirected: result.redirected, held: held.length, fix: held.some(h => h.includes('gbrain sync --source default')) })+ .toEqual({ redirected: 0, held: 1, fix: true });+ expect({ phantomFile: b.file(PHANTOM) === edited, phantomLive: await b.live(PHANTOM) }).toEqual({ phantomFile: true, phantomLive: true });+ expect({ canonicalFile: b.file(CANONICAL) === canonicalFile, canonicalBody: (await b.body(CANONICAL)) === canonicalBody })+ .toEqual({ canonicalFile: true, canonicalBody: true });+ });+ }, 180_000);++ test('D-6 file-newer frontmatter: a key only the file carries holds the phantom and keeps the file', async () => {+ await withBrain(databaseUrl, async b => {+ const edited = `---\naliases: [alice-ex]\n---\n${PHANTOM_BODY}`;+ writeFileSync(b.path(PHANTOM), edited);+ const result = await expectUnitNotAborted(() => b.pass());+ expect({ redirected: result.redirected, held: heldFor(result, PHANTOM).length }).toEqual({ redirected: 0, held: 1 });+ expect({ phantomFile: b.file(PHANTOM) === edited, phantomLive: await b.live(PHANTOM) }).toEqual({ phantomFile: true, phantomLive: true });+ });+ }, 180_000);++ test('D-6 write-through off: the phantom is redirected in the database and its file is never removed', async () => {+ await withBrain(databaseUrl, async b => {+ await b.engine.setConfig('sync.write_through', 'false');+ _resetWriteThroughCacheForTest();+ const phantomFile = b.file(PHANTOM);+ const result = await expectUnitNotAborted(() => b.pass());+ expect({ redirected: result.redirected, held: result.held }).toEqual({ redirected: 1, held: [] });+ expect({ phantomFile: existsSync(b.path(PHANTOM)) && b.file(PHANTOM) === phantomFile, phantomLive: await b.live(PHANTOM) })+ .toEqual({ phantomFile: true, phantomLive: false });+ expect(claims(await b.body(CANONICAL))).toEqual([CLAIM]);+ });+ }, 180_000);++ test('D-6 concurrent phantom file edit after the comparison: the redirect lands, the edited file is kept and reported', async () => {+ await withBrain(databaseUrl, async b => {+ const edited = `${PHANTOM_BODY}\n${LATE_EDIT}\n`;+ let landed = false;+ const racing = editsBeforePhantomDelete(b.engine, async () => { writeFileSync(b.path(PHANTOM), edited); landed = true; });+ const result = await expectUnitNotAborted(() => b.pass(racing));+ expect(landed).toBe(true);+ expect({ redirected: result.redirected, held: heldFor(result, PHANTOM).length }).toEqual({ redirected: 1, held: 1 });+ expect({ phantomFile: existsSync(b.path(PHANTOM)) && b.file(PHANTOM) === edited }).toEqual({ phantomFile: true });+ });+ }, 180_000);++ test('D-6 agreeing copies: the phantom is redirected and its file is removed', async () => {+ await withBrain(databaseUrl, async b => {+ const result = await expectUnitNotAborted(() => b.pass());+ expect({ redirected: result.redirected, held: result.held }).toEqual({ redirected: 1, held: [] });+ expect({ phantomFile: existsSync(b.path(PHANTOM)), phantomLive: await b.live(PHANTOM) }).toEqual({ phantomFile: false, phantomLive: false });+ expect({ file: claims(b.file(CANONICAL)), db: claims(await b.body(CANONICAL)) }).toEqual({ file: [CLAIM], db: [CLAIM] });+ });+ }, 180_000);+ });+}