Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

belief ledger lane A: purge epoch, ledger redaction, purge mirror, restore replay (wip)

garrytan6ac512a74485
diff --git a/src/core/backup/snapshot.ts b/src/core/backup/snapshot.ts
index 8e246a8c49..d9671ebbcb 100644
--- a/src/core/backup/snapshot.ts
+++ b/src/core/backup/snapshot.ts
@@ -15,6 +15,7 @@ import { quarantineRestoredExecution, rebaseRestorePath, relativeBackupPath, typ
import { quarantineSharedSkillRestore, validateSharedSkillRestoreMode, type SharedSkillRestore, type SharedSkillRestoreOptions } from '../shared-skills/restore.ts';
import { isPhysicalRootMetadata } from '../persistence/physical-root-record.ts';
import { protectNewBackupPath } from './private-path.ts';
+import { PURGE_MIRROR_FILE, readPurgeMirror, replayPurgesInRestore, type PurgeReplayState, type ReplayRecord } from '../belief/purge-mirror.ts';
interface SourceInventory { id: string; local_path: string | null; managed_relative_path: string | null }
interface BackupMetadata {
@@ -222,7 +223,12 @@ function metadataOf(manifest: ArchiveManifest): BackupMetadata {
return value;
}
-export async function restorePgliteBackup(options: { archive: string; into: string } & SharedSkillRestoreOptions): Promise<{ root: string; quarantined_jobs: number; reconnect_required: string[]; shared_skills: SharedSkillRestore | null }> {
+/**
+ * `purgeMirror` names a copy of the original brain's purge mirror when its root is gone (default:
+ * `<original_root>/.gbrain/purge-events.jsonl`); the restore replays the purges recorded there after the archive.
+ */
+export async function restorePgliteBackup(options: { archive: string; into: string; purgeMirror?: string } & SharedSkillRestoreOptions): Promise<{ root: string; quarantined_jobs: number;
+ reconnect_required: string[]; shared_skills: SharedSkillRestore | null; purge_replay: { state: PurgeReplayState; replays: ReplayRecord[] } }> {
const mode = validateSharedSkillRestoreMode(options);
const root = checkedRoot(options.into);
if (!existsSync(dirname(root))) throw new AgentInstallError('parent_missing', 'Restore parent directory must already exist.');
@@ -266,12 +272,16 @@ export async function restorePgliteBackup(options: { archive: string; into: stri
let quarantined = 0;
let execution: RestoreQuarantine;
let sharedSkills: SharedSkillRestore | null = null;
+ let purgeReplay: { state: PurgeReplayState; replays: ReplayRecord[] } = { state: 'none', replays: [] };
await engine.transaction(async tx => {
sharedSkills = await quarantineSharedSkillRestore(tx, restoreId, options);
await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");
execution = await quarantineRestoredExecution(tx, { sources: metadata.sources, originalRoot: metadata.original_root, root, managedPaths: metadata.managed_paths, restoreId });
const jobs = await tx.executeRaw<{ id: number }>(`UPDATE minion_jobs SET status = 'cancelled', lock_token = NULL, lock_until = NULL, finished_at = NOW(), updated_at = NOW(), error_text = 'quarantined by backup restore; inspect and explicitly resubmit', data = data || jsonb_build_object('__restore_previous_status', status, '__restore_id', $1::text) WHERE status NOT IN ('completed', 'failed', 'dead', 'cancelled') RETURNING id`, [restoreId]);
quarantined = jobs.length;
+ // W1 (BELIEF_LEDGER.md 8): purges made after the archive are replayed before the root is published; coverage.restored names the archive time.
+ purgeReplay = await replayPurgesInRestore(tx, { lines: readPurgeMirror(options.purgeMirror ?? join(metadata.original_root, '.gbrain', PURGE_MIRROR_FILE)),
+ archivedAt: metadata.created_at, restoreId });
});
// #6696 (A1): the restore failed every pending effect; their requests give back their unused reservations.
await trueUpRequests(engine, (await engine.executeRaw<{ request_id: string }>(
@@ -325,11 +335,14 @@ export async function restorePgliteBackup(options: { archive: string; into: stri
if (existsSync(join(root, name))) throw new AgentInstallError('restore_collision', 'New content appeared in the reserved restore root.');
renameSync(join(restored, name), join(root, name));
}
- const reconnect = [...new Set([...metadata.credential_references.map(key => `Configure credential: ${key}`), ...metadata.omitted, ...detachedConfig, ...execution!.reconnect, 'Autopilot is paused; review .gbrain/restore-detached.json before explicitly resuming automation.'])];
- privateWrite(receiptPath, JSON.stringify({ format_version: 1, restore_id: restoreId, state: 'ready', original_root: metadata.original_root, shared_skills: sharedSkills, quarantined_jobs: quarantined, reconnect_required: reconnect, launcher_ready: false, setup_required: true, native_automation_started: false }, null, 2) + '\n');
+ const replayWarning = purgeReplay.state === 'none' || purgeReplay.state === 'complete' ? [] : [purgeReplay.state === 'unavailable'
+ ? `Purges made after the archive (${metadata.created_at}) were not replayed: no purge mirror could be read under ${metadata.original_root}. Restore again with the original brain's .gbrain/${PURGE_MIRROR_FILE} available (purgeMirror), or purge the content again.`
+ : `Purge replay is ${purgeReplay.state} for request(s) ${purgeReplay.replays.filter(r => r.outcome !== 'complete').map(r => `${r.request_id} (${r.outcome})`).join(', ')}: review them and run those purges again if the content is still present.`];
+ const reconnect = [...new Set([...metadata.credential_references.map(key => `Configure credential: ${key}`), ...metadata.omitted, ...detachedConfig, ...execution!.reconnect, ...replayWarning, 'Autopilot is paused; review .gbrain/restore-detached.json before explicitly resuming automation.'])];
+ privateWrite(receiptPath, JSON.stringify({ format_version: 1, restore_id: restoreId, state: 'ready', original_root: metadata.original_root, shared_skills: sharedSkills, quarantined_jobs: quarantined, reconnect_required: reconnect, purge_replay: purgeReplay, launcher_ready: false, setup_required: true, native_automation_started: false }, null, 2) + '\n');
syncDirectory(root);
published = true;
- return { root, quarantined_jobs: quarantined, reconnect_required: reconnect, shared_skills: sharedSkills };
+ return { root, quarantined_jobs: quarantined, reconnect_required: reconnect, shared_skills: sharedSkills, purge_replay: purgeReplay };
} catch (error) {
privateWrite(receiptPath, JSON.stringify({ format_version: 1, restore_id: restoreId, state: 'failed', mode, reason: error instanceof AgentInstallError ? error.code : 'restore_failed', original_preserved: true }) + '\n');
throw error;
diff --git a/src/core/belief/append.ts b/src/core/belief/append.ts
index ff0076c948..a88472e3b9 100644
--- a/src/core/belief/append.ts
+++ b/src/core/belief/append.ts
@@ -29,6 +29,11 @@ export interface AppendContext {
writerTier?: string | null; remote?: boolean;
/** Skip the tombstone and register reads when the source never had a purge (begin's probe). */
purgesPossible?: boolean;
+ /**
+ * The source's purge_epoch when a payload prepared outside this transaction (backfill, a refresh proposal) was
+ * built; the append refuses with `belief_stale_preparation` when a purge committed since (section 6.5).
+ */
+ preparedEpoch?: number;
}
const KIND_RANK: Record<string, number> = { coverage: 0, page: 1, fact: 2, take: 3, link: 4, link_transition: 5 };
@@ -114,6 +119,13 @@ export async function appendBeliefEvents(tx: BrainEngine, input: BeliefEventDraf
if (!drafts.length) return 0;
const ordered = orderDrafts(drafts);
const sourceId = ordered[0]!.sourceId;
+ if (ctx.preparedEpoch !== undefined) {
+ const [source] = await tx.executeRaw<{ purge_epoch: string | number }>('SELECT purge_epoch FROM sources WHERE id = $1', [sourceId]);
+ if (Number(source?.purge_epoch ?? 0) !== ctx.preparedEpoch) {
+ throw Object.assign(new Error(`belief_stale_preparation: a purge committed in source ${sourceId} since this payload was prepared (epoch ${ctx.preparedEpoch}, now ${source?.purge_epoch}); prepare it again from current state`),
+ { code: 'belief_stale_preparation' });
+ }
+ }
const purgedFps = ctx.purgesPossible === false ? new Set<string>() : await tombstoned(tx, sourceId, ordered);
const redactions = ctx.purgesPossible === false ? new Map<BeliefEventDraft, string[]>() : await applyRedactions(tx, sourceId, ordered, ctx);
const rows = ordered.map((d, ord) => {
diff --git a/src/core/belief/history.ts b/src/core/belief/history.ts
index 4f6d2a4adf..098dd763d7 100644
--- a/src/core/belief/history.ts
+++ b/src/core/belief/history.ts
@@ -7,6 +7,9 @@
* - the stream page's current lifetime is visible now (a page made private
* later hides its earlier events; an ended lifetime hides them too);
* - for links, every page-backed endpoint and the origin are visible now.
+ * For every caller, a key with a `derived.hidden` (a purge hid the row it
+ * describes, section 6.5) hides its events below that marker and its backfill
+ * events at any id; the marker itself stays visible as the disclosure.
*/
import type { BrainEngine } from '../engine.ts';
import { privatePagesFilterFragment } from '../search/private-visibility.ts';
@@ -36,6 +39,8 @@ export async function readBeliefHistory(engine: BrainEngine, q: BeliefHistoryQue
WHERE l.page_lifetime = e.page_lifetime AND l.ended_at IS NULL) AS stream_visible
FROM belief_events e
WHERE e.source_id = $1 AND ($2::text IS NULL OR e.slug = $2) AND ($3::text IS NULL OR e.subject_key = $3) AND e.id > $4
+ AND NOT EXISTS (SELECT 1 FROM belief_events h WHERE h.source_id = e.source_id AND h.subject_kind = e.subject_kind AND h.subject_key = e.subject_key
+ AND h.event_type = 'derived.hidden' AND h.id <> e.id AND (h.id > e.id OR e.origin = 'backfill'))
ORDER BY e.id LIMIT $5`, [q.sourceId, q.slug ?? null, q.subjectKey ?? null, q.afterId ?? 0, Math.min(Math.max(q.limit ?? 1000, 1), 10_000)]);
const json = (v: unknown) => typeof v === 'string' ? JSON.parse(v) : v;
const out = rows.map(r => ({ ...r, id: Number(r.id), value: json(r.value) as BeliefHistoryRow['value'], cause: json(r.cause) as BeliefHistoryRow['cause'] }));
diff --git a/src/core/belief/ledger.ts b/src/core/belief/ledger.ts
index c68a131c8b..18dd9cde21 100644
--- a/src/core/belief/ledger.ts
+++ b/src/core/belief/ledger.ts
@@ -26,7 +26,7 @@ export type BeliefNote =
| { kind: 'held'; holdKind: string; fingerprint: string; holdId: number; slug: string; tier: string; valueHash: string }
| { kind: 'withdrawn'; factIds: number[] }
| { kind: 'superseded'; oldId: number; newId: number | null }
- | { kind: 'purged'; table: 'facts' | 'takes'; ids: number[]; request: string }
+ | { kind: 'purged'; table: 'facts' | 'takes' | 'pages'; ids: number[]; request: string; derivedWalk?: 'truncated' }
| { kind: 'transferred'; fromLifetime: string; table: 'facts' | 'takes'; ids: number[] };
export interface BeliefBatchOptions {
@@ -245,7 +245,10 @@ function pageDrafts(d: DiffContext, stream: Stream, lifetime: string, after: Sub
subjectKey: pageKey(lifetime), writerTier: d.writerTier, visibility: page.visible ? 'world' : 'private', stateHash: d.streamHash(page.slug), cause: d.cause() };
const emit = (eventType: string, value: Record<string, unknown>, tier: string) => push({ ...base, eventType, trustTier: tier, value });
if (p0 && !p1) {
- emit(d.opts.hardDeleteEvent ?? 'page.deleted', { revision_before: p0.revision, hard: true }, p0.tier);
+ const purge = d.batch.notes.find(n => n.kind === 'purged' && n.table === 'pages' && n.ids.includes(p0.id));
+ const type = purge ? 'page.purged' : d.opts.hardDeleteEvent ?? 'page.deleted';
+ push({ ...base, eventType: type, trustTier: p0.tier, value: type === 'page.purged' ? null : { revision_before: p0.revision, hard: true },
+ purged: type === 'page.purged', cause: purge?.kind === 'purged' ? d.cause({ purge_request: purge.request, ...(purge.derivedWalk ? { derived_walk: purge.derivedWalk } : {}) }) : base.cause });
return true;
}
if (!p0 && p1) {
@@ -353,9 +356,10 @@ export async function currentStateHash(tx: BrainEngine, sourceId: string, incarn
export { stateHashOf };
/** The batch options of one journaled page publication (single or group member). */
-export function publicationBeliefOptions(row: { id: string; source_id: string; slug: string; operation: string; authority: { remote?: boolean } },
+export function publicationBeliefOptions(row: { id: string; source_id: string; slug: string; operation: string; authority: { remote?: boolean }; intent?: Record<string, unknown> | null },
additionalKeys: readonly { sourceId: string; slug: string }[] = [], report?: { appended: number }): BeliefBatchOptions {
return { sourceId: row.source_id, slugs: [...new Set([row.slug, ...additionalKeys.filter(k => k.sourceId === row.source_id).map(k => k.slug)])],
publicationId: row.id, op: row.operation, remote: row.authority.remote !== false,
- ...(row.operation === 'revert_version' ? { pageEventType: 'page.reverted' as const } : {}), ...(report ? { report } : {}) };
+ ...(row.operation === 'revert_version' ? { pageEventType: 'page.reverted' as const } : {}),
+ ...(row.operation === 'delete_page' && row.intent?.retention === true ? { hardDeleteEvent: 'page.expired' as const } : {}), ...(report ? { report } : {}) };
}
diff --git a/src/core/belief/purge-mirror.ts b/src/core/belief/purge-mirror.ts
new file mode 100644
index 0000000000..2db81b4051
--- /dev/null
+++ b/src/core/belief/purge-mirror.ts
@@ -0,0 +1,232 @@
+/**
+ * The text-free purge mirror and restore-time purge replay
+ * (docs/designs/BELIEF_LEDGER.md section 8).
+ *
+ * Every owner-requested purge appends an `intent` line to
+ * `<brain home>/purge-events.jsonl` (0600) and fsyncs it before its
+ * transaction commits, and a `committed` line after. A line names the request,
+ * the source and its incarnation, the scope, the fingerprints and content
+ * hashes, the page lifetimes and the purge_epoch it commits; never claim text.
+ * The mirror is a superset of committed purges: a purge that rolled back may
+ * leave an intent line with no committed line.
+ *
+ * A restore (PGLite: `restorePgliteBackup`; Postgres: `replayPurgesFromDatabase`,
+ * the `gbrain beliefs replay-purges` step) replays every committed purge newer
+ * than the archive for a matching source incarnation: tombstones, the restored
+ * rows' removal, the standard ledger redaction, and one `fact.purged` or
+ * `page.purged` with cause `restore_replay` naming the original request. Each
+ * replay records `complete` (a restored row held the text and the carrying-field
+ * pass ran), `partial` (no restored row matched: tombstones and key-level
+ * redaction only) or `unverified` (an intent line with no committed line, not
+ * replayed). `coverage.restored` carries the outcome, or `purge_replay:
+ * 'unavailable'` when no mirror could be read.
+ */
+import { randomUUID } from 'node:crypto';
+import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, writeSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import { configDir } from '../config.ts';
+import { COVERAGE_KEY, factKey, pageKey, slugRef } from './keys.ts';
+import { appendBeliefEvents, type BeliefEventDraft } from './append.ts';
+import { bumpPurgeEpoch, pagePurgeClaims, redactCarryingFields, redactPurgedKeys, registerLiveCarriers } from './purge.ts';
+
+export const PURGE_MIRROR_FILE = 'purge-events.jsonl';
+
+export interface PurgeMirrorFact { fact_hash: string; visibility: string; subject: string }
+export interface PurgeMirrorIntent {
+ kind: 'intent'; request: string; request_id: string; source_id: string; source_incarnation: string; scope: 'fact' | 'page';
+ recorded_at: string; purge_epoch: number; slug?: string; content_hashes?: string[]; facts: PurgeMirrorFact[]; takes: string[]; lifetimes: string[];
+}
+export type PurgeMirrorLine = PurgeMirrorIntent | { kind: 'committed'; request: string; recorded_at: string };
+
+export const purgeMirrorPath = (home = configDir()) => join(home, PURGE_MIRROR_FILE);
+
+/** Appends one line and fsyncs it (file 0600). Called before the purge commits (intent) and after (committed). */
+export function appendPurgeMirror(line: Omit<PurgeMirrorIntent, 'recorded_at'> | { kind: 'committed'; request: string }, home = configDir()): void {
+ const path = purgeMirrorPath(home);
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
+ const fd = openSync(path, 'a', 0o600);
+ try {
+ writeSync(fd, `${JSON.stringify({ ...line, recorded_at: new Date().toISOString() })}\n`);
+ fsyncSync(fd);
+ } finally { closeSync(fd); }
+ chmodSync(path, 0o600);
+}
+
+/**
+ * Reads a mirror. Null when it cannot be read: the file is unreadable or
+ * corrupt, or neither it nor the brain home it lives in exists. A brain home
+ * without the file never purged, so it reads as empty.
+ */
+export function readPurgeMirror(path: string): PurgeMirrorLine[] | null {
+ if (!existsSync(path)) return existsSync(join(dirname(path), 'config.json')) ? [] : null;
+ try {
+ return readFileSync(path, 'utf8').split('\n').filter(l => l.trim()).map(l => JSON.parse(l) as PurgeMirrorLine);
+ } catch { return null; }
+}
+
+export type ReplayOutcome = 'complete' | 'partial' | 'unverified';
+export interface ReplayRecord { request: string; request_id: string; scope: string; outcome: ReplayOutcome }
+export type PurgeReplayState = 'none' | 'complete' | 'partial' | 'unverified' | 'unavailable';
+
+const RANK: Record<PurgeReplayState, number> = { none: 0, complete: 1, partial: 2, unverified: 3, unavailable: 4 };
+export const replayState = (records: readonly ReplayRecord[]): PurgeReplayState =>
+ records.reduce<PurgeReplayState>((worst, r) => RANK[r.outcome] > RANK[worst] ? r.outcome : worst, 'none');
+
+/** One replayed purge inside the restore transaction. No other process can reach the restored database, so it takes no page keys. */
+async function replayOne(tx: BrainEngine, intent: PurgeMirrorIntent): Promise<ReplayOutcome> {
+ const src = intent.source_id, actor = 'restore_replay';
+ await tx.executeRaw("SELECT set_config('gbrain.write_sources', $1, true)", [JSON.stringify([src])]);
+ await bumpPurgeEpoch(tx, src);
+ for (const f of intent.facts) {
+ await tx.executeRaw(`INSERT INTO fact_purges(source_id,visibility,subject,fact_hash,request_id,actor,reason) VALUES ($1,$2,$3,$4,$5::uuid,$6,'restore replay')
+ ON CONFLICT DO NOTHING`, [src, f.visibility, f.subject, f.fact_hash, intent.request, actor]);
+ }
+ const takeHashes = [...new Set([...intent.takes, ...(intent.scope === 'fact' ? intent.facts.map(f => f.fact_hash) : [])])];
+ for (const hash of takeHashes) {
+ await tx.executeRaw('INSERT INTO take_purges(source_id,subject,claim_hash,request_id) VALUES ($1,$2,$3,$4::uuid) ON CONFLICT DO NOTHING',
+ [src, intent.scope === 'page' ? intent.slug : intent.facts[0]?.subject ?? '*', hash, intent.request]);
+ }
+ if (intent.content_hashes?.length) {
+ await tx.executeRaw(`INSERT INTO page_purges(source_id,content_hash,slug,request_id) SELECT $1,h,$3,$4::uuid FROM unnest($2::text[]) AS h
+ ON CONFLICT (source_id,content_hash) DO UPDATE SET slug=EXCLUDED.slug,request_id=EXCLUDED.request_id`, [src, intent.content_hashes, intent.slug, intent.request]);
+ }
+ const fps = [...new Set([...intent.facts.map(f => f.fact_hash), ...intent.takes])];
+ let claims: string[] = [];
+ let lifetimes = intent.lifetimes;
+ let restoredPage: { id: number; slug: string } | null = null;
+ if (intent.scope === 'page' && intent.slug) {
+ const [page] = await tx.executeRaw<{ id: number; slug: string }>(`SELECT p.id, p.slug FROM pages p WHERE p.source_id = $1
+ AND (p.slug = $2 OR p.content_hash = ANY($3::text[])) ORDER BY (p.slug = $2) DESC LIMIT 1`, [src, intent.slug, intent.content_hashes ?? []]);
+ if (page) {
+ restoredPage = { id: Number(page.id), slug: page.slug };
+ const own = await tx.executeRaw<{ page_lifetime: string }>(`SELECT page_lifetime::text AS page_lifetime FROM belief_page_lifetimes WHERE source_id = $1
+ AND (page_id = $2 OR (slug = $3 AND ended_at IS NULL))`, [src, restoredPage.id, restoredPage.slug]);
+ lifetimes = [...new Set([...lifetimes, ...own.map(r => r.page_lifetime)])];
+ claims = (await pagePurgeClaims(tx, { sourceId: src, slug: restoredPage.slug, pageId: restoredPage.id, lifetimes })).claims;
+ await tx.executeRaw('DELETE FROM facts WHERE source_id = $1 AND source_markdown_slug = $2', [src, restoredPage.slug]);
+ await tx.deletePage(restoredPage.slug, { sourceId: src });
+ }
+ } else {
+ const scope = intent.facts[0] ?? { fact_hash: '', visibility: 'world', subject: '*' };
+ const rows = await tx.executeRaw<{ id: number; fact: string; slug: string | null }>(`SELECT id, fact, source_markdown_slug AS slug FROM facts WHERE source_id = $1
+ AND gbrain_fact_fingerprint(fact) = $2 AND visibility = $3 AND ($4 = '*' OR entity_slug = $4)`, [src, scope.fact_hash, scope.visibility, scope.subject]);
+ const takes = await tx.executeRaw<{ id: number; claim: string; page_id: number }>(`SELECT k.id, k.claim, k.page_id 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, scope.fact_hash, scope.subject]);
+ claims = [...new Set([...rows.map(r => r.fact), ...takes.map(t => t.claim)])];
+ if (claims.length) {
+ const { rewritePageBodies, redactPageVersions } = await import('../facts/purge.ts');
+ const pages = await tx.executeRaw<{ slug: string; page_id: number; revision: string }>(`SELECT slug, id AS page_id, knowledge_revision::text AS revision FROM pages
+ WHERE source_id = $1 AND (slug = ANY($2::text[]) OR id = ANY($3::int[]))`, [src, rows.map(r => r.slug).filter(Boolean), takes.map(t => Number(t.page_id))]);
+ await tx.executeRaw('DELETE FROM takes WHERE id = ANY($1::bigint[])', [takes.map(t => Number(t.id))]);
+ await tx.executeRaw('DELETE FROM facts WHERE id = ANY($1::bigint[])', [rows.map(r => Number(r.id))]);
+ await rewritePageBodies(tx, src, pages.map(p => ({ ...p, page_id: Number(p.page_id) })));
+ for (const claim of claims) await redactPageVersions(tx, src, claim, pages.map(p => Number(p.page_id)));
+ }
+ }
+ await redactPurgedKeys(tx, { sourceId: src, claimFps: fps, lifetimes });
+ if (claims.length) {
+ await redactCarryingFields(tx, { sourceId: src, request: intent.request, claims });
+ await registerLiveCarriers(tx, { sourceId: src, request: intent.request, claims });
+ }
+ const outcome: ReplayOutcome = claims.length ? 'complete' : 'partial';
+ await appendBeliefEvents(tx, [await replayDraft(tx, intent, lifetimes, outcome)], { publicationId: randomUUID(), origin: 'live', purgesPossible: true });
+ return outcome;
+}
+
+async function replayDraft(tx: BrainEngine, intent: PurgeMirrorIntent, lifetimes: readonly string[], outcome: ReplayOutcome): Promise<BeliefEventDraft> {
+ const cause = { op: 'restore_replay', cause: 'restore_replay', purge_request: intent.request, request_id: intent.request_id, outcome };
+ const base = { sourceId: intent.source_id, incarnation: intent.source_incarnation, value: null, purged: true, trustTier: 'unknown', tierBasis: 'unknown' as const,
+ visibility: 'world', stateHash: '', cause };
+ if (intent.scope === 'page') {
+ const lifetime = lifetimes[0] ?? null;
+ return { ...base, lifetime, slug: intent.slug ?? '', subjectKind: 'page', subjectKey: lifetime ? pageKey(lifetime) : JSON.stringify(['p', slugRef(intent.source_incarnation, intent.slug ?? '')]),
+ eventType: 'page.purged' };
+ }
+ const f = intent.facts[0]!;
+ const [known] = await tx.executeRaw<{ subject_key: string; slug: string; page_lifetime: string | null }>(`SELECT subject_key, slug, page_lifetime::text AS page_lifetime
+ FROM belief_events WHERE source_id = $1 AND subject_kind = 'fact' AND claim_fp = $2 ORDER BY id DESC LIMIT 1`, [intent.source_id, f.fact_hash]);
+ return { ...base, lifetime: known?.page_lifetime ?? null, slug: known?.slug ?? f.subject, subjectKind: 'fact', claimFp: f.fact_hash, eventType: 'fact.purged',
+ subjectKey: known?.subject_key ?? factKey(slugRef(intent.source_incarnation, f.subject), f.fact_hash, f.visibility) };
+}
+
+/**
+ * Replays the purges newer than `archivedAt` for the restored database's sources (matching incarnation), in
+ * recorded order, then appends `coverage.restored` naming the archive time and the outcome on every source with
+ * coverage. `lines` null means no mirror could be read: `purge_replay: 'unavailable'`.
+ */
+export async function replayPurgesInRestore(tx: BrainEngine, input: { lines: PurgeMirrorLine[] | null; archivedAt: string; restoreId: string }):
+ Promise<{ state: PurgeReplayState; replays: ReplayRecord[] }> {
+ const sources = await tx.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources ORDER BY id');
+ const replays: ReplayRecord[] = [];
+ if (input.lines) {
+ const committed = new Set(input.lines.filter(l => l.kind === 'committed').map(l => l.request));
+ const seen = new Set<string>();
+ const newer = input.lines.filter((l): l is PurgeMirrorIntent => l.kind === 'intent' && l.recorded_at > input.archivedAt
+ && sources.some(s => s.id === l.source_id && s.incarnation === l.source_incarnation));
+ for (const intent of newer) {
+ if (seen.has(intent.request)) continue;
+ seen.add(intent.request);
+ const outcome = committed.has(intent.request) ? await replayOne(tx, intent) : 'unverified';
+ replays.push({ request: intent.request, request_id: intent.request_id, scope: intent.scope, outcome });
+ }
+ }
+ const state: PurgeReplayState = input.lines ? replayState(replays) : 'unavailable';
+ for (const source of sources) {
+ const [covered] = await tx.executeRaw<{ id: number }>(`SELECT id FROM belief_events WHERE source_id = $1 AND source_incarnation = $2::uuid AND subject_kind = 'coverage'
+ LIMIT 1`, [source.id, source.incarnation]);
+ if (!covered) continue;
+ await appendBeliefEvents(tx, [{ sourceId: source.id, incarnation: source.incarnation, lifetime: null, slug: '', subjectKind: 'coverage', subjectKey: COVERAGE_KEY,
+ eventType: 'coverage.restored', trustTier: 'unknown', tierBasis: 'unknown', visibility: 'world', value: null, stateHash: '',
+ cause: { op: 'coverage.restored', restore_id: input.restoreId, archived_at: input.archivedAt, purge_replay: state,
+ replays: replays.filter(r => newerFor(input.lines, r.request, source.id)) } }], { publicationId: randomUUID(), origin: 'live', purgesPossible: false });
+ }
+ return { state, replays };
+}
+
+const newerFor = (lines: PurgeMirrorLine[] | null, request: string, sourceId: string) =>
+ !!lines?.some(l => l.kind === 'intent' && l.request === request && l.source_id === sourceId);
+
+/** The last restore's purge replay per source (`coverage.restored`), for the doctor finding: anything but none/complete asks the user. */
+export async function readRestorePurgeReplay(engine: Pick<BrainEngine, 'executeRaw'>): Promise<Array<{ source_id: string; archived_at: string; purge_replay: PurgeReplayState;
+ replays: ReplayRecord[]; recorded_at: string }>> {
+ const rows = await engine.executeRaw<{ source_id: string; cause: unknown; recorded_at: string }>(`SELECT DISTINCT ON (e.source_id) e.source_id, e.cause, e.recorded_at
+ FROM belief_events e JOIN sources s ON s.id = e.source_id AND s.incarnation = e.source_incarnation
+ WHERE e.subject_kind = 'coverage' AND e.event_type = 'coverage.restored' ORDER BY e.source_id, e.id DESC`);
+ return rows.map(r => {
+ const cause = (typeof r.cause === 'string' ? JSON.parse(r.cause) : r.cause) as { archived_at: string; purge_replay: PurgeReplayState; replays?: ReplayRecord[] };
+ return { source_id: r.source_id, archived_at: cause.archived_at, purge_replay: cause.purge_replay, replays: cause.replays ?? [], recorded_at: new Date(r.recorded_at).toISOString() };
+ });
+}
+
+/**
+ * Postgres restores happen outside gbrain: `gbrain beliefs replay-purges --from <pre-restore database url> --since <archive time>`
+ * runs this against the restored database. The pre-restore database is complete by construction: its tombstones
+ * (fact_purges, take_purges, page_purges) newer than the archive, grouped by request, are the purges to replay.
+ */
+export async function replayPurgesFromDatabase(restored: BrainEngine, preRestore: Pick<BrainEngine, 'executeRaw'>, archivedAt: string):
+ Promise<{ state: PurgeReplayState; replays: ReplayRecord[] }> {
+ const facts = await preRestore.executeRaw<{ request: string; source_id: string; visibility: string; subject: string; fact_hash: string; at: string }>(`SELECT
+ request_id::text AS request, source_id, visibility, subject, fact_hash, purged_at::text AS at FROM fact_purges WHERE purged_at > $1::timestamptz AND request_id IS NOT NULL`, [archivedAt]);
+ const takes = await preRestore.executeRaw<{ request: string; source_id: string; claim_hash: string; at: string }>(`SELECT request_id::text AS request, source_id, claim_hash,
+ purged_at::text AS at FROM take_purges WHERE purged_at > $1::timestamptz AND request_id IS NOT NULL`, [archivedAt]);
+ const pages = await preRestore.executeRaw<{ request: string; source_id: string; slug: string; content_hash: string; at: string }>(`SELECT request_id::text AS request,
+ source_id, slug, content_hash, purged_at::text AS at FROM page_purges WHERE purged_at > $1::timestamptz AND request_id IS NOT NULL`, [archivedAt]);
+ const incarnations = new Map((await preRestore.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources'))
+ .map(s => [s.id, s.incarnation]));
+ const intents = new Map<string, PurgeMirrorIntent>();
+ const intentFor = (request: string, sourceId: string, at: string) => {
+ const existing = intents.get(request);
+ if (existing) return existing;
+ const created: PurgeMirrorIntent = { kind: 'intent', request, request_id: request, source_id: sourceId, source_incarnation: incarnations.get(sourceId) ?? '',
+ scope: 'fact', recorded_at: new Date(at).toISOString(), purge_epoch: 0, facts: [], takes: [], lifetimes: [] };
+ intents.set(request, created);
+ return created;
+ };
+ for (const p of pages) { const i = intentFor(p.request, p.source_id, p.at); i.scope = 'page'; i.slug = p.slug; i.content_hashes = [...(i.content_hashes ?? []), p.content_hash]; }
+ for (const f of facts) intentFor(f.request, f.source_id, f.at).facts.push({ fact_hash: f.fact_hash, visibility: f.visibility, subject: f.subject });
+ for (const t of takes) intentFor(t.request, t.source_id, t.at).takes.push(t.claim_hash);
+ const lines: PurgeMirrorLine[] = [...intents.values()].sort((a, b) => a.recorded_at < b.recorded_at ? -1 : 1)
+ .flatMap(i => [i, { kind: 'committed' as const, request: i.request, recorded_at: i.recorded_at }]);
+ return restored.transaction(tx => replayPurgesInRestore(tx, { lines, archivedAt: new Date(archivedAt).toISOString(), restoreId: randomUUID() }));
+}
diff --git a/src/core/belief/purge.ts b/src/core/belief/purge.ts
new file mode 100644
index 0000000000..18c389265d
--- /dev/null
+++ b/src/core/belief/purge.ts
@@ -0,0 +1,311 @@
+/**
+ * Purge redaction of the belief ledger (docs/designs/BELIEF_LEDGER.md section
+ * 6.5), run inside the purge transaction after its projections:
+ *
+ * 1. purged keys: every event of a purged claim fingerprint (fact and take
+ * events carry the claim-only fingerprint in `claim_fp`, so kind, holder,
+ * subject and the rename chain cannot evade it) and every event of the purged
+ * page's lifetimes loses its value and is marked `purged`;
+ * 2. carrying fields: every event in the source whose value contains a purge
+ * needle has each carrying field that quotes a claim replaced by the
+ * redaction marker, its value_hash recomputed and the field listed in
+ * `redacted_fields`; each replacement is registered in `belief_redactions`
+ * so later appends keep the marker until an owner release (append.ts);
+ * 3. derived keys: each row the derivation walk hides gets one `derived.hidden`
+ * event naming the purge request; `readBeliefHistory` hides the key's events
+ * up to it (and its backfill events at any id).
+ *
+ * The scans are keyset batches over the source's events; a statement timeout
+ * propagates (57014) and the caller refuses the whole purge with the typed
+ * `purge_lookup_timeout`, never a partial one. Nothing runs when the source has
+ * no ledger events.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { escapeFenceCell } from '../fence-shared.ts';
+import { parseFactsFence } from '../facts-fence.ts';
+import { parseTakesFence } from '../takes-fence.ts';
+import { faultPoint } from '../persistence/fault-points.ts';
+import type { DerivedRow } from '../facts/derivation-inputs.ts';
+import { CARRYING_FIELDS, REDACTION_MARKER, canonicalJson, fieldHash, pageKey, valueHash } from './keys.ts';
+import { readBeliefState } from './state.ts';
+import { keyedSubjects, pageNeeds } from './subjects.ts';
+import { resolveLifetimes } from './lifetimes.ts';
+import { appendBeliefEvents, type BeliefEventDraft } from './append.ts';
+import { coverageActive, readLedgerSource } from './ledger.ts';
+
+const SCAN_BATCH = 1000;
+
+export type PurgeRedactionFault = 'skip_purged_keys' | 'skip_carrying_fields' | 'skip_live_carriers' | 'skip_derived_hidden' | 'bounded_inventory';
+let redactionFault: PurgeRedactionFault | null = null;
+/** Forced-probe seam (section 11): a deliberately broken redaction pass the probe that covers it must catch. Null restores it. */
+export function __setPurgeRedactionFaultForTests(fault: PurgeRedactionFault | null): void { redactionFault = fault; }
+
+/** The source's purge counter, incremented in the purge transaction; payloads prepared under an older epoch are refused. */
+export async function bumpPurgeEpoch(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<number> {
+ const [row] = await tx.executeRaw<{ purge_epoch: string | number }>('UPDATE sources SET purge_epoch = purge_epoch + 1 WHERE id = $1 RETURNING purge_epoch', [sourceId]);
+ return Number(row?.purge_epoch ?? 0);
+}
+
+export async function sourceHasBeliefEvents(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<boolean> {
+ const [row] = await tx.executeRaw<{ present: boolean }>('SELECT EXISTS (SELECT 1 FROM belief_events WHERE source_id = $1) AS present', [sourceId]);
+ return row?.present === true;
+}
+
+/** A claim as it can appear in stored text: plain, fence-escaped, and each JSON-escaped (event values are matched as JSON text). */
+export function purgeNeedles(claims: readonly string[]): string[] {
+ const out = new Set<string>();
+ for (const claim of claims) {
+ const lower = claim.trim().toLowerCase();
+ if (!lower) continue;
+ for (const form of [lower, escapeFenceCell(lower)]) { out.add(form); out.add(JSON.stringify(form).slice(1, -1)); }
+ }
+ return [...out];
+}
+
+const quotes = (text: string, claims: readonly string[]) => {
+ const lower = text.toLowerCase();
+ return claims.some(c => { const l = c.trim().toLowerCase(); return !!l && (lower.includes(l) || lower.includes(escapeFenceCell(l))); });
+};
+
+/** Pass 1: purged keys lose their values. Returns the events marked. */
+export async function redactPurgedKeys(tx: Pick<BrainEngine, 'executeRaw'>, input: { sourceId: string; claimFps: readonly string[]; lifetimes: readonly string[] }): Promise<number> {
+ if ((!input.claimFps.length && !input.lifetimes.length) || redactionFault === 'skip_purged_keys') return 0;
+ const rows = await tx.executeRaw(`UPDATE belief_events SET value = NULL, value_hash = NULL, purged = true
+ WHERE source_id = $1 AND ((subject_kind IN ('fact','take') AND claim_fp = ANY($2::text[])) OR page_lifetime = ANY($3::uuid[]))
+ AND (purged = false OR value IS NOT NULL) RETURNING id`, [input.sourceId, [...input.claimFps], [...input.lifetimes]]);
+ return rows.length;
+}
+
+export interface RedactedField { subject_key: string; field: string; event_id: number }
+
+/** Pass 2: carrying fields that quote a purged claim become the redaction marker and enter the redaction register. */
+export async function redactCarryingFields(tx: Pick<BrainEngine, 'executeRaw'>, input: { sourceId: string; request: string; claims: readonly string[] }): Promise<RedactedField[]> {
+ const needles = purgeNeedles(input.claims);
+ if (!needles.length || redactionFault === 'skip_carrying_fields') return [];
+ const out: RedactedField[] = [];
+ const registered = new Set<string>();
+ for (let after = 0; ;) {
+ await faultPoint('purge:ledger_redaction', { sourceId: input.sourceId });
+ const rows = await tx.executeRaw<{ id: number; subject_kind: string; subject_key: string; value: unknown; redacted_fields: string[] | null }>(`SELECT e.id, e.subject_kind,
+ e.subject_key, e.value, e.redacted_fields FROM belief_events e
+ WHERE e.source_id = $1 AND e.id > $2 AND e.value IS NOT NULL AND e.subject_kind IN ('fact','take','link')
+ AND EXISTS (SELECT 1 FROM unnest($3::text[]) n WHERE strpos(lower(e.value::text), n) > 0)
+ ORDER BY e.id LIMIT ${SCAN_BATCH}`, [input.sourceId, after, needles]);
+ if (!rows.length) break;
+ after = Number(rows[rows.length - 1]!.id);
+ for (const row of rows) {
+ const value = (typeof row.value === 'string' ? JSON.parse(row.value) : row.value) as Record<string, unknown>;
+ const fields = (CARRYING_FIELDS[row.subject_kind] ?? []).filter(f => typeof value[f] === 'string' && quotes(value[f] as string, input.claims));
+ if (!fields.length) continue;
+ const next = { ...value };
+ for (const field of fields) {
+ const tag = `${row.subject_key}\u0000${field}\u0000${fieldHash(value[field] as string)}`;
+ if (!registered.has(tag)) {
+ registered.add(tag);
+ await tx.executeRaw(`INSERT INTO belief_redactions (source_id, subject_key, field, purge_request, field_hash)
+ SELECT $1, $2, $3, $4::uuid, $5 WHERE NOT EXISTS (SELECT 1 FROM belief_redactions WHERE source_id = $1 AND subject_key = $2 AND field = $3
+ AND purge_request = $4::uuid AND field_hash = $5)`, [input.sourceId, row.subject_key, field, input.request, fieldHash(value[field] as string)]);
+ }
+ next[field] = REDACTION_MARKER(input.request);
+ out.push({ subject_key: row.subject_key, field, event_id: Number(row.id) });
+ }
+ const listed = [...new Set([...(row.redacted_fields ?? []), ...fields])];
+ await tx.executeRaw('UPDATE belief_events SET value = $2::text::jsonb, value_hash = $3, redacted_fields = $4::text[] WHERE id = $1',
+ [row.id, canonicalJson(next), valueHash(next), listed]);
+ }
+ if (rows.length < SCAN_BATCH) break;
+ }
+ return out;
+}
+
+/**
+ * Pass 2, live half: a surviving row whose carrying field quotes a purged claim (a fence row's context, a take's
+ * resolution evidence, a link's context) is left as it is by the purge, so its key enters the redaction register
+ * with the field's current hash; its next event (a confidence edit, a reconcile, a backfill) then writes the marker
+ * until the owner releases it. Returns the registered keys, which the receipt names.
+ */
+export async function registerLiveCarriers(tx: BrainEngine, input: { sourceId: string; request: string; claims: readonly string[] }): Promise<RedactedField[]> {
+ const needles = [...new Set(input.claims.map(c => c.trim().toLowerCase()).filter(Boolean).flatMap(c => [c, escapeFenceCell(c)]))];
+ const source = await readLedgerSource(tx, input.sourceId);
+ if (!needles.length || !source || redactionFault === 'skip_live_carriers') return [];
+ await faultPoint('purge:ledger_redaction', { sourceId: input.sourceId });
+ const quoting = (column: string) => `EXISTS (SELECT 1 FROM unnest($2::text[]) n WHERE strpos(lower(COALESCE(${column},'')), n) > 0)`;
+ const slugs = (await tx.executeRaw<{ slug: string }>(`SELECT DISTINCT slug FROM (
+ SELECT COALESCE(f.source_markdown_slug, f.entity_slug) AS slug FROM facts f WHERE f.source_id = $1 AND f.expired_at IS NULL AND ${quoting('f.context')}
+ UNION SELECT p.slug FROM takes k JOIN pages p ON p.id = k.page_id WHERE p.source_id = $1 AND ${quoting('k.resolved_source')}
+ UNION SELECT COALESCE(o.slug, f.slug) FROM links l JOIN pages f ON f.id = l.from_page_id LEFT JOIN pages o ON o.id = l.origin_page_id
+ WHERE COALESCE(o.source_id, f.source_id) = $1 AND ${quoting('l.context')}) s WHERE slug IS NOT NULL ORDER BY slug`, [input.sourceId, needles])).map(r => r.slug);
+ const out: RedactedField[] = [];
+ for (let at = 0; at < slugs.length; at += 200) {
+ const state = await readBeliefState(tx, input.sourceId, slugs.slice(at, at + 200));
+ const lifetimes = await resolveLifetimes(tx, pageNeeds(input.sourceId, source.incarnation, state));
+ const subjects = keyedSubjects({ incarnation: source.incarnation, lifetimes, pagesBySlug: new Map(state.pages.map(p => [p.slug, p])) }, state,
+ id => state.pages.find(p => p.id === id)?.visible === false ? 'private' : 'world');
+ for (const subject of subjects) for (const field of CARRYING_FIELDS[subject.kind] ?? []) {
+ const text = subject.value[field];
+ if (typeof text !== 'string' || !quotes(text, input.claims)) continue;
+ await tx.executeRaw(`INSERT INTO belief_redactions (source_id, subject_key, field, purge_request, field_hash)
+ SELECT $1, $2, $3, $4::uuid, $5 WHERE NOT EXISTS (SELECT 1 FROM belief_redactions WHERE source_id = $1 AND subject_key = $2 AND field = $3
+ AND purge_request = $4::uuid AND field_hash = $5)`, [input.sourceId, subject.key, field, input.request, fieldHash(text)]);
+ out.push({ subject_key: subject.key, field, event_id: 0 });
+ }
+ }
+ return out;
+}
+
+/** The lifetimes of one page: its open lifetime at the slug and every lifetime whose page hint is the page (renames keep it). */
+export async function pageLifetimesOf(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slug: string, pageId: number): Promise<string[]> {
+ const rows = await tx.executeRaw<{ page_lifetime: string }>(`SELECT page_lifetime::text AS page_lifetime FROM belief_page_lifetimes
+ WHERE source_id = $1 AND (page_id = $3 OR (slug = $2 AND ended_at IS NULL AND page_id IS NULL))`, [sourceId, slug, pageId]);
+ return rows.map(r => r.page_lifetime);
+}
+
+/**
+ * A page purge's exhaustive claim inventory: every fact and take claim on the page, every fence claim
+ * in its retained versions, and every claim in its lifetimes' events (keyset batches, no row or length cap).
+ */
+export async function pagePurgeClaims(tx: Pick<BrainEngine, 'executeRaw'>, input: { sourceId: string; slug: string; pageId: number; lifetimes: readonly string[] }): Promise<{ claims: string[]; fps: string[] }> {
+ const claims = new Set<string>();
+ const fps = new Set<string>();
+ const live = await tx.executeRaw<{ claim: string; fp: string }>(`SELECT fact AS claim, gbrain_fact_fingerprint(fact) AS fp FROM facts WHERE source_id = $1 AND source_markdown_slug = $2
+ UNION SELECT claim, gbrain_fact_fingerprint(claim) FROM takes WHERE page_id = $3`, [input.sourceId, input.slug, input.pageId]);
+ for (const r of live) { claims.add(r.claim); fps.add(r.fp); }
+ for (let after = 0; ;) {
+ await faultPoint('purge:ledger_redaction', { sourceId: input.sourceId });
+ const versions = await tx.executeRaw<{ id: number; compiled_truth: string; timeline: string | null }>(`SELECT id, compiled_truth, timeline FROM page_versions
+ WHERE page_id = $1 AND id > $2 ORDER BY id LIMIT ${SCAN_BATCH}`, [input.pageId, after]);
+ if (!versions.length) break;
+ after = Number(versions[versions.length - 1]!.id);
+ for (const v of versions) for (const body of [v.compiled_truth ?? '', v.timeline ?? '']) {
+ parseFactsFence(body).facts.forEach(f => claims.add(f.claim));
+ parseTakesFence(body).takes.forEach(t => claims.add(t.claim));
+ }
+ if (versions.length < SCAN_BATCH) break;
+ }
+ if (input.lifetimes.length) for (let after = 0; ;) {
+ await faultPoint('purge:ledger_redaction', { sourceId: input.sourceId });
+ const events = await tx.executeRaw<{ id: number; claim: string | null; claim_fp: string | null }>(`SELECT id, COALESCE(value->>'fact', value->>'claim') AS claim, claim_fp
+ FROM belief_events WHERE page_lifetime = ANY($1::uuid[]) AND subject_kind IN ('fact','take') AND id > $2 ORDER BY id LIMIT ${SCAN_BATCH}`, [[...input.lifetimes], after]);
+ if (!events.length) break;
+ after = Number(events[events.length - 1]!.id);
+ for (const e of events) { if (e.claim) claims.add(e.claim); if (e.claim_fp) fps.add(e.claim_fp); }
+ if (events.length < SCAN_BATCH) break;
+ }
+ if (redactionFault === 'bounded_inventory') return { claims: [...new Set([...live.map(r => r.claim)].map(c => c.trim()).filter(c => c.length >= 8))].slice(0, 32), fps: [...fps] };
+ return { claims: [...claims].filter(c => c.trim()), fps: [...fps] };
+}
+
+/** The stream slug of each derived row (fact: its fence page or entity; take: its page; page: itself). */
+export async function derivedStreamSlugs(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string, rows: readonly DerivedRow[]): Promise<Map<string, string>> {
+ const ids = (table: string) => rows.filter(r => r.table === table && /^\d+$/.test(r.id)).map(r => Number(r.id));
+ const found = await tx.executeRaw<{ ref: string; slug: string }>(`SELECT 'facts:' || id AS ref, COALESCE(source_markdown_slug, entity_slug) AS slug FROM facts
+ WHERE source_id = $1 AND id = ANY($2::bigint[]) AND COALESCE(source_markdown_slug, entity_slug) IS NOT NULL
+ UNION ALL SELECT 'takes:' || k.id, p.slug FROM takes k JOIN pages p ON p.id = k.page_id WHERE p.source_id = $1 AND k.id = ANY($3::bigint[])
+ UNION ALL SELECT 'pages:' || id, slug FROM pages WHERE source_id = $1 AND id = ANY($4::int[])`, [sourceId, ids('facts'), ids('takes'), ids('pages')]);
+ return new Map(found.map(r => [r.ref, r.slug]));
+}
+
+export interface DerivedTarget { ref: string; slug: string; draft: Omit<BeliefEventDraft, 'eventType' | 'cause' | 'value'> }
+
+/** Maps each derived row to its logical key, before the walk hides it (an expired fact leaves the stream's state). */
+export async function derivedBeliefTargets(tx: BrainEngine, sourceId: string, rows: readonly DerivedRow[]): Promise<DerivedTarget[]> {
+ const source = await readLedgerSource(tx, sourceId);
+ if (!rows.length || !source) return [];
+ const slugs = await derivedStreamSlugs(tx, sourceId, rows);
+ const streams = [...new Set(slugs.values())];
+ if (!streams.length) return [];
+ const state = await readBeliefState(tx, sourceId, streams);
+ const lifetimes = await resolveLifetimes(tx, pageNeeds(sourceId, source.incarnation, state));
+ const subjects = keyedSubjects({ incarnation: source.incarnation, lifetimes, pagesBySlug: new Map(state.pages.map(p => [p.slug, p])) }, state,
+ id => state.pages.find(p => p.id === id)?.visible === false ? 'private' : 'world');
+ const out: DerivedTarget[] = [];
+ for (const row of rows) {
+ const ref = `${row.table}:${row.id}`, slug = slugs.get(ref);
+ if (!slug) continue;
+ const page = state.pages.find(p => p.slug === slug) ?? null;
+ const lifetime = page ? lifetimes.get(page.id) ?? null : null;
+ const base = { sourceId, incarnation: source.incarnation, lifetime, slug, stream: slug, stateHash: '', tierBasis: 'row' as const };
+ if (row.table === 'pages' && page && lifetime) {
+ out.push({ ref, slug, draft: { ...base, subjectKind: 'page', subjectKey: pageKey(lifetime), trustTier: page.tier, visibility: page.visible ? 'world' : 'private' } });
+ continue;
+ }
+ const kind = row.table === 'facts' ? 'fact' : row.table === 'takes' ? 'take' : null;
+ const subject = kind ? subjects.find(s => s.kind === kind && s.rowIds.includes(Number(row.id))) : undefined;
+ if (subject) out.push({ ref, slug, draft: { ...base, subjectKind: subject.kind, subjectKey: subject.key, trustTier: subject.tier || 'unknown',
+ visibility: subject.visibility, claimFp: subject.claimFp } });
+ }
+ return out;
+}
+
+/** Pass 3: one `derived.hidden` per hidden key, appended when coverage is active or the key already has events. */
+export async function appendDerivedHidden(tx: BrainEngine, input: { sourceId: string; request: string; publicationId: string; op: string;
+ targets: readonly DerivedTarget[]; truncated: boolean; cause?: Record<string, unknown> }): Promise<number> {
+ if (!input.targets.length || redactionFault === 'skip_derived_hidden') return 0;
+ const source = await readLedgerSource(tx, input.sourceId);
+ if (!source) return 0;
+ const keys = [...new Set(input.targets.map(t => t.draft.subjectKey))];
+ const known = new Set((await tx.executeRaw<{ subject_key: string }>(`SELECT DISTINCT subject_key FROM belief_events WHERE source_id = $1 AND subject_key = ANY($2::text[])`,
+ [input.sourceId, keys])).map(r => r.subject_key));
+ const active = coverageActive(source.coverage);
+ const seen = new Set<string>();
+ const drafts: BeliefEventDraft[] = [];
+ for (const t of input.targets) {
+ if (seen.has(t.draft.subjectKey) || (!active && !known.has(t.draft.subjectKey))) continue;
+ seen.add(t.draft.subjectKey);
+ drafts.push({ ...t.draft, eventType: 'derived.hidden', value: null, cause: { op: input.op, purge_request: input.request, row: t.ref,
+ ...(input.truncated ? { derived_walk: 'truncated' } : {}), ...input.cause } });
+ }
+ return appendBeliefEvents(tx, drafts, { publicationId: input.publicationId, origin: source.managed ? 'live' : 'unmanaged', purgesPossible: true });
+}
+
+export interface LedgerPurgeReport { purged_events: number; redacted_fields: RedactedField[]; live_carriers: RedactedField[]; derived_hidden: number; derived_walk: 'complete' | 'truncated' }
+
+/** Purge requests whose derivation walk was truncated: the coverage check withholds certification of their source until a complete walk runs. */
+export async function truncatedPurgeWalks(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<string[]> {
+ const rows = await engine.executeRaw<{ request: string }>(`SELECT DISTINCT cause->>'purge_request' AS request FROM belief_events
+ WHERE source_id = $1 AND cause->>'derived_walk' = 'truncated' AND cause->>'purge_request' IS NOT NULL ORDER BY 1`, [sourceId]);
+ return rows.map(r => r.request);
+}
+
+/** The logical key of one live fact or take row and its carrying-field values, for an owner release. */
+async function rowSubject(engine: BrainEngine, table: 'facts' | 'takes', id: number): Promise<{ sourceId: string; key: string; value: Record<string, unknown> } | null> {
+ const [row] = await engine.executeRaw<{ source_id: string; slug: string | null }>(table === 'facts'
+ ? 'SELECT source_id, COALESCE(source_markdown_slug, entity_slug) AS slug FROM facts WHERE id = $1'
+ : 'SELECT p.source_id, p.slug FROM takes k JOIN pages p ON p.id = k.page_id WHERE k.id = $1', [id]);
+ if (!row?.slug) return null;
+ const source = await readLedgerSource(engine, row.source_id);
+ if (!source) return null;
+ const state = await readBeliefState(engine, row.source_id, [row.slug]);
+ const lifetimes = await resolveLifetimes(engine, pageNeeds(row.source_id, source.incarnation, state));
+ const subject = keyedSubjects({ incarnation: source.incarnation, lifetimes, pagesBySlug: new Map(state.pages.map(p => [p.slug, p])) }, state,
+ pageId => state.pages.find(p => p.id === pageId)?.visible === false ? 'private' : 'world')
+ .find(s => s.kind === (table === 'facts' ? 'fact' : 'take') && s.rowIds.includes(id));
+ return subject ? { sourceId: row.source_id, key: subject.key, value: subject.value } : null;
+}
+
+/** Carrying fields of a row still under a purge redaction its current value has not been released for. */
+export async function suppressedFields(engine: BrainEngine, table: 'facts' | 'takes', id: number): Promise<string[]> {
+ const subject = await rowSubject(engine, table, id);
+ if (!subject) return [];
+ const rows = await engine.executeRaw<{ field: string; released_hash: string | null }>(`SELECT field, released_hash FROM belief_redactions
+ WHERE source_id = $1 AND subject_key = $2`, [subject.sourceId, subject.key]);
+ return [...new Set(rows.filter(r => typeof subject.value[r.field] === 'string' && r.released_hash !== fieldHash(subject.value[r.field] as string)).map(r => r.field))];
+}
+
+/**
+ * The owner release (section 6.5): the confirm action on a key binds each suppressed field to its current value
+ * (`released_hash`), so the next append that writes exactly that value records it; any later change is redacted again.
+ */
+export async function releaseSuppressedFields(engine: BrainEngine, table: 'facts' | 'takes', id: number, releasedBy: string): Promise<string[]> {
+ const subject = await rowSubject(engine, table, id);
+ if (!subject) return [];
+ const released: string[] = [];
+ for (const field of CARRYING_FIELDS[table === 'facts' ? 'fact' : 'take'] ?? []) {
+ const text = subject.value[field];
+ if (typeof text !== 'string') continue;
+ const rows = await engine.executeRaw(`UPDATE belief_redactions SET released_by = $4::uuid, released_hash = $5 WHERE source_id = $1 AND subject_key = $2 AND field = $3
+ AND released_hash IS DISTINCT FROM $5 RETURNING id`, [subject.sourceId, subject.key, field, releasedBy, fieldHash(text)]);
+ if (rows.length) released.push(field);
+ }
+ return released;
+}
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.ts
index a8c44a963c..f191646755 100644
--- a/src/core/deletion-inventory.ts
+++ b/src/core/deletion-inventory.ts
@@ -36,6 +36,10 @@ export interface InventoryEntry {
type Row = [table: string, cls: InventoryClass, reason: string, columns: string, probe?: string];
const ROWS: readonly Row[] = [
['access_tokens', 'out_of_scope', 'secret_material', 'name token_hash scopes permissions source_grant source_id federated_read allowed_operations takes_holders min_trust'],
+ ['belief_events', 'swept', 'belief_ledger', 'event_key source_id slug subject_kind subject_key event_type origin trust_tier writer_tier tier_basis visibility value value_hash prior_hash state_hash cause claim_fp redacted_fields'],
+ ['belief_page_lifetimes', 'out_of_scope', 'text_free_ledger', 'source_id slug'],
+ ['belief_redactions', 'out_of_scope', 'text_free_ledger', 'source_id subject_key field field_hash released_hash'],
+ ['belief_retier_manifest', 'out_of_scope', 'text_free_ledger', 'source_id subject_kind subject_key from_tier to_tier'],
['budget_ledger', 'out_of_scope', 'no_memory_text', 'scope resolver_id'],
['budget_reservations', 'out_of_scope', 'no_memory_text', 'reservation_id scope resolver_id status'],
['calibration_profiles', 'out_of_scope', 'probed_reported', 'source_id holder wave_version domain_scorecards pattern_statements active_bias_tags model_id', 'pattern_statements domain_scorecards'],
diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.ts
index 72982f4e88..b1980ced46 100644
--- a/src/core/facts/purge-verify.ts
+++ b/src/core/facts/purge-verify.ts
@@ -26,6 +26,7 @@ import type { WriteRequest } from '../persistence/model.ts';
import { DELETION_INVENTORY, OUT_OF_REACH_RESIDUALS, type InventoryEntry } from '../deletion-inventory.ts';
import type { PurgePlan, PurgeTarget } from './purge.ts';
import { gitChildEnv } from '../git-env.ts';
+import { purgeNeedles, type LedgerPurgeReport } from '../belief/purge.ts';
export type StoreCount = Record<string, number>;
export type StoreStatus = 'deleted' | 'would_remove' | 'retained_inactive' | 'unverified' | 'out_of_reach' | 'out_of_scope' | 'not_present' | 'incomplete';
@@ -117,8 +118,86 @@ async function probeTable(engine: BrainEngine, entry: InventoryEntry, sourceId:
return boundedCount(engine, `SELECT 1 FROM ${entry.table} WHERE ${scoped ? 'source_id=$1 AND' : '$1::text IS NOT NULL AND'} (${ors.join(' OR ')})`, params, deadline);
}
+/**
+ * W1 prerequisite (BELIEF_LEDGER.md 6.5): link context, timeline detail and raw data are reported, not swept, so their
+ * receipt names the rows that still carry the claim (scoped to the source through their page), not only a count.
+ */
+const NAMED_ROW_PROBES: Readonly<Record<string, { select: string; columns: readonly string[] }>> = {
+ links: { columns: ['l.context'], select: `SELECT 'link:' || l.id || ' ' || f.slug || ' -> ' || t.slug AS item FROM links l JOIN pages f ON f.id = l.from_page_id
+ JOIN pages t ON t.id = l.to_page_id WHERE (f.source_id = $1 OR t.source_id = $1)` },
+ timeline_entries: { columns: ['x.summary', 'x.detail'], select: `SELECT 'timeline:' || x.id || ' ' || p.slug || ' ' || x.date::text AS item FROM timeline_entries x
+ JOIN pages p ON p.id = x.page_id WHERE p.source_id = $1` },
+ raw_data: { columns: ['r.data'], select: `SELECT 'raw_data:' || r.id || ' ' || p.slug || ' ' || r.source AS item FROM raw_data r JOIN pages p ON p.id = r.page_id WHERE p.source_id = $1` },
+};
+
+let namedRowProbes = true;
+/** Forced-probe seam: false restores the count-only generic adapter for these stores. */
+export function __setNamedRowProbesForTests(enabled: boolean): void { namedRowProbes = enabled; }
+
+async function probeNamedRows(engine: BrainEngine, entry: InventoryEntry, sourceId: string, needles: readonly string[], deadline: number): Promise<StoreReport> {
+ const named = NAMED_ROW_PROBES[entry.table]!;
+ const params: unknown[] = [sourceId];
+ const ors: string[] = [];
+ for (const needle of needles.filter(Boolean).slice(0, 32)) {
+ params.push(needle.toLowerCase(), JSON.stringify(needle).slice(1, -1).toLowerCase());
+ ors.push(...named.columns.map(col => textMatch(col, params.length - 1)));
+ }
+ if (!ors.length) return { store: entry.table, status: 'not_present' };
+ const sql = `${named.select} AND (${ors.join(' OR ')})`;
+ const counted = await boundedCount(engine, sql, params, deadline);
+ if ('unverified' in counted) return { store: entry.table, status: 'unverified', reason: counted.unverified };
+ if (!counted.count) return { store: entry.table, status: 'not_present' };
+ const items = (await engine.executeRaw<{ item: string }>(`${sql} ORDER BY 1 LIMIT 20`, params)).map(r => r.item);
+ return { store: entry.table, status: 'out_of_scope', reason: 'probed_reported', remaining: counted.count, items,
+ detail: `${counted.count} row(s) still carry the purged text (listed in items, up to 20); purge does not rewrite this store, so edit or remove them.` };
+}
+
+/** W1 (BELIEF_LEDGER.md 6.5): a queued effect whose payload still carries the purged text would write it back after the purge. */
+async function effectPayloadReport(engine: BrainEngine, sourceId: string, needles: readonly string[], deadline: number, removed: number): Promise<StoreReport> {
+ const list = needles.filter(Boolean).slice(0, 32);
+ if (!list.length) return { store: 'persistence_effects', status: 'not_present' };
+ const params: unknown[] = [sourceId, ...list.flatMap(n => [n.toLowerCase(), JSON.stringify(n).slice(1, -1).toLowerCase()])];
+ const ors = list.flatMap((_, i) => ['data', 'outcome', 'recovery'].map(c => textMatch(`COALESCE(e.${c}::text,'')`, 2 + i * 2)));
+ const sql = `SELECT 'effect:' || e.id || ' ' || e.kind || ' ' || e.state AS item FROM persistence_effects e WHERE e.source_id = $1 AND (${ors.join(' OR ')})`;
+ const counted = await boundedCount(engine, sql, params, deadline);
+ if ('unverified' in counted) return { store: 'persistence_effects', status: 'unverified', reason: counted.unverified, removed };
+ if (!counted.count) return { store: 'persistence_effects', status: removed ? 'deleted' : 'not_present', removed };
+ const items = (await engine.executeRaw<{ item: string }>(`${sql} ORDER BY 1 LIMIT 20`, params)).map(r => r.item);
+ return { store: 'persistence_effects', status: 'incomplete', remaining: counted.count, items, removed,
+ detail: 'Queued or recorded effects still carry the purged text in their payload, so running them could write it back.' };
+}
+
+/**
+ * The belief ledger after its purge redaction (BELIEF_LEDGER.md 6.5): a carrying field still quoting the claim is
+ * `incomplete`; the redacted fields are named; a live row whose own context quotes the claim survives the purge and is
+ * named as `fact_context` (`out_of_scope: source_prose`) so the user can edit it.
+ */
+async function ledgerReports(engine: BrainEngine, sourceId: string, claims: readonly string[], ledger: LedgerPurgeReport | null | undefined, deadline: number): Promise<StoreReport[]> {
+ const needles = purgeNeedles(claims);
+ if (!needles.length) return [];
+ const carrying = `EXISTS (SELECT 1 FROM unnest($2::text[]) n WHERE strpos(lower(COALESCE(e.value->>'context','')), n) > 0 OR strpos(lower(COALESCE(e.value->>'resolved_source','')), n) > 0)`;
+ const left = await boundedCount(engine, `SELECT 1 FROM belief_events e WHERE e.source_id = $1 AND e.value IS NOT NULL AND e.subject_kind IN ('fact','take','link') AND ${carrying}`,
+ [sourceId, needles], deadline);
+ const redacted = ledger?.redacted_fields ?? [];
+ const removed = (ledger?.purged_events ?? 0) + redacted.length;
+ const items = [...new Set(redacted.map(r => `${r.field}@${r.subject_key}`))].slice(0, 20);
+ const reports: StoreReport[] = ['unverified' in left ? { store: 'belief_events', status: 'unverified', reason: left.unverified, removed }
+ : left.count ? { store: 'belief_events', status: 'incomplete', remaining: left.count, removed }
+ : { store: 'belief_events', status: removed ? 'deleted' : 'not_present', removed, ...(items.length ? { items,
+ detail: 'Recorded history keeps each event\'s skeleton; the purged values and every carrying field that quoted them now read as the redaction marker.' } : {}) }];
+ const live = await engine.executeRaw<{ id: number }>(`SELECT f.id FROM facts f WHERE f.source_id = $1 AND f.expired_at IS NULL
+ AND EXISTS (SELECT 1 FROM unnest($2::text[]) n WHERE strpos(lower(COALESCE(f.context,'')), n) > 0) ORDER BY f.id LIMIT 20`, [sourceId, needles]);
+ if (live.length) {
+ const keys = [...new Set([...(ledger?.live_carriers ?? []), ...redacted].filter(r => r.field === 'context').map(r => r.subject_key))].slice(0, 20);
+ reports.push({ store: 'fact_context', status: 'out_of_scope', reason: 'source_prose', remaining: live.length, items: [...live.map(r => `f${r.id}`), ...keys],
+ detail: 'These live facts quote the purged claim in their context, which purge leaves as it is; their recorded history shows the redaction marker until the owner replaces the context. Edit them.' });
+ }
+ return reports;
+}
+
/** The generic adapter for a `probed_reported` inventory entry. */
async function probeInventoryStore(engine: BrainEngine, entry: InventoryEntry, sourceId: string, needles: readonly string[], deadline: number): Promise<StoreReport> {
+ if (namedRowProbes && NAMED_ROW_PROBES[entry.table]) return probeNamedRows(engine, entry, sourceId, needles, deadline);
const result = await probeTable(engine, entry, sourceId, needles, deadline);
if ('unverified' in result) return { store: entry.table, status: 'unverified', reason: result.unverified };
return result.count
@@ -233,7 +312,7 @@ async function vectorProbe(engine: BrainEngine, target: PurgeTarget): Promise<Re
/** Build the receipt: swept-store verification (or would-remove counts on a dry run), probes, residuals first. */
export async function verifyFactPurge(engine: BrainEngine, input: { target: PurgeTarget; plan: PurgePlan; dryRun: boolean; removed?: StoreCount;
- prose?: Array<{ slug: string; version_id: number }>; vacuum?: boolean }): Promise<PurgeReceipt> {
+ prose?: Array<{ slug: string; version_id: number }>; vacuum?: boolean; ledger?: LedgerPurgeReport | null }): Promise<PurgeReceipt> {
const { target, plan, dryRun } = input;
const deadline = performance.now() + probeLimits.totalMs;
const claim = target.fact, needle = claim.toLowerCase(), src = target.source_id;
@@ -278,6 +357,10 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purg
AND NOT EXISTS (SELECT 1 FROM derivation_inputs d WHERE d.derived_table='pages' AND d.derived_id=p.id::text)`, [src]);
if (Number(legacy?.n ?? 0)) stores.push({ store: 'derived_legacy', status: 'unverified', reason: 'legacy_no_derivation_edges', remaining: Number(legacy.n),
detail: `${legacy.n} model-derived page(s) in this source predate derivation edges, so purge cannot tell whether they restate the claim in other words.` });
+ if (!dryRun) {
+ stores.push(...await ledgerReports(engine, src, [claim], input.ledger, deadline));
+ stores.push(await effectPayloadReport(engine, src, [claim], deadline, removed.persistence_effects ?? 0));
+ }
stores.push(...await sweptInventoryReports(engine, new Set(stores.map(s => s.store)), src, [claim], removed, deadline, dryRun));
for (const entry of DELETION_INVENTORY) {
if (entry.class !== 'out_of_scope' || entry.reason !== 'probed_reported') continue;
@@ -312,7 +395,7 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purg
}
/** In-process context a page purge keeps for its receipt (never journaled): the page's claims as probe needles, and row ids. */
-export interface PagePurgeContext { needles: string[]; factIds: number[]; pageId: number; paths: string[] }
+export interface PagePurgeContext { needles: string[]; factIds: number[]; pageId: number; paths: string[]; ledgerClaims?: string[]; ledger?: LedgerPurgeReport | null }
const outOfReach = (engine: BrainEngine): StoreReport[] => OUT_OF_REACH_RESIDUALS.map(r => ({ store: r.store, status: 'out_of_reach' as const,
detail: r.store === 'database_physical' ? `${r.detail}${engine.kind === 'pglite' ? ' PGLite has no autovacuum.' : ' On Postgres the operator runs VACUUM; WAL archives, replicas and PITR windows are outside gbrain.'}` : r.detail }));
@@ -356,6 +439,10 @@ export async function verifyPagePurge(engine: BrainEngine, input: { sourceId: st
await keyed('persistence_requests', `SELECT 1 FROM persistence_requests WHERE source_id=$1 AND request_id<>$3::uuid AND (
(slug=$2 AND intent IS NOT NULL AND state IN ('committed','conflict','failed','cancelled'))${textChecks.length ? ` OR ${textChecks.join(' OR ')}` : ''})`,
[src, slug, input.requestId, ...needles.map(n => n.toLowerCase())]);
+ if (context) {
+ stores.push(...await ledgerReports(engine, src, context.ledgerClaims ?? needles, context.ledger, deadline));
+ stores.push(await effectPayloadReport(engine, src, needles, deadline, removed.persistence_effects ?? 0));
+ }
stores.push(...await sweptInventoryReports(engine, new Set(stores.map(s => s.store)), src, needles, removed, deadline, false));
for (const entry of DELETION_INVENTORY) {
if (entry.class === 'out_of_scope' && entry.reason === 'probed_reported') stores.push(await probeInventoryStore(engine, entry, src, needles, deadline));
diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.ts
index 8fa207f37c..4bac47c9e3 100644
--- a/src/core/facts/purge.ts
+++ b/src/core/facts/purge.ts
@@ -44,6 +44,11 @@ import { findRequestsCarrying, redactionCounterKeys, redactRequestIntents } from
import { withPageTierKept } from '../trust/fence-append.ts';
import { rebuildPendingPageProjections } from '../page-state/projections.ts';
import { carriesClaimSql, claimNeedles, purgeCompletion, verifyFactPurge, type PurgeReceipt, type StoreCount } from './purge-verify.ts';
+import { noteBelief, withBeliefBatch } from '../belief/ledger.ts';
+import { markBeliefCommits } from '../belief/append.ts';
+import { appendPurgeMirror } from '../belief/purge-mirror.ts';
+import { appendDerivedHidden, bumpPurgeEpoch, derivedBeliefTargets, derivedStreamSlugs, redactCarryingFields, redactPurgedKeys, registerLiveCarriers, sourceHasBeliefEvents,
+ type LedgerPurgeReport } from '../belief/purge.ts';
export const PURGE_OPERATION = 'purge_fact';
const PURGE_TERMINAL_RESERVATION = 64 * 1024;
@@ -134,6 +139,25 @@ export async function planFactPurge(engine: BrainEngine, target: PurgeTarget, al
reviewRows: review.decide_review_queue + review.decide_review_proposals + review.decide_proposals, review, revision };
}
+/** The belief streams a fact purge batches: each purged fact's stream, the rewritten pages, and each derived row's stream. */
+async function factPurgeStreams(tx: BrainEngine, sourceId: string, plan: PurgePlan): Promise<string[]> {
+ const facts = await tx.executeRaw<{ slug: string }>(`SELECT DISTINCT COALESCE(source_markdown_slug, entity_slug) AS slug FROM facts
+ WHERE id = ANY($1::bigint[]) AND COALESCE(source_markdown_slug, entity_slug) IS NOT NULL`, [plan.factIds]);
+ const derived = await derivedStreamSlugs(tx, sourceId, plan.derived.rows);
+ return [...new Set([...facts.map(f => f.slug), ...plan.pages.map(page => page.slug), ...derived.values()])].sort();
+}
+
+/** The ledger redaction's statement timeout refuses the whole purge with the typed code, as the journal lookup does (#6511). */
+async function ledgerLookup<T>(fn: () => Promise<T>, factId: number, sourceId: string): Promise<T> {
+ try { return await fn(); } catch (error) {
+ if ((error as { code?: unknown } | null)?.code !== '57014') throw error;
+ throw opError('purge_lookup_timeout', 'This purge could not finish; nothing was purged. Do not assume the requested content was erased.',
+ `The belief ledger's redaction scan for fact ${factId} in source ${sourceId} exceeded the purge transaction's statement budget, so the transaction rolled back and nothing was removed, tombstoned or redacted. `
+ + 'Run the purge again with a new request id; if it times out again, report it with the belief_ledger_coverage entry of gbrain doctor --json.',
+ { fix: readFix('Lists the request-table indexes and their state, read-only.', { argv: ['gbrain', 'repair', 'request-indexes', '--json'] }) });
+ }
+}
+
/** Pages with a pending recovery record or an unfinished mirror refuse a purge, as effects refuse other writes. */
async function assertNoPendingPublication(tx: BrainEngine, sourceId: string, pages: PurgePlan['pages'], ownRequest: string): Promise<void> {
if (!pages.length) return;
@@ -150,7 +174,7 @@ async function assertNoPendingPublication(tx: BrainEngine, sourceId: string, pag
}
/** Drop purged rows from each affected page's stored body; returns the slugs rewritten. */
-async function rewritePageBodies(tx: BrainEngine, sourceId: string, pages: PurgePlan['pages']): Promise<string[]> {
+export async function rewritePageBodies(tx: BrainEngine, sourceId: string, pages: PurgePlan['pages']): Promise<string[]> {
if (!pages.length) return [];
const rows = await tx.executeRaw<Record<string, unknown>>(`SELECT p.*,COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id),'[]'::jsonb) AS purge_tags
FROM pages p WHERE p.source_id=$1 AND p.id=ANY($2::int[]) ORDER BY p.slug`, [sourceId, pages.map(p => p.page_id)]);
@@ -173,7 +197,7 @@ async function rewritePageBodies(tx: BrainEngine, sourceId: string, pages: Purge
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 }> }> {
+export async function redactPageVersions(tx: BrainEngine, sourceId: string, claim: string, pageIds: number[]): Promise<{ redacted: number; prose: Array<{ slug: string; version_id: number }> }> {
const [needle, escaped] = claimNeedles(claim);
let redacted = 0;
const prose: Array<{ slug: string; version_id: number }> = [];
@@ -279,6 +303,9 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec
let rewritten: string[] = [];
let counts: StoreCount = {};
let prose: Array<{ slug: string; version_id: number }> = [];
+ let ledger = null as LedgerPurgeReport | null;
+ let derivedHidden: Awaited<ReturnType<typeof hideDerivedRows>> = { hidden: {}, markedOnly: {} };
+ const beliefReport = { appended: 0 };
const row = await retryWriteAdmission(p.requestId, remaining => ctx.engine.transaction(async tx => {
await declareDurablePersistence(tx, `${Math.min(2000, remaining)}ms`, '30s');
const [source] = await tx.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation,archived FROM sources WHERE id=$1 FOR UPDATE', [p.sourceId]);
@@ -306,7 +333,16 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec
const plan = committedPlan;
await assertNoPendingPublication(tx, p.sourceId, plan.pages, admitted.id);
const intents = await redactRequestIntents(tx, plan.requests, admitted.id, { needles: [current.fact] });
- await tx.lockPageKeys(plan.pages.map(page => ({ sourceId: p.sourceId, slug: page.slug })));
+ const ledgerPresent = await sourceHasBeliefEvents(tx, p.sourceId);
+ const streams = ledgerPresent ? await factPurgeStreams(tx, p.sourceId, plan) : [];
+ await tx.lockPageKeys([...new Set([...plan.pages.map(page => page.slug), ...streams])].map(slug => ({ sourceId: p.sourceId, slug })));
+ const epoch = await bumpPurgeEpoch(tx, p.sourceId);
+ const derivedTargets = ledgerPresent ? await ledgerLookup(() => derivedBeliefTargets(tx, p.sourceId, plan.derived.rows), current.id, p.sourceId) : [];
+ const walk = plan.derived.truncated ? 'truncated' as const : 'complete' as const;
+ const purgeCause = { purge_request: admitted.id, ...(walk === 'truncated' ? { derived_walk: walk } : {}) };
+ await withBeliefBatch(tx, { sourceId: p.sourceId, slugs: streams, publicationId: admitted.id, op: PURGE_OPERATION, remote: false, cause: purgeCause, report: beliefReport }, async () => {
+ noteBelief({ kind: 'purged', table: 'facts', ids: plan.factIds, request: admitted.id });
+ noteBelief({ kind: 'purged', table: 'takes', ids: plan.takes.map(t => t.id), request: admitted.id });
// Derived rows are hidden while their evidence still exists.
const derived = await hideDerivedRows(tx, plan.derived.rows, { sourceId: p.sourceId, requestId: admitted.id, reason: `purge:${token}` });
await tx.executeRaw(`INSERT INTO fact_purges(source_id,visibility,subject,fact_hash,request_id,actor,reason)
@@ -351,8 +387,21 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec
query_cache: cache, decide_review: review, open_loops: loops, take_proposals: proposals, core_edit_notices: notices,
write_gate_holds: holdIds.length, write_gate_receipts: gateReceipts,
derived_hidden: Object.values(derived.hidden).reduce((a, b) => a + b, 0) };
+ derivedHidden = derived;
+ });
+ ledger = ledgerPresent ? await ledgerLookup(async () => ({
+ purged_events: await redactPurgedKeys(tx, { sourceId: p.sourceId, claimFps: [current.fact_hash], lifetimes: [] }),
+ redacted_fields: await redactCarryingFields(tx, { sourceId: p.sourceId, request: admitted.id, claims: [current.fact] }),
+ live_carriers: await registerLiveCarriers(tx, { sourceId: p.sourceId, request: admitted.id, claims: [current.fact] }),
+ derived_hidden: await appendDerivedHidden(tx, { sourceId: p.sourceId, request: admitted.id, publicationId: admitted.id, op: PURGE_OPERATION,
+ targets: derivedTargets, truncated: walk === 'truncated' }),
+ derived_walk: walk }), current.id, p.sourceId) : null;
+ counts.belief_events = ledger ? ledger.purged_events + ledger.redacted_fields.length : 0;
+ appendPurgeMirror({ kind: 'intent', request: admitted.id, request_id: p.requestId, source_id: p.sourceId, source_incarnation: source.incarnation, scope: 'fact',
+ purge_epoch: epoch, facts: [{ fact_hash: current.fact_hash, visibility: current.visibility, subject: plan.subject }], takes: [], lifetimes: [] });
return completeWrite(tx, admitted, 'committed', { purge: { fact_id: p.id, hash8: token, fact_hash: current.fact_hash, subject: plan.subject,
- visibility: current.visibility, removed: counts, derived: { ...derived, truncated: plan.derived.truncated }, pages: rewritten.length },
+ visibility: current.visibility, removed: counts, derived: { ...derivedHidden, truncated: plan.derived.truncated }, pages: rewritten.length,
+ ...(ledger ? { ledger: { purged_events: ledger.purged_events, redacted_fields: ledger.redacted_fields.length, live_carriers: ledger.live_carriers.length, derived_hidden: ledger.derived_hidden, derived_walk: ledger.derived_walk } } : {}) },
persistence: { mode: 'database' } });
}, requestAttribution(admitted));
}), 30_000);
@@ -362,8 +411,10 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec
await rebuildPendingPageProjections(ctx.engine, 100, { pages: { sourceId: p.sourceId, slugs: slugs.slice(start, start + 100) } }).catch(() => undefined);
}
if (row.state !== 'committed') return { ...(row.outcome ?? {}), request_id: row.request_id, state: row.state, error: row.error_code };
+ appendPurgeMirror({ kind: 'committed', request: row.id });
+ if (beliefReport.appended || ledger?.derived_hidden) await markBeliefCommits(ctx.engine, [row.id]).catch(() => undefined);
const receipt: PurgeReceipt = await verifyFactPurge(ctx.engine, { target, plan: committedPlan, dryRun: false, removed: counts, prose,
- vacuum: params.vacuum === true });
+ vacuum: params.vacuum === true, ledger });
return { ...receipt, purge: (row.outcome as { purge?: unknown } | null)?.purge, request_id: row.request_id, state: row.state, similar_active: similar,
...await purgeCompletion(ctx.engine, row as WriteRequest, receipt) };
}
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index e0a0d9bc41..57ad404a0c 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -22,6 +22,8 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
| 'purge:slug_lookup' | 'purge:tail_recheck' | 'purge:pending_recheck' | 'purge:redaction_read'
// #6511: before each keyset chunk of the preparation-time journal sweep (a stalling hook models a slow chunk), and the fact purge's planning read.
| 'purge:sweep_chunk' | 'purge:carrying_lookup'
+ // W1: before each keyset batch of the belief ledger's purge redaction (belief/purge.ts); a 57014 from the hook models its statement timeout.
+ | 'purge:ledger_redaction'
// #6650: `gbrain repair stuck-recovery` (recovery-resolve.ts): after the backup is durable (before its journal step), after the prior
// bytes are written (before their journal step), after a --keep disk write is abandoned (its journal step written), and after recoverPublication returns.
| 'stuck_recovery:backed_up' | 'stuck_recovery:written' | 'stuck_recovery:abandoned' | 'stuck_recovery:recovered'
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 7fa9cdf7a9..b18c5f007d 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -398,6 +398,9 @@ async function prepareDeletePageMutation(engine: BrainEngine, row: WriteRequest,
// #6511: the purge's journal sweep runs here, under the preparation budget, never inside the 5 s publication transaction.
const preparedPurge: PreparedPagePurge | null = purge ? await preparePagePurge(engine, row, snapshot, clock) : null;
const prepared: PreparedMutation = { observedRevision, noop, file, ...await pageDatabaseOnlyPublication(engine, row, file),
+ // W1: a purge bumps sources.purge_epoch, so it holds the source row exclusively from the start; the derived rows' streams are locked with the page.
+ ...(purge ? { sourceExclusive: true } : {}),
+ ...(preparedPurge?.derivedSlugs.length ? { additionalPageKeys: preparedPurge.derivedSlugs.map(slug => ({ sourceId: row.source_id, slug })) } : {}),
...(excludedPath !== null ? { databaseOnlyReason: 'sync_excluded' as const } : {}), ...(shared ? { databaseOnlyReason: 'shared_origin' as const } : {}),
...(shared ? { validate: async (tx: BrainEngine) => { prepared.databaseOnlyWarning = await validateSharedOrigin(tx, row, shared); } } : {}),
apply: async tx => {
diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.ts
index 308bcc1e38..4b759adb5e 100644
--- a/src/core/persistence/page-purge.ts
+++ b/src/core/persistence/page-purge.ts
@@ -40,6 +40,11 @@ import { findRequestsForSlugs, recheckRequestsCarrying, redactRequestIntents, sw
import { dropPurgedFenceRows } from '../facts/purge-overlay.ts';
import { derivedRowsFrom, hideDerivedRows } from '../facts/derivation-inputs.ts';
import { contentHash } from '../utils.ts';
+import { assertHeldPageKeys } from '../page-state/guards.ts';
+import { noteBelief } from '../belief/ledger.ts';
+import { appendPurgeMirror } from '../belief/purge-mirror.ts';
+import { appendDerivedHidden, bumpPurgeEpoch, derivedBeliefTargets, derivedStreamSlugs, pageLifetimesOf, pagePurgeClaims, redactCarryingFields, redactPurgedKeys, registerLiveCarriers,
+ sourceHasBeliefEvents, type LedgerPurgeReport } from '../belief/purge.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), '
+ 'its take proposals, open loops and core notices, stored write intents for the slug and its attached file records. Still out of reach: the brain repository\'s '
@@ -56,7 +61,7 @@ function hostOnly(command: string) {
* needles) and row ids, keyed by `<source_id>:<request_id>`, in this process only. A receipt built where the
* map has no entry reports the prose probe as unverified.
*/
-const purgeContext = new Map<string, { needles: string[]; factIds: number[]; pageId: number; paths: string[] }>();
+const purgeContext = new Map<string, { needles: string[]; factIds: number[]; pageId: number; paths: string[]; ledgerClaims?: string[]; ledger?: LedgerPurgeReport | null }>();
const PURGE_CONTEXT_LIMIT = 64;
const purgeReceipts = new Map<string, { receipt: Record<string, unknown>; purge: Record<string, unknown> }>();
@@ -69,24 +74,36 @@ async function readPurgeClaims(engine: Pick<BrainEngine, 'executeRaw'>, sourceId
}
/** What the delete preparation hands the purge apply: the claims it searched for, the journal census, and the slug index's state for the failure hint. */
-export interface PreparedPagePurge { needles: string[]; sweep: JournalSweep; slugIndex: RequestIndexState['state'] }
+export interface PreparedPagePurge {
+ needles: string[]; sweep: JournalSweep; slugIndex: RequestIndexState['state'];
+ /** Retention removal of an expired tombstone (`gbrain pages purge-deleted`): no content tombstone, no ledger redaction, `page.expired`. */
+ retention: boolean;
+ /** The belief streams of the rows the derivation walk would hide, locked with the page so their `derived.hidden` events append under their keys. */
+ derivedSlugs: string[];
+}
/**
* #6511: at preparation, before the root lock and outside any transaction: the page's claims, the slug index's state and
* the keyset journal sweep under the preparation budget (the clock between chunks; `boundedReads` on Postgres).
*/
export async function preparePagePurge(engine: BrainEngine, row: WriteRequest, snapshot: PageSnapshot, clock: ClaimPhaseClock | undefined): Promise<PreparedPagePurge> {
enterClaimStep(clock, 'purge_claims', undefined, 'db');
- const { needles } = await readPurgeClaims(engine, row.source_id, snapshot.page.slug, snapshot.page.id);
+ const { needles, factRows, takeRows } = await readPurgeClaims(engine, row.source_id, snapshot.page.slug, snapshot.page.id);
const [slugIndex] = await readRequestIndexStates(engine, [PERSISTENCE_REQUEST_SLUG_INTENT_INDEX]);
const sweep = await sweepRequestsCarrying(engine, row.source_id, needles, { clock, exclude: row.id,
onChunk: () => faultPoint('purge:sweep_chunk', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation }) });
- return { needles, sweep, slugIndex: slugIndex?.state ?? 'missing' };
+ const retention = row.intent?.retention === true;
+ const derivedSlugs = !retention && await sourceHasBeliefEvents(engine, row.source_id)
+ ? [...new Set((await derivedStreamSlugs(engine, row.source_id, (await derivedRowsFrom(engine, [{ table: 'pages', id: snapshot.page.id },
+ ...factRows.map(f => ({ table: 'facts', id: f.id })), ...takeRows.map(t => ({ table: 'takes', id: t.id }))])).rows)).values())].filter(s => s !== snapshot.page.slug).sort()
+ : [];
+ return { needles, sweep, slugIndex: slugIndex?.state ?? 'missing', retention, derivedSlugs };
}
/** The in-transaction journal lookups a statement timeout ends as `purge_lookup_timeout` (also the purge's fault-point seams). */
-export type PurgeLookupPoint = 'slug_lookup' | 'tail_recheck' | 'pending_recheck' | 'redaction_read';
+export type PurgeLookupPoint = 'slug_lookup' | 'tail_recheck' | 'pending_recheck' | 'redaction_read' | 'ledger_redaction';
const LOOKUP_LABEL: Record<PurgeLookupPoint, string> = { slug_lookup: 'lookup of stored intents for the slug', tail_recheck: 're-check of requests admitted after its preparation scan',
- pending_recheck: 're-check of requests that were pending at its preparation scan', redaction_read: 'locking read of the requests to redact' };
+ pending_recheck: 're-check of requests that were pending at its preparation scan', redaction_read: 'locking read of the requests to redact',
+ ledger_redaction: 'belief ledger claim inventory and redaction scan' };
export const PURGE_LOOKUP_TIMEOUT_MESSAGE = 'This purge could not finish; later writes to the source can move again. Do not assume the requested content was erased.';
/** [R6] The failure's `fix` names the index repair only when the slug index is missing or invalid; otherwise a fresh request id. */
export function purgeLookupTimeout(row: Pick<WriteRequest, 'request_id' | 'slug' | 'source_id'>, point: PurgeLookupPoint, slugIndex: RequestIndexState['state']): OperationError {
@@ -113,39 +130,59 @@ async function journalLookup<T>(row: WriteRequest, point: PurgeLookupPoint, slug
}
}
-/** Inside the coordinated delete transaction, before the page row is deleted. */
-export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest, snapshot: PageSnapshot, prepared: PreparedPagePurge): Promise<Record<string, unknown>> {
- const page = snapshot.page, sourceId = row.source_id, slug = page.slug;
- const actor = `${row.principal_kind}:${row.principal_id}`;
- const [stored] = await tx.executeRaw<{ content_hash: string | null }>('SELECT content_hash FROM pages WHERE id=$1', [page.id]);
- const storedHash = stored?.content_hash ?? null;
+/** The text-free tombstones of an owner-requested page purge: its facts, takes, and the content hash of the page and every retained version. */
+async function tombstonePage(tx: BrainEngine, sourceId: string, slug: string, pageId: number, snapshot: PageSnapshot, requestId: string, actor: string,
+ storedHash: string | null, hashes: Set<string>): Promise<void> {
await tx.executeRaw(`INSERT INTO fact_purges(source_id,visibility,subject,fact_hash,request_id,actor,reason)
SELECT DISTINCT source_id,visibility,COALESCE(entity_slug,'*'),gbrain_fact_fingerprint(fact),$3::uuid,$4,'page purge'
- FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ON CONFLICT DO NOTHING`, [sourceId, slug, row.id, actor]);
+ FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ON CONFLICT DO NOTHING`, [sourceId, slug, requestId, actor]);
await tx.executeRaw(`INSERT INTO take_purges(source_id,subject,claim_hash,request_id)
- SELECT DISTINCT $1,$2,gbrain_fact_fingerprint(claim),$4::uuid FROM takes WHERE page_id=$3 ON CONFLICT DO NOTHING`, [sourceId, slug, page.id, row.id]);
+ SELECT DISTINCT $1,$2,gbrain_fact_fingerprint(claim),$4::uuid FROM takes WHERE page_id=$3 ON CONFLICT DO NOTHING`, [sourceId, slug, pageId, requestId]);
// Tombstone the content hash of the page and of every retained version, each as an import of that body would
// compute it and as the purge overlay leaves it (the overlay now drops this page's tombstoned fence rows), so
// neither the stale file nor an older version of it imports again under any slug.
const versions = await tx.executeRaw<Record<string, unknown>>(`SELECT title,type,compiled_truth,timeline,frontmatter,tags,source_path FROM page_versions
- WHERE page_id=$1 ORDER BY id DESC LIMIT 1000`, [page.id]);
- const bodies = [{ ...page, tags: snapshot.tags }, ...versions.map(v => ({ title: String(v.title ?? ''), type: v.type as never,
+ WHERE page_id=$1 ORDER BY id DESC LIMIT 1000`, [pageId]);
+ const bodies = [{ ...snapshot.page, tags: snapshot.tags }, ...versions.map(v => ({ title: String(v.title ?? ''), type: v.type as never,
compiled_truth: String(v.compiled_truth ?? ''), timeline: String(v.timeline ?? ''), frontmatter: (v.frontmatter ?? {}) as Record<string, unknown>,
tags: Array.isArray(v.tags) ? v.tags.map(String) : [] }))];
- const hashes = new Set<string>(storedHash ? [storedHash] : []);
+ if (storedHash) hashes.add(storedHash);
for (const body of bodies) {
hashes.add(contentHash(body));
hashes.add(contentHash({ ...body, compiled_truth: await dropPurgedFenceRows(tx, sourceId, body.compiled_truth, slug),
timeline: await dropPurgedFenceRows(tx, sourceId, body.timeline ?? '', slug) }));
}
await tx.executeRaw(`INSERT INTO page_purges(source_id,content_hash,slug,request_id) SELECT $1,h,$3,$4::uuid FROM unnest($2::text[]) AS h
- 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]);
+ ON CONFLICT (source_id,content_hash) DO UPDATE SET slug=EXCLUDED.slug,request_id=EXCLUDED.request_id,purged_at=now()`, [sourceId, [...hashes], slug, requestId]);
+}
+
+/** Inside the coordinated delete transaction, before the page row is deleted. */
+export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest, snapshot: PageSnapshot, prepared: PreparedPagePurge): Promise<Record<string, unknown>> {
+ const page = snapshot.page, sourceId = row.source_id, slug = page.slug;
+ const actor = `${row.principal_kind}:${row.principal_id}`;
+ const [stored] = await tx.executeRaw<{ content_hash: string | null }>('SELECT content_hash FROM pages WHERE id=$1', [page.id]);
+ const storedHash = stored?.content_hash ?? null;
+ const lookup = <T>(point: PurgeLookupPoint, fn: () => Promise<T>) => journalLookup(row, point, prepared.slugIndex, fn);
+ const retention = prepared.retention;
+ const ledgerPresent = !retention && await sourceHasBeliefEvents(tx, sourceId);
+ const epoch = retention ? 0 : await bumpPurgeEpoch(tx, sourceId);
+ const lifetimes = ledgerPresent ? await pageLifetimesOf(tx, sourceId, slug, page.id) : [];
+ const inventory = ledgerPresent ? await lookup('ledger_redaction', () => pagePurgeClaims(tx, { sourceId, slug, pageId: page.id, lifetimes })) : { claims: [], fps: [] };
+ const mirrorFacts = retention ? [] : await tx.executeRaw<{ fact_hash: string; visibility: string; subject: string }>(`SELECT DISTINCT gbrain_fact_fingerprint(fact) AS fact_hash,
+ visibility, COALESCE(entity_slug,'*') AS subject FROM facts WHERE source_id=$1 AND source_markdown_slug=$2`, [sourceId, slug]);
+ const mirrorTakes = retention ? [] : (await tx.executeRaw<{ claim_hash: string }>('SELECT DISTINCT gbrain_fact_fingerprint(claim) AS claim_hash FROM takes WHERE page_id=$1', [page.id])).map(t => t.claim_hash);
+ const hashes = new Set<string>();
+ if (!retention) await tombstonePage(tx, sourceId, slug, page.id, snapshot, row.id, actor, storedHash, hashes);
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 derivedRows = derivedFrom.rows.filter(r => !purgedHere.has(`${r.table}:${r.id}`));
+ const targets = ledgerPresent ? await lookup('ledger_redaction', () => derivedBeliefTargets(tx, sourceId, derivedRows)) : [];
+ const heldTargets = targets.filter(t => { try { assertHeldPageKeys(tx, [{ sourceId, slug: t.slug }]); return true; } catch { return false; } });
+ const walk = derivedFrom.truncated || heldTargets.length < targets.length ? 'truncated' as const : 'complete' as const;
+ if (!retention) noteBelief({ kind: 'purged', table: 'pages', ids: [page.id], request: row.id, ...(walk === 'truncated' ? { derivedWalk: walk } : {}) });
+ const derived = await hideDerivedRows(tx, derivedRows, { 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> = {
@@ -170,7 +207,6 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
removed.page_aliases = await count('DELETE FROM page_aliases WHERE source_id=$1 AND slug=$2 RETURNING 1', [sourceId, slug]);
removed.slug_aliases = await count('DELETE FROM slug_aliases WHERE source_id=$1 AND canonical_slug=$2 RETURNING 1', [sourceId, slug]);
// #6511 [R2]: the preparation sweep's targets, plus the tail past its ceiling and the rows pending at scan time, re-tested here.
- const lookup = <T>(point: PurgeLookupPoint, fn: () => Promise<T>) => journalLookup(row, point, prepared.slugIndex, fn);
const recheck = await lookup('tail_recheck', () => recheckRequestsCarrying(tx, sourceId, needles, prepared.sweep,
{ exclude: row.id, beforePending: () => faultPoint('purge:pending_recheck', { requestId: row.request_id, sourceId, operation: row.operation }) }));
const forSlug = await lookup('slug_lookup', () => findRequestsForSlugs(tx, sourceId, [slug]));
@@ -185,14 +221,25 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
(SELECT count(*)::int FROM content_chunks WHERE page_id=$1) AS chunks, (SELECT count(*)::int FROM page_versions WHERE page_id=$1) AS versions,
(SELECT count(*)::int FROM takes WHERE page_id=$1) AS takes, (SELECT count(*)::int FROM timeline_entries WHERE page_id=$1) AS timeline`, [page.id]);
Object.assign(removed, { content_chunks: cascade?.chunks ?? 0, page_versions: cascade?.versions ?? 0, takes: cascade?.takes ?? 0, timeline_entries: cascade?.timeline ?? 0, pages: 1 });
- const paths = [...new Set([page.source_path, ...versions.map(v => v.source_path as string | null)].filter((p): p is string => !!p))].slice(0, 64);
+ const versions = await tx.executeRaw<{ source_path: string | null }>('SELECT DISTINCT source_path FROM page_versions WHERE page_id=$1 AND source_path IS NOT NULL LIMIT 64', [page.id]);
+ const paths = [...new Set([page.source_path, ...versions.map(v => v.source_path)].filter((p): p is string => !!p))].slice(0, 64);
+ const ledger: LedgerPurgeReport | null = ledgerPresent ? await lookup('ledger_redaction', async () => ({
+ purged_events: await redactPurgedKeys(tx, { sourceId, claimFps: inventory.fps, lifetimes }),
+ redacted_fields: await redactCarryingFields(tx, { sourceId, request: row.id, claims: inventory.claims }),
+ live_carriers: await registerLiveCarriers(tx, { sourceId, request: row.id, claims: inventory.claims }),
+ derived_hidden: await appendDerivedHidden(tx, { sourceId, request: row.id, publicationId: row.id, op: 'delete_page', targets: heldTargets, truncated: walk === 'truncated' }),
+ derived_walk: walk })) : null;
+ if (ledger) removed.belief_events = ledger.purged_events + ledger.redacted_fields.length;
await tx.deletePage(slug, { sourceId });
+ if (!retention) appendPurgeMirror({ kind: 'intent', request: row.id, request_id: row.request_id, source_id: sourceId, source_incarnation: row.source_incarnation,
+ scope: 'page', slug, purge_epoch: epoch, content_hashes: [...hashes], facts: mirrorFacts, takes: mirrorTakes, lifetimes });
const key = `${sourceId}:${row.request_id}`;
purgeContext.delete(key);
- purgeContext.set(key, { needles, factIds, pageId: page.id, paths });
+ purgeContext.set(key, { needles, factIds, pageId: page.id, paths, ledgerClaims: inventory.claims, ledger });
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,
+ return { status: 'purged', slug, source_id: sourceId, residuals: PURGE_RESIDUALS, journal_sweep: journalSweep, ...(retention ? { retention: true } : {}),
+ purge: { content_hash8: storedHash?.slice(0, 8) ?? null, tombstoned: hashes.size > 0, content_hashes_tombstoned: hashes.size, removed, ...(retention ? {} : { mirror_request: row.id }),
+ ...(ledger ? { ledger: { purged_events: ledger.purged_events, redacted_fields: ledger.redacted_fields.length, live_carriers: ledger.live_carriers.length, derived_hidden: ledger.derived_hidden, derived_walk: ledger.derived_walk } } : {}),
derived: { ...derived, truncated: derivedFrom.truncated },
blobs: files.map(f => f.storage_path).filter(Boolean) } };
}
@@ -207,7 +254,8 @@ export async function finishPagePurge(ctx: Pick<OperationContext, 'engine' | 'co
// A same-id replay in this process returns what the purge call returned (blobs and verification are not re-run).
const finished = purgeReceipts.get(key);
if (finished) return { ...result, ...finished };
- const purge = (result.purge ?? {}) as { blobs?: string[]; removed?: Record<string, number> };
+ const purge = (result.purge ?? {}) as { blobs?: string[]; removed?: Record<string, number>; mirror_request?: string };
+ if (purge.mirror_request) appendPurgeMirror({ kind: 'committed', request: purge.mirror_request });
const remaining: string[] = [];
if (purge.blobs?.length) {
try {
diff --git a/src/core/persistence/purge-deleted.ts b/src/core/persistence/purge-deleted.ts
index 37f898e926..fc3452e614 100644
--- a/src/core/persistence/purge-deleted.ts
+++ b/src/core/persistence/purge-deleted.ts
@@ -5,6 +5,8 @@ import type { OperationContext } from '../ops/contract.ts';
import { requireConsent, type ConsentRequest } from '../consent.ts';
import { managedPersistenceEnabled } from './ownership.ts';
import { submitPageMutation } from './page-mutations.ts';
+import { withBeliefBatch } from '../belief/ledger.ts';
+import { markBeliefCommits } from '../belief/append.ts';
/** A tombstone that moved under a concurrent writer; the next run retries it. */
const DEFERRAL_CODES = new Set(['revision_conflict', 'page_not_found', 'page_identity_changed']);
@@ -51,6 +53,32 @@ export async function consentedPurgeDeletedPages(engine: BrainEngine, olderThanH
return { status: result.failed ? 'partial' : 'purged', count: result.count, slugs: result.slugs, ...(result.blocked.length ? { blocked: result.blocked } : {}) };
}
+/**
+ * W1 (BELIEF_LEDGER.md 6.5): on an unmanaged brain, each expired tombstone of a source the belief ledger records is
+ * removed under its page key inside a belief batch, which appends `page.expired` (retention, never a purge: no
+ * tombstone, nothing redacted). The bulk delete then takes the rest.
+ */
+async function expireRecordedTombstones(engine: BrainEngine, olderThanHours: number): Promise<string[]> {
+ const hours = String(Math.max(0, Math.floor(olderThanHours)));
+ const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string }>(`SELECT p.id, p.source_id, p.slug FROM pages p
+ WHERE p.deleted_at IS NOT NULL AND p.deleted_at < now() - ($1 || ' hours')::interval
+ AND EXISTS (SELECT 1 FROM belief_events e WHERE e.source_id = p.source_id AND e.subject_kind = 'coverage')
+ ORDER BY p.deleted_at ASC, p.source_id ASC, p.slug ASC`, [hours]);
+ const slugs: string[] = [];
+ for (const row of rows) {
+ const publicationId = randomUUID(), report = { appended: 0 };
+ const deleted = await engine.transaction(async tx => {
+ await tx.lockPageKeys([{ sourceId: row.source_id, slug: row.slug }]);
+ return withBeliefBatch(tx, { sourceId: row.source_id, slugs: [row.slug], publicationId, op: 'purge_deleted_pages', hardDeleteEvent: 'page.expired', report },
+ async () => (await tx.executeRaw(`DELETE FROM pages WHERE id = $1 AND deleted_at IS NOT NULL AND deleted_at < now() - ($2 || ' hours')::interval RETURNING id`,
+ [row.id, hours])).length > 0);
+ });
+ if (report.appended) await markBeliefCommits(engine, [publicationId]).catch(() => undefined);
+ if (deleted) slugs.push(row.slug);
+ }
+ return slugs;
+}
+
/**
* #5405: hard-delete tombstones older than the recovery window. An unmanaged
* brain keeps the engine's bulk delete. A managed brain refuses that bulk
@@ -61,8 +89,9 @@ export async function consentedPurgeDeletedPages(engine: BrainEngine, olderThanH
*/
export async function purgeDeletedPagesCoordinated(engine: BrainEngine, olderThanHours: number): Promise<DeletedPagePurge> {
if (!await managedPersistenceEnabled(engine)) {
+ const recorded = await expireRecordedTombstones(engine, olderThanHours);
const result = await engine.purgeDeletedPages(olderThanHours);
- return { slugs: result.slugs, count: result.count, blocked: [], deferred: 0, failed: 0 };
+ return { slugs: [...recorded, ...result.slugs], count: recorded.length + result.count, blocked: [], deferred: 0, failed: 0 };
}
const hours = Math.max(0, Math.floor(olderThanHours));
const rows = await engine.executeRaw<{ source_id: string; slug: string; cutoff: string }>(
@@ -82,7 +111,7 @@ export async function purgeDeletedPagesCoordinated(engine: BrainEngine, olderTha
const ctx: OperationContext = { engine, config, remote: false, sourceId: row.source_id, dryRun: false,
logger: { info() {}, warn() {}, error() {} } };
await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: row.slug, source_id: row.source_id,
- purge: true, expected_revision: snapshot.revision, request_id: randomUUID() } });
+ purge: true, retention: true, expected_revision: snapshot.revision, request_id: randomUUID() } });
slugs.push(row.slug);
} catch (error) {
const code = typeof (error as { code?: unknown })?.code === 'string' ? (error as { code: string }).code : null;
diff --git a/src/core/persistence/purge-params.ts b/src/core/persistence/purge-params.ts
index ad2d675e55..068735df5c 100644
--- a/src/core/persistence/purge-params.ts
+++ b/src/core/persistence/purge-params.ts
@@ -9,6 +9,9 @@ export function assertPurgeParams(params: Record<string, unknown>, remote: boole
if (params.purge !== undefined && typeof params.purge !== 'boolean') {
throw opError('invalid_params', 'purge must be a boolean.', `Pass purge: true (CLI: gbrain delete ${slug ?? '<slug>'} --purge).`);
}
+ if (params.retention !== undefined && (params.retention !== true || params.purge !== true || remote !== false)) {
+ throw opError('invalid_params', 'retention is internal to the trusted local retention purge.', 'Omit retention; gbrain pages purge-deleted sets it.');
+ }
if (params.purge === true && remote !== false) {
throw opError('permission_denied', 'purge is only available to the local CLI.',
`Remote callers soft-delete only (omit purge; restore_page can undo it for 72h). To remove the page immediately the user runs \`gbrain delete ${slug ?? '<slug>'} --purge\` on the brain host.`,
diff --git a/src/core/trust/confirm.ts b/src/core/trust/confirm.ts
index 8107ec4e78..71bcfcd627 100644
--- a/src/core/trust/confirm.ts
+++ b/src/core/trust/confirm.ts
@@ -17,6 +17,9 @@ import { isInteractive, readLine, type InteractiveProbe } from '../interaction.t
import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
import { databaseRefusal } from '../persistence/publication-failure.ts';
import { hasScope } from '../scope.ts';
+import type { BrainEngine } from '../engine.ts';
+import { randomUUID } from 'node:crypto';
+import { releaseSuppressedFields, suppressedFields } from '../belief/purge.ts';
export const MEMORY_CONFIRM_SCOPE = 'memory_confirm';
@@ -89,6 +92,19 @@ export async function requireOwnerConfirmation(ctx: OperationContext, target: Co
{ why: 'Raising trust is the owner\'s decision, so it needs a person at a terminal typing the confirmation token; piped input, agents and --yes cannot confirm.', fix });
}
+/**
+ * BELIEF_LEDGER.md 6.5: a carrying field a purge redacted (a fact's context, a take's resolution evidence) stays
+ * redacted in recorded history until the owner releases it. Confirming the row is that release, bound to the field's
+ * current value, so it needs the same owner confirmation as a raise. `pendingRedactionRelease` says whether a confirm
+ * has one to make; `releaseConfirmedRedactions` makes it after the owner confirmed.
+ */
+export async function pendingRedactionRelease(engine: BrainEngine, table: 'facts' | 'takes', id: number): Promise<string[]> {
+ return suppressedFields(engine, table, id);
+}
+export async function releaseConfirmedRedactions(engine: BrainEngine, table: 'facts' | 'takes', id: number): Promise<string[]> {
+ return releaseSuppressedFields(engine, table, id, randomUUID());
+}
+
/**
* The tier trigger's database refusal (trust/schema.ts) as the registered
* `trust_raise_refused` error, for direct writers outside the coordinator
diff --git a/src/core/trust/owner-actions.ts b/src/core/trust/owner-actions.ts
index c83cf95532..6e4e03a0c0 100644
--- a/src/core/trust/owner-actions.ts
+++ b/src/core/trust/owner-actions.ts
@@ -24,7 +24,7 @@ import type { OperationContext } from '../ops/contract.ts';
import { opError } from '../ops/contract.ts';
import type { Principal } from '../persistence/model.ts';
import type { OwnerConfirmation } from './confirm.ts';
-import { tierRaiseFix } from './confirm.ts';
+import { pendingRedactionRelease, releaseConfirmedRedactions, tierRaiseFix } from './confirm.ts';
import { decideTrustProposal } from './decide.ts';
import { resolveContestedFactOnConfirm } from './supersede-handlers.ts';
import { getTrustProposal, pendingTrustProposalsFor, trustProposalRef, type TrustDecisionResult, type TrustProposalRow } from './proposals.ts';
@@ -278,8 +278,10 @@ async function previewConfirm(engine: BrainEngine, ref: TrustRef, input: OwnerAc
const row = ref.kind === 'fact' ? await readFactTarget(engine, ref.id) : await readTakeTarget(engine, ref.id);
if (!row) throw notFound(label, ref.kind);
if (!row.live) throw opError('invalid_params', `${label} is no longer active (expired, superseded or forgotten); there is nothing to confirm.`, 'Confirm the row that replaced it instead; gbrain trust explain shows its history.');
- return { action: 'confirm', ref: label, token: label, command: trustCommand('confirm', label), raises: row.tier !== 'user_confirmed', binding: row.binding,
- tier: row.tier, target_tier: 'user_confirmed', summary: `Raise ${ref.kind} ${label} ("${snippet(row.text)}") from "${trustLabel(row.tier)}" to "confirmed by you"` };
+ const release = await pendingRedactionRelease(engine, row.table, row.id);
+ return { action: 'confirm', ref: label, token: label, command: trustCommand('confirm', label), raises: row.tier !== 'user_confirmed' || release.length > 0, binding: row.binding,
+ tier: row.tier, target_tier: 'user_confirmed', summary: `Raise ${ref.kind} ${label} ("${snippet(row.text)}") from "${trustLabel(row.tier)}" to "confirmed by you"`
+ + (release.length ? ` and release its purge-redacted ${release.join(', ')} in recorded history` : '') };
}
if (ref.kind === 'page') {
const { sourceId, slug } = await resolvePageRef(engine, ref, input.source);
@@ -441,11 +443,12 @@ export async function applyOwnerAction(engine: BrainEngine, input: OwnerActionIn
const resolved = ref.kind === 'fact' && row.binding === opts.binding ? await resolveContestedFactOnConfirm(engine, ref.id, decision) : null;
if (resolved?.status === 'accepted') return { action: input.action, ref: preview.ref, status: 'confirmed', tier: 'user_confirmed', prior_tier: row.tier, detail: { resolved_proposal: resolved.ref } };
if (!preview.raises) return { action: input.action, ref: preview.ref, status: 'unchanged', tier: 'user_confirmed', prior_tier: 'user_confirmed' };
- const ok = await setRowTier(engine, { table: row.table, id: row.id, sourceId: row.sourceId, tier: 'user_confirmed', ceiling: 'user_confirmed', by,
+ const ok = row.tier === 'user_confirmed' || await setRowTier(engine, { table: row.table, id: row.id, sourceId: row.sourceId, tier: 'user_confirmed', ceiling: 'user_confirmed', by,
note: { via: confirmation.via, action: 'confirm', by: principalLabel(by) },
expect: async tx => (await read(tx, ref.id))?.binding === opts.binding });
if (!ok) throw opError('preview_changed', `${preview.ref} changed after you approved it; nothing was changed.`, 'Run the command again.');
- return { action: input.action, ref: preview.ref, status: 'confirmed', tier: 'user_confirmed', prior_tier: row.tier };
+ const released = await releaseConfirmedRedactions(engine, row.table, row.id);
+ return { action: input.action, ref: preview.ref, status: 'confirmed', tier: 'user_confirmed', prior_tier: row.tier, ...(released.length ? { detail: { released_redactions: released } } : {}) };
}
if (ref?.kind === 'page') {
const { sourceId, slug } = await resolvePageRef(engine, ref, input.source);
diff --git a/test/belief-ledger-purge.test.ts b/test/belief-ledger-purge.test.ts
new file mode 100644
index 0000000000..6dfaeba05e
--- /dev/null
+++ b/test/belief-ledger-purge.test.ts
@@ -0,0 +1,302 @@
+/**
+ * Belief ledger purge probes (docs/designs/BELIEF_LEDGER.md section 11: 10,
+ * 22, 27, 30, 31, 35, 36 (live half), 37, 38). Each asserts exact event keys,
+ * types and values and the reconstructed history on PGLite and on Postgres
+ * when DATABASE_URL is set, and each has a forced probe: a deliberately broken
+ * emitter or redaction pass that must make the same assertion fail.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { __setBeliefEmitterFaultForTests, appendBeliefEvents, type BeliefEventDraft } from '../src/core/belief/append.ts';
+import { __setPurgeRedactionFaultForTests, type PurgeRedactionFault } from '../src/core/belief/purge.ts';
+import { readBeliefHistory } from '../src/core/belief/history.ts';
+import { withBeliefBatch } from '../src/core/belief/ledger.ts';
+import { REDACTION_MARKER, fieldHash } from '../src/core/belief/keys.ts';
+import { __setNamedRowProbesForTests } from '../src/core/facts/purge-verify.ts';
+import { recordDerivationInputs } from '../src/core/facts/derivation-inputs.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { purgeDeletedPagesCoordinated } from '../src/core/persistence/purge-deleted.ts';
+import { applyOwnerAction, previewOwnerAction } from '../src/core/trust/owner-actions.ts';
+import { configDir } from '../src/core/config.ts';
+import { operations } from '../src/core/operations.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { beliefBrain, beliefEngineCase, beliefPage, shape, type BeliefBrain, type BeliefEvent } from './helpers/belief-ledger.ts';
+
+afterEach(() => { __setBeliefEmitterFaultForTests(null); __setPurgeRedactionFaultForTests(null); __setNamedRowProbesForTests(true); });
+
+const X = 'Door code is 4417';
+const purgeOp = operations.find(o => o.name === 'purge_fact')!;
+const deleteOp = operations.find(o => o.name === 'delete_page')!;
+const marker = (request: string) => REDACTION_MARKER(request);
+
+async function fp(b: BeliefBrain, claim: string): Promise<string> {
+ return (await b.engine.executeRaw<{ fp: string }>('SELECT gbrain_fact_fingerprint($1) AS fp', [claim]))[0]!.fp;
+}
+
+async function purgeFact(b: BeliefBrain, claim: string): Promise<Record<string, any>> {
+ const [row] = await b.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id = $1 AND fact = $2 AND expired_at IS NULL ORDER BY id LIMIT 1', [b.sourceId, claim]);
+ const dry = await purgeOp.handler(b.ctx, { id: Number(row!.id), dry_run: true }) as Record<string, any>;
+ return await purgeOp.handler(b.ctx, { id: Number(row!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() }) as Record<string, any>;
+}
+
+async function purgePage(b: BeliefBrain, slug: string): Promise<Record<string, any>> {
+ const snapshot = await b.engine.readPageSnapshot(slug, { sourceId: b.sourceId, includeDeleted: true });
+ return await deleteOp.handler(b.ctx, { slug, purge: true, expected_revision: snapshot!.revision, request_id: randomUUID() }) as Record<string, any>;
+}
+
+/** The purge's internal request id (the `purge_request` its events and markers name). */
+async function purgeRequest(b: BeliefBrain, clientRequestId: string): Promise<string> {
+ return (await b.engine.executeRaw<{ id: string }>('SELECT id::text AS id FROM persistence_requests WHERE request_id = $1::uuid', [clientRequestId]))[0]!.id;
+}
+
+const history = (b: BeliefBrain, q: { slug?: string; subjectKey?: string } = {}) => readBeliefHistory(b.engine, { sourceId: b.sourceId, remote: false, ...q });
+
+/** Runs `scenario` once for real and once under `fault`; the real run must pass `check` and the faulty one must fail it. */
+async function forced<T>(scenario: () => Promise<T>, check: (value: T) => void, fault: () => void): Promise<void> {
+ check(await scenario());
+ fault();
+ try {
+ const value = await scenario();
+ let failed = false;
+ try { check(value); } catch { failed = true; }
+ expect(failed).toBe(true);
+ } finally { __setBeliefEmitterFaultForTests(null); __setPurgeRedactionFaultForTests(null); __setNamedRowProbesForTests(true); }
+}
+const redactionFault = (fault: PurgeRedactionFault) => () => __setPurgeRedactionFaultForTests(fault);
+
+for (const engineCase of testBackends().map(beliefEngineCase)) {
+ describe(`belief ledger purge (${engineCase.name})`, () => {
+ const brain = (run: (b: BeliefBrain) => Promise<void>, managed = true) => beliefBrain(run, { managed, databaseUrl: engineCase.databaseUrl });
+
+ test('probe 10: purge redacts the key\'s whole history to skeletons and appends one fact.purged; nothing re-asserts it', async () => {
+ const scenario = () => new Promise<Record<string, unknown>>((resolve, reject) => brain(async b => {
+ const slug = `companies/acme-${randomUUID().slice(0, 6)}`;
+ const stale = beliefPage({ facts: [X, 'Acme sells widgets'] });
+ await b.put(slug, stale);
+ await b.put(slug, beliefPage({ facts: [{ claim: X, confidence: '0.5' }, 'Acme sells widgets'] }));
+ const revised = (await b.events()).find(e => e.event_type === 'fact.revised')!;
+ const mark = await b.lastId();
+ const result = await purgeFact(b, X);
+ const request = await purgeRequest(b, String(result.request_id));
+ const after = await b.events(mark);
+ const keyHistory = await history(b, { subjectKey: revised.subject_key });
+ const beforeInsert = await b.lastId();
+ const insert = await b.engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source_markdown_slug) VALUES ($1, $2, $3, 'fact', 'world', $2)`,
+ [b.sourceId, slug, X]).then(() => 'inserted', (e: Error) => e.message.includes('purged') || e.message.includes('writer_coordinator_required') ? 'refused' : e.message);
+ const afterInsert = await b.lastId();
+ await b.put(slug, stale);
+ const reimport = (await b.events(afterInsert)).filter(e => e.claim_fp === revised.claim_fp && /asserted|revised|adopted/.test(e.event_type));
+ const prepared: BeliefEventDraft = { sourceId: b.sourceId, incarnation: revised.source_incarnation, lifetime: revised.page_lifetime, slug, stream: slug,
+ subjectKind: 'fact', subjectKey: revised.subject_key, eventType: 'fact.asserted', trustTier: 'unknown', tierBasis: 'unknown', visibility: 'world',
+ value: { fact: X, context: null }, stateHash: '', claimFp: revised.claim_fp, cause: { op: 'backfill' } };
+ const backfillId = randomUUID();
+ await b.engine.transaction(tx => appendBeliefEvents(tx, [prepared], { publicationId: backfillId, origin: 'backfill' }));
+ const backfilled = (await b.events(afterInsert)).filter(e => e.publication_id === backfillId);
+ const [epoch] = await b.engine.executeRaw<{ e: number }>('SELECT purge_epoch AS e FROM sources WHERE id = $1', [b.sourceId]);
+ await b.put(`notes/other-${randomUUID().slice(0, 6)}`, beliefPage({ facts: ['Acme has a second claim'] }));
+ await purgeFact(b, 'Acme has a second claim');
+ const stalePrepared = await b.engine.transaction(tx => appendBeliefEvents(tx, [{ ...prepared, subjectKey: `${prepared.subjectKey}#stale` }],
+ { publicationId: randomUUID(), origin: 'backfill', preparedEpoch: Number(epoch!.e) })).then(() => 'appended', (e: { code?: string }) => e.code ?? 'error');
+ resolve({ request, after, revised, keyHistory, insert, inserted: afterInsert - beforeInsert, reimport, backfilled, stalePrepared, fp: await fp(b, X) });
+ }).catch(reject));
+ await forced(scenario, (r: any) => {
+ expect(shape(r.after)).toEqual(['page:page.published', 'fact:fact.purged']);
+ const purged = r.after[1] as BeliefEvent;
+ expect(purged).toMatchObject({ subject_key: r.revised.subject_key, value: null, value_hash: null, purged: true, claim_fp: r.fp });
+ expect(purged.cause).toMatchObject({ op: 'purge_fact', purge_request: r.request });
+ expect(r.keyHistory.map((e: BeliefEvent) => [e.event_type, e.value, e.value_hash, e.purged])).toEqual([
+ ['fact.revised', null, null, true], ['fact.purged', null, null, true]]);
+ expect(r.insert).toBe('refused');
+ expect(r.inserted).toBe(0);
+ expect(r.reimport).toEqual([]);
+ expect(r.backfilled.map((e: BeliefEvent) => [e.event_type, e.value, e.purged])).toEqual([['fact.asserted', null, true]]);
+ expect(r.stalePrepared).toBe('belief_stale_preparation');
+ }, redactionFault('skip_purged_keys'));
+ await forced(scenario, (r: any) => expect(shape(r.after)).toEqual(['page:page.published', 'fact:fact.purged']),
+ () => __setBeliefEmitterFaultForTests(drafts => drafts.map(d => d.eventType === 'fact.purged' ? { ...d, eventType: 'fact.retracted' } : d)));
+ }, 240_000);
+
+ test('probe 22: a claim quoted only in another fact\'s context, a take\'s resolution evidence or a link\'s context is redacted', async () => {
+ const scenario = () => new Promise<Record<string, unknown>>((resolve, reject) => brain(async b => {
+ await b.put('people/alice-example', beliefPage({ type: 'person', title: 'Alice Example' }));
+ await b.put('companies/acme-example', beliefPage({ facts: ['Acme sells widgets'], takes: ['Acme will win its market'] }));
+ await b.put('companies/acme-example', beliefPage({ facts: [{ claim: 'Acme sells widgets', context: `notes say ${X}` }], takes: ['Acme will win its market'],
+ prose: `The lobby sign says ${X}.`, links: ['people/alice-example'] }));
+ await b.op('takes_resolve', { slug: 'companies/acme-example', row_num: 1, quality: 'correct', evidence: `confirmed: ${X}` });
+ await b.put('vault/codes-example', beliefPage({ facts: [X] }));
+ const result = await purgeFact(b, X);
+ const request = await purgeRequest(b, String(result.request_id));
+ const carriers = (await b.events()).filter(e => e.redacted_fields?.length);
+ const leaks = (await b.events()).filter(e => JSON.stringify(e.value ?? {}).toLowerCase().includes(X.toLowerCase()));
+ const register = await b.engine.executeRaw<{ field: string; purge_request: string }>(`SELECT DISTINCT field, purge_request::text AS purge_request
+ FROM belief_redactions WHERE source_id = $1 ORDER BY field`, [b.sourceId]);
+ resolve({ request, carriers, leaks, register });
+ }).catch(reject));
+ await forced(scenario, (r: any) => {
+ const byKind = Object.fromEntries((r.carriers as BeliefEvent[]).map(e => [`${e.subject_kind}:${e.event_type}`, e]));
+ expect(Object.keys(byKind).sort()).toEqual(['fact:fact.revised', 'link:link.asserted', 'take:take.resolved']);
+ expect(byKind['fact:fact.revised']!.value!.context).toBe(marker(r.request));
+ expect(byKind['fact:fact.revised']!.redacted_fields).toEqual(['context']);
+ expect(byKind['take:take.resolved']!.value!.resolved_source).toBe(marker(r.request));
+ expect(byKind['take:take.resolved']!.redacted_fields).toEqual(['resolved_source']);
+ expect(byKind['link:link.asserted']!.value!.context).toBe(marker(r.request));
+ expect(byKind['link:link.asserted']!.redacted_fields).toEqual(['context']);
+ expect(r.leaks).toEqual([]);
+ expect(r.register).toEqual([{ field: 'context', purge_request: r.request }, { field: 'resolved_source', purge_request: r.request }]);
+ }, redactionFault('skip_carrying_fields'));
+ }, 240_000);
+
+ test('probe 37: a context that quotes a purged claim stays the marker until an owner replaces it, and again after an agent change', async () => {
+ const page = (context: string, confidence = '1.0') => beliefPage({ facts: [X, { claim: 'Acme sells widgets', context, confidence }] });
+ const scenario = () => new Promise<Record<string, unknown>>((resolve, reject) => brain(async b => {
+ const slug = 'companies/acme-example';
+ await b.put(slug, page(`notes say ${X}`));
+ const result = await purgeFact(b, X);
+ const request = await purgeRequest(b, String(result.request_id));
+ const receiptKeys = (result.stores as Array<{ store: string; items?: string[] }>).find(s => s.store === 'fact_context')?.items ?? [];
+ const step = async (fn: () => Promise<unknown>) => { const mark = await b.lastId(); await fn(); return (await b.events(mark)).filter(e => e.event_type.startsWith('fact.')); };
+ const confidence = await step(() => b.put(slug, page(`notes say ${X}`, '0.5')));
+ const agentEdit = await step(() => b.put(slug, page(`notes say ${X} and more`, '0.5')));
+ const owner = await step(() => b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], async () => {
+ await tx.lockPageKeys([{ sourceId: b.sourceId, slug }]);
+ await withBeliefBatch(tx, { sourceId: b.sourceId, slugs: [slug], op: 'owner_edit', remote: false },
+ () => tx.executeRaw(`UPDATE facts SET context = 'owner rewrote this' WHERE source_id = $1 AND fact = 'Acme sells widgets' AND expired_at IS NULL`, [b.sourceId]));
+ }, { ...TEST_WRITE_ATTRIBUTION, trust: { tier: 'operator_curated', origin: { channel: 'cli:owner_edit' } } })));
+ const later = await step(() => b.put(slug, page('agent rewrote this', '0.5')));
+ const [fact] = await b.engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE source_id = $1 AND fact = 'Acme sells widgets' AND expired_at IS NULL`, [b.sourceId]);
+ const preview = await previewOwnerAction(b.engine, { action: 'confirm', ref: `f${fact!.id}` });
+ await applyOwnerAction(b.engine, { action: 'confirm', ref: `f${fact!.id}` }, { binding: preview.binding, confirmation: { via: 'tty' } });
+ const confirmed = await step(() => b.put(slug, page('agent rewrote this', '0.25')));
+ resolve({ request, receiptKeys, confidence, agentEdit, owner, later, confirmed, raises: preview.raises });
+ }).catch(reject));
+ await forced(scenario, (r: any) => {
+ const ctx = (events: BeliefEvent[]) => events.map(e => [e.event_type, e.value?.context, e.redacted_fields]);
+ expect(r.receiptKeys.length).toBe(2);
+ expect(ctx(r.confidence)).toEqual([['fact.revised', marker(r.request), ['context']]]);
+ expect(ctx(r.agentEdit)).toEqual([['fact.revised', marker(r.request), ['context']]]);
+ expect(ctx(r.owner)).toEqual([['fact.revised', 'owner rewrote this', null]]);
+ expect(ctx(r.later)).toEqual([['fact.revised', marker(r.request), ['context']]]);
+ expect(r.raises).toBe(true);
+ expect(ctx(r.confirmed)).toEqual([['fact.revised', 'agent rewrote this', null]]);
+ expect(r.receiptKeys).toContain(r.confidence[0].subject_key);
+ }, redactionFault('skip_live_carriers'));
+ }, 240_000);
+
+ test('probe 38: the suppression follows replacement, adoption, transfer and a verbatim copy into an unlinked fact', async () => {
+ const scenario = () => new Promise<Record<string, unknown>>((resolve, reject) => brain(async b => {
+ const slug = 'companies/acme-example', quote = `notes say ${X}`;
+ await b.put(slug, beliefPage({ facts: [{ claim: 'Acme sells widgets', context: quote }, X] }));
+ await b.engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, context, source) VALUES ($1, 'people/bob-example', 'Bob runs ops', 'fact', 'world', $2, 'test')`,
+ [b.sourceId, quote]);
+ const result = await purgeFact(b, X);
+ const request = await purgeRequest(b, String(result.request_id));
+ let mark = await b.lastId();
+ await b.put(slug, beliefPage({ facts: [{ claim: 'Acme sells gadgets', context: quote }] }));
+ const replaced = (await b.events(mark)).filter(e => e.subject_kind === 'fact');
+ mark = await b.lastId();
+ await b.put('people/bob-example', beliefPage({ type: 'person', title: 'Bob Example' }));
+ const adopted = (await b.events(mark)).filter(e => e.event_type === 'fact.adopted');
+ const source = replaced.find(e => e.event_type === 'fact.asserted')!;
+ const transferId = randomUUID();
+ await b.engine.transaction(tx => appendBeliefEvents(tx, [{ sourceId: b.sourceId, incarnation: source.source_incarnation, lifetime: null, slug: 'companies/merged-example',
+ subjectKind: 'fact', subjectKey: '["f","S:transfer","x"]', eventType: 'fact.transferred', trustTier: 'agent_written', visibility: 'world',
+ value: { fact: 'Acme sells gadgets', context: quote }, stateHash: '', cause: { op: 'merge', from_key: source.subject_key } }], { publicationId: transferId, origin: 'live' }));
+ const transferred = (await b.events(mark)).filter(e => e.publication_id === transferId);
+ mark = await b.lastId();
+ await b.put('notes/copy-example', beliefPage({ facts: ['Gadget orders doubled'] }));
+ await b.put('notes/copy-example', beliefPage({ facts: [{ claim: 'Gadget orders doubled', context: quote }] }));
+ const copied = (await b.events(mark)).filter(e => e.subject_kind === 'fact');
+ resolve({ request, replaced, adopted, transferred, copied });
+ }, false).catch(reject));
+ await forced(scenario, (r: any) => {
+ const ctx = (events: BeliefEvent[]) => events.map(e => [e.event_type, e.value?.context ?? null, e.redacted_fields]);
+ expect(ctx(r.replaced)).toEqual([['fact.retracted', null, null], ['fact.asserted', marker(r.request), ['context']]]);
+ expect(r.replaced[1].cause.replaces).toBe(r.replaced[0].subject_key);
+ expect(ctx(r.adopted)).toEqual([['fact.adopted', marker(r.request), ['context']]]);
+ expect(ctx(r.transferred)).toEqual([['fact.transferred', marker(r.request), ['context']]]);
+ expect(ctx(r.copied)).toEqual([['fact.revised', marker(r.request), ['context']]]);
+ }, redactionFault('skip_live_carriers'));
+ }, 240_000);
+ test('probe 27: purge-verify names the link, timeline and raw-data rows that still carry the claim', async () => {
+ const scenario = () => new Promise<Record<string, unknown>>((resolve, reject) => brain(async b => {
+ await b.put('companies/acme-example', beliefPage({ facts: [X] }));
+ await b.put('people/alice-example', beliefPage({ type: 'person', title: 'Alice Example' }));
+ const ids = await b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], async () => {
+ const [from] = await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id = $1 AND slug = $2', [b.sourceId, 'people/alice-example']);
+ const [to] = await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id = $1 AND slug = $2', [b.sourceId, 'companies/acme-example']);
+ const [link] = await tx.executeRaw<{ id: number }>(`INSERT INTO links (from_page_id, to_page_id, link_type, context) VALUES ($1, $2, 'mentions', $3) RETURNING id`, [from!.id, to!.id, `said ${X}`]);
+ const [line] = await tx.executeRaw<{ id: number }>(`INSERT INTO timeline_entries (page_id, date, summary, detail) VALUES ($1, '2026-01-02', 'Visited', $2) RETURNING id`, [from!.id, `heard ${X}`]);
+ const [raw] = await tx.executeRaw<{ id: number }>(`INSERT INTO raw_data (page_id, source, data) VALUES ($1, 'crm', $2::jsonb) RETURNING id`, [from!.id, JSON.stringify({ note: X })]);
+ return { link: link!.id, line: line!.id, raw: raw!.id };
+ }, TEST_WRITE_ATTRIBUTION));
+ const result = await purgeFact(b, X);
+ const stores = Object.fromEntries((result.stores as Array<{ store: string; status: string; items?: string[] }>)
+ .filter(s => ['links', 'timeline_entries', 'raw_data'].includes(s.store)).map(s => [s.store, { status: s.status, items: s.items ?? null }]));
+ resolve({ ids, stores });
+ }).catch(reject));
+ await forced(scenario, (r: any) => expect(r.stores).toEqual({
+ links: { status: 'out_of_scope', items: [`link:${r.ids.link} people/alice-example -> companies/acme-example`] },
+ timeline_entries: { status: 'out_of_scope', items: [`timeline:${r.ids.line} people/alice-example 2026-01-02`] },
+ raw_data: { status: 'out_of_scope', items: [`raw_data:${r.ids.raw} people/alice-example crm`] },
+ }), () => __setNamedRowProbesForTests(false));
+ }, 240_000);
+
+ test('probe 30: a page purge redacts quotes of its 40th claim, a short claim and a claim left only in historical take events', async () => {
+ const many = Array.from({ length: 40 }, (_, i) => `Vault fact ${i + 1} is sealed`);
+ const short = 'Code Z9', gone = 'Vault will reopen in May';
+ const scenario = () => new Promise<Record<string, unknown>>((resolve, reject) => brain(async b => {
+ const slug = 'vault/codes-example';
+ await b.put(slug, beliefPage({ facts: [...many, short], takes: [gone] }));
+ await b.put(slug, beliefPage({ facts: [...many, short] }));
+ await b.put('notes/quotes-example', beliefPage({ facts: [
+ { claim: 'Quote one', context: `as noted, ${many[39]}` }, { claim: 'Quote two', context: `badge: ${short}` }, { claim: 'Quote three', context: `plan: ${gone}` }] }));
+ const result = await purgePage(b, slug);
+ const request = await purgeRequest(b, String(result.request_id));
+ const all = await b.events();
+ const quotes = all.filter(e => e.slug === 'notes/quotes-example' && e.subject_kind === 'fact').map(e => [e.value?.fact, e.value?.context, e.redacted_fields]);
+ const leaks = all.filter(e => [many[39]!, short, gone].some(c => JSON.stringify(e.value ?? {}).toLowerCase().includes(c.toLowerCase()))).map(e => e.id);
+ resolve({ request, quotes, leaks });
+ }).catch(reject));
+ await forced(scenario, (r: any) => {
+ expect(r.quotes).toEqual([['Quote one', marker(r.request), ['context']], ['Quote two', marker(r.request), ['context']], ['Quote three', marker(r.request), ['context']]]);
+ expect(r.leaks).toEqual([]);
+ }, redactionFault('bounded_inventory'));
+ }, 240_000);
+
+ test('probes 31 and 35: after purge, re-derivation and a backfill of the pre-purge derived page, history shows no pre-purge derived event', async () => {
+ const Y = 'Acme had a strong quarter';
+ const scenario = () => new Promise<Record<string, unknown>>((resolve, reject) => brain(async b => {
+ const derivedSlug = 'notes/summary-example';
+ await b.put('companies/acme-example', beliefPage({ facts: [X] }));
+ await b.put(derivedSlug, beliefPage({ facts: [Y] }));
+ const [x] = await b.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id = $1 AND fact = $2', [b.sourceId, X]);
+ const [y] = await b.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id = $1 AND fact = $2', [b.sourceId, Y]);
+ await b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId],
+ () => recordDerivationInputs(tx, { table: 'facts', id: y!.id, sourceId: b.sourceId }, [{ table: 'facts', id: x!.id }]), TEST_WRITE_ATTRIBUTION));
+ const before = (await b.events()).filter(e => e.slug === derivedSlug && e.subject_kind === 'fact');
+ const result = await purgeFact(b, X);
+ const request = await purgeRequest(b, String(result.request_id));
+ const hidden = (await b.events()).filter(e => e.event_type === 'derived.hidden');
+ const mark = await b.lastId();
+ await b.put(derivedSlug, beliefPage({ facts: [Y], prose: 'Re-derived.' }));
+ const rederived = (await b.events(mark)).filter(e => e.subject_kind === 'fact');
+ const key = before[0]!.subject_key;
+ const backfillId = randomUUID();
+ await b.engine.transaction(tx => appendBeliefEvents(tx, [{ sourceId: b.sourceId, incarnation: before[0]!.source_incarnation, lifetime: before[0]!.page_lifetime,
+ slug: derivedSlug, stream: derivedSlug, subjectKind: 'fact', subjectKey: key, eventType: 'fact.asserted', trustTier: 'unknown', tierBasis: 'unknown',
+ visibility: 'world', value: before[0]!.value, stateHash: '', claimFp: before[0]!.claim_fp, cause: { op: 'backfill' } }], { publicationId: backfillId, origin: 'backfill' }));
+ const read = (await history(b, { slug: derivedSlug })).filter(e => e.subject_kind === 'fact').map(e => [e.id, e.event_type, e.origin]);
+ resolve({ request, key, before: before.map(e => e.id), hidden, rederived: rederived.map(e => [e.id, e.event_type, e.subject_key]), read });
+ }).catch(reject));
+ await forced(scenario, (r: any) => {
+ expect(r.hidden.map((e: BeliefEvent) => [e.subject_key, e.value, e.cause.purge_request])).toEqual([[r.key, null, r.request]]);
+ expect(r.rederived.map((e: unknown[]) => e.slice(1))).toEqual([['fact.asserted', r.key]]);
+ expect(r.read).toEqual([[r.hidden[0].id, 'derived.hidden', 'live'], [r.rederived[0][0], 'fact.asserted', 'live']]);
+ for (const id of r.before) expect(r.read.map((e: unknown[]) => e[0])).not.toContain(id);
+ }, redactionFault('skip_derived_hidden'));
+ }, 240_000);
+ });
+}