Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-161 PR 2: gate fixes: purge scrubs recorded fence blocks, segmented fences read whole, one-statement ledger items, fence-generation retire gates the expire, inventories

garrytanfafc6663c8e4
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.md
index 998e851a87..1b7dfe7bfc 100644
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@ -232,7 +232,7 @@ or a physical projection that leaves attribution untouched):
- `src/core/cycle/dream-provenance.ts` (1): the dream provenance frontmatter stamp runs per page in `maintenanceTransaction`, or `derivedMaintenanceTransaction` at the child's derived tier when the ref carries its taint (unmanaged brains only; managed synthesis publishes through maintenance requests).
- `src/core/cycle/dream-taint.ts` (3): the unmanaged dream summary page, its frontmatter tags, and the page_versions row of the different body it replaces (#6982), run in `derivedMaintenanceTransaction` at the tier of the pages it indexes; managed brains publish it through a maintenance request.
- `src/core/cycle/drift.ts` (1): the unmanaged drift report page runs in `maintenanceTransaction`; managed brains publish it through a maintenance request.
-- `src/core/cycle/extract-facts.ts` (7): the unmanaged page reconcile and the expiry of fence facts whose page was soft-deleted run in `maintenanceTransaction`; managed brains publish `managed_maintenance_fence_facts` and `managed_maintenance_deleted_page_facts_expire` requests whose preparers write inside the coordinator publication. Both reconcile paths write at the page's tier and gate new rows.
+- `src/core/cycle/extract-facts.ts` (6): the unmanaged page reconcile and the expiry of fence facts whose page was soft-deleted run in `maintenanceTransaction`; managed brains publish `managed_maintenance_fence_facts` and `managed_maintenance_deleted_page_facts_expire` requests whose preparers write inside the coordinator publication. Both reconcile paths write at the page's tier and gate new rows.
- `src/core/cycle/extract-takes.ts` (1): one projected-takes writer stamps each page's tier and runs the write gate: inside a receipted `managed_maintenance_takes_reextract` request per changed page on managed brains, one `maintenanceTransaction` per page tier for the unmanaged batch upsert.
- `src/core/enrichment-service.ts` (2): the enrichment stub fallback write and its auto-timeline entry run in `maintenanceTransaction` at the source page's derived tier (the stub import is lowered to it afterwards).
- `src/core/extract-timeline-from-meetings.ts` (2): on an unmanaged brain each meeting timeline batch runs in `maintenanceTransaction`, one meeting tier per batch; a managed brain publishes receipted `managed_maintenance_meeting_timeline` requests instead, whose preparer (`prepareMeetingTimeline`) inserts the rows inside the coordinated publication (#6273).
@@ -259,6 +259,8 @@ or a physical projection that leaves attribution untouched):
- `src/core/trust/timeline-projection.ts` (2): `gbrain extract` timeline walks (file, incremental, stale) and the per-entry fallback write through it: one `maintenanceTransaction` per page tier.
- `src/core/facts/write-single.ts` (2): the legacy single-fact insert and its supersession link each run in `maintenanceTransaction`; managed brains publish through the fact request.
- `src/core/generations/adapters/atoms.ts` (1): the unmanaged atom completion stamp (`source_hash`) runs inside the generation activation's `maintenanceTransaction` (`publish.ts`, GBRA-161).
+- `src/core/generations/adapters/extracted-facts.ts` (2): the extracted-facts generation's row inserts and retirements (`publishExtractedFacts`, GBRA-161 PR 2) run inside the generation activation's `maintenanceTransaction` (`publish.ts`); its restore runs in the restore runner's (`repair.ts`).
+- `src/core/generations/adapters/fact-rows.ts` (1): putting a fact's recorded before-state back (`restoreFactRow`) runs only inside a generation restore's `maintenanceTransaction` (`repair.ts`, GBRA-161 PR 2).
- `src/core/import-file.ts` (12): direct markdown, code and image imports, the moved-file rename (`updateSlug`) and the #3694 legacy-hash re-stamp run in `maintenanceTransaction`; managed imports go through the page request preparer.
- `src/core/minions/handlers/ingest-capture.ts` (1): the capture ingest tombstone soft delete runs in `maintenanceTransaction`.
- `src/core/ops/extraction.ts` (2): extraction review promote (frontmatter) and reject (soft delete) each run in `maintenanceTransaction`.
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 1762299636..3cb1afd69e 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -83,10 +83,10 @@ import { writeReceipt } from '../extract/receipt-writer.ts';
import { fenceUnfencedFacts, planUnfencedFacts } from '../facts/unfenced-facts.ts';
import { classifyRunStop, upsertExtractRollup } from '../extract/rollup-writer.ts';
import { factsFenceView } from '../facts-fence.ts';
-import { publishFenceGeneration, readFenceBlocks, FACT_FENCE_KIND, type FenceRead } from '../generations/fence.ts';
+import { fenceReadOf, publishFenceGeneration, readFenceBlocks, FACT_FENCE_KIND, type FenceRead } from '../generations/fence.ts';
import type { BodyStorage } from '../page-body/types.ts';
import { factFenceItems, factPreimages, factRetireItem } from '../generations/adapters/fact-rows.ts';
-import { segmentedBodyMatchesFile, segmentedFactsFenceView } from '../page-body/segment-facts.ts';
+import { segmentedBodyMatchesFile, segmentedFactsFence } from '../page-body/segment-facts.ts';
import {
duplicateActiveFenceRows,
extractFactsFromFenceText,
@@ -396,7 +396,8 @@ interface FenceReconcilePlan {
* fence in each section of the page (#6686: a split fence) preserves the page's existing index.
*/
async function planFenceReconcile(db: BrainEngine, page: PageFenceInput, slug: string, sourceId: string, warnings: string[]): Promise<FenceReconcilePlan | null> {
- const view = isSegmentedPage(page) ? await segmentedFactsFenceView(db, page) : factsFenceView(page);
+ const segmented = isSegmentedPage(page) ? await segmentedFactsFence(db, page) : null;
+ const view = segmented?.view ?? factsFenceView(page);
// #6686: a lone fence below the timeline sentinel that parses cleanly is the page's fence, read where the writers
// edit it; one that does not parse keeps the #3625 guard below.
const below = !view.sections.body && view.sections.timeline ? view.timeline : null;
@@ -463,7 +464,7 @@ async function planFenceReconcile(db: BrainEngine, page: PageFenceInput, slug: s
return resolveSupersession(f, byRow, chain, slug).superseded_by === (stored == null ? null : Number(stored));
});
}
- const read: FenceRead = isSegmentedPage(page) ? { state: 'segmented' } : readFenceBlocks(page, 'facts');
+ const read: FenceRead = segmented ? fenceReadOf(segmented.blocks) : readFenceBlocks(page, 'facts');
return { fenceRows: parsed.facts.length, read, extracted, matched, stale, updates, toInsert, chain, inSync };
}
diff --git a/src/core/generations/adapters/extracted-facts.ts b/src/core/generations/adapters/extracted-facts.ts
index 53a7829659..711226297f 100644
--- a/src/core/generations/adapters/extracted-facts.ts
+++ b/src/core/generations/adapters/extracted-facts.ts
@@ -121,6 +121,8 @@ export const extractedFactsAdapter: GenerationAdapter<{ input: InputState }> = {
/**
* GBRA-60 entry point: publishes one page's extracted facts as a generation of `writer` on that page. Call it
* with the whole result of one extraction and the page input it read; `coverage` says whether that was the whole page.
+ * `facts` are the rows the write gate already let through (`decideFactWrite`, as conversation-publication.ts and
+ * backstop.ts decide today); this publishes them and records no gate receipt.
*/
export async function publishExtractedFacts(engine: BrainEngine, request: ExtractedFactsRequest): Promise<ExtractedFactsOutcome> {
const { rows, detached } = placeFacts(request);
diff --git a/src/core/generations/adapters/fact-rows.ts b/src/core/generations/adapters/fact-rows.ts
index 0268de835b..a3ea2a1558 100644
--- a/src/core/generations/adapters/fact-rows.ts
+++ b/src/core/generations/adapters/fact-rows.ts
@@ -61,7 +61,7 @@ export async function factPreimages(db: BrainEngine, sourceId: string, ids: read
* extractor rows only when a fence row claims their number, #5731). Held: the caller expires nothing.
*/
export async function projectFactFenceGeneration(tx: BrainEngine, input: { sourceId: string; slug: string; read: FenceRead; incoming: string;
- rows: ReadonlyArray<{ row_num: number; fact: string; visibility?: string | null }>; writer: string }): Promise<FenceGenerationOutcome> {
+ rows: ReadonlyArray<{ row_num: number; fact: string; visibility?: string | null }>; writer: string }): Promise<FenceGenerationOutcome & { retiring: number }> {
const retire = (await tx.executeRaw<{ preimage: FactPreimage }>(`SELECT ${FACT_PREIMAGE_SQL} AS preimage FROM facts f
WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL
AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%'
@@ -69,8 +69,9 @@ export async function projectFactFenceGeneration(tx: BrainEngine, input: { sourc
AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text)
WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)
ORDER BY f.row_num, f.id`, [input.sourceId, input.slug, input.incoming])).map(row => factRetireItem(row.preimage));
- return publishFenceGeneration(tx, { kind: FACT_FENCE_KIND, sourceId: input.sourceId, slug: input.slug, read: input.read,
+ const outcome = await publishFenceGeneration(tx, { kind: FACT_FENCE_KIND, sourceId: input.sourceId, slug: input.slug, read: input.read,
items: factFenceItems(input.rows), retire, writer: input.writer });
+ return { ...outcome, retiring: retire.length };
}
/**
diff --git a/src/core/generations/fence.ts b/src/core/generations/fence.ts
index 6dff6be40a..d8da29ae70 100644
--- a/src/core/generations/fence.ts
+++ b/src/core/generations/fence.ts
@@ -48,10 +48,12 @@ export function readFenceBlocks(page: { compiled_truth: string | null; timeline?
const { beginIdx, endIdx } = locateOutsideCode(text ?? '', begin, end);
return beginIdx !== -1 && endIdx > beginIdx ? text!.slice(beginIdx, endIdx + end.length) : null;
};
- const blocks = { body: block(page.compiled_truth), timeline: block(page.timeline) };
- return blocks.body === null && blocks.timeline === null ? { state: 'absent' } : { state: 'parsed', blocks };
+ return fenceReadOf({ body: block(page.compiled_truth), timeline: block(page.timeline) });
}
+/** The read of a fence whose blocks were read whole (each from its begin to its end marker): `absent` when neither section holds one. */
+export const fenceReadOf = (blocks: FenceBlocks): FenceRead => blocks.body === null && blocks.timeline === null ? { state: 'absent' } : { state: 'parsed', blocks };
+
/** A row's identity: what makes it the same canonical row (number and claim; visibility for facts, kind and holder for takes). */
export const factRowIdentity = (row: { row_num: number; fact: string; visibility: string }) =>
digest(['fact-fence-row-v1', Number(row.row_num), row.fact, row.visibility]).slice(0, 32);
diff --git a/src/core/generations/ledger-scrub.ts b/src/core/generations/ledger-scrub.ts
index 8b254970aa..2d250762c9 100644
--- a/src/core/generations/ledger-scrub.ts
+++ b/src/core/generations/ledger-scrub.ts
@@ -2,7 +2,9 @@
* GBRA-161: purge reaches the generation ledger. Superseded generations keep bounded item preimages and held rows keep
* the proposal they would publish; both copy memory text, so a page purge nulls every preimage of the purged item and
* every held proposal naming it, and a fact purge nulls every preimage and proposal carrying the claim. The ledger rows
- * themselves stay (keys, identity hashes and actions only), so restore refuses a scrubbed item with `no_preimage`.
+ * themselves stay (keys, identity hashes and actions only), so restore refuses a scrubbed item with `no_preimage`. A fence
+ * generation (GBRA-161 PR 2) also records the fence blocks it read (`completeness.fence`), which a fence restore transplants;
+ * a purge of the page, or of a claim those blocks carry, drops them, and that restore then refuses `no_preimage` too.
*/
import type { BrainEngine } from '../engine.ts';
@@ -16,7 +18,9 @@ export async function scrubGenerationLedger(tx: BrainEngine, sourceId: string, t
const held = await tx.executeRaw(`UPDATE derived_generations SET proposal=NULL, updated_at=now()
WHERE source_id=$1 AND proposal IS NOT NULL AND (right(owner_key, length($2) + 1) = ':' || $2 OR proposal @> jsonb_build_array(jsonb_build_object('key', $2::text)))
RETURNING 1`, [sourceId, target.slug]);
- return { derived_generation_items: items.length, derived_generations: held.length };
+ const fences = await tx.executeRaw(`UPDATE derived_generations SET completeness=completeness - 'fence'::text, updated_at=now()
+ WHERE source_id=$1 AND owner_key='page:' || $2::text AND completeness->'fence' IS NOT NULL RETURNING 1`, [sourceId, target.slug]);
+ return { derived_generation_items: items.length, derived_generations: held.length + fences.length };
}
const needles = target.needles.filter(Boolean).flatMap(needle => [needle.toLowerCase(), JSON.stringify(needle).slice(1, -1).toLowerCase()]);
if (!needles.length) return { derived_generation_items: 0, derived_generations: 0 };
@@ -25,5 +29,7 @@ export async function scrubGenerationLedger(tx: BrainEngine, sourceId: string, t
WHERE g.id=i.generation_id AND g.source_id=$1 AND i.preimage IS NOT NULL AND ${carries('i.preimage')} RETURNING 1`, [sourceId, needles]);
const held = await tx.executeRaw(`UPDATE derived_generations SET proposal=NULL, held_context=NULL, updated_at=now()
WHERE source_id=$1 AND (proposal IS NOT NULL AND ${carries('proposal')} OR held_context IS NOT NULL AND ${carries('held_context')}) RETURNING 1`, [sourceId, needles]);
- return { derived_generation_items: items.length, derived_generations: held.length };
+ const fences = await tx.executeRaw(`UPDATE derived_generations SET completeness=completeness - 'fence'::text, updated_at=now()
+ WHERE source_id=$1 AND completeness->'fence' IS NOT NULL AND ${carries("(completeness->'fence')")} RETURNING 1`, [sourceId, needles]);
+ return { derived_generation_items: items.length, derived_generations: held.length + fences.length };
}
diff --git a/src/core/generations/publish.ts b/src/core/generations/publish.ts
index f569163724..4670bf0f2e 100644
--- a/src/core/generations/publish.ts
+++ b/src/core/generations/publish.ts
@@ -101,13 +101,15 @@ export async function activateGeneration(tx: BrainEngine, key: GenerationKey, li
JSON.stringify(row.completeness), row.setHash, row.restoreOf ?? null, row.activationId ?? null, row.locator ?? live?.locator ?? null]);
const id = Number(created!.id);
if (live) await tx.executeRaw('UPDATE derived_generations SET superseded_by=$1 WHERE id=$2', [id, live.id]);
- for (const item of items) {
+ if (items.length) {
await tx.executeRaw(`INSERT INTO derived_generation_items (generation_id, item_key, identity_hash, action, preimage, preimage_bytes, pending)
- VALUES ($1,$2,$3,$4,$5::text::jsonb,$6,$7)`,
- [id, item.key, item.identityHash, item.action, item.preimage?.json ? JSON.stringify(item.preimage.json) : null, item.preimage?.bytes ?? null, item.pending === true]);
+ SELECT $1, i.item_key, i.identity_hash, i.action, i.preimage, i.preimage_bytes, i.pending
+ FROM jsonb_to_recordset($2::text::jsonb) AS i(item_key text, identity_hash text, action text, preimage jsonb, preimage_bytes integer, pending boolean)`,
+ [id, JSON.stringify(items.map(item => ({ item_key: item.key, identity_hash: item.identityHash, action: item.action, preimage: item.preimage?.json ?? null,
+ preimage_bytes: item.preimage?.bytes ?? null, pending: item.pending === true })))]);
}
- await tx.executeRaw(`DELETE FROM derived_generations WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='held'`, [key.sourceId, key.kind, key.ownerKey]);
- await tx.executeRaw('DELETE FROM derived_generation_attempts WHERE source_id=$1 AND kind=$2 AND owner_key=$3', [key.sourceId, key.kind, key.ownerKey]);
+ await tx.executeRaw(`WITH held AS (DELETE FROM derived_generations WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='held' RETURNING 1)
+ DELETE FROM derived_generation_attempts WHERE source_id=$1 AND kind=$2 AND owner_key=$3`, [key.sourceId, key.kind, key.ownerKey]);
return { id, generation };
}
diff --git a/src/core/page-body/segment-facts.ts b/src/core/page-body/segment-facts.ts
index a504af950d..e896c0f988 100644
--- a/src/core/page-body/segment-facts.ts
+++ b/src/core/page-body/segment-facts.ts
@@ -86,16 +86,22 @@ async function regionFence(engine: BrainEngine, page: FencePage, region: BodyReg
if (end !== -1) parsedText = fence.join('');
}
const reduced = parsedText ?? (fence ? FACTS_FENCE_BEGIN : endOnly ? `${'\n'.repeat(FACTS_FENCE_BEGIN.length)}${FACTS_FENCE_END}` : '');
- return { parsed: parseFactsFence(reduced), holds: fence !== null, marker };
+ return { parsed: parseFactsFence(reduced), holds: fence !== null, marker, text: parsedText };
}
/** factsFenceView of a segmented page, reading only the runs that can hold a fence marker. */
export async function segmentedFactsFenceView(engine: BrainEngine, page: { id?: number; slug?: string; source_id?: string }): Promise<FactsFenceView> {
+ return (await segmentedFactsFence(engine, page)).view;
+}
+
+/** segmentedFactsFenceView with each region's whole fence text (`blocks`, null where the region holds no closed fence). */
+export async function segmentedFactsFence(engine: BrainEngine, page: { id?: number; slug?: string; source_id?: string }): Promise<{ view: FactsFenceView; blocks: { body: string | null; timeline: string | null } }> {
const p = { id: Number(page.id), slug: page.slug ?? '', source_id: page.source_id ?? 'default' };
const marked = await markerSeqs(engine, p.id);
const truth = await regionFence(engine, p, 'truth', marked);
const timeline = await regionFence(engine, p, 'timeline', marked);
- return { body: truth.parsed, timeline: timeline.parsed, sections: { body: truth.holds, timeline: timeline.holds }, timelineMarker: timeline.marker };
+ return { view: { body: truth.parsed, timeline: timeline.parsed, sections: { body: truth.holds, timeline: timeline.holds }, timelineMarker: timeline.marker },
+ blocks: { body: truth.text, timeline: timeline.text } };
}
const FILE_READ_BYTES = 1024 * 1024;
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index 05c25dab58..7d933b51a6 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -673,14 +673,16 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
}
// GBRA-161 PR 2: the fact and take generations decide first. A held one (its fence absent from this body) retires and
// overwrites nothing, so its rows stay as they are; every row a published one retires is recorded with its before-state.
- const factsHeld = (await step('fact_generation', () => projectFactFenceGeneration(tx, { sourceId, slug, read: fenceReads.facts, incoming, rows: factRows,
- writer: 'projection' }))).state === 'held';
+ const factGeneration = await step('fact_generation', () => projectFactFenceGeneration(tx, { sourceId, slug, read: fenceReads.facts, incoming, rows: factRows,
+ writer: 'projection' }));
+ const factsHeld = factGeneration.state === 'held';
const takesHeld = (await step('take_generation', () => projectTakeFenceGeneration(tx, { sourceId, slug, pageId: id, read: fenceReads.takes,
takes: projectedTakes, gone: takeRowsGone.filter(n => !heldRowNums.has(n)), writer: 'projection' }))).state === 'held';
// #5575: rows more trusted than the writer are never expired by it, and new rows pass the write gate (trust/fence-guard.ts).
- // The timeline rows are independent of the fact and take rows, so they ride in the first pipeline.
+ // The timeline rows are independent of the fact and take rows, so they ride in the first pipeline. The expire uses the
+ // generation's retire predicate under the page lock, so it runs only when that generation found rows to retire.
const guard = factsHeld ? { rows: [] as typeof factRows, finish: async () => [] as string[] } : await step('timeline', () => guardFenceRows(tx, { sourceId, slug, incoming, rows: factRows, cfg: loadWriteGateConfig },
- () => pipelined(tx, [expireFacts, ...timelineRows])));
+ () => pipelined(tx, factGeneration.retiring ? [expireFacts, ...timelineRows] : timelineRows)));
if (factsHeld) await step('timeline', () => pipelined(tx, timelineRows));
if (guard.rows.length) await step('facts', () => tx.insertFacts(guard.rows, { source_id: sourceId })); // gbrain-allow-direct-insert: canonical fence projection shares the journal publication transaction
const contested = await step('fact_trust', () => guard.finish(tx));
diff --git a/test/belief-ledger-weekly-diff.test.ts b/test/belief-ledger-weekly-diff.test.ts
index 1443401a40..efb416e9cb 100644
--- a/test/belief-ledger-weekly-diff.test.ts
+++ b/test/belief-ledger-weekly-diff.test.ts
@@ -149,7 +149,7 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
await b.put(slug, beliefPage({ facts: ['Acme sells widgets'], takes: [{ claim: 'Acme will IPO', who: 'world', weight: '0.4' }] }));
const t0 = await at(b);
await b.put('companies/newco-example', beliefPage({ title: 'Newco', facts: ['Newco signed SECRET-CONTRACT', 'Newco is public'], takes: [{ claim: 'Newco is privately loved', who: 'garry-example' }] }));
- await b.put(slug, beliefPage({ facts: ['Acme sells widgets'] }));
+ await b.put(slug, beliefPage({ facts: ['Acme sells widgets'], takes: [] }));
const t1 = await at(b);
// Made private after the window: the window's events never mention the fact, so only the creation body could show it.
await b.put('companies/newco-example', beliefPage({ title: 'Newco', facts: [{ claim: 'Newco signed SECRET-CONTRACT', visibility: 'private' }, 'Newco is public'],
diff --git a/test/e2e/managed-import-statement-budget.test.ts b/test/e2e/managed-import-statement-budget.test.ts
index 5056943f40..9620f8f2d9 100644
--- a/test/e2e/managed-import-statement-budget.test.ts
+++ b/test/e2e/managed-import-statement-budget.test.ts
@@ -27,8 +27,8 @@ import { byText, chunkOf, CHUNKED, PAGE_SLUG, prepareManagedImport, publicationO
import type { YcShapedPage } from '../helpers/yc-shaped-page.ts';
import { withEnv } from '../helpers/with-env.ts';
-/** About 10% over the import's own statements in the publication transaction at 1x (#6712 L6 measured 67 on Postgres; 317 before code references were batched); the folded stamp is budgeted apart. */
-const PUBLICATION_BUDGET = 74;
+/** About 10% over the import's own statements in the publication transaction at 1x (#6712 L6 measured 67 on Postgres; 317 before code references were batched); the folded stamp is budgeted apart. GBRA-161 PR 2 adds five for the fact fence generation (its lock, its live read, the generation row, its items in one statement, and the held and attempts clear); on a first import its retire read replaces the expire update. */
+const PUBLICATION_BUDGET = 79;
/**
* #6712 PR 4b: the folded pass stamp, budgeted on its own inside the same transaction (about 10% over 17 measured on
* Postgres). A writeback import publishes the source checkpoint here instead of as a separate checkpoint request, so these
diff --git a/test/fixtures/fold-hook-noop-6712.json b/test/fixtures/fold-hook-noop-6712.json
index 2cf51abf0c..96aab5eedb 100644
--- a/test/fixtures/fold-hook-noop-6712.json
+++ b/test/fixtures/fold-hook-noop-6712.json
@@ -33,8 +33,8 @@
"UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS NULL RETURNING id",
"UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND source_path=$3 AND database_only_reason='origin_twin'",
"UPDATE pages SET source_kind=$3,ingested_via=$4,ingested_at=$5::timestamptz WHERE source_id=$1 AND slug=$2",
+ "SELECT jsonb_build_object('id', f.id, 'row_num', f.row_num, 'fact', f.fact, 'visibility', f.visibility, 'kind', f.kind, 'entity_slug', f.entity_slug, 'source', f.source, 'expired_at', f.expired_at, 'valid_from', f.valid_from, 'valid_until', f.valid_until, 'superseded_by', f.superseded_by, 'consolidated_at', f.consolidated_at, 'consolidated_into', f.consolidated_into, 'attributed_to', f.attributed_to) AS preimage FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility) ORDER BY f.row_num, f.id",
"SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) ORDER BY f.row_num FOR UPDATE",
- "UPDATE facts f SET expired_at=COALESCE(expired_at,now()),row_num=NULL WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)",
"DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text,removed boolean) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source AND t.summary=d.summary AND t.detail=d.detail RETURNING t.date::text AS date, d.removed",
"UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail",
"SELECT k.row_num FROM takes k JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) ORDER BY k.row_num LIMIT $3",
@@ -98,8 +98,8 @@
"INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image, embedding_pending_since, projected_byte_start, projected_byte_end) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector, CASE WHEN c.embedding IS NULL THEN now() ELSE NULL END, c.projected_byte_start, c.projected_byte_end FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text, projected_byte_start bigint, projected_byte_end bigint) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding\" IS NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL AND EXCLUDED.\"embedding\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, projected_byte_start = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.projected_byte_start ELSE COALESCE(EXCLUDED.projected_byte_start, content_chunks.projected_byte_start) END, projected_byte_end = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.projected_byte_end ELSE COALESCE(EXCLUDED.projected_byte_end, content_chunks.projected_byte_end) END, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image), embedding_pending_since = CASE WHEN EXCLUDED.\"embedding\" IS NOT NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL THEN COALESCE(content_chunks.embedding_pending_since, now()) WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN now() ELSE content_chunks.embedding_pending_since END",
"UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND database_only_reason='unbound_source'",
"WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 ORDER BY (p.slug=$1) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, wd.snapshot_withdrawals, wd.snapshot_global_purges, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline FROM chosen p CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges) wd",
+ "SELECT jsonb_build_object('id', f.id, 'row_num', f.row_num, 'fact', f.fact, 'visibility', f.visibility, 'kind', f.kind, 'entity_slug', f.entity_slug, 'source', f.source, 'expired_at', f.expired_at, 'valid_from', f.valid_from, 'valid_until', f.valid_until, 'superseded_by', f.superseded_by, 'consolidated_at', f.consolidated_at, 'consolidated_into', f.consolidated_into, 'attributed_to', f.attributed_to) AS preimage FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility) ORDER BY f.row_num, f.id",
"SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) ORDER BY f.row_num FOR UPDATE",
- "UPDATE facts f SET expired_at=COALESCE(expired_at,now()),row_num=NULL WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)",
"DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text,removed boolean) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source AND t.summary=d.summary AND t.detail=d.detail RETURNING t.date::text AS date, d.removed",
"UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail",
"SELECT k.row_num FROM takes k JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) ORDER BY k.row_num LIMIT $3",
@@ -158,15 +158,15 @@
"INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image, embedding_pending_since, projected_byte_start, projected_byte_end) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector, CASE WHEN c.embedding IS NULL THEN now() ELSE NULL END, c.projected_byte_start, c.projected_byte_end FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text, projected_byte_start bigint, projected_byte_end bigint) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\"",
"SELECT id, slug, source_path, deleted_at FROM pages WHERE source_id=$1 AND slug=$2",
"UPDATE pages SET source_kind=$3,ingested_via=$4,ingested_at=$5::timestamptz WHERE source_id=$1 AND slug=$2",
- "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) ORDER BY f.row_num FOR UPDATE",
+ "SELECT jsonb_build_object('id', f.id, 'row_num', f.row_num, 'fact', f.fact, 'visibility', f.visibility, 'kind', f.kind, 'entity_slug', f.entity_slug, 'source', f.source, 'expired_at', f.expired_at, 'valid_from', f.valid_from, 'valid_until', f.valid_until, 'superseded_by', f.superseded_by, 'consolidated_at', f.consolidated_at, 'consolidated_into', f.consolidated_into, 'attributed_to', f.attributed_to) AS preimage FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility) ORDER BY f.row_num, f.id",
"SELECT local_path, config->>'slug_root_mode' AS mode FROM sources WHERE id=$1",
- "UPDATE facts f SET expired_at=COALESCE(expired_at,now()),row_num=NULL WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)",
+ "SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) ORDER BY f.row_num FOR UPDATE",
+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",
"DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text,removed boolean) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source AND t.summary=d.summary AND t.detail=d.detail RETURNING t.date::text AS date, d.removed",
"UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail",
- "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",
+ "SELECT slug, source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path=ANY($2::text[]) AND id<>$3 ORDER BY slug",
"SELECT k.row_num FROM takes k JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) ORDER BY k.row_num LIMIT $3",
"DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])",
- "SELECT slug, source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path=ANY($2::text[]) AND id<>$3 ORDER BY slug",
"UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS NULL RETURNING id",
"UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND source_path=$3 AND database_only_reason='origin_twin'",
"WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 AND p.deleted_at IS NULL ORDER BY (p.slug=$1) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, wd.snapshot_withdrawals, wd.snapshot_global_purges, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline FROM chosen p CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',co",
@@ -232,8 +232,8 @@
"UPDATE pages SET chunker_version=$5, text_projection_revision=CASE WHEN knowledge_revision=$4::uuid THEN knowledge_revision ELSE text_projection_revision END, search_vector=CASE WHEN knowledge_revision=$4::uuid THEN setweight(to_tsvector('english',gbrain_fts_input(COALESCE(title,''))),'A') || setweight(to_tsvector('english',gbrain_fts_input(left($3::text,65536))),'C') ELSE search_vector END WHERE source_id=$1 AND slug=$2 RETURNING id",
"SELECT COALESCE((completed_keys->0->>'count')::int,0) AS count FROM op_checkpoints WHERE op=$1 AND fingerprint=$2",
"INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()",
+ "SELECT jsonb_build_object('id', f.id, 'row_num', f.row_num, 'fact', f.fact, 'visibility', f.visibility, 'kind', f.kind, 'entity_slug', f.entity_slug, 'source', f.source, 'expired_at', f.expired_at, 'valid_from', f.valid_from, 'valid_until', f.valid_until, 'superseded_by', f.superseded_by, 'consolidated_at', f.consolidated_at, 'consolidated_into', f.consolidated_into, 'attributed_to', f.attributed_to) AS preimage FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility) ORDER BY f.row_num, f.id",
"SELECT f.id, f.row_num, f.fact, f.visibility, f.trust_tier FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND (COALESCE(f.source, '') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num = f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer, fact text, visibility text) WHERE n.row_num = f.row_num AND n.fact = f.fact AND n.visibility = f.visibility) AND (CASE f.trust_tier WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) > (CASE COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown') WHEN 'user_confirmed' THEN 6 WHEN 'operator_curated' THEN 5 WHEN 'tool_observed' THEN 4 WHEN 'agent_written' THEN 3 WHEN 'unknown' THEN 2 WHEN 'external_untrusted' THEN 1 ELSE 0 END) ORDER BY f.row_num FOR UPDATE",
- "UPDATE facts f SET expired_at=COALESCE(expired_at,now()),row_num=NULL WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%' OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num)) AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text) WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)",
"DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text,removed boolean) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source AND t.summary=d.summary AND t.detail=d.detail RETURNING t.date::text AS date, d.removed",
"UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail",
"SELECT k.row_num FROM takes k JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) ORDER BY k.row_num LIMIT $3",
diff --git a/test/helpers/belief-ledger.ts b/test/helpers/belief-ledger.ts
index 41e8ab1588..17285d30d6 100644
--- a/test/helpers/belief-ledger.ts
+++ b/test/helpers/belief-ledger.ts
@@ -142,7 +142,7 @@ export async function withFileBeliefBrain(sourceId: string, run: (brain: FileBel
} finally { rmSync(home, { recursive: true, force: true }); }
}
-/** A page body with a facts fence, a takes fence, prose and wikilinks. */
+/** A page body with a facts fence, a takes fence, prose and wikilinks. A fence is written when its list is given, so an empty list writes the empty fence that retires the stored rows (GBRA-161 PR 2: an omitted fence holds them). */
export function beliefPage(o: { title?: string; type?: string; prose?: string; facts?: Array<string | { claim: string; context?: string; confidence?: string; visibility?: string }>;
takes?: Array<string | { claim: string; weight?: string; since?: string; who?: string }>; links?: string[]; frontmatter?: Record<string, string> } = {}): string {
const fm = { type: o.type ?? 'company', title: o.title ?? 'Acme Example', ...o.frontmatter };
@@ -150,11 +150,11 @@ export function beliefPage(o: { title?: string; type?: string; prose?: string; f
const takes = (o.takes ?? []).map(t => typeof t === 'string' ? { claim: t } : t);
const parts = [`---\n${Object.entries(fm).map(([k, v]) => `${k}: ${v}`).join('\n')}\n---`,
`${o.prose ?? 'Draft.'}${(o.links ?? []).map(l => ` See [[${l}]].`).join('')}`];
- if (facts.length) parts.push(['<!--- gbrain:facts:begin -->', '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',
+ if (o.facts) parts.push(['<!--- gbrain:facts:begin -->', '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',
'|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',
...facts.map((f, i) => `| ${i + 1} | ${f.claim} | fact | ${f.confidence ?? '1.0'} | ${f.visibility ?? 'world'} | medium | 2026-01-01 | | remember | ${f.context ?? ''} |`),
'<!--- gbrain:facts:end -->'].join('\n'));
- if (takes.length) parts.push(['<!--- gbrain:takes:begin -->', '| # | claim | kind | who | weight | since | source |', '|---|-------|------|-----|--------|-------|--------|',
+ if (o.takes) parts.push(['<!--- gbrain:takes:begin -->', '| # | claim | kind | who | weight | since | source |', '|---|-------|------|-----|--------|-------|--------|',
...takes.map((t, i) => `| ${i + 1} | ${t.claim} | take | ${t.who ?? 'brain'} | ${t.weight ?? '0.5'} | ${t.since ?? '2026-07'} | notes |`), '<!--- gbrain:takes:end -->'].join('\n'));
return `${parts.join('\n\n')}\n`;
}
diff --git a/test/managed-import-statement-budget.test.ts b/test/managed-import-statement-budget.test.ts
index 4daead6ae7..15a0872566 100644
--- a/test/managed-import-statement-budget.test.ts
+++ b/test/managed-import-statement-budget.test.ts
@@ -29,8 +29,8 @@ import { byText, chunkOf, CHUNKED, PAGE_SLUG, prepareManagedImport, publicationO
import type { YcShapedPage } from './helpers/yc-shaped-page.ts';
import { withEnv } from './helpers/with-env.ts';
-/** About 10% over the import's own statements in the publication transaction at 1x (#6712 L6 measured 69 on PGLite; 416 before code references were batched); the folded stamp is budgeted apart. */
-const PUBLICATION_BUDGET = 76;
+/** About 10% over the import's own statements in the publication transaction at 1x (#6712 L6 measured 69 on PGLite; 416 before code references were batched); the folded stamp is budgeted apart. GBRA-161 PR 2 adds five for the fact fence generation (its lock, its live read, the generation row, its items in one statement, and the held and attempts clear); on a first import its retire read replaces the expire update. */
+const PUBLICATION_BUDGET = 81;
/**
* #6712 PR 4b: the folded pass stamp, budgeted on its own inside the same transaction (about 10% over 16 measured on
* PGLite). A writeback import publishes the source checkpoint here instead of as a separate checkpoint request, so these
diff --git a/test/persistence-semantic-pages.test.ts b/test/persistence-semantic-pages.test.ts
index ac15200707..7dab1d2fd0 100644
--- a/test/persistence-semantic-pages.test.ts
+++ b/test/persistence-semantic-pages.test.ts
@@ -10,6 +10,7 @@ import type { OperationContext } from '../src/core/ops/contract.ts';
import { renderFactsTable } from '../src/core/facts-fence.ts';
import { renderTakesFence } from '../src/core/takes-fence.ts';
import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { emptyFenceBlock } from '../src/core/generations/fence.ts';
let engine: PGLiteEngine;
const root = mkdtempSync(join(tmpdir(), 'gbrain-semantic-pages-'));
@@ -100,10 +101,19 @@ test('canonical replacement and revert restore facts, takes and timeline from co
const before=(await engine.readPageSnapshot('projections',{sourceId}))!;
expect(await engine.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND expired_at IS NULL',[sourceId,'projections'])).toHaveLength(2);
expect(await engine.executeRaw('SELECT id FROM takes WHERE page_id=$1',[before.page.id])).toHaveLength(2);
+ // GBRA-161 PR 2: a replacement without the fences holds both fence generations (fence_absent) and keeps their rows;
+ // the empty fences are the proof that retires them.
await submit('put_page',{slug:'projections',content:'---\ntitle: Replacement\ntype: note\n---\nReplacement body',expected_revision:before.revision});
+ expect(await engine.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND expired_at IS NULL',[sourceId,'projections'])).toHaveLength(2);
+ expect(await engine.executeRaw('SELECT id FROM takes WHERE page_id=$1',[before.page.id])).toHaveLength(2);
+ expect((await engine.executeRaw<{kind:string;held_reason:string}>("SELECT kind,held_reason FROM derived_generations WHERE source_id=$1 AND owner_key=$2 AND state='held' ORDER BY kind",
+ [sourceId,'page:projections'])).map(row=>[row.kind,row.held_reason])).toEqual([['fact_fence','fence_absent'],['take_fence','fence_absent']]);
+ expect(await engine.getTimeline('projections',{sourceId})).toHaveLength(0);
+ const replaced=(await engine.readPageSnapshot('projections',{sourceId}))!;
+ await submit('put_page',{slug:'projections',content:`---\ntitle: Replacement\ntype: note\n---\nReplacement body\n\n${emptyFenceBlock('facts')}\n${emptyFenceBlock('takes')}`,expected_revision:replaced.revision});
expect(await engine.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND expired_at IS NULL',[sourceId,'projections'])).toHaveLength(0);
expect(await engine.executeRaw('SELECT id FROM takes WHERE page_id=$1',[before.page.id])).toHaveLength(0);
- expect(await engine.getTimeline('projections',{sourceId})).toHaveLength(0);
+ expect(await engine.executeRaw("SELECT 1 FROM derived_generations WHERE source_id=$1 AND owner_key=$2 AND state='held'",[sourceId,'page:projections'])).toHaveLength(0);
const [version]=await engine.executeRaw<{id:number}>('SELECT id FROM page_versions WHERE page_id=$1 AND knowledge_revision=$2::uuid',[before.page.id,before.revision]);
const current=(await engine.readPageSnapshot('projections',{sourceId}))!;
await submit('revert_version',{slug:'projections',version_id:version.id,expected_revision:current.revision});
diff --git a/test/trust-write-gate-drift.test.ts b/test/trust-write-gate-drift.test.ts
index 5dace42574..5db8c3920c 100644
--- a/test/trust-write-gate-drift.test.ts
+++ b/test/trust-write-gate-drift.test.ts
@@ -55,6 +55,9 @@ const EXEMPT: Record<string, string> = {
'src/core/persistence/memory-mutations.ts': 'forget (lifecycle); remember is gated in memory-prepare.ts',
'src/core/repair/captured-facts.ts': 'owner repair of existing rows',
'src/core/repair/consolidate-ties.ts': 'owner repair reopening the validity of existing facts (lifecycle)',
+ 'src/core/repair/duplicate-facts.ts': 'owner repair behind a preview: expires exact duplicates of existing fact rows and points them at the row kept (lifecycle); no new text',
+ 'src/core/generations/adapters/extracted-facts.ts': 'callers gate first and pass only rows the gate inserts or flags (the conversation lane and the backstop decide in conversation-publication.ts and backstop.ts); restore puts back a row\'s own recorded state',
+ 'src/core/generations/adapters/fact-rows.ts': 'generation restore puts back a fact row\'s own recorded before-state (lifecycle); no new text',
'src/core/repair/extractor-facts.ts': 'owner repair of existing rows',
'src/core/repair/redacted-facts.ts': 'owner repair behind a preview hash: puts back into existing fact rows the words a stored source page proves; fenced rows publish through put_page, which runs the gate',
'src/core/repair/facts-rehome.ts': 'owner repair moving existing facts onto their entity page (placement)',