Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: keep DB-only take grades on publish; close inherited purge read gaps

garrytand2d4017ec9f2
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index c0eb15ad43..896e61e8a0 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -1,7 +1,7 @@
# Canonical writer census for issue #5105. Counts include lexical references in comments.
# path write-reference ceiling enforcement boundary review rationale
src/core/persistence/activation.ts 0 coordinator Trusted private administration requires explicit quiescence and durable refusal records before enabling managed canonical writer enforcement.
-src/core/persistence/canonical-projections.ts 9 coordinator Facts, takes, timeline, chunks and aliases install within the guarded canonical publication transaction before its receipt commits.
+src/core/persistence/canonical-projections.ts 10 coordinator Facts, takes, timeline, chunks and aliases install within the guarded canonical publication transaction before its receipt commits; a take whose claim changed in place loses its stored resolution there, and a fence row without resolution cells keeps it.
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/takes-prepare.ts 4 coordinator Semantic takes apply only through the journal publication callback after current revision, holder and authority validation. takes_remove deletes the removed row inside the same coordinated apply (#5167).
@@ -74,7 +74,7 @@ src/core/facts/backstop.ts 3 engine_guard Canonical table SQL trigger requires c
src/core/facts/fence-write.ts 2 coordinator Managed brains publish fence rows through the managed_facts_entity intent before any file or row write; unmanaged writes keep the source filesystem ownership check before editing canonical fact fences.
src/core/facts/forget.ts 4 filesystem_guard Managed callers journal withdrawal; legacy filesystem helper and the supersession-only expiry require coordinated write.
src/core/facts/proposal-supersede.ts 4 filesystem_guard System One S9 accept/undo (local CLI only): unmanaged brains update the two facts rows and strike or restore the fence row in one transaction under the source filesystem lock and page lock, publishing the file last; managed brains run the same change as the coordinator mutation decide_proposal.
-src/core/facts/relink-publish.ts 2 coordinator #5836 facts relink (local CLI only, managed or not): the coordinator mutation relink_facts re-locks each pinned unlinked fact, moves linked rows onto their entity fence positions (and retires exact duplicates expired and detached) ahead of the page's canonical projection in the same publication, then restores take resolutions and records the attempt and conflict-sweep handoff in that transaction.
+src/core/facts/relink-publish.ts 2 coordinator #5836 facts relink (local CLI only, managed or not): the coordinator mutation relink_facts re-locks each pinned unlinked fact, moves linked rows onto their entity fence positions (and retires exact duplicates expired and detached) ahead of the page's canonical projection in the same publication and records the attempt and conflict-sweep handoff in that transaction.
src/core/persistence/loop-fact-retirement.ts 1 coordinator #5869 loops_close fact retirement (managed or not, local or write-bound remote): the coordinator mutation (operation loops_close, intent retire_loop_fact) expires the commitment fact and strikes its fence row through the entity page publication in one transaction, only when the fact is in the loop's source and no other open loop references it.
src/core/facts/withdrawal-schema.ts 1 schema Migration v174 DDL/backfill expires fact rows that match a folded withdrawal fingerprint; schema installation runs under coordinated activation, which quiesces canonical writers.
src/core/facts/withdrawal.ts 2 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.
@@ -138,7 +138,7 @@ src/commands/enrich.ts 0 coordinator A managed brain preflights maintenance auth
src/core/persistence/source-lifecycle.ts 7 coordinator Native affected roots precede topology, source, principal and receipt guards; every shared-root generation and old queued intent changes together.
src/core/persistence/topology-recovery.ts 2 coordinator Verified directory-swap recovery checks source incarnation, current logical manifest and physical identity before topology commitment; permanent receipt IDs survive deletion.
src/core/persistence/connector-sync.ts 4 coordinator Connector freshness and source-scoped deletion commit through original/current authority, source and revision guards, canonical publication and checkpoint CAS. A skipped unchanged checkpoint save stamps sources.last_sync_at/newest_content_at (never page content) inside withCoordinatedWrite, in a transaction that first asserts the connector sync lease, scoped to the source incarnation (#5686/#5470). Its importFromContent calls carry prepare and run inside the coordinator publication.
-src/core/persistence/prepared-maintenance.ts 5 coordinator Named local maintenance uses native owner publication; contributing semantic facts and take lifecycle are revalidated and committed together with canonical files and receipts; a chronicle event page and its depth timeline projection commit in one publication; v0.32.2 fact adoption re-locks the pinned legacy facts and their fence positions and sets their row positions ahead of the canonical projection in the same publication, then restores take resolutions recorded only in the database that the unchanged takes fence projection would clear.
+src/core/persistence/prepared-maintenance.ts 4 coordinator Named local maintenance uses native owner publication; contributing semantic facts and take lifecycle are revalidated and committed together with canonical files and receipts; a chronicle event page and its depth timeline projection commit in one publication; v0.32.2 fact adoption re-locks the pinned legacy facts and their fence positions and sets their row positions ahead of the canonical projection in the same publication.
src/core/persistence/facts-prepare.ts 3 coordinator Multi-entity fact publication rechecks original/current source authority, origin and target revisions, withdrawals and deduplication under coordinated page locks; a direct single-fact write (supersede intent) strikes the superseded fence row and expires and links the old fact in the same publication transaction.
src/core/persistence/file-repair.ts 5 coordinator The managed_file_repair preparer (#5988) re-screens and re-prepares the repaired file exactly as a managed sync import (importFromContent with prepare, no write) and refuses any result that differs from the previewed digest; its apply runs inside the coordinated publication with the page key locked: updateSlug and the implicit type for a rename, the prepared import, source_path, projections, the hold clear and the import provenance commit with the file write.
src/core/embed-facts.ts 1 projection Explicit bounded repair updates only fact embedding projections with selected-brain off-switch, invocation budget, source incarnation and fact-row version checks before atomic installation.
diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.ts
index 0be2b89dfb..ac7ee0b3b1 100644
--- a/scripts/check-engine-sql-dynamic.ts
+++ b/scripts/check-engine-sql-dynamic.ts
@@ -66,6 +66,7 @@ const VETTED_BUILDERS: Record<string, string> = {
privateLinkOriginFilterFragment: 'src/core/search/private-visibility.ts: constant link-origin visibility predicate over a caller alias',
privateTimelineEventFilterFragment: 'src/core/search/private-visibility.ts: constant timeline-event visibility predicate over a caller alias',
privateSnapshotFilterFragment: 'src/core/search/private-visibility.ts: constant snapshot visibility predicate over a caller alias',
+ rederiveHiddenSql: 'src/core/eligibility/sql.ts: constant needs_rederive NOT EXISTS predicate over a literal table name and caller alias; no values',
privateProvenanceFilterFragment: 'src/core/search/private-visibility.ts: constant fact-provenance visibility predicate over a caller alias',
rankingLinkSql: 'src/core/link-ranking-policy.ts: constant non-ranking link-type predicate (code-constant type names) over a caller alias',
vectorLiteralSql: 'src/core/engine-sql/facts.ts: master\'s inlined vector literal; toPgVectorLiteral output (numbers joined by commas) + a ::vector/::halfvec constant',
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index f52de40059..24bb5545c5 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -641,6 +641,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// #6610: classic unfenced facts on database-only pages.
{ since: '0.60.249.0', text: 'On a brain without managed persistence, `extract_facts` (and the v0.32.2 fence step) now fences unfenced facts of a database-only page (no recorded file and none at its slug path) into the page\'s database body when such a write is database-only (`sync.write_through` off, or on Postgres an unbound source with `persistence.unbound_write=database_only`, which stamps the page `unbound_source`), instead of reporting a missing canonical file and halting the facts fence every run. Without that opt-in the rows stay unfenced and their page skips reconciliation, but they no longer count as pending (`legacyRowsPending`) or trigger the guard; doctor `fence_integrity` lists them under `unbound_legacy_facts` and asks the user about the opt-in, and the migration reports them as `skipped_unbound_source`.' },
{ since: '0.60.249.0', text: 'On a brain without managed persistence, `gbrain restore` / `restore_page` of a soft-deleted page whose recorded file is gone from the checkout now refuses (`source_changed`, detail `canonical_file_absent`) when the restore writes no file, instead of restoring a page the next `gbrain sync --full` deletes again. Put the file back and sync, or pass `--detach` (`detach: true`) to restore it database-only (`database_only_reason=detached`, no `source_path`); a file synced back at its path binds the page again. New doctor check `missing_recorded_files` lists live pages a full sync would delete this way.' },
+ // Pre-W1 integrity wave (belief ledger Q6 + inherited purge read gaps). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.249.0', text: 'A take graded only in the database (for example by `grade_takes` on a source without managed persistence) keeps its grade when its page is published again from a fence that has no resolution cells: a prose edit, a re-import, a sync or `revert_version` to a version from before the grade. Before, every such publish erased the grade. A fence that carries resolution cells still writes them, and a take whose claim is edited in place (same row number) now drops the old claim\'s grade.' },
+ { since: '0.60.249.0', text: 'After `purge_fact` or a page purge, no read returns the purged text from what the purge hid: a page a purge hid for re-derivation now reads as missing in `get_page` and `fetch` (even with `include_deleted`) and returns no `get_versions` history, and a page purge now hides rows derived from the page and its facts, as `purge_fact` already did. `purge_fact` now redacts every retained version of a page (it stopped after 5,000), and its receipt\'s `pages` and `page_versions` stores also report a page or version that still states the claim in its title or frontmatter, alongside prose (`out_of_scope: source_prose`).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index 9a24d03904..8463703553 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -23,6 +23,7 @@ import { sanitizeText } from '../batch-rows.ts';
import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion } from '../search/safe-chunks.ts';
import { privatePagesFilterFragment, privateSnapshotFilterFragment } from '../search/private-visibility.ts';
import { quarantineFilterFragment } from '../quarantine.ts';
+import { rederiveHiddenSql } from '../eligibility/sql.ts';
import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, isUndefinedTableError, warnOncePerProcess } from '../utils.ts';
import { DELETE_BATCH_SIZE } from '../engine-constants.ts';
import { jsonbParam, type SqlExecutor } from './executor.ts';
@@ -899,9 +900,10 @@ const PAGE_VERSION_METADATA_COLUMNS = trustedSql('pv.id, pv.page_id, pv.frontmat
+ 'pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path');
/**
- * Newest first (`pv.id` breaks snapshot_at ties). Scope and privacy
- * predicates sit in WHERE, so `limit` bounds only rows the caller may read;
- * `includeBody: false` never selects the body columns.
+ * Newest first (`pv.id` breaks snapshot_at ties). Scope, privacy and
+ * re-derivation (a page a purge hid) predicates sit in WHERE, so `limit`
+ * bounds only rows the caller may read; `includeBody: false` never selects
+ * the body columns.
*/
export async function getVersions<B extends boolean = true>(
exec: LegacyUnscopedRead,
@@ -919,7 +921,7 @@ export async function getVersions<B extends boolean = true>(
SELECT ${columns} FROM page_versions pv
JOIN pages p ON p.id = pv.page_id
WHERE p.slug = ${slug} ${scope}
- ${privacy}
+ ${privacy} AND ${trustedSql(rederiveHiddenSql('pages', 'p'))}
ORDER BY pv.snapshot_at DESC, pv.id DESC
${limit}
`);
diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.ts
index 6c5d2412ee..543de981db 100644
--- a/src/core/facts/purge-verify.ts
+++ b/src/core/facts/purge-verify.ts
@@ -47,6 +47,15 @@ export interface PurgeReceipt {
tell_user_to_run?: { argv: string[]; why: string };
}
+/**
+ * A page or page-version row (alias `a`) still states the claim: in its body,
+ * timeline, title or frontmatter. `$n` is the lowercased claim, `$n+1` its
+ * JSON-escaped form (frontmatter is matched as JSON text).
+ */
+export const carriesClaimSql = (a: string, n: number) => `(strpos(lower(${a}.compiled_truth),$${n})>0 OR strpos(lower(COALESCE(${a}.timeline,'')),$${n})>0
+ OR strpos(lower(COALESCE(${a}.title,'')),$${n})>0 OR strpos(lower(COALESCE(${a}.frontmatter::text,'')),$${n + 1})>0)`;
+export const claimNeedles = (claim: string): [string, string] => [claim.toLowerCase(), JSON.stringify(claim.toLowerCase()).slice(1, -1)];
+
export const PURGE_PROBE_LIMITS = { rows: 1000, statementMs: 2_000, totalMs: 20_000, gitBytes: 64 * 1024 * 1024, gitMs: 10_000 } as const;
let probeLimits: { rows: number; statementMs: number; totalMs: number } = { ...PURGE_PROBE_LIMITS };
/** Test seam: shrink the probe bounds (null restores them). */
@@ -227,14 +236,13 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purg
[src, target.visibility, target.fact_hash, plan.subject], plan.factIds.length, removed.facts);
await swept('takes', `SELECT 1 FROM takes k JOIN pages p ON p.id=k.page_id WHERE p.source_id=$1 AND gbrain_fact_fingerprint(k.claim)=$2 AND ($3='*' OR p.slug=$3)`,
[src, target.fact_hash, plan.subject], plan.takes.length, removed.takes);
- const prose = { status: 'out_of_scope' as const, reason: 'source_prose', detail: 'The claim text survives outside a facts fence (page prose); purge the page or edit it to remove it.' };
- await swept('pages', `SELECT 1 FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND (strpos(lower(compiled_truth),$2)>0 OR strpos(lower(timeline),$2)>0)`,
- [src, needle], plan.pages.length, removed.pages, prose);
+ const prose = { status: 'out_of_scope' as const, reason: 'source_prose', detail: 'The claim text survives outside a facts fence (page prose, title or frontmatter); purge the page or edit it to remove it.' };
+ await swept('pages', `SELECT 1 FROM pages p WHERE p.source_id=$1 AND p.deleted_at IS NULL AND ${carriesClaimSql('p', 2)}`,
+ [src, ...claimNeedles(claim)], plan.pages.length, removed.pages, prose);
await swept('content_chunks', `SELECT 1 FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.source_id=$1 AND strpos(lower(c.chunk_text),$2)>0`,
[src, needle], plan.pages.length, removed.chunks, prose);
- await swept('page_versions', `SELECT 1 FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1
- AND (strpos(lower(v.compiled_truth),$2)>0 OR strpos(lower(COALESCE(v.timeline,'')),$2)>0)`,
- [src, needle], plan.versions, removed.page_versions, { ...prose, items: (input.prose ?? []).slice(0, 20) });
+ await swept('page_versions', `SELECT 1 FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1 AND ${carriesClaimSql('v', 2)}`,
+ [src, ...claimNeedles(claim)], plan.versions, removed.page_versions, { ...prose, items: (input.prose ?? []).slice(0, 20) });
await swept('persistence_requests', `SELECT 1 FROM persistence_requests WHERE source_id=$1 AND (${['intent', 'outcome', 'error_detail', 'error_message']
.map(c => `strpos(lower(COALESCE(${c}::text,'')),$2)>0 OR strpos(lower(COALESCE(${c}::text,'')),$3)>0`).join(' OR ')})`,
[src, needle, JSON.stringify(claim).slice(1, -1).toLowerCase()], plan.requests.length, removed.persistence_requests);
diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.ts
index fd246d7cc9..7c5856a61d 100644
--- a/src/core/facts/purge.ts
+++ b/src/core/facts/purge.ts
@@ -42,7 +42,7 @@ import { retryWriteAdmission } from '../persistence/admission-retry.ts';
import { findRequestsCarrying, redactionCounterKeys, redactRequestIntents } from '../persistence/intent-redaction.ts';
import { withPageTierKept } from '../trust/fence-append.ts';
import { rebuildPendingPageProjections } from '../page-state/projections.ts';
-import { purgeCompletion, verifyFactPurge, type PurgeReceipt, type StoreCount } from './purge-verify.ts';
+import { carriesClaimSql, claimNeedles, purgeCompletion, verifyFactPurge, type PurgeReceipt, type StoreCount } from './purge-verify.ts';
export const PURGE_OPERATION = 'purge_fact';
const PURGE_TERMINAL_RESERVATION = 64 * 1024;
@@ -108,7 +108,7 @@ export async function planFactPurge(engine: BrainEngine, target: PurgeTarget, al
'SELECT slug,id AS page_id,knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND id=ANY($2::int[])', [target.source_id, extra]) : [];
const pages = [...discovered, ...takePages.map(p => ({ ...p, page_id: Number(p.page_id) }))].sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0);
const [versions] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_id
- WHERE p.source_id=$1 AND (strpos(lower(v.compiled_truth),$2)>0 OR strpos(lower(COALESCE(v.timeline,'')),$2)>0)`, [target.source_id, target.fact.toLowerCase()]);
+ WHERE p.source_id=$1 AND ${carriesClaimSql('v', 2)}`, [target.source_id, ...claimNeedles(target.fact)]);
// #6511 [R5]: a statement timeout of this unindexable substring search is deterministic on a large journal, not contention: the typed code, not a retry.
const requests = await faultPoint('purge:carrying_lookup', { sourceId: target.source_id, operation: PURGE_OPERATION })
.then(() => findRequestsCarrying(engine, target.source_id, target.fact)).catch(error => {
@@ -168,23 +168,31 @@ async function rewritePageBodies(tx: BrainEngine, sourceId: string, pages: Purge
return rewritten;
}
+const VERSION_REDACTION_BATCH = 5000;
+
/** Redact the row from every retained snapshot that carries the claim; returns redacted and still-carrying (prose) counts. */
async function redactPageVersions(tx: BrainEngine, sourceId: string, claim: string, pageIds: number[]): Promise<{ redacted: number; prose: Array<{ slug: string; version_id: number }> }> {
- const needle = claim.toLowerCase();
- const rows = await tx.executeRaw<{ id: number; slug: string; compiled_truth: string; timeline: string | null }>(`SELECT v.id,p.slug,v.compiled_truth,v.timeline
- FROM page_versions v JOIN pages p ON p.id=v.page_id
- WHERE p.source_id=$1 AND (v.page_id=ANY($3::int[]) OR strpos(lower(v.compiled_truth),$2)>0 OR strpos(lower(COALESCE(v.timeline,'')),$2)>0)
- ORDER BY v.id LIMIT 5000`, [sourceId, needle, pageIds]);
+ const [needle, escaped] = claimNeedles(claim);
let redacted = 0;
const prose: Array<{ slug: string; version_id: number }> = [];
- for (const v of rows) {
- const compiled = await dropPurgedFenceRows(tx, sourceId, v.compiled_truth, v.slug);
- const timeline = await dropPurgedFenceRows(tx, sourceId, v.timeline ?? '', v.slug);
- if (compiled !== v.compiled_truth || timeline !== (v.timeline ?? '')) {
- await tx.executeRaw('UPDATE page_versions SET compiled_truth=$2,timeline=$3 WHERE id=$1', [v.id, compiled, timeline]);
- redacted++;
+ for (let after = 0; ;) {
+ const rows = await tx.executeRaw<{ id: number; slug: string; compiled_truth: string; timeline: string | null; metadata: boolean }>(`SELECT v.id,p.slug,v.compiled_truth,v.timeline,
+ (strpos(lower(COALESCE(v.title,'')),$4)>0 OR strpos(lower(COALESCE(v.frontmatter::text,'')),$5)>0) AS metadata
+ FROM page_versions v JOIN pages p ON p.id=v.page_id
+ WHERE p.source_id=$1 AND v.id>$3 AND (v.page_id=ANY($2::int[]) OR ${carriesClaimSql('v', 4)})
+ ORDER BY v.id LIMIT ${VERSION_REDACTION_BATCH}`, [sourceId, pageIds, after, needle, escaped]);
+ if (!rows.length) break;
+ after = Number(rows[rows.length - 1].id);
+ for (const v of rows) {
+ const compiled = await dropPurgedFenceRows(tx, sourceId, v.compiled_truth, v.slug);
+ const timeline = await dropPurgedFenceRows(tx, sourceId, v.timeline ?? '', v.slug);
+ if (compiled !== v.compiled_truth || timeline !== (v.timeline ?? '')) {
+ await tx.executeRaw('UPDATE page_versions SET compiled_truth=$2,timeline=$3 WHERE id=$1', [v.id, compiled, timeline]);
+ redacted++;
+ }
+ if (v.metadata || compiled.toLowerCase().includes(needle) || timeline.toLowerCase().includes(needle)) prose.push({ slug: v.slug, version_id: Number(v.id) });
}
- if (compiled.toLowerCase().includes(needle) || timeline.toLowerCase().includes(needle)) prose.push({ slug: v.slug, version_id: Number(v.id) });
+ if (rows.length < VERSION_REDACTION_BATCH) break;
}
return { redacted, prose };
}
diff --git a/src/core/facts/relink-publish.ts b/src/core/facts/relink-publish.ts
index 1d78dd9854..4041845481 100644
--- a/src/core/facts/relink-publish.ts
+++ b/src/core/facts/relink-publish.ts
@@ -29,7 +29,7 @@ import { formatFenceDate, parseFactsFence, upsertFactRow } from '../facts-fence.
import { digest } from '../persistence/digest.ts';
import type { PreparedMutation } from '../persistence/coordinator.ts';
import type { WriteRequest } from '../persistence/model.ts';
-import { applyPreservingTakeResolutions, readFacts, type FactSnapshot } from '../persistence/prepared-maintenance.ts';
+import { readFacts, type FactSnapshot } from '../persistence/prepared-maintenance.ts';
import { decideSingleFact } from './single-prepare.ts';
import { isFactWithdrawn } from './withdrawal.ts';
import { appendContextNote } from './subject-infer.ts';
@@ -226,7 +226,7 @@ export async function prepareRelinkMutation(engine: BrainEngine, row: WriteReque
outcome.skipped.push({ id: c.id, reason: c.reason });
}
}
- const published = page ? await applyPreservingTakeResolutions(tx, row.page_id, page) : {};
+ const published = page ? await page.apply(tx) : {};
for (const c of planned) {
if (c.action === 'skip') continue;
const f = byId.get(c.id)!;
diff --git a/src/core/ops/get-page-projection.ts b/src/core/ops/get-page-projection.ts
index 81368e61f5..06b37536b9 100644
--- a/src/core/ops/get-page-projection.ts
+++ b/src/core/ops/get-page-projection.ts
@@ -9,6 +9,7 @@ import { renderTrustedText, type TrustFields } from '../eligibility/labels.ts';
import { loadPageTrust } from '../eligibility/stamp.ts';
import { resolveReadEligibility, type ReadEligibility } from '../eligibility/policy.ts';
import { admitsTrust } from '../trust/tier.ts';
+import { rederiveHiddenSql } from '../eligibility/sql.ts';
/**
* #6259: how a get_page reader sees a page the content-quality gate hid as junk.
@@ -121,8 +122,9 @@ export function projectGetPage(page: Page, o: GetPageProjectionOpts) {
/**
* #5575 (A6, CEO-18, ENG-14): get_page and fetch read one page's trust once.
* Returns its label fields and the read eligibility (for the page's timeline
- * rows), or null when the page sits below the effective read floor, which the
- * caller answers exactly like a missing page (no existence oracle).
+ * rows), or null when the page sits below the effective read floor or a purge
+ * hid it for re-derivation (even with include_deleted), which the caller
+ * answers exactly like a missing page (no existence oracle).
*/
export async function pageTrustForRead(ctx: Pick<OperationContext, 'engine' | 'auth'>, page: Pick<Page, 'id'>, minTrust: unknown):
Promise<{ trust: TrustFields; eligibility: ReadEligibility } | null> {
@@ -130,6 +132,9 @@ export async function pageTrustForRead(ctx: Pick<OperationContext, 'engine' | 'a
const trust = (await loadPageTrust(ctx.engine, [{ page_id: page.id, slug: '' }]).catch(() => null))?.byId.get(page.id)
?? { trust_tier: 'unknown' as const, origin: 'unrecorded' };
if (eligibility.floor && !admitsTrust(trust.trust_tier, eligibility.floor)) return null;
+ const [hidden] = await ctx.engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM pages p WHERE p.id = $1 AND NOT ${rederiveHiddenSql('pages', 'p')}`, [page.id]);
+ if (Number(hidden?.n) > 0) return null;
return { trust, eligibility };
}
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index 94b4a597c9..c1a94208b3 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -430,19 +430,26 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num=r.row_num`, [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]);
- // Full canonical versions include resolution fields; a revert restores those
- // fields from Markdown too, without the ordinary immutable-resolution API.
- const resolutions = JSON.stringify(takes.map(take => ({ row_num: take.rowNum, resolved_at: take.resolvedAt ?? null,
+ // 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.
+ const fenceResolved = takes.filter(take => take.resolvedAt !== undefined || take.resolvedQuality !== undefined);
+ const claims = JSON.stringify(takes.map(take => ({ row_num: take.rowNum, claim: take.claim })));
+ const clearChangedResolutions = () => takes.length ? tx.executeRaw(`UPDATE takes k SET resolved_at=NULL,resolved_quality=NULL,
+ resolved_outcome=NULL,resolved_source=NULL,resolved_value=NULL,resolved_unit=NULL,resolved_by=NULL
+ FROM jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text)
+ WHERE k.page_id=$1 AND k.row_num=n.row_num AND k.resolved_at IS NOT NULL AND k.claim IS DISTINCT FROM n.claim`, [id, claims]) : Promise.resolve([]);
+ const resolutions = JSON.stringify(fenceResolved.map(take => ({ row_num: take.rowNum, resolved_at: take.resolvedAt ?? null,
resolved_quality: take.resolvedQuality ?? null,
resolved_outcome: take.resolvedQuality === 'correct' ? true : take.resolvedQuality === 'incorrect' ? false : null,
resolved_source: take.resolvedEvidence ?? null, resolved_value: take.resolvedValue ?? null, resolved_unit: take.resolvedUnit ?? null,
resolved_by: take.resolvedBy ?? null })));
- const resolveTakes = () => tx.executeRaw(`UPDATE takes k SET resolved_at=r.resolved_at::timestamptz,resolved_quality=r.resolved_quality,
+ const resolveTakes = () => fenceResolved.length ? tx.executeRaw(`UPDATE takes k SET resolved_at=r.resolved_at::timestamptz,resolved_quality=r.resolved_quality,
resolved_outcome=r.resolved_outcome,resolved_source=r.resolved_source,resolved_value=r.resolved_value,resolved_unit=r.resolved_unit,
resolved_by=r.resolved_by
FROM jsonb_to_recordset($2::text::jsonb) AS r(row_num integer,resolved_at text,resolved_quality text,resolved_outcome boolean,
resolved_source text,resolved_value real,resolved_unit text,resolved_by text)
- WHERE k.page_id=$1 AND k.row_num=r.row_num`, [id, resolutions]);
+ WHERE k.page_id=$1 AND k.row_num=r.row_num`, [id, resolutions]) : Promise.resolve([]);
// Event-page references have a different canonical origin and remain intact;
// new rows carry their Markdown detail on insert, pinned rows refresh only from their preimage.
const timelineRows = [
@@ -471,7 +478,7 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
() => pipelined(tx, [expireFacts, ...timelineRows])));
if (guard.rows.length) await step('facts', () => tx.insertFacts(guard.rows, { source_id: sourceId })); // gbrain-allow-direct-insert: canonical fence projection shares the journal publication transaction
const contested = await step('fact_trust', () => guard.finish(tx));
- await step('fact_fields', () => pipelined(tx, [factFields, checkTakes, dropTakes]));
+ await step('fact_fields', () => pipelined(tx, [factFields, checkTakes, dropTakes, clearChangedResolutions]));
if (takes.length) {
await step('takes', async () => {
await tx.addTakesBatch(takes.map(t => takesPreparation.toCanonicalBatchInput(id, t)));
diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.ts
index 5ba3f2a286..308bcc1e38 100644
--- a/src/core/persistence/page-purge.ts
+++ b/src/core/persistence/page-purge.ts
@@ -38,6 +38,7 @@ import { readRequestIndexStates, REQUEST_INDEXES_REPAIR_COMMAND, type RequestInd
import { faultPoint } from './fault-points.ts';
import { findRequestsForSlugs, recheckRequestsCarrying, redactRequestIntents, sweepRequestsCarrying, type JournalSweep } from './intent-redaction.ts';
import { dropPurgedFenceRows } from '../facts/purge-overlay.ts';
+import { derivedRowsFrom, hideDerivedRows } from '../facts/derivation-inputs.ts';
import { contentHash } from '../utils.ts';
export const PURGE_RESIDUALS = 'Removed from live stores: the page row with its chunks, versions, takes, timeline, links and raw data, the facts filed on it (tombstoned), '
@@ -141,6 +142,10 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
ON CONFLICT (source_id,content_hash) DO UPDATE SET slug=EXCLUDED.slug,request_id=EXCLUDED.request_id,purged_at=now()`, [sourceId, [...hashes], slug, row.id]);
const { factRows, takeRows, needles } = await readPurgeClaims(tx, sourceId, slug, page.id);
const factIds = factRows.map(f => Number(f.id)), takeIds = takeRows.map(t => Number(t.id));
+ const derivedFrom = await derivedRowsFrom(tx, [{ table: 'pages', id: page.id }, ...factIds.map(id => ({ table: 'facts', id })), ...takeIds.map(id => ({ table: 'takes', id }))]);
+ const purgedHere = new Set([...factIds.map(id => `facts:${id}`), ...takeIds.map(id => `takes:${id}`)]);
+ const derived = await hideDerivedRows(tx, derivedFrom.rows.filter(r => !purgedHere.has(`${r.table}:${r.id}`)),
+ { sourceId, requestId: row.id, reason: 'page purge' });
const count = async (sql: string, params: unknown[]) => (await tx.executeRaw(sql, params)).length;
const refs = factIds.map(String);
const removed: Record<string, number> = {
@@ -188,6 +193,7 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
while (purgeContext.size > PURGE_CONTEXT_LIMIT) purgeContext.delete(purgeContext.keys().next().value!);
return { status: 'purged', slug, source_id: sourceId, residuals: PURGE_RESIDUALS, journal_sweep: journalSweep,
purge: { content_hash8: storedHash?.slice(0, 8) ?? null, tombstoned: hashes.size > 0, content_hashes_tombstoned: hashes.size, removed,
+ derived: { ...derived, truncated: derivedFrom.truncated },
blobs: files.map(f => f.storage_path).filter(Boolean) } };
}
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index 33fb062140..2fa3885687 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -463,27 +463,11 @@ async function prepareFactFenceAdoption(unbounded: BrainEngine, row: WriteReques
if (adopted.length !== facts.length) throw opError('revision_conflict', 'A legacy fact was adopted by another run.',
`Another run adopted a legacy fact on ${row.slug} in ${row.source_id} while request ${row.request_id} was publishing, so its transaction rolled back. Read the receipt with gbrain write-request -- ${row.request_id} for the final state before planning any new adoption.`,
{ fix: receiptFix(row) });
- const outcome = await applyPreservingTakeResolutions(tx, row.page_id, prepared);
+ const outcome = await prepared.apply(tx);
return { ...outcome, facts_adopted: facts.length };
} };
}
-/**
- * Apply a page publication that republishes the page's takes fence unchanged.
- * Its projection would clear take resolutions recorded only in the database,
- * so they are restored afterwards in the same transaction.
- */
-export async function applyPreservingTakeResolutions(tx: BrainEngine, pageId: number | null, prepared: PreparedMutation): Promise<Record<string, unknown>> {
- const resolved = await tx.executeRaw<Record<string, unknown>>(`SELECT row_num,resolved_at,resolved_quality,resolved_outcome,
- resolved_source,resolved_value,resolved_unit,resolved_by FROM takes WHERE page_id=$1 AND resolved_at IS NOT NULL`, [pageId]);
- const outcome = await prepared.apply(tx);
- for (const take of resolved) await tx.executeRaw(`UPDATE takes SET resolved_at=$3,resolved_quality=$4,resolved_outcome=$5,
- resolved_source=$6,resolved_value=$7,resolved_unit=$8,resolved_by=$9 WHERE page_id=$1 AND row_num=$2 AND resolved_at IS NULL`,
- [pageId, take.row_num, take.resolved_at, take.resolved_quality, take.resolved_outcome, take.resolved_source,
- take.resolved_value, take.resolved_unit, take.resolved_by]);
- return outcome;
-}
-
/**
* #5575 I2: a maintenance intent that carries a derivation declaration
* publishes at the declared tier (never above agent_written), lowers its
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 453df02aff..c20b3941e0 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -136,6 +136,7 @@ test/persistence-writer-fences.test.ts
test/physical-root-birth-tolerance-6501.test.ts
test/purge-fact.test.ts
test/purge-global-marker.test.ts
+test/purge-read-surfaces.test.ts
test/recall-page-fill.test.ts
test/remediation-manual-only.test.ts
test/repair-apply-pending-6543.test.ts
@@ -178,6 +179,7 @@ test/sync-staged-catchup.test.ts
test/sync-status-failure-detail-6513.test.ts
test/sync-waiver-budget.test.ts
test/sync-waiver-run-imports.test.ts
+test/take-resolution-survives-publish.test.ts
test/takes-vector-lifecycle-5885.serial.test.ts
test/terminal-failures-6650.test.ts
test/trust-channel-writes.test.ts
diff --git a/test/purge-read-surfaces.test.ts b/test/purge-read-surfaces.test.ts
new file mode 100644
index 0000000000..25bbce3b60
--- /dev/null
+++ b/test/purge-read-surfaces.test.ts
@@ -0,0 +1,167 @@
+/**
+ * After a purge, no read operation returns the purged value: not from a
+ * retained page version, and not from a row derived from the purged one.
+ *
+ * Protects: get_versions (bodies, newest first) after `purge_fact` on a page
+ * with more retained versions than one redaction batch; the purge receipt's
+ * page_versions store naming every retained version whose prose, title or
+ * frontmatter still states the claim (text outside a fence is out of scope
+ * for redaction, so it must be reported); recall (with and
+ * without include_expired) after a page purge whose fact had a derived fact
+ * on another page; takes_list (active: false), recall (include_expired),
+ * get_page (include_deleted) and get_versions after `purge_fact` hides derived
+ * rows (needs_rederive read eligibility).
+ * Fails when: version redaction stops at a fixed row cap, a version carrying
+ * the claim only in its title or frontmatter goes unreported, page purge does not
+ * walk derivation_inputs, or a hidden derived row (a soft-deleted derived page
+ * included) stays readable.
+ * Seams: none; PGLite always, Postgres too when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+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 type { OperationContext } from '../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { operations } from '../src/core/operations.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { recordDerivationInputs } from '../src/core/facts/derivation-inputs.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const CLAIM = 'Vault combination is 8812';
+const home = mkdtempSync(join(tmpdir(), 'gbrain-purge-surfaces-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+const fence = `<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+| 1 | ${CLAIM} | fact | 1.0 | world | medium | 2026-01-01 | | chat | |
+| 2 | Likes green tea | preference | 1.0 | world | medium | 2026-01-01 | | chat | |
+<!--- gbrain:facts:end -->`;
+const pageBody = (title: string) => `---\ntitle: ${title}\ntype: person\n---\n# ${title}\n\nProse about ${title}.\n\n## Facts\n\n${fence}\n`;
+const ctx = (engine: BrainEngine): OperationContext => ({ engine, sourceId: 'default', remote: false, dryRun: false,
+ config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} } } as OperationContext);
+const op = (name: string) => operations.find(o => o.name === name)!;
+const call = (engine: BrainEngine, name: string, params: Record<string, unknown>) => op(name).handler(ctx(engine), params) as Promise<any>;
+const carries = (value: unknown) => JSON.stringify(value).toLowerCase().includes(CLAIM.toLowerCase());
+
+async function seedPage(engine: BrainEngine, slug: string): Promise<{ factId: number; pageId: number }> {
+ await importFromContent(engine, slug, pageBody(slug.split('/')[1]!), { noEmbed: true, sourceId: 'default' });
+ await runExtractFacts(engine, { slugs: [slug] });
+ const [row] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE fact=$1 AND entity_slug=$2', [CLAIM, slug]);
+ const [page] = await engine.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE source_id='default' AND slug=$1`, [slug]);
+ return { factId: Number(row.id), pageId: Number(page.id) };
+}
+
+async function purgeFact(engine: BrainEngine, id: number) {
+ const dry = await call(engine, 'purge_fact', { id, dry_run: true });
+ const done = await call(engine, 'purge_fact', { id, confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() });
+ expect(done.state).toBe('committed');
+ return done;
+}
+
+const coordinated = <T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>) =>
+ engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => fn(tx), TEST_WRITE_ATTRIBUTION));
+
+beforeAll(async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+ for (const engine of engines) await registerLocalWriter(engine, 'cli');
+}), 120_000);
+afterAll(async () => { await engines[0]?.disconnect(); await closePostgres?.(); rmSync(home, { recursive: true, force: true }); });
+
+describe('purged values on read surfaces', () => {
+ test('get_versions: no retained version past one redaction batch returns the purged fence row', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const seen: unknown[] = [];
+ for (const engine of engines) {
+ const slug = 'people/vault-versions-example';
+ const { factId, pageId } = await seedPage(engine, slug);
+ await engine.executeRaw(`INSERT INTO page_versions (page_id, compiled_truth, frontmatter, timeline)
+ SELECT p.id, p.compiled_truth, p.frontmatter, p.timeline FROM pages p, generate_series(1, 5010) WHERE p.id=$1`, [pageId]);
+ await purgeFact(engine, factId);
+ const newest = await call(engine, 'get_versions', { slug, include_body: true, limit: 20 });
+ const [left] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_versions WHERE page_id=$1 AND strpos(lower(compiled_truth), lower($2)) > 0`, [pageId, CLAIM]);
+ seen.push({ engine: engine.kind, returned: newest.length, get_versions: carries(newest), versions_carrying: left.n });
+ }
+ expect(seen).toEqual(engines.map(engine => ({ engine: engine.kind, returned: 20, get_versions: false, versions_carrying: 0 })));
+ }), 300_000);
+
+ test('purge_fact: retained versions stating the claim in prose, title or frontmatter are reported', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const seen: unknown[] = [];
+ for (const engine of engines) {
+ const slug = 'people/vault-metadata-example';
+ const { factId, pageId } = await seedPage(engine, slug);
+ const ids = (await engine.executeRaw<{ id: number }>(`INSERT INTO page_versions (page_id, compiled_truth, frontmatter, timeline, title)
+ VALUES ($1, $2, '{}'::jsonb, '', 'Plain'), ($1, 'Plain body.', '{}'::jsonb, '', $3), ($1, 'Plain body.', $4::jsonb, '', 'Plain') RETURNING id`,
+ [pageId, `Old prose: ${CLAIM}.`, `Title: ${CLAIM}`, JSON.stringify({ note: CLAIM })])).map(r => Number(r.id));
+ const done = await purgeFact(engine, factId);
+ const versions = done.stores.find((s: { store: string }) => s.store === 'page_versions');
+ const reported = new Set((versions?.items ?? []).map((i: { version_id: number }) => i.version_id));
+ seen.push({ engine: engine.kind, status: versions?.status, reason: versions?.reason,
+ prose: reported.has(ids[0]), title: reported.has(ids[1]), frontmatter: reported.has(ids[2]),
+ still_readable: carries(await call(engine, 'get_versions', { slug, limit: 20 })) });
+ }
+ expect(seen).toEqual(engines.map(engine => ({ engine: engine.kind, status: 'out_of_scope', reason: 'source_prose',
+ prose: true, title: true, frontmatter: true, still_readable: true })));
+ }), 300_000);
+
+ test('purge_fact: hidden derived take, fact and page stay unreadable', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const seen: unknown[] = [];
+ for (const engine of engines) {
+ const slug = 'people/vault-derived-example';
+ const { factId, pageId } = await seedPage(engine, slug);
+ const derivedSlug = 'notes/vault-synthesis-example';
+ for (const line of [`Synthesis: ${CLAIM}.`, `Synthesis, revised: ${CLAIM}.`])
+ await importFromContent(engine, derivedSlug, `---\ntitle: Vault synthesis\ntype: note\n---\n${line}\n`, { noEmbed: true, sourceId: 'default' });
+ const [derivedPage] = await engine.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE source_id='default' AND slug=$1`, [derivedSlug]);
+ expect(carries(await call(engine, 'get_versions', { slug: derivedSlug, include_body: true }))).toBe(true);
+ await coordinated(engine, async tx => {
+ const [take] = await tx.executeRaw<{ id: number }>(`INSERT INTO takes(page_id,row_num,claim,kind,holder) VALUES ($1,90,$2,'take','brain') RETURNING id`, [pageId, `Synthesized: ${CLAIM}`]);
+ const [fact] = await tx.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,fact,entity_slug,visibility,source) VALUES ('default',$1,$2,'world','consolidate') RETURNING id`, [`Derived: ${CLAIM}`, slug]);
+ for (const row of [{ table: 'takes', id: take.id }, { table: 'facts', id: fact.id }, { table: 'pages', id: derivedPage.id }])
+ await recordDerivationInputs(tx, { ...row, sourceId: 'default' }, [{ table: 'facts', id: factId }]);
+ });
+ await purgeFact(engine, factId);
+ const surfaces = {
+ engine: engine.kind,
+ takes_list: carries(await call(engine, 'takes_list', { page_slug: slug, active: false })),
+ recall: carries(await call(engine, 'recall', { entity: slug, include_expired: true })),
+ get_page: carries(await call(engine, 'get_page', { slug: derivedSlug, include_deleted: true }).catch(() => null)),
+ get_versions: carries(await call(engine, 'get_versions', { slug: derivedSlug, include_body: true })),
+ };
+ seen.push(surfaces);
+ }
+ expect(seen).toEqual(engines.map(engine => ({ engine: engine.kind, takes_list: false, recall: false, get_page: false, get_versions: false })));
+ }), 300_000);
+
+ test('page purge: a fact derived from the purged page on another page leaves no purged text', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const seen: unknown[] = [];
+ for (const engine of engines) {
+ const slug = 'people/vault-page-purge-example';
+ const { factId } = await seedPage(engine, slug);
+ const other = 'people/vault-other-example';
+ await importFromContent(engine, other, `---\ntitle: Other\ntype: person\n---\nOther page.\n`, { noEmbed: true, sourceId: 'default' });
+ await coordinated(engine, async tx => {
+ const [fact] = await tx.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,fact,entity_slug,visibility,source) VALUES ('default',$1,$2,'world','consolidate') RETURNING id`, [`Derived: ${CLAIM}`, other]);
+ await recordDerivationInputs(tx, { table: 'facts', id: fact.id, sourceId: 'default' }, [{ table: 'facts', id: factId }]);
+ });
+ const [page] = await engine.executeRaw<{ revision: string }>(`SELECT knowledge_revision::text AS revision FROM pages WHERE source_id='default' AND slug=$1`, [slug]);
+ const done = await call(engine, 'delete_page', { slug, purge: true, expected_revision: page.revision, request_id: randomUUID() });
+ expect(done.state).toBe('committed');
+ seen.push({ engine: engine.kind, recall: carries(await call(engine, 'recall', { entity: other })),
+ recall_expired: carries(await call(engine, 'recall', { entity: other, include_expired: true })) });
+ }
+ expect(seen).toEqual(engines.map(engine => ({ engine: engine.kind, recall: false, recall_expired: false })));
+ }), 300_000);
+});
diff --git a/test/take-resolution-survives-publish.test.ts b/test/take-resolution-survives-publish.test.ts
new file mode 100644
index 0000000000..4febb03a37
--- /dev/null
+++ b/test/take-resolution-survives-publish.test.ts
@@ -0,0 +1,115 @@
+/**
+ * A take resolution recorded only in the database (unmanaged `grade_takes`
+ * auto-resolve, `cycle/grade-takes.ts`) survives the page's next publication.
+ *
+ * Protects: an ordinary put_page, and a revert to a version from before the
+ * grade, whose takes fence carries no resolution cells keep the stored
+ * resolution of a take whose claim is unchanged; a claim edited in place at
+ * the same row number drops the old claim's resolution; a fence that carries
+ * resolution cells still writes them.
+ * Fails when: the canonical projection writes every resolution column from
+ * the fence unconditionally (it nulled database-only grades on every publish).
+ * Seams: none; PGLite always, Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { maintenanceTransaction } from '../src/core/persistence/attribution.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const SLUG = 'concepts/graded-take';
+const takesFence = (first: string, resolution?: string) => [
+ '## Takes', '', '<!--- gbrain:takes:begin -->',
+ resolution
+ ? '| # | claim | kind | who | weight | since | source | resolved | quality | evidence | value | unit | by |'
+ : '| # | claim | kind | who | weight | since | source |',
+ resolution ? '|---|-------|------|-----|--------|-------|--------|----------|---------|----------|-------|------|----|' : '|---|-------|------|-----|--------|-------|--------|',
+ resolution ? `| 1 | ${first} | bet | brain | 0.6 | | manual | ${resolution} |` : `| 1 | ${first} | bet | brain | 0.6 | | manual |`,
+ resolution ? '| 2 | a second open take | bet | brain | 0.4 | | manual | | | | | | |' : '| 2 | a second open take | bet | brain | 0.4 | | manual |',
+ '<!--- gbrain:takes:end -->',
+].join('\n');
+const page = (prose: string, fence: string) => `---\ntype: concept\ntitle: Graded take\n---\n${prose}\n\n${fence}\n`;
+
+for (const backend of testBackends()) {
+ describe(`${backend}: take resolutions recorded only in the database`, () => {
+ let engine: BrainEngine;
+ let ctx: OperationContext;
+ const sourceId = `take-resolution-${randomUUID().slice(0, 8)}`;
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-take-resolution-'));
+ const root = join(dir, 'brain');
+ const home = { GBRAIN_HOME: join(dir, 'home') };
+ const submit = async (operation: string, params: Record<string, unknown>) => {
+ const result = await withEnv(home, () => submitPageMutation(ctx, { operation, params: { request_id: randomUUID(), force: true, ...params } }));
+ expect(result.state).toBe('committed');
+ return result;
+ };
+ const resolutions = () => engine.executeRaw<{ row_num: number; claim: string; resolved_quality: string | null; resolved_source: string | null; resolved_by: string | null }>(
+ `SELECT t.row_num, t.claim, t.resolved_quality, t.resolved_source, t.resolved_by FROM takes t JOIN pages p ON p.id = t.page_id
+ WHERE p.source_id = $1 AND p.slug = $2 ORDER BY t.row_num`, [sourceId, SLUG]);
+ const gradeInDatabase = async () => {
+ const [{ id }] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id = $1 AND slug = $2', [sourceId, SLUG]);
+ await maintenanceTransaction(engine, tx => tx.resolveTake(id, 1, { quality: 'correct', source: 'grader note', resolvedBy: 'system' }));
+ };
+
+ beforeAll(async () => {
+ if (backend === 'postgres') {
+ const pg = new PostgresEngine();
+ await pg.connect({ database_url: requirePostgresTestDatabase() });
+ engine = pg;
+ } else {
+ const lite = new PGLiteEngine();
+ await lite.connect({});
+ engine = lite;
+ }
+ await engine.initSchema();
+ ctx = { engine, config: { engine: backend }, sourceId, remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } } as OperationContext;
+ mkdirSync(root);
+ await engine.executeRaw('INSERT INTO sources (id, name, local_path) VALUES ($1, $1, $2)', [sourceId, root]);
+ await withEnv(home, () => claimWorktree(engine, sourceId, root));
+ await submit('put_page', { slug: SLUG, content: page('First prose.', takesFence('an earlier graded take')) });
+ await gradeInDatabase();
+ }, 180_000);
+
+ afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('DELETE FROM sources WHERE id = $1', [sourceId]);
+ await engine.disconnect();
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ test('a prose edit keeps the grade and leaves the open take open', async () => {
+ await submit('put_page', { slug: SLUG, content: page('Edited prose.', takesFence('an earlier graded take')) });
+ expect(await resolutions()).toEqual([
+ { row_num: 1, claim: 'an earlier graded take', resolved_quality: 'correct', resolved_source: 'grader note', resolved_by: 'system' },
+ { row_num: 2, claim: 'a second open take', resolved_quality: null, resolved_source: null, resolved_by: null },
+ ]);
+ }, 60_000);
+
+ test('a revert to a version from before the grade keeps the grade', async () => {
+ const [version] = await engine.executeRaw<{ id: number }>(`SELECT v.id FROM page_versions v JOIN pages p ON p.id = v.page_id
+ WHERE p.source_id = $1 AND p.slug = $2 AND v.compiled_truth LIKE '%First prose.%' ORDER BY v.id LIMIT 1`, [sourceId, SLUG]);
+ await submit('revert_version', { slug: SLUG, version_id: Number(version.id) });
+ expect((await resolutions())[0]).toMatchObject({ claim: 'an earlier graded take', resolved_quality: 'correct', resolved_source: 'grader note' });
+ }, 60_000);
+
+ test('a fence that carries resolution cells writes them', async () => {
+ await submit('put_page', { slug: SLUG, content: page('Fence-carried grade.', takesFence('an earlier graded take', '2026-10-01 | incorrect | fence note | | | owner')) });
+ expect((await resolutions())[0]).toMatchObject({ resolved_quality: 'incorrect', resolved_source: 'fence note', resolved_by: 'owner' });
+ }, 60_000);
+
+ test('a claim edited in place drops the old claim\'s grade', async () => {
+ await submit('put_page', { slug: SLUG, content: page('Claim rewritten.', takesFence('a different claim at the same row')) });
+ expect((await resolutions())[0]).toEqual({ row_num: 1, claim: 'a different claim at the same row', resolved_quality: null, resolved_source: null, resolved_by: null });
+ }, 60_000);
+ });
+}