Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(takes): think --take keeps its derived trust on insert; bootstrap routes a bound source's file-backed pages through put_page (#6982)
garrytan62811e015546
diff --git a/docs/architecture/key-files/hindsight.md b/docs/architecture/key-files/hindsight.mdindex f35b7113fc..d9079de021 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 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/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`), and so does a file-backed page of a source with a canonical owner (bound before the run, or bound by the run's own first `put_page`, as PGLite does), so a mixed batch never reaches the fenced md-first writer; other unmanaged pages retain the md-first writer. A file-backed page whose file is missing is skipped as `mirror_unavailable` before the classifier runs. 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/src/commands/think.ts b/src/commands/think.tsindex c58c14a6a1..e8d89c1efa 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 through the- // coordinated takes_add mutation; a refusal (no repo, empty+ // executed — runThink ignored opts.take entirely. Persist md-first+ // through the canonical takes write-through; 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/extract-takes-from-pages.ts b/src/core/extract-takes-from-pages.tsindex 7ba7859169..b633fcf4a8 100644--- a/src/core/extract-takes-from-pages.ts+++ b/src/core/extract-takes-from-pages.ts@@ -28,7 +28,7 @@ import {resolveTakesWritePath,TakesWriteError,} from './takes-write.ts';-import { managedPersistenceEnabled } from './persistence/ownership.ts';+import { getWorktreeBinding, managedPersistenceEnabled } from './persistence/ownership.ts';import { isWriteThroughDisabled, resolvePageWriteTarget } from './write-through.ts';import { isDbOnly, loadStorageConfig } from './storage-config.ts';import { serializePageToMarkdown } from './markdown.ts';@@ -282,14 +282,19 @@ export async function extractTakesFromPages(// 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));+ // snapshot and published through put_page, never from a file. A source+ // with a canonical owner (bound before the run, or by this run's first+ // put_page) fences the md-first writer, so its file-backed pages publish+ // through put_page too.+ const databaseOnly = !dryRun && await databaseOnlyPage(engine, page.slug, page.source_id);+ const ownedFileBacked = !dryRun && !managedJournalWrites && !databaseOnly && await getWorktreeBinding(engine, page.source_id) !== null;+ const fromDatabase = managedJournalWrites || databaseOnly || ownedFileBacked;// #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 && !fromDatabase) {+ if (!dryRun && (!fromDatabase || ownedFileBacked)) {try {const { path } = await resolveTakesWritePath(engine, repoDir, page.slug, page.source_id);if (existsSync(path)) mdPath = path;diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.tsindex 202d5ba9a4..26bb36e380 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- // through the coordinated takes_add mutation; refusals surface as+ // md-first through the canonical takes write-through; refusals surface as// loud machine-stable warnings + take_row:null. Remote stays blocked above.let takeRow: number | null = null;if (safeTake) {@@ -369,6 +369,7 @@ 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 736569a694..1eaf2173f5 100644--- a/src/core/think/persist-take.ts+++ b/src/core/think/persist-take.ts@@ -15,16 +15,18 @@* (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 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.+ * - 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), with the synthesis-derived+ * trust on the insert.+ * - #6982 (D-18): the take is refused (TAKE_WRITE_FAILED) when the page's+ * file is not its canonical copy (write-through off, `storage.db_only`,+ * gitignored), when the page has no file, or when the file and the+ * database differ outside the takes section. Appending there would write+ * a takes-only or stale file that the next sync imports over the page.* - no brain repo (resolveTakesRepoDir null) → TAKE_MIRROR_UNAVAILABLE- * warning, nothing written.+ * warning, nothing written (md is canonical; a DB-only take would be+ * clobbered by the next reconcile).** Remote (MCP) callers never reach this — the `think` op forces* safeTake=false for ctx.remote !== false, unchanged.@@ -33,12 +35,12 @@import type { BrainEngine } from '../engine.ts';import { stripGapsSection, type ThinkResult } from './index.ts';import { resolveOwnerHolder } from '../owner-holder.ts';-import { resolveTakesRepoDir } from '../takes-write.ts';+import { resolveTakesRepoDir, addTakeToPage, TakesWriteError } 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';+import { derivedFileTarget } from '../cycle/derived-write-through.ts';+import { fileDatabaseDriftToken, mirroredBody, readStoredBody } from '../facts/file-body-guard.ts';+import { stripTakesFence, TAKES_FENCE_BEGIN } from '../takes-fence.ts';+import { existsSync, readFileSync } from 'node:fs';/** Max claim length for a fence cell — one readable line, not an essay. */export const TAKE_CLAIM_MAX_CHARS = 300;@@ -46,7 +48,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 (unset when nothing was written or the page is database-only). */+ /** Markdown file the row landed in (set iff take_row is non-null). */path?: string;/** Machine-stable warning codes (mirrors the think warnings channel). */warnings: string[];@@ -95,7 +97,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 },+ opts: { anchor: string; sourceId?: string; lockTimeoutMs?: number },): Promise<PersistTakeResult> {const warnings: string[] = [];@@ -123,27 +125,67 @@ 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 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 };+ await assertTakeFileCanonical(engine, opts.anchor, opts.sourceId ?? 'default');+ 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 {+ try {+ 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' })) }));+ } catch (e) {+ warnings.push(`TAKE_LINEAGE_WARNING: the take was written at its derived trust tier but its input edges were not recorded: ${e instanceof Error ? e.message : String(e)}`);+ }+ }+ return { take_row: rowNum, path: mirror.path, warnings };} catch (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));+ // 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));warnings.push(`TAKE_WRITE_FAILED: ${detail}`);return { take_row: null, warnings };}}++/** A page body with its takes section (fence and the heading addTakeToPage adds) removed and whitespace collapsed. */+function bodyOutsideTakes(compiledTruth: string | null, timeline: string | null): string {+ const text = `${compiledTruth ?? ''}\n${timeline ?? ''}`.replace(new RegExp(`(^|\\n)## Takes\\s*\\n(?=${TAKES_FENCE_BEGIN})`), '$1');+ return stripTakesFence(text).replace(/\s+/g, ' ').trim();+}++async function assertTakeFileCanonical(engine: BrainEngine, slug: string, sourceId: string): Promise<void> {+ const stored = await readStoredBody(engine, sourceId, slug);+ if (!stored) return;+ const resolved = await derivedFileTarget(engine, slug, sourceId);+ if (!resolved.ok) {+ throw new TakesWriteError('mirror_unavailable',+ `${slug} has no canonical markdown file (${resolved.skipped}), so the take was not written: a takes file there would be imported over the database page.`,+ `Add it with gbrain takes add ${slug} --source ${sourceId}, which puts a database-only page's take in its database body.`);+ }+ const path = resolved.target.filePath;+ if (!existsSync(path)) {+ throw new TakesWriteError('mirror_unavailable',+ `${slug} has no checkout file, so the take was not written: a takes-only file would be imported over the database page.`,+ `Restore the page's file first (gbrain get ${slug} --source ${sourceId}, then gbrain put ${slug} --source-id ${sourceId} with write-through on), then rerun the take.`);+ }+ const file = mirroredBody(readFileSync(path, 'utf-8'), slug);+ if (bodyOutsideTakes(file.compiled_truth, file.timeline) !== bodyOutsideTakes(stored.compiled_truth, stored.timeline)) {+ throw new TakesWriteError('mirror_unavailable', fileDatabaseDriftToken(slug, sourceId, 'before', 'the take was not written'));+ }+}diff --git a/test/pathological/d18-think-take-db-only.test.ts b/test/pathological/d18-think-take-db-only.test.tsindex c8a40376e3..6df173bb9d 100644--- a/test/pathological/d18-think-take-db-only.test.ts+++ b/test/pathological/d18-think-take-db-only.test.ts@@ -1,27 +1,27 @@/*** 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.+ * file for a database-only page or appends to a file older than the database,+ * and the take keeps the trust tier of its synthesis inputs.*- * 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.+ * Protects: `persistTakeFromSynthesis` keeps the md-first addTakeToPage+ * writer, which inserts the take at the synthesis-derived trust tier. Before+ * it writes, a page whose file is not canonical (`sync.write_through` off, a+ * declared `storage.db_only` directory), a page with no file, and a file whose+ * body differs from the database outside the takes section (a newer database+ * edit, or an unimported file edit) are refused+ * (`TAKE_WRITE_FAILED: mirror_unavailable`) with both copies unchanged.+ * Agreeing copies get the take in the file and the database, and a second+ * take before sync imports the first still lands. A take derived from an+ * `external_untrusted` page is written at `external_untrusted` with its input+ * edge, and when recording the edge fails the take is still at that tier and+ * reported written. On a source with a canonical owner the legacy writer is+ * refused and nothing is written.+ * Fails when: a missing file is read as an empty body and a takes-only file is+ * written that the next sync imports over the page, a stale file is appended+ * to, or the take is inserted under the ordinary agent channel and lowered in+ * a later transaction (a failed lowering leaves it over-trusted and reported+ * as not written).+ * Seams: a test trigger on derivation_inputs fails the lineage transaction.* PGLite always, Postgres when DATABASE_URL is set.*/import { describe, expect, test } from 'bun:test';@@ -30,6 +30,7 @@ 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 { maintenanceTransaction } from '../../src/core/persistence/attribution.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';@@ -50,7 +51,8 @@ interface Brain {file(): string | null;body(): Promise<string>;takes(): Promise<string[]>;- take(): ReturnType<typeof persistTakeFromSynthesis>;+ take(taintSlug?: string): ReturnType<typeof persistTakeFromSynthesis>;+ tier(): Promise<string | undefined>;}async function withBrain(databaseUrl: string | undefined, run: (b: Brain) => Promise<void>, opts: { bound?: boolean } = {}): Promise<void> {@@ -65,7 +67,7 @@ async function withBrain(databaseUrl: string | undefined, run: (b: Brain) => PromkdirSync(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);+ if (opts.bound) 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({@@ -75,7 +77,11 @@ async function withBrain(databaseUrl: string | undefined, run: (b: Brain) => Pro"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' }),+ take: (taintSlug?: string) => persistTakeFromSynthesis(engine,+ { ...ANSWER, ...(taintSlug ? { taint_refs: [{ table: 'pages', sourceId: 'default', slug: taintSlug }] } : {}) } as never,+ { anchor: ALICE, sourceId: 'default' }),+ tier: async () => (await engine.executeRaw<{ trust_tier: string }>(+ "SELECT t.trust_tier FROM takes t JOIN pages p ON p.id = t.page_id WHERE p.source_id = 'default' AND p.slug = $1", [ALICE]))[0]?.trust_tier,});} finally { await close(); }});@@ -92,34 +98,39 @@ async function fileFromDatabase(b: Brain): Promise<string> {}const fenceClaims = (text: string) => parseTakesFence(text).takes.map(t => t.claim);+const refused = (r: { warnings: string[] }) => r.warnings.some(w => w.startsWith('TAKE_WRITE_FAILED: mirror_unavailable'));++async function externalPage(b: Brain): Promise<number> {+ const page = await maintenanceTransaction(b.engine, tx => tx.putPage('notes/external-example', { type: 'note', title: 'External example',+ compiled_truth: 'An imported third-party note about Acme Example.' }, { sourceId: 'default' }), { tier: 'external_untrusted', origin: { channel: 'test' } });+ return Number(page.id);+}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 () => {+ describe(`D-18 think --take on a database-only, drifted or tainted page (${backend})`, () => {+ test('D-18 write-through off: refused, no file is created and the database is unchanged', 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] });+ expect({ row: r.take_row, refused: refused(r), 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 storage.db_only page: the take lands in the database body and no file is created', async () => {+ test('D-18 storage.db_only page: refused, no file is created and the database is unchanged', 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] });+ expect({ row: r.take_row, refused: refused(r), 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 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() })+ expect({ row: r.take_row, refused: refused(r), file: b.file(), body: await b.body(), takes: await b.takes() }).toEqual({ row: null, refused: true, file: null, body: BODY, takes: [] });});}, 180_000);@@ -130,7 +141,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) {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() })+ expect({ row: r.take_row, refused: r.warnings.some(w => w.includes('file_database_drift')), 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);@@ -140,28 +151,65 @@ for (const { backend, databaseUrl } of pathologicalArms()) {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() })+ expect({ row: r.take_row, refused: r.warnings.some(w => w.includes('file_database_drift')), 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 () => {+ test('D-18 a second take before sync imports the first lands after it', 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 });+ await fileFromDatabase(b);+ const first = await expectUnitNotAborted(() => b.take());+ const second = await expectUnitNotAborted(() => persistTakeFromSynthesis(b.engine,+ { answer: 'Acme Example ships monthly.', synthesisOk: true }, { anchor: ALICE, sourceId: 'default' }));+ expect({ rows: [first.take_row, second.take_row], warnings: [...first.warnings, ...second.warnings], file: fenceClaims(b.file()!), body: await b.body() })+ .toEqual({ rows: [1, 2], warnings: [], file: [CLAIM, 'Acme Example ships monthly.'], body: BODY });+ });}, 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] });+ expect({ row: r.take_row, warnings: r.warnings, path: r.path, file: fenceClaims(b.file()!), fileKept: b.file()!.includes('DB-BODY-MARKER'), takes: await b.takes() })+ .toEqual({ row: 1, warnings: [], path: b.path, file: [CLAIM], fileKept: true, takes: [CLAIM] });+ });+ }, 180_000);++ test('D-18 claimed source: the legacy writer is refused and nothing is written', async () => {+ await withBrain(databaseUrl, async b => {+ const bytes = await fileFromDatabase(b);+ const r = await expectUnitNotAborted(() => b.take());+ expect({ row: r.take_row, failed: r.warnings.some(w => w.startsWith('TAKE_WRITE_FAILED')), file: b.file() === bytes, body: await b.body(), takes: await b.takes() })+ .toEqual({ row: null, failed: true, file: true, body: BODY, takes: [] });+ }, { bound: true });+ }, 180_000);++ test('D-18 tainted input: the take is written at external_untrusted with its input edge', async () => {+ await withBrain(databaseUrl, async b => {+ await fileFromDatabase(b);+ const input = await externalPage(b);+ const r = await expectUnitNotAborted(() => b.take('notes/external-example'));+ const edges = await b.engine.executeRaw<{ input_id: string }>(+ "SELECT d.input_id FROM derivation_inputs d JOIN takes t ON d.derived_table = 'takes' AND d.derived_id = t.id::text JOIN pages p ON p.id = t.page_id WHERE p.slug = $1 AND d.input_table = 'pages'", [ALICE]);+ expect({ row: r.take_row, warnings: r.warnings, tier: await b.tier(), edges: edges.map(e => Number(e.input_id)) })+ .toEqual({ row: 1, warnings: [], tier: 'external_untrusted', edges: [input] });+ });+ }, 180_000);++ test('D-18 tainted input, lineage failure: the take is still external_untrusted and reported written', async () => {+ await withBrain(databaseUrl, async b => {+ await fileFromDatabase(b);+ await externalPage(b);+ await b.engine.executeRaw("CREATE OR REPLACE FUNCTION d18_fail_lineage() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'd18 lineage seam'; END $$");+ await b.engine.executeRaw('CREATE TRIGGER d18_fail_lineage BEFORE INSERT ON derivation_inputs FOR EACH ROW EXECUTE FUNCTION d18_fail_lineage()');+ try {+ const r = await expectUnitNotAborted(() => b.take('notes/external-example'));+ expect({ row: r.take_row, lineage: r.warnings.some(w => w.startsWith('TAKE_LINEAGE_WARNING')), tier: await b.tier(), takes: await b.takes() })+ .toEqual({ row: 1, lineage: true, tier: 'external_untrusted', takes: [CLAIM] });+ } finally {+ await b.engine.executeRaw('DROP TRIGGER IF EXISTS d18_fail_lineage ON derivation_inputs');+ }});}, 180_000);});diff --git a/test/pathological/d19-takes-bootstrap-db-only.test.ts b/test/pathological/d19-takes-bootstrap-db-only.test.tsindex b4232ae04e..a892b585e6 100644--- a/test/pathological/d19-takes-bootstrap-db-only.test.ts+++ b/test/pathological/d19-takes-bootstrap-db-only.test.ts@@ -10,15 +10,20 @@* 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+ * md-first in both copies on an unbound source. On a source with a canonical+ * owner (bound before the run, or bound by the run's own first put_page, as+ * PGLite does automatically) a file-backed page gets the claim through+ * put_page too, so a mixed batch never reaches the fenced 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.+ * to the checkout file; or a file-backed page of a bound source takes the+ * md-first branch, whose file write is refused (writer_coordinator_required)+ * and aborts the batch.* Seams: `__setChatTransportForTests` (stub classifier, no paid call).* PGLite always, Postgres when DATABASE_URL is set.*/@@ -164,5 +169,40 @@ for (const { backend, databaseUrl } of pathologicalArms()) {.toEqual({ extracted: 1, file: [CLAIM], fileKept: true, takes: [CLAIM] });}, { bound: false });}, 180_000);++ const ESSAY = 'writing/acme-example-essay';+ const essayPath = (b: Brain) => join(b.root, `${ESSAY}.md`);+ const essayTakes = async (b: Brain) => (await b.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", [ESSAY])).map(r => r.claim);++ if (backend === 'pglite') test('D-19 mixed order, unbound PGLite: after the database-only put_page binds the source, a file-backed page is routed through put_page and the batch finishes', async () => {+ await withBrain(databaseUrl, async b => {+ writeFileSync(join(b.root, 'gbrain.yml'), 'storage:\n db_only:\n - concepts/\n');+ await b.engine.putPage(ESSAY, { type: 'writing', title: 'Acme Example essay', compiled_truth: BODY });+ await b.engine.executeRaw("UPDATE pages SET source_path = $1, updated_at = now() - interval '1 hour' WHERE source_id = 'default' AND slug = $2", [`${ESSAY}.md`, ESSAY]);+ const snapshot = (await b.engine.readPageSnapshot(ESSAY, { sourceId: 'default' }))!;+ const essay = serializePageToMarkdown(snapshot.page, snapshot.tags);+ mkdirSync(dirname(essayPath(b)), { recursive: true });+ writeFileSync(essayPath(b), essay);+ const r = await expectUnitNotAborted(() => b.run());+ const body = await b.body();+ expect({ extracted: r.claims_extracted, skipped: r.skipped, file: b.file(), fence: fenceClaims(body),+ essayFile: readFileSync(essayPath(b), 'utf8') === essay, essayTakes: await essayTakes(b) })+ .toEqual({ extracted: 1, skipped: [{ slug: ESSAY, reason: 'source_changed' }], file: null, fence: [CLAIM], essayFile: true, essayTakes: [] });+ }, { bound: false });+ }, 180_000);++ test('D-19 bound source: a coordinated file-backed page gets the claim through put_page in both copies', async () => {+ await withBrain(databaseUrl, async b => {+ const { operations } = await import('../../src/core/operations.ts');+ const putPage = operations.find(operation => operation.name === 'put_page')!;+ await putPage.handler({ engine: b.engine, config: { engine: b.engine.kind }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: 'default' } as never,+ { slug: ESSAY, content: `---\ntype: writing\ntitle: Acme Example essay\n---\n\n${BODY}\n` });+ const r = await expectUnitNotAborted(() => b.run());+ const essay = readFileSync(essayPath(b), 'utf8');+ expect({ extracted: r.claims_extracted, skipped: r.skipped, essayFile: fenceClaims(essay), essayKept: essay.includes('DB-BODY-MARKER'), essayTakes: await essayTakes(b) })+ .toEqual({ extracted: 1, skipped: [{ slug: SLUG, reason: 'mirror_unavailable' }], essayFile: [CLAIM], essayKept: true, essayTakes: [CLAIM] });+ }, { bound: true });+ }, 180_000);});}