Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(write-through): reuse fileDatabaseDriftToken, report derived file holds, refuse brainstorm resume and DB-only takes before overwriting (#6982)

garrytan4b3102875465
diff --git a/docs/architecture/key-files/core-cycle-patterns.md b/docs/architecture/key-files/core-cycle-patterns.md
index ff5780f53b..c69a9fafe9 100644
--- a/docs/architecture/key-files/core-cycle-patterns.md
+++ b/docs/architecture/key-files/core-cycle-patterns.md
@@ -21,8 +21,8 @@ Patterns, drift reports and the cycle modules listed after them.
- `src/core/cycle/triage-rescue.ts` — THE dream triage gate (`passesTriageGate`) + the verified-segment rescue (`applyTriageRescue`). Rescue fires only for scores in `[floor, threshold)` (floor inclusive; at/above threshold is the plain gate's job) with content_type in the buried-signal allowlist (default mixed/reflection/idea/strategy/people — never routine/technical) and ≥ minSegments of the judge's own segments verifying as normalized transcript substrings (`normForGrounding`, ≥40 chars, deduped by normalized quote — repetition is not more evidence). $0 — no LLM calls; fabricated segments cannot fire it; works on cached verdicts (gate-time only). Fail-closed on every malformed shape (null score, missing/short/non-string segments), never throws. `minSegments: 0` is the kill switch (gate degenerates to the plain threshold). ONE-GATE RULE: `runTriagePass` (report construction — `worth`/`rescued`/telemetry/dry-run), the synthesize fan-out, and `dream retriage` (reconcile-queue cancels + `--audit-rejects` sampling) all read this predicate — a second hand-rolled `score >= threshold` check is how an operator sweep cancels exactly the jobs the rescue admitted. Config: `dream.triage.rescue_floor` / `rescue_min_segments` / `rescue_content_types`. Pinned by `test/cycle-triage-rescue.test.ts` + the rescue suites in `test/cycle-synthesize-triage.test.ts` / `test/dream-retriage.test.ts`. System One S7: a decide verdict (`model` starting with `DECIDE_VERDICT_PREFIX`) is gated against the S7 slot threshold (the optional fifth argument) and never enters the rescue band.
-- `src/core/cycle/derived-write-through.ts` — opt-in markdown write-through for generated pages on an unmanaged brain (#5041). `cycle.extract_atoms.write_through` / `cycle.synthesize_concepts.write_through` (off by default; `true`/`1`/`yes`/`on`) make `derivedWriteThrough` return a hook (null when off, managed or dry run): `extract_atoms` writes each item's atoms after the completion flip and removes the files of atoms it retired; `synthesize_concepts` writes through `publishClassicConcept`, which also rewrites a concept that already has a file whatever the key says. Creating the hook writes up to 200 generated pages per run that have no file yet (`source_path` NULL; pending atoms excluded), so enabling the key backfills. `writeDerivedPageThrough` keeps a page database-only when its target is ignored by git or sits in a declared `storage.db_only` directory, then calls `writePageThrough` (which honours `sync.write_through=off`) and returns its result (`written`, `skipped`, `error`) so `publishClassicConcept` can surface a failed write. Tests: `test/cycle/derived-write-through.test.ts`.
-- `src/core/cycle/concept-publication.ts` — managed `synthesize_concepts` publication: `publishManagedConcept` publishes through `publishMaintenancePage` (a concept with a recorded `source_path` republishes to its file unless a `db_only` tier covers it; new concepts are database-only), and `composeConceptRepublication` keeps an existing concept's facts/takes fences, timeline, tags and other frontmatter, holding the concept (`concept_preservation_hold`) when a fence is duplicated, unbalanced, unparseable or below the timeline sentinel. `addManagedProvenanceLinks` commits the concept-provenance edges inside a coordinated transaction. On an unmanaged brain `publishClassicConcept` writes under the page lock the fence writers take: it re-reads the page, defers (`revision_conflict`) when the narrative changed since synthesis started, another writer owns it, or the page's file holds an edit the database has not imported (narrative, frontmatter, tags, type or title; formatting is ignored), and otherwise composes the new narrative with the latest fences (from the page's file when it has one), so a take added during synthesis survives. The file write after `importPage` passes the bytes read under the lock as `expectedFileBytes`, so an edit landing during the import is kept and the concept deferred; a failed file write holds the concept (`concept_write_through_failed`) instead of reporting success (W9F item 3, `test/cycle/concept-publication-file-recheck.test.ts`). `stripFenceSections` is the shared narrative view. Tests: `test/cycle/synthesize-concepts-fences.test.ts`. The phase keeps the private-first, provenance, then promotion order; revision races are deferred and holds reported in the phase details. Tests: `test/managed-writers-w3.test.ts`. #6161: `preserveCanonicalFences` also carries curated `## Facets` / `## Merged` sections verbatim (`cycle/concept-sections.ts`; a model-written copy is dropped, and the lossless check covers them), and `synthesize-concepts.ts` groups atoms through `cycle/concept-redirects.ts` `loadConceptRedirects` (`merged_into` on any live concept page, `aliases` on phase-owned ones; one hop, two-way redirects ignored) and skips a tombstoned concept page as `skipped_deleted` instead of resurrecting it (`test/cycle/synthesize-concepts-merge.test.ts`). #5965: the same module folds spelling variants for one run: `addSpellingRedirects` groups the post-redirect stems by `spellingFoldKey` (ASCII `-`, `_` and `.` removed; Unicode kept), and a group of two or more stems redirects every stem to the one that already has a live top-level `concepts/<stem>` page (`loadLiveConceptStems`), else to the most frequent spelling (tie: the hyphenated one, then alphabetical); a group where two or more spellings already have live pages is left alone ([R28]: `re-sign` / `resign` are different concepts and only the human merge path joins them). The redirects are in-memory only (no `merged_into` write); the grouping applies `canonicalConceptStem` twice (human hop, then spelling hop), and the phase receipt lists the folds in `details.folded_spellings`. Pinned by `test/cycle-synthesize-concepts-grouping.test.ts`.
+- `src/core/cycle/derived-write-through.ts` — opt-in markdown write-through for generated pages on an unmanaged brain (#5041). `cycle.extract_atoms.write_through` / `cycle.synthesize_concepts.write_through` (off by default; `true`/`1`/`yes`/`on`) make `derivedWriteThrough` return a hook (null when off, managed or dry run): `extract_atoms` writes each item's atoms after the completion flip and removes the files of atoms it retired; `synthesize_concepts` writes through `publishClassicConcept`, which also rewrites a concept that already has a file whatever the key says. Creating the hook writes up to 200 generated pages per run that have no file yet (`source_path` NULL; pending atoms excluded), so enabling the key backfills. `writeDerivedPageThrough` keeps a page database-only when its target is ignored by git or sits in a declared `storage.db_only` directory (`derivedFileTarget`), replaces an existing file only when `replaceableFile` (`facts/file-body-guard.ts`) finds it equal to the page or one of its recent page_versions rows, then calls `writePageThrough` bound to the bytes compared and returns its result (`written`, `skipped`, `error`) so `publishClassicConcept` can surface a failed write. A retired atom's file is removed under the same filter and comparison, the unlink rechecking the bytes under the source filesystem lock. A file holding an edit the database lacks (or an unindexed file at a backfilled page's path) is left as it is and listed in the hook's `held`, which both phases report as `details.file_holds` (`file_database_drift`) with a `warn` status. Tests: `test/cycle/derived-write-through.test.ts`, `test/pathological/d10-derived-atom-file-overwrite.test.ts`, `test/pathological/d11-derived-retired-atom-unlink.test.ts`.
+- `src/core/cycle/concept-publication.ts` — managed `synthesize_concepts` publication: `publishManagedConcept` publishes through `publishMaintenancePage` (a concept with a recorded `source_path` republishes to its file unless a `db_only` tier covers it; new concepts are database-only), and `composeConceptRepublication` keeps an existing concept's facts/takes fences, timeline, tags and other frontmatter, holding the concept (`concept_preservation_hold`) when a fence is duplicated, unbalanced, unparseable or below the timeline sentinel. `addManagedProvenanceLinks` commits the concept-provenance edges inside a coordinated transaction. On an unmanaged brain `publishClassicConcept` writes under the page lock the fence writers take: it re-reads the page, defers (`revision_conflict`) when the narrative changed since synthesis started, another writer owns it, or the page's canonical file holds anything the database lacks (`replaceableFile`: body, fences, timeline, frontmatter, tags, type or title equal to neither the page nor a recent page_versions row; formatting is ignored; this also covers an unindexed file at a new concept's path, and the message names the page with `file_database_drift`), and otherwise composes the new narrative with the database's latest fences, timeline, tags and frontmatter, so a take added during synthesis survives (`test/pathological/d12-concept-stale-fences.test.ts`, `d13-concept-occupied-path.test.ts`). The file write after `importPage` passes the bytes read under the lock as `expectedFileBytes`, so an edit landing during the import is kept and the concept deferred; a failed file write holds the concept (`concept_write_through_failed`) instead of reporting success (W9F item 3, `test/cycle/concept-publication-file-recheck.test.ts`). `stripFenceSections` is the shared narrative view. Tests: `test/cycle/synthesize-concepts-fences.test.ts`. The phase keeps the private-first, provenance, then promotion order; revision races are deferred and holds reported in the phase details. Tests: `test/managed-writers-w3.test.ts`. #6161: `preserveCanonicalFences` also carries curated `## Facets` / `## Merged` sections verbatim (`cycle/concept-sections.ts`; a model-written copy is dropped, and the lossless check covers them), and `synthesize-concepts.ts` groups atoms through `cycle/concept-redirects.ts` `loadConceptRedirects` (`merged_into` on any live concept page, `aliases` on phase-owned ones; one hop, two-way redirects ignored) and skips a tombstoned concept page as `skipped_deleted` instead of resurrecting it (`test/cycle/synthesize-concepts-merge.test.ts`). #5965: the same module folds spelling variants for one run: `addSpellingRedirects` groups the post-redirect stems by `spellingFoldKey` (ASCII `-`, `_` and `.` removed; Unicode kept), and a group of two or more stems redirects every stem to the one that already has a live top-level `concepts/<stem>` page (`loadLiveConceptStems`), else to the most frequent spelling (tie: the hyphenated one, then alphabetical); a group where two or more spellings already have live pages is left alone ([R28]: `re-sign` / `resign` are different concepts and only the human merge path joins them). The redirects are in-memory only (no `merged_into` write); the grouping applies `canonicalConceptStem` twice (human hop, then spelling hop), and the phase receipt lists the folds in `details.folded_spellings`. Pinned by `test/cycle-synthesize-concepts-grouping.test.ts`.
- `src/core/cycle/connector-atoms.ts` — the connector atom setting (#5856). `CONNECTOR_ATOM_PAGES_KEY` (`cycle.extract_atoms.connector_pages`, on when unset; `connectorAtomPagesEnabled` treats only false/0/off/no as opted out) gates `CONNECTOR_ATOM_PAGE_TYPES` (`email`, `meeting`) of sources whose `config.kind` is a connector kind (`CONNECTOR_SOURCE_KINDS`). `connectorAtomExclusionSql` returns the `pages p` predicate atom discovery and the backlog count append (empty unless opted out), so the routine cycle, `dream --drain` and autopilot auto-drain extract connector mail and calendar pages under the auto-drain budget until the user opts out. Other page types of a connector source and every checkout-backed page are unaffected. Tests: `test/connector-atom-pages.test.ts`, `test/autopilot-auto-drain-dispatch.test.ts`, and the `atom_drain_default_on` / `atom_drain_opted_out` cases of `test/helpers/managed-connector-job-contract.ts`, run by `test/managed-connector-job-contract.test.ts` and its Postgres twin `test/e2e/managed-connector-job-contract.test.ts`.
diff --git a/docs/architecture/key-files/hindsight.md b/docs/architecture/key-files/hindsight.md
index 4dd0b2cc5a..f35b7113fc 100644
--- a/docs/architecture/key-files/hindsight.md
+++ b/docs/architecture/key-files/hindsight.md
@@ -35,7 +35,7 @@ unresolvable+true|false, pre-v80 NULL/NULL rows survive).
- `src/commands/calibration.ts` — CLI: `gbrain calibration` (read + print), `--regenerate`, `--undo-wave <ver>`, `ab-report`. MCP op `get_calibration_profile` (scope: read) backs the same data path. Source-scoped via `sourceScopeOpts(ctx)`.
- `src/core/owner-holder.ts` — single source of truth for "the brain owner" holder string. `DEFAULT_OWNER_HOLDER = 'self'` (matches the consolidate facts→takes writer + `docs/takes-vs-facts.md`); `resolveOwnerHolder({override, configValue})` returns override > `emotional_weight.user_holder` config > `'self'`. Consumed by the calibration_profile cycle phase, `gbrain calibration` CLI, the `get_calibration_profile` op, `think`'s calibration block, `emotional-weight`'s `DEFAULT_USER_HOLDER`, and doctor's `calibration_freshness`. Pure; unit-tested in `test/owner-holder.test.ts`. Does NOT unify owner-identity fragmentation (`self`/`brain`/`people-<owner>`) — tracked separately.
- `src/commands/takes.ts` — the full `gbrain takes` subcommand dispatcher (list/search/embed/add/update/supersede/resolve/propose/scorecard/calibration/extract/revisit). `takes list --limit N --offset N` validates integers at the CLI; the engine clamps limit (default 100, cap 500) and floors offset at 0. `takes revisit <slug>` opens $EDITOR on the source page with a `<!-- gbrain:revisit -->` cursor marker. #5167: `takes remove <slug> --row N` goes through `takes-mutation.ts` to the local-only `takes_remove` op (persistence `takes-prepare.ts`): the row leaves the takes table and its fence row becomes a reservation row (`| N | ~~(removed)~~ | take | world | 0.0 | | removed |`, W9F item 4) in one coordinated publication, other row numbers stay, and a resolved row, a row another row cites as "superseded by" it, or a row whose DB claim disagrees with the fence is refused (the last names `takes rebuild`); thin clients are refused. Reservations: `parseTakesFence` returns them in `reservedRowNums`, never in `takes`, so no reader or projection sees a take there; `renderTakesFence(takes, reservedRowNums)` puts them back in row order, and `upsertTakeRow`, `supersedeRow` and `takesPreparation.replaceFence` keep the reservations of the body they rewrite. Every new take row number comes from GBRA-54's `nextFreeRowNum` (`fence-repair/normalize.ts`): one more than every fence row on the page (facts and takes, live, struck and reserved) and, in `takes-prepare.ts`, every stored facts/takes row (`storedFenceRows`), revalidated under the publication lock; the promise holds while the reservation row exists. #6450: `takes_add` and an explicit `takes_supersede` holder override are trimmed and checked with `isValidHolder` at the write boundary (syntax before authority: `invalid_params` naming the grammar, before `assertHolderAllowed`); the inherited supersede holder is not re-validated (the existing fence already round-tripped). Every prepared takes fence is parsed again before publication and refused `invalid_params` on any warning, so no write can leave a fence the next write would refuse. Test: `test/takes-holder-validation-6450.test.ts`. `test/takes-row-reservation.test.ts` (both engines), `test/takes-reservation-callers.test.ts` (census of `parseTakesFence` callers). `takes rebuild <slug> [--source-id]` runs the local-only `takes_rebuild` op (W9F item 8; `runTakesRebuild` in `takes-mutation.ts`, delegated to a resident `gbrain serve` owner over persistence IPC, else the local engine, with the same JSON, warnings and exit 1 on a missing page or a warning), which calls `extractTakes({source:"db", slugs:[slug], sourceId, rebuild:true})`, whose rebuild now deletes only indexed rows whose (row_num, claim) left the fence, so matching rows keep resolutions and vectors. The v0_28_0 hint names `gbrain reindex --markdown` instead of the nonexistent `extract takes --rebuild`. GBRA-130 A-25: `takes propose --failed [--source <id>] [--json]` lists pages propose_takes held with a failure tombstone (`listFailedProposals`); `takes propose --retry-failed [--slug <slug>] [--source <id>] [--json]` deletes their tombstones and ledger records (`retryFailedProposals`) so the next run re-extracts them.
-- `src/core/extract-takes-from-pages.ts` — bootstrap extraction selects uncovered pages newest first. Managed pages capture their revision before classification and publish the complete appended takes fence through coordinated `put_page`, whose canonical projection commits the takes rows with the page; conflicts skip that page. Unmanaged pages retain the md-first writer. Pinned by `test/persistence-managed-takes-extract.test.ts` and `test/extract-takes-md-first.test.ts`. `takes extract --before <updated_at>,<id>` (CLI-only) continues strictly below a prior run's `next_before`, an `(updated_at, id)` keyset with exact timestamptz text, so zero-claim pages no longer starve older ones; a budget stop resumes at the first unclassified page, a failed page stays uncovered for the next run without `--before`, and a malformed cursor is an exit-2 `invalid_params` refusal before any page is read. Pinned by `test/extract-takes-from-pages-progression.test.ts`, `test/takes-extract-json.test.ts` and `test/e2e/takes-extract-cursor-postgres.test.ts`.
+- `src/core/extract-takes-from-pages.ts` — bootstrap extraction selects uncovered pages newest first. Managed pages capture their revision before classification and publish the complete appended takes fence through coordinated `put_page`, whose canonical projection commits the takes rows with the page; conflicts skip that page. Unmanaged pages take the same database path when the database is their copy of record (`sync.write_through` off, or the page in a declared `storage.db_only` directory; an unbound Postgres source skips that page `owner_unavailable`); other unmanaged pages retain the md-first writer and still skip a missing file as `mirror_unavailable`. Pinned by `test/persistence-managed-takes-extract.test.ts`, `test/extract-takes-md-first.test.ts` and `test/pathological/d19-takes-bootstrap-db-only.test.ts`. `takes extract --before <updated_at>,<id>` (CLI-only) continues strictly below a prior run's `next_before`, an `(updated_at, id)` keyset with exact timestamptz text, so zero-claim pages no longer starve older ones; a budget stop resumes at the first unclassified page, a failed page stays uncovered for the next run without `--before`, and a malformed cursor is an exit-2 `invalid_params` refusal before any page is read. Pinned by `test/extract-takes-from-pages-progression.test.ts`, `test/takes-extract-json.test.ts` and `test/e2e/takes-extract-cursor-postgres.test.ts`.
- `src/core/take-proposals.ts` — owns the `take_proposals` queue's row contract. `normalizeTakeProposalRow` coerces Postgres driver BigInt/string values (`id`, `weight`, `promoted_row_num`) to numbers at the query boundary so both engines return the same numeric row shape. `acceptProposal` promotes through a coordinated `takes_add` mutation (`submitPageMutation`, the same path `gbrain takes add` uses), so accept works on a managed brain where a direct fence write is refused with `writer_coordinator_required` (`test/takes-propose-accept-managed.test.ts`). #5214: an accepted proposal's take records `take_proposals#<id>` as its source; `acceptProposal(target, id, edits)` (`takes propose --accept <id> --claim/--weight/--who/--kind`) applies the edits as a plain takes_add with source `take_proposals#<id> (edited)` while the queue row keeps the original claim text.
- `admin/src/pages/Calibration.tsx` — Calibration tab. Single-column layout. `<TrustedSVG>` wrapper handles `dangerouslySetInnerHTML` for the server-rendered SVG.
- `admin/src/index.css` — `--text-muted: #777` (WCAG AA contrast bump to ~5.5 on the #0a0a0f bg).
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index b72530641c..1233f44a72 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -107,7 +107,6 @@ src/core/cycle/chronicle.ts discover sql STREAM
src/core/cycle/concept-publication.ts composeConceptRepublication call:serializeMarkdown INLINE
src/core/cycle/concept-publication.ts composeConceptRepublication field INLINE
src/core/cycle/concept-publication.ts conceptPreservationHold field INLINE
-src/core/cycle/concept-publication.ts fileHoldsPage field INLINE
src/core/cycle/concept-publication.ts preserveCanonicalFences call:serializeMarkdown INLINE after assertInlineBody
src/core/cycle/concept-publication.ts preserveCanonicalFences field INLINE assertInlineBody: refuses a segmented page (concept pages inline; enrich/connector callers SEGW)
src/core/cycle/concept-publication.ts publishClassicConcept call:serializeMarkdown INLINE
diff --git a/src/commands/brainstorm.ts b/src/commands/brainstorm.ts
index f42e42ccc9..bb1cf62500 100644
--- a/src/commands/brainstorm.ts
+++ b/src/commands/brainstorm.ts
@@ -24,10 +24,10 @@ import {
} from '../core/brainstorm/orchestrator.ts';
import { loadConfig } from '../core/config.ts';
import { StructuredAgentError } from '../core/errors.ts';
-import { parseMarkdown, serializeMarkdown } from '../core/markdown.ts';
+import { serializeMarkdown } from '../core/markdown.ts';
import { importFromContent } from '../core/import-file.ts';
import { isWriteThroughDisabled, resolvePageWriteTarget, writePageThrough, type WriteThroughResult } from '../core/write-through.ts';
-import { fileDatabaseDriftHold, replaceableFile } from '../core/facts/file-body-guard.ts';
+import { fileDatabaseDriftToken, 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';
@@ -338,7 +338,7 @@ async function runBrainstormCli(
// the saved file round-trips through `gbrain sync` byte-for-byte. Include
// filtered ideas (onlyPassed:false) so a judge-failed run still shows every
// idea; `--resume <run_id>` re-scores and overwrites this same page.
- const fmObj = buildBrainstormFrontmatterObject(result);
+ const fmObj = { ...buildBrainstormFrontmatterObject(result), source_kind: profile.label };
const body = formatBrainstormMarkdown(result, { onlyPassed: false, includeMeta: true });
const content = serializeMarkdown(fmObj, body, '', { type: 'note', title, tags: [] });
@@ -377,9 +377,9 @@ 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 (`source_kind` is part of
- * the imported frontmatter). 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 (the CLI puts `source_kind`
+ * in the content's frontmatter, so the row and the rendered file agree). 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
@@ -398,13 +398,10 @@ export async function persistSavedIdea(
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 } };
+ return { dbSaved: false, held: fileDatabaseDriftToken(args.slug, sourceId, 'before', '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, {
+ await importFromContent(engine, args.slug, args.content, {
noEmbed: true,
sourceId,
sourcePath: `${args.slug}.md`,
@@ -414,7 +411,11 @@ export async function persistSavedIdea(
dbError = err instanceof Error ? err.message : String(err);
}
const writeThrough: WriteThroughResult = dbSaved
- ? await writePageThrough(engine, args.slug, { sourceId, expectedFileBytes })
+ ? await writePageThrough(engine, args.slug, {
+ sourceId,
+ frontmatterOverrides: { source_kind: args.provenanceVia },
+ expectedFileBytes,
+ })
: { written: false, skipped: 'page_not_found_after_write' };
return { dbSaved, dbError, writeThrough };
}
diff --git a/src/core/cycle/concept-publication.ts b/src/core/cycle/concept-publication.ts
index 42d342fd38..57ae35eae5 100644
--- a/src/core/cycle/concept-publication.ts
+++ b/src/core/cycle/concept-publication.ts
@@ -19,7 +19,7 @@ import { withCoordinatedWrite } from '../persistence/context.ts';
import { maintenanceAttribution } from '../persistence/attribution.ts';
import { acquirePageLock } from '../page-lock.ts';
import { derivedFileTarget, writeDerivedPageThrough } from './derived-write-through.ts';
-import { fileDatabaseDriftHold, replaceableFile } from '../facts/file-body-guard.ts';
+import { fileDatabaseDriftToken, 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). */
@@ -208,7 +208,7 @@ export async function publishClassicConcept(engine: BrainEngine, slug: string, s
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' });
+ throw Object.assign(new Error(fileDatabaseDriftToken(slug, sourceId, 'before', 'the concept was not published')), { code: 'revision_conflict' });
}
const markdown = page
? composeConceptRepublication(page, snapshot!.tags, synthesized, narrative)
diff --git a/src/core/cycle/derived-write-through.ts b/src/core/cycle/derived-write-through.ts
index 1187b627b1..d28bd64565 100644
--- a/src/core/cycle/derived-write-through.ts
+++ b/src/core/cycle/derived-write-through.ts
@@ -23,10 +23,11 @@
import { execFileSync } from '../spawn.ts';
import { relative } from 'node:path';
import type { BrainEngine } from '../engine.ts';
+import type { PhaseResult } from '../cycle.ts';
import { isDbOnly, loadStorageConfig } from '../storage-config.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';
+import { fileDatabaseDriftToken, replaceableFile } from '../facts/file-body-guard.ts';
export const DERIVED_WRITE_THROUGH_KEYS = {
extract_atoms: 'cycle.extract_atoms.write_through',
@@ -108,6 +109,13 @@ async function deleteDerivedPageThrough(engine: BrainEngine, slug: string, sourc
return deletePageThrough(engine, slug, { sourceId, target: resolved.target, expectedFileBytes: file.expectedFileBytes });
}
+/** `result` with the hook's held pages reported: `details.file_holds`, a `warn` status and a summary note. */
+export function reportFileHolds(result: PhaseResult, held: readonly string[] | undefined, noun: string): PhaseResult {
+ if (!held?.length) return result;
+ return { ...result, status: result.status === 'fail' ? 'fail' : 'warn', details: { ...result.details, file_holds: [...held] },
+ summary: `${result.summary} (${held.length} ${noun} file(s) left as they are: file_database_drift)` };
+}
+
/** 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>;
@@ -132,12 +140,12 @@ export async function derivedWriteThrough(
const write = async (slugs: readonly string[], retired: readonly string[] = []) => {
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'));
+ held.push(fileDatabaseDriftToken(slug, sourceId, 'before', 'the generated page was not written to its file'));
}
}
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'));
+ held.push(fileDatabaseDriftToken(slug, sourceId, 'before', 'the retired page\'s file was not removed'));
}
}
};
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index 84b896aa65..130fb4ac66 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -67,7 +67,7 @@ import type { ProgressReporter } from '../progress.ts';
import { chat as gatewayChat, withBudgetTracker, isAvailable } from '../ai/gateway.ts';
import { createGlobalLlmHaltTracker, haltedClassOf, providerContentBlockReason, type GlobalLlmErrorClass } from '../ai/errors.ts';
import { importFromContent } from '../import-file.ts';
-import { derivedWriteThrough } from './derived-write-through.ts';
+import { derivedWriteThrough, reportFileHolds } from './derived-write-through.ts';
import { serializeMarkdown } from '../markdown.ts';
import { DEFAULT_EXTRACT_MAX_INPUT_CHARS, extractAtomsInput, inputTruncatedLine, recordPartialDisposition, releasePartialDispositions, resolveExtractAtomsInputCap, stampTranscriptTombstone, type ExtractAtomsInput, type ExtractAtomsItem } from './extract-atoms-input.ts';
import { commitExtractionPlan, readPageWatermark } from '../extraction-watermark.ts';
@@ -862,16 +862,13 @@ 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 {
+ return reportFileHolds({
phase: 'extract_atoms',
- status: held.length > 0 ? 'warn' : 'skipped',
+ status: 'skipped',
duration_ms: 0,
- summary: 'extract_atoms: no transcripts or pages to process'
- + (held.length > 0 ? ` (${held.length} atom file(s) left as they are: file_database_drift)` : ''),
+ summary: 'extract_atoms: no transcripts or pages to process',
details: {
reason: 'no_work',
- ...(held.length > 0 ? { file_holds: held } : {}),
source_id: sourceId,
atoms_extracted: 0,
transcripts_processed: 0,
@@ -885,7 +882,7 @@ export async function runPhaseExtractAtoms(
budget_usd: DEFAULT_BUDGET_USD,
dry_run: opts.dryRun ?? false,
},
- };
+ }, atomFiles?.held, 'atom');
}
// 4. Per work-item: extract atoms via the configured extract_atoms model
@@ -1411,13 +1408,13 @@ export async function runPhaseExtractAtoms(
});
}
- return {
+ return reportFileHolds({
phase: 'extract_atoms',
// A phase that skipped every work item and produced nothing did not
// 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 || (atomFiles?.held.length ?? 0) > 0 ||
+ failures.length > 0 ||
(work.length > 0 &&
totalAtomsExtracted === 0 &&
transcriptsSkipped + pagesSkipped === work.length)
@@ -1432,11 +1429,9 @@ export async function runPhaseExtractAtoms(
(transcriptsSkipped + pagesSkipped > 0
? ` (${transcriptsSkipped + pagesSkipped} budget-skipped)`
: '') +
- (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)` : ''),
+ (inputTruncated > 0 ? ` (${inputTruncated} input-truncated: the model did not read the tail)` : ''),
details: {
atoms_extracted: totalAtomsExtracted,
- ...((atomFiles?.held.length ?? 0) > 0 ? { file_holds: atomFiles!.held } : {}),
transcripts_processed: transcriptsProcessed,
transcripts_total: transcripts.length,
transcripts_skipped_budget: transcriptsSkipped,
@@ -1460,7 +1455,7 @@ export async function runPhaseExtractAtoms(
source_id: sourceId,
dry_run: opts.dryRun ?? false,
},
- };
+ }, atomFiles?.held, 'atom');
}
/**
diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.ts
index ea3b15d258..dc38104dd8 100644
--- a/src/core/cycle/synthesize-concepts.ts
+++ b/src/core/cycle/synthesize-concepts.ts
@@ -42,7 +42,7 @@ import { slugifySegment } from '../sync.ts';
import { validatePageSlug } from '../ops/context.ts';
import { privatePagesFilterFragment, strictestVisibility, type Visibility } from '../search/private-visibility.ts';
import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';
-import { derivedWriteThrough } from './derived-write-through.ts';
+import { derivedWriteThrough, reportFileHolds } from './derived-write-through.ts';
import { addSpellingRedirects, canonicalConceptStem, loadConceptRedirects, loadLiveConceptStems } from './concept-redirects.ts';
import {
addManagedProvenanceLinks, CONCEPT_DEFERRAL_CODES, CONCEPT_HOLD_CODES, publishClassicConcept, publishManagedConcept, stripFenceSections,
@@ -617,10 +617,9 @@ export async function runPhaseSynthesizeConcepts(
});
}
- return {
+ return reportFileHolds({
phase: 'synthesize_concepts',
- status: failures.length > 0 || linkWarnings.length > 0 || publicationDeferred.length > 0 || publicationHeld.length > 0 || skippedFileDrift.length > 0
- || (conceptFiles?.held.length ?? 0) > 0 ? 'warn' : 'ok',
+ status: failures.length > 0 || linkWarnings.length > 0 || publicationDeferred.length > 0 || publicationHeld.length > 0 || skippedFileDrift.length > 0 ? 'warn' : 'ok',
duration_ms: 0,
summary:
`synthesize_concepts: ${conceptsWritten} concepts ` +
@@ -635,8 +634,7 @@ 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('; ')})` : '') +
- ((conceptFiles?.held.length ?? 0) > 0 ? ` (${conceptFiles!.held.length} concept file(s) left as they are: file_database_drift)` : ''),
+ (skippedFileDrift.length > 0 ? ` (${skippedFileDrift.length} skipped before synthesis: canonical file differs from the database; ${driftActions.join('; ')})` : ''),
details: {
concepts_written: conceptsWritten,
tier_counts: tierCounts,
@@ -657,14 +655,13 @@ 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,
pricing_fallback_models: [...pricingFallbackModels],
dry_run: opts.dryRun ?? false,
},
- };
+ }, conceptFiles?.held, 'concept');
}
/**
diff --git a/src/core/extract-takes-from-pages.ts b/src/core/extract-takes-from-pages.ts
index c51be5b4b0..7ba7859169 100644
--- a/src/core/extract-takes-from-pages.ts
+++ b/src/core/extract-takes-from-pages.ts
@@ -419,7 +419,8 @@ export async function extractTakesFromPages(
}
} catch (err) {
const code = (err as { code?: string; writeError?: string })?.code ?? (err as { writeError?: string })?.writeError;
- if (fromDatabase && (code === 'revision_conflict' || code === 'page_identity_changed' || code === 'source_changed')) {
+ if (fromDatabase && (code === 'revision_conflict' || code === 'page_identity_changed' || code === 'source_changed'
+ || (!managedJournalWrites && code === 'owner_unavailable'))) {
skipPage(page.slug, code);
continue;
}
diff --git a/src/core/facts/file-body-guard.ts b/src/core/facts/file-body-guard.ts
index 66225e13a9..8073e12f77 100644
--- a/src/core/facts/file-body-guard.ts
+++ b/src/core/facts/file-body-guard.ts
@@ -91,7 +91,8 @@ function fileHeldBy(fileBytes: string, slug: string, state: StoredState): boolea
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]) => stableJson(value) === stableJson(stored.frontmatter[key]));
+ return Object.entries(file.frontmatter).every(([key, value]) =>
+ stored.frontmatter[key] !== undefined && stableJson(value) === stableJson(stored.frontmatter[key]));
}
/**
@@ -118,13 +119,3 @@ export async function replaceableFile(engine: BrainEngine, sourceId: string, slu
[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/test/pathological/d14-brainstorm-resume-overwrite.test.ts b/test/pathological/d14-brainstorm-resume-overwrite.test.ts
index 7b6346bedd..f1da48a34f 100644
--- a/test/pathological/d14-brainstorm-resume-overwrite.test.ts
+++ b/test/pathological/d14-brainstorm-resume-overwrite.test.ts
@@ -14,6 +14,7 @@
* 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.
+ * The content carries `source_kind` in its frontmatter as the CLI writes it.
* Seams: an engine proxy whose first transaction (the import's) lands the
* concurrent edit. PGLite always, Postgres when DATABASE_URL is set.
*/
@@ -34,7 +35,7 @@ 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}`, '',
+const idea = (text: string) => serializeMarkdown({ mode: 'lsd', question: 'why acme-example', source_kind: 'lsd' }, `# LSD: why acme-example\n\n${text}`, '',
{ type: 'note', title: 'LSD: why acme-example', tags: [] });
interface Brain {
diff --git a/test/pathological/d18-think-take-db-only.test.ts b/test/pathological/d18-think-take-db-only.test.ts
new file mode 100644
index 0000000000..c8a40376e3
--- /dev/null
+++ b/test/pathological/d18-think-take-db-only.test.ts
@@ -0,0 +1,168 @@
+/**
+ * D-18 (GBRA-131, #6982): `think --take --anchor` never creates a takes-only
+ * file for a database-only page, or appends to a file that differs from the
+ * database.
+ *
+ * Protects: `persistTakeFromSynthesis` publishes the take through the
+ * coordinated `takes_add` mutation, which composes the fence from the page's
+ * database snapshot. With `sync.write_through` off, or for a page in a
+ * declared `storage.db_only` directory, the take lands in the page's
+ * database body after its existing text and no file is created. With
+ * write-through on, a page whose file is missing, or whose file and database
+ * body differ (a newer database edit, or an unimported file edit), is
+ * refused with `TAKE_WRITE_FAILED: source_changed` and neither copy changes.
+ * Agreeing copies get the take in both. On Postgres a classic brain's source
+ * with no canonical owner refuses the take (`owner_unavailable`) and writes
+ * nothing; there the other cases bind the source first (`claimWorktree`, the
+ * claim PGLite makes automatically on its first coordinated write, so the
+ * PGLite arm starts unclaimed).
+ * Fails when: the take goes through the legacy md-first addTakeToPage (the
+ * pre-fix path), which reads a missing file as an empty body and writes a
+ * takes-only file the next sync imports over the page, or appends to a stale
+ * file.
+ * Seams: none. A concurrent edit after the comparison is the coordinator's
+ * own admission recheck (covered by its tests), not this caller's.
+ * PGLite always, Postgres when DATABASE_URL is set.
+ */
+import { describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { serializePageToMarkdown } from '../../src/core/markdown.ts';
+import { claimWorktree, managedPersistenceEnabled } from '../../src/core/persistence/ownership.ts';
+import { parseTakesFence } from '../../src/core/takes-fence.ts';
+import { persistTakeFromSynthesis } from '../../src/core/think/persist-take.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 ALICE = 'people/alice-example';
+const BODY = '# Alice Example\n\nDB-BODY-MARKER: Alice Example works at Acme Example.';
+const ANSWER = { answer: '- Alice Example is the strongest operator at Acme Example.\n\nDetail.', synthesisOk: true };
+const CLAIM = 'Alice Example is the strongest operator at Acme Example.';
+
+interface Brain {
+ engine: BrainEngine;
+ root: string;
+ path: string;
+ file(): string | null;
+ body(): Promise<string>;
+ takes(): Promise<string[]>;
+ take(): ReturnType<typeof persistTakeFromSynthesis>;
+}
+
+async function withBrain(databaseUrl: string | undefined, run: (b: Brain) => Promise<void>, opts: { bound?: boolean } = {}): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-d18-'));
+ 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]);
+ await engine.setConfig('sync.repo_path', root);
+ if (opts.bound ?? databaseUrl !== undefined) await claimWorktree(engine, 'default', root);
+ await engine.putPage(ALICE, { type: 'person', title: 'Alice Example', compiled_truth: BODY });
+ const path = join(root, `${ALICE}.md`);
+ await run({
+ engine, root, path,
+ file: () => existsSync(path) ? readFileSync(path, 'utf8') : null,
+ body: async () => (await engine.executeRaw<{ compiled_truth: string }>(
+ "SELECT compiled_truth FROM pages WHERE source_id = 'default' AND slug = $1", [ALICE]))[0]!.compiled_truth,
+ takes: async () => (await engine.executeRaw<{ claim: string }>(
+ "SELECT t.claim FROM takes t JOIN pages p ON p.id = t.page_id WHERE p.source_id = 'default' AND p.slug = $1 ORDER BY t.row_num", [ALICE])).map(r => r.claim),
+ take: () => persistTakeFromSynthesis(engine, ANSWER, { anchor: ALICE, sourceId: 'default' }),
+ });
+ } finally { await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+async function fileFromDatabase(b: Brain): Promise<string> {
+ await b.engine.executeRaw("UPDATE pages SET source_path = $1 WHERE source_id = 'default' AND slug = $2", [`${ALICE}.md`, ALICE]);
+ const snapshot = (await b.engine.readPageSnapshot(ALICE, { sourceId: 'default' }))!;
+ const bytes = serializePageToMarkdown(snapshot.page, snapshot.tags);
+ mkdirSync(dirname(b.path), { recursive: true });
+ writeFileSync(b.path, bytes);
+ return bytes;
+}
+
+const fenceClaims = (text: string) => parseTakesFence(text).takes.map(t => t.claim);
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`D-18 think --take on a database-only or drifted page (${backend})`, () => {
+ test('D-18 write-through off: the take lands in the database body after its text and no file is created', async () => {
+ await withBrain(databaseUrl, async b => {
+ await b.engine.setConfig('sync.write_through', 'false');
+ _resetWriteThroughCacheForTest();
+ const r = await expectUnitNotAborted(() => b.take());
+ const body = await b.body();
+ expect({ row: r.take_row, warnings: r.warnings, file: b.file(), kept: body.startsWith(BODY), fence: fenceClaims(body), takes: await b.takes() })
+ .toEqual({ row: 1, warnings: [], file: null, kept: true, fence: [CLAIM], takes: [CLAIM] });
+ });
+ }, 180_000);
+
+ test('D-18 storage.db_only page: the take lands in the database body and no file is created', async () => {
+ await withBrain(databaseUrl, async b => {
+ writeFileSync(join(b.root, 'gbrain.yml'), 'storage:\n db_only:\n - people/\n');
+ const r = await expectUnitNotAborted(() => b.take());
+ const body = await b.body();
+ expect({ row: r.take_row, file: b.file(), kept: body.startsWith(BODY), fence: fenceClaims(body), takes: await b.takes() })
+ .toEqual({ row: 1, file: null, kept: true, fence: [CLAIM], takes: [CLAIM] });
+ });
+ }, 180_000);
+
+ test('D-18 write-through on, page with no file: refused, no takes-only file is created and the body is unchanged', async () => {
+ await withBrain(databaseUrl, async b => {
+ const r = await expectUnitNotAborted(() => b.take());
+ expect({ row: r.take_row, refused: r.warnings.some(w => w.startsWith('TAKE_WRITE_FAILED: source_changed')), file: b.file(), body: await b.body(), takes: await b.takes() })
+ .toEqual({ row: null, refused: true, file: null, body: BODY, takes: [] });
+ });
+ }, 180_000);
+
+ test('D-18 db-newer: a stale file is not appended to; refused and both copies stay', async () => {
+ await withBrain(databaseUrl, async b => {
+ const stale = await fileFromDatabase(b);
+ await b.engine.putPage(ALICE, { type: 'person', title: 'Alice Example', compiled_truth: `${BODY}\n\nDB-NEWER-MARKER: edited with write-through off.` });
+ const bodyBefore = await b.body();
+ const r = await expectUnitNotAborted(() => b.take());
+ expect({ row: r.take_row, refused: r.warnings.some(w => w.startsWith('TAKE_WRITE_FAILED: source_changed')), file: b.file() === stale, body: (await b.body()) === bodyBefore, takes: await b.takes() })
+ .toEqual({ row: null, refused: true, file: true, body: true, takes: [] });
+ });
+ }, 180_000);
+
+ test('D-18 file-newer: an unimported file edit is refused and both copies stay', async () => {
+ await withBrain(databaseUrl, async b => {
+ const edited = (await fileFromDatabase(b)).replace('works at Acme Example.', 'works at Acme Example.\n\nFILE-ONLY-EDIT-MARKER.');
+ writeFileSync(b.path, edited);
+ const r = await expectUnitNotAborted(() => b.take());
+ expect({ row: r.take_row, refused: r.warnings.some(w => w.startsWith('TAKE_WRITE_FAILED: source_changed')), file: b.file() === edited, body: await b.body(), takes: await b.takes() })
+ .toEqual({ row: null, refused: true, file: true, body: BODY, takes: [] });
+ });
+ }, 180_000);
+
+ if (backend === 'postgres') test('D-18 Postgres, unbound source: the take is refused owner_unavailable and nothing is written', async () => {
+ await withBrain(databaseUrl, async b => {
+ const stale = await fileFromDatabase(b);
+ const r = await expectUnitNotAborted(() => b.take());
+ expect({ row: r.take_row, refused: r.warnings.some(w => w.startsWith('TAKE_WRITE_FAILED: owner_unavailable')), file: b.file() === stale, body: await b.body(), takes: await b.takes() })
+ .toEqual({ row: null, refused: true, file: true, body: BODY, takes: [] });
+ }, { bound: false });
+ }, 180_000);
+
+ test('D-18 agreeing copies: the take lands in the file and the database with the body kept', async () => {
+ await withBrain(databaseUrl, async b => {
+ await fileFromDatabase(b);
+ const r = await expectUnitNotAborted(() => b.take());
+ const body = await b.body();
+ expect({ row: r.take_row, warnings: r.warnings, path: r.path, file: fenceClaims(b.file()!), fileKept: b.file()!.includes('DB-BODY-MARKER'),
+ db: fenceClaims(body), dbKept: body.startsWith(BODY), takes: await b.takes() })
+ .toEqual({ row: 1, warnings: [], path: b.path, file: [CLAIM], fileKept: true, db: [CLAIM], dbKept: true, takes: [CLAIM] });
+ });
+ }, 180_000);
+ });
+}
diff --git a/test/pathological/d19-takes-bootstrap-db-only.test.ts b/test/pathological/d19-takes-bootstrap-db-only.test.ts
new file mode 100644
index 0000000000..b4232ae04e
--- /dev/null
+++ b/test/pathological/d19-takes-bootstrap-db-only.test.ts
@@ -0,0 +1,168 @@
+/**
+ * D-19 (GBRA-131, #6982 family): the takes bootstrap reads a database-only
+ * page from the database instead of requiring a file.
+ *
+ * Protects: on an unmanaged brain `extractTakesFromPages` treats the database
+ * as the copy of record for a page in a declared `storage.db_only` directory,
+ * and for every page when `sync.write_through` is off: the classifier runs on
+ * the database body, the claim is appended to the page's database takes fence
+ * through coordinated put_page (bound to the revision read before the
+ * classifier), and no file is created or changed. A file-backed page whose
+ * file is missing is still skipped (`mirror_unavailable`) before any
+ * classifier call, and a file-backed page with its file still gets the claim
+ * md-first in both copies (an unbound source: a claimed one fences the legacy
+ * md-first writer). On Postgres the database-side cases bind the source first
+ * (`claimWorktree`, the claim PGLite makes on its first coordinated write); on
+ * Postgres a database-only page of an unbound source is skipped
+ * (`owner_unavailable`) while the run's file-backed pages still get claims.
+ * Fails when: the bootstrap requires a physical file before choosing the
+ * database or file branch (the pre-fix path): every db_only page is skipped
+ * as `mirror_unavailable`, and with write-through off the claim is appended
+ * to the checkout file.
+ * Seams: `__setChatTransportForTests` (stub classifier, no paid call).
+ * PGLite always, Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { __setChatTransportForTests, configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { extractTakesFromPages } from '../../src/core/extract-takes-from-pages.ts';
+import { serializePageToMarkdown } from '../../src/core/markdown.ts';
+import { claimWorktree, managedPersistenceEnabled } from '../../src/core/persistence/ownership.ts';
+import { parseTakesFence } from '../../src/core/takes-fence.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/acme-example-pricing';
+const BODY = `DB-BODY-MARKER: ${'Acme Example raises prices every spring and customers accept it. '.repeat(5)}`;
+const CLAIM = 'Acme Example has pricing power';
+let classified: string[] = [];
+
+beforeAll(() => {
+ configureGateway({ chat_model: 'anthropic:claude-haiku-4-5-20251001', env: { ANTHROPIC_API_KEY: 'sk-ant-test-d19' } });
+ __setChatTransportForTests(async opts => {
+ const user = opts.messages?.find((m: { role: string }) => m.role === 'user');
+ classified.push(typeof user?.content === 'string' ? user.content : JSON.stringify(user?.content ?? ''));
+ const text = JSON.stringify([{ claim: CLAIM, kind: 'take', weight: 0.7 }]);
+ return { text, blocks: [{ type: 'text' as const, text }], stopReason: 'end' as const,
+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'anthropic:claude-haiku-4-5-20251001', providerId: 'anthropic' };
+ });
+});
+
+afterAll(() => {
+ __setChatTransportForTests(null);
+ resetGateway();
+});
+
+interface Brain {
+ engine: BrainEngine;
+ root: string;
+ path: string;
+ file(): string | null;
+ body(): Promise<string>;
+ takes(): Promise<string[]>;
+ writeFileFromDatabase(): Promise<string>;
+ run(): ReturnType<typeof extractTakesFromPages>;
+}
+
+async function withBrain(databaseUrl: string | undefined, run: (b: Brain) => Promise<void>, opts: { bound?: boolean } = {}): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-d19-'));
+ 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]);
+ await engine.setConfig('sync.repo_path', root);
+ if (opts.bound ?? databaseUrl !== undefined) await claimWorktree(engine, 'default', root);
+ await engine.putPage(SLUG, { type: 'concept', title: 'Acme Example pricing', compiled_truth: BODY });
+ const path = join(root, `${SLUG}.md`);
+ classified = [];
+ await run({
+ engine, root, path,
+ file: () => existsSync(path) ? readFileSync(path, 'utf8') : null,
+ body: async () => (await engine.executeRaw<{ compiled_truth: string }>(
+ "SELECT compiled_truth FROM pages WHERE source_id = 'default' AND slug = $1", [SLUG]))[0]!.compiled_truth,
+ takes: async () => (await engine.executeRaw<{ claim: string }>(
+ "SELECT t.claim FROM takes t JOIN pages p ON p.id = t.page_id WHERE p.source_id = 'default' AND p.slug = $1 ORDER BY t.row_num", [SLUG])).map(r => r.claim),
+ async writeFileFromDatabase() {
+ await engine.executeRaw("UPDATE pages SET source_path = $1 WHERE source_id = 'default' AND slug = $2", [`${SLUG}.md`, SLUG]);
+ const snapshot = (await engine.readPageSnapshot(SLUG, { sourceId: 'default' }))!;
+ const bytes = serializePageToMarkdown(snapshot.page, snapshot.tags);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, bytes);
+ return bytes;
+ },
+ run: () => extractTakesFromPages(engine, { bootstrapEnabled: true, maxPages: 10, holder: 'world' }),
+ });
+ } finally { await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+const fenceClaims = (text: string) => parseTakesFence(text).takes.map(t => t.claim);
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`D-19 takes bootstrap on database-only pages (${backend})`, () => {
+ test('D-19 storage.db_only page with no file: the claim lands in the database fence and no file is created', async () => {
+ await withBrain(databaseUrl, async b => {
+ writeFileSync(join(b.root, 'gbrain.yml'), 'storage:\n db_only:\n - concepts/\n');
+ const r = await expectUnitNotAborted(() => b.run());
+ const body = await b.body();
+ expect({ extracted: r.claims_extracted, skipped: r.skipped, file: b.file(), kept: body.startsWith(BODY.trim()), fence: fenceClaims(body), takes: await b.takes(),
+ classifiedDb: classified.some(c => c.includes('DB-BODY-MARKER')) })
+ .toEqual({ extracted: 1, skipped: [], file: null, kept: true, fence: [CLAIM], takes: [CLAIM], classifiedDb: true });
+ });
+ }, 180_000);
+
+ test('D-19 write-through off: the claim lands in the database fence and the checkout file is untouched', async () => {
+ await withBrain(databaseUrl, async b => {
+ const fileBefore = await b.writeFileFromDatabase();
+ await b.engine.setConfig('sync.write_through', 'false');
+ _resetWriteThroughCacheForTest();
+ const r = await expectUnitNotAborted(() => b.run());
+ const body = await b.body();
+ expect({ extracted: r.claims_extracted, file: b.file() === fileBefore, kept: body.startsWith(BODY.trim()), fence: fenceClaims(body), takes: await b.takes() })
+ .toEqual({ extracted: 1, file: true, kept: true, fence: [CLAIM], takes: [CLAIM] });
+ });
+ }, 180_000);
+
+ test('D-19 file-backed page whose file is missing: still skipped mirror_unavailable before the classifier runs', async () => {
+ await withBrain(databaseUrl, async b => {
+ const r = await expectUnitNotAborted(() => b.run());
+ expect({ extracted: r.claims_extracted, skipped: r.skipped, classified: classified.length, file: b.file(), body: await b.body(), takes: await b.takes() })
+ .toEqual({ extracted: 0, skipped: [{ slug: SLUG, reason: 'mirror_unavailable' }], classified: 0, file: null, body: BODY, takes: [] });
+ });
+ }, 180_000);
+
+ if (backend === 'postgres') test('D-19 Postgres, unbound source: a db_only page is skipped owner_unavailable and the run goes on', async () => {
+ await withBrain(databaseUrl, async b => {
+ writeFileSync(join(b.root, 'gbrain.yml'), 'storage:\n db_only:\n - concepts/\n');
+ await b.engine.putPage('writing/acme-example-essay', { type: 'writing', title: 'Acme Example essay', compiled_truth: BODY });
+ await b.engine.executeRaw("UPDATE pages SET source_path = 'writing/acme-example-essay.md' WHERE source_id = 'default' AND slug = 'writing/acme-example-essay'");
+ mkdirSync(join(b.root, 'writing'), { recursive: true });
+ writeFileSync(join(b.root, 'writing/acme-example-essay.md'), `# Acme Example essay\n\n${BODY}\n`);
+ const r = await expectUnitNotAborted(() => b.run());
+ expect({ skipped: r.skipped, extracted: r.claims_extracted, file: b.file(), body: await b.body(),
+ essay: parseTakesFence(readFileSync(join(b.root, 'writing/acme-example-essay.md'), 'utf8')).takes.map(t => t.claim) })
+ .toEqual({ skipped: [{ slug: SLUG, reason: 'owner_unavailable' }], extracted: 1, file: null, body: BODY, essay: [CLAIM] });
+ }, { bound: false });
+ }, 180_000);
+
+ test('D-19 control: a file-backed page with its file gets the claim md-first', async () => {
+ await withBrain(databaseUrl, async b => {
+ await b.writeFileFromDatabase();
+ const r = await expectUnitNotAborted(() => b.run());
+ expect({ extracted: r.claims_extracted, file: fenceClaims(b.file()!), fileKept: b.file()!.includes('DB-BODY-MARKER'), takes: await b.takes() })
+ .toEqual({ extracted: 1, file: [CLAIM], fileKept: true, takes: [CLAIM] });
+ }, { bound: false });
+ }, 180_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index ed4254c19a..b346cc680d 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -272,9 +272,16 @@ test/pathological/c4-bundle-stuck-recovery.test.ts
test/pathological/c5-writer-transfer-cancel.test.ts
test/pathological/c7-content-receipt-root.test.ts
test/pathological/d1-unfenced-facts-overwrite.test.ts
+test/pathological/d10-derived-atom-file-overwrite.test.ts
+test/pathological/d11-derived-retired-atom-unlink.test.ts
+test/pathological/d12-concept-stale-fences.test.ts
+test/pathological/d13-concept-occupied-path.test.ts
+test/pathological/d14-brainstorm-resume-overwrite.test.ts
test/pathological/d15-sync-reexport-overwrite.test.ts
test/pathological/d16-google-file-replacement.test.ts
test/pathological/d17-github-file-replacement.test.ts
+test/pathological/d18-think-take-db-only.test.ts
+test/pathological/d19-takes-bootstrap-db-only.test.ts
test/pathological/d2-fence-write-overwrite.test.ts
test/pathological/d21-migration-verifier-record.test.ts
test/pathological/d22-legacy-hash-body-history.test.ts