Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-161 PR 2: facts and takes fences, consolidation on the generation primitive
garrytan764bd38770ad
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex af1733c03e..740f683202 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -5,6 +5,7 @@ src/core/persistence/canonical-projections.ts 10 coordinator Facts, takes, timelsrc/core/persistence/derived-retirement-hold.ts 2 contract retireDerivedPages versions, soft-deletes and stamps retired_by/retired_at on derived pages (unmanaged extract_atoms retirement) inside maintenanceTransaction behind the canonical table trigger; it never revives or rewrites content, and the purge hold it defines only keeps rows longer.src/core/generations/adapters/page.ts 1 contract GBRA-161: importPageItem writes a derived page item through importFromContent inside the generation activation's maintenanceTransaction (publish.ts), behind the canonical table trigger; managed brains keep the coordinator path.src/core/generations/adapters/atoms.ts 1 contract GBRA-161: the unmanaged atom completion flip (source_hash) runs in the generation activation's maintenanceTransaction after every atom and provenance edge was written and before the items are rechecked live; managed brains keep the coordinator path.+src/core/generations/adapters/fact-rows.ts 1 contract GBRA-161 PR 2: restoreFactRow puts a recorded fact before-state back (lifecycle, consolidation marks, fence row number) only inside a generation restore maintenanceTransaction, matched on id, claim and visibility; managed brains refuse generation restores.src/core/persistence/links-maintenance.ts 1 coordinator Managed extract --stale and post-sync extraction add only the coordinator's unrecorded canonical timeline tuples inside a revision-bound withCoordinatedWrite transaction that also replaces the page's derived links and stamps its watermark.src/core/extract-takes-from-pages.ts 0 coordinator Managed bootstrap submits one revision-checked put_page per source page so its complete takes fence and projected rows commit together; unmanaged writes retain the md-first helper.src/core/persistence/origin-guard.ts 2 engine_guard #6948 bindOrigin records a page origin (and drops an origin_twin marker) only after assertOriginUnclaimed holds the origin advisory lock inside the caller's engine.transaction(); callers are the guarded publication applies and repairs.diff --git a/src/commands/doctor/checks/generations.ts b/src/commands/doctor/checks/generations.tsindex ccfbdb51ef..72be9e2e02 100644--- a/src/commands/doctor/checks/generations.ts+++ b/src/commands/doctor/checks/generations.ts@@ -21,6 +21,7 @@ import { readGenerationsConfig } from '../../../core/generations/config.ts';import { RELEASABLE_HELD_REASONS, type HeldReason } from '../../../core/generations/contract.ts';import { generationsPreviewArgv } from '../../../core/generations/repair.ts';import { listOrphanCandidates, listPendingMembers } from '../../../core/generations/managed.ts';+import { fenceHoldEntries } from '../../../core/generations/fence.ts';const DOCS = 'docs/guides/repair.md#generations';@@ -64,6 +65,16 @@ export async function generationHeldCheck(engine: BrainEngine, sourceIds?: strinconst count = byReason.reduce((sum, row) => sum + row.count, 0);const details = { count, releasable: byReason.filter(row => row.releasable).reduce((sum, row) => sum + row.count, 0), by_reason: byReason, repair: 'generations', docs: DOCS };if (!count) return { name: 'generation_held', status: 'ok', details, message: 'No derived generation is held.' };+ const fences = await fenceHoldEntries(engine, sources);+ if (fences.length) {+ const fence = fences[0]!;+ return { name: 'generation_held', status: 'warn', details: { ...details, fence_holds: fences.map(({ fix: _fix, ...hold }) => hold) },+ message: `${count} derived result(s) were held instead of published (${byReason.map(row => `${row.source_id}/${row.kind} ${row.held_reason}: ${row.count}`).join('; ')}); `+ + 'the previous generation of each key stays live and nothing was retired. '+ + `${fences.length} page(s) lost a facts or takes fence (first: ${fence.slug} in ${fence.source_id}, ${fence.kind} ${fence.reason}, ${fence.rows} row(s) kept); `+ + 'whether to restore the section or retire its rows is the user\'s decision.',+ fix: fence.fix };+ }const first = byReason.find(row => row.releasable) ?? byReason[0]!;const preview = generationsPreviewArgv({ kind: first.kind, sourceId: first.source_id }, 'release-held');return { name: 'generation_held', status: 'warn', details,diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.tsindex 659960bbf3..4f4cb10416 100644--- a/src/commands/sync/operator.ts+++ b/src/commands/sync/operator.ts@@ -151,7 +151,8 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promisconst notifier = notifierBlock && { ...notifierBlock, fix: notifierBlock.fix ? renderAction(notifierBlock.fix, ctx) : null };const read = (r: typeof status.cursors_read) => r.status === 'read' ? r : { ...r, fix: renderAction(r.fix, ctx) };const rendered = { ...status, holds: status.holds.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })),- git_push_holds: status.git_push_holds.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })), next: status.next ? renderAction(status.next, ctx) : null,+ git_push_holds: status.git_push_holds.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })),+ fence_holds: status.fence_holds.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })), next: status.next ? renderAction(status.next, ctx) : null,checkpoint_blockers_read: read(status.checkpoint_blockers_read), cursors_read: read(status.cursors_read), terminal_failures_read: read(status.terminal_failures_read),landing_read: read(status.landing_read), landing: status.landing?.status === 'ok' ? { ...status.landing, pages: status.landing.pages.map(page => ({ ...page, fix: page.fix ? renderAction(page.fix, ctx) : null })) } : status.landing,capacity: { status: snapshot.status, pause_pct: snapshot.pause_pct, low: snapshot.low, paused: snapshot.paused }, freshness, notifier, ...(notices.length ? { notices } : {}) };@@ -185,6 +186,7 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promis+ `${landing.gaps ? ` (${Object.entries(landing.by_state).map(([state, n]) => `${state} ${n}`).join(', ')})` : ''}`);for (const page of landing.pages) console.log(` ${page.slug}: ${page.state}, synced ${page.age_seconds} s ago${page.fix?.argv ? `; fix: ${page.fix.argv.join(' ')}` : ''}`);} else if (landing) console.log(` synced but not searchable: ${landing.status} (${landing.reason})`);+ for (const hold of status.fence_holds) console.log(` ${hold.kind} held (${hold.reason}) on ${hold.slug}: ${hold.rows} row(s) kept live; ASK THE USER: ${hold.fix.user_message ?? hold.fix.why}`);for (const hold of status.git_push_holds) console.log(` git backups not pushed: ${hold.retrying} retrying, ${hold.parked} parked (${hold.codes.join(', ')}) since ${hold.oldest_at}${hold.conflict ? `; CONFLICT in ${hold.conflict.paths.join(', ')} needs a person` : ''}`);const connector = status.connector_last_error;if (connector) console.log(` connector: ${connector.stopped ? 'STOPPED, ' : ''}the last ${connector.consecutive} run(s) ended on ${connector.code}${connector.slug ? ` at ${connector.slug}` : ''}: ${connector.message}`);diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex c363570794..2f96afff23 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -83,6 +83,8 @@ 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 { factFenceItems, factPreimages, factRetireItem } from '../generations/adapters/fact-rows.ts';import { segmentedBodyMatchesFile, segmentedFactsFenceView } from '../page-body/segment-facts.ts';import {duplicateActiveFenceRows,@@ -375,6 +377,8 @@ type PageFenceInput = { id?: number; slug?: string; source_id?: string; body_stointerface FenceReconcilePlan {/** Rows the parsed fence carries (duplicates included), for the pages-with-facts count. */fenceRows: number;+ /** GBRA-161 PR 2: what the reconcile read of the fence; only a fence read whole retires rows (fence.ts). */+ read: FenceRead;extracted: FenceExtractedFact[];matched: Map<number, ExistingPageFact>;stale: ExistingPageFact[];@@ -458,7 +462,8 @@ async function planFenceReconcile(db: BrainEngine, page: PageFenceInput, slug: sreturn resolveSupersession(f, byRow, chain, slug).superseded_by === (stored == null ? null : Number(stored));});}- return { fenceRows: parsed.facts.length, extracted, matched, stale, updates, toInsert, chain, inSync };+ const read: FenceRead = isSegmentedPage(page) ? { state: 'segmented' } : readFenceBlocks(page, 'facts');+ return { fenceRows: parsed.facts.length, read, extracted, matched, stale, updates, toInsert, chain, inSync };}/**@@ -480,7 +485,16 @@ function reconcileWrites(plan: FenceReconcilePlan) {/** One page's reconcile writes, inside a transaction that holds the page key. */async function writeFenceReconcile(tx: BrainEngine, sourceId: string, slug: string, plan: FenceReconcilePlan,- writes: ReturnType<typeof reconcileWrites>, signal?: AbortSignal): Promise<{ inserted: number; updated: number; warnings: string[]; write_gate?: GateTally }> {+ writes: ReturnType<typeof reconcileWrites>, signal?: AbortSignal): Promise<{ inserted: number; updated: number; deleted: number; held?: true; warnings: string[]; write_gate?: GateTally }> {+ // GBRA-161 PR 2: the fact generation decides before any row changes. A fence that is absent or not read whole holds+ // (`fence_absent`) and the page's rows stay exactly as they are; a published one records each retired row's before-state.+ const retiring = [...writes.detach, ...writes.expireInPlace].map(f => Number(f.id));+ const generation = await publishFenceGeneration(tx, { kind: FACT_FENCE_KIND, sourceId, slug, read: plan.read, items: factFenceItems(plan.extracted),+ retire: (await factPreimages(tx, sourceId, retiring)).map(factRetireItem), writer: 'extract_facts' });+ if (generation.state === 'held') {+ return { inserted: 0, updated: 0, deleted: 0, held: true, warnings: [`${slug}: FACTS_FENCE_HELD: ${generation.reason}: the page's facts fence is ${plan.read.state}, so its `+ + `${retiring.length} fact row(s) were kept, not retired; gbrain doctor --only generation_held names the user's choice (restore the fence or write an empty one)`] };+ }const tally = emptyGateTally();// #5575 I2: the fence rows restate the page (no model), so every write here is at the page's tier, capped at operator_curated.const derivation = await deriveTrust(tx, [{ table: 'pages', sourceId, slug }], { channel: 'derive:facts_fence', projection: true });@@ -515,7 +529,7 @@ async function writeFenceReconcile(tx: BrainEngine, sourceId: string, slug: striconst linked = await syncSupersession(tx, sourceId, slug, plan.extracted, plan.chain, insertedRows);signal?.throwIfAborted();const updated = new Set([...plan.updates.map(f => f.row_num), ...linked.changed.filter(row => !insertedRows.has(row))]);- return { inserted: inserted.inserted, updated: updated.size, warnings: linked.warnings, ...(mergeGateTally(tally, undefined) ? { write_gate: tally } : {}) };+ return { inserted: inserted.inserted, updated: updated.size, deleted: retiring.length, warnings: linked.warnings, ...(mergeGateTally(tally, undefined) ? { write_gate: tally } : {}) };});}@@ -582,8 +596,7 @@ export async function prepareFenceFactsReconcile(engine: BrainEngine, row: Write}const writes = reconcileWrites(plan);const written = await writeFenceReconcile(tx, row.source_id, row.slug, plan, writes);- return { status: 'completed', ...written, deleted: writes.detach.length + writes.expireInPlace.length, deferred: writes.deferInserts,- warnings: [...warnings, ...written.warnings] };+ return { status: 'completed', ...written, deferred: writes.deferInserts, warnings: [...warnings, ...written.warnings] };} };}@@ -622,15 +635,25 @@ export async function prepareDeletedPageFactsExpiry(engine: BrainEngine, row: Wrawait authorizeWrite(engine, row.authority, 'submit_job', row.slug);return { observedRevision: snapshot.revision, noop: true,validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },- apply: async tx => {- const expired = await tx.executeRaw<{ id: number }>(- `UPDATE facts f SET expired_at = now()- 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 EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND p.id = $3 AND p.deleted_at IS NOT NULL)- RETURNING f.id`,- [row.source_id, row.slug, Number(row.page_id)]);- return { status: 'completed', expired: expired.map(e => Number(e.id)) };- } };+ apply: async tx => ({ status: 'completed', expired: await expireDeletedPageFacts(tx, row.source_id, row.slug, Number(row.page_id)) }) };+}++/**+ * GBRA-161 PR 2: one deleted page's fence rows expire (never detach: a restored page re-matches them) only on+ * `originGone`, which the fact generation rechecks under the page key; a restored page (or one whose id moved) expires+ * nothing. Each expired row's before-state is recorded on the ledger. Returns the expired ids.+ */+async function expireDeletedPageFacts(tx: BrainEngine, sourceId: string, slug: string, pageId: number | null): Promise<number[]> {+ const ids = (await tx.executeRaw<{ id: number }>(+ `SELECT f.id 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 EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND ($3::integer IS NULL OR p.id = $3::integer) AND p.deleted_at IS NOT NULL)`,+ [sourceId, slug, pageId])).map(r => Number(r.id));+ if (!ids.length) return [];+ const generation = await publishFenceGeneration(tx, { kind: FACT_FENCE_KIND, sourceId, slug, read: { state: 'absent' }, items: [], originGone: true,+ retire: (await factPreimages(tx, sourceId, ids)).map(factRetireItem), writer: 'deleted_page' });+ if (generation.state !== 'published') return [];+ return (await tx.executeRaw<{ id: number }>('UPDATE facts SET expired_at = now() WHERE source_id = $1 AND id = ANY($2::bigint[]) AND expired_at IS NULL RETURNING id',+ [sourceId, ids])).map(r => Number(r.id));}export interface ExtractFactsOpts {@@ -895,19 +918,21 @@ export async function runExtractFacts(// forgotten claims expired). Rows of a page that simply has no DB row yet// (a fence write ahead of sync) are untouched.if (!opts.dryRun) {- const expireDeleted = (db: BrainEngine) => db.executeRaw<{ id: number }>(- `UPDATE facts f SET expired_at = now()- WHERE f.source_id = $1 AND f.row_num IS NOT NULL AND f.expired_at IS NULL- AND EXISTS (SELECT 1 FROM pages p- WHERE p.source_id = f.source_id AND p.slug = f.source_markdown_slug- AND p.deleted_at IS NOT NULL)- RETURNING f.id`,- [sourceId],- );+ // GBRA-161 PR 2: one transaction per deleted page, under its key, retiring through the fact generation (originGone).+ const expireDeleted = async () => {+ const expired: Array<{ id: number }> = [];+ for (const slug of await deletedPagesWithActiveFacts(engine, sourceId)) {+ expired.push(...(await maintenanceTransaction(engine, async tx => {+ await tx.lockPageKeys([{ sourceId, slug }]);+ return expireDeletedPageFacts(tx, sourceId, slug, null);+ })).map(id => ({ id })));+ }+ return expired;+ };// Managed: one receipted request per page, rechecked under its key, so a// concurrent restore is either seen as restored or waited for, never// expired underneath it.- const expired = managed ? await expireDeletedPagesManaged(engine, sourceId, managedAuthority, result.warnings) : await maintenanceTransaction(engine, expireDeleted);+ const expired = managed ? await expireDeletedPagesManaged(engine, sourceId, managedAuthority, result.warnings) : await expireDeleted();result.factsExpiredForDeletedPages = expired.length;}@@ -1126,17 +1151,22 @@ export async function runExtractFacts(* A refused page never stops the expiry or the reconcile after it (GBRA-130 A-21): it is a* FACTS_EXPIRE_FAILED warning retried by the next run; a page the refusal breaker holds back is skipped.*/-async function expireDeletedPagesManaged(engine: BrainEngine, sourceId: string,- managedAuthority: () => Promise<MaintenanceAuthority | null>, warnings: string[]): Promise<Array<{ id: number }>> {- const pages = await engine.executeRaw<{ slug: string }>(+/** The soft-deleted pages of `sourceId` that still have active fence rows. */+async function deletedPagesWithActiveFacts(engine: BrainEngine, sourceId: string): Promise<string[]> {+ return (await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT f.source_markdown_slug AS slug FROM facts fWHERE f.source_id = $1 AND f.row_num IS NOT NULL AND f.expired_at IS NULL- AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = f.source_id AND p.slug = f.source_markdown_slug AND p.deleted_at IS NOT NULL)`,+ AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = f.source_id AND p.slug = f.source_markdown_slug AND p.deleted_at IS NOT NULL)+ ORDER BY 1`,[sourceId],- );+ )).map(row => row.slug);+}++async function expireDeletedPagesManaged(engine: BrainEngine, sourceId: string,+ managedAuthority: () => Promise<MaintenanceAuthority | null>, warnings: string[]): Promise<Array<{ id: number }>> {const expired: Array<{ id: number }> = [];const run = new ItemRun('extract_facts.expire_deleted');- for (const { slug } of pages) {+ for (const slug of await deletedPagesWithActiveFacts(engine, sourceId)) {const authority = (await managedAuthority())!;try {expired.push(...(await expireDeletedPageFactsManaged(engine, authority, slug)).map(id => ({ id })));diff --git a/src/core/cycle/extract-takes.ts b/src/core/cycle/extract-takes.tsindex b2b4681b45..a975b89061 100644--- a/src/core/cycle/extract-takes.ts+++ b/src/core/cycle/extract-takes.ts@@ -55,6 +55,8 @@ import { digest } from '../persistence/digest.ts';import { getWriteRequest } from '../persistence/journal.ts';import { maintenancePreflight, submitDatabaseMaintenanceIntent, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';import { opError, OperationError } from '../ops/contract.ts';+import { publishFenceGeneration, readFenceBlocks, TAKE_FENCE_KIND, type FenceRead } from '../generations/fence.ts';+import { takeFenceItems, takeItem, takePreimages } from '../generations/adapters/take-rows.ts';export interface ExtractTakesOpts {/** Brain repo root. Required for source='fs'. */@@ -122,41 +124,52 @@ async function reconcileTier(engine: BrainEngine, pageId: number): Promise<{ tie/*** W1 #6783 §12 (a): of the stored takes a reconcile would delete, those more trusted than the page's restatement or held- * by an open contest stay; each gets the owner's `forget` proposal. Then the rest are deleted.+ * by an open contest stay; each gets the owner's `forget` proposal. Returns the rest, which the take generation retires.*/-async function deleteUnheldTakes(engine: BrainEngine, pageId: number, where: string, params: unknown[], change: HeldChange): Promise<void> {- const candidates = (await engine.executeRaw<{ id: number }>(`SELECT id FROM takes WHERE page_id = $1 AND ${where}`, [pageId, ...params])).map(r => Number(r.id));- if (!candidates.length) return;- const page = await reconcileTier(engine, pageId);- const held = page ? await heldRows(engine, 'takes', candidates, { writer: page.tier, pending: true }) : new Map();- if (page && held.size) await contestHeldRows(engine, { sourceId: page.sourceId, slug: page.slug, table: 'takes', proposer: 'takes_reextract', writer: page.tier,+async function unheldTakes(db: BrainEngine, pageId: number, where: string, params: unknown[], change: HeldChange): Promise<number[]> {+ const candidates = (await db.executeRaw<{ id: number }>(`SELECT id FROM takes WHERE page_id = $1 AND ${where}`, [pageId, ...params])).map(r => Number(r.id));+ if (!candidates.length) return [];+ const page = await reconcileTier(db, pageId);+ const held = page ? await heldRows(db, 'takes', candidates, { writer: page.tier, pending: true }) : new Map();+ if (page && held.size) await contestHeldRows(db, { sourceId: page.sourceId, slug: page.slug, table: 'takes', proposer: 'takes_reextract', writer: page.tier,rows: [...held].map(([id, tier]) => ({ id, tier, change })) });- const ids = candidates.filter(id => !held.has(id));- if (ids.length) await engine.executeRaw('DELETE FROM takes WHERE id = ANY($1::bigint[])', [ids]);+ return candidates.filter(id => !held.has(id));}/**- * Remove takes whose rows left the page's fence. Only a fence that parsed- * cleanly is authoritative (a skipped malformed row is not a deletion), and a- * page without a fence keeps whatever the index holds.+ * Remove takes whose rows left the page's fence (and, under rebuild, rows whose claim diverged; rows that still match keep+ * resolution and vector). Only a fence that parsed cleanly is authoritative (a skipped malformed row is not a deletion),+ * and a page without a takes marker keeps whatever the index holds. GBRA-161 PR 2: the deletions, and the takes the upsert+ * will replace at their row number (B-19), go through the take generation first, which records each full row; a fence+ * that is not read whole (a marker only in code, a segmented page) holds and nothing is deleted or upserted. Returns+ * false when held. `inTx`: `db` is the caller's transaction; otherwise the deletes run in their own.*/-async function pruneRemovedTakes(- engine: BrainEngine,- pageId: number,- hasBegin: boolean,- takes: ParsedTake[],- warnings: string[],- dryRun: boolean,-): Promise<void> {- if (dryRun || warnings.length > 0 || !hasBegin) return;- await deleteUnheldTakes(engine, pageId, 'NOT (row_num = ANY($2::integer[]))', [takes.map(t => t.rowNum)], 'removed');+async function reconcileTakesGeneration(db: BrainEngine, inTx: boolean, page: { id: number; slug: string; source_id: string }, read: FenceRead, takes: ParsedTake[],+ warnings: string[], rebuild: boolean, dryRun: boolean, hasBegin: boolean, result: ExtractTakesResult): Promise<boolean> {+ if (dryRun || warnings.length > 0) return true;+ const prune = async (tx: BrainEngine): Promise<boolean> => {+ const ids = hasBegin ? [...new Set([...await unheldTakes(tx, page.id, 'NOT (row_num = ANY($2::integer[]))', [takes.map(t => t.rowNum)], 'removed'),+ ...(rebuild ? await unheldTakes(tx, page.id, `NOT EXISTS (+ SELECT 1 FROM jsonb_to_recordset($2::text::jsonb) AS f(row_num int, claim text) WHERE f.row_num = takes.row_num AND f.claim = takes.claim)`,+ [JSON.stringify(takes.map(t => ({ row_num: t.rowNum, claim: t.claim })))], 'replaced') : [])])] : [];+ const before = await takePreimages(tx, page.id, ids, takes);+ const outcome = await publishFenceGeneration(tx, { kind: TAKE_FENCE_KIND, sourceId: page.source_id, slug: page.slug, read, items: takeFenceItems(takes),+ retire: before.gone.map(row => takeItem(row)), overwrite: before.replaced.map(row => takeItem(row, takeFenceItems(takes.filter(t => t.rowNum === Number(row.row_num)))[0]?.key)),+ writer: 'extract_takes' });+ if (outcome.state === 'held') {+ result.warnings.push(`${page.slug}: TAKES_FENCE_HELD: ${outcome.reason}: the page's takes fence is ${read.state}, so its ${ids.length} take row(s) were kept and nothing was upserted; `+ + 'gbrain doctor --only generation_held names the user\'s choice (restore the fence or write an empty one)');+ return false;+ }+ if (ids.length) await tx.executeRaw('DELETE FROM takes WHERE id = ANY($1::bigint[])', [ids]);+ return true;+ };+ return inTx ? prune(db) : maintenanceTransaction(db, prune);}-/** Rebuild: drop indexed rows the fence no longer carries with the same claim; rows that still match keep resolution and vector. */-async function deleteDivergedTakes(engine: BrainEngine, pageId: number, takes: ParsedTake[]): Promise<void> {- await deleteUnheldTakes(engine, pageId, `NOT EXISTS (- SELECT 1 FROM jsonb_to_recordset($2::text::jsonb) AS f(row_num int, claim text) WHERE f.row_num = takes.row_num AND f.claim = takes.claim)`,- [JSON.stringify(takes.map(t => ({ row_num: t.rowNum, claim: t.claim })))], 'replaced');+/** What a takes reconcile read of the page's fence: segmented bodies are never read whole here (fence.ts). */+function takesFenceRead(page: { body_storage?: BodyStorage | null; compiled_truth: string | null; timeline: string | null }): FenceRead {+ return isSegmentedPage(page) ? { state: 'segmented' } : readFenceBlocks(page, 'takes');}function parsedTakeToBatchInput(pageId: number, t: ParsedTake): TakeBatchInput {@@ -292,11 +305,10 @@ export async function extractTakesFromFs(}// #6259: the stored page decides (the gate stamps quarantine on it); a quarantined page projects no takes.if ((await engine.executeRaw('SELECT 1 FROM pages WHERE id=$1 AND frontmatter ? $2', [pageId, QUARANTINE_KEY])).length) continue;- await pruneRemovedTakes(engine, pageId, body.includes(TAKES_FENCE_BEGIN), takes, warnings, dryRun);+ if (!await reconcileTakesGeneration(engine, false, { id: pageId, slug, source_id: sourceId }, readFenceBlocks({ compiled_truth: body, timeline: '' }, 'takes'),+ takes, warnings, opts.rebuild === true, dryRun, body.includes(TAKES_FENCE_BEGIN), result)) continue;if (takes.length === 0) continue;- if (opts.rebuild && !dryRun) await deleteDivergedTakes(engine, pageId, takes);-result.pagesWithTakes++;for (const t of takes) {buffer.push(parsedTakeToBatchInput(pageId, t));@@ -355,12 +367,12 @@ export async function extractTakesFromDb(}if (covered.has(source_id)) {await withUnmanagedBeliefs(engine, source_id, [slug], 'takes_reextract', run => maintenanceTransaction(engine, tx => run(tx, async () => {- const takes = await reconcilePageTakes(tx, page.id, read, slug, rebuild, false, result);+ const takes = await reconcilePageTakes(tx, true, page, read, slug, rebuild, false, result);result.takesUpserted += await upsertProjectedTakes(engine, takes.map(t => parsedTakeToBatchInput(page.id, t)), result, tx);})));continue;}- const takes = await reconcilePageTakes(engine, page.id, read, slug, rebuild, dryRun, result);+ const takes = await reconcilePageTakes(engine, false, page, read, slug, rebuild, dryRun, result);for (const t of takes) {buffer.push(parsedTakeToBatchInput(page.id, t));if (buffer.length >= BATCH_SIZE) await flushBatch(engine, buffer, result, dryRun);@@ -386,7 +398,8 @@ async function readPageTakes(engine: BrainEngine, page: TakesPage): Promise<Stre*/async function reconcilePageTakes(db: BrainEngine,- pageId: number,+ inTx: boolean,+ page: TakesPage,read: StreamedTakes,slug: string,rebuild: boolean,@@ -403,9 +416,8 @@ async function reconcilePageTakes(result.failedFiles.push({ path: slug, error: w });}}- await pruneRemovedTakes(db, pageId, read.hasBegin, takes, warnings, dryRun);+ if (!await reconcileTakesGeneration(db, inTx, page, takesFenceRead(page), takes, warnings, rebuild, dryRun, read.hasBegin, result)) return [];if (takes.length === 0) return [];- if (rebuild && !dryRun) await deleteDivergedTakes(db, pageId, takes);result.pagesWithTakes++;return takes;}@@ -511,7 +523,7 @@ export async function prepareTakesReextract(engine: BrainEngine, row: WriteReque`SELECT ${TAKES_PAGE_COLUMNS} FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL`, [row.source_id, row.slug]);const local: ExtractTakesResult = { pagesScanned: 0, pagesWithTakes: 0, takesUpserted: 0, warnings: [], failedFiles: [] };const read = page && (isSegmentedPage(page) ? segmented : await readPageTakes(tx, page));- const takes = page && read ? await reconcilePageTakes(tx, page.id, read, row.slug, rebuild, false, local) : [];+ const takes = page && read ? await reconcilePageTakes(tx, true, page, read, row.slug, rebuild, false, local) : [];const upserted = takes.length ? await upsertProjectedTakes(tx, takes.map(t => takesPreparation.toCanonicalBatchInput(page!.id, t)), local, tx) : 0;return { status: 'completed', takes_upserted: upserted, with_takes: local.pagesWithTakes > 0, ...(local.writeGate ? { write_gate: local.writeGate } : {}),warnings: local.warnings.map(w => w.slice(row.slug.length + 2)) };diff --git a/src/core/cycle/phases/consolidate.ts b/src/core/cycle/phases/consolidate.tsindex f452d4a4ae..cc0d7087f3 100644--- a/src/core/cycle/phases/consolidate.ts+++ b/src/core/cycle/phases/consolidate.ts@@ -33,6 +33,7 @@ import { createHash } from 'node:crypto';import { isAborted } from '../../abort-check.ts';import { classifyItemFailure, ItemRun } from '../../item-failure.ts';import { maintenancePreflight, submitMaintenanceConsolidation } from '../../persistence/prepared-maintenance.ts';+import { clearConsolidationTies, consolidationRestored, factPreimages, holdConsolidationTie, recordConsolidationGeneration } from '../../generations/adapters/fact-rows.ts';import { managedPersistenceEnabled } from '../../persistence/ownership.ts';import { declareDerivation, derivedMaintenanceTransaction, derivedWriteTrust, isExternalTier, readTaintInputs } from '../../trust/taint.ts';import { DEFAULT_WRITE_GATE_CONFIG, type WriteGateConfig } from '../../write-gate.ts';@@ -263,11 +264,20 @@ export async function runPhaseConsolidate([pageId],);let nextRowNum = (rowMaxRows[0]?.max ?? 0) + 1;+ const recordsTies = !dryRun && !maintenance;+ if (recordsTies) await clearConsolidationTies(engine, b.source_id, b.entity_slug);for (const cluster of clusters) {if (cluster.length < 2) continue;const tie = clusterTie(cluster, claims);- if (tie) { clustersHeldSameInstant += 1; if (sameInstantClusters.length < SAME_INSTANT_SAMPLES) sameInstantClusters.push(heldCluster(b, tie)); continue; }+ if (tie) {+ clustersHeldSameInstant += 1;+ if (sameInstantClusters.length < SAME_INSTANT_SAMPLES) sameInstantClusters.push(heldCluster(b, tie));+ if (recordsTies) await engine.transaction(tx => holdConsolidationTie(tx, b.source_id, b.entity_slug, cluster.map(f => f.id),+ { entity_slug: b.entity_slug, tied: tie.ids, valid_from: new Date(tie.at).toISOString(), metric: tie.metric }));+ continue;+ }+ if (await consolidationRestored(engine, b.source_id, b.entity_slug, cluster.map(f => f.id))) continue;// Take selection: pick the highest-confidence fact's text as the// take claim (v0.31 deterministic). v0.32 will swap to a Sonnet// synthesis pass.@@ -380,10 +390,10 @@ export async function runPhaseConsolidate(if (gate) await recordFlaggedRow(tx, gate, { table: 'takes', id: takeId, sourceId: b.source_id });}- // Mark all contributing facts consolidated.+ const before = await factPreimages(tx, b.source_id, cluster.map(f => f.id));for (const f of cluster) await tx.consolidateFact(f.id, takeId);-await writeValidUntilChain(tx, cluster);+ await recordConsolidationGeneration(tx, b.source_id, b.entity_slug, before);return { result: { created, takeId }, rows: [{ table: 'takes' as const, id: Number(takeId), sourceId: b.source_id }] };});if (written?.created) nextRowNum += 1;diff --git a/src/core/generations/adapters/fact-rows.ts b/src/core/generations/adapters/fact-rows.tsnew file mode 100644index 0000000000..b6678d8463--- /dev/null+++ b/src/core/generations/adapters/fact-rows.ts@@ -0,0 +1,196 @@+/**+ * GBRA-161 PR 2: the fact-rows adapter. Fence-projected facts (`fact_fence`, one owner key per page) and consolidation+ * chains (`consolidation`, one owner key per cluster) are rows of the facts table, so they share the before-state they+ * record and the one writer that puts it back.+ *+ * - `fact_fence`: the page's `## Facts` fence is the generation (fence.ts). Every writer that retires fence rows (the page+ * publication's projection, extract_facts, the deleted-page expiry) asks `publishFenceGeneration` first and records each+ * retired row's before-state; a restore transplants the earlier fence block (generations/repair.ts) and re-attaches the+ * retired rows of that block by id instead of inserting copies.+ * - `consolidation`: the dream consolidate phase closes the older members of a cluster at the next member's+ * `valid_from` (`valid_until`) and marks them consolidated. A cluster whose members are not in strict chronological+ * order is held (`tie`, #6023); a strict chain records each member's `valid_until`, `consolidated_at` and+ * `consolidated_into` before it changes them, and `gbrain repair generations --kind consolidation --mode restore` puts+ * them back.+ */+import type { BrainEngine } from '../../engine.ts';+import { digest } from '../../persistence/digest.ts';+import { readGenerationsConfig } from '../config.ts';+import type { GenerationAdapter, GenerationKey, ItemRow } from '../contract.ts';+import { factRowIdentity, fenceRowKey, FACT_FENCE_KIND, publishFenceGeneration, type FenceGenerationOutcome, type FenceItem, type FenceRead } from '../fence.ts';+import { activateGeneration, generationKeyLock, itemSetHash, readLiveGeneration, recordHeld } from '../publish.ts';++export const CONSOLIDATION_KIND = 'consolidation';++/** The columns a fact's before-state keeps. */+const FACT_PREIMAGE_SQL = `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)`;++export type FactPreimage = { id: number; row_num: number | null; fact: string; visibility: string; expired_at: string | null; valid_until: string | null;+ superseded_by: number | null; consolidated_at: string | null; consolidated_into: number | null };++/** The fence rows of the new generation (one per row number; a duplicate number keeps its first row, as the reconcile does). */+export function factFenceItems(rows: ReadonlyArray<{ row_num: number; fact: string; visibility?: string | null }>): FenceItem[] {+ const seen = new Set<number>();+ return rows.flatMap(row => {+ const rowNum = Number(row.row_num);+ if (seen.has(rowNum)) return [];+ seen.add(rowNum);+ const identityHash = factRowIdentity({ row_num: rowNum, fact: row.fact, visibility: row.visibility ?? 'private' });+ return [{ key: fenceRowKey(rowNum, identityHash), identityHash }];+ });+}++/** A stored fact a writer would retire: keyed by id, with its before-state. */+export function factRetireItem(preimage: FactPreimage): FenceItem {+ return { key: `fact:${preimage.id}`, preimage: preimage as unknown as Record<string, unknown>,+ identityHash: factRowIdentity({ row_num: Number(preimage.row_num ?? 0), fact: preimage.fact, visibility: preimage.visibility }) };+}++/** Before-states of the facts `ids` of `sourceId`. */+export async function factPreimages(db: BrainEngine, sourceId: string, ids: readonly number[]): Promise<FactPreimage[]> {+ if (!ids.length) return [];+ return (await db.executeRaw<{ preimage: FactPreimage }>(`SELECT ${FACT_PREIMAGE_SQL} AS preimage FROM facts f WHERE f.source_id=$1 AND f.id = ANY($2::bigint[]) ORDER BY f.id`,+ [sourceId, [...ids]])).map(row => row.preimage);+}++/**+ * The page publication's fence projection (persistence/canonical-projections.ts): the rows it would expire and detach+ * are those attached to the page that the incoming fence no longer holds at the same number and claim (conversation+ * 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> {+ 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%'+ 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`, [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,+ items: factFenceItems(input.rows), retire, writer: input.writer });+}++/**+ * Puts a fact's recorded before-state back: lifecycle (`expired_at`, `valid_until`, `superseded_by`), consolidation+ * marks, and its fence position when that number is free. Only a row whose claim and visibility still match is changed;+ * returns whether it was.+ */+export async function restoreFactRow(tx: BrainEngine, sourceId: string, preimage: Record<string, unknown>): Promise<boolean> {+ const p = preimage as unknown as FactPreimage;+ const rows = await tx.executeRaw<{ id: number }>(`UPDATE facts f SET expired_at=$4::timestamptz, valid_until=$5::timestamptz, superseded_by=$6::bigint,+ consolidated_at=$7::timestamptz, consolidated_into=$8::bigint,+ row_num=CASE WHEN $9::integer IS NULL OR f.row_num IS NOT DISTINCT FROM $9::integer THEN f.row_num+ WHEN NOT EXISTS (SELECT 1 FROM facts o WHERE o.source_id=f.source_id AND o.source_markdown_slug=f.source_markdown_slug AND o.row_num=$9::integer AND o.id<>f.id)+ THEN $9::integer ELSE f.row_num END+ WHERE f.source_id=$1 AND f.id=$2::bigint AND f.fact=$3 AND f.visibility=$10 RETURNING f.id`,+ [sourceId, p.id, p.fact, p.expired_at, p.valid_until, p.superseded_by, p.consolidated_at, p.consolidated_into, p.row_num, p.visibility]);+ return rows.length === 1;+}++/** One consolidation chain's identity: a member's id, its claim and the close it carries. */+const memberIdentity = (row: { id: number; fact: string; valid_until: string | null; consolidated_into: number | null }) =>+ digest(['consolidation-member-v1', Number(row.id), row.fact, row.valid_until ? new Date(row.valid_until).toISOString() : null, row.consolidated_into === null ? null : Number(row.consolidated_into)]).slice(0, 32);++/** The owner key of a consolidation cluster: its entity and sorted member ids. */+export const consolidationOwnerKey = (entitySlug: string, ids: readonly number[]) => `entity:${entitySlug}:cluster:${[...ids].map(Number).sort((a, b) => a - b).join(',')}`;+const clusterIds = (ownerKey: string) => (ownerKey.split(':cluster:')[1] ?? '').split(',').filter(Boolean).map(Number);++const memberKey = (id: number) => `fact:${Number(id)}`;++/**+ * After the consolidate phase closed a strict chain (`valid_until` and the consolidation marks of `before`'s members, in+ * the caller's transaction): records it as the cluster's live generation, each member at its new identity with its+ * `before` state as preimage. A cluster with no generation yet first records its members as they were (the baseline a+ * restore returns to).+ */+export async function recordConsolidationGeneration(tx: BrainEngine, sourceId: string, entitySlug: string, before: readonly FactPreimage[], runId?: string): Promise<void> {+ if (!before.length) return;+ const ids = before.map(row => Number(row.id));+ const key: GenerationKey = { kind: CONSOLIDATION_KIND, sourceId, ownerKey: consolidationOwnerKey(entitySlug, ids) };+ await tx.executeRaw('SELECT pg_advisory_xact_lock(hashtext($1)::bigint)', [generationKeyLock(key)]);+ const after = await factPreimages(tx, sourceId, ids);+ if (after.every((row, i) => memberIdentity(row) === memberIdentity(before[i]!))) return;+ const input = { pin: digest(['consolidation-input-v1', before.map(row => [row.id, row.fact])]), size: before.length };+ let live = await readLiveGeneration(tx, key);+ if (!live) {+ const baseline = before.map(row => ({ key: memberKey(row.id), identityHash: memberIdentity(row) }));+ await activateGeneration(tx, key, null, { operationId: digest(['consolidation-baseline-v1', key, baseline]), runId, input, setHash: itemSetHash(baseline),+ completeness: { complete: true, writer: 'consolidate', baseline: true } }, baseline.map(item => ({ ...item, action: 'kept' as const })));+ live = await readLiveGeneration(tx, key);+ }+ const prior = new Map(before.map(row => [Number(row.id), row]));+ const items = after.map(row => ({ key: memberKey(row.id), identityHash: memberIdentity(row) }));+ await activateGeneration(tx, key, live, { operationId: digest(['consolidation-v1', key, items]), runId, input, setHash: itemSetHash(items),+ completeness: { complete: true, writer: 'consolidate' } }, items.map(item => {+ const json = prior.get(Number(item.key.slice('fact:'.length))) as unknown as Record<string, unknown>;+ return { ...item, action: 'published' as const, preimage: { json, bytes: JSON.stringify(json).length } };+ }));+}++/** A cluster the consolidate phase will not close because its members tie (#6023): held `tie`, nothing written. */+export async function holdConsolidationTie(tx: BrainEngine, sourceId: string, entitySlug: string, ids: readonly number[], context: Record<string, unknown>): Promise<void> {+ const key: GenerationKey = { kind: CONSOLIDATION_KIND, sourceId, ownerKey: consolidationOwnerKey(entitySlug, ids) };+ await tx.executeRaw('SELECT pg_advisory_xact_lock(hashtext($1)::bigint)', [generationKeyLock(key)]);+ const items = [...ids].map(id => ({ key: memberKey(id), content: '', identityHash: memberKey(id) }));+ await recordHeld(tx, key, await readGenerationsConfig(tx), { key, items, input: null }, itemSetHash(items), 'tie', { members: ids.length, ...context });+}++/** Whether the operator restored this cluster's chain (`repair generations --kind consolidation --mode restore`): the consolidate phase leaves it open. */+export async function consolidationRestored(db: BrainEngine, sourceId: string, entitySlug: string, ids: readonly number[]): Promise<boolean> {+ const [row] = await db.executeRaw<{ restored: boolean }>(`SELECT restore_of IS NOT NULL AS restored FROM derived_generations+ WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='live'`, [sourceId, CONSOLIDATION_KIND, consolidationOwnerKey(entitySlug, ids)]);+ return row?.restored === true;+}++/** Clears the entity's `tie` holds before a consolidate pass re-records the ties it still finds. */+export async function clearConsolidationTies(db: BrainEngine, sourceId: string, entitySlug: string): Promise<void> {+ const prefix = `entity:${entitySlug}:cluster:`;+ await db.executeRaw(`DELETE FROM derived_generations WHERE source_id=$1 AND kind=$2 AND state='held' AND held_reason='tie' AND left(owner_key, $3)=$4`,+ [sourceId, CONSOLIDATION_KIND, prefix.length, prefix]);+}++/** The consolidation adapter: items are the cluster's member facts; a restore writes each member's before-state back. */+export const consolidationAdapter: GenerationAdapter<undefined> = {+ kind: CONSOLIDATION_KIND,+ retiredBy: 'generation-restore',+ modelProduced: false,+ strictOrder: true,+ lockKeys: () => [],+ async readInput(engine, key) {+ const ids = clusterIds(key.ownerKey);+ const rows = await factPreimages(engine, key.sourceId, ids);+ return rows.length ? { pin: digest(['consolidation-input-v1', rows.map(row => [row.id, row.fact, row.expired_at])]), size: rows.length } : null;+ },+ async readItems(engine, key, itemKeys) {+ const ids = [...new Set([...clusterIds(key.ownerKey), ...itemKeys.map(itemKey => Number(itemKey.replace(/^fact:/, '')))])];+ const rows = await factPreimages(engine, key.sourceId, ids);+ return new Map(rows.map(row => [`fact:${row.id}`, { key: `fact:${row.id}`, identityHash: memberIdentity(row), live: row.expired_at === null, owned: true, segmented: false,+ preimage: () => ({ json: row as unknown as Record<string, unknown>, bytes: JSON.stringify(row).length }) } satisfies ItemRow]));+ },+ legacyEvidence: async () => new Set(),+ publishItems: async () => { throw new Error('consolidation members publish through the consolidate phase'); },+ retireItems: async () => {},+ async restoreItem(tx: BrainEngine, key: GenerationKey, _itemKey: string, preimage: Record<string, unknown>) {+ if (!await restoreFactRow(tx, key.sourceId, preimage)) throw new Error(`consolidation member ${String(preimage.id)} changed; nothing restored`);+ },+ preimageIdentity: preimage => memberIdentity(preimage as unknown as FactPreimage),+};++/** The fact_fence adapter as the repair command resolves it: fence kinds restore by transplanting the fence (repair.ts). */+export const factFenceAdapter: GenerationAdapter<undefined> = {+ kind: FACT_FENCE_KIND,+ retiredBy: 'generation-restore',+ modelProduced: false,+ fence: 'facts',+ lockKeys: (key) => [{ sourceId: key.sourceId, slug: key.ownerKey.replace(/^page:/, '') }],+ readInput: async () => null,+ readItems: async () => new Map(),+ legacyEvidence: async () => new Set(),+ publishItems: async () => { throw new Error('fact_fence rows publish through the page fence (publishFenceGeneration)'); },+ retireItems: async () => { throw new Error('fact_fence rows retire through the page fence (publishFenceGeneration)'); },+ restoreItem: async (tx, key, _itemKey, preimage) => { await restoreFactRow(tx, key.sourceId, preimage); },+ preimageIdentity: preimage => factRowIdentity(preimage as unknown as { row_num: number; fact: string; visibility: string }),+};diff --git a/src/core/generations/adapters/index.ts b/src/core/generations/adapters/index.tsindex 7b62612351..c84dde3cc6 100644--- a/src/core/generations/adapters/index.ts+++ b/src/core/generations/adapters/index.ts@@ -4,8 +4,11 @@*/import type { GenerationAdapter } from '../contract.ts';import { atomGenerationAdapter } from './atoms.ts';+import { consolidationAdapter, factFenceAdapter } from './fact-rows.ts';+import { takeFenceAdapter } from './take-rows.ts';-const adapters = new Map<string, GenerationAdapter<unknown>>([[atomGenerationAdapter.kind, atomGenerationAdapter as GenerationAdapter<unknown>]]);+const adapters = new Map<string, GenerationAdapter<unknown>>([atomGenerationAdapter, factFenceAdapter, takeFenceAdapter, consolidationAdapter]+ .map(adapter => [adapter.kind, adapter as GenerationAdapter<unknown>]));export function generationAdapter(kind: string): GenerationAdapter<unknown> | undefined { return adapters.get(kind); }export function generationKinds(): string[] { return [...adapters.keys()]; }diff --git a/src/core/generations/adapters/take-rows.ts b/src/core/generations/adapters/take-rows.tsnew file mode 100644index 0000000000..d2298de12e--- /dev/null+++ b/src/core/generations/adapters/take-rows.ts@@ -0,0 +1,77 @@+/**+ * GBRA-161 PR 2: the take-rows adapter (`take_fence`, one owner key per page). A page's takes fence is the system of+ * record for its takes (fence.ts). The page publication's projection and `gbrain extract takes` delete the takes whose row+ * left a fence that was read whole, and overwrite a take whose claim, kind or holder changed at its row number (the+ * `addTakesBatch` upsert, B-19). Both now ask `publishFenceGeneration` first: an absent fence holds (`fence_absent`) and+ * deletes nothing, and every deleted or replaced take's full row (database-only resolution included) is recorded on the+ * ledger before it changes.+ */+import type { BrainEngine } from '../../engine.ts';+import type { GenerationAdapter } from '../contract.ts';+import { fenceRowKey, publishFenceGeneration, takeRowIdentity, TAKE_FENCE_KIND, type FenceGenerationOutcome, type FenceItem, type FenceRead } from '../fence.ts';++/** The columns a take's before-state keeps (every column but its vector and write attribution). */+const TAKE_PREIMAGE_SQL = `jsonb_build_object('id', k.id, 'page_id', k.page_id, 'row_num', k.row_num, 'claim', k.claim, 'kind', k.kind, 'holder', k.holder,+ 'weight', k.weight, 'since_date', k.since_date, 'until_date', k.until_date, 'source', k.source, 'superseded_by', k.superseded_by, 'active', k.active,+ 'resolved_at', k.resolved_at, 'resolved_outcome', k.resolved_outcome, 'resolved_value', k.resolved_value, 'resolved_unit', k.resolved_unit,+ 'resolved_source', k.resolved_source, 'resolved_by', k.resolved_by, 'resolved_quality', k.resolved_quality)`;++type TakePreimage = { id: number; row_num: number; claim: string; kind: string; holder: string };+type IncomingTake = { rowNum: number; claim: string; kind: string; holder: string };++export function takeFenceItems(takes: readonly IncomingTake[]): FenceItem[] {+ return takes.map(take => {+ const identityHash = takeRowIdentity({ row_num: take.rowNum, claim: take.claim, kind: take.kind, holder: take.holder });+ return { key: fenceRowKey(take.rowNum, identityHash), identityHash };+ });+}++export const takeItem = (preimage: TakePreimage, key = `take:${preimage.id}`): FenceItem => ({ key, preimage: preimage as unknown as Record<string, unknown>,+ identityHash: takeRowIdentity({ row_num: Number(preimage.row_num), claim: preimage.claim, kind: preimage.kind, holder: preimage.holder }) });++/** Full rows of the takes `ids` of page `pageId` (before-states), and of the takes `replaced` would overwrite at their numbers. */+export async function takePreimages(db: BrainEngine, pageId: number, ids: readonly number[], replaced: readonly IncomingTake[] = []): Promise<{ gone: TakePreimage[]; replaced: TakePreimage[] }> {+ if (!ids.length && !replaced.length) return { gone: [], replaced: [] };+ const incoming = JSON.stringify(replaced.map(take => ({ row_num: take.rowNum, claim: take.claim, kind: take.kind, holder: take.holder })));+ const rows = await db.executeRaw<{ preimage: TakePreimage; gone: boolean }>(+ `SELECT ${TAKE_PREIMAGE_SQL} AS preimage, k.id = ANY($2::bigint[]) AS gone FROM takes k+ LEFT JOIN jsonb_to_recordset($3::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.id = ANY($2::bigint[]) OR (n.row_num IS NOT NULL AND (k.claim, k.kind, k.holder) IS DISTINCT FROM (n.claim, n.kind, n.holder)))+ ORDER BY k.row_num`, [pageId, [...ids], incoming]);+ return { gone: rows.filter(row => row.gone).map(row => row.preimage), replaced: rows.filter(row => !row.gone).map(row => row.preimage) };+}++/**+ * Before a takes write: the stored takes it would delete (`gone` row numbers) and those it would replace (same number,+ * different claim, kind or holder), each with its full row. Held: the caller deletes and overwrites nothing.+ */+export async function projectTakeFenceGeneration(tx: BrainEngine, input: { sourceId: string; slug: string; pageId: number; read: FenceRead;+ takes: readonly IncomingTake[]; gone: readonly number[]; writer: string; runId?: string }): Promise<FenceGenerationOutcome> {+ const incoming = JSON.stringify(input.takes.map(take => ({ row_num: take.rowNum, claim: take.claim, kind: take.kind, holder: take.holder })));+ const rows = (input.gone.length || input.takes.length) ? await tx.executeRaw<{ preimage: TakePreimage; gone: boolean }>(+ `SELECT ${TAKE_PREIMAGE_SQL} AS preimage, k.row_num = ANY($2::integer[]) AS gone FROM takes k+ LEFT JOIN jsonb_to_recordset($3::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.row_num = ANY($2::integer[]) OR (n.row_num IS NOT NULL AND (k.claim, k.kind, k.holder) IS DISTINCT FROM (n.claim, n.kind, n.holder)))+ ORDER BY k.row_num`, [input.pageId, [...input.gone], incoming]) : [];+ const items = takeFenceItems(input.takes);+ const byRow = new Map(input.takes.map((take, index) => [take.rowNum, items[index]!.key]));+ return publishFenceGeneration(tx, { kind: TAKE_FENCE_KIND, sourceId: input.sourceId, slug: input.slug, read: input.read, items, writer: input.writer, runId: input.runId,+ retire: rows.filter(row => row.gone).map(row => takeItem(row.preimage)),+ overwrite: rows.filter(row => !row.gone).map(row => takeItem(row.preimage, byRow.get(Number(row.preimage.row_num)))) });+}++/** The take_fence adapter as the repair command resolves it: fence kinds restore by transplanting the fence (repair.ts). */+export const takeFenceAdapter: GenerationAdapter<undefined> = {+ kind: TAKE_FENCE_KIND,+ retiredBy: 'generation-restore',+ modelProduced: false,+ fence: 'takes',+ lockKeys: (key) => [{ sourceId: key.sourceId, slug: key.ownerKey.replace(/^page:/, '') }],+ readInput: async () => null,+ readItems: async () => new Map(),+ legacyEvidence: async () => new Set(),+ publishItems: async () => { throw new Error('take_fence rows publish through the page fence (publishFenceGeneration)'); },+ retireItems: async () => { throw new Error('take_fence rows retire through the page fence (publishFenceGeneration)'); },+ restoreItem: async () => { throw new Error('take_fence rows restore through the fence block (repair generations)'); },+ preimageIdentity: preimage => takeRowIdentity(preimage as unknown as { row_num: number; claim: string; kind: string; holder: string }),+};diff --git a/src/core/generations/contract.ts b/src/core/generations/contract.tsindex b592b0e63b..4eeb1aa5d6 100644--- a/src/core/generations/contract.ts+++ b/src/core/generations/contract.ts@@ -37,6 +37,8 @@ export interface GenerationAdapter<C = unknown> {modelProduced: boolean;/** The result is a ranked cut: every item carries a distinct `order`, and a tie (or a missing rank) holds the result (`tie`). */strictOrder?: boolean;+ /** A canonical fence kind (generations/fence.ts): it publishes through `publishFenceGeneration` and restores by transplanting the fence. */+ fence?: 'facts' | 'takes';/** Page keys locked before the ledger row, in slug order with the input guard (D7). */lockKeys(key: GenerationKey, itemKeys: readonly string[]): Array<{ sourceId: string; slug: string }>;/** The input as stored now, or null when it is gone. `context` carries an input the database does not hold (a transcript). */diff --git a/src/core/generations/fence.ts b/src/core/generations/fence.tsnew file mode 100644index 0000000000..4da8030cbe--- /dev/null+++ b/src/core/generations/fence.ts@@ -0,0 +1,231 @@+/**+ * GBRA-161 PR 2: the canonical fence kinds (`fact_fence`, `take_fence`) on the generation primitive (plan D4, D6). A page's+ * `## Facts` and takes fences are the system of record for the rows projected from them, so a fence that was read whole+ * and is valid is complete whatever its row count: rows that left it retire, and an empty fence retires them all+ * (`fenceParsedEmpty`). No shrink floor, valve or item cap applies to a canonical kind. A fence that is absent, unread or+ * segmented proves nothing: every writer that would retire rows on it (the page publication's projection, extract_facts,+ * extract takes) records a held generation (`generation_held`, reason `fence_absent`) and retires nothing. The rows of a+ * deleted page expire only on `originGone`, rechecked here under the caller's page key.+ *+ * Writers call `publishFenceGeneration` inside the transaction that already holds the page key (D7: page keys, then the+ * generation key). It decides, records the generation with the before-state of every row it retires or replaces, and+ * says whether the caller may retire; the caller's own statements do the writes in that same transaction.+ */+import type { Action } from '../agent-output.ts';+import type { BrainEngine } from '../engine.ts';+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, renderFactsTable } from '../facts-fence.ts';+import { locateOutsideCode } from '../fence-scan.ts';+import { digest } from '../persistence/digest.ts';+import { renderTakesFence, TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../takes-fence.ts';+import { readGenerationsConfig } from './config.ts';+import type { GenerationKey, HeldReason, Preimage } from './contract.ts';+import { activateGeneration, generationKeyLock, itemSetHash, readLiveGeneration, recordHeld, type LedgerItem } from './publish.ts';++export const FACT_FENCE_KIND = 'fact_fence';+export const TAKE_FENCE_KIND = 'take_fence';+export type FenceGenerationKind = typeof FACT_FENCE_KIND | typeof TAKE_FENCE_KIND;+export const FENCE_GENERATION_KINDS: readonly FenceGenerationKind[] = [FACT_FENCE_KIND, TAKE_FENCE_KIND];++/** The largest fence block a generation keeps for restore (UTF-8 bytes); a larger one restores nothing (`no_preimage`). */+export const FENCE_BLOCK_MAX_BYTES = 256 * 1024;+/** The largest before-state one row keeps (UTF-8 bytes of its JSON). */+const ROW_PREIMAGE_MAX_BYTES = 64 * 1024;++export const fenceOwnerKey = (slug: string) => `page:${slug}`;+export const fenceSlugOf = (ownerKey: string) => ownerKey.startsWith('page:') ? ownerKey.slice('page:'.length) : null;+export const fenceName = (kind: FenceGenerationKind) => kind === FACT_FENCE_KIND ? 'facts' as const : 'takes' as const;++/** One fence block per body section, exactly as the page holds it (markers included). */+export interface FenceBlocks { body: string | null; timeline: string | null }+export type FenceRead = { state: 'parsed'; blocks: FenceBlocks } | { state: 'absent' | 'unread' | 'segmented' };++/** The page's `fence` blocks outside markdown code, or `absent` when neither section holds one. */+export function readFenceBlocks(page: { compiled_truth: string | null; timeline?: string | null }, fence: 'facts' | 'takes'): FenceRead {+ const [begin, end] = fence === 'facts' ? [FACTS_FENCE_BEGIN, FACTS_FENCE_END] : [TAKES_FENCE_BEGIN, TAKES_FENCE_END];+ const block = (text: string | null | undefined) => {+ 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 };+}++/** 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);+export const takeRowIdentity = (row: { row_num: number; claim: string; kind: string; holder: string }) =>+ digest(['take-fence-row-v1', Number(row.row_num), row.claim, row.kind, row.holder]).slice(0, 32);++/** One fence row of the new generation, or a stored row it retires or replaces (with its before-state). */+export interface FenceItem { key: string; identityHash: string; preimage?: Record<string, unknown> }+export const fenceRowKey = (rowNum: number, identity: string) => `row:${rowNum}:${identity.slice(0, 12)}`;++export interface FenceGenerationRequest {+ kind: FenceGenerationKind;+ sourceId: string;+ slug: string;+ read: FenceRead;+ /** The rows the fence holds after this write. */+ items: readonly FenceItem[];+ /** Stored rows the writer would retire (left the fence, or every row of an empty fence or a deleted page). */+ retire: readonly FenceItem[];+ /** Stored rows the writer overwrites in place with a different identity (a take replaced at its row number). */+ overwrite?: readonly FenceItem[];+ /** The page is deleted: its rows retire on `originGone`, rechecked here. */+ originGone?: boolean;+ /** Which writer published (projection, extract_facts, extract_takes, deleted_page, restore). */+ writer: string;+ runId?: string;+}++export type FenceGenerationOutcome =+ | { state: 'published'; generation: number }+ | { state: 'unchanged' }+ | { state: 'held'; reason: HeldReason; holdId: string };++const preimageOf = (json: Record<string, unknown> | undefined): Preimage | undefined => {+ if (!json) return undefined;+ const bytes = Buffer.byteLength(JSON.stringify(json), 'utf8');+ return { json: bytes <= ROW_PREIMAGE_MAX_BYTES ? json : null, bytes };+};++/** The input pin of a read fence: its blocks as the page holds them. */+export function fenceInput(read: FenceRead): { pin: string; size: number } | null {+ if (read.state !== 'parsed') return null;+ return { pin: digest(['fence-blocks-v1', read.blocks.body, read.blocks.timeline]),+ size: Buffer.byteLength(`${read.blocks.body ?? ''}${read.blocks.timeline ?? ''}`, 'utf8') };+}++function storedBlocks(read: FenceRead): FenceBlocks | null {+ if (read.state !== 'parsed') return null;+ return Buffer.byteLength(`${read.blocks.body ?? ''}${read.blocks.timeline ?? ''}`, 'utf8') <= FENCE_BLOCK_MAX_BYTES ? read.blocks : null;+}++/** Whether `slug` is deleted (or gone) in `sourceId`, read under the caller's page key. */+async function originGoneNow(tx: BrainEngine, sourceId: string, slug: string): Promise<boolean> {+ const rows = await tx.executeRaw<{ deleted: boolean }>('SELECT deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);+ return !rows.length || rows.every(row => row.deleted);+}++/**+ * Decides one fence write and records it. `published`: the caller retires every row of `retire` (and overwrites+ * `overwrite`); `unchanged`: the fence owns what the live generation recorded and nothing retires; `held`: retire nothing.+ */+export async function publishFenceGeneration(tx: BrainEngine, request: FenceGenerationRequest): Promise<FenceGenerationOutcome> {+ const key: GenerationKey = { kind: request.kind, sourceId: request.sourceId, ownerKey: fenceOwnerKey(request.slug) };+ const overwrite = request.overwrite ?? [];+ if (!request.items.length && !request.retire.length && !overwrite.length) {+ if (request.read.state === 'parsed') await clearFenceHold(tx, key);+ return { state: 'unchanged' };+ }+ await tx.executeRaw('SELECT pg_advisory_xact_lock(hashtext($1)::bigint)', [generationKeyLock(key)]);+ const live = await readLiveGeneration(tx, key);+ const input = fenceInput(request.read);+ const setHash = itemSetHash(request.items);+ const hold = async (reason: HeldReason): Promise<FenceGenerationOutcome> => {+ const proposal = request.items.map(item => ({ key: item.key, content: '', identityHash: item.identityHash }));+ const outcome = await recordHeld(tx, key, await readGenerationsConfig(tx), { key, items: proposal, input, runId: request.runId }, setHash, reason,+ { slug: request.slug, fence: fenceName(request.kind), writer: request.writer, read: request.read.state, rows: request.retire.length });+ return outcome.state === 'held' ? { state: 'held', reason: outcome.reason, holdId: outcome.holdId } : { state: 'unchanged' };+ };+ let proof: string | null = null;+ if (request.retire.length) {+ if (request.originGone) {+ if (!await originGoneNow(tx, request.sourceId, request.slug)) return hold('no_proof');+ proof = 'originGone';+ } else if (request.read.state !== 'parsed') {+ return hold('fence_absent');+ } else if (!request.items.length) {+ proof = 'fenceParsedEmpty';+ }+ }+ const recorded = live?.items ?? new Map<string, string>();+ if (live && !request.retire.length && !overwrite.length && recorded.size === request.items.length+ && request.items.every(item => recorded.get(item.key) === item.identityHash)) {+ if (request.read.state === 'parsed') await clearFenceHold(tx, key);+ return { state: 'unchanged' };+ }+ const replaced = new Map(overwrite.map(item => [item.key, item]));+ const items: LedgerItem[] = [+ ...request.items.map(item => ({ key: item.key, identityHash: item.identityHash, action: recorded.has(item.key) ? 'kept' as const : 'published' as const,+ ...(replaced.get(item.key)?.preimage ? { preimage: preimageOf(replaced.get(item.key)!.preimage) } : {}) })),+ ...request.retire.map(item => ({ key: item.key, identityHash: item.identityHash, action: 'retired' as const, preimage: preimageOf(item.preimage) })),+ ];+ const operationId = digest(['fence-generation-v1', key, live?.generation ?? 0, input?.pin ?? null, setHash, request.retire.map(item => item.key).sort(), request.writer]);+ const activated = await activateGeneration(tx, key, live, { operationId, runId: request.runId, input, setHash,+ completeness: { complete: true, writer: request.writer, proof, fence: storedBlocks(request.read), fence_bytes: input?.size ?? null } }, items);+ return { state: 'published', generation: activated.generation };+}++/** A readable fence answers a held `fence_absent` (or `no_proof`) row: it is the proof the hold waited for. */+async function clearFenceHold(tx: BrainEngine, key: GenerationKey): Promise<void> {+ await tx.executeRaw(`DELETE FROM derived_generations WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='held' AND held_reason IN ('fence_absent','no_proof')`,+ [key.sourceId, key.kind, key.ownerKey]);+}++/** A held fence result, as doctor, `get_page` and `gbrain sync status` list it. */+export interface FenceHold { source_id: string; kind: FenceGenerationKind; slug: string; reason: HeldReason; read: string; rows: number; since: string; writer: string | null }++/** The held fence results of `sources` (one page with `slug`), oldest first. */+export async function listFenceHolds(db: BrainEngine, sources: readonly string[], slug?: string): Promise<FenceHold[]> {+ const params: unknown[] = [[...sources], [...FENCE_GENERATION_KINDS]];+ if (slug !== undefined) params.push(fenceOwnerKey(slug));+ const rows = await db.executeRaw<{ source_id: string; kind: FenceGenerationKind; owner_key: string; held_reason: HeldReason; held_context: Record<string, unknown> | null; created_at: string }>(+ `SELECT source_id, kind, owner_key, held_reason, held_context, created_at::text AS created_at FROM derived_generations+ WHERE source_id = ANY($1::text[]) AND kind = ANY($2::text[]) AND state = 'held'${slug === undefined ? '' : ' AND owner_key = $3'}+ ORDER BY created_at, id`, params);+ return rows.map(row => ({ source_id: row.source_id, kind: row.kind, slug: fenceSlugOf(row.owner_key) ?? row.owner_key, reason: row.held_reason,+ read: String(row.held_context?.read ?? 'absent'), rows: Number(row.held_context?.rows ?? 0), since: row.created_at,+ writer: typeof row.held_context?.writer === 'string' ? row.held_context.writer : null }));+}++/** A held fence result with the owner's decision it waits for (`fenceAbsentFix`), as the three surfaces show it. */+export type FenceHoldEntry = FenceHold & { fix: Action };++/** `listFenceHolds` with each hold's fix; a page without a recorded file gets the put_page/edit_page form. At most `limit`. */+export async function fenceHoldEntries(db: BrainEngine, sources: readonly string[], opts: { slug?: string; limit?: number } = {}): Promise<FenceHoldEntry[]> {+ const holds = (await listFenceHolds(db, sources, opts.slug)).slice(0, opts.limit ?? 20);+ if (!holds.length) return [];+ const files = await db.executeRaw<{ source_id: string; slug: string; database_only: boolean }>(+ `SELECT source_id, slug, NULLIF(btrim(source_path), '') IS NULL AS database_only FROM pages+ WHERE source_id = ANY($1::text[]) AND slug = ANY($2::text[]) AND deleted_at IS NULL`, [[...new Set(holds.map(hold => hold.source_id))], holds.map(hold => hold.slug)]);+ const databaseOnly = new Map(files.map(row => [`${row.source_id}\u0000${row.slug}`, row.database_only === true]));+ return holds.map(hold => ({ ...hold, fix: fenceAbsentFix(hold, { databaseOnly: databaseOnly.get(`${hold.source_id}\u0000${hold.slug}`) ?? false }) }));+}++/** The exact empty fence that retires every row of `fence` on the next write (`fenceParsedEmpty`). */+export function emptyFenceBlock(fence: 'facts' | 'takes'): string {+ return fence === 'facts' ? `## Facts\n\n${renderFactsTable([])}\n` : `## Takes\n\n${renderTakesFence([])}\n`;+}++/**+ * The owner's decision a held fence waits for (`ask_user`). For an absent fence: whether the section was removed on+ * purpose. Restoring the fence keeps the rows; writing the empty fence retires them. Neither is the default and nothing+ * runs without the user. A database-only page (no file to edit) changes through `put_page` or `edit_page`.+ */+export function fenceAbsentFix(hold: Pick<FenceHold, 'source_id' | 'kind' | 'slug' | 'rows' | 'read' | 'reason'>, opts: { databaseOnly: boolean }): Action {+ const fence = fenceName(hold.kind);+ const section = fence === 'facts' ? '## Facts' : '## Takes';+ const what = `${hold.rows} ${fence === 'facts' ? 'fact' : 'take'} row(s)`;+ if (hold.reason !== 'fence_absent' || hold.read !== 'absent') {+ return { consent: [], actor: 'user', requires_exclusive: false, ask_user: true,+ why: `The ${fence} rows of ${hold.slug} (source ${hold.source_id}) were held (${hold.reason}, fence ${hold.read}), so gbrain kept its ${what} live instead of retiring them; `+ + 'nothing was retired. Ask the user whether the page should keep these rows; the next write that reads the whole fence (or, for a deleted page, finds it still deleted) reconciles them.',+ user_message: `gbrain could not confirm the ${section} section of ${hold.slug}, so it kept its ${what} as they were. Nothing was removed.`,+ verify: { argv: ['gbrain', 'doctor', '--only', 'generation_held', '--json'] }, docs: 'docs/guides/repair.md#fence-absent' };+ }+ const block = emptyFenceBlock(fence);+ const write = opts.databaseOnly+ ? ' This page has no file, so either change is a page write: read it with get_page (include_content: true), then put_page with expected_revision and the full '+ + 'content (restored section, or the empty block appended), or edit_page with expected_revision and edits: [{ old_text: <the page\'s last line>, new_text: <that line, a blank line, then the block> }].'+ : ' Edit the page\'s file and sync it, or write the page with put_page or edit_page and its expected_revision.';+ return { consent: [], actor: 'user', requires_exclusive: false, ask_user: true,+ why: `Page ${hold.slug} (source ${hold.source_id}) was written without its ${section} section, so gbrain kept its ${what} live instead of retiring them; `+ + `nothing was retired. The user may have deleted the whole ${section} section on purpose, or an edit may have lost it: ask which. `+ + `To keep the rows, restore the ${section} section (from the page's history or the previous version of its file). `+ + `To retire them, write this exact empty fence into the page; the next write retires every row on it:\n${block}${write}`,+ user_message: `The ${section} section of ${hold.slug} is gone, so gbrain kept its ${what} instead of deleting them. Did you mean to remove them? `+ + `To keep them, restore the ${section} section. To remove them, add this empty section to the page:\n${block}`,+ verify: { argv: ['gbrain', 'doctor', '--only', 'generation_held', '--json'] },+ docs: 'docs/guides/repair.md#fence-absent' };+}diff --git a/src/core/ops/get-page-projection.ts b/src/core/ops/get-page-projection.tsindex 06b37536b9..f4ef373e5d 100644--- a/src/core/ops/get-page-projection.ts+++ b/src/core/ops/get-page-projection.ts@@ -64,6 +64,8 @@ export interface GetPageProjectionOpts {timeline_entries?: unknown;/** A held source file (sync could not import it); present in both shapes so an editor sees it. */file_held?: unknown;+ /** GBRA-161 PR 2: the page's held facts or takes fence (`fence_absent`), each with its ask-the-user fix; present in both shapes. */+ fence_held?: unknown;/** #6259: the page is quarantined; `body_omitted` drops compiled_truth, timeline and `content`. */quarantined?: QuarantinedView | null;/** #5575 A6: the page's trust tier and short write origin. */@@ -92,6 +94,7 @@ export function projectGetPage(page: Page, o: GetPageProjectionOpts) {...(quarantined ? { quarantined } : {}),...(o.timeline_entries !== undefined ? { timeline_entries: o.timeline_entries } : {}),...(o.file_held !== undefined ? { file_held: o.file_held } : {}),+ ...(o.fence_held !== undefined ? { fence_held: o.fence_held } : {}),...(resolved_slug ? { resolved_slug } : {}), ...(content_flag ? { content_flag } : {}),};if (o.includeContent && o.contentOnly) {diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 5769626d43..6d15c77f2c 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -27,6 +27,7 @@ import { isAutoLinkEnabled } from '../link-extraction.ts';import { sanitizeRemoteBody } from '../remote-body.ts';import { getContentFlag } from '../quarantine.ts';import { fileHeldField, readHeldPages } from '../persistence/held-reads.ts';+import { fenceHoldEntries } from '../generations/fence.ts';import { bumpLastRetrievedAt } from '../last-retrieved.ts';import { resolveExcludePrivatePages, isPrivatePage, findPrivateOnlySlugs } from '../search/private-visibility.ts';import { LIST_PAGES_DESCRIPTION, CAPTURE_DESCRIPTION } from '../operations-descriptions.ts';@@ -226,7 +227,9 @@ const get_page: Operation = {// Read-only, over the same visibility-filtered body the reader gets.const lineGrammar = p.grammar_diagnostics !== true ? undefined : await (await import('../line-grammar-report.ts')).grammarDiagnosticsForPage(ctx.engine, page, visibleBody);const quarantined = readQuarantined(ctx, page, p.include_quarantined === true); // #6259- const fileHeld = held ? { file_held: fileHeldField(held, isUntrustedReader) } : {};+ const fenceHolds = await fenceHoldEntries(ctx.engine, [page.source_id], { slug: page.slug }).catch(() => []);+ const fileHeld = { ...(held ? { file_held: fileHeldField(held, isUntrustedReader) } : {}),+ ...(fenceHolds.length ? { fence_held: fenceHolds.map(({ source_id: _source, slug: _slug, ...hold }) => hold) } : {}) };const segmented = isSegmentedPage(page);const pin = authorizedReadPin(ctx, page, snapshot!.bodyGeneration, p.min_trust, () => pageNotFoundError(ctx, slug, { includeDeleted, sourceIdParam }));const whole = bodyRequest.mode === 'full'diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.tsindex d7bea35dc4..05c25dab58 100644--- a/src/core/persistence/canonical-projections.ts+++ b/src/core/persistence/canonical-projections.ts@@ -25,6 +25,9 @@ import type { FenceSection } from '../fence-repair/types.ts';import { contestHeldRows, factsAboveWriter, guardFenceRows, guardFenceTakes, heldRows } from '../trust/fence-guard.ts';import { propagateFactLowering } from '../trust/propagation.ts';import { loadWriteGateConfig } from '../trust/gate-outcomes.ts';+import { fenceOwnerKey, readFenceBlocks, TAKE_FENCE_KIND } from '../generations/fence.ts';+import { projectFactFenceGeneration } from '../generations/adapters/fact-rows.ts';+import { projectTakeFenceGeneration } from '../generations/adapters/take-rows.ts';const FENCE_PAIRS=[{begin:FACTS_FENCE_BEGIN,end:FACTS_FENCE_END},{begin:TAKES_FENCE_BEGIN,end:TAKES_FENCE_END}];@@ -538,6 +541,8 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par// #6259: a page the content-quality gate hid as junk projects no facts or takes. Rows projected before it// was quarantined are left as they are (hiding them would need a new row state); only new projection stops.const projectFences = !isQuarantined(page.frontmatter);+ // GBRA-161 PR 2: the incoming body's fences decide the fact and take generations; an absent one retires nothing.+ const fenceReads = { facts: readFenceBlocks(page, 'facts'), takes: readFenceBlocks(page, 'takes') };const storedRows = prior ? await storedTimeline(engine, prior.page.id) : [];const prior_ = prior ? await priorView(engine, prior.page, slug, storedRows) : null;const { timeline, exactIncoming, pinned } = classifyTimeline(storedRows, page, prior_?.rows ?? null, slug, writer, policy);@@ -546,7 +551,14 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Parconst refreshRows = pinned.filter(row => row.action === 'refresh_detail').map(row => ({ id: row.id, detail: row.detail, next: exactIncoming.get(exactTimelineKey(row)) })).filter(row => row.next !== row.detail);- const priorTakes = prior_?.takeRows ?? new Set<number>();+ // GBRA-161 PR 2: a write that dropped the takes fence was held and left its rows stored; once a fence parses again it+ // is compared with those rows, not with the fenceless body before it.+ const heldTakeFence = !!prior && projectFences && fenceReads.takes.state === 'parsed' && (await engine.executeRaw(+ `SELECT 1 FROM derived_generations WHERE source_id=$1 AND kind=$2 AND owner_key=$3 AND state='held' AND held_reason='fence_absent'`,+ [sourceId, TAKE_FENCE_KIND, fenceOwnerKey(slug)])).length > 0;+ const priorTakes = heldTakeFence+ ? new Set([...(prior_?.takeRows ?? []), ...(await engine.executeRaw<{ row_num: number }>('SELECT row_num FROM takes WHERE page_id=$1', [prior!.page.id])).map(r => Number(r.row_num))])+ : prior_?.takeRows ?? new Set<number>();// TE1 (#6188): when the prior takes fence does not parse, its stored rows count as prior canonical rows, so a// row Tier 1 normalized (same number, holder `system` -> `brain`) updates its stored take instead of colliding.const priorCanonical = prior && prior_?.takesWarn@@ -611,7 +623,8 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Parr.valid_until::timestamptz,r.expired_at::timestamptz,r.source,r.confidence,r.claim_metric,r.claim_value,r.claim_unit,r.claim_period,r.attributed_to)`,[sourceId, slug, fieldRows]) : Promise.resolve([]);const checkTakes = () => refuseCollisions(tx, id);- const dropTakes = () => tx.executeRaw('DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])', [id, takeRowsGone.filter(n => !heldRowNums.has(n))]);+ const dropTakes = (held: boolean) => () => held ? Promise.resolve([])+ : tx.executeRaw('DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])', [id, takeRowsGone.filter(n => !heldRowNums.has(n))]);// A fence row's resolution cells are written as Markdown says, so a revert to a version that carries them restores// them. A row without resolution cells keeps the stored resolution (a database-only grade, e.g. unmanaged// grade_takes) unless its claim changed in place, which drops the old claim's grade. A held take keeps its grade:@@ -658,15 +671,22 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Parconst held = await step('held', contestHeld);return { timelineRowsRemoved: removedSummary(removedDates), ...(held.length ? { contested: held } : {}) };}+ // 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 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.- const guard = await step('timeline', () => guardFenceRows(tx, { sourceId, slug, incoming, rows: factRows, cfg: loadWriteGateConfig },+ 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])));+ 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 transactionconst contested = await step('fact_trust', () => guard.finish(tx));// W1 #6783 §12 (b): a fence row's field rewrite can lower a more trusted fact (the tier trigger); what was derived from it follows.const above = factRows.length ? await factsAboveWriter(tx, sourceId, slug) : [];- await step('fact_fields', () => pipelined(tx, [factFields, checkTakes, dropTakes, clearChangedResolutions]));+ await step('fact_fields', () => pipelined(tx, [factFields, checkTakes, dropTakes(takesHeld), clearChangedResolutions]));if (above.length) await propagateFactLowering(tx, above);if (projectedTakes.length) {await step('takes', async () => {diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex deb04ca82c..66d6243e07 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -32,6 +32,7 @@ import { MaintenanceWriteWait } from './maintenance-wait.ts';import { auditConflictsCommand, FILE_DRIFT_MESSAGE, liveFileDrift } from './drift-conflicts.ts';import { declaredWriteTrust, lowerToDerivedTier, readDerivationDeclaration, recordTaintEdges, type DerivationDeclaration } from '../trust/taint.ts';import { sameInstantTies } from '../facts/claim-ties.ts';+import { factPreimages, recordConsolidationGeneration } from '../generations/adapters/fact-rows.ts';export interface MaintenanceAuthority {writer: WriteAuthority;@@ -592,12 +593,14 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, coif (!take) throw opError('storage_error', 'The consolidated take did not commit.',`Consolidation request ${row.request_id} on ${row.slug} in ${row.source_id} did not find its take inside the publication transaction, so the transaction rolled back. Read the receipt with gbrain write-request -- ${row.request_id} and check the owner with gbrain sources writer status --source ${row.source_id} --json before any new consolidation.`,{ fix: receiptFix(row) });+ const before = await factPreimages(tx, row.source_id, facts.map(f => f.id));for (const fact of facts) await tx.consolidateFact(fact.id, take.id);const chronological = [...facts].sort((a, b) => Date.parse(String(a.value.valid_from)) - Date.parse(String(b.value.valid_from)) || a.id - b.id);for (let i = 0; i < chronological.length - 1; i++) {await tx.executeRaw('UPDATE facts SET valid_until=$1::timestamptz WHERE source_id=$2 AND id=$3',[chronological[i + 1].value.valid_from, row.source_id, chronological[i].id]);}+ await recordConsolidationGeneration(tx, row.source_id, row.slug, before);return { ...outcome, noop: false, facts_consolidated: facts.length, takes_written: existing ? 0 : 1, take_id: Number(take.id) };} };}diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex 26dbb9d00f..d6c750eed9 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -133,6 +133,12 @@ export interface SyncStatus {connector_last_error: import('./connector-status.ts').ConnectorLastError | null;/** #7010: Git effects of the source whose local commit has not reached the remote (retrying or parked on a push code), with the fix; `next` falls back to a parked or conflicted one's fix. */git_push_holds: GitPushHold[];+ /**+ * GBRA-161 PR 2: pages of the source whose facts or takes fence the generation primitive held (`fence_absent`: the+ * page was written without the fence, so its rows stayed live), at most 20, each with the ask-the-user fix. `next`+ * falls back to the first one's fix.+ */+ fence_holds: import('../generations/fence.ts').FenceHoldEntry[];next: Action | null;/*** #6712 PR 2 (L5): the source's state in the sync outcome vocabulary (`synced` | `resumable` | `blocked`) and why@@ -366,6 +372,7 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts: { status: 'unknown' as const, reason: 'not_read: run sync status with --detail', recovery_next: recovery.status === 'ok' && recovery.first ? recoveryAction(sourceId, recovery.first) : undefined };const connectorLastError = await (await import('./connector-status.ts')).readConnectorLastError(engine, sourceId);const gitPushHolds = committed?.git_push_held ? await readGitPushHolds(engine, [sourceId]) : [];+ const fenceHolds = await (await import('../generations/fence.ts')).fenceHoldEntries(engine, [sourceId]);const [state, stateReason] = statusState({ human: !!(liveError?.needs_human), heldForHuman: holds.some(hold => hold.needs_human), oldest, recovery, liveJob: liveJob !== null, unfinished, lastError: !!liveError, actionable: actionable.length > 0, holds: holds.length > 0, pass: passState });const admission = await syncAdmissionStatus(engine, sourceId, source.incarnation,{ stored: source.admission_stored, row_value: source.admission_row_value, set_at: source.admission_set_at });@@ -375,11 +382,11 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, optscommitted_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob, holds, identity_downgrades: await withIdentityRemedies(engine, await listIdentityDowngrades(engine, [sourceId])), last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),needs_human_from: !human ? null : 'path' in human && 'held_since' in human ? { kind: 'hold', path: human.path, slug: human.slug, code: human.code } : { kind: 'last_error', code: human.code },resume_argv: resume, ...blockers, cursors: detail ? await liveCursors(engine, sourceId, source.incarnation, selected?.key ?? null, failures) : [],- terminal_failures: terminal, connector_last_error: connectorLastError, git_push_holds: gitPushHolds, next: next ?? recovery_next ?? passNext ?? (stateReason === 'request_pending' && oldest.status === 'ok' && oldest.request ? { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify,+ terminal_failures: terminal, connector_last_error: connectorLastError, git_push_holds: gitPushHolds, fence_holds: fenceHolds, next: next ?? recovery_next ?? passNext ?? (stateReason === 'request_pending' && oldest.status === 'ok' && oldest.request ? { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify,why: `Write request ${oldest.request.request_id} of this source is still ${oldest.request.state}${oldest.request.step ? ` (step ${oldest.request.step})` : ''}; a running owner finishes it on its own, and the next sync of this source drains it.` } satisfies Action: stateReason === 'status_unknown' ? { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,why: `The oldest-blocker or recovery probe did not answer within ${SYNC_STATUS_PROBE_MS / 1000} s, so this status does not know the state (it is not reported synced). Rerun it after a short wait; gbrain doctor --json checks the database if it keeps timing out.` } satisfies Action- : gitPushHolds.find(hold => hold.conflict || hold.parked)?.fix ?? null),+ : gitPushHolds.find(hold => hold.conflict || hold.parked)?.fix ?? fenceHolds[0]?.fix ?? null),state, reason: stateReason,oldest_blocker: oldest, recovery, checkpoint_blockers_read: detail ? { status: 'read' } : notRead('checkpoint blocker list'),cursors_read: detail ? { status: 'read' } : notRead('live cursor'), terminal_failures_read: detail ? { status: 'read' } : notRead('terminal-failure summary'),diff --git a/test/extract-facts-phase.test.ts b/test/extract-facts-phase.test.tsindex 2391d3a410..93035aba2f 100644--- a/test/extract-facts-phase.test.ts+++ b/test/extract-facts-phase.test.ts@@ -16,6 +16,7 @@ import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';import { parseFactsFence } from '../src/core/facts-fence.ts';+import { emptyFenceBlock } from '../src/core/generations/fence.ts';import { importFromContent } from '../src/core/import-file.ts';import { acquirePageLock } from '../src/core/page-lock.ts';import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';@@ -85,6 +86,32 @@ ${rows}<!--- gbrain:facts:end -->`;++/**+ * GBRA-161 PR 2 (D4): a page whose facts fence is absent keeps its rows (the fact generation holds `fence_absent` and the+ * owner decides); writing the empty fence is the deletion, and it retires every row (`fenceParsedEmpty`).+ */+async function expectAbsentHoldsThenEmptyFenceRetires(slug: string, write: (body: string) => Promise<void>, body: string): Promise<void> {+ await write(body);+ const held = await runExtractFacts(engine, { slugs: [slug] });+ expect(held.factsDeleted).toBe(0);+ expect(held.warnings.some(w => w.includes('FACTS_FENCE_BELOW_SENTINEL'))).toBe(false);+ expect(held.warnings.filter(w => w.includes('FACTS_FENCE_HELD: fence_absent'))).toHaveLength(1);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const kept = await (engine as any).db.query(`SELECT COUNT(*) AS n FROM facts WHERE source_markdown_slug = $1 AND expired_at IS NULL AND row_num IS NOT NULL`, [slug]);+ expect(Number(kept.rows[0].n)).toBe(1);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const holds = await (engine as any).db.query(`SELECT held_reason FROM derived_generations WHERE kind = 'fact_fence' AND owner_key = $1 AND state = 'held'`, ['page:' + slug]);+ expect(holds.rows.map((row: { held_reason: string }) => row.held_reason)).toEqual(['fence_absent']);+ await write(body + '\n' + emptyFenceBlock('facts'));+ const retired = await runExtractFacts(engine, { slugs: [slug] });+ expect(retired.factsDeleted).toBe(1);+ expect(retired.warnings).toEqual([]);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const rows = await (engine as any).db.query(`SELECT COUNT(*) AS n FROM facts WHERE source_markdown_slug = $1 AND (expired_at IS NULL OR row_num IS NOT NULL)`, [slug]);+ expect(Number(rows.rows[0].n)).toBe(0);+}+describe('runExtractFacts — happy path', () => {test('reconciles fence facts into DB for a single page', async () => {const body = FACT_FENCE(@@ -692,26 +719,14 @@ describe('runExtractFacts — happy path', () => {expect(rows.rows.map((row: { fact: string }) => row.fact)).toEqual(['Seeded']);});- test('page with no facts fence → its fence rows are expired and detached (empty fence reconciles to an empty active index)', async () => {+ test('page with no facts fence → its fence rows are kept (held fence_absent); an empty fence reconciles to an empty active index', async () => {await putPage('people/alice', FACT_FENCE(`| 1 | seeded | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,));await runExtractFacts(engine, { slugs: ['people/alice'] });- // Now write a fact-less version of the page.- await putPage('people/alice', '# Just a page\n\nNo fence.\n');- const r = await runExtractFacts(engine, { slugs: ['people/alice'] });-- expect(r.pagesWithFacts).toBe(0);- expect(r.factsInserted).toBe(0);- expect(r.factsDeleted).toBe(1);-- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const rows = await (engine as any).db.query(- `SELECT COUNT(*) AS n FROM facts WHERE source_markdown_slug = 'people/alice'- AND (expired_at IS NULL OR row_num IS NOT NULL)`,- );- expect(Number(rows.rows[0].n)).toBe(0);+ // Now write a fact-less version of the page: GBRA-161 PR 2 holds it; the empty fence is the deletion.+ await expectAbsentHoldsThenEmptyFenceRetires('people/alice', body => putPage('people/alice', body), '# Just a page\n\nNo fence.\n');});test('#3625 / #6686: a lone Facts fence below the timeline sentinel reconciles from where it lives, not as a deleted fence', async () => {@@ -767,18 +782,9 @@ describe('runExtractFacts — happy path', () => {));await runExtractFacts(engine, { slugs: ['people/alice'] });- await putPageWithTimeline('people/alice', '# Just a page\n\nNo fence.\n', 'Some unrelated timeline prose.\n');- const r = await runExtractFacts(engine, { slugs: ['people/alice'] });-- expect(r.factsDeleted).toBe(1);- expect(r.warnings.some(w => w.includes('FACTS_FENCE_BELOW_SENTINEL'))).toBe(false);-- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const rows = await (engine as any).db.query(- `SELECT COUNT(*) AS n FROM facts WHERE source_markdown_slug = 'people/alice'- AND (expired_at IS NULL OR row_num IS NOT NULL)`,- );- expect(Number(rows.rows[0].n)).toBe(0);+ // GBRA-161 PR 2: a truly absent fence now holds (fence_absent) instead of wiping; the empty fence is the deletion.+ await expectAbsentHoldsThenEmptyFenceRetires('people/alice',+ body => putPageWithTimeline('people/alice', body, 'Some unrelated timeline prose.\n'), '# Just a page\n\nNo fence.\n');});test('#3625 adversarial review finding: the marker merely mentioned inside a ```code block``` does not block a genuine deletion', async () => {@@ -790,15 +796,10 @@ describe('runExtractFacts — happy path', () => {));await runExtractFacts(engine, { slugs: ['people/alice'] });- await putPageWithTimeline(- 'people/alice',- '# Alice\n\nThe real Facts fence was removed.\n',- '## Docs\n\n```markdown\n<!--- gbrain:facts:begin -->\nexample only\n```\n',- );- const r = await runExtractFacts(engine, { slugs: ['people/alice'] });-- expect(r.factsDeleted).toBe(1);- expect(r.warnings).toEqual([]);+ // GBRA-161 PR 2: the mention is still not a fence (no FACTS_FENCE_BELOW_SENTINEL), so the page's fence is absent and+ // holds; the empty fence, written beside the same mention, is the genuine deletion and is not blocked by it.+ await expectAbsentHoldsThenEmptyFenceRetires('people/alice',+ body => putPageWithTimeline('people/alice', body, '## Docs\n\n```markdown\n<!--- gbrain:facts:begin -->\nexample only\n```\n'), '# Alice\n\nThe real Facts fence was removed.\n');});test('#3625 adversarial review finding: the marker merely quoted in prose does not block a genuine deletion', async () => {@@ -807,15 +808,10 @@ describe('runExtractFacts — happy path', () => {));await runExtractFacts(engine, { slugs: ['people/alice'] });- await putPageWithTimeline(- 'people/alice',- '# Alice\n\nThe real Facts fence was removed.\n',- '> Historical docs mention the token <!--- gbrain:facts:begin -->, but this is not a fence.\n',- );- const r = await runExtractFacts(engine, { slugs: ['people/alice'] });-- expect(r.factsDeleted).toBe(1);- expect(r.warnings).toEqual([]);+ // GBRA-161 PR 2: the mention is still not a fence (no FACTS_FENCE_BELOW_SENTINEL), so the page's fence is absent and+ // holds; the empty fence, written beside the same mention, is the genuine deletion and is not blocked by it.+ await expectAbsentHoldsThenEmptyFenceRetires('people/alice',+ body => putPageWithTimeline('people/alice', body, '> Historical docs mention the token <!--- gbrain:facts:begin -->, but this is not a fence.\n'), '# Alice\n\nThe real Facts fence was removed.\n');});test('#3625 control: a genuine unbalanced marker (own line, not inside a code block) still blocks deletion', async () => {@@ -849,15 +845,10 @@ describe('runExtractFacts — happy path', () => {));await runExtractFacts(engine, { slugs: ['people/alice'] });- await putPageWithTimeline(- 'people/alice',- '# Alice\n\nThe real Facts fence was removed.\n',- '## Docs\r\n\r\n```markdown\r\n<!--- gbrain:facts:begin -->\r\nexample only\r\n```\r\n',- );- const r = await runExtractFacts(engine, { slugs: ['people/alice'] });-- expect(r.factsDeleted).toBe(1);- expect(r.warnings).toEqual([]);+ // GBRA-161 PR 2: the mention is still not a fence (no FACTS_FENCE_BELOW_SENTINEL), so the page's fence is absent and+ // holds; the empty fence, written beside the same mention, is the genuine deletion and is not blocked by it.+ await expectAbsentHoldsThenEmptyFenceRetires('people/alice',+ body => putPageWithTimeline('people/alice', body, '## Docs\r\n\r\n```markdown\r\n<!--- gbrain:facts:begin -->\r\nexample only\r\n```\r\n'), '# Alice\n\nThe real Facts fence was removed.\n');});test('#3625 adversarial review round 2: two identical code-block mentions of the marker do not false-positive', async () => {@@ -867,15 +858,10 @@ describe('runExtractFacts — happy path', () => {await runExtractFacts(engine, { slugs: ['people/alice'] });const codeBlock = '```markdown\n<!--- gbrain:facts:begin -->\nexample only\n```\n';- await putPageWithTimeline(- 'people/alice',- '# Alice\n\nThe real Facts fence was removed.\n',- `${codeBlock}\n${codeBlock}`,- );- const r = await runExtractFacts(engine, { slugs: ['people/alice'] });-- expect(r.factsDeleted).toBe(1);- expect(r.warnings).toEqual([]);+ // GBRA-161 PR 2: the mention is still not a fence (no FACTS_FENCE_BELOW_SENTINEL), so the page's fence is absent and+ // holds; the empty fence, written beside the same mention, is the genuine deletion and is not blocked by it.+ await expectAbsentHoldsThenEmptyFenceRetires('people/alice',+ body => putPageWithTimeline('people/alice', body, `${codeBlock}\n${codeBlock}`), '# Alice\n\nThe real Facts fence was removed.\n');});test('#3625 via the real MCP write path: a stray fence below the sentinel is preserved even when import-file.ts is in play', async () => {diff --git a/test/extract-facts-reconcile-drain.test.ts b/test/extract-facts-reconcile-drain.test.tsindex 62028d33f3..e159387da6 100644--- a/test/extract-facts-reconcile-drain.test.ts+++ b/test/extract-facts-reconcile-drain.test.ts@@ -28,6 +28,7 @@ import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';import type { BrainEngine } from '../src/core/engine.ts';import { applyFactsReconcileBacklog, readFactsReconcileBacklog } from '../src/core/facts/reconcile-watermark.ts';import { acquirePageLock } from '../src/core/page-lock.ts';+import { emptyFenceBlock } from '../src/core/generations/fence.ts';import { managedPersistenceEnabled } from '../src/core/persistence/ownership.ts';import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';@@ -121,7 +122,7 @@ for (const backend of testBackends()) {expect((await activeFacts(engine)).map(f => f.fact)).toEqual(['Claim one', 'Claim two']);}), 60_000);- test(`${backend}: removing the whole fence expires its rows; cli: facts and withdrawals survive`, () => brain(databaseUrl, async ({ engine }) => {+ test(`${backend}: removing the whole fence holds its rows; the empty fence expires them; cli: facts and withdrawals survive`, () => brain(databaseUrl, async ({ engine }) => {await put(engine, 'people/alice-example', body(`${row(1, 'Claim one')}\n${row(2, 'Claim two')}`));await drainRun(engine);await engine.insertFacts( // gbrain-allow-direct-insert: test fixture for a conversation-origin row@@ -131,6 +132,12 @@ for (const backend of testBackends()) {await engine.executeRaw(`INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash) VALUES ('default', 'world', 'people/alice-example', 'abc123')`);await put(engine, 'people/alice-example', '# Page\n\nProse only now.');+ const held = await drainRun(engine);+ expect(held.factsDeleted).toBe(0);+ expect((await activeFacts(engine)).map(f => f.fact)).toEqual(['Claim one', 'Claim two', 'Said in a meeting']);+ const [hold] = await engine.executeRaw<{ held_reason: string }>("SELECT held_reason FROM derived_generations WHERE kind='fact_fence' AND state='held'");+ expect(hold?.held_reason).toBe('fence_absent');+ await put(engine, 'people/alice-example', `# Page\n\nProse only now.\n\n${emptyFenceBlock('facts')}`);const r = await drainRun(engine);expect(r.factsDeleted).toBe(2);expect(await activeFacts(engine)).toEqual([{ slug: 'people/alice-example', fact: 'Said in a meeting', row_num: 100 }]);diff --git a/test/fence-marker-projection.test.ts b/test/fence-marker-projection.test.tsindex bed1643f09..e507c1c864 100644--- a/test/fence-marker-projection.test.ts+++ b/test/fence-marker-projection.test.ts@@ -9,6 +9,7 @@ import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';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 { emptyFenceBlock } from '../src/core/generations/fence.ts';/*** The canonical projection mirrors the body's fences into the takes and facts@@ -87,6 +88,10 @@ test('a code example beside the real fence does not block ordinary writes', asynawait put('deleted', `${example}\n${fences('Example belief', 'Example fact')}`);await put('deleted', example);+ expect(await rows('deleted')).toEqual({ takes: 1, facts: 1 });+ expect(await engine.executeRaw("SELECT kind, held_reason FROM derived_generations WHERE owner_key='page:deleted' AND state='held' ORDER BY kind"))+ .toEqual([{ kind: 'fact_fence', held_reason: 'fence_absent' }, { kind: 'take_fence', held_reason: 'fence_absent' }]);+ await put('deleted', `${example}\n${emptyFenceBlock('takes')}\n${emptyFenceBlock('facts')}`);expect(await rows('deleted')).toEqual({ takes: 0, facts: 0 });});diff --git a/test/pathological/g2-consolidation-generations.test.ts b/test/pathological/g2-consolidation-generations.test.tsnew file mode 100644index 0000000000..649322493b--- /dev/null+++ b/test/pathological/g2-consolidation-generations.test.ts@@ -0,0 +1,102 @@+/**+ * GBRA-161 PR 2 (B-17, #6023): the dream consolidate phase publishes through the generation primitive. A cluster whose+ * typed claims tie at one instant is held (`generation_held`, reason `tie`) with nothing written; a strict+ * chronological chain records each member's before-state, and `gbrain repair generations --kind consolidation --mode+ * restore` reopens it. PGLite; Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';+import { runPhaseConsolidate } from '../../src/core/cycle/phases/consolidate.ts';+import type { GenerationsSelection } from '../../src/core/generations/repair.ts';+import { generationHeldCheck } from '../../src/commands/doctor/checks/generations.ts';+import { resolveRepairScope, type RepairResult } from '../../src/core/repair/core.ts';+import { repairRunner } from '../../src/core/repair/registry.ts';+import { managedPersistenceEnabled } from '../../src/core/persistence/ownership.ts';+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { withEnv } from '../helpers/with-env.ts';+import { pathologicalArms } from './harness.ts';++const SLUG = 'companies/probe-example';+const VECTOR = '[' + [1, ...Array(1535).fill(0)].join(',') + ']';++async function withBrain(databaseUrl: string | undefined, run: (engine: BrainEngine) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-g2c-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ _resetWriteThroughCacheForTest();+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ expect(await managedPersistenceEnabled(engine)).toBe(false);+ await engine.executeRaw("INSERT INTO pages(slug,type,title) VALUES($1,'company','Probe Example') ON CONFLICT DO NOTHING", [SLUG]);+ await run(engine);+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++async function seed(engine: BrainEngine, fact: string, at: string, claim?: { metric: string; unit: string; period: string; value: number }): Promise<number> {+ const [row] = await engine.executeRaw<{ id: number }>(+ `INSERT INTO facts(source_id,entity_slug,fact,kind,source,visibility,valid_from,confidence,embedding,embedded_at,embedding_model,embedded_text_hash,+ claim_metric,claim_unit,claim_period,claim_value)+ VALUES('default',$1,$2,'fact','synthetic fixture','world',$3::timestamptz,0.9,$4::vector,$3::timestamptz,'openai:text-embedding-3-large',md5($2),$5,$6,$7,$8)+ RETURNING id`, [SLUG, fact, at, VECTOR, claim?.metric ?? null, claim?.unit ?? null, claim?.period ?? null, claim?.value ?? null]);+ return Number(row.id);+}++const facts = (engine: BrainEngine) => engine.executeRaw<{ id: number; valid_until: string | null; consolidated: boolean; into: number | null }>(+ 'SELECT id, valid_until::text AS valid_until, consolidated_at IS NOT NULL AS consolidated, consolidated_into AS "into" FROM facts ORDER BY id');++async function repair(engine: BrainEngine, selection: GenerationsSelection, expectHash?: string): Promise<RepairResult> {+ const scope = await resolveRepairScope(engine, 'default');+ const quiet = { info: () => {}, warn: () => {}, error: () => {} };+ return (await repairRunner(engine, { apply: expectHash !== undefined, noEmbed: true, logger: quiet })).run('generations', scope,+ { explicit: true, sourceFlag: 'default', generations: selection, ...(expectHash ? { expect: expectHash } : {}) });+}++beforeAll(() => configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} }));+afterAll(() => resetGateway());++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`GBRA-161 PR 2 consolidation generations (${backend})`, () => {+ test('#6023: a same-instant tie is held as generation_held tie with nothing written', async () => {+ await withBrain(databaseUrl, async engine => {+ const claim = { metric: 'deposit_amount', unit: 'USD', period: '2026-01-01' };+ const a = await seed(engine, 'The deposit amount was initially reported as $100,000.', '2026-01-01T00:00:00Z', { ...claim, value: 100000 });+ const b = await seed(engine, 'Correction: the deposit amount is $82,000.', '2026-01-01T00:00:00Z', { ...claim, value: 82000 });+ await engine.executeRaw(`INSERT INTO facts(source_id,entity_slug,fact,kind,source,visibility,valid_from)+ VALUES('default',$1,'A separate invoice has not been approved.','fact','synthetic fixture','world','2026-01-01T00:00:00Z')`, [SLUG]);+ await runPhaseConsolidate(engine, {});+ expect((await facts(engine)).slice(0, 2)).toEqual([{ id: a, valid_until: null, consolidated: false, into: null }, { id: b, valid_until: null, consolidated: false, into: null }]);+ const held = await engine.executeRaw<{ owner_key: string; held_reason: string }>(+ "SELECT owner_key, held_reason FROM derived_generations WHERE kind='consolidation' AND state='held'");+ expect(held).toEqual([{ owner_key: `entity:${SLUG}:cluster:${a},${b}`, held_reason: 'tie' }]);+ expect((await generationHeldCheck(engine, ['default'])).status).toBe('warn');+ await runPhaseConsolidate(engine, {});+ expect(await engine.executeRaw("SELECT 1 FROM derived_generations WHERE kind='consolidation'")).toHaveLength(1);+ });+ }, 120_000);++ test('a strict chain records each member before-state and repair generations restore reopens it', async () => {+ await withBrain(databaseUrl, async engine => {+ const claim = 'Acme-example reports steady recurring revenue growth.';+ const ids = [await seed(engine, claim, '2026-01-15T00:00:00Z'), await seed(engine, claim, '2026-04-12T00:00:00Z'), await seed(engine, claim, '2026-07-08T00:00:00Z')];+ const result = await runPhaseConsolidate(engine, {});+ expect(result.details.facts_consolidated).toBe(3);+ const closed = await facts(engine);+ expect(closed.map(row => [row.valid_until !== null, row.consolidated])).toEqual([[true, true], [true, true], [false, true]]);+ const selection: GenerationsSelection = { kind: 'consolidation', mode: 'restore', key: `entity:${SLUG}:cluster:${ids.join(',')}` };+ const preview = await repair(engine, selection);+ expect(preview.listing).toEqual([{ item: `default:${selection.key}`, class: 'restore', detail: 'generation 2 back to 1: revive 3, retire 0' }]);+ expect((await repair(engine, selection, preview.preview_hash)).outcomes).toEqual({ restored: 1 });+ expect(await facts(engine)).toEqual(ids.map(id => ({ id, valid_until: null, consolidated: false, into: null })));+ await runPhaseConsolidate(engine, {});+ expect(await facts(engine)).toEqual(ids.map(id => ({ id, valid_until: null, consolidated: false, into: null })));+ });+ }, 120_000);+ });+}diff --git a/test/pathological/g2-fence-generations.test.ts b/test/pathological/g2-fence-generations.test.tsnew file mode 100644index 0000000000..6eda80a7f2--- /dev/null+++ b/test/pathological/g2-fence-generations.test.ts@@ -0,0 +1,31 @@+/**+ * GBRA-161 PR 2: facts and takes publish through the generation primitive. A canonical fence retires rows only when it+ * is read whole and valid; an absent, unread or segmented fence holds (`generation_held`, reason `fence_absent`).+ * PGLite; Postgres when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { pathologicalArms } from './harness.ts';+import { FACTS_FENCE, managedSource, PERSON } from './managed-fixture.ts';++const ROW = (n: number, claim: string) => `| ${n} | ${claim} | fact | 1.0 | world | medium | 2020-01-01 | | chat | |`;+const SLUG = 'people/alice-example';++async function factRows(engine: BrainEngine, sourceId: string) {+ return engine.executeRaw<{ fact: string; row_num: number | null; expired: boolean }>(+ 'SELECT fact, row_num, expired_at IS NOT NULL AS expired FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ORDER BY id', [sourceId, SLUG]);+}++describe('GBRA-161 PR 2 fence generations', () => {+ for (const { backend, databaseUrl } of pathologicalArms()) {+ test(`[${backend}] B-5: a page write whose body lost its facts fence keeps every fact live`, async () => {+ await managedSource(databaseUrl, async () => {}, async ({ engine, sourceId, put }) => {+ await put(SLUG, PERSON('Alice Example', FACTS_FENCE([ROW(1, 'Alice founded acme-example'), ROW(2, 'Alice plays chess'), ROW(3, 'Alice lives in Lisbon')].join('\n'))));+ expect((await factRows(engine, sourceId)).map(row => [row.row_num, row.expired])).toEqual([[1, false], [2, false], [3, false]]);+ await put(SLUG, PERSON('Alice Example', 'Alice is an example person. The facts section was removed in this edit.\n'));+ expect((await factRows(engine, sourceId)).map(row => [row.fact, row.row_num, row.expired])).toEqual([+ ['Alice founded acme-example', 1, false], ['Alice plays chess', 2, false], ['Alice lives in Lisbon', 3, false]]);+ });+ }, 120_000);+ }+});