Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(purge): purge_fact op with journaled sweep, deletion inventory and verified receipt
garrytan84d124aa04b7
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsnew file mode 100644index 0000000000..a5e55be4e1--- /dev/null+++ b/src/core/deletion-inventory.ts@@ -0,0 +1,189 @@+/**+ * The deletion-target inventory (#5575 CEO-22, ENG-12): one registry that+ * classifies every table holding text, JSON, bytes, lexemes or vectors, so a+ * purge receipt can say exactly what it swept, what it hid, what it probed and+ * reported, and what is out of its reach. `test/deletion-inventory.test.ts`+ * fails when a migration adds a text-bearing column this registry does not+ * list, so a new store is classified before it ships.+ *+ * Classes:+ * - `swept`: purge removes or redacts matching content (`adapter` names how).+ * - `retained_inactive`: rows purge hides and marks `needs_rederive`.+ * - `out_of_scope` with a reason:+ * - `probed_reported`: may carry memory text purge does not rewrite; the+ * verification probes `probe` columns and lists matches as residuals;+ * - `text_free_ledger`: tombstones and edges (hashes and ids only);+ * - `secret_material`: credential hashes and grants;+ * - `no_memory_text`: identifiers, hashes, enums, operational metadata.+ *+ * "Verified" in a receipt applies only to the swept scope. Purge removes+ * content from live stores; it never claims physical erasure.+ */++export type InventoryClass = 'swept' | 'retained_inactive' | 'out_of_scope';+export type OutOfScopeReason = 'probed_reported' | 'text_free_ledger' | 'secret_material' | 'no_memory_text';+export interface InventoryEntry {+ table: string;+ class: InventoryClass;+ /** The swept adapter, or the out-of-scope reason. */+ reason: string;+ /** Every text-bearing column (text, varchar, json/jsonb, bytea, arrays, tsvector, vector) at registration. */+ columns: readonly string[];+ /** For `probed_reported`: the columns the verification probes for the claim. */+ probe?: readonly string[];+}++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'],+ ['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'],+ ['chat_usage_log', 'out_of_scope', 'no_memory_text', 'model provider phase'],+ ['chronicle_judge_reservations', 'out_of_scope', 'no_memory_text', 'source_id content_hash'],+ ['chronicle_page_state', 'out_of_scope', 'no_memory_text', 'source_id content_hash slug state reason trigger principal_kind principal_id event_slugs event_hashes campaign_id pricing_policy'],+ ['code_edges_chunk', 'out_of_scope', 'no_memory_text', 'from_symbol_qualified to_symbol_qualified edge_type edge_metadata source_id'],+ ['code_edges_symbol', 'out_of_scope', 'no_memory_text', 'from_symbol_qualified to_symbol_qualified edge_type edge_metadata source_id'],+ ['code_traversal_cache', 'out_of_scope', 'no_memory_text', 'symbol_qualified source_id response_json'],+ ['config', 'out_of_scope', 'no_memory_text', 'key value'],+ ['content_chunks', 'swept', 'chunks', 'chunk_text chunk_source embedding model embedded_text_hash embedding_input_hash language symbol_name symbol_type modality embedding_image embedding_multimodal parent_symbol_path doc_comment symbol_name_qualified search_vector'],+ ['context_volunteer_events', 'out_of_scope', 'probed_reported', 'source_id slug match_arm rationale channel session_id', 'rationale'],+ ['conversation_parser_llm_cache', 'out_of_scope', 'probed_reported', 'content_sha256 model_id call_shape value_json', 'value_json'],+ ['core_edit_notices', 'swept', 'core_notice_base', 'source_id slug revision base_revision base_text actor'],+ ['decide_calibrations', 'out_of_scope', 'no_memory_text', 'slot call_site provider model_resolved metric qualification policy_fingerprint dataset_hash split_hash calibrate_ids_hash pack_shape notes'],+ ['decide_proposals', 'swept', 'review_rows', 'source_id sweep_id direction model_resolved status before_state after_state'],+ ['decide_review_proposals', 'swept', 'review_rows', 'kind source_id sweep_id a_ref b_ref subject visibility model_resolved question_version status receipt'],+ ['decide_review_queue', 'swept', 'review_rows', 'kind source_id a_ref b_ref evidence reason'],+ ['decide_spend', 'out_of_scope', 'no_memory_text', 'request_id source_id slot provider model_resolved lane outcome'],+ ['decide_state', 'out_of_scope', 'no_memory_text', 'key value'],+ ['decide_sweep_deferred', 'out_of_scope', 'no_memory_text', 'source_id slot reason'],+ ['decision_receipts', 'out_of_scope', 'probed_reported', 'decision_id source_id slot mode provider model_alias model_resolved question_kind state_hash question_hash answer_choice outcome subject_ref call_site lane policy_fingerprint calibration_ref error_reason run_meta', 'run_meta'],+ ['derivation_inputs', 'out_of_scope', 'text_free_ledger', 'derived_table derived_id input_table input_id source_id'],+ ['dream_synthesis_completions', 'out_of_scope', 'no_memory_text', 'source_id idempotency_key'],+ ['dream_verdicts', 'out_of_scope', 'probed_reported', 'file_path content_hash reasons content_type segments entities model', 'segments entities reasons'],+ ['drift_decisions', 'out_of_scope', 'probed_reported', 'reasoning applied_by', 'reasoning'],+ ['entity_identities', 'out_of_scope', 'no_memory_text', 'entity_id source_id established_by'],+ ['eval_candidates', 'out_of_scope', 'probed_reported', 'tool_name query retrieved_slugs source_ids detail detail_resolved salience_param recency_param salience_resolved recency_resolved salience_source recency_source embedding_column schema_pack_per_source', 'query'],+ ['eval_capture_failures', 'out_of_scope', 'no_memory_text', 'reason'],+ ['eval_contradictions_cache', 'out_of_scope', 'probed_reported', 'chunk_a_hash chunk_b_hash model_id prompt_version truncation_policy verdict', 'verdict'],+ ['eval_contradictions_runs', 'out_of_scope', 'probed_reported', 'run_id judge_model prompt_version source_tier_breakdown report_json', 'report_json'],+ ['eval_takes_quality_runs', 'out_of_scope', 'probed_reported', 'receipt_sha8_corpus receipt_sha8_prompt receipt_sha8_models receipt_sha8_rubric rubric_version verdict dim_scores receipt_json receipt_disk_path', 'receipt_json'],+ ['extract_atoms_page_state', 'out_of_scope', 'no_memory_text', 'content_hash'],+ ['extract_atoms_transcript_state', 'out_of_scope', 'no_memory_text', 'source_id file_path content_hash'],+ ['extract_rollup_7d', 'out_of_scope', 'no_memory_text', 'kind source_id'],+ ['fact_purges', 'out_of_scope', 'text_free_ledger', 'source_id visibility subject fact_hash actor reason'],+ ['fact_relink_attempts', 'out_of_scope', 'probed_reported', 'source_id outcome reason tier model target_slug run_id', 'reason'],+ ['fact_withdrawals', 'out_of_scope', 'text_free_ledger', 'source_id visibility subject fact_hash'],+ ['facts', 'swept', 'fact', 'source_id entity_slug fact kind visibility notability context source source_session embedding source_markdown_slug claim_metric claim_unit claim_period event_type dimension value value_hash dim_status embedding_model embedded_text_hash write_principal_kind write_principal_id last_write_principal_kind last_write_principal_id attributed_to'],+ ['files', 'swept', 'page_files', 'source_id page_slug filename storage_path mime_type content_hash metadata'],+ ['gbrain_cycle_locks', 'out_of_scope', 'no_memory_text', 'id holder_host'],+ ['ingest_log', 'out_of_scope', 'probed_reported', 'source_id source_type source_ref pages_updated summary', 'summary pages_updated'],+ ['link_edge_proposals', 'out_of_scope', 'probed_reported', 'source_id link_type evidence_hash status model generated_line detail', 'generated_line detail'],+ ['link_relationships', 'out_of_scope', 'no_memory_text', 'link_type scope source_id semantics status_now evidence_hash'],+ ['link_transitions', 'out_of_scope', 'no_memory_text', 'source_id link_type kind date_precision producer line_hash'],+ ['links', 'out_of_scope', 'probed_reported', 'link_type context link_source link_kind origin_field resolution_type assertion_tense', 'context'],+ ['loop_suppressions', 'out_of_scope', 'no_memory_text', 'source_id kind value'],+ ['mcp_request_log', 'out_of_scope', 'probed_reported', 'token_name agent_name operation status params error_message', 'params error_message'],+ ['mcp_spend_log', 'out_of_scope', 'no_memory_text', 'client_id token_name operation provider model budget_key'],+ ['mcp_spend_reservations', 'out_of_scope', 'no_memory_text', 'client_id model provider status usage_unknown_reason budget_key'],+ ['mention_gazetteer_entries', 'out_of_scope', 'no_memory_text', 'source_id name_norm target_slug'],+ ['mention_index_status', 'out_of_scope', 'no_memory_text', 'source_id state policy_fingerprint error'],+ ['migration_impact_log', 'out_of_scope', 'probed_reported', 'remediation_id metric_name source_id brain_id idempotency_key applied_by details', 'details'],+ ['minion_attachments', 'out_of_scope', 'probed_reported', 'filename content_type content storage_uri sha256', 'content'],+ ['minion_budget_log', 'out_of_scope', 'no_memory_text', 'event_type model'],+ ['minion_inbox', 'out_of_scope', 'probed_reported', 'sender payload', 'payload'],+ ['minion_jobs', 'out_of_scope', 'probed_reported', 'name queue status submission_authority data backoff_type lock_token on_child_fail idempotency_key private_queue_owner_token result progress error_text stacktrace quiet_hours stagger_key spend_authorization', 'data result error_text'],+ ['minion_lease_pressure_log', 'out_of_scope', 'no_memory_text', 'lease_key queue_name job_name model provider'],+ ['minion_self_fix_log', 'out_of_scope', 'no_memory_text', 'classifier_bucket policy_applied outcome'],+ ['needs_rederive', 'out_of_scope', 'text_free_ledger', 'derived_table derived_id source_id reason'],+ ['oauth_clients', 'out_of_scope', 'secret_material', 'client_id client_secret_hash client_name redirect_uris grant_types scope token_endpoint_auth_method source_id federated_read bound_tools bound_source_id bound_brain_id bound_slug_prefixes surface surface_set_by allowed_operations delegated_slug_prefixes delegated_namespace grant_profile grant_repair_reasons source_grant takes_holders'],+ ['oauth_codes', 'out_of_scope', 'secret_material', 'code_hash client_id scopes code_challenge code_challenge_method redirect_uri state resource'],+ ['oauth_grant_audit', 'out_of_scope', 'no_memory_text', 'client_id actor action before_grant after_grant'],+ ['oauth_tokens', 'out_of_scope', 'secret_material', 'token_hash token_type client_id scopes resource'],+ ['op_checkpoint_paths', 'out_of_scope', 'no_memory_text', 'op fingerprint path'],+ ['op_checkpoints', 'out_of_scope', 'no_memory_text', 'op fingerprint completed_keys'],+ ['open_loops', 'swept', 'open_loops', 'source_id dedup_key loop_type counterparty_slug counterparty_email summary evidence thread_id page_slug status detector closed_by'],+ ['page_aliases', 'out_of_scope', 'probed_reported', 'source_id alias_norm slug origin alias_text', 'alias_text'],+ ['page_facts_reconcile', 'out_of_scope', 'no_memory_text', 'outcome'],+ ['page_mention_state', 'out_of_scope', 'no_memory_text', 'source_id'],+ ['page_projection_jobs', 'out_of_scope', 'no_memory_text', 'slug reason'],+ ['page_purges', 'out_of_scope', 'text_free_ledger', 'source_id content_hash slug'],+ ['page_versions', 'swept', 'page_versions', 'compiled_truth frontmatter timeline title type tags source_path write_principal_kind write_principal_id archived_principal_kind archived_principal_id'],+ ['page_write_guards', 'out_of_scope', 'no_memory_text', 'slug'],+ ['pages', 'swept', 'page_body', 'source_id slug type page_kind title compiled_truth timeline frontmatter content_hash effective_date_source import_filename database_only_reason contextual_retrieval_mode corpus_generation search_vector source_path ingested_via source_uri source_kind embedding_signature revision_principal_kind revision_principal_id'],+ ['persistence_counters', 'out_of_scope', 'no_memory_text', 'key'],+ ['persistence_effects', 'swept', 'effect_recovery', 'kind data state source_id error_code outcome recovery'],+ ['persistence_graduation', 'out_of_scope', 'probed_reported', 'role state source_data_dir trigger_bypass table_receipts replay_probe timings doctor rollback', 'table_receipts'],+ ['persistence_host_bindings', 'out_of_scope', 'no_memory_text', 'local_path coordination_path'],+ ['persistence_local_writers', 'out_of_scope', 'secret_material', 'lane credential_hash grant_ceiling'],+ ['persistence_requests', 'swept', 'request_intent', 'principal_kind principal_id operation source_id slug digest intent authority state recovery outcome error_code error_message blocked_reason target_kind admitter_version consumer_version error_detail claim_phase'],+ ['persistence_source_bindings', 'out_of_scope', 'no_memory_text', 'source_id relative_path'],+ ['persistence_topology_changes', 'out_of_scope', 'probed_reported', 'digest operation source_id state recovery outcome', 'recovery outcome'],+ ['persistence_worktree_refreshes', 'out_of_scope', 'probed_reported', 'source_ids state old_head target_head upstream_ref preserved_uncommitted outcome', 'outcome'],+ ['persistence_worktrees', 'out_of_scope', 'no_memory_text', 'state manifest'],+ ['planner_stats_deltas', 'out_of_scope', 'no_memory_text', 'table_name'],+ ['planner_stats_state', 'out_of_scope', 'no_memory_text', 'table_name'],+ ['query_cache', 'swept', 'query_cache', 'id query_text source_id embedding results meta knobs_hash page_generations'],+ ['raw_data', 'out_of_scope', 'probed_reported', 'source data', 'source data'],+ ['retrieval_event_links', 'out_of_scope', 'no_memory_text', 'event_id source_id edge_key to_slug'],+ ['retrieval_event_pages', 'out_of_scope', 'no_memory_text', 'event_id source_id slug content_hash'],+ ['retrieval_events', 'out_of_scope', 'no_memory_text', 'id client_id op'],+ ['retrieval_feedback', 'out_of_scope', 'no_memory_text', 'event_id signal element_kind source_id element_key client_id'],+ ['retrieval_weights', 'out_of_scope', 'no_memory_text', 'source_id element_kind element_key content_hash'],+ ['search_telemetry', 'out_of_scope', 'no_memory_text', 'date mode intent'],+ ['session_context_state', 'out_of_scope', 'probed_reported', 'source_id client_id session_id standing_entities surfaced_slugs checkpoint_manifest', 'checkpoint_manifest standing_entities'],+ ['shared_skill_delivery_batches', 'out_of_scope', 'no_memory_text', 'view_token authority_digest revisions evidence'],+ ['shared_skill_heads', 'out_of_scope', 'no_memory_text', 'source_id pack_id name metadata policy_epoch'],+ ['shared_skill_members', 'out_of_scope', 'no_memory_text', 'principal_kind principal_id adapter follow_policy desired_view acknowledged_view'],+ ['shared_skill_packs', 'out_of_scope', 'no_memory_text', 'source_id pack_id manifest manifest_hash'],+ ['shared_skill_policies', 'out_of_scope', 'no_memory_text', 'source_id policy'],+ ['shared_skill_policy_audit', 'out_of_scope', 'no_memory_text', 'source_id principal_kind principal_id previous_epoch policy'],+ ['shared_skill_revision_leases', 'out_of_scope', 'no_memory_text', 'lease_kind source_id pack_id name principal_kind principal_id'],+ ['shared_skill_revisions', 'out_of_scope', 'probed_reported', 'source_id pack_id name metadata files policy_epoch', 'files metadata'],+ ['shared_skill_state', 'out_of_scope', 'secret_material', 'token_secret'],+ ['slug_aliases', 'out_of_scope', 'no_memory_text', 'source_id alias_slug canonical_slug notes'],+ ['source_ingestion_receipts', 'out_of_scope', 'probed_reported', 'source_id approved_revision profile schema_fingerprint extractor_version phase outcome counts checkpoint_refs diagnostic policy_fingerprint', 'diagnostic'],+ ['sources', 'out_of_scope', 'no_memory_text', 'id name local_path last_commit config contextual_retrieval_mode chunker_version upstream_commit'],+ ['subagent_messages', 'out_of_scope', 'probed_reported', 'role content_blocks provider_id model', 'content_blocks'],+ ['subagent_rate_leases', 'out_of_scope', 'no_memory_text', 'key'],+ ['subagent_tool_executions', 'out_of_scope', 'probed_reported', 'tool_use_id tool_name input status output error provider_id', 'input output'],+ ['tags', 'out_of_scope', 'no_memory_text', 'tag tag_source'],+ ['take_domain_assignments', 'out_of_scope', 'no_memory_text', 'domain pack source'],+ ['take_grade_cache', 'out_of_scope', 'probed_reported', 'prompt_version judge_model_id evidence_signature wave_version verdict', 'verdict'],+ ['take_nudge_log', 'out_of_scope', 'no_memory_text', 'source_id nudge_pattern channel wave_version'],+ ['take_proposals', 'swept', 'take_proposals', 'source_id page_slug content_hash prompt_version wave_version proposal_run_id status claim_text kind holder domain dedup_against_fence_rows model_id acted_by'],+ ['take_purges', 'out_of_scope', 'text_free_ledger', 'source_id subject claim_hash'],+ ['takes', 'swept', 'take', 'claim kind holder since_date until_date source resolved_unit resolved_source resolved_by embedding resolved_quality embedding_model embedded_text_hash write_principal_kind write_principal_id last_write_principal_kind last_write_principal_id'],+ ['think_ab_results', 'out_of_scope', 'probed_reported', 'source_id wave_version question baseline_answer with_calibration_answer preferred model_id notes', 'question baseline_answer with_calibration_answer'],+ ['timeline_entries', 'out_of_scope', 'probed_reported', 'source summary detail write_principal_kind write_principal_id last_write_principal_kind last_write_principal_id', 'summary detail'],+ ['wanted_links', 'out_of_scope', 'probed_reported', 'source_id producer ref_kind target_source_id target_ref link_type context', 'context'],+];++export const DELETION_INVENTORY: readonly InventoryEntry[] = ROWS.map(([table, cls, reason, columns, probe]) => ({+ table, class: cls, reason, columns: columns.split(' '), ...(probe ? { probe: probe.split(' ') } : {}),+}));++export const DELETION_INVENTORY_BY_TABLE: ReadonlyMap<string, InventoryEntry> = new Map(DELETION_INVENTORY.map(e => [e.table, e]));++/** Rows reached through derivation_inputs are hidden in their own table and marked needs_rederive. */+export const DERIVED_ARTIFACTS_ENTRY: InventoryEntry = {+ table: 'derived_artifacts', class: 'retained_inactive', reason: 'needs_rederive', columns: [],+};++/** Stores outside the database. `swept` ones purge checks and cleans; `out_of_reach` ones it can only name. */+export interface OnDiskStore { store: string; status: 'swept' | 'out_of_reach'; detail: string }+export const ON_DISK_STORES: readonly OnDiskStore[] = [+ { store: 'canonical_markdown', status: 'swept', detail: 'The page file is rewritten without the row by the post-commit mirror effect (managed sources) and committed as "gbrain: purge fact <hash8>".' },+ { store: 'fence_tmp_evidence', status: 'swept', detail: 'A quarantined <page file>.tmp left by a failed fence write is deleted when it carries the claim.' },+ { store: 'facts_write_failures_log', status: 'out_of_reach', detail: '~/.gbrain/facts.write_failures.jsonl keeps fence-write warnings; purge reports whether it mentions the claim and never rewrites it.' },+ { store: 'exports', status: 'out_of_reach', detail: 'Markdown exports and compiled context files written before the purge keep their copy.' },+];++/** Residuals no purge can reach. Listed first in every receipt. */+export const OUT_OF_REACH_RESIDUALS: ReadonlyArray<{ store: string; detail: string }> = [+ { store: 'git_history', detail: 'Earlier commits in the brain repository (and every clone and remote) still contain the row; purge lists them and never rewrites history.' },+ { store: 'other_clones', detail: 'Other checkouts, pulled copies and pushed remotes of the brain repository are outside this host.' },+ { store: 'backups', detail: 'A backup taken before the purge restores the content and an older purge ledger.' },+ { store: 'provider_copies', detail: 'Embedding, decision and chat providers that received the text keep whatever their retention keeps.' },+ { store: 'database_physical', detail: 'Deleted rows stay in table pages, indexes and the write-ahead log until vacuum and WAL recycling; replicas and point-in-time recovery windows keep them longer.' },+];diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 2d4b3a8598..ef35ffa83e 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -273,6 +273,8 @@ export const CODES = {projection_pending: { class: 'retryable', summary: "The current text projection is not ready." },provenance_required: { class: 'caller', summary: "provenance is required and must be non-empty." },publication_pending: { class: 'retryable', summary: "The catalog adoption is accepted but not fully committed." },+ purge_blocked_pending_recovery: { class: 'retryable', summary: "A purge was refused because a pending, running or recovering write still needs the content it would remove; nothing was purged.", why: "Purge redacts stored write intents and rewrites pages; doing that under an unfinished publication or recovery would lose or resurrect content.", suggestion: 'Wait for the named write to finish or recover (gbrain write-request <id>), then retry the purge with the same request id.', docs: 'docs/guides/memory-boundaries.md#purge' },+ purged_content: { class: 'caller', summary: "The content matches a purged fact, take or page in this source, so it was not saved.", why: "A purge leaves a text-free tombstone (the claim fingerprint or the page content hash) so stale files, re-syncs, reverts and re-extraction cannot bring purged content back.", suggestion: 'Do not retry the same content. Write it in new words if it is still true, or ask the user to clear the tombstone on the brain host (gbrain pages purges list, then gbrain pages unpurge <slug> for a page).', docs: 'docs/guides/memory-boundaries.md#purge' },queue_capacity: { class: 'retryable', summary: "The bounded queue is full; existing requests keep their place." },rate_limited: { class: 'retryable', summary: "The request was rate-limited; retry after the stated delay." },receipt_conflict: { class: 'retryable', summary: "The ingestion receipt changed since it was read.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },diff --git a/src/core/facts/derivation-inputs.ts b/src/core/facts/derivation-inputs.tsnew file mode 100644index 0000000000..19750d2554--- /dev/null+++ b/src/core/facts/derivation-inputs.ts@@ -0,0 +1,100 @@+/**+ * Complete derivation edges (`derivation_inputs`). A deriver (consolidation,+ * synthesis, patterns, atoms, chronicle, extraction) calls+ * `recordDerivationInputs` in the same transaction that writes the derived+ * row, naming every input placed in the model's context. `write_origin`'s+ * taint sample is a bounded display copy; these edges are the complete set.+ *+ * Purge walks the edges transitively from the purged rows, hides each derived+ * row through its table's own inactive state and records it in+ * `needs_rederive`, before cascades delete the evidence.+ */++import type { BrainEngine } from '../engine.ts';++/** A row reference: `table` is the owning table name, `id` its primary key (stringified). */+export interface DerivationRef { table: string; id: string | number }++export const DERIVATION_EDGE_LIMIT = 10_000;+const TABLE_NAME = /^[a-z_][a-z0-9_]{0,62}$/;++function refKey(ref: DerivationRef): { table: string; id: string } {+ if (!TABLE_NAME.test(ref.table)) throw new TypeError(`Invalid derivation table name: ${ref.table}`);+ const id = String(ref.id);+ if (!id) throw new TypeError('A derivation reference needs an id.');+ return { table: ref.table, id };+}++/**+ * Record every input of one derived row. Idempotent; call it inside the+ * transaction that writes `row`. `sourceId` scopes the edges for cleanup when+ * a source is purged.+ */+export async function recordDerivationInputs(tx: BrainEngine, row: DerivationRef & { sourceId?: string | null },+ inputs: readonly DerivationRef[]): Promise<void> {+ if (!inputs.length) return;+ const derived = refKey(row);+ if (inputs.length > DERIVATION_EDGE_LIMIT) throw new RangeError(`A derivation records at most ${DERIVATION_EDGE_LIMIT} inputs.`);+ const edges = inputs.map(refKey);+ await tx.executeRaw(`INSERT INTO derivation_inputs(derived_table,derived_id,input_table,input_id,source_id)+ SELECT $1,$2,e.input_table,e.input_id,$3 FROM jsonb_to_recordset($4::text::jsonb) AS e(input_table text,input_id text)+ ON CONFLICT DO NOTHING`, [derived.table, derived.id, row.sourceId ?? null, JSON.stringify(edges.map(e => ({ input_table: e.table, input_id: e.id })))]);+}++export interface DerivedRow { table: string; id: string; depth: number }++/**+ * Every row derived (transitively) from `inputs`, breadth-first, bounded by+ * `limit` rows and `maxDepth` hops. `truncated` is true when a bound stopped+ * the walk; the caller reports the remainder as unverified.+ */+export async function derivedRowsFrom(engine: BrainEngine, inputs: readonly DerivationRef[],+ opts: { limit?: number; maxDepth?: number } = {}): Promise<{ rows: DerivedRow[]; truncated: boolean }> {+ const limit = opts.limit ?? 1_000, maxDepth = opts.maxDepth ?? 8;+ const seen = new Set(inputs.map(i => `${i.table}:${i.id}`));+ const rows: DerivedRow[] = [];+ let frontier = inputs.map(refKey);+ for (let depth = 1; frontier.length && depth <= maxDepth; depth++) {+ const next = await engine.executeRaw<{ derived_table: string; derived_id: string }>(`SELECT DISTINCT d.derived_table,d.derived_id+ FROM derivation_inputs d JOIN jsonb_to_recordset($1::text::jsonb) AS f(input_table text,input_id text)+ ON d.input_table=f.input_table AND d.input_id=f.input_id+ ORDER BY d.derived_table,d.derived_id LIMIT $2`, [JSON.stringify(frontier.map(f => ({ input_table: f.table, input_id: f.id }))), limit + 1]);+ frontier = [];+ for (const r of next) {+ const key = `${r.derived_table}:${r.derived_id}`;+ if (seen.has(key)) continue;+ seen.add(key);+ if (rows.length >= limit) return { rows, truncated: true };+ rows.push({ table: r.derived_table, id: r.derived_id, depth });+ frontier.push({ table: r.derived_table, id: r.derived_id });+ }+ if (depth === maxDepth && frontier.length) return { rows, truncated: true };+ }+ return { rows, truncated: false };+}++/**+ * Hide each derived row through its table's own inactive state and mark it+ * `needs_rederive`. Facts expire, takes deactivate, pages soft-delete;+ * a table without a known inactive state is only marked (reported unverified).+ * Returns the rows hidden per table.+ */+export async function hideDerivedRows(tx: BrainEngine, rows: readonly DerivedRow[], mark: { sourceId: string; requestId: string | null; reason: string }):+ Promise<{ hidden: Record<string, number>; markedOnly: Record<string, number> }> {+ const hidden: Record<string, number> = {}, markedOnly: Record<string, number> = {};+ const byTable = new Map<string, string[]>();+ for (const r of rows) byTable.set(r.table, [...(byTable.get(r.table) ?? []), r.id]);+ for (const [table, ids] of byTable) {+ const numeric = ids.filter(id => /^\d+$/.test(id)).map(Number);+ let count = 0;+ if (table === 'facts') count = (await tx.executeRaw(`UPDATE facts SET expired_at=COALESCE(expired_at,now()) WHERE id=ANY($1::bigint[]) AND source_id=$2 RETURNING id`, [numeric, mark.sourceId])).length;+ else if (table === 'takes') count = (await tx.executeRaw(`UPDATE takes k SET active=false FROM pages p WHERE k.id=ANY($1::bigint[]) AND p.id=k.page_id AND p.source_id=$2 RETURNING k.id`, [numeric, mark.sourceId])).length;+ else if (table === 'pages') count = (await tx.executeRaw(`UPDATE pages SET deleted_at=COALESCE(deleted_at,now()) WHERE id=ANY($1::integer[]) AND source_id=$2 RETURNING id`, [numeric, mark.sourceId])).length;+ if (count) hidden[table] = count;+ if (count < ids.length) markedOnly[table] = ids.length - count;+ await tx.executeRaw(`INSERT INTO needs_rederive(derived_table,derived_id,source_id,request_id,reason)+ SELECT $1,unnest($2::text[]),$3,$4::uuid,$5 ON CONFLICT (derived_table,derived_id) DO UPDATE SET reason=EXCLUDED.reason,request_id=EXCLUDED.request_id,marked_at=now()`,+ [table, ids, mark.sourceId, mark.requestId, mark.reason]);+ }+ return { hidden, markedOnly };+}diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.tsnew file mode 100644index 0000000000..dc73fd1ad7--- /dev/null+++ b/src/core/facts/purge-verify.ts@@ -0,0 +1,278 @@+/**+ * Purge receipts and verification (#5575 C4, CEO-22, ENG-12, DX-12).+ *+ * One adapter per inventory store, each with an explicit scope, a row bound+ * and a statement deadline. A swept store whose probe still finds the claim is+ * `incomplete`; a probe stopped by its deadline or bound is `unverified`;+ * claim text that survives outside a fence (page prose, a version's prose) is+ * `out_of_scope: source_prose`; rows purge hid are `retained_inactive`, never+ * counted as a zero residual. The vector probe lists same-model neighbours as+ * paraphrase candidates and is never a gate.+ *+ * The receipt lists residuals first and says "removed from live stores"; it+ * never claims erasure. Verification needs the claim text, which exists only+ * in memory during the purge call; `--status` reports completion from the+ * stored receipt, the effects and a fingerprint probe.+ */++import { spawn } from 'node:child_process';+import { existsSync, readFileSync, unlinkSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { getCode } from '../retry-matcher.ts';+import { escapeFenceCell } from '../fence-shared.ts';+import { gbrainPath } from '../config.ts';+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';++export type StoreCount = Record<string, number>;+export type StoreStatus = 'deleted' | 'would_remove' | 'retained_inactive' | 'unverified' | 'out_of_reach' | 'out_of_scope' | 'not_present' | 'incomplete';+export interface StoreReport { store: string; status: StoreStatus; removed?: number; remaining?: number; reason?: string; detail?: string; items?: unknown[] }+export type PurgeCompletion = 'committed' | 'complete' | 'incomplete';+export interface PurgeReceipt {+ summary: string;+ fact_id: number;+ /** gbrain_fact_fingerprint of the claim: the receipt's content hash. Guessable for short claims. */+ fact_hash: string;+ hash8: string;+ source_id: string;+ subject: string;+ visibility: string;+ residuals: StoreReport[];+ stores: StoreReport[];+ vector_probe: Record<string, unknown>;+ next: string[];+ tell_user_to_run?: { argv: string[]; why: string };+}++export const PURGE_PROBE_LIMITS = { rows: 1000, statementMs: 2_000, totalMs: 20_000, gitBytes: 64 * 1024 * 1024, gitMs: 10_000 } as const;+let probeLimits: { rows: number; statementMs: number; totalMs: number } = { ...PURGE_PROBE_LIMITS };+/** Test seam: shrink the probe bounds (null restores them). */+export function __setPurgeProbeLimitsForTests(limits: Partial<typeof probeLimits> | null): void {+ probeLimits = limits ? { ...probeLimits, ...limits } : { ...PURGE_PROBE_LIMITS };+}++type ProbeResult = { count: number } | { unverified: string };++/** One bounded probe: `sql` selects matching rows (no LIMIT); the adapter caps rows and the statement time. */+async function boundedCount(engine: BrainEngine, sql: string, params: unknown[], deadline: number): Promise<ProbeResult> {+ if (performance.now() > deadline) return { unverified: 'verification_deadline' };+ try {+ return await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('statement_timeout',$1,true)", [`${probeLimits.statementMs}ms`]);+ const [row] = await tx.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM (${sql} LIMIT ${probeLimits.rows + 1}) bounded`, params);+ const count = Number(row?.n ?? 0);+ return count > probeLimits.rows ? { unverified: 'row_bound' } : { count };+ });+ } catch (error) {+ if (getCode(error) === '57014') return { unverified: 'statement_deadline' };+ throw error;+ }+}++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`;++/** The generic adapter for a `probed_reported` inventory entry. */+async function probeInventoryStore(engine: BrainEngine, entry: InventoryEntry, sourceId: string, claim: string, deadline: number): Promise<StoreReport> {+ const scoped = entry.columns.includes('source_id');+ 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);+ 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)'}.` }+ : { store: entry.table, status: 'not_present' };+}++/** 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> {+ if (!paths.length || !existsSync(join(root, '.git'))) return { store: 'git_history', status: 'out_of_reach', reason: 'no_repository', detail: 'No brain repository is recorded for these pages.' };+ const needles = [escapeFenceCell(claim).toLowerCase(), claim.toLowerCase()];+ return new Promise(resolve => {+ const child = spawn('git', ['-C', root, '--literal-pathspecs', 'log', '--all', '--format=commit %H %cI', '-p', '--no-color', '--no-ext-diff', '--', ...paths],+ { stdio: ['ignore', 'pipe', 'ignore'], env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_NOSYSTEM: '1' } });+ const commits: Array<{ commit: string; committed_at: string }> = [];+ let current: { commit: string; committed_at: string } | null = null, bytes = 0, tail = '', bounded: string | null = null;+ const timer = setTimeout(() => { bounded = 'deadline'; child.kill('SIGKILL'); }, limits.ms);+ const scan = (line: string) => {+ if (line.startsWith('commit ')) { const [, commit, at] = line.split(' '); current = { commit, committed_at: at }; return; }+ if (!current || commits.at(-1)?.commit === current.commit) return;+ if ((line.startsWith('+') || line.startsWith('-')) && !line.startsWith('+++') && !line.startsWith('---')) {+ const lower = line.toLowerCase();+ if (needles.some(n => lower.includes(n))) commits.push(current);+ }+ };+ child.stdout.on('data', (chunk: Buffer) => {+ bytes += chunk.length;+ if (bytes > limits.bytes) { bounded = 'byte_bound'; child.kill('SIGKILL'); return; }+ const lines = (tail + chunk.toString('utf8')).split('\n');+ tail = lines.pop() ?? '';+ for (const line of lines) scan(line);+ });+ child.on('error', () => { clearTimeout(timer); resolve({ store: 'git_history', status: 'out_of_reach', reason: 'git_unavailable' }); });+ child.on('close', () => {+ clearTimeout(timer);+ if (tail) scan(tail);+ const items = commits.slice(0, 50);+ resolve({ store: 'git_history', status: bounded ? 'unverified' : 'out_of_reach', ...(bounded ? { reason: bounded } : {}), remaining: commits.length, items,+ detail: commits.length ? `${commits.length} commit(s) in this repository's history add or remove the row; purge never rewrites history (other clones and remotes have their own copies).`+ : 'No commit in the page files\' recorded history carries the row.' });+ });+ });+}++async function pageFilePaths(engine: BrainEngine, sourceId: string, pageIds: number[]): Promise<{ root: string | null; paths: string[]; files: string[] }> {+ const [source] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [sourceId]);+ if (!source?.local_path || !pageIds.length) return { root: source?.local_path ?? null, paths: [], files: [] };+ const rows = await engine.executeRaw<{ source_path: string }>(`SELECT DISTINCT source_path FROM (+ SELECT source_path FROM pages WHERE id=ANY($1::int[]) UNION ALL SELECT source_path FROM page_versions WHERE page_id=ANY($1::int[])) s+ WHERE source_path IS NOT NULL AND source_path<>'' AND source_path NOT LIKE '/%' AND source_path NOT LIKE '%..%' LIMIT 64`, [pageIds]);+ const paths = rows.map(r => r.source_path);+ return { root: source.local_path, paths, files: paths.map(p => join(source.local_path!, p)) };+}++/** The canonical files, their .tmp evidence and the failure log; the .tmp copy carrying the claim is deleted. */+function onDiskReports(files: string[], claim: string, dryRun: boolean): StoreReport[] {+ const needle = claim.toLowerCase();+ const carrying = (path: string) => { try { return existsSync(path) && readFileSync(path, 'utf8').toLowerCase().includes(needle); } catch { return false; } };+ const stale = files.filter(carrying);+ const tmp = files.map(f => `${f}.tmp`).filter(carrying);+ if (!dryRun) for (const path of tmp) { try { unlinkSync(path); } catch { /* reported below */ } }+ const tmpLeft = dryRun ? tmp : tmp.filter(existsSync);+ const log = carrying(gbrainPath('facts.write_failures.jsonl'));+ return [+ { store: 'canonical_markdown', status: !files.length ? 'not_present' : stale.length ? (dryRun ? 'would_remove' : 'out_of_scope') : (dryRun ? 'not_present' : 'deleted'),+ ...(!files.length ? { detail: 'No page file is recorded for the affected pages (database-only source).' } : {}),+ ...(stale.length ? { remaining: stale.length, reason: dryRun ? undefined : 'pending_mirror_or_prose',+ detail: dryRun ? 'The mirror effect rewrites these files after commit.' : 'A page file still carries the claim: the mirror effect has not run yet, the source has no managed checkout, or the text is prose outside the fence.' } : {}) },+ { store: 'fence_tmp_evidence', status: tmpLeft.length ? (dryRun ? 'would_remove' : 'incomplete') : tmp.length ? 'deleted' : 'not_present', ...(tmp.length ? { removed: dryRun ? 0 : tmp.length - tmpLeft.length } : {}) },+ { store: 'facts_write_failures_log', status: log ? 'out_of_reach' : 'not_present', ...(log ? { detail: '~/.gbrain/facts.write_failures.jsonl mentions the claim; edit it by hand if needed.' } : {}) },+ ];+}++/** Same-model nearest neighbours of the purged fact's embedding: paraphrase candidates, never a gate. */+async function vectorProbe(engine: BrainEngine, target: PurgeTarget): Promise<Record<string, unknown>> {+ if (!target.embedding || !target.embedding_model) return { status: 'skipped', reason: 'no_embedding', gate: false };+ try {+ const rows = await engine.executeRaw<{ id: number; similarity: number; contains_claim: boolean }>(`SELECT id,(1-(embedding <=> $1::halfvec))::float8 AS similarity,+ strpos(gbrain_fact_normalize(fact),gbrain_fact_normalize($4))>0 AS contains_claim+ FROM facts WHERE source_id=$2 AND embedding_model=$3 AND embedding IS NOT NULL+ ORDER BY embedding <=> $1::halfvec LIMIT 5`, [target.embedding, target.source_id, target.embedding_model, target.fact]);+ return { status: 'checked', gate: false, model: target.embedding_model,+ candidates: rows.map(r => ({ fact_id: Number(r.id), similarity: Math.round(Number(r.similarity) * 1000) / 1000, contains_claim: r.contains_claim === true })),+ note: 'Nearest same-model facts are possible rewordings for the user to review; a neighbour always exists, so this is not a residual count.' };+ } catch {+ return { status: 'skipped', reason: 'model_or_dimension_mismatch', gate: false };+ }+}++/** 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> {+ const { target, plan, dryRun } = input;+ const deadline = performance.now() + probeLimits.totalMs;+ const claim = target.fact, needle = claim.toLowerCase(), src = target.source_id;+ const removed = input.removed ?? {};+ const stores: StoreReport[] = [];+ const swept = async (store: string, sql: string, params: unknown[], planned: number, removedCount: number | undefined, onRemaining: Omit<StoreReport, 'store'> = { status: 'incomplete' }) => {+ if (dryRun) { stores.push({ store, status: planned ? 'would_remove' : 'not_present', removed: planned }); return; }+ const result = await boundedCount(engine, sql, params, deadline);+ if ('unverified' in result) stores.push({ store, status: 'unverified', reason: result.unverified, removed: removedCount ?? 0 });+ else if (result.count) stores.push({ store, removed: removedCount ?? 0, remaining: result.count, ...onRemaining });+ else stores.push({ store, status: removedCount ? 'deleted' : 'not_present', removed: removedCount ?? 0 });+ };+ await swept('facts', `SELECT 1 FROM facts WHERE source_id=$1 AND visibility=$2 AND gbrain_fact_fingerprint(fact)=$3 AND ($4='*' OR entity_slug=$4)`,+ [src, target.visibility, target.fact_hash, plan.subject], plan.factIds.length, removed.facts);+ await swept('takes', `SELECT 1 FROM takes k JOIN pages p ON p.id=k.page_id WHERE p.source_id=$1 AND gbrain_fact_fingerprint(k.claim)=$2 AND ($3='*' OR p.slug=$3)`,+ [src, target.fact_hash, plan.subject], plan.takes.length, removed.takes);+ const prose = { status: 'out_of_scope' as const, reason: 'source_prose', detail: 'The claim text survives outside a facts fence (page prose); purge the page or edit it to remove it.' };+ await swept('pages', `SELECT 1 FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND (strpos(lower(compiled_truth),$2)>0 OR strpos(lower(timeline),$2)>0)`,+ [src, needle], plan.pages.length, removed.pages, prose);+ await swept('content_chunks', `SELECT 1 FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.source_id=$1 AND strpos(lower(c.chunk_text),$2)>0`,+ [src, needle], plan.pages.length, removed.chunks, prose);+ await swept('page_versions', `SELECT 1 FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1+ AND (strpos(lower(v.compiled_truth),$2)>0 OR strpos(lower(COALESCE(v.timeline,'')),$2)>0)`,+ [src, needle], plan.versions, removed.page_versions, { ...prose, items: (input.prose ?? []).slice(0, 20) });+ await swept('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)`,+ [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);+ 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',+ removed: plan.derived.rows.length, ...(plan.derived.truncated ? { reason: 'derivation_walk_bound' } : {}),+ ...(plan.derived.rows.length ? { detail: 'Model-derived rows built from this fact are hidden and marked needs_rederive; they are not counted as removed text.' } : {}) });+ const [legacy] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages p WHERE p.source_id=$1 AND p.deleted_at IS NULL+ AND (p.type='atom' OR p.frontmatter->>'dream_generated'='true')+ 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.` });+ 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));+ }+ const [other] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM facts WHERE source_id=$1 AND gbrain_fact_fingerprint(fact)=$2+ AND NOT (visibility=$3 AND ($4='*' OR entity_slug=$4))`, [src, target.fact_hash, target.visibility, plan.subject]);+ const files = await pageFilePaths(engine, src, plan.pages.map(page => page.page_id));+ stores.push(...onDiskReports(files.files, claim, dryRun));+ const residuals: StoreReport[] = [];+ if (files.root && files.paths.length) residuals.push(await gitResidualCommits(files.root, files.paths, claim));+ for (const r of OUT_OF_REACH_RESIDUALS) {+ if (r.store === 'git_history' && residuals.length) continue;+ const detail = r.store === 'database_physical' ? `${r.detail}${engine.kind === 'pglite' ? (input.vacuum ? ' VACUUM ran on the touched tables; filesystem blocks and snapshots may still hold old pages.' : ' PGLite has no autovacuum; rerun with --vacuum to compact the touched tables.') : ' On Postgres the operator runs VACUUM; WAL archives, replicas and PITR windows are outside gbrain.'}` : r.detail;+ residuals.push({ store: r.store, status: 'out_of_reach', detail });+ }+ if (Number(other?.n ?? 0)) residuals.push({ store: 'facts_other_scope', status: 'out_of_scope', reason: plan.subject === '*' ? 'other_visibility' : 'other_subject', remaining: Number(other.n),+ detail: `${other.n} fact row(s) state the same claim about another entity or at another visibility; rerun with --all-subjects to purge every entity's copy.` });+ residuals.push(...stores.filter(s => s.reason === 'source_prose' || s.reason === 'probed_reported' || s.store === 'canonical_markdown' && s.status === 'out_of_scope'));+ if (input.vacuum && !dryRun && engine.kind === 'pglite') await engine.executeRaw('VACUUM facts, takes, pages, content_chunks, page_versions, persistence_requests, query_cache').catch(() => undefined);+ const next = dryRun+ ? ['Review the residuals with the user, then confirm with the token printed above (gbrain forget <id> --purge asks for it on a terminal).']+ : ['Poll completion with gbrain forget --purge --status --request-id <request_id> until it reports complete.'];+ return {+ summary: dryRun ? 'Dry run: nothing was removed. Counts are what the purge would remove from live stores.'+ : 'Removed from live stores. Residuals below are copies purge cannot reach; this is not physical erasure.',+ fact_id: target.id, fact_hash: target.fact_hash, hash8: target.fact_hash.slice(0, 8), source_id: src, subject: plan.subject, visibility: target.visibility,+ residuals, stores, vector_probe: await vectorProbe(engine, target), next,+ ...(engine.kind === 'postgres' && !dryRun ? { tell_user_to_run: { argv: ['psql', '-c', 'VACUUM (VERBOSE) facts, takes, pages, content_chunks, page_versions, 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):+ 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,+ jsonb_array_length(COALESCE(data->'parked','[]'::jsonb))>0 AS parked FROM persistence_effects WHERE request_id=$1::uuid ORDER BY kind`, [row.id]);+ const purge = (row.outcome as { purge?: { fact_hash?: string; subject?: string } } | null)?.purge;+ let fingerprint: Record<string, number> | undefined;+ if (purge?.fact_hash) {+ const [probe] = await engine.executeRaw<{ facts: number; takes: number }>(`SELECT+ (SELECT count(*)::int FROM facts WHERE source_id=$1 AND gbrain_fact_fingerprint(fact)=$2 AND ($3='*' OR entity_slug=$3)) AS facts,+ (SELECT count(*)::int 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)) AS takes`,+ [row.source_id, purge.fact_hash, purge.subject ?? '*']);+ fingerprint = { facts: Number(probe?.facts ?? 0), takes: Number(probe?.takes ?? 0) };+ }+ const failed = effects.some(e => e.state === 'failed' || e.parked);+ const sweptResidual = receipt?.stores.some(s => s.status === 'incomplete') || (fingerprint && (fingerprint.facts || fingerprint.takes));+ const pending = effects.some(e => e.state !== 'committed');+ const completion: PurgeCompletion = failed || sweptResidual ? 'incomplete' : pending ? 'committed' : 'complete';+ return { completion, effects: effects.map(({ kind, state, error_code }) => ({ kind, state, error_code })),+ exit_code: completion === 'complete' ? 0 : completion === 'committed' ? 10 : 75, ...(fingerprint ? { fingerprint_probe: fingerprint } : {}) };+}diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.tsnew file mode 100644index 0000000000..56be613ccc--- /dev/null+++ b/src/core/facts/purge.ts@@ -0,0 +1,334 @@+/**+ * `purge_fact` (#5575 Part C): remove a fact's text from every live store the+ * deletion inventory sweeps, block its return, and hand back a receipt that+ * lists residuals first.+ *+ * Purge is a separate owner-only operation, never a mode of the frozen+ * `forget` verb (MEMORY_VERBS_v1: forget expires, never deletes). It runs only+ * from the trusted local CLI on the brain host, directly or through the+ * resident owner's 0600 socket. Its journaled intent holds the fact id, the+ * claim fingerprint and the reason, never the claim text.+ *+ * One transaction, in the global lock order (source -> counters -> requests ->+ * page keys -> facts): a text-free tombstone (fact_purges, take_purges), the+ * hidden derived rows (derivation_inputs -> needs_rederive), the deleted fact+ * and verbatim take rows, fence rows dropped from the stored page bodies and+ * from every page_versions snapshot, chunks deleted for rebuild, carried+ * request intents redacted, legacy query cache rows and the fact's P8 review+ * rows dropped. Post-commit effects rewrite the canonical file and commit it+ * as `gbrain: purge fact <hash8>`; verification then probes each store.+ */++import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import type { OperationContext } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import { contentHash, rowToPage } from '../utils.ts';+import { discoverWithdrawalTargets, withdrawalDiscoveryFailure } from './withdrawal-discovery.ts';+import { dropPurgedFenceRows } from './purge-overlay.ts';+import { derivedRowsFrom, hideDerivedRows, type DerivationRef } from './derivation-inputs.ts';+import { initializeLocalPersistence, requestPrincipalForContext } from '../persistence/page-mutations.ts';+import { authorizeStoredRequest, submissionAuthority } from '../persistence/authority.ts';+import { admitWriteInTransaction, assertPageRequestIdentity, assertReplayIntent, completeWrite, getWriteRequest, intentDigest, lockCounters } from '../persistence/journal.ts';+import { assertPersistenceAccepting } from '../persistence/service.ts';+import { declareDurablePersistence } from '../persistence/protocol.ts';+import { parseWriteRequestId } from '../persistence/preconditions.ts';+import { withCoordinatedWrite } from '../persistence/context.ts';+import { requestAttribution } from '../persistence/attribution.ts';+import { isTerminal, principalKey, type WriteRequest } from '../persistence/model.ts';+import { retryWriteAdmission } from '../persistence/admission-retry.ts';+import { findRequestsCarrying, redactionCounterKeys, redactRequestIntents } from '../persistence/intent-redaction.ts';+import { rebuildPendingPageProjections } from '../page-state/projections.ts';+import { purgeCompletion, verifyFactPurge, type PurgeReceipt, type StoreCount } from './purge-verify.ts';++export const PURGE_OPERATION = 'purge_fact';+const PURGE_TERMINAL_RESERVATION = 64 * 1024;++export interface PurgeTarget {+ id: number; source_id: string; visibility: 'private' | 'world'; fact: string; entity_slug: string | null;+ source_markdown_slug: string | null; fact_hash: string; embedding: string | null; embedding_model: string | null;+}++/** The scope a purge covers: every same-fingerprint fact row in the source, visibility and subject. */+export interface PurgePlan {+ subject: string;+ factIds: number[];+ takes: Array<{ id: number; page_id: number }>;+ pages: Array<{ slug: string; page_id: number; revision: string }>;+ versions: number;+ requests: Awaited<ReturnType<typeof findRequestsCarrying>>;+ derived: Awaited<ReturnType<typeof derivedRowsFrom>>;+ reviewRows: number;+ /** A digest of the target set; a confirmation binds to it. */+ revision: string;+}++/** The refusal every route but the trusted local CLI gets (same envelope on stdio, HTTP and thin clients). */+export function purgeHostOnly(id: unknown): OperationError {+ const ref = typeof id === 'string' || typeof id === 'number' ? String(id) : '<fact-id>';+ return opError('trusted_local_only', 'purge_fact runs only from the trusted local CLI on the brain host, not over MCP.',+ `Ask the user to run \`gbrain forget ${ref} --purge\` on the brain host. It prints a dry-run receipt first and asks before removing anything.`,+ { legacy_error: 'permission_denied', fix: { argv: ['gbrain', 'forget', ref, '--purge'], consent: ['destructive'], actor: 'user', requires_exclusive: false,+ why: 'Purge removes text from the brain and cannot be undone, so only the owner on the brain host may run it.' } });+}++function notFound(rawId: string): OperationError {+ return opError('fact_not_found', `No fact with id "${rawId}" in this source.`,+ 'Ids come from remember or recall. A purged fact no longer exists; check a purge with --status --request-id <id>.',+ { fix: readFix('Lists recent facts with their ids, read-only.', { argv: ['gbrain', 'recall', '--json'] }) });+}++async function loadTarget(engine: BrainEngine, id: number, sourceId: string): Promise<PurgeTarget | null> {+ const [row] = await engine.executeRaw<PurgeTarget>(`SELECT id,source_id,visibility,fact,entity_slug,source_markdown_slug,+ gbrain_fact_fingerprint(fact) AS fact_hash,embedding::text AS embedding,embedding_model+ FROM facts WHERE id=$1 AND source_id=$2`, [id, sourceId]);+ return row ? { ...row, id: Number(row.id) } : null;+}++/** Read-only: everything a purge of `target` would touch. Inside the purge transaction it runs under the source lock. */+export async function planFactPurge(engine: BrainEngine, target: PurgeTarget, allSubjects: boolean): Promise<PurgePlan> {+ const subject = allSubjects ? '*' : target.entity_slug ?? '*';+ const facts = await engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE source_id=$1 AND visibility=$2+ AND gbrain_fact_fingerprint(fact)=$3 AND ($4='*' OR entity_slug=$4) ORDER BY id`, [target.source_id, target.visibility, target.fact_hash, subject]);+ const factIds = facts.map(f => Number(f.id));+ const takes = (await engine.executeRaw<{ id: number; page_id: number }>(`SELECT DISTINCT k.id,k.page_id FROM takes k JOIN pages p ON p.id=k.page_id+ WHERE p.source_id=$1 AND (k.id IN (SELECT consolidated_into FROM facts WHERE id=ANY($2::bigint[]) AND consolidated_into IS NOT NULL)+ OR (gbrain_fact_fingerprint(k.claim)=$3 AND ($4='*' OR p.slug=$4))) ORDER BY k.id`,+ [target.source_id, factIds, target.fact_hash, subject])).map(t => ({ id: Number(t.id), page_id: Number(t.page_id) }));+ const discovered = await discoverWithdrawalTargets(engine, target.source_id,+ [{ visibility: target.visibility, fact_hash: target.fact_hash, subject, claim: target.fact }]).catch(withdrawalDiscoveryFailure);+ const known = new Set(discovered.map(p => p.page_id));+ const extra = takes.map(t => t.page_id).filter(id => !known.has(id));+ const takePages = extra.length ? await engine.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 id=ANY($2::int[])', [target.source_id, extra]) : [];+ const pages = [...discovered, ...takePages.map(p => ({ ...p, page_id: Number(p.page_id) }))].sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0);+ const [versions] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_id+ WHERE p.source_id=$1 AND (strpos(lower(v.compiled_truth),$2)>0 OR strpos(lower(COALESCE(v.timeline,'')),$2)>0)`, [target.source_id, target.fact.toLowerCase()]);+ const 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`,+ [target.source_id, factIds.map(String), factIds]);+ 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 };+}++/** 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;+ const [blocked] = await tx.executeRaw<{ request_id: string; slug: string; state: string }>(`SELECT r.request_id::text,r.slug,r.state FROM persistence_requests r+ WHERE r.source_id=$1 AND r.id<>$3::uuid AND r.slug=ANY($2::text[]) AND (r.recovery IS NOT NULL OR r.state IN ('queued','running','recovering'))+ UNION ALL SELECT r.request_id::text,COALESCE(t->>'slug',r.slug),e.state FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id+ CROSS JOIN LATERAL jsonb_array_elements(COALESCE(e.data->'targets','[]'::jsonb)) t+ WHERE e.source_id=$1 AND e.request_id<>$3::uuid AND e.kind='withdrawal-mirror' AND (e.state<>'committed' OR e.recovery IS NOT NULL) AND t->>'slug'=ANY($2::text[])+ LIMIT 1`, [sourceId, pages.map(p => p.slug), ownRequest]);+ if (blocked) throw opError('purge_blocked_pending_recovery', 'A page this purge rewrites has a pending write or recovery, so nothing was purged.',+ `Request ${blocked.request_id} on ${blocked.slug} is ${blocked.state} or still recovering; its publication must finish first. Retry the purge with the same request id once it is final.`,+ { fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Shows the source\'s pending and recovering writes, read-only.' } });+}++/** 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[]> {+ 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)]);+ const rewritten: string[] = [];+ for (const row of rows) {+ const page = rowToPage(row);+ const compiled = await dropPurgedFenceRows(tx, sourceId, page.compiled_truth, page.slug);+ const timeline = await dropPurgedFenceRows(tx, sourceId, page.timeline ?? '', page.slug);+ if (compiled === page.compiled_truth && timeline === (page.timeline ?? '')) continue;+ const hash = contentHash({ ...page, compiled_truth: compiled, timeline, tags: row.purge_tags as string[] });+ await tx.executeRaw(`UPDATE pages SET compiled_truth=$3,timeline=$4,content_hash=$5,updated_at=now(),text_projection_revision=NULL,embedding_signature=NULL+ WHERE source_id=$1 AND id=$2`, [sourceId, page.id, compiled, timeline, hash]);+ rewritten.push(page.slug);+ }+ return rewritten;+}++/** Redact the row from every retained snapshot that carries the claim; returns redacted and still-carrying (prose) counts. */+async function redactPageVersions(tx: BrainEngine, sourceId: string, claim: string, pageIds: number[]): Promise<{ redacted: number; prose: Array<{ slug: string; version_id: number }> }> {+ const needle = claim.toLowerCase();+ const rows = await tx.executeRaw<{ id: number; slug: string; compiled_truth: string; timeline: string | null }>(`SELECT v.id,p.slug,v.compiled_truth,v.timeline+ FROM page_versions v JOIN pages p ON p.id=v.page_id+ WHERE p.source_id=$1 AND (v.page_id=ANY($3::int[]) OR strpos(lower(v.compiled_truth),$2)>0 OR strpos(lower(COALESCE(v.timeline,'')),$2)>0)+ ORDER BY v.id LIMIT 5000`, [sourceId, needle, pageIds]);+ let redacted = 0;+ const prose: Array<{ slug: string; version_id: number }> = [];+ for (const v of rows) {+ const compiled = await dropPurgedFenceRows(tx, sourceId, v.compiled_truth, v.slug);+ const timeline = await dropPurgedFenceRows(tx, sourceId, v.timeline ?? '', v.slug);+ if (compiled !== v.compiled_truth || timeline !== (v.timeline ?? '')) {+ await tx.executeRaw('UPDATE page_versions SET compiled_truth=$2,timeline=$3 WHERE id=$1', [v.id, compiled, timeline]);+ redacted++;+ }+ if (compiled.toLowerCase().includes(needle) || timeline.toLowerCase().includes(needle)) prose.push({ slug: v.slug, version_id: Number(v.id) });+ }+ return { redacted, prose };+}++interface PurgeParams { id: number; rawId: string; sourceId: string; reason: string | null; allSubjects: boolean; requestId: string }++function parseParams(ctx: OperationContext, params: Record<string, unknown>): PurgeParams {+ const rawId = String(params.id ?? '').trim();+ const id = Number(rawId);+ if (!Number.isSafeInteger(id) || id <= 0) throw notFound(rawId);+ const reason = typeof params.reason === 'string' && params.reason.trim() ? params.reason.trim().slice(0, 200) : null;+ return { id, rawId, reason, allSubjects: params.all_subjects === true,+ sourceId: typeof params.source_id === 'string' ? params.source_id : ctx.sourceId ?? 'default',+ requestId: parseWriteRequestId(params.request_id) ?? randomUUID() };+}++/** `--match`: candidate facts for a text, so the owner picks an id (purge always needs a ref). Owner-only output. */+async function matchCandidates(engine: BrainEngine, sourceId: string, text: string): Promise<Record<string, unknown>> {+ const rows = await engine.executeRaw<{ id: number; entity_slug: string | null; visibility: string; expired: boolean; fact: string }>(`SELECT id,entity_slug,visibility,+ expired_at IS NOT NULL AS expired,left(fact,160) AS fact FROM facts WHERE source_id=$1 AND strpos(lower(fact),lower($2))>0 ORDER BY id LIMIT 25`, [sourceId, text]);+ return { action: 'purge_fact', match: true, candidates: rows.map(r => ({ ...r, id: Number(r.id) })),+ next: rows.length ? 'Pick one id and run gbrain forget <id> --purge; --match never purges.' : 'No fact in this source contains that text.' };+}++/** `--status`: the stored receipt and the current completion of an earlier purge request. Never re-reads claim text. */+async function purgeStatus(ctx: OperationContext, requestId: string): Promise<Record<string, unknown>> {+ const principal = await requestPrincipalForContext(ctx);+ const row = await getWriteRequest(ctx.engine, principal, requestId);+ if (!row || row.operation !== PURGE_OPERATION) throw opError('not_found', `No purge request ${requestId} for this caller.`,+ 'Pass the --request-id a purge printed. Status reads only purges this CLI submitted.');+ return { ...(row.outcome ?? {}), request_id: row.request_id, state: row.state, ...await purgeCompletion(ctx.engine, row) };+}++export function purgeConfirmToken(target: Pick<PurgeTarget, 'fact_hash'>): string { return target.fact_hash.slice(0, 8); }++/**+ * The purge_fact handler. `dry_run` (or ctx.dryRun) returns the receipt with+ * would-remove counts and the confirmation token; a real run needs+ * `confirm` equal to that token (the fingerprint's first 8 hex), and an+ * `expected_revision` from the dry run when given must still match.+ */+export async function submitPurgeFactMutation(ctx: OperationContext, params: Record<string, unknown>): Promise<Record<string, unknown>> {+ if (ctx.remote !== false) throw purgeHostOnly(params.id);+ assertPersistenceAccepting(ctx.engine);+ await initializeLocalPersistence(ctx);+ if (params.status === true) {+ const requestId = parseWriteRequestId(params.request_id);+ if (!requestId) throw opError('invalid_params', '--status needs --request-id.', 'Pass the request id the purge printed: gbrain forget --purge --status --request-id <uuid>.');+ return purgeStatus(ctx, requestId);+ }+ const sourceIdForMatch = typeof params.source_id === 'string' ? params.source_id : ctx.sourceId ?? 'default';+ if (typeof params.match === 'string') return matchCandidates(ctx.engine, sourceIdForMatch, params.match);+ const p = parseParams(ctx, params);+ const principal = await requestPrincipalForContext(ctx);+ const callerIntent = { id: p.rawId, reason: p.reason, all_subjects: p.allSubjects };+ const dryRun = ctx.dryRun === true || params.dry_run === true;+ if (!dryRun) {+ await assertPageRequestIdentity(ctx.engine, principal, p.requestId);+ const prior = await getWriteRequest(ctx.engine, principal, p.requestId);+ if (prior) {+ assertReplayIntent(prior, intentDigest({ operation: PURGE_OPERATION, sourceId: p.sourceId, slug: prior.slug, callerIntent }));+ return { ...(prior.outcome ?? {}), request_id: prior.request_id, state: prior.state, replayed: true, ...await purgeCompletion(ctx.engine, prior) };+ }+ }+ const target = await loadTarget(ctx.engine, p.id, p.sourceId);+ if (!target) throw notFound(p.rawId);+ const token = purgeConfirmToken(target);+ const plan = await planFactPurge(ctx.engine, target, p.allSubjects);+ if (dryRun) {+ const receipt = await verifyFactPurge(ctx.engine, { target, plan, dryRun: true });+ return { dry_run: true, action: 'purge_fact', request_id: p.requestId, confirm_token: token, expected_revision: plan.revision, ...receipt };+ }+ if (params.confirm !== token) throw opError('confirmation_required', 'Purge needs a confirmation bound to this fact.',+ `Run the dry run first (gbrain forget ${p.rawId} --purge --dry-run), review its receipt with the user, then confirm with the fact's token (the first 8 characters of its fingerprint).`,+ { fix: { argv: ['gbrain', 'forget', p.rawId, '--purge', '--dry-run', '--json'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Prints what the purge would remove and the confirmation token, without changing anything.' } });+ const { similarActiveAfterForget } = await import('./similar-active.ts');+ const similar = await similarActiveAfterForget(ctx.engine, { sourceId: p.sourceId, factId: p.id, remote: false, committed: true, semanticReview: false })+ .then(s => ({ ...s, candidates: s.candidates.filter(c => !plan.factIds.includes(Number(c.fact_id))) })).catch(() => null);++ let committedPlan = plan;+ let rewritten: string[] = [];+ let counts: StoreCount = {};+ let prose: Array<{ slug: string; version_id: number }> = [];+ 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]);+ if (!source || source.archived) throw opError('source_changed', 'The purge source is not active.', `Source ${p.sourceId} is archived or missing, so nothing was purged.`);+ const prior = await getWriteRequest(tx, principal, p.requestId);+ if (prior) {+ await authorizeStoredRequest(tx, prior, true);+ assertReplayIntent(prior, intentDigest({ operation: PURGE_OPERATION, sourceId: p.sourceId, slug: prior.slug, callerIntent }));+ return prior;+ }+ const current = await loadTarget(tx, p.id, p.sourceId);+ if (!current) throw notFound(p.rawId);+ committedPlan = await planFactPurge(tx, current, p.allSubjects);+ if (typeof params.expected_revision === 'string' && params.expected_revision !== committedPlan.revision) {+ throw opError('revision_conflict', 'What this purge would remove changed since its dry run.',+ 'Run the dry run again, review the new receipt, and confirm that one.');+ }+ const slug = current.source_markdown_slug ?? current.entity_slug ?? 'memory/unattributed';+ await lockCounters(tx, ['brain', principalKey(principal), ...redactionCounterKeys(committedPlan.requests)]);+ const authority = await submissionAuthority({ ...ctx, engine: tx }, PURGE_OPERATION, p.sourceId, source.incarnation, slug);+ const admitted = await admitWriteInTransaction(tx, { principal, operation: PURGE_OPERATION, sourceId: p.sourceId, sourceIncarnation: source.incarnation,+ slug, requestId: p.requestId, callerIntent, intent: { ...callerIntent, fact_hash: current.fact_hash }, authority, terminalReservation: PURGE_TERMINAL_RESERVATION });+ if (isTerminal(admitted)) return admitted;+ return 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);+ 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}` });+ 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,$7) ON CONFLICT DO NOTHING`,+ [p.sourceId, current.visibility, plan.subject, current.fact_hash, admitted.id, `${principal.kind}:${principal.id}`, p.reason]);+ await tx.executeRaw(`INSERT INTO take_purges(source_id,subject,claim_hash,request_id) VALUES ($1,$2,$3,$4::uuid) ON CONFLICT DO NOTHING`,+ [p.sourceId, plan.subject, current.fact_hash, admitted.id]);+ const takes = plan.takes.length ? (await tx.executeRaw('DELETE FROM takes WHERE id=ANY($1::bigint[]) RETURNING id', [plan.takes.map(t => t.id)])).length : 0;+ const ids = plan.factIds;+ const review = (await tx.executeRaw(`DELETE FROM decide_review_queue WHERE source_id=$1 AND (a_ref=ANY($2::text[]) OR b_ref=ANY($2::text[])) RETURNING 1`, [p.sourceId, ids.map(String)])).length+ + (await tx.executeRaw(`DELETE FROM decide_review_proposals WHERE source_id=$1 AND (a_ref=ANY($2::text[]) OR b_ref=ANY($2::text[])) RETURNING 1`, [p.sourceId, ids.map(String)])).length+ + (await tx.executeRaw(`DELETE FROM decide_proposals WHERE source_id=$1 AND (new_fact_id=ANY($2::bigint[]) OR old_fact_id=ANY($2::bigint[])) RETURNING 1`, [p.sourceId, ids])).length;+ const loops = (await tx.executeRaw('DELETE FROM open_loops WHERE source_id=$1 AND fact_id=ANY($2::bigint[]) RETURNING 1', [p.sourceId, ids])).length;+ const proposals = (await tx.executeRaw('DELETE FROM take_proposals WHERE source_id=$1 AND gbrain_fact_fingerprint(claim_text)=$2 RETURNING 1', [p.sourceId, current.fact_hash])).length;+ const notices = (await tx.executeRaw(`UPDATE core_edit_notices SET base_text=NULL WHERE source_id=$1 AND strpos(lower(base_text),$2)>0 RETURNING 1`,+ [p.sourceId, current.fact.toLowerCase()])).length;+ const facts = (await tx.executeRaw('DELETE FROM facts WHERE id=ANY($1::bigint[]) AND source_id=$2 RETURNING id', [ids, p.sourceId])).length;+ rewritten = await rewritePageBodies(tx, p.sourceId, plan.pages);+ const pageIds = plan.pages.map(page => page.page_id);+ const chunks = pageIds.length ? (await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=ANY($1::integer[]) RETURNING 1', [pageIds])).length : 0;+ const versions = await redactPageVersions(tx, p.sourceId, current.fact, pageIds);+ prose = versions.prose;+ const cache = (await tx.executeRaw('DELETE FROM query_cache RETURNING 1')).length;+ const pages = pageIds.length ? await tx.executeRaw<{ id: number; slug: string; knowledge_revision: string }>(+ 'SELECT id,slug,knowledge_revision::text AS knowledge_revision FROM pages WHERE source_id=$1 AND id=ANY($2::int[]) ORDER BY slug', [p.sourceId, pageIds]) : [];+ await tx.executeRaw(`INSERT INTO persistence_effects(request_id,kind,data,source_id,source_incarnation,worktree_id)+ SELECT $1::uuid,k.kind,$3::text::jsonb,s.id,s.incarnation,b.worktree_id+ FROM sources s LEFT JOIN persistence_source_bindings b ON b.source_id=s.id AND b.source_incarnation=s.incarnation+ CROSS JOIN (VALUES ('withdrawal-mirror'),('git'),('embedding')) AS k(kind)+ WHERE s.id=$2 ON CONFLICT(request_id,kind) DO NOTHING`, [admitted.id, p.sourceId, JSON.stringify({ version: 2, mode: 'purge',+ commit_subject: `gbrain: purge fact ${token}`, commit_line: `purge fact ${token}`,+ targets: pages.map(page => ({ slug: page.slug, page_id: Number(page.id), revision: page.knowledge_revision })) })]);+ counts = { facts, takes, chunks, page_versions: versions.redacted, pages: rewritten.length, persistence_requests: intents,+ query_cache: cache, decide_review: review, open_loops: loops, take_proposals: proposals, core_edit_notices: notices,+ derived_hidden: Object.values(derived.hidden).reduce((a, b) => a + b, 0) };+ 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 },+ persistence: { mode: 'database' } });+ }, requestAttribution(admitted));+ }), 30_000);+ // Chunks of rewritten pages were deleted; rebuild them from the purged bodies before acknowledging.+ const slugs = committedPlan.pages.map(page => page.slug);+ for (let start = 0; start < slugs.length; start += 100) {+ 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 };+ const receipt: PurgeReceipt = await verifyFactPurge(ctx.engine, { target, plan: committedPlan, dryRun: false, removed: counts, prose,+ vacuum: params.vacuum === true });+ return { ...receipt, request_id: row.request_id, state: row.state, similar_active: similar, ...await purgeCompletion(ctx.engine, row as WriteRequest, receipt) };+}diff --git a/src/core/operations.ts b/src/core/operations.tsindex e81e5329fd..448017c6dd 100644--- a/src/core/operations.ts+++ b/src/core/operations.ts@@ -107,6 +107,7 @@ import { transcriptsOperations } from './ops/transcripts.ts';import { connectorsOperations } from './ops/connectors.ts';import { sourcesOperations } from './ops/sources.ts';import { factsOperations } from './ops/facts.ts';+import { purgeOperations } from './ops/purge.ts';import { codeIntelOperations } from './ops/code-intel.ts';import { embeddingMigrationOperations } from './ops/embedding-migration.ts';import { imageOperations } from './ops/image.ts';@@ -204,7 +205,7 @@ export const operations: Operation[] = [...entityIdentityOperations,// v0.31: hot memory (extract_facts, recall, context_pack, delta,// forget_fact) — ops/facts.ts- ...factsOperations,+ ...factsOperations, ...purgeOperations,// v0.32.6: contradiction probe MCP surface (M3) — ops/insights.tsfind_contradictions,// v0.33: expertise + relationship-proximity routing — ops/insights.tsdiff --git a/src/core/ops/purge.ts b/src/core/ops/purge.tsnew file mode 100644index 0000000000..7b7393d639--- /dev/null+++ b/src/core/ops/purge.ts@@ -0,0 +1,77 @@+/**+ * Owner-only purge operations (#5575 Part C). Every one is `cliOnly`: an MCP+ * session (stdio or HTTP, including one hosted by the resident owner process)+ * gets `trusted_local_only` with the exact host command; the local CLI reaches+ * them directly or over the owner's 0600 socket (`LOCAL_CLI_OWNER_OPERATIONS`).+ */++import { WRITE_REQUEST_PARAM } from '../persistence/params.ts';+import { type Operation } from './contract.ts';++const purge_fact: Operation = {+ name: 'purge_fact',+ idempotent: true,+ outputRedaction: 'no_stored_text',+ description: 'Owner-only, trusted local CLI on the brain host (`gbrain forget <id> --purge`). Removes a fact\'s claim from every live store the deletion inventory sweeps (fact rows, verbatim takes, fence rows in page bodies and versions, chunks, stored write intents, review rows), blocks it from returning (text-free tombstone), hides model-derived rows for re-derivation, and returns a receipt listing residuals first. Not a mode of forget: forget expires, purge deletes. dry_run returns the receipt and a confirmation token; a real run needs confirm equal to that token. Purge removes content from live stores; it never claims physical erasure.',+ params: {+ request_id: WRITE_REQUEST_PARAM,+ id: { type: 'number', description: 'Fact id to purge (from recall or remember).' },+ reason: { type: 'string', description: 'Optional short reason stored in the text-free purge ledger.' },+ all_subjects: { type: 'boolean', description: 'Purge the same claim about every entity in the source (default: only the fact\'s own entity, like forget).' },+ dry_run: { type: 'boolean', description: 'Return the receipt with would-remove counts and the confirmation token; changes nothing.' },+ confirm: { type: 'string', description: 'The confirmation token from the dry run (first 8 hex of the claim fingerprint).' },+ expected_revision: { type: 'string', description: 'The expected_revision from the dry run; refuses when the target set changed since.' },+ match: { type: 'string', description: 'List candidate fact ids whose text contains this; never purges.' },+ status: { type: 'boolean', description: 'Report the stored receipt and completion of the purge named by request_id.' },+ vacuum: { type: 'boolean', description: 'PGLite only: VACUUM the touched tables after the purge.' },+ source_id: { type: 'string', description: 'Source holding the fact (default: the routed source).' },+ },+ mutating: true,+ scope: 'admin',+ cliOnly: { argv: ['gbrain', 'forget', '<id>', '--purge'] },+ handler: async (ctx, p) => {+ const { submitPurgeFactMutation } = await import('../facts/purge.ts');+ return submitPurgeFactMutation(ctx, p);+ },+ cliHints: { name: 'purge-fact', hidden: true },+};++const list_page_purges: Operation = {+ name: 'list_page_purges',+ idempotent: true,+ outputRedaction: 'no_stored_text',+ description: 'Owner-only (`gbrain pages purges list`). Lists page purge tombstones: slug, content hash prefix, request and time. Never returns content.',+ params: {+ source_id: { type: 'string', description: 'Limit to one source.' },+ limit: { type: 'number', description: 'Maximum rows (default 100).' },+ },+ mutating: false,+ scope: 'admin',+ cliOnly: { argv: ['gbrain', 'pages', 'purges', 'list'] },+ handler: async (ctx, p) => {+ const { listPagePurges } = await import('../persistence/page-purge.ts');+ return listPagePurges(ctx, p);+ },+ cliHints: { name: 'list-page-purges', hidden: true },+};++const unpurge_page: Operation = {+ name: 'unpurge_page',+ idempotent: true,+ outputRedaction: 'no_stored_text',+ description: 'Owner-only (`gbrain pages unpurge <slug>`). Clears the purge tombstones recorded for a slug so the same content can be imported again. Restores nothing.',+ params: {+ slug: { type: 'string', required: true, description: 'Slug of the purged page.' },+ source_id: { type: 'string', description: 'Source of the purged page (default: the routed source).' },+ },+ mutating: true,+ scope: 'admin',+ cliOnly: { argv: ['gbrain', 'pages', 'unpurge', '<slug>'] },+ handler: async (ctx, p) => {+ const { unpurgePage } = await import('../persistence/page-purge.ts');+ return unpurgePage(ctx, p);+ },+ cliHints: { name: 'unpurge-page', hidden: true },+};++export const purgeOperations: Operation[] = [purge_fact, list_page_purges, unpurge_page];diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex e0521d998f..41f1dd660b 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -254,7 +254,7 @@ async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding:await finishPage(engine, effect, snapshot, { git: 'skipped', reason: 'db_only' });return;}- const result = await publishGitEffect(root, relative(root, path).split(sep).join('/'), opts.signal, hardened);+ const result = await publishGitEffect(root, relative(root, path).split(sep).join('/'), opts.signal, hardened, gitCommitNote(effect));if (result.reason === 'durability_not_enabled') await completeEffect(engine, effect, result);else await finishPage(engine, effect, snapshot, result);}diff --git a/src/core/persistence/intent-redaction.ts b/src/core/persistence/intent-redaction.tsnew file mode 100644index 0000000000..211e2e74e6--- /dev/null+++ b/src/core/persistence/intent-redaction.ts@@ -0,0 +1,85 @@+/**+ * Accounting-aware intent redaction for purge (#5575 ENG-6). The journal keeps+ * a request's normalized `intent` until receipt compaction; purge must remove+ * claim text from it sooner. This primitive applies compaction's accounting+ * to an explicit request set:+ *+ * - every affected request is locked (counters first, then request rows, the+ * global lock order);+ * - a request that is queued, running, recovering or carries a recovery record+ * refuses the whole purge with retryable `purge_blocked_pending_recovery`,+ * because its intent is still the input of a pending publication;+ * - a terminal request has `intent` (and `error_message`) nulled, is marked+ * compacted, and its terminal byte reservation shrinks to what the retained+ * receipt still needs, released from its counters exactly as compaction does.+ *+ * Replay keys on the stored `digest`, so a later retry of a redacted request+ * returns its stored outcome without re-executing.+ */++import { opError } from '../ops/contract.ts';+import type { BrainEngine } from '../engine.ts';+import { jsonBytes } from './digest.ts';+import { lockCounters } from './journal.ts';+import { isTerminal, principalKey, requestPrincipal, type WriteRequest } from './model.ts';++export interface IntentRedactionTarget { id: string; principal_kind: string; principal_id: string }++/** Requests in `sourceId` whose stored intent or error text carries `claim`, bounded. Owner-only; never returns the text. */+export async function findRequestsCarrying(engine: BrainEngine, sourceId: string, claim: string, limit = 10_000): Promise<IntentRedactionTarget[]> {+ const needle = claim.toLowerCase();+ // The claim as it appears inside a JSON string (quotes and backslashes escaped), lowercased.+ const jsonNeedle = JSON.stringify(claim).slice(1, -1).toLowerCase();+ return engine.executeRaw<IntentRedactionTarget>(`SELECT id::text AS id,principal_kind,principal_id 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))+ OR (error_message IS NOT NULL AND strpos(lower(error_message),$2)>0))+ ORDER BY sequence LIMIT $4`, [sourceId, needle, jsonNeedle, limit]);+}++/** Requests in `sourceId` that target one of `slugs` and still hold an intent (page purge). */+export async function findRequestsForSlugs(engine: BrainEngine, sourceId: string, slugs: readonly string[], limit = 10_000): Promise<IntentRedactionTarget[]> {+ return engine.executeRaw<IntentRedactionTarget>(`SELECT id::text AS id,principal_kind,principal_id FROM persistence_requests+ WHERE source_id=$1 AND slug=ANY($2::text[]) AND NOT compacted AND intent IS NOT NULL ORDER BY sequence LIMIT $3`, [sourceId, [...slugs], limit]);+}++/** The counter keys an affected request set touches; lock them before admitting the purge's own request. */+export function redactionCounterKeys(targets: readonly IntentRedactionTarget[]): string[] {+ return [...new Set(targets.map(t => principalKey({ kind: t.principal_kind as WriteRequest['principal_kind'], id: t.principal_id })))];+}++/**+ * Redact the intents of `targets` inside the caller's transaction. The caller+ * already holds the counter locks (`redactionCounterKeys` plus 'brain').+ * `exclude` is the purge's own request id. Returns the number redacted.+ */+export async function redactRequestIntents(tx: BrainEngine, targets: readonly IntentRedactionTarget[], exclude?: string,+ opts: { skipPending?: boolean } = {}): Promise<number> {+ const ids = targets.map(t => t.id).filter(id => id !== exclude);+ if (!ids.length) return 0;+ await lockCounters(tx, ['brain', ...redactionCounterKeys(targets)]);+ const rows = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY id FOR UPDATE', [ids]);+ // A page purge leaves later queued writes for the slug in place (they fail on the missing page); a fact purge refuses.+ const blocked = opts.skipPending ? undefined : rows.find(row => !isTerminal(row) || row.recovery);+ if (blocked) {+ throw opError('purge_blocked_pending_recovery', 'A pending write still carries this content, so nothing was purged.',+ `Request ${blocked.request_id} (${blocked.operation} on ${blocked.slug}, state ${blocked.state}${blocked.recovery ? ', with a recovery record' : ''}) still needs its stored intent. `+ + 'Wait for it to finish or recover, then retry the purge with the same request id.',+ { fix: { argv: ['gbrain', 'write-request', '--', blocked.request_id], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Shows the blocking write\'s state, read-only; retry the purge once it is final.' } });+ }+ let redacted = 0;+ for (const current of rows) {+ if (current.compacted || !isTerminal(current) || current.recovery) continue;+ const [effects] = await tx.executeRaw<{ bytes: string }>(`SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0)::text AS bytes+ FROM persistence_effects WHERE request_id=$1::uuid`, [current.id]);+ const retained = Math.min(Number(current.terminal_reservation), jsonBytes(current.authority) + jsonBytes(current.outcome ?? {})+ + (current.error_detail ? jsonBytes(current.error_detail) : 0) + Number(effects.bytes) + 1024);+ await tx.executeRaw('UPDATE persistence_requests SET intent=NULL,compacted=true,error_message=NULL,terminal_reservation=$2 WHERE id=$1::uuid', [current.id, retained]);+ for (const key of ['brain', principalKey(requestPrincipal(current))]) {+ await tx.executeRaw('UPDATE persistence_counters SET terminal_bytes=terminal_bytes-$2 WHERE key=$1', [key, Number(current.terminal_reservation) - retained]);+ }+ redacted++;+ }+ return redacted;+}diff --git a/src/core/persistence/ipc.ts b/src/core/persistence/ipc.tsindex 3ddf613dfe..3d0f02ab86 100644--- a/src/core/persistence/ipc.ts+++ b/src/core/persistence/ipc.ts@@ -24,7 +24,15 @@ export const PERSISTENCE_IPC_OPERATIONS = ['get_skill_policy', 'set_skill_policy', 'get_skill_retention', 'prune_skill_revisions','retain_skill_revision', 'import_skill_proposal','add_tag', 'remove_tag', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'takes_remove',+ 'purge_fact', 'list_page_purges', 'unpurge_page',] as const;+/**+ * Owner-only operations the resident owner runs for its verified local CLI+ * registration alone (never for a stdio or HTTP MCP session it also hosts),+ * whatever the writer grant's scopes. The CLI asks for the user's typed+ * confirmation before it sends one; the handler re-checks that binding.+ */+export const LOCAL_CLI_OWNER_OPERATIONS: ReadonlySet<string> = new Set(['purge_fact', 'list_page_purges', 'unpurge_page']);export type PersistenceIpcOperation = typeof PERSISTENCE_IPC_OPERATIONS[number];const OPERATIONS = new Set<string>(PERSISTENCE_IPC_OPERATIONS);const MUTATIONS = new Set<string>([diff --git a/src/core/persistence/provider.ts b/src/core/persistence/provider.tsindex 24141acd7f..c08602a8fc 100644--- a/src/core/persistence/provider.ts+++ b/src/core/persistence/provider.ts@@ -8,7 +8,7 @@ import { dispatchToolCall } from '../../mcp/dispatch.ts';import { registerLocalWriter, withVerifiedLocalRegistration } from './identity.ts';import { startPersistenceConsumer, assertPersistenceAccepting } from './service.ts';import { isWriteErrorCode, isWriteReceipt } from './types.ts';-import type { PersistenceIpcProvider } from './ipc.ts';+import { LOCAL_CLI_OWNER_OPERATIONS, type PersistenceIpcProvider } from './ipc.ts';import { runPersistenceAdministration } from './administration.ts';import { boundedWriteWaitMs } from './write-wait.ts';export { residentPersistenceConfig } from './local-client.ts';@@ -39,7 +39,8 @@ export async function createPersistenceIpcProvider(engine: BrainEngine, config:}const operation = operations.find(op => op.name === request.operation);const localSkillAdministration = !verified.remote && verified.principal.kind === 'local_cli'- && ['get_skill_policy', 'set_skill_policy', 'get_skill_retention', 'prune_skill_revisions', 'retain_skill_revision', 'import_skill_proposal'].includes(request.operation);+ && (['get_skill_policy', 'set_skill_policy', 'get_skill_retention', 'prune_skill_revisions', 'retain_skill_revision', 'import_skill_proposal'].includes(request.operation)+ || LOCAL_CLI_OWNER_OPERATIONS.has(request.operation));if (!operation || (!localSkillAdministration && !hasScope(verified.grant.scopes, operation.scope ?? 'read'))|| (verified.remote && !operationScopesAllowed(verified.grant.scopes, operation))|| (verified.grant.operations !== null && !verified.grant.operations.includes(operation.name))) {diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.tsindex 88bdbdaf13..14f6c8e784 100644--- a/src/core/persistence/publication-failure.ts+++ b/src/core/persistence/publication-failure.ts@@ -39,6 +39,7 @@ export interface PublicationFailure { code: string; message: string; detail?: Puconst IDENT = /^[A-Za-z_][A-Za-z0-9_.:-]{0,79}$/;const ident = (value: unknown) => typeof value === 'string' && IDENT.test(value) ? value : undefined;const GUARD_PREFIX = 'writer_coordinator_required:';+const PURGED_PREFIX = 'purged_content:';const RELATIONSHIP_TEXT: Record<string, string> = {different_source: 'a row in a source this publication does not own',missing_source: 'a row whose source could not be resolved',@@ -69,6 +70,8 @@ export function databaseRefusal(error: unknown): PublicationFailure | null {const table = ident(e.table_name ?? e.table);const constraint = typeof (e.constraint_name ?? e.constraint) === 'string' ? String(e.constraint_name ?? e.constraint) : '';const message = typeof e.message === 'string' ? e.message : '';+ if (message.startsWith(PURGED_PREFIX)) return { code: 'purged_content', message: `${message.slice(PURGED_PREFIX.length).trim()}. Nothing was committed.`,+ detail: { origin: 'database_trigger', sqlstate, ...(raiser ? { raiser } : {}), ...(table ? { table } : {}) } };if (message.startsWith(GUARD_PREFIX) || constraint.startsWith('managed_writer_guard')) {const branch = constraint.startsWith('managed_writer_guard:') ? ident(constraint.slice('managed_writer_guard:'.length)) : undefined;const detail: PublicationFailureDetail = { origin: 'database_guard', sqlstate, raiser: raiser ?? 'gbrain_require_managed_writer',