Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(write-through): derived atoms/concepts, brainstorm and takes never overwrite a checkout file the database does not hold (#6982)
garrytan13e682e056cf
diff --git a/src/commands/brainstorm.ts b/src/commands/brainstorm.tsindex de2498a3e8..f42e42ccc9 100644--- a/src/commands/brainstorm.ts+++ b/src/commands/brainstorm.ts@@ -24,9 +24,10 @@ import {} from '../core/brainstorm/orchestrator.ts';import { loadConfig } from '../core/config.ts';import { StructuredAgentError } from '../core/errors.ts';-import { serializeMarkdown } from '../core/markdown.ts';+import { parseMarkdown, serializeMarkdown } from '../core/markdown.ts';import { importFromContent } from '../core/import-file.ts';-import { writePageThrough, type WriteThroughResult } from '../core/write-through.ts';+import { isWriteThroughDisabled, resolvePageWriteTarget, writePageThrough, type WriteThroughResult } from '../core/write-through.ts';+import { fileDatabaseDriftHold, replaceableFile } from '../core/facts/file-body-guard.ts';import { randomBytes } from 'crypto';import { legacyNestedErrorDocument } from '../core/agent-output.ts';import { CapFlagError, mergeCapFlag, parseCapFlag, type CapFlag } from '../core/budget/cap-flag.ts';@@ -357,6 +358,8 @@ export interface SaveOutcome {dbError?: string;/** Disk write-through result (rendered from the saved row). */writeThrough: WriteThroughResult;+ /** Set when nothing was saved because the page's file holds content the database lacks (`file_database_drift`). */+ held?: string;}export interface SaveMessage {@@ -374,8 +377,14 @@ export interface SaveMessage {* embedding cost at save time) writes the DB row, then the shared* `writePageThrough` helper renders that row to disk. Rendering from the row* means the two sinks cannot diverge, and the row matches what `gbrain sync`- * would produce — so a later sync doesn't churn it. The file is only attempted- * when the DB write landed (it's rendered from the row).+ * would produce — so a later sync doesn't churn it (`source_kind` is part of+ * the imported frontmatter). The file is only attempted when the DB write+ * landed (it's rendered from the row).+ *+ * #6982: before importing, the page's file (a `--resume` reuses the slug) must+ * hold nothing the database lacks (`replaceableFile`); otherwise nothing is+ * saved and `held` says why. The file write is bound to the bytes compared, so+ * an edit landing during the save is kept (`skipped: 'file_changed'`).*/export async function persistSavedIdea(engine: BrainEngine,@@ -384,8 +393,18 @@ export async function persistSavedIdea(const sourceId = args.sourceId ?? 'default';let dbSaved = false;let dbError: string | undefined;+ let expectedFileBytes: string | null | undefined;try {- await importFromContent(engine, args.slug, args.content, {+ const target = await isWriteThroughDisabled(engine) ? null : await resolvePageWriteTarget(engine, args.slug, sourceId);+ const file = target?.ok ? await replaceableFile(engine, sourceId, args.slug, target.filePath) : null;+ if (file && !file.ok) {+ return { dbSaved: false, held: fileDatabaseDriftHold(args.slug, sourceId, 'the idea was not saved'), writeThrough: { written: false } };+ }+ expectedFileBytes = file?.expectedFileBytes;+ const parsed = parseMarkdown(args.content, `${args.slug}.md`);+ const content = serializeMarkdown({ ...parsed.frontmatter, source_kind: args.provenanceVia }, parsed.compiled_truth, parsed.timeline,+ { type: parsed.type, title: parsed.title, tags: parsed.tags });+ await importFromContent(engine, args.slug, content, {noEmbed: true,sourceId,sourcePath: `${args.slug}.md`,@@ -395,10 +414,7 @@ export async function persistSavedIdea(dbError = err instanceof Error ? err.message : String(err);}const writeThrough: WriteThroughResult = dbSaved- ? await writePageThrough(engine, args.slug, {- sourceId,- frontmatterOverrides: { source_kind: args.provenanceVia },- })+ ? await writePageThrough(engine, args.slug, { sourceId, expectedFileBytes }): { written: false, skipped: 'page_not_found_after_write' };return { dbSaved, dbError, writeThrough };}@@ -416,6 +432,10 @@ export function formatSaveOutcome(): SaveMessage {const { dbSaved, dbError, writeThrough } = outcome;const stderr: string[] = [];+ if (outcome.held) {+ stderr.push(`gbrain ${ctx.profileLabel}: save refused: ${outcome.held}. Rerun with --resume <run_id> once the page and its file agree.`);+ return { stderr, exitCode: 1 };+ }if (dbError) stderr.push(`gbrain ${ctx.profileLabel}: DB save failed: ${dbError}`);if (writeThrough.error) {stderr.push(`gbrain ${ctx.profileLabel}: file write failed: ${writeThrough.error}`);@@ -442,6 +462,13 @@ export function formatSaveOutcome(exitCode: 0,};}+ if (dbSaved && writeThrough.skipped === 'file_changed') {+ return {+ stdout: `\n_Saved to DB page \`${ctx.slug}\` (its file changed during the save and was kept, not rewritten: file_changed; \`gbrain sync\` imports that edit, and page history keeps this save)._`,+ stderr,+ exitCode: 0,+ };+ }if (dbSaved && writeThrough.skipped === 'url_clone') {return {stdout: `\n_Saved to DB page \`${ctx.slug}\` (the source is a clone gbrain pulls from upstream — kept database-only)._`,diff --git a/src/commands/think.ts b/src/commands/think.tsindex e8d89c1efa..c58c14a6a1 100644--- a/src/commands/think.ts+++ b/src/commands/think.ts@@ -231,8 +231,8 @@ prints what would have been the input (exit 0).}// #2556: --take was documented (and parsed) since v0.28 but never- // executed — runThink ignored opts.take entirely. Persist md-first- // through the canonical takes write-through; a refusal (no repo, empty+ // executed — runThink ignored opts.take entirely. Persist through the+ // coordinated takes_add mutation; a refusal (no repo, empty// answer, failed synthesis, write error) exits non-zero (same F2// posture as --save: the user explicitly asked for a persist).if (take && anchor) {diff --git a/src/core/cycle/concept-publication.ts b/src/core/cycle/concept-publication.tsindex f145f1b374..42d342fd38 100644--- a/src/core/cycle/concept-publication.ts+++ b/src/core/cycle/concept-publication.ts@@ -10,18 +10,16 @@ import type { BrainEngine, LinkBatchInput } from '../engine.ts';import { preservedConceptSections, stripPreservedConceptSections } from './concept-sections.ts';import type { Page } from '../types.ts';import { assertInlineBody } from '../page-body/page-shape.ts';-import { serializeMarkdown, parseMarkdown, type ParsedMarkdown } from '../markdown.ts';-import { digest } from '../persistence/digest.ts';+import { serializeMarkdown, parseMarkdown } from '../markdown.ts';import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, replaceOrInsertFactsFence, stripFactsFence } from '../facts-fence.ts';import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence, stripTakesFence } from '../takes-fence.ts';import { isDbOnly, loadStorageConfig } from '../storage-config.ts';import { publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';import { withCoordinatedWrite } from '../persistence/context.ts';import { maintenanceAttribution } from '../persistence/attribution.ts';-import { existsSync, readFileSync } from 'node:fs';import { acquirePageLock } from '../page-lock.ts';-import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';-import { writeDerivedPageThrough } from './derived-write-through.ts';+import { derivedFileTarget, writeDerivedPageThrough } from './derived-write-through.ts';+import { fileDatabaseDriftHold, replaceableFile } from '../facts/file-body-guard.ts';import { declareDerivation, deriveTrust, lowerDerivedPage } from '../trust/taint.ts';/** #5575 I2: the narrative carries the tier of the member atoms its prompt was built from (capped at agent_written). */@@ -172,50 +170,27 @@ export function stripFenceSections(body: string): string {.replace(/\n{3,}/g, '\n\n').trim();}-/**- * The page's markdown file when write-through is not off: its raw bytes (null- * when absent), which bind the later file write to this read, and, when it- * exists, its parse. The fence writers write the file first.- */-async function conceptFile(engine: BrainEngine, slug: string, sourceId: string): Promise<{ bytes: string | null; parsed: ParsedMarkdown | null } | null> {- if (await isWriteThroughDisabled(engine)) return null;- const target = await resolvePageWriteTarget(engine, slug, sourceId);- if (!target.ok) return null;- if (!existsSync(target.filePath)) return { bytes: null, parsed: null };- const bytes = readFileSync(target.filePath, 'utf-8');- return { bytes, parsed: parseMarkdown(bytes, target.filePath) };-}--/**- * Whether the page's file holds the database row in every part publication- * takes from the row: the narrative (fences aside, which publication carries- * from the file), frontmatter, tags, type and title. Formatting differs- * freely; any edit the database has not imported does not match.- */-function fileHoldsPage(file: ParsedMarkdown, page: Page, tags: string[]): boolean {- const owned = (p: { compiled_truth: string; type: string; title: string; frontmatter: Record<string, unknown> }, t: string[]) => digest({- narrative: stripFenceSections(p.compiled_truth), type: p.type, title: p.title.trim(), frontmatter: p.frontmatter, tags: [...new Set(t)].sort(),- });- return owned({ ...file, type: file.typeExplicit ? file.type : page.type }, file.tags) === owned(page, tags);-}-/*** Publish one concept page on an unmanaged brain (D-N3). Under the page lock* the fence writers take, the page is re-read: when its narrative changed- * since `baseline` (the narrative the synthesis started from), another- * writer took it over, or its file holds an edit the database has not- * imported (narrative, frontmatter or tags), nothing is written and the- * concept is deferred (`revision_conflict`) to the next run; sync imports the- * edit first. Otherwise the new narrative is composed with the latest- * `## Facts` / `## Takes` fences, timeline, tags and frontmatter, so a take- * or fact appended during synthesis survives. The page's file is rewritten- * when it already has one (a stale file would otherwise be synced back over- * the new narrative) or when `cycle.synthesize_concepts.write_through` is on- * (#5041). `importPage` writes the composed markdown to the database; the- * file write is then bound to the bytes read under the lock, so an edit made- * while the import ran is kept and the concept deferred, and a failed file- * write holds the concept (`concept_write_through_failed`). Returns the- * narrative now on the page (the next call's baseline).+ * since `baseline` (the narrative the synthesis started from) or another+ * writer took it over, nothing is written and the concept is deferred+ * (`revision_conflict`) to the next run. #6982: when the page's canonical+ * file exists and holds anything the database lacks (`replaceableFile`: it+ * equals neither the page nor one of its recent versions, which covers a hand+ * edit sync has not imported and an unindexed file at a new concept's path),+ * nothing is written and the concept is deferred (`revision_conflict`, its+ * message naming the page with `file_database_drift` and the fix).+ * Otherwise the new narrative is composed with the page's latest `## Facts`+ * / `## Takes` fences, timeline, tags and frontmatter from the database, so+ * a take or fact appended during synthesis survives. The page's file is+ * rewritten when it already has one (a stale file would otherwise be synced+ * back over the new narrative) or when `cycle.synthesize_concepts.write_through`+ * is on (#5041). `importPage` writes the composed markdown to the database;+ * the file write is then bound to the bytes compared under the lock, so an+ * edit made while the import ran is kept and the concept deferred, and a+ * failed file write holds the concept (`concept_write_through_failed`).+ * Returns the narrative now on the page (the next call's baseline).*/export async function publishClassicConcept(engine: BrainEngine, slug: string, sourceId: string,synthesized: Record<string, unknown>, narrative: string, baseline: string,@@ -230,20 +205,19 @@ export async function publishClassicConcept(engine: BrainEngine, slug: string, sthrow Object.assign(new Error('The concept narrative changed during synthesis.'), { code: 'revision_conflict' });}const title = slug.split('/').pop()!.replace(/-/g, ' ');- const file = await conceptFile(engine, slug, sourceId);- const existing = page && file?.parsed ? file.parsed : null;- if (existing && !fileHoldsPage(existing, page!, snapshot!.tags)) {- throw Object.assign(new Error('The concept file holds an edit the database has not imported.'), { code: 'revision_conflict' });+ const resolved = await derivedFileTarget(engine, slug, sourceId);+ const file = resolved.ok ? await replaceableFile(engine, sourceId, slug, resolved.target.filePath) : null;+ if (file && !file.ok) {+ throw Object.assign(new Error(fileDatabaseDriftHold(slug, sourceId, 'the concept was not published')), { code: 'revision_conflict' });}const markdown = page- ? composeConceptRepublication({ ...page, ...(existing ? { compiled_truth: existing.compiled_truth, timeline: existing.timeline } : {}) },- snapshot!.tags, synthesized, narrative)+ ? composeConceptRepublication(page, snapshot!.tags, synthesized, narrative): serializeMarkdown(synthesized, narrative, '', { type: 'concept', title, tags: [] });await opts.importPage(markdown);// The import stamps the page by its own channel; the derivation lowers it to the members' taint and records the edges.if (opts.members) await lowerDerivedPage(engine, await conceptDerivation(engine, sourceId, opts.members), sourceId, slug);- if (existing || opts.writeThrough) {- const written = await writeDerivedPageThrough(engine, slug, sourceId, file ? { expectedFileBytes: file.bytes } : {});+ if (file && (file.expectedFileBytes !== null || opts.writeThrough)) {+ const written = await writeDerivedPageThrough(engine, slug, sourceId, { expectedFileBytes: file.expectedFileBytes });if (written.skipped === 'file_changed') {throw Object.assign(new Error('The concept file changed while the page was published; the edit was kept.'), { code: 'revision_conflict' });}diff --git a/src/core/cycle/derived-write-through.ts b/src/core/cycle/derived-write-through.tsindex dc3a7fafc2..1187b627b1 100644--- a/src/core/cycle/derived-write-through.ts+++ b/src/core/cycle/derived-write-through.ts@@ -13,13 +13,20 @@* database-only. The first run after the key is enabled also writes the* generated pages that have no file yet, a bounded batch per run. A page the* phase retires has its file removed, so sync cannot bring it back.+ *+ * #6982: a file is replaced or removed only when it holds nothing the+ * database lacks (`replaceableFile`: absent, or equal to the page or one of+ * its recent versions), and the write is bound to the bytes compared. A file+ * holding a hand edit or an unindexed file at the path is left as it is and+ * the page is reported in the hook's `held` list (`file_database_drift`).*/import { execFileSync } from '../spawn.ts';import { relative } from 'node:path';import type { BrainEngine } from '../engine.ts';import { isDbOnly, loadStorageConfig } from '../storage-config.ts';-import { deletePageThrough, resolvePageWriteTarget, writePageThrough } from '../write-through.ts';+import { deletePageThrough, isWriteThroughDisabled, resolvePageWriteTarget, writePageThrough, type PageWriteTarget } from '../write-through.ts';import { gitChildEnv } from '../git-env.ts';+import { fileDatabaseDriftHold, replaceableFile } from '../facts/file-body-guard.ts';export const DERIVED_WRITE_THROUGH_KEYS = {extract_atoms: 'cycle.extract_atoms.write_through',@@ -45,24 +52,68 @@ function gitIgnores(root: string, filePath: string): boolean {}}+/**+ * The checkout file a generated page publishes to, or why it has none this+ * module writes: write-through off (`disabled_by_config`), no resolvable+ * target, or a target ignored by git or inside a declared `storage.db_only`+ * directory (`not_canonical`). `includeDeleted` resolves a retired page's+ * recorded path.+ */+export async function derivedFileTarget(engine: BrainEngine, slug: string, sourceId: string,+ opts: { includeDeleted?: boolean } = {}): Promise<{ ok: true; target: Extract<PageWriteTarget, { ok: true }> } | { ok: false; skipped: string }> {+ if (await isWriteThroughDisabled(engine)) return { ok: false, skipped: 'disabled_by_config' };+ const target = await resolvePageWriteTarget(engine, slug, sourceId, opts);+ if (!target.ok) return { ok: false, skipped: target.skipped };+ let storage = null;+ try { storage = loadStorageConfig(target.writeRoot); } catch { /* unreadable gbrain.yml: sync reports it */ }+ if ((storage && isDbOnly(slug, storage)) || gitIgnores(target.writeRoot, target.filePath)) return { ok: false, skipped: 'not_canonical' };+ return { ok: true, target };+}+/*** Write one generated page's markdown file. Never throws; the result says* whether a file was written, why not, or the write error. Ignored and db_only* targets are skipped on purpose (`skipped: 'not_canonical'`).- * `expectedFileBytes` binds the write to the file the caller read.+ * `expectedFileBytes` binds the write to the file the caller read (and+ * already compared); without it the file must pass `replaceableFile` first,+ * else nothing is written (`skipped: 'file_database_drift'`).*/export async function writeDerivedPageThrough(engine: BrainEngine, slug: string, sourceId: string,opts: { expectedFileBytes?: string | null } = {}): Promise<{ written: boolean; skipped?: string; error?: string }> {- const target = await resolvePageWriteTarget(engine, slug, sourceId);- if (!target.ok) return { written: false, skipped: target.skipped };- let storage = null;- try { storage = loadStorageConfig(target.writeRoot); } catch { /* unreadable gbrain.yml: sync reports it */ }- if ((storage && isDbOnly(slug, storage)) || gitIgnores(target.writeRoot, target.filePath)) return { written: false, skipped: 'not_canonical' };- const result = await writePageThrough(engine, slug, { sourceId, expectedFileBytes: opts.expectedFileBytes });+ const resolved = await derivedFileTarget(engine, slug, sourceId);+ if (!resolved.ok) return { written: false, skipped: resolved.skipped };+ let expectedFileBytes = opts.expectedFileBytes;+ if (expectedFileBytes === undefined) {+ const file = await replaceableFile(engine, sourceId, slug, resolved.target.filePath);+ if (!file.ok) return { written: false, skipped: 'file_database_drift' };+ expectedFileBytes = file.expectedFileBytes;+ }+ const result = await writePageThrough(engine, slug, { sourceId, expectedFileBytes });if (result.error) console.error(`[write-through] ${slug}: ${result.error}`);return result;}+/**+ * Remove a retired generated page's file when the retired page (or one of+ * its versions) holds everything in it; the unlink is bound to the bytes+ * compared. Returns `file_database_drift` when the file holds an edit the+ * database lacks.+ */+async function deleteDerivedPageThrough(engine: BrainEngine, slug: string, sourceId: string): Promise<{ removed: boolean; skipped?: string }> {+ const resolved = await derivedFileTarget(engine, slug, sourceId, { includeDeleted: true });+ if (!resolved.ok) return { removed: false, skipped: resolved.skipped };+ const file = await replaceableFile(engine, sourceId, slug, resolved.target.filePath);+ if (!file.ok) return { removed: false, skipped: 'file_database_drift' };+ if (file.expectedFileBytes === null) return { removed: false, skipped: 'file_not_present' };+ return deletePageThrough(engine, slug, { sourceId, target: resolved.target, expectedFileBytes: file.expectedFileBytes });+}++/** The phase's write-through hook: `write` publishes pages and removes retired ones' files; `held` reports each page left alone. */+export interface DerivedWriteThrough {+ write(slugs: readonly string[], retired?: readonly string[]): Promise<void>;+ held: string[];+}+/*** The phase's write-through hook, or null when it does not apply (key off,* managed brain, dry run): writes the given pages and removes the files of@@ -74,11 +125,21 @@ export async function derivedWriteThrough(phase: keyof typeof DERIVED_WRITE_THROUGH_KEYS,sourceId: string,opts: { managed: boolean; dryRun: boolean },-): Promise<((slugs: readonly string[], retired?: readonly string[]) => Promise<void>) | null> {+): Promise<DerivedWriteThrough | null> {if (opts.managed || opts.dryRun || !await derivedWriteThroughEnabled(engine, phase)) return null;+ const held: string[] = [];+ const kept = (skipped: string | undefined) => skipped === 'file_database_drift' || skipped === 'file_changed';const write = async (slugs: readonly string[], retired: readonly string[] = []) => {- for (const slug of slugs) await writeDerivedPageThrough(engine, slug, sourceId);- for (const slug of retired) await deletePageThrough(engine, slug, { sourceId });+ for (const slug of slugs) {+ if (kept((await writeDerivedPageThrough(engine, slug, sourceId)).skipped)) {+ held.push(fileDatabaseDriftHold(slug, sourceId, 'the generated page was not written to it'));+ }+ }+ for (const slug of retired) {+ if (kept((await deleteDerivedPageThrough(engine, slug, sourceId)).skipped)) {+ held.push(fileDatabaseDriftHold(slug, sourceId, 'the retired page\'s file was not removed'));+ }+ }};const rows = await engine.executeRaw<{ slug: string }>(`SELECT slug FROM pages@@ -89,5 +150,5 @@ export async function derivedWriteThrough([sourceId, phase === 'extract_atoms' ? 'atom' : 'concept', DERIVED_BACKFILL_LIMIT],);await write(rows.map(r => r.slug));- return write;+ return { write, held };}diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex 9298f99163..84b896aa65 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -862,13 +862,16 @@ export async function runPhaseExtractAtoms(// Phase-level no-op: nothing to extract today.if (work.length === 0 && transcripts.length === 0 && pages.length === 0) {+ const held = atomFiles?.held ?? [];return {phase: 'extract_atoms',- status: 'skipped',+ status: held.length > 0 ? 'warn' : 'skipped',duration_ms: 0,- summary: 'extract_atoms: no transcripts or pages to process',+ summary: 'extract_atoms: no transcripts or pages to process'+ + (held.length > 0 ? ` (${held.length} atom file(s) left as they are: file_database_drift)` : ''),details: {reason: 'no_work',+ ...(held.length > 0 ? { file_holds: held } : {}),source_id: sourceId,atoms_extracted: 0,transcripts_processed: 0,@@ -1302,7 +1305,7 @@ export async function runPhaseExtractAtoms(// #6503: a cut item keeps its atoms provisional (`pending:<hash>`, the upsert path when it runs// again), retires nothing and records its partial disposition instead of a completion stamp.const retired = truncated ? [] : await completeUnmanagedItem(engine, sourceId, item, hash16, importedSlugs);- await atomFiles?.(importedSlugs, retired);+ await atomFiles?.write(importedSlugs, retired);if (truncated) await recordPartialDisposition(engine, sourceId, item, maxInputChars);else if (item.kind === 'page') await stampAtomsScanHash(item);await commitAtomsWatermark(item, input, []);@@ -1414,7 +1417,7 @@ export async function runPhaseExtractAtoms(// succeed, even though skips are not failures and leave failures[] empty.// Reporting 'ok' there hides a total no-op behind a green status.status:- failures.length > 0 ||+ failures.length > 0 || (atomFiles?.held.length ?? 0) > 0 ||(work.length > 0 &&totalAtomsExtracted === 0 &&transcriptsSkipped + pagesSkipped === work.length)@@ -1429,9 +1432,11 @@ export async function runPhaseExtractAtoms((transcriptsSkipped + pagesSkipped > 0? ` (${transcriptsSkipped + pagesSkipped} budget-skipped)`: '') +- (inputTruncated > 0 ? ` (${inputTruncated} input-truncated: the model did not read the tail)` : ''),+ (inputTruncated > 0 ? ` (${inputTruncated} input-truncated: the model did not read the tail)` : '') ++ ((atomFiles?.held.length ?? 0) > 0 ? ` (${atomFiles!.held.length} atom file(s) left as they are: file_database_drift)` : ''),details: {atoms_extracted: totalAtomsExtracted,+ ...((atomFiles?.held.length ?? 0) > 0 ? { file_holds: atomFiles!.held } : {}),transcripts_processed: transcriptsProcessed,transcripts_total: transcripts.length,transcripts_skipped_budget: transcriptsSkipped,diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.tsindex 8220096847..ea3b15d258 100644--- a/src/core/cycle/synthesize-concepts.ts+++ b/src/core/cycle/synthesize-concepts.ts@@ -619,7 +619,8 @@ export async function runPhaseSynthesizeConcepts(return {phase: 'synthesize_concepts',- status: failures.length > 0 || linkWarnings.length > 0 || publicationDeferred.length > 0 || publicationHeld.length > 0 || skippedFileDrift.length > 0 ? 'warn' : 'ok',+ status: failures.length > 0 || linkWarnings.length > 0 || publicationDeferred.length > 0 || publicationHeld.length > 0 || skippedFileDrift.length > 0+ || (conceptFiles?.held.length ?? 0) > 0 ? 'warn' : 'ok',duration_ms: 0,summary:`synthesize_concepts: ${conceptsWritten} concepts ` +@@ -634,7 +635,8 @@ export async function runPhaseSynthesizeConcepts((skippedRetryBound.length > 0 ? ` (${skippedRetryBound.length} skipped after ${MAX_CONCEPT_ATTEMPTS} failed attempts on unchanged members)` : '') +(publicationDeferred.length > 0 ? ` (${publicationDeferred.length} publication(s) deferred: page changed, retried next run)` : '') +(publicationHeld.length > 0 ? ` (${publicationHeld.length} publication(s) held: existing page needs import/repair)` : '') +- (skippedFileDrift.length > 0 ? ` (${skippedFileDrift.length} skipped before synthesis: canonical file differs from the database; ${driftActions.join('; ')})` : ''),+ (skippedFileDrift.length > 0 ? ` (${skippedFileDrift.length} skipped before synthesis: canonical file differs from the database; ${driftActions.join('; ')})` : '') ++ ((conceptFiles?.held.length ?? 0) > 0 ? ` (${conceptFiles!.held.length} concept file(s) left as they are: file_database_drift)` : ''),details: {concepts_written: conceptsWritten,tier_counts: tierCounts,@@ -655,6 +657,7 @@ export async function runPhaseSynthesizeConcepts(folded_spellings: foldedSpellings,publication_deferred: publicationDeferred,publication_held: publicationHeld,+ ...((conceptFiles?.held.length ?? 0) > 0 ? { file_holds: conceptFiles!.held } : {}),...(abortedGlobalError ? { aborted_global_error: abortedGlobalError } : {}),estimated_spend_usd: estimatedSpendUsd,budget_usd: budgetCap,diff --git a/src/core/extract-takes-from-pages.ts b/src/core/extract-takes-from-pages.tsindex 916860e8f7..c51be5b4b0 100644--- a/src/core/extract-takes-from-pages.ts+++ b/src/core/extract-takes-from-pages.ts@@ -29,6 +29,8 @@ import {TakesWriteError,} from './takes-write.ts';import { managedPersistenceEnabled } from './persistence/ownership.ts';+import { isWriteThroughDisabled, resolvePageWriteTarget } from './write-through.ts';+import { isDbOnly, loadStorageConfig } from './storage-config.ts';import { serializePageToMarkdown } from './markdown.ts';import { BudgetMeter, loadPricingOverrides } from './cycle/budget-meter.ts';import { parseTakesFence } from './takes-fence.ts';@@ -143,6 +145,19 @@ interface PageRow {resume_at: string;}+/** Whether an unmanaged page's database body is its copy of record: write-through off, or its target in a storage.db_only directory. */+async function databaseOnlyPage(engine: BrainEngine, slug: string, sourceId: string): Promise<boolean> {+ if (await isWriteThroughDisabled(engine)) return true;+ const target = await resolvePageWriteTarget(engine, slug, sourceId);+ if (!target.ok) return false;+ try {+ const storage = loadStorageConfig(target.writeRoot);+ return storage !== null && isDbOnly(slug, storage);+ } catch {+ return false;+ }+}+/*** Pure helper: parse Haiku JSON output into typed claims. Returns []* on any parse failure (caller treats as "no claims extracted").@@ -264,11 +279,17 @@ export async function extractTakesFromPages(if (!page.compiled_truth || page.compiled_truth.length < 200) continue;- // #4473: locate the page's markdown home BEFORE the LLM call — a page the- // fence writer would refuse must not burn classifier budget (skipped pages- // hold no takes, so every future run would re-classify them).+ // The database is the page's copy of record on a managed brain, and on an+ // unmanaged one when write-through is off or the page sits in a declared+ // storage.db_only directory: its takes are composed from the database+ // snapshot and published through put_page, never from a file.+ const fromDatabase = managedJournalWrites || (!dryRun && await databaseOnlyPage(engine, page.slug, page.source_id));++ // #4473: locate a file-backed page's markdown home BEFORE the LLM call — a+ // page the fence writer would refuse must not burn classifier budget+ // (skipped pages hold no takes, so every future run would re-classify them).let mdPath: string | null = null;- if (!dryRun) {+ if (!dryRun && !fromDatabase) {try {const { path } = await resolveTakesWritePath(engine, repoDir, page.slug, page.source_id);if (existsSync(path)) mdPath = path;@@ -281,11 +302,11 @@ export async function extractTakesFromPages(}}- // Pin the selected page before spending time on extraction. A managed- // publication with a newer revision must skip the whole page atomically.- const managedSnapshot = managedJournalWrites && !dryRun+ // Pin the selected page before spending time on extraction. A publication+ // with a newer revision must skip the whole page atomically.+ const managedSnapshot = fromDatabase && !dryRun? await engine.readPageSnapshot(page.slug, { sourceId: page.source_id }) : null;- if (managedJournalWrites && !dryRun && (!managedSnapshot || managedSnapshot.page.id !== page.id)) {+ if (fromDatabase && !dryRun && (!managedSnapshot || managedSnapshot.page.id !== page.id)) {skipPage(page.slug, 'page_identity_changed');continue;}@@ -348,7 +369,7 @@ export async function extractTakesFromPages(// Never append a claim the page's takes fence already holds (a rerun with// includeCovered, or a hand-added take): duplicate gradeable takes skew// calibration. The fence is canonical, so dedupe against its active rows.- const duplicateBody = managedJournalWrites+ const duplicateBody = fromDatabase? serializePageToMarkdown(managedSnapshot!.page, managedSnapshot!.tags): readFileSync(mdPath!, 'utf-8');const held = new Set(parseTakesFence(duplicateBody).takes@@ -372,7 +393,7 @@ export async function extractTakesFromPages(weight: c.weight,source: 'cli:takes-bootstrap-from-pages',}));- if (managedJournalWrites) {+ if (fromDatabase) {const body = await materializeTakeResolutions(engine, managedSnapshot!.page.id, serializePageToMarkdown(managedSnapshot!.page, managedSnapshot!.tags));const composed = appendTakesToPageBody(body, rows);const { operations } = await import('./operations.ts');@@ -398,7 +419,7 @@ export async function extractTakesFromPages(}} catch (err) {const code = (err as { code?: string; writeError?: string })?.code ?? (err as { writeError?: string })?.writeError;- if (managedJournalWrites && (code === 'revision_conflict' || code === 'page_identity_changed' || code === 'source_changed')) {+ if (fromDatabase && (code === 'revision_conflict' || code === 'page_identity_changed' || code === 'source_changed')) {skipPage(page.slug, code);continue;}diff --git a/src/core/facts/file-body-guard.ts b/src/core/facts/file-body-guard.tsindex f09db2fdb1..6488990e08 100644--- a/src/core/facts/file-body-guard.ts+++ b/src/core/facts/file-body-guard.ts@@ -13,7 +13,7 @@import { existsSync, readFileSync } from 'node:fs';import type { BrainEngine } from '../engine.ts';import { sanitizeText } from '../batch-rows.ts';-import { parseMarkdown } from '../markdown.ts';+import { parseMarkdown, parseMarkdownHead } from '../markdown.ts';import { contentHash, contentHashFrontmatterAndTags } from '../utils.ts';export interface StoredBody {@@ -60,12 +60,26 @@ export async function mirrorFileBody(tx: BrainEngine, sourceId: string, slug: st/** Page states a checkout file is compared with: the live row, then its newest page_versions rows. */const HISTORY_ROWS = 20;-interface StoredState extends StoredBody { frontmatter: Record<string, unknown> | null }+interface StoredState extends StoredBody {+ frontmatter: Record<string, unknown> | null;+ title: string | null;+ type: string | null;+ tags: unknown;+}-/** Whether the file's body, timeline and every frontmatter key it carries (ephemeral keys aside) equal `state`'s. */+/**+ * Whether the file's body, timeline, every frontmatter key it carries (ephemeral keys aside), its tags, and the title+ * and type its frontmatter declares equal `state`'s.+ */function fileHeldBy(fileBytes: string, slug: string, state: StoredState): boolean {if (!fileBodyMatchesStored(fileBytes, slug, state)) return false;- const file = contentHashFrontmatterAndTags({ frontmatter: parseMarkdown(fileBytes, `${slug}.md`).frontmatter });+ const parsed = parseMarkdown(fileBytes, `${slug}.md`);+ const declared = parseMarkdownHead(fileBytes).frontmatter;+ if (declared.title !== undefined && parsed.title.trim() !== (state.title ?? '').trim()) return false;+ if (parsed.typeExplicit && parsed.type !== state.type) return false;+ const storedTags = Array.isArray(state.tags) ? state.tags.map(String) : [];+ if (JSON.stringify([...new Set(parsed.tags)].sort()) !== JSON.stringify([...new Set(storedTags)].sort())) return false;+ const file = contentHashFrontmatterAndTags({ frontmatter: parsed.frontmatter });const stored = contentHashFrontmatterAndTags({ frontmatter: state.frontmatter ?? {} });return Object.entries(file.frontmatter).every(([key, value]) => JSON.stringify(value) === JSON.stringify(stored.frontmatter[key]));}@@ -85,10 +99,22 @@ export async function replaceableFile(engine: BrainEngine, sourceId: string, sluif (!existsSync(filePath)) return { ok: true, expectedFileBytes: null };const bytes = readFileSync(filePath, 'utf-8');const states = await engine.executeRaw<StoredState>(- `(SELECT compiled_truth, timeline, frontmatter FROM pages WHERE source_id = $1 AND slug = $2)+ `(SELECT p.compiled_truth, p.timeline, p.frontmatter, p.title, p.type,+ to_jsonb(ARRAY(SELECT t.tag FROM tags t WHERE t.page_id = p.id)) AS tags+ FROM pages p WHERE p.source_id = $1 AND p.slug = $2)UNION ALL- (SELECT v.compiled_truth, v.timeline, v.frontmatter FROM page_versions v JOIN pages p ON p.id = v.page_id+ (SELECT v.compiled_truth, v.timeline, v.frontmatter, v.title, v.type, v.tags FROM page_versions v JOIN pages p ON p.id = v.page_idWHERE p.source_id = $1 AND p.slug = $2 AND v.compiled_truth IS NOT NULL ORDER BY v.id DESC LIMIT ${HISTORY_ROWS})`,[sourceId, slug]);return states.some(state => fileHeldBy(bytes, slug, state)) ? { ok: true, expectedFileBytes: bytes } : { ok: false };}++/**+ * #6982: the report for a page whose checkout file holds content the database lacks (a hand edit sync has not imported,+ * or an unindexed file at the page's path), so the file was left as it is; `outcome` says what the caller did not do.+ */+export function fileDatabaseDriftHold(slug: string, sourceId: string, outcome: string): string {+ return `${slug} (file_database_drift: the checkout file holds content the database does not, so it was left as it is and ${outcome}. `+ + `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)`;+}diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.tsindex 26bb36e380..202d5ba9a4 100644--- a/src/core/ops/takes.ts+++ b/src/core/ops/takes.ts@@ -358,7 +358,7 @@ const think: Operation = {// #2556: `take` was gated (safeTake) but never EXECUTED — runThink ignores// opts.take, so a local `take: true` silently persisted nothing. Persist- // md-first through the canonical takes write-through; refusals surface as+ // through the coordinated takes_add mutation; refusals surface as// loud machine-stable warnings + take_row:null. Remote stays blocked above.let takeRow: number | null = null;if (safeTake) {@@ -369,7 +369,6 @@ const think: Operation = {const persisted = await persistTakeFromSynthesis(ctx.engine, result, {anchor: String(p.anchor),sourceId: ctx.sourceId,- lockTimeoutMs: 2000,});takeRow = persisted.take_row;for (const w of persisted.warnings) result.warnings.push(w);diff --git a/src/core/think/persist-take.ts b/src/core/think/persist-take.tsindex ade62fccc7..736569a694 100644--- a/src/core/think/persist-take.ts+++ b/src/core/think/persist-take.ts@@ -15,12 +15,16 @@* (control chars collapsed, fence-marker text removed, bounded length).* - holder = resolveOwnerHolder (config emotional_weight.user_holder,* else 'self') — the take is the OWNER's synthesized position.- * - persistence goes md-first through addTakeToPage (the same canonical- * write-through every takes verb uses: fence row on disk, DB mirrored,- * mirror failure downgraded to a warning).+ * - persistence goes through the coordinated `takes_add` mutation (the+ * same path `gbrain takes add` uses), which composes the fence from the+ * page's database snapshot: a database-only page (`sync.write_through`+ * off, a `storage.db_only` directory) gets the take in its database body+ * and no file; a page whose file and database differ is refused+ * (`source_changed`) with both copies kept (#6982). Before, the legacy+ * md-first writer treated a page with no file as an empty body and+ * created a takes-only file that the next sync imported over the page.* - no brain repo (resolveTakesRepoDir null) → TAKE_MIRROR_UNAVAILABLE- * warning, nothing written (md is canonical; a DB-only take would be- * clobbered by the next reconcile).+ * warning, nothing written.** Remote (MCP) callers never reach this — the `think` op forces* safeTake=false for ctx.remote !== false, unchanged.@@ -29,8 +33,12 @@import type { BrainEngine } from '../engine.ts';import { stripGapsSection, type ThinkResult } from './index.ts';import { resolveOwnerHolder } from '../owner-holder.ts';-import { resolveTakesRepoDir, addTakeToPage, TakesWriteError } from '../takes-write.ts';+import { resolveTakesRepoDir } from '../takes-write.ts';import { deriveTrust, derivedMaintenanceTransaction } from '../trust/taint.ts';+import { loadConfig } from '../config.ts';+import { OperationError } from '../ops/contract.ts';+import { submitPageMutation } from '../persistence/page-mutations.ts';+import { resolvePageWriteTarget } from '../write-through.ts';/** Max claim length for a fence cell — one readable line, not an essay. */export const TAKE_CLAIM_MAX_CHARS = 300;@@ -38,7 +46,7 @@ export const TAKE_CLAIM_MAX_CHARS = 300;export interface PersistTakeResult {/** Appended fence row number, or null when nothing was written. */take_row: number | null;- /** Markdown file the row landed in (set iff take_row is non-null). */+ /** Markdown file the row landed in (unset when nothing was written or the page is database-only). */path?: string;/** Machine-stable warning codes (mirrors the think warnings channel). */warnings: string[];@@ -87,7 +95,7 @@ export function claimFromAnswer(answer: string): string | null {export async function persistTakeFromSynthesis(engine: BrainEngine,result: Pick<ThinkResult, 'answer' | 'synthesisOk' | 'taint_refs'>,- opts: { anchor: string; sourceId?: string; lockTimeoutMs?: number },+ opts: { anchor: string; sourceId?: string },): Promise<PersistTakeResult> {const warnings: string[] = [];@@ -115,34 +123,26 @@ export async function persistTakeFromSynthesis(const holder = resolveOwnerHolder({configValue: await engine.getConfig('emotional_weight.user_holder'),});+ const sourceId = opts.sourceId ?? 'default';// #5575 I2: the take restates the synthesis, so it carries the tier of everything in the synthesis prompt.const derivation = await deriveTrust(engine, result.taint_refs ?? [], { channel: 'derive:think' });try {- const { rowNum, mirror } = await addTakeToPage(- {- engine,- slug: opts.anchor,- brainDir,- sourceId: opts.sourceId,- trust: derivation.trust,- ...(opts.lockTimeoutMs !== undefined ? { lockTimeoutMs: opts.lockTimeoutMs } : {}),- },- { claim, kind: 'take', holder, source: 'think' },- );- if (mirror.mirror_warning) {- warnings.push(`TAKE_DB_MIRROR_WARNING: ${mirror.mirror_warning}`);- } else {- await derivedMaintenanceTransaction(engine, derivation, async tx => ({ result: undefined, rows: (await tx.executeRaw<{ id: number }>(- 'SELECT k.id FROM takes k JOIN pages p ON p.id=k.page_id WHERE p.source_id=$1 AND p.slug=$2 AND k.row_num=$3',- [opts.sourceId ?? 'default', opts.anchor, rowNum])).map(take => ({ table: 'takes' as const, id: Number(take.id), sourceId: opts.sourceId ?? 'default' })) }));- }- return { take_row: rowNum, path: mirror.path, warnings };+ const written = await submitPageMutation({+ engine, config: loadConfig() ?? { engine: engine.kind }, remote: false, sourceId, dryRun: false,+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ }, { operation: 'takes_add', params: { slug: opts.anchor, claim, kind: 'take', holder, source: 'think', source_id: sourceId } });+ const rowNum = Number(written.row_num);+ await derivedMaintenanceTransaction(engine, derivation, async tx => ({ result: undefined, rows: (await tx.executeRaw<{ id: number }>(+ 'SELECT k.id FROM takes k JOIN pages p ON p.id=k.page_id WHERE p.source_id=$1 AND p.slug=$2 AND k.row_num=$3',+ [sourceId, opts.anchor, rowNum])).map(take => ({ table: 'takes' as const, id: Number(take.id), sourceId })) }));+ const target = written.mirror_written ? await resolvePageWriteTarget(engine, opts.anchor, sourceId) : null;+ return { take_row: rowNum, ...(target?.ok ? { path: target.filePath } : {}), warnings };} catch (e) {- // Typed write refusals (page not found, lock timeout, fence malformed)- // become a loud warning + null row — think's answer already printed and- // must not be lost to a persistence failure.- const detail = e instanceof TakesWriteError ? `${e.code}: ${e.message}` : (e instanceof Error ? e.message : String(e));+ // Typed write refusals (page not found, a file that differs from the+ // database, a malformed fence) become a loud warning + null row — think's+ // answer already printed and must not be lost to a persistence failure.+ const detail = e instanceof OperationError ? `${e.code}: ${e.message}` : (e instanceof Error ? e.message : String(e));warnings.push(`TAKE_WRITE_FAILED: ${detail}`);return { take_row: null, warnings };}diff --git a/src/core/write-through.ts b/src/core/write-through.tsindex d647b3b70b..f05e65b949 100644--- a/src/core/write-through.ts+++ b/src/core/write-through.ts@@ -537,8 +537,10 @@ export interface DeleteThroughResult {* - url_clone: the source is a clone gbrain owns and pulls (#6946); its checkout is never written.* - file_not_present: the page had no artifact on disk (DB-only page, or* already removed by hand) — a clean no-op, not a failure.+ * - file_changed: the caller passed `expectedFileBytes` and the file no+ * longer holds them (an edit landed after the caller read it) — kept.*/- skipped?: 'disabled_by_config' | 'url_clone' | 'file_not_present' | Extract<PageWriteTarget, { ok: false }>['skipped'];+ skipped?: 'disabled_by_config' | 'url_clone' | 'file_not_present' | 'file_changed' | Extract<PageWriteTarget, { ok: false }>['skipped'];/** Set when the unlink itself threw (EACCES, EPERM, read-only mount). */error?: string;}@@ -566,11 +568,15 @@ export interface DeleteThroughResult {* stamp would miss the recorded path, fall back to the slug-derived twin, and* report a clean `file_not_present` no-op while the REAL artifact stayed on* disk — the very silent-no-op class this helper exists to close.+ *+ * `opts.expectedFileBytes`: the file bytes the caller compared; rechecked+ * under the source filesystem lock right before the unlink, and a file that+ * changed since is kept (`skipped: 'file_changed'`).*/export async function deletePageThrough(engine: BrainEngine,slug: string,- opts: { sourceId?: string; logger?: WriteThroughLogger; target?: PageWriteTarget } = {},+ opts: { sourceId?: string; logger?: WriteThroughLogger; target?: PageWriteTarget; expectedFileBytes?: string } = {},): Promise<DeleteThroughResult> {const sourceId = opts.sourceId ?? 'default';try {@@ -592,6 +598,9 @@ export async function deletePageThrough(if (!existsSync(filePath)) {return { removed: false, path: filePath, skipped: 'file_not_present' };}+ if (opts.expectedFileBytes !== undefined && readFileSync(filePath, 'utf-8') !== opts.expectedFileBytes) {+ return { removed: false, path: filePath, skipped: 'file_changed' };+ }assertSourceFilesystemActive();unlinkSync(filePath);diff --git a/test/pathological/d10-derived-atom-file-overwrite.test.ts b/test/pathological/d10-derived-atom-file-overwrite.test.tsnew file mode 100644index 0000000000..1539a02f62--- /dev/null+++ b/test/pathological/d10-derived-atom-file-overwrite.test.ts@@ -0,0 +1,193 @@+/**+ * D-10 (GBRA-131, #6982): the opt-in atom write-through never replaces a+ * checkout file that holds content the database lacks.+ *+ * Protects: with `cycle.extract_atoms.write_through` on, `extract_atoms`+ * writes an atom's file only when the file is absent or holds nothing the+ * database lacks (it equals the atom or one of its recent page_versions rows,+ * the state before the database write being published). A hand edit to an+ * atom's file that sync has not imported, alone or next to a newer database+ * extraction, and an unindexed file sitting at the path of an atom the+ * enable-time backfill would write, are kept byte for byte with the database+ * body unchanged; the phase warns and names the page in+ * `details.file_holds` with `file_database_drift` and the sync fix. An edit+ * landing after the comparison is kept too (the write is bound to the bytes+ * compared). A file that is the database's previous version is rewritten.+ * Fails when: the hook calls writePageThrough with no expectedFileBytes (the+ * pre-fix path), or the backfill treats source_path IS NULL as "no file".+ * Seams: the phase's `_transcripts` / `_chat` test inputs (no paid call), and+ * an engine proxy whose first url-clone source read once the new extraction+ * is complete (inside writePageThrough, after the comparison) lands a+ * concurrent file edit. PGLite always, Postgres when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';+import { runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts';+import type { BrainEngine } from '../../src/core/engine.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 FILE_EDIT = 'FILE-ONLY-EDIT-MARKER: a line added in the editor, not yet synced.';+const LATE_EDIT = 'CONCURRENT-EDIT-MARKER: saved while the phase ran.';+const UNINDEXED = '# Notes by alice-example\n\nA file nobody imported, at the atom path.\n';++interface Brain {+ engine: BrainEngine;+ path(slug: string): string;+ file(slug: string): string;+ body(slug: string): Promise<string>;+ atoms(): Promise<string[]>;+ extract(titles: string[], hash: string, opts?: { engine?: BrainEngine; bodySuffix?: string })+ : Promise<{ status: string; holds: string[] }>;+}++const chat = (titles: string[], bodySuffix: string) => async (_o: ChatOpts): Promise<ChatResult> => {+ const text = JSON.stringify(titles.map(title => ({ title, atom_type: 'insight', body: `${title} body.${bodySuffix}` })));+ return {+ text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic',+ };+};++async function withBrain(databaseUrl: string | undefined, run: (b: Brain) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-d10-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ _resetWriteThroughCacheForTest();+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ expect(await managedPersistenceEnabled(engine)).toBe(false);+ const root = join(home, 'brain');+ mkdirSync(root, { recursive: true });+ execFileSync('git', ['init', '-q'], { cwd: root });+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [root]);+ const path = (slug: string) => join(root, `${slug}.md`);+ await run({+ engine, path,+ file: slug => readFileSync(path(slug), 'utf8'),+ body: async slug => (await engine.executeRaw<{ compiled_truth: string }>(+ "SELECT compiled_truth FROM pages WHERE source_id = 'default' AND slug = $1", [slug]))[0]!.compiled_truth,+ atoms: async () => (await engine.executeRaw<{ slug: string }>(+ "SELECT slug FROM pages WHERE type = 'atom' AND deleted_at IS NULL ORDER BY slug")).map(r => r.slug),+ async extract(titles, hash, opts = {}) {+ const result = await runPhaseExtractAtoms(opts.engine ?? engine, {+ _transcripts: titles.length ? [{ filePath: '/fake/2026-09-07-meeting.txt', content: 'content', contentHash: hash }] : [],+ _pages: [], _chat: chat(titles, opts.bodySuffix ?? ''),+ });+ return { status: result.status, holds: ((result.details as { file_holds?: string[] }).file_holds ?? []).map(String) };+ },+ });+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++/**+ * The engine whose first url-clone source read (the one writePageThrough makes before it writes) once `slug`'s new+ * extraction is complete (its body carries `marker` and its source_hash is final) runs `before` first.+ */+function editsBeforeWrite(engine: BrainEngine, slug: string, marker: string, before: () => void): { engine: BrainEngine; fired(): boolean } {+ let fired = false;+ const complete = async () => (await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM pages WHERE source_id = 'default' AND slug = $1 AND compiled_truth LIKE '%' || $2 || '%'+ AND frontmatter->>'source_hash' NOT LIKE 'pending:%'`, [slug, marker]))[0]!.n > 0;+ const proxy = new Proxy(engine, {+ get(target, prop) {+ if (prop === 'executeRaw') return async (sql: string, ...rest: unknown[]) => {+ if (!fired && sql.includes('SELECT local_path, config FROM sources') && await complete()) { fired = true; before(); }+ return (target.executeRaw as (...a: unknown[]) => unknown).apply(target, [sql, ...rest]);+ };+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ return { engine: proxy, fired: () => fired };+}++const holdFor = (holds: string[], slug: string) => holds.filter(h => h.startsWith(`${slug} (file_database_drift`));++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`D-10 atom write-through and a checkout file the database does not hold (${backend})`, () => {+ test('D-10 control: a new atom is written, and a file holding the previous version is rewritten when the database is newer', async () => {+ await withBrain(databaseUrl, async b => {+ await b.engine.setConfig('cycle.extract_atoms.write_through', 'true');+ const first = await expectUnitNotAborted(() => b.extract(['Renders vs proof'], 'hash-one'));+ const [slug] = await b.atoms();+ expect({ status: first.status, holds: first.holds, body: b.file(slug!).includes('Renders vs proof body.') })+ .toEqual({ status: 'ok', holds: [], body: true });+ const second = await expectUnitNotAborted(() => b.extract(['Renders vs proof'], 'hash-two', { bodySuffix: ' DB-NEWER-MARKER.' }));+ expect({ holds: second.holds, file: b.file(slug!).includes('DB-NEWER-MARKER'), db: (await b.body(slug!)).includes('DB-NEWER-MARKER') })+ .toEqual({ holds: [], file: true, db: true });+ });+ }, 180_000);++ test('D-10 file-newer: a hand edit to the atom file is kept and the page is held with file_database_drift', async () => {+ await withBrain(databaseUrl, async b => {+ await b.engine.setConfig('cycle.extract_atoms.write_through', 'true');+ await b.extract(['Renders vs proof'], 'hash-one');+ const [slug] = await b.atoms();+ const edited = b.file(slug!).replace('Renders vs proof body.', `Renders vs proof body.\n\n${FILE_EDIT}`);+ writeFileSync(b.path(slug!), edited);+ const bodyBefore = await b.body(slug!);+ const phase = await expectUnitNotAborted(() => b.extract(['Renders vs proof'], 'hash-two'));+ expect({ file: b.file(slug!) === edited, body: (await b.body(slug!)) === bodyBefore }).toEqual({ file: true, body: true });+ const held = holdFor(phase.holds, slug!);+ expect({ status: phase.status, held: held.length, fix: held.some(h => h.includes('gbrain sync --source default')) })+ .toEqual({ status: 'warn', held: 1, fix: true });+ });+ }, 180_000);++ test('D-10 both changed: a newer database extraction does not replace the hand-edited file; both copies stay', async () => {+ await withBrain(databaseUrl, async b => {+ await b.engine.setConfig('cycle.extract_atoms.write_through', 'true');+ await b.extract(['Renders vs proof'], 'hash-one');+ const [slug] = await b.atoms();+ const edited = b.file(slug!).replace('Renders vs proof body.', `Renders vs proof body.\n\n${FILE_EDIT}`);+ writeFileSync(b.path(slug!), edited);+ const phase = await expectUnitNotAborted(() => b.extract(['Renders vs proof'], 'hash-two', { bodySuffix: ' DB-NEWER-MARKER.' }));+ expect({ file: b.file(slug!) === edited, db: (await b.body(slug!)).includes('DB-NEWER-MARKER') }).toEqual({ file: true, db: true });+ expect(holdFor(phase.holds, slug!).length).toBe(1);+ });+ }, 180_000);++ test('D-10 backfill: an unindexed file at a generated atom\'s path is kept when the key is enabled', async () => {+ await withBrain(databaseUrl, async b => {+ await b.extract(['Renders vs proof'], 'hash-one');+ const [slug] = await b.atoms();+ expect(existsSync(b.path(slug!))).toBe(false);+ mkdirSync(dirname(b.path(slug!)), { recursive: true });+ writeFileSync(b.path(slug!), UNINDEXED);+ const bodyBefore = await b.body(slug!);+ await b.engine.setConfig('cycle.extract_atoms.write_through', 'true');+ const phase = await expectUnitNotAborted(() => b.extract([], 'unused'));+ expect({ file: b.file(slug!) === UNINDEXED, body: (await b.body(slug!)) === bodyBefore }).toEqual({ file: true, body: true });+ expect({ status: phase.status, held: holdFor(phase.holds, slug!).length }).toEqual({ status: 'warn', held: 1 });+ });+ }, 180_000);++ test('D-10 concurrent file edit after the comparison: the editor\'s bytes survive and the page is held', async () => {+ await withBrain(databaseUrl, async b => {+ await b.engine.setConfig('cycle.extract_atoms.write_through', 'true');+ await b.extract(['Renders vs proof'], 'hash-one');+ const [slug] = await b.atoms();+ let edited = '';+ const racing = editsBeforeWrite(b.engine, slug!, 'DB-NEWER-MARKER', () => {+ edited = b.file(slug!).replace('Renders vs proof body.', `Renders vs proof body.\n\n${LATE_EDIT}`);+ writeFileSync(b.path(slug!), edited);+ });+ const phase = await expectUnitNotAborted(() => b.extract(['Renders vs proof'], 'hash-two', { engine: racing.engine, bodySuffix: ' DB-NEWER-MARKER.' }));+ expect({ fired: racing.fired(), file: b.file(slug!) === edited, late: edited.includes(LATE_EDIT) }).toEqual({ fired: true, file: true, late: true });+ expect((await b.body(slug!)).includes('DB-NEWER-MARKER')).toBe(true);+ expect(holdFor(phase.holds, slug!).length).toBe(1);+ });+ }, 180_000);+ });+}diff --git a/test/pathological/d11-derived-retired-atom-unlink.test.ts b/test/pathological/d11-derived-retired-atom-unlink.test.tsnew file mode 100644index 0000000000..b5eaf687c7--- /dev/null+++ b/test/pathological/d11-derived-retired-atom-unlink.test.ts@@ -0,0 +1,172 @@+/**+ * D-11 (GBRA-131, #6982): retiring a generated atom never unlinks a checkout+ * file that holds content the database lacks, or a file outside gbrain's+ * write targets.+ *+ * Protects: with `cycle.extract_atoms.write_through` on, an atom+ * `extract_atoms` retires loses its file only when the retired page (or one+ * of its page_versions rows) holds everything in it. A hand edit to the+ * retired atom's file is kept byte for byte, the phase warns and names the+ * page in `details.file_holds` with `file_database_drift`, and the other+ * atoms of the run are still written. A file in a declared `storage.db_only`+ * directory (which the writer never writes) is not removed. An edit landing+ * after the comparison is kept (the unlink rechecks the bytes compared under+ * the source filesystem lock). A file that is the retired page is removed.+ * Fails when: the retirement hook calls deletePageThrough with no content+ * check and no storage filter (the pre-fix path).+ * Seams: the phase's `_transcripts` / `_chat` test inputs (no paid call), and+ * an engine proxy whose first url-clone source read once the old atom is+ * retired and the new atom's file is written (deletePageThrough's, after the+ * comparison) lands the edit. PGLite always, Postgres when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';+import { runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts';+import type { BrainEngine } from '../../src/core/engine.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 FILE_EDIT = 'FILE-ONLY-EDIT-MARKER: a line added in the editor, not yet synced.';+const LATE_EDIT = 'CONCURRENT-EDIT-MARKER: saved while the retirement ran.';++interface Brain {+ engine: BrainEngine;+ root: string;+ path(slug: string): string;+ file(slug: string): string;+ atoms(live: boolean): Promise<string[]>;+ extract(titles: string[], hash: string, on?: BrainEngine): Promise<{ status: string; holds: string[] }>;+}++const chat = (titles: string[]) => async (_o: ChatOpts): Promise<ChatResult> => {+ const text = JSON.stringify(titles.map(title => ({ title, atom_type: 'insight', body: `${title} body.` })));+ return {+ text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic',+ };+};++async function withBrain(databaseUrl: string | undefined, run: (b: Brain) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-d11-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ _resetWriteThroughCacheForTest();+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ expect(await managedPersistenceEnabled(engine)).toBe(false);+ const root = join(home, 'brain');+ mkdirSync(root, { recursive: true });+ execFileSync('git', ['init', '-q'], { cwd: root });+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [root]);+ await engine.setConfig('cycle.extract_atoms.write_through', 'true');+ const path = (slug: string) => join(root, `${slug}.md`);+ await run({+ engine, root, path,+ file: slug => readFileSync(path(slug), 'utf8'),+ atoms: async live => (await engine.executeRaw<{ slug: string }>(+ "SELECT slug FROM pages WHERE type = 'atom' AND (deleted_at IS NULL) = $1 ORDER BY slug", [live])).map(r => r.slug),+ async extract(titles, hash, on = engine) {+ const result = await runPhaseExtractAtoms(on, {+ _transcripts: [{ filePath: '/fake/2026-09-07-meeting.txt', content: 'content', contentHash: hash }], _pages: [], _chat: chat(titles),+ });+ return { status: result.status, holds: ((result.details as { file_holds?: string[] }).file_holds ?? []).map(String) };+ },+ });+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++/**+ * The engine whose first url-clone source read once `retired` is retired and every live atom's file exists (the read+ * deletePageThrough makes before it unlinks) runs `before` first.+ */+function editsBeforeUnlink(engine: BrainEngine, retired: string, path: (slug: string) => string, before: () => void): { engine: BrainEngine; fired(): boolean } {+ let fired = false;+ const ready = async () => {+ const rows = await engine.executeRaw<{ slug: string; deleted: boolean }>(+ "SELECT slug, deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id = 'default' AND type = 'atom'");+ return rows.some(r => r.slug === retired && r.deleted) && rows.filter(r => !r.deleted).every(r => existsSync(path(r.slug)));+ };+ const proxy = new Proxy(engine, {+ get(target, prop) {+ if (prop === 'executeRaw') return async (sql: string, ...rest: unknown[]) => {+ if (!fired && sql.includes('SELECT local_path, config FROM sources') && await ready()) { fired = true; before(); }+ return (target.executeRaw as (...a: unknown[]) => unknown).apply(target, [sql, ...rest]);+ };+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ return { engine: proxy, fired: () => fired };+}++const holdFor = (holds: string[], slug: string) => holds.filter(h => h.startsWith(`${slug} (file_database_drift`) && h.includes('was not removed'));++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`D-11 retired atom files and a checkout file the database does not hold (${backend})`, () => {+ test('D-11 control: a retired atom whose file is the retired page loses its file', async () => {+ await withBrain(databaseUrl, async b => {+ await b.extract(['Renders vs proof'], 'hash-one');+ const [old] = await b.atoms(true);+ expect(existsSync(b.path(old!))).toBe(true);+ const phase = await expectUnitNotAborted(() => b.extract(['A different lesson'], 'hash-two'));+ expect({ retired: await b.atoms(false), file: existsSync(b.path(old!)), holds: phase.holds }).toEqual({ retired: [old!], file: false, holds: [] });+ });+ }, 180_000);++ test('D-11 file-newer: a hand edit to a retired atom\'s file is kept, held with file_database_drift, and the new atom is still written', async () => {+ await withBrain(databaseUrl, async b => {+ await b.extract(['Renders vs proof'], 'hash-one');+ const [old] = await b.atoms(true);+ const edited = b.file(old!).replace('Renders vs proof body.', `Renders vs proof body.\n\n${FILE_EDIT}`);+ writeFileSync(b.path(old!), edited);+ const phase = await expectUnitNotAborted(() => b.extract(['A different lesson'], 'hash-two'));+ const [current] = await b.atoms(true);+ expect({ retired: await b.atoms(false), file: existsSync(b.path(old!)) && b.file(old!) === edited, current: existsSync(b.path(current!)) })+ .toEqual({ retired: [old!], file: true, current: true });+ const held = holdFor(phase.holds, old!);+ expect({ status: phase.status, held: held.length, fix: held.some(h => h.includes('gbrain sync --source default')) })+ .toEqual({ status: 'warn', held: 1, fix: true });+ });+ }, 180_000);++ test('D-11 storage.db_only: a file in a db_only directory is never removed by retirement', async () => {+ await withBrain(databaseUrl, async b => {+ writeFileSync(join(b.root, 'gbrain.yml'), 'storage:\n db_only:\n - atoms/\n');+ await b.extract(['Renders vs proof'], 'hash-one');+ const [old] = await b.atoms(true);+ expect(existsSync(b.path(old!))).toBe(false);+ mkdirSync(join(b.path(old!), '..'), { recursive: true });+ const local = '# Renders vs proof\n\nA local copy kept in the db_only directory.\n';+ writeFileSync(b.path(old!), local);+ await expectUnitNotAborted(() => b.extract(['A different lesson'], 'hash-two'));+ expect({ retired: await b.atoms(false), file: existsSync(b.path(old!)) && b.file(old!) === local }).toEqual({ retired: [old!], file: true });+ });+ }, 180_000);++ test('D-11 concurrent file edit after the comparison: the editor\'s bytes survive and the page is held', async () => {+ await withBrain(databaseUrl, async b => {+ await b.extract(['Renders vs proof'], 'hash-one');+ const [old] = await b.atoms(true);+ let edited = '';+ const racing = editsBeforeUnlink(b.engine, old!, b.path, () => {+ edited = b.file(old!).replace('Renders vs proof body.', `Renders vs proof body.\n\n${LATE_EDIT}`);+ writeFileSync(b.path(old!), edited);+ });+ const phase = await expectUnitNotAborted(() => b.extract(['A different lesson'], 'hash-two', racing.engine));+ expect({ fired: racing.fired(), file: existsSync(b.path(old!)) && b.file(old!) === edited, late: edited.includes(LATE_EDIT) })+ .toEqual({ fired: true, file: true, late: true });+ expect(holdFor(phase.holds, old!).length).toBe(1);+ });+ }, 180_000);+ });+}diff --git a/test/pathological/d12-concept-stale-fences.test.ts b/test/pathological/d12-concept-stale-fences.test.tsnew file mode 100644index 0000000000..5dae30c43d--- /dev/null+++ b/test/pathological/d12-concept-stale-fences.test.ts@@ -0,0 +1,163 @@+/**+ * D-12 (GBRA-131, #6982): an unmanaged concept republication never copies a+ * stale file's fences or timeline over the database's.+ *+ * Protects: `publishClassicConcept` composes the new narrative with the+ * `## Facts` fence, timeline, tags and frontmatter the database holds, and+ * proceeds only when the concept's canonical file holds nothing the database+ * lacks (it equals the page or one of its recent page_versions rows). A+ * facts row and timeline entry the database gained after the file was+ * written survive in both copies after publication. A database-only edit no+ * page_versions row explains, and a file edit to the fence or timeline that+ * sync has not imported, defer the concept (`revision_conflict`, message+ * naming the page with `file_database_drift`) with both copies unchanged.+ * An edit landing while the database import runs is kept. Agreeing copies+ * publish, and the replaced body is kept in page_versions.+ * Fails when: the file comparison skips fences and timeline and the+ * composition takes them from the file (the pre-fix path), dropping the+ * database's newer rows.+ * Seams: `importPage` (the phase's importer callback) lands the concurrent+ * edit. PGLite always, Postgres when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { publishClassicConcept } from '../../src/core/cycle/concept-publication.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { parseFactsFence, upsertFactRow } from '../../src/core/facts-fence.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { parseMarkdown, serializeMarkdown } from '../../src/core/markdown.ts';+import { managedPersistenceEnabled } from '../../src/core/persistence/ownership.ts';+import { _resetWriteThroughCacheForTest, writePageThrough } 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 SLUG = 'concepts/launch-dates';+const NARRATIVE = 'Launch dates slip when nobody owns them.';+const SYNTHESIZED = 'SYNTHESIZED: launch dates need a single owner.';+const T1 = '- **2026-01-05** | Acme Example moved its launch.';+const T2 = '- **2026-02-09** | DB-NEWER-TIMELINE: alice-example took ownership.';+const FM = { synthesized_by: 'synthesize_concepts-v0.41', tier: 2, member_hash: 'h1', visibility: 'world' };+const fact = (claim: string) => ({ claim, kind: 'fact' as const, confidence: 0.9, visibility: 'world' as const, notability: 'medium' as const, validFrom: '2026-01-05', source: 'test' });+const withFact = (body: string, claim: string) => upsertFactRow(body, fact(claim)).body;+const BODY_V1 = withFact(NARRATIVE, 'Acme Example ships quarterly');++interface Brain {+ engine: BrainEngine;+ path: string;+ file(): string;+ page(): Promise<{ compiled_truth: string; timeline: string }>;+ importBody(body: string, timeline: string): Promise<void>;+ publish(importPage?: (markdown: string) => Promise<unknown>): Promise<string>;+ versionsHolding(marker: string): Promise<number>;+}++async function withBrain(databaseUrl: string | undefined, run: (b: Brain) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-d12-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ _resetWriteThroughCacheForTest();+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ expect(await managedPersistenceEnabled(engine)).toBe(false);+ const root = join(home, 'brain');+ mkdirSync(root, { recursive: true });+ execFileSync('git', ['init', '-q'], { cwd: root });+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [root]);+ const importBody = async (body: string, timeline: string) => {+ await importFromContent(engine, SLUG, serializeMarkdown(FM, body, timeline, { type: 'concept', title: 'launch dates', tags: ['ops'] }), { noEmbed: true });+ };+ await importBody(BODY_V1, T1);+ const written = await writePageThrough(engine, SLUG, { sourceId: 'default' });+ expect(written.written).toBe(true);+ const importPage = (markdown: string) => importFromContent(engine, SLUG, markdown, { noEmbed: true });+ await run({+ engine, path: written.path!, importBody,+ file: () => readFileSync(written.path!, 'utf8'),+ page: async () => (await engine.executeRaw<{ compiled_truth: string; timeline: string }>(+ "SELECT compiled_truth, timeline FROM pages WHERE source_id = 'default' AND slug = $1", [SLUG]))[0]!,+ publish: (hook = importPage) => publishClassicConcept(engine, SLUG, 'default', { ...FM, member_hash: 'h2' }, SYNTHESIZED, NARRATIVE,+ { writeThrough: false, importPage: hook }).then(() => 'published', (err: { code?: string; message?: string }) => `${err.code}: ${err.message}`),+ versionsHolding: async marker => Number((await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id = v.page_id+ WHERE p.source_id = 'default' AND p.slug = $1 AND (v.compiled_truth LIKE '%' || $2 || '%' OR v.timeline LIKE '%' || $2 || '%')`, [SLUG, marker]))[0]!.n),+ });+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++const claims = (text: string) => parseFactsFence(text).facts.map(f => f.claim);+const deferredForDrift = (outcome: string) => outcome.startsWith('revision_conflict: ') && outcome.includes(`${SLUG} (file_database_drift`)+ && outcome.includes('gbrain sync --source default');++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`D-12 concept republication and stale file fences/timeline (${backend})`, () => {+ test('D-12 db-newer (versioned): the database\'s newer facts row and timeline entry survive in both copies', async () => {+ await withBrain(databaseUrl, async b => {+ await b.importBody(withFact(BODY_V1, 'DB-NEWER-FACT: Acme Example ships monthly'), `${T1}\n${T2}`);+ const outcome = await expectUnitNotAborted(() => b.publish());+ const page = await b.page();+ const file = parseMarkdown(b.file(), b.path);+ expect({ outcome, db: claims(page.compiled_truth), dbTimeline: page.timeline.includes('DB-NEWER-TIMELINE'), dbNarrative: page.compiled_truth.includes(SYNTHESIZED) })+ .toEqual({ outcome: 'published', db: ['Acme Example ships quarterly', 'DB-NEWER-FACT: Acme Example ships monthly'], dbTimeline: true, dbNarrative: true });+ expect({ file: claims(file.compiled_truth), fileTimeline: file.timeline.includes('DB-NEWER-TIMELINE'), fileNarrative: file.compiled_truth.includes(SYNTHESIZED) })+ .toEqual({ file: ['Acme Example ships quarterly', 'DB-NEWER-FACT: Acme Example ships monthly'], fileTimeline: true, fileNarrative: true });+ });+ }, 180_000);++ test('D-12 db-newer (no version holds the file): the concept defers with file_database_drift and both copies stay', async () => {+ await withBrain(databaseUrl, async b => {+ const current = (await b.engine.getPage(SLUG, { sourceId: 'default' }))!;+ await b.engine.putPage(SLUG, { type: 'concept', title: current.title, compiled_truth: withFact(BODY_V1, 'DB-NEWER-FACT: Acme Example ships monthly'),+ timeline: `${T1}\n${T2}`, frontmatter: current.frontmatter }, { sourceId: 'default' } as never);+ const fileBefore = b.file();+ const pageBefore = await b.page();+ const outcome = await expectUnitNotAborted(() => b.publish());+ expect({ drift: deferredForDrift(outcome), file: b.file() === fileBefore, db: JSON.stringify(await b.page()) === JSON.stringify(pageBefore) })+ .toEqual({ drift: true, file: true, db: true });+ });+ }, 180_000);++ test('D-12 file-newer: an unimported fence and timeline edit in the file defers the concept; neither copy changes', async () => {+ await withBrain(databaseUrl, async b => {+ const edited = b.file().replace(T1, `${T1}\n- **2026-03-01** | FILE-ONLY-TIMELINE: saved in the editor.`);+ writeFileSync(b.path, edited);+ const pageBefore = await b.page();+ const outcome = await expectUnitNotAborted(() => b.publish());+ expect({ drift: deferredForDrift(outcome), file: b.file() === edited, db: JSON.stringify(await b.page()) === JSON.stringify(pageBefore) })+ .toEqual({ drift: true, file: true, db: true });+ });+ }, 180_000);++ test('D-12 concurrent fence edit while the import runs: the editor\'s bytes survive', async () => {+ await withBrain(databaseUrl, async b => {+ let edited = '';+ const outcome = await expectUnitNotAborted(() => b.publish(async markdown => {+ const result = await importFromContent(b.engine, SLUG, markdown, { noEmbed: true });+ edited = b.file().replace(T1, `${T1}\n- **2026-03-02** | CONCURRENT-TIMELINE: saved during the import.`);+ writeFileSync(b.path, edited);+ return result;+ }));+ expect({ outcome: outcome.startsWith('revision_conflict'), file: b.file() === edited, late: edited.includes('CONCURRENT-TIMELINE') })+ .toEqual({ outcome: true, file: true, late: true });+ });+ }, 180_000);++ test('D-12 agreeing copies: the concept publishes to both copies with its fence and timeline, and the old body is versioned', async () => {+ await withBrain(databaseUrl, async b => {+ const versionsBefore = await b.versionsHolding(NARRATIVE);+ const outcome = await expectUnitNotAborted(() => b.publish());+ const page = await b.page();+ const file = parseMarkdown(b.file(), b.path);+ expect({ outcome, db: claims(page.compiled_truth), file: claims(file.compiled_truth), dbT: page.timeline.trim(), fileT: file.timeline.trim(),+ narrative: page.compiled_truth.includes(SYNTHESIZED) && file.compiled_truth.includes(SYNTHESIZED) })+ .toEqual({ outcome: 'published', db: ['Acme Example ships quarterly'], file: ['Acme Example ships quarterly'], dbT: T1, fileT: T1, narrative: true });+ expect(await b.versionsHolding(NARRATIVE)).toBe(versionsBefore + 1);+ });+ }, 180_000);+ });+}diff --git a/test/pathological/d13-concept-occupied-path.test.ts b/test/pathological/d13-concept-occupied-path.test.tsnew file mode 100644index 0000000000..001b8d23e5--- /dev/null+++ b/test/pathological/d13-concept-occupied-path.test.ts@@ -0,0 +1,125 @@+/**+ * D-13 (GBRA-131, #6982): a new concept never overwrites an unindexed file+ * sitting at its path.+ *+ * Protects: on an unmanaged brain `publishClassicConcept` publishes a concept+ * with no database page only when nothing occupies its file path. A file the+ * database has never held at that path (an unindexed note) defers the+ * concept (`revision_conflict`, message naming the page with+ * `file_database_drift` and the sync fix) before anything is written: the+ * file keeps its bytes and no page is created, with+ * `cycle.synthesize_concepts.write_through` on or off, and the phase+ * reports the deferral while the run's other concepts publish. A file that+ * appears while the database import runs is kept. With the path free the+ * concept publishes to the database and, with the key on, to its file.+ * Fails when: a new concept's write binds `expectedFileBytes` to the unknown+ * file's own bytes (the pre-fix path), which overwrites it.+ * Seams: `importPage` (the phase's importer callback) lands the concurrent+ * file; the phase's `_atoms` input (deterministic narrative, no paid call).+ * PGLite always, Postgres when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { publishClassicConcept } from '../../src/core/cycle/concept-publication.ts';+import { runPhaseSynthesizeConcepts } from '../../src/core/cycle/synthesize-concepts.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { importFromContent } from '../../src/core/import-file.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 SLUG = 'concepts/flywheel';+const SYNTHESIZED = 'SYNTHESIZED: a flywheel compounds.';+const UNINDEXED = '---\ntitle: Flywheel notes\n---\n\n# Flywheel notes by alice-example\n\nNever imported.\n';+const FM = { synthesized_by: 'synthesize_concepts-v0.41', tier: 3, member_hash: 'h1', visibility: 'world' };++interface Brain {+ engine: BrainEngine;+ path(slug: string): string;+ page(slug: string): Promise<string | null>;+ publish(opts: { writeThrough: boolean; importPage?: (markdown: string) => Promise<unknown> }): Promise<string>;+}++async function withBrain(databaseUrl: string | undefined, run: (b: Brain) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-d13-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ _resetWriteThroughCacheForTest();+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ expect(await managedPersistenceEnabled(engine)).toBe(false);+ const root = join(home, 'brain');+ mkdirSync(join(root, 'concepts'), { recursive: true });+ execFileSync('git', ['init', '-q'], { cwd: root });+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [root]);+ await engine.setConfig('models.dream.synthesize', 'anthropic:claude-sonnet-4-6');+ const importPage = (markdown: string) => importFromContent(engine, SLUG, markdown, { noEmbed: true });+ await run({+ engine,+ path: slug => join(root, `${slug}.md`),+ page: async slug => (await engine.executeRaw<{ compiled_truth: string }>(+ "SELECT compiled_truth FROM pages WHERE source_id = 'default' AND slug = $1", [slug]))[0]?.compiled_truth ?? null,+ publish: opts => publishClassicConcept(engine, SLUG, 'default', FM, SYNTHESIZED, '',+ { writeThrough: opts.writeThrough, importPage: opts.importPage ?? importPage })+ .then(() => 'published', (err: { code?: string; message?: string }) => `${err.code}: ${err.message}`),+ });+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++const deferredForDrift = (outcome: string, slug = SLUG) => outcome.startsWith('revision_conflict: ') && outcome.includes(`${slug} (file_database_drift`)+ && outcome.includes('gbrain sync --source default');++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`D-13 new concept and an unindexed file at its path (${backend})`, () => {+ for (const writeThrough of [true, false]) {+ test(`D-13 occupied path, write-through key ${writeThrough ? 'on' : 'off'}: the file keeps its bytes and no page is created`, async () => {+ await withBrain(databaseUrl, async b => {+ writeFileSync(b.path(SLUG), UNINDEXED);+ const outcome = await expectUnitNotAborted(() => b.publish({ writeThrough }));+ expect({ drift: deferredForDrift(outcome), file: readFileSync(b.path(SLUG), 'utf8') === UNINDEXED, page: await b.page(SLUG) })+ .toEqual({ drift: true, file: true, page: null });+ });+ }, 180_000);+ }++ test('D-13 the phase reports the deferral and still publishes the run\'s other concept', async () => {+ await withBrain(databaseUrl, async b => {+ await b.engine.setConfig('cycle.synthesize_concepts.write_through', 'true');+ writeFileSync(b.path(SLUG), UNINDEXED);+ const atoms = ['flywheel', 'moat'].flatMap(concept => [0, 1].map(i => ({ slug: `atoms/${concept}-${i}`, title: `${concept} ${i}`, body: `b${i}`,+ concept_refs: [concept], visibility: 'world' as const })));+ const result = await expectUnitNotAborted(() => runPhaseSynthesizeConcepts(b.engine, { _atoms: atoms, sourceId: 'default' }));+ const deferred = ((result.details as { publication_deferred?: Array<{ concept: string; reason: string }> }).publication_deferred ?? []);+ expect({ status: result.status, deferred: deferred.filter(d => d.concept === 'flywheel' && deferredForDrift(d.reason)).length,+ file: readFileSync(b.path(SLUG), 'utf8') === UNINDEXED, page: await b.page(SLUG), moat: existsSync(b.path('concepts/moat')) })+ .toEqual({ status: 'warn', deferred: 1, file: true, page: null, moat: true });+ });+ }, 180_000);++ test('D-13 concurrent: a file appearing while the database import runs is kept', async () => {+ await withBrain(databaseUrl, async b => {+ const outcome = await expectUnitNotAborted(() => b.publish({ writeThrough: true, importPage: async markdown => {+ const result = await importFromContent(b.engine, SLUG, markdown, { noEmbed: true });+ writeFileSync(b.path(SLUG), UNINDEXED);+ return result;+ } }));+ expect({ outcome: outcome.startsWith('revision_conflict'), file: readFileSync(b.path(SLUG), 'utf8') === UNINDEXED }).toEqual({ outcome: true, file: true });+ });+ }, 180_000);++ test('D-13 control: with the path free the concept publishes to the database and its file', async () => {+ await withBrain(databaseUrl, async b => {+ const outcome = await expectUnitNotAborted(() => b.publish({ writeThrough: true }));+ expect({ outcome, db: (await b.page(SLUG))?.includes(SYNTHESIZED), file: existsSync(b.path(SLUG)) && readFileSync(b.path(SLUG), 'utf8').includes(SYNTHESIZED) })+ .toEqual({ outcome: 'published', db: true, file: true });+ });+ }, 180_000);+ });+}diff --git a/test/pathological/d14-brainstorm-resume-overwrite.test.ts b/test/pathological/d14-brainstorm-resume-overwrite.test.tsnew file mode 100644index 0000000000..7b6346bedd--- /dev/null+++ b/test/pathological/d14-brainstorm-resume-overwrite.test.ts@@ -0,0 +1,159 @@+/**+ * D-14 (GBRA-131, #6982): `brainstorm --save` / `lsd --save` (and a+ * `--resume` that reuses the slug) never overwrites a saved idea's file that+ * holds content the database lacks.+ *+ * Protects: `persistSavedIdea` checks the page's file before it imports+ * anything. A hand edit to a saved idea's file that sync has not imported,+ * or an unindexed file at a new idea's path, refuses the save: neither copy+ * changes, no page is created, and the message names the page with+ * `file_database_drift` and the sync fix (exit 1, nothing persisted). A file+ * edit landing after the check is kept (the file write is bound to the bytes+ * checked) and the message says so. Re-saving over an unedited file, or over+ * a file the database has since replaced (its prior body kept in+ * page_versions), writes both copies.+ * Fails when: the save imports and calls writePageThrough with no check (the+ * pre-fix path), overwriting the user's edit.+ * Seams: an engine proxy whose first transaction (the import's) lands the+ * concurrent edit. PGLite always, Postgres when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { formatSaveOutcome, persistSavedIdea } from '../../src/commands/brainstorm.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { serializeMarkdown } from '../../src/core/markdown.ts';+import { managedPersistenceEnabled } from '../../src/core/persistence/ownership.ts';+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { withEnv } from '../helpers/with-env.ts';+import { expectUnitNotAborted, pathologicalArms } from './harness.ts';++const SLUG = 'wiki/ideas/2026-10-18-lsd-why-acme-example-nonce01';+const FILE_EDIT = 'FILE-ONLY-EDIT-MARKER: notes added in the editor, not yet synced.';+const LATE_EDIT = 'CONCURRENT-EDIT-MARKER: saved while the idea was being saved.';+const idea = (text: string) => serializeMarkdown({ mode: 'lsd', question: 'why acme-example' }, `# LSD: why acme-example\n\n${text}`, '',+ { type: 'note', title: 'LSD: why acme-example', tags: [] });++interface Brain {+ engine: BrainEngine;+ path: string;+ file(): string;+ body(): Promise<string | null>;+ save(text: string, on?: BrainEngine): ReturnType<typeof persistSavedIdea>;+ versionsHolding(marker: string): Promise<number>;+}++async function withBrain(databaseUrl: string | undefined, run: (b: Brain) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-d14-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ _resetWriteThroughCacheForTest();+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ expect(await managedPersistenceEnabled(engine)).toBe(false);+ const root = join(home, 'brain');+ mkdirSync(root, { recursive: true });+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [root]);+ const path = join(root, `${SLUG}.md`);+ await run({+ engine, path,+ file: () => readFileSync(path, 'utf8'),+ body: async () => (await engine.executeRaw<{ compiled_truth: string }>(+ "SELECT compiled_truth FROM pages WHERE source_id = 'default' AND slug = $1", [SLUG]))[0]?.compiled_truth ?? null,+ save: (text, on = engine) => persistSavedIdea(on, { slug: SLUG, content: idea(text), provenanceVia: 'lsd' }),+ versionsHolding: async marker => Number((await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id = v.page_id+ WHERE p.source_id = 'default' AND p.slug = $1 AND v.compiled_truth LIKE '%' || $2 || '%'`, [SLUG, marker]))[0]!.n),+ });+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++/** The engine whose first transaction (the import's) runs `before` first. */+function editsAtFirstTransaction(engine: BrainEngine, before: () => void): { engine: BrainEngine; fired(): boolean } {+ let fired = false;+ const proxy = new Proxy(engine, {+ get(target, prop) {+ if (prop === 'transaction') return async (...args: unknown[]) => {+ if (!fired) { fired = true; 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;+ },+ });+ return { engine: proxy, fired: () => fired };+}++const refusedForDrift = (outcome: Awaited<ReturnType<typeof persistSavedIdea>>) => {+ const message = formatSaveOutcome(outcome, { profileLabel: 'lsd', slug: SLUG });+ return { exit: message.exitCode, named: message.stderr.some(l => l.includes(`${SLUG} (file_database_drift`) && l.includes('gbrain sync --source default')) };+};++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`D-14 brainstorm save and a file the database does not hold (${backend})`, () => {+ test('D-14 file-newer (resume after a hand edit): the save is refused and both copies stay', async () => {+ await withBrain(databaseUrl, async b => {+ expect((await b.save('First run ideas.')).writeThrough.written).toBe(true);+ const edited = b.file().replace('First run ideas.', `First run ideas.\n\n${FILE_EDIT}`);+ writeFileSync(b.path, edited);+ const bodyBefore = await b.body();+ const outcome = await expectUnitNotAborted(() => b.save('Resumed run ideas.'));+ expect({ file: b.file() === edited, body: (await b.body()) === bodyBefore, saved: outcome.dbSaved, ...refusedForDrift(outcome) })+ .toEqual({ file: true, body: true, saved: false, exit: 1, named: true });+ });+ }, 180_000);++ test('D-14 unindexed file at a new idea\'s path: the save is refused, the file keeps its bytes and no page is created', async () => {+ await withBrain(databaseUrl, async b => {+ mkdirSync(dirname(b.path), { recursive: true });+ const unindexed = '# Notes by alice-example\n\nNever imported.\n';+ writeFileSync(b.path, unindexed);+ const outcome = await expectUnitNotAborted(() => b.save('First run ideas.'));+ expect({ file: b.file() === unindexed, body: await b.body(), ...refusedForDrift(outcome) }).toEqual({ file: true, body: null, exit: 1, named: true });+ });+ }, 180_000);++ test('D-14 concurrent file edit after the check: the editor\'s bytes survive and the message says the file was kept', async () => {+ await withBrain(databaseUrl, async b => {+ await b.save('First run ideas.');+ let edited = '';+ const racing = editsAtFirstTransaction(b.engine, () => {+ edited = b.file().replace('First run ideas.', `First run ideas.\n\n${LATE_EDIT}`);+ writeFileSync(b.path, edited);+ });+ const outcome = await expectUnitNotAborted(() => b.save('Resumed run ideas.', racing.engine));+ const message = formatSaveOutcome(outcome, { profileLabel: 'lsd', slug: SLUG });+ expect({ fired: racing.fired(), file: b.file() === edited, late: edited.includes(LATE_EDIT), db: (await b.body())?.includes('Resumed run ideas.'),+ skipped: outcome.writeThrough.skipped, said: message.stdout?.includes('file_changed') })+ .toEqual({ fired: true, file: true, late: true, db: true, skipped: 'file_changed', said: true });+ });+ }, 180_000);++ test('D-14 db-newer: a file holding the database\'s previous body is rewritten, and the replaced database body is versioned', async () => {+ await withBrain(databaseUrl, async b => {+ await b.save('First run ideas.');+ const current = b.file();+ await importFromContent(b.engine, SLUG, current.replace('First run ideas.', 'First run ideas.\n\nDB-NEWER-MARKER: edited in the database.'), { noEmbed: true });+ const outcome = await expectUnitNotAborted(() => b.save('Resumed run ideas.'));+ expect({ written: outcome.writeThrough.written, file: b.file().includes('Resumed run ideas.'), db: (await b.body())?.includes('Resumed run ideas.') })+ .toEqual({ written: true, file: true, db: true });+ expect(await b.versionsHolding('DB-NEWER-MARKER')).toBeGreaterThan(0);+ });+ }, 180_000);++ test('D-14 control: re-saving over an unedited file writes both copies', async () => {+ await withBrain(databaseUrl, async b => {+ await b.save('First run ideas.');+ const outcome = await expectUnitNotAborted(() => b.save('Resumed run ideas.'));+ expect({ written: outcome.writeThrough.written, file: b.file().includes('Resumed run ideas.'), db: (await b.body())?.includes('Resumed run ideas.'),+ exit: formatSaveOutcome(outcome, { profileLabel: 'lsd', slug: SLUG }).exitCode })+ .toEqual({ written: true, file: true, db: true, exit: 0 });+ });+ }, 180_000);+ });+}