Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(purge): receipts list every swept inventory store; page purge returns a store-by-store receipt and tombstones every saved version's hash
garrytan7dd0e03285a6
diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.tsindex dc73fd1ad7..08ba247b81 100644--- a/src/core/facts/purge-verify.ts+++ b/src/core/facts/purge-verify.ts@@ -71,25 +71,59 @@ async function boundedCount(engine: BrainEngine, sql: string, params: unknown[],}}-const textMatch = (column: string, json: boolean) => json- ? `(strpos(lower(${column}::text),$2)>0 OR strpos(lower(${column}::text),$3)>0)` : `strpos(lower(${column}::text),$2)>0`;+const textMatch = (column: string, at: number) => `(strpos(lower(${column}::text),$${at})>0 OR strpos(lower(${column}::text),$${at + 1})>0)`;+/** Vector and lexeme columns carry no probe-able text. */+const PROBE_SKIP = /embedding|search_vector/;-/** The generic adapter for a `probed_reported` inventory entry. */-async function probeInventoryStore(engine: BrainEngine, entry: InventoryEntry, sourceId: string, claim: string, deadline: number): Promise<StoreReport> {+/** Probe one inventory table for any of `needles` (exact, case-insensitive; JSON also in its escaped form). Scoped to the source when the table has one. */+async function probeTable(engine: BrainEngine, entry: InventoryEntry, sourceId: string, needles: readonly string[], deadline: number): Promise<ProbeResult> {+ const columns = (entry.probe ?? entry.columns).filter(col => !PROBE_SKIP.test(col));+ const list = needles.filter(Boolean).slice(0, 32);+ if (!columns.length || !list.length) return { count: 0 };const scoped = entry.columns.includes('source_id');+ // Bytes are matched exactly (case-sensitive) against the UTF-8 needle.const binary = entry.table === 'minion_attachments';- // Bytes are matched exactly (case-sensitive); text and JSON columns case-insensitively, JSON also in its escaped form.- const where = binary ? (entry.probe ?? []).map(col => `position(convert_to($2::text,'UTF8') in ${col})>0`).join(' OR ')- : (entry.probe ?? []).map(col => textMatch(col, true)).join(' OR ');- const result = await boundedCount(engine, `SELECT 1 FROM ${entry.table} WHERE ${scoped ? 'source_id=$1 AND' : '$1::text IS NOT NULL AND'} (${where})`,- binary ? [sourceId, claim] : [sourceId, claim.toLowerCase(), JSON.stringify(claim).slice(1, -1).toLowerCase()], deadline);+ const params: unknown[] = [sourceId];+ const ors: string[] = [];+ for (const needle of list) {+ if (binary) { params.push(needle); ors.push(...columns.map(col => `position(convert_to($${params.length}::text,'UTF8') in ${col})>0`)); continue; }+ params.push(needle.toLowerCase(), JSON.stringify(needle).slice(1, -1).toLowerCase());+ ors.push(...columns.map(col => textMatch(col, params.length - 1)));+ }+ 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);+}++/** 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> {+ 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? { store: entry.table, status: 'out_of_scope', reason: 'probed_reported', remaining: result.count,- detail: `${result.count} row(s) still mention the claim; purge does not rewrite this store${scoped ? '' : ' (probed brain-wide)'}.` }+ detail: `${result.count} row(s) still mention the purged text; purge does not rewrite this store${entry.columns.includes('source_id') ? '' : ' (probed brain-wide)'}.` }: { store: entry.table, status: 'not_present' };}+/**+ * CEO-22: every swept inventory store appears in a receipt. A swept store+ * without its own adapter is probed for the purged text: still present is+ * `incomplete`; absent is `deleted` when the sweep removed rows there, else+ * `not_present`.+ */+async function sweptInventoryReports(engine: BrainEngine, reported: ReadonlySet<string>, sourceId: string, needles: readonly string[],+ removed: StoreCount, deadline: number, dryRun: boolean): Promise<StoreReport[]> {+ const reports: StoreReport[] = [];+ for (const entry of DELETION_INVENTORY) {+ if (entry.class !== 'swept' || reported.has(entry.table)) continue;+ const planned = removed[entry.table] ?? 0;+ if (dryRun) { reports.push({ store: entry.table, status: planned ? 'would_remove' : 'not_present', removed: planned }); continue; }+ const result = await probeTable(engine, entry, sourceId, needles, deadline);+ if ('unverified' in result) reports.push({ store: entry.table, status: 'unverified', reason: result.unverified, removed: planned });+ else if (result.count) reports.push({ store: entry.table, status: 'incomplete', remaining: result.count, removed: planned });+ else reports.push({ store: entry.table, status: planned ? 'deleted' : 'not_present', removed: planned });+ }+ return reports;+}+/** Commits in the page files' history that add or remove the claim's fence cell. The pattern never enters argv. */export async function gitResidualCommits(root: string, paths: readonly string[], claim: string, limits = { bytes: PURGE_PROBE_LIMITS.gitBytes, ms: PURGE_PROBE_LIMITS.gitMs }):Promise<StoreReport> {@@ -200,13 +234,16 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purgawait swept('page_versions', `SELECT 1 FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1AND (strpos(lower(v.compiled_truth),$2)>0 OR strpos(lower(COALESCE(v.timeline,'')),$2)>0)`,[src, needle], plan.versions, removed.page_versions, { ...prose, items: (input.prose ?? []).slice(0, 20) });- await swept('persistence_requests', `SELECT 1 FROM persistence_requests WHERE source_id=$1 AND NOT compacted AND intent IS NOT NULL- AND (strpos(lower(intent::text),$2)>0 OR strpos(lower(intent::text),$3)>0)`,+ await swept('persistence_requests', `SELECT 1 FROM persistence_requests WHERE source_id=$1 AND (${['intent', 'outcome', 'error_detail', 'error_message']+ .map(c => `strpos(lower(COALESCE(${c}::text,'')),$2)>0 OR strpos(lower(COALESCE(${c}::text,'')),$3)>0`).join(' OR ')})`,[src, needle, JSON.stringify(claim).slice(1, -1).toLowerCase()], plan.requests.length, removed.persistence_requests);await swept('query_cache', 'SELECT 1 FROM query_cache WHERE $1::text IS NOT NULL', [src], 0, removed.query_cache);- await swept('decide_review', `SELECT 1 FROM decide_review_queue WHERE source_id=$1 AND (a_ref=ANY($2::text[]) OR b_ref=ANY($2::text[]))- UNION ALL SELECT 1 FROM decide_review_proposals WHERE source_id=$1 AND (a_ref=ANY($2::text[]) OR b_ref=ANY($2::text[]))`,- [src, plan.factIds.map(String)], plan.reviewRows, removed.decide_review);+ const refs = plan.factIds.map(String);+ for (const table of ['decide_review_queue', 'decide_review_proposals'] as const) {+ await swept(table, `SELECT 1 FROM ${table} WHERE source_id=$1 AND (a_ref=ANY($2::text[]) OR b_ref=ANY($2::text[]))`, [src, refs], plan.review[table], plan.review[table]);+ }+ await swept('decide_proposals', 'SELECT 1 FROM decide_proposals WHERE source_id=$1 AND (new_fact_id=ANY($2::bigint[]) OR old_fact_id=ANY($2::bigint[]))',+ [src, plan.factIds], plan.review.decide_proposals, plan.review.decide_proposals);await swept('take_proposals', 'SELECT 1 FROM take_proposals WHERE source_id=$1 AND gbrain_fact_fingerprint(claim_text)=$2', [src, target.fact_hash], 0, removed.take_proposals);await swept('core_edit_notices', 'SELECT 1 FROM core_edit_notices WHERE source_id=$1 AND strpos(lower(base_text),$2)>0', [src, needle], 0, removed.core_edit_notices);stores.push({ store: 'derived_artifacts', status: plan.derived.truncated ? 'unverified' : plan.derived.rows.length ? (dryRun ? 'would_remove' : 'retained_inactive') : 'not_present',@@ -217,9 +254,10 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: PurgAND 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.` });+ 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;- stores.push(await probeInventoryStore(engine, entry, src, claim, deadline));+ stores.push(await probeInventoryStore(engine, entry, src, [claim], deadline));}const [other] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM facts WHERE source_id=$1 AND gbrain_fact_fingerprint(fact)=$2AND NOT (visibility=$3 AND ($4='*' OR entity_slug=$4))`, [src, target.fact_hash, target.visibility, plan.subject]);@@ -249,13 +287,111 @@ 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[] }++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 }));++/**+ * CEO-4 / C4: the page purge receipt, store by store like the fact receipt. Page-keyed stores are checked by+ * slug and page id; every other swept inventory store and every probed store is searched for the page's claims;+ * other pages whose prose still carries one are listed as `source_prose`; residuals come first.+ */+export async function verifyPagePurge(engine: BrainEngine, input: { sourceId: string; slug: string; requestId: string; removed: StoreCount;+ blobsRemaining: string[]; context: PagePurgeContext | null }): Promise<Record<string, unknown>> {+ const { sourceId: src, slug, removed, context } = input;+ const deadline = performance.now() + probeLimits.totalMs;+ const needles = context?.needles ?? [];+ const stores: StoreReport[] = [];+ const keyed = async (store: string, sql: string, params: unknown[]) => {+ const result = await boundedCount(engine, sql, params, deadline);+ const n = removed[store] ?? 0;+ if ('unverified' in result) stores.push({ store, status: 'unverified', reason: result.unverified, removed: n });+ else if (result.count) stores.push({ store, status: 'incomplete', remaining: result.count, removed: n });+ else stores.push({ store, status: n ? 'deleted' : 'not_present', removed: n });+ };+ await keyed('pages', 'SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2', [src, slug]);+ if (context) for (const table of ['content_chunks', 'page_versions', 'takes', 'timeline_entries']) await keyed(table, `SELECT 1 FROM ${table} WHERE page_id=$1`, [context.pageId]);+ await keyed('facts', 'SELECT 1 FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [src, slug]);+ for (const table of ['take_proposals', 'open_loops']) await keyed(table, `SELECT 1 FROM ${table} WHERE source_id=$1 AND page_slug=$2`, [src, slug]);+ await keyed('core_edit_notices', 'SELECT 1 FROM core_edit_notices WHERE source_id=$1 AND slug=$2', [src, slug]);+ await keyed('files', 'SELECT 1 FROM files WHERE page_slug=$2 AND (source_id=$1 OR source_id IS NULL)', [src, slug]);+ await keyed('write_gate_holds', 'SELECT 1 FROM write_gate_holds WHERE source_id=$1 AND slug=$2', [src, slug]);+ await keyed('query_cache', 'SELECT 1 FROM query_cache WHERE $1::text IS NOT NULL', [src]);+ if (context) {+ const refs = context.factIds.map(String);+ for (const table of ['decide_review_queue', 'decide_review_proposals']) await keyed(table, `SELECT 1 FROM ${table} WHERE source_id=$1 AND (a_ref=ANY($2::text[]) OR b_ref=ANY($2::text[]))`, [src, refs]);+ await keyed('decide_proposals', 'SELECT 1 FROM decide_proposals WHERE source_id=$1 AND (new_fact_id=ANY($2::bigint[]) OR old_fact_id=ANY($2::bigint[]))', [src, context.factIds]);+ await keyed('trust_proposals', `SELECT 1 FROM trust_proposals WHERE source_id=$1 AND ((target_table='pages' AND target_id=$2) OR (related_table='pages' AND related_id=$2)+ OR (target_table='facts' AND target_id=ANY($3::bigint[])) OR (related_table='facts' AND related_id=ANY($3::bigint[])))`, [src, context.pageId, context.factIds]);+ }+ const textChecks = needles.flatMap((n, i) => ['intent', 'outcome', 'error_detail', 'error_message'].map(c => `strpos(lower(COALESCE(${c}::text,'')),$${4 + i})>0`));+ 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())]);+ 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));+ }+ if (!context) stores.push({ store: 'source_prose', status: 'unverified', reason: 'prose_probe_unavailable',+ detail: 'The receipt was built by another process than the purge, so other pages were not searched for the purged page\'s claims.' });+ else if (needles.length) {+ // Page-text stores are judged source-wide as in the fact receipt: the purged page's rows are gone, so any claim+ // text left there is another page's prose (`out_of_scope: source_prose`, naming those pages).+ const lowered = needles.map(n => n.toLowerCase());+ const proseIn: Record<string, string> = {+ pages: `SELECT DISTINCT p.slug FROM pages p WHERE p.source_id=$1 AND p.deleted_at IS NULL+ AND EXISTS (SELECT 1 FROM unnest($2::text[]) n WHERE strpos(lower(p.compiled_truth),n)>0 OR strpos(lower(COALESCE(p.timeline,'')),n)>0)`,+ content_chunks: `SELECT DISTINCT p.slug FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.source_id=$1+ AND EXISTS (SELECT 1 FROM unnest($2::text[]) n WHERE strpos(lower(c.chunk_text),n)>0)`,+ page_versions: `SELECT DISTINCT p.slug FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1+ AND EXISTS (SELECT 1 FROM unnest($2::text[]) n WHERE strpos(lower(v.compiled_truth),n)>0 OR strpos(lower(COALESCE(v.timeline,'')),n)>0)`,+ timeline_entries: `SELECT DISTINCT p.slug FROM timeline_entries t JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1+ AND EXISTS (SELECT 1 FROM unnest($2::text[]) n WHERE strpos(lower(t.summary),n)>0 OR strpos(lower(COALESCE(t.detail,'')),n)>0)`,+ };+ const all = new Set<string>();+ for (const [store, sql] of Object.entries(proseIn)) {+ const slugs = (await engine.executeRaw<{ slug: string }>(`${sql} ORDER BY 1 LIMIT 20`, [src, lowered])).map(r => r.slug);+ if (!slugs.length) continue;+ slugs.forEach(s => all.add(s));+ const at = stores.findIndex(s => s.store === store);+ const report: StoreReport = { store, status: 'out_of_scope', reason: 'source_prose', removed: removed[store] ?? 0, remaining: slugs.length, items: slugs,+ detail: 'The purged page\'s rows are gone; other pages still state one of its claims in their prose. Edit or purge them.' };+ if (at >= 0 && stores[at]!.status !== 'incomplete') stores[at] = report; else if (at < 0) stores.push(report);+ }+ stores.push(all.size ? { store: 'source_prose', status: 'out_of_scope', reason: 'source_prose', remaining: all.size, items: [...all].sort(),+ detail: 'Other pages still state a claim from the purged page in their prose; edit or purge them.' } : { store: 'source_prose', status: 'not_present' });+ }+ const [source] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [src]);+ const files = source?.local_path ? (context?.paths ?? []).filter(p => !p.startsWith('/') && !p.includes('..')).map(p => join(source.local_path!, p)) : [];+ const present = files.filter(f => existsSync(f)), tmp = files.map(f => `${f}.tmp`).filter(f => existsSync(f));+ for (const path of tmp) { try { unlinkSync(path); } catch { /* reported below */ } }+ stores.push({ store: 'canonical_markdown', status: !files.length ? 'not_present' : present.length ? 'incomplete' : 'deleted', ...(present.length ? { remaining: present.length } : {}) },+ { store: 'fence_tmp_evidence', status: tmp.some(existsSync) ? 'incomplete' : tmp.length ? 'deleted' : 'not_present' },+ { store: 'file_blobs', status: input.blobsRemaining.length ? 'incomplete' : (removed.files ? 'deleted' : 'not_present'), ...(input.blobsRemaining.length ? { items: input.blobsRemaining } : {}) });+ const [tombstones] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_purges WHERE source_id=$1 AND slug=$2', [src, slug]);+ const residuals: StoreReport[] = [];+ if (source?.local_path && context?.paths.length && needles.length) residuals.push(await gitResidualCommits(source.local_path, context.paths, needles[0]!));+ residuals.push(...outOfReach(engine).filter(r => !(r.store === 'git_history' && residuals.length)));+ residuals.push(...stores.filter(s => s.reason === 'source_prose' || s.reason === 'probed_reported'));+ const [row] = await engine.executeRaw<Pick<WriteRequest, 'id' | 'state' | 'source_id' | 'outcome'>>(`SELECT id,state,source_id,outcome FROM persistence_requests+ WHERE source_id=$1 AND request_id=$2::uuid AND operation='delete_page' ORDER BY created_at DESC LIMIT 1`, [src, input.requestId]);+ return { summary: 'Removed from live stores. Residuals below are copies purge cannot reach; this is not physical erasure.',+ residuals, stores, page_tombstones: Number(tombstones?.n ?? 0),+ ...(row ? await purgeCompletion(engine, row, { stores }) : {}),+ next: ['Other pages listed under source_prose still state the purged claims; edit or purge them. gbrain pages purges list shows the tombstones.'],+ ...(engine.kind === 'postgres' ? { tell_user_to_run: { argv: ['psql', '-c', 'VACUUM (VERBOSE) pages, content_chunks, page_versions, facts, takes, persistence_requests'],+ why: 'Deleted rows stay in Postgres table pages and WAL until VACUUM and WAL recycling; the operator runs it (gbrain does not on Postgres).' } } : {}) };+}+/*** DX-12: `committed` once the transaction committed and effects are pending,* `complete` once every effect committed and no swept store reported a* residual, `incomplete` when an effect failed or parked or a swept store* still holds the claim. Out-of-reach residuals never make it incomplete.*/-export async function purgeCompletion(engine: BrainEngine, row: Pick<WriteRequest, 'id' | 'state' | 'source_id' | 'outcome'>, receipt?: PurgeReceipt):+export async function purgeCompletion(engine: BrainEngine, row: Pick<WriteRequest, 'id' | 'state' | 'source_id' | 'outcome'>, receipt?: Pick<PurgeReceipt, 'stores'>):Promise<{ completion: PurgeCompletion; effects: Array<{ kind: string; state: string; error_code: string | null }>; exit_code: number; fingerprint_probe?: Record<string, number> }> {if (row.state !== 'committed') return { completion: 'incomplete', effects: [], exit_code: 75 };const effects = await engine.executeRaw<{ kind: string; state: string; error_code: string | null; parked: boolean }>(`SELECT kind,state,error_code,diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.tsindex 88443863de..65f016818c 100644--- a/src/core/facts/purge.ts+++ b/src/core/facts/purge.ts@@ -60,6 +60,8 @@ export interface PurgePlan {requests: Awaited<ReturnType<typeof findRequestsCarrying>>;derived: Awaited<ReturnType<typeof derivedRowsFrom>>;reviewRows: number;+ /** Per review table: rows naming the purged facts (all dropped by the purge). */+ review: Record<'decide_review_queue' | 'decide_review_proposals' | 'decide_proposals', number>;/** A digest of the target set; a confirmation binds to it. */revision: string;}@@ -108,15 +110,17 @@ export async function planFactPurge(engine: BrainEngine, target: PurgeTarget, alconst requests = await findRequestsCarrying(engine, target.source_id, target.fact);const inputs: DerivationRef[] = [...factIds.map(id => ({ table: 'facts', id })), ...takes.map(t => ({ table: 'takes', id: t.id }))];const derived = await derivedRowsFrom(engine, inputs);- const [review] = await engine.executeRaw<{ n: number }>(`SELECT- (SELECT count(*) FROM decide_review_queue WHERE source_id=$1 AND (a_ref=ANY($2::text[]) OR b_ref=ANY($2::text[])))- + (SELECT count(*) FROM decide_review_proposals WHERE source_id=$1 AND (a_ref=ANY($2::text[]) OR b_ref=ANY($2::text[])))- + (SELECT count(*) FROM decide_proposals WHERE source_id=$1 AND (new_fact_id=ANY($3::bigint[]) OR old_fact_id=ANY($3::bigint[]))) AS n`,+ const [counts] = await engine.executeRaw<{ q: number; rp: number; dp: number }>(`SELECT+ (SELECT count(*)::int FROM decide_review_queue WHERE source_id=$1 AND (a_ref=ANY($2::text[]) OR b_ref=ANY($2::text[]))) AS q,+ (SELECT count(*)::int FROM decide_review_proposals WHERE source_id=$1 AND (a_ref=ANY($2::text[]) OR b_ref=ANY($2::text[]))) AS rp,+ (SELECT count(*)::int FROM decide_proposals WHERE source_id=$1 AND (new_fact_id=ANY($3::bigint[]) OR old_fact_id=ANY($3::bigint[]))) AS dp`,[target.source_id, factIds.map(String), factIds]);+ const review = { decide_review_queue: Number(counts?.q ?? 0), decide_review_proposals: Number(counts?.rp ?? 0), decide_proposals: Number(counts?.dp ?? 0) };const { createHash } = await import('node:crypto');const revision = createHash('sha256').update(JSON.stringify({ subject, factIds, takes: takes.map(t => t.id),pages: pages.map(p => [p.page_id, p.revision]), requests: requests.map(r => r.id) })).digest('hex').slice(0, 16);- return { subject, factIds, takes, pages, versions: Number(versions?.n ?? 0), requests, derived, reviewRows: Number(review?.n ?? 0), revision };+ return { subject, factIds, takes, pages, versions: Number(versions?.n ?? 0), requests, derived,+ reviewRows: review.decide_review_queue + review.decide_review_proposals + review.decide_proposals, review, revision };}/** Pages with a pending recovery record or an unfinished mirror refuse a purge, as effects refuse other writes. */@@ -280,7 +284,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Recreturn withCoordinatedWrite(tx, [p.sourceId], async () => {const plan = committedPlan;await assertNoPendingPublication(tx, p.sourceId, plan.pages, admitted.id);- const intents = await redactRequestIntents(tx, plan.requests, 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 })));// 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}` });diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 054f155981..25323b9ecc 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -399,7 +399,7 @@ const delete_page: Operation = {}return { dry_run: true, action: p.purge === true ? 'purge_page' : 'delete_page', slug: p.slug };}- return (await import('../persistence/page-purge.ts')).finishPagePurge(ctx.config, await submitPageMutation(ctx, { operation: 'delete_page', params: p }));+ return (await import('../persistence/page-purge.ts')).finishPagePurge(ctx, await submitPageMutation(ctx, { operation: 'delete_page', params: p }));},cliHints: { name: 'delete', positional: ['slug'] },};diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.tsindex 6df8f262b5..bc337606a4 100644--- a/src/core/persistence/page-purge.ts+++ b/src/core/persistence/page-purge.ts@@ -17,12 +17,11 @@*/import type { BrainEngine } from '../engine.ts';-import type { GBrainConfig } from '../config.ts';import type { OperationContext } from '../ops/contract.ts';import { opError } from '../ops/contract.ts';import type { PageSnapshot } from '../page-state/types.ts';import type { WriteRequest } from './model.ts';-import { findRequestsForSlugs, redactRequestIntents } from './intent-redaction.ts';+import { findRequestsCarrying, findRequestsForSlugs, redactRequestIntents } from './intent-redaction.ts';import { dropPurgedFenceRows } from '../facts/purge-overlay.ts';import { contentHash } from '../utils.ts';@@ -36,57 +35,115 @@ function hostOnly(command: string) {`Ask the user to run \`${command}\` on the brain host.`, { legacy_error: 'permission_denied' });}+/**+ * What the post-commit receipt needs and the journal must never hold: the purged page's claims (verification+ * 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 PURGE_CONTEXT_LIMIT = 64;+const purgeReceipts = new Map<string, { receipt: Record<string, unknown>; purge: Record<string, unknown> }>();+/** Inside the coordinated delete transaction, before the page row is deleted. */export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest, snapshot: PageSnapshot): 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;- if (storedHash) await tx.executeRaw(`INSERT INTO page_purges(source_id,content_hash,slug,request_id) VALUES ($1,$2,$3,$4::uuid)- ON CONFLICT (source_id,content_hash) DO UPDATE SET slug=EXCLUDED.slug,request_id=EXCLUDED.request_id,purged_at=now()`, [sourceId, storedHash, slug, row.id]);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]);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]);- // A re-import passes through the purge overlay, which now drops this page's tombstoned fence rows;- // its content hash is tombstoned too, so the stale file is refused either way.- const overlaid = { ...page, compiled_truth: await dropPurgedFenceRows(tx, sourceId, page.compiled_truth, slug),- timeline: await dropPurgedFenceRows(tx, sourceId, page.timeline ?? '', slug), tags: snapshot.tags };- const overlaidHash = contentHash(overlaid);- if (storedHash && overlaidHash !== storedHash) await tx.executeRaw(`INSERT INTO page_purges(source_id,content_hash,slug,request_id) VALUES ($1,$2,$3,$4::uuid)- ON CONFLICT (source_id,content_hash) DO UPDATE SET slug=EXCLUDED.slug,request_id=EXCLUDED.request_id,purged_at=now()`, [sourceId, overlaidHash, slug, row.id]);+ // 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,+ 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] : []);+ 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]);+ const factRows = await tx.executeRaw<{ id: number; fact: string }>('SELECT id,fact FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ORDER BY id LIMIT 1000', [sourceId, slug]);+ const takeRows = await tx.executeRaw<{ id: number; claim: string }>('SELECT id,claim FROM takes WHERE page_id=$1 ORDER BY id LIMIT 1000', [page.id]);+ const factIds = factRows.map(f => Number(f.id)), takeIds = takeRows.map(t => Number(t.id));+ const needles = [...new Set([...factRows.map(f => f.fact), ...takeRows.map(t => t.claim)].map(t => t.trim()).filter(t => t.length >= 8))].slice(0, 32);const count = async (sql: string, params: unknown[]) => (await tx.executeRaw(sql, params)).length;- const facts = await count('DELETE FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 RETURNING 1', [sourceId, slug]);- const takeProposals = await count('DELETE FROM take_proposals WHERE source_id=$1 AND page_slug=$2 RETURNING 1', [sourceId, slug]);- const openLoops = await count('DELETE FROM open_loops WHERE source_id=$1 AND page_slug=$2 RETURNING 1', [sourceId, slug]);- const notices = await count('DELETE FROM core_edit_notices WHERE source_id=$1 AND slug=$2 RETURNING 1', [sourceId, slug]);- const requests = await findRequestsForSlugs(tx, sourceId, [slug]);- const intents = await redactRequestIntents(tx, requests, row.id, { skipPending: true });+ const refs = factIds.map(String);+ const removed: Record<string, number> = {+ decide_review_queue: await count('DELETE FROM decide_review_queue WHERE source_id=$1 AND (a_ref=ANY($2::text[]) OR b_ref=ANY($2::text[])) RETURNING 1', [sourceId, refs]),+ decide_review_proposals: await count('DELETE FROM decide_review_proposals WHERE source_id=$1 AND (a_ref=ANY($2::text[]) OR b_ref=ANY($2::text[])) RETURNING 1', [sourceId, refs]),+ decide_proposals: await count('DELETE FROM decide_proposals WHERE source_id=$1 AND (new_fact_id=ANY($2::bigint[]) OR old_fact_id=ANY($2::bigint[])) RETURNING 1', [sourceId, factIds]),+ trust_proposals: await count(`DELETE FROM trust_proposals WHERE source_id=$1 AND ((target_table='pages' AND target_id=$2) OR (related_table='pages' AND related_id=$2)+ OR (target_table='facts' AND target_id=ANY($3::bigint[])) OR (related_table='facts' AND related_id=ANY($3::bigint[]))+ OR (target_table='takes' AND target_id=ANY($4::bigint[])) OR (related_table='takes' AND related_id=ANY($4::bigint[]))) RETURNING 1`, [sourceId, page.id, factIds, takeIds]),+ };+ const holds = (await tx.executeRaw<{ id: string }>('DELETE FROM write_gate_holds WHERE source_id=$1 AND slug=$2 RETURNING id::text AS id', [sourceId, slug])).map(h => h.id);+ removed.write_gate_holds = holds.length;+ removed.write_gate_receipts = await count(`DELETE FROM write_gate_receipts WHERE (target_table='pages' AND target_id=$1) OR (target_table='facts' AND target_id=ANY($2::text[]))+ OR (target_table='takes' AND target_id=ANY($3::text[])) OR (target_table='write_gate_holds' AND target_id=ANY($4::text[])) RETURNING 1`,+ [String(page.id), refs, takeIds.map(String), holds]);+ removed.query_cache = await count('DELETE FROM query_cache RETURNING 1', []);+ removed.facts = await count('DELETE FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 RETURNING 1', [sourceId, slug]);+ removed.take_proposals = await count('DELETE FROM take_proposals WHERE source_id=$1 AND page_slug=$2 RETURNING 1', [sourceId, slug]);+ removed.open_loops = await count('DELETE FROM open_loops WHERE source_id=$1 AND page_slug=$2 RETURNING 1', [sourceId, slug]);+ removed.core_edit_notices = await count('DELETE FROM core_edit_notices WHERE source_id=$1 AND slug=$2 RETURNING 1', [sourceId, slug]);+ const carrying = needles.length ? (await Promise.all(needles.map(n => findRequestsCarrying(tx, sourceId, n)))).flat() : [];+ const requests = [...new Map([...await findRequestsForSlugs(tx, sourceId, [slug]), ...carrying].map(r => [r.id, r])).values()];+ removed.persistence_requests = await redactRequestIntents(tx, requests, row.id, { skipPending: true, needles });const files = await tx.executeRaw<{ storage_path: string }>(`DELETE FROM files WHERE (page_id=$1 OR (page_slug=$2 AND (source_id=$3 OR source_id IS NULL)))RETURNING storage_path`, [page.id, slug, sourceId]);+ removed.files = files.length;const [cascade] = await tx.executeRaw<{ chunks: number; versions: number; takes: number; timeline: number }>(`SELECT(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);await tx.deletePage(slug, { sourceId });+ const key = `${sourceId}:${row.request_id}`;+ purgeContext.delete(key);+ purgeContext.set(key, { needles, factIds, pageId: page.id, paths });+ while (purgeContext.size > PURGE_CONTEXT_LIMIT) purgeContext.delete(purgeContext.keys().next().value!);return { status: 'purged', slug, source_id: sourceId, residuals: PURGE_RESIDUALS,- purge: { content_hash8: storedHash?.slice(0, 8) ?? null, tombstoned: storedHash !== null,- removed: { facts, take_proposals: takeProposals, open_loops: openLoops, core_edit_notices: notices, persistence_requests: intents,- files: files.length, content_chunks: cascade?.chunks ?? 0, page_versions: cascade?.versions ?? 0, takes: cascade?.takes ?? 0, timeline_entries: cascade?.timeline ?? 0 },+ purge: { content_hash8: storedHash?.slice(0, 8) ?? null, tombstoned: hashes.size > 0, content_hashes_tombstoned: hashes.size, removed,blobs: files.map(f => f.storage_path).filter(Boolean) } };}-/** After commit: delete the purged page's stored blobs; any that remain are listed by storage path. */-export async function finishPagePurge(config: GBrainConfig | undefined, result: Record<string, unknown>): Promise<Record<string, unknown>> {- const purge = result.purge as { blobs?: string[] } | undefined;- if (result.status !== 'purged' || !purge?.blobs?.length) return result;+/**+ * After commit: delete the purged page's stored blobs (any that remain are listed by storage path), then build the+ * store-by-store receipt the fact purge returns: residuals first, every swept inventory store with a status.+ */+export async function finishPagePurge(ctx: Pick<OperationContext, 'engine' | 'config'>, result: Record<string, unknown>): Promise<Record<string, unknown>> {+ if (result.status !== 'purged') return result;+ const sourceId = String(result.source_id), slug = String(result.slug), key = `${sourceId}:${String(result.request_id)}`;+ // 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 remaining: string[] = [];- try {- const { createStorage } = await import('../storage.ts');- const storage = await createStorage((config as { storage?: unknown } | undefined)?.storage as never);- for (const path of purge.blobs) { try { await storage.delete(path); } catch { remaining.push(path); } }- } catch { remaining.push(...purge.blobs); }- return { ...result, purge: { ...purge, blobs_deleted: purge.blobs.length - remaining.length, blobs_remaining: remaining } };+ if (purge.blobs?.length) {+ try {+ const { createStorage } = await import('../storage.ts');+ const storage = await createStorage((ctx.config as { storage?: unknown } | undefined)?.storage as never);+ for (const path of purge.blobs) { try { await storage.delete(path); } catch { remaining.push(path); } }+ } catch { remaining.push(...purge.blobs); }+ }+ const { verifyPagePurge } = await import('../facts/purge-verify.ts');+ const receipt = await verifyPagePurge(ctx.engine, { sourceId, slug, requestId: String(result.request_id), removed: purge.removed ?? {},+ blobsRemaining: remaining, context: purgeContext.get(key) ?? null });+ purgeContext.delete(key);+ // `residuals` stays the delete_page prose string; the store-by-store receipt (same shape as purge_fact's) rides as `receipt`.+ const extra = { receipt, purge: { ...purge, blobs_deleted: (purge.blobs?.length ?? 0) - remaining.length, blobs_remaining: remaining } };+ purgeReceipts.set(key, extra);+ while (purgeReceipts.size > PURGE_CONTEXT_LIMIT) purgeReceipts.delete(purgeReceipts.keys().next().value!);+ return { ...result, ...extra };}/** Prefetch for import screens: every page tombstone of a source, content hash -> slug (bounded). */