Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Fix lane R: purge_fact versions segmented pages first; restore-time purge replay deletes segment texts
garrytan66b3e5ae3c66
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.mdindex 3a86531220..cda7d8213a 100644--- a/docs/architecture/key-files/memory-purge.md+++ b/docs/architecture/key-files/memory-purge.md@@ -4,10 +4,10 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#purge).-- `src/core/facts/purge.ts` — `submitPurgeFactMutation`, the handler of the owner-only `purge_fact` op (`gbrain forget <id> --purge`). Refuses every caller whose `ctx.remote !== false` with `trusted_local_only` (`purgeHostOnly`, actor user, the exact host command). `planFactPurge` (read-only) computes the scope: every fact row with the same `gbrain_fact_fingerprint` in the fact's source, visibility and subject (the fact's `entity_slug`, `'*'` with `all_subjects`), verbatim takes (`facts.consolidated_into` plus same-fingerprint takes on the subject's page), affected pages from `discoverWithdrawalTargets`, page_versions carrying the text, terminal request intents carrying it (`findRequestsCarrying` behind the `purge:carrying_lookup` seam; its 57014 is the typed `purge_lookup_timeout`, nothing planned or purged, pinned by `test/fact-purge-lookup-timeout-6511.test.ts`), derived rows from `derivation_inputs`, the fact's P8 review rows, and a `revision` digest. A dry run returns the receipt, `confirm_token` (fingerprint's first 8 hex) and `expected_revision`; a real run requires `confirm === token` and, when given, an unchanged revision. The journaled intent is `{id, reason, all_subjects, fact_hash}`, never claim text; replay by request id returns the stored outcome. One transaction in the global lock order: source `FOR UPDATE` (serializes with the guards' `FOR SHARE`), counters for the purge and every redacted request, admission, then inside `withCoordinatedWrite`: pending-publication refusal (`purge_blocked_pending_recovery`), intent redaction, page locks, derived rows hidden before evidence goes, `fact_purges`/`take_purges` tombstones, deletes (takes, review rows, open loops by fact id, take proposals by fingerprint, facts), core-notice base text nulled, page bodies rewritten through the purge overlay, chunks deleted, versions redacted in place, legacy `query_cache` cleared, and `withdrawal-mirror`/`git`/`embedding` effects with `mode: 'purge'` and `commit_subject: gbrain: purge fact <hash8>`. Chunks are rebuilt before acknowledging; `similar_active` is computed before deletion. Pinned by `test/purge-fact.test.ts` (both engines) and `test/forget-purge-cli.test.ts`. Segmented pages (Wave B): live bodies are rewritten fence by fence through `rewriteLiveSegmentedFences` (a new generation; only the rewritten occurrences' chunks change, an unsealed page is projected after commit), retained generations through `rewriteSegmentedGeneration`; the plan (and its digest) also lists open, sealed or prepared stagings whose staged texts or parts hold the claim plus the queued requests whose `body_ref` names them (`findRequestsHoldingStagings`): the stagings are aborted with their parts deleted, the requests cancelled with `purged_content` (a running or recovering one refuses with `purge_blocked_pending_recovery`), and the segment texts no manifest row references any more are deleted in the same transaction, never left to GC.+- `src/core/facts/purge.ts` — `submitPurgeFactMutation`, the handler of the owner-only `purge_fact` op (`gbrain forget <id> --purge`). Refuses every caller whose `ctx.remote !== false` with `trusted_local_only` (`purgeHostOnly`, actor user, the exact host command). `planFactPurge` (read-only) computes the scope: every fact row with the same `gbrain_fact_fingerprint` in the fact's source, visibility and subject (the fact's `entity_slug`, `'*'` with `all_subjects`), verbatim takes (`facts.consolidated_into` plus same-fingerprint takes on the subject's page), affected pages from `discoverWithdrawalTargets`, page_versions carrying the text, terminal request intents carrying it (`findRequestsCarrying` behind the `purge:carrying_lookup` seam; its 57014 is the typed `purge_lookup_timeout`, nothing planned or purged, pinned by `test/fact-purge-lookup-timeout-6511.test.ts`), derived rows from `derivation_inputs`, the fact's P8 review rows, and a `revision` digest. A dry run returns the receipt, `confirm_token` (fingerprint's first 8 hex) and `expected_revision`; a real run requires `confirm === token` and, when given, an unchanged revision. The journaled intent is `{id, reason, all_subjects, fact_hash}`, never claim text; replay by request id returns the stored outcome. One transaction in the global lock order: source `FOR UPDATE` (serializes with the guards' `FOR SHARE`), counters for the purge and every redacted request, admission, then inside `withCoordinatedWrite`: pending-publication refusal (`purge_blocked_pending_recovery`), intent redaction, page locks, derived rows hidden before evidence goes, `fact_purges`/`take_purges` tombstones, deletes (takes, review rows, open loops by fact id, take proposals by fingerprint, facts), core-notice base text nulled, page bodies rewritten through the purge overlay, chunks deleted, versions redacted in place, legacy `query_cache` cleared, and `withdrawal-mirror`/`git`/`embedding` effects with `mode: 'purge'` and `commit_subject: gbrain: purge fact <hash8>`. Chunks are rebuilt before acknowledging; `similar_active` is computed before deletion. Pinned by `test/purge-fact.test.ts` (both engines) and `test/forget-purge-cli.test.ts`; the segmented preimage version by `test/large-pages/purge-fact-segmented-preimage.test.ts` (inline twin parity, both engines). Segmented pages (Wave B): live bodies are rewritten fence by fence through `rewriteLiveSegmentedFences` (a new generation; only the rewritten occurrences' chunks change, an unsealed page is projected after commit), and each rewritten page gets the preimage version an inline page gets: a segmented version of the revision the flip moved off, read before the flip and referencing the new generation (the body a reader of that revision sees under the purge's tombstone, as the inline preimage is read), so no generation holding the claim stays pinned; retained generations are rebuilt through `rewriteSegmentedGeneration`; the plan (and its digest) also lists open, sealed or prepared stagings whose staged texts or parts hold the claim plus the queued requests whose `body_ref` names them (`stagingsHoldingClaim`, which also reads `page_body_staging_texts`; `findRequestsHoldingStagings`): the stagings are aborted with their parts deleted, the requests cancelled with `purged_content` (a running or recovering one refuses with `purge_blocked_pending_recovery`), and the segment texts no manifest row references any more are deleted in the same transaction, never left to GC (`purgeSegmentStorage`, which the restore-time replay also runs).- `src/core/facts/purge-verify.ts` — receipts and verification. `verifyFactPurge` runs one bounded adapter per store (row bound, per-statement `statement_timeout`, a total deadline; `__setPurgeProbeLimitsForTests`): swept stores report `deleted`, `incomplete` (still holds the claim) or `unverified` (bound hit); page-text stores report remaining text as `out_of_scope: source_prose`; every `probed_reported` inventory table is probed and listed; derived rows are `retained_inactive`; model-derived pages without edges are `derived_legacy: unverified`. On-disk: page files (`canonical_markdown`), a quarantined `<file>.tmp` carrying the claim is deleted, the facts write-failure log is reported. `gitResidualCommits` scans `git log --all -p -- <page paths>` output in-process (the pattern never enters argv; byte and time bounded) and lists commits; `OUT_OF_REACH_RESIDUALS` lead every receipt. Links, timeline entries and raw data that still carry the claim are named row by row (`link:<id> <from> -> <to>`, `timeline:<id> <slug> <date>`, `raw_data:<id> <slug> <source>`, up to 20); queued `persistence_effects` whose data, outcome or recovery carry it are reported; `belief_events` and `fact_context` get ledger reports. The vector probe returns same-model neighbours as paraphrase candidates and is never a gate. `purgeCompletion` derives `committed | complete | incomplete` from effects (failed or parked = incomplete), a fingerprint probe and the receipt, with exit codes 10/0/75. A segmented page or version is probed segment by segment (`segmentedBodyContains`, a needle split by a cut is found; row and time bounded) and reported with the page stores; `page_segment_texts` gets an exact-bytes probe (an unreferenced text holding the claim is `incomplete`, a referenced one `out_of_scope`); the page purge probes the texts its manifests referenced (`PagePurgeContext.segmentShas`).- `src/core/belief/purge.ts` — the purge half of the belief ledger (BELIEF_LEDGER.md 6.5). Every fact or page purge bumps `sources.purge_epoch` (`bumpPurgeEpoch`; an append prepared at an older epoch with `preparedEpoch` refuses `belief_stale_preparation`) and runs three passes inside the purge transaction: `redactPurgedKeys` (the purged keys, by `claim_fp` and page lifetime, keep skeletons: value, value_hash and prior_hash null, `purged`), `redactCarryingFields` (keyset batches of 1000 reading only the carrying fields of fact, take and link events, matched in JS by `quotes` over `claimForms`, never SQL `lower()`/`strpos`: each carrying field from `CARRYING_FIELDS` that quotes a purged claim, plain or fence-escaped, becomes `REDACTION_MARKER(<purge request>)` and is listed in `redacted_fields`; a later event's prior_hash naming the old hash names the new one) with `registerLiveCarriers` (a surviving row whose field quotes the claim enters `belief_redactions` with its field hash, so its next event writes the marker until an explicit owner edit sets a different value: `publicationBeliefOptions` marks `ownerEdit` only on a local `put_page`, `edit_page`, `takes_update` or `takes_resolve` with no internal intent kind, and append still needs `OWNER_TIER_FLOOR`) and, for a fact purge, `registerVersionCarriers` (the retained versions still quoting the claim, registered under the keys the backfill gives them). A claim shorter than 8 characters quotes a field only as a word in spaced scripts (`ceo` does not match `herbaceous`; CJK and markup still match), and `appendDerivedHidden` (one `derived.hidden` per key the derivation walk hid; `readBeliefHistory` then hides that key's earlier events and every backfill event of it). A page purge's claims come from `pagePurgeClaims`: the page's facts and takes, every retained version's fence rows and every claim in its lifetimes' events, unbounded. `releaseSuppressedFields` is the owner release `trust confirm` runs (`belief_redactions.released_hash`); every release, there or in an owner-edit append, appends one `redaction.released` (`redactionReleasedDraft`: fields, purge requests and released hashes, never the text) in the publication `released_by` names. The receipt's `ledger` block reports the counts and `derived_walk`; a truncated walk withholds certification of its coverage interval (`coverage-report.ts`). Purge-verify's ledger report is a JS keyset scan too: a missed carrying field is `incomplete`, another subject's recorded value quoting the claim is `out_of_scope` with `field@key` items. Seam: `__setPurgeRedactionFaultForTests`. Probes: `test/belief-ledger-purge.test.ts` (both engines).-- `src/core/belief/purge-mirror.ts` — the text-free purge mirror `<brain home>/.gbrain/purge-events.jsonl` (0600, fsynced): an `intent` line before the purge commits (`appendPurgeIntent`; request, source and incarnation, scope, fingerprints, content hashes, lifetimes, epoch; never claim text; an unwritable mirror refuses the purge with the typed `purge_mirror_unwritable`, with or without a ledger) and a `committed` line after (`appendPurgeCommitted`, best effort; a page purge writes it from the coordinator's `afterCommit`, so it does not depend on the op handler finishing). `restorePgliteBackup` (`gbrain backup restore --purge-mirror <absolute path>` names a mirror other than the brain home's) replays every committed purge newer than the archive inside its transaction (`replayPurgesInRestore`: tombstones, row removal, the three passes, the derived rows hidden again with `derived.hidden` cause `restore_replay`, one `fact.purged`/`page.purged` with cause `restore_replay`; a page-scope replay matches pages by content hash or lifetime, never by slug alone; an archive from before the ledger, no `belief_events`, replays tombstones and row removal and reports `ledger: 'absent'`; an intent whose request already has tombstones is skipped), records each as `complete`, `partial` (no restored row held the text, or the derivation walk could not run) or `unverified` (intent without committed line, not replayed), returns `purge_replay` in the receipt and adds a reconnect warning unless the state is `none` or `complete`; an unreadable mirror is `unavailable`. `coverage.restored` carries the outcome, which `readRestorePurgeReplay` reads back for the doctor. A Postgres restore runs `gbrain beliefs replay-purges --archived-at <iso> (--purge-mirror <abs path> | --from-url-env <VAR>) [--apply]` (`src/commands/beliefs-replay-purges.ts`; dry run by default: `replayPurges` runs the replay in a transaction that rolls back), whose database source `purgeLinesFromDatabase` rebuilds the intents from every pre-restore tombstone (not bounded by `purged_at`, the purge transaction's start) and skips those the archive already holds. Seam: `__setPurgeReplayFaultForTests`. Probes: `test/belief-ledger-restore.test.ts`.+- `src/core/belief/purge-mirror.ts` — the text-free purge mirror `<brain home>/.gbrain/purge-events.jsonl` (0600, fsynced): an `intent` line before the purge commits (`appendPurgeIntent`; request, source and incarnation, scope, fingerprints, content hashes, lifetimes, epoch; never claim text; an unwritable mirror refuses the purge with the typed `purge_mirror_unwritable`, with or without a ledger) and a `committed` line after (`appendPurgeCommitted`, best effort; a page purge writes it from the coordinator's `afterCommit`, so it does not depend on the op handler finishing). `restorePgliteBackup` (`gbrain backup restore --purge-mirror <absolute path>` names a mirror other than the brain home's) replays every committed purge newer than the archive inside its transaction (`replayPurgesInRestore`: tombstones, row removal (a fact-scope replay rewrites page bodies and versions through `rewritePageBodies` / `redactPageVersions`, then runs `purgeSegmentStorage` with each claim's `stagingsHoldingClaim`; a page-scope replay deletes the page through `deletePageWithSegments`, so segment texts that held the purged content go in the replay, as in the purge), the three passes, the derived rows hidden again with `derived.hidden` cause `restore_replay`, one `fact.purged`/`page.purged` with cause `restore_replay`; a page-scope replay matches pages by content hash or lifetime, never by slug alone; an archive from before the ledger, no `belief_events`, replays tombstones and row removal and reports `ledger: 'absent'`; an intent whose request already has tombstones is skipped), records each as `complete`, `partial` (no restored row held the text, or the derivation walk could not run) or `unverified` (intent without committed line, not replayed), returns `purge_replay` in the receipt and adds a reconnect warning unless the state is `none` or `complete`; an unreadable mirror is `unavailable`. `coverage.restored` carries the outcome, which `readRestorePurgeReplay` reads back for the doctor. A Postgres restore runs `gbrain beliefs replay-purges --archived-at <iso> (--purge-mirror <abs path> | --from-url-env <VAR>) [--apply]` (`src/commands/beliefs-replay-purges.ts`; dry run by default: `replayPurges` runs the replay in a transaction that rolls back), whose database source `purgeLinesFromDatabase` rebuilds the intents from every pre-restore tombstone (not bounded by `purged_at`, the purge transaction's start) and skips those the archive already holds. Seam: `__setPurgeReplayFaultForTests`. Probes: `test/belief-ledger-restore.test.ts`; segment storage after a replay: `test/large-pages/purge-replay-segments.test.ts` (both engines).- `src/core/facts/purge-overlay.ts` — purge mode of the import overlay: `dropPurgedFenceRows` drops facts-fence rows matching `fact_purges` and takes-fence rows matching `take_purges` (the takes fence re-renders with its reservation rows plus the dropped numbers reserved, so a purged number is never reused; pinned by `test/purge-overlay-reservations.test.ts`) (subject = page slug; malformed fences left to the withdrawal diagnostics, which refuse a purged claim inside one). Called first by `preserveWithdrawnFenceRows`, so `import-file.ts` needs no change; the snapshot overlay (`page-state/snapshot.ts`) and export (`export-snapshot.ts`) carry purge tombstones as `PageWithdrawal.purged`, which `overlayWithdrawalBody` drops instead of striking.- `src/core/facts/purge-schema.ts` — `MEMORY_PURGE_SCHEMA_SQL` (schema.sql fragment: `fact_purges`, `take_purges`, `page_purges` keyed `(source_id, content_hash)`, `derivation_inputs`, `needs_rederive`) and `MEMORY_PURGE_GUARD_SQL` (migration only): `facts_refuse_purged`, `takes_refuse_purged` and `pages_refuse_purged` raise `P0001 purged_content: …` (mapped to typed `purged_content` by `persistence/publication-failure.ts`) instead of skipping the row, whatever `expired_at` says. The pages guard has no column list so it never pins columns. `FACT_PURGE_LOOKUP_INDEX_SQL` (migration v231, CONCURRENTLY on Postgres) adds `fact_purges_subject_idx` (a page's own tombstones, the '*' lookup by fingerprint) and the partial `fact_purges_all_subjects_idx` (subject '*' only, for the snapshot marker count).- `src/core/page-state/snapshot.ts` — a page snapshot lists only the page's own `fact_purges` tombstones; subject-'*' ones come back as `PageSnapshot.globalPurges` (count, latest `purged_at`, world-only flag; absent at count 0). `resolveGlobalPurges` turns the marker into purge withdrawals for the fence rows of whatever text is overlaid (stored page, incoming file in `page-prepare.ts`, `overlayCanonicalBodies`), on the caller's query. Reconcile pins/preimages and extract-atoms page-state hashing carry the marker, so a new '*' purge invalidates them and an artifact without it reads stale. Alias resolution: `readPageSnapshot` with `resolveAlias` first runs the exact-slug statement (an exact hit outranks every alias), then, on a miss or for `requireUnambiguous`, one `WITH chosen` statement whose candidates are a UNION ALL of the exact-slug probe and an alias-join probe (`slug_aliases` → `pages` on `(source_id, canonical_slug)`, `p.slug<>$1` keeps the branches disjoint so `count(*) OVER ()` still counts pages). #6281: never `slug=$1 OR EXISTS(alias)`, which read every page of every readable source; `page-snapshot-alias-plan.test.ts` pins fewer than 100 `pages` rows per statement from EXPLAIN on both engines.@@ -15,7 +15,7 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu- `src/core/deletion-inventory.ts` — the deletion-target registry: every table with a text, JSON, bytes, array, lexeme or vector column, classed `swept`, `retained_inactive` or `out_of_scope` (`probed_reported` with probe columns, `text_free_ledger`, `secret_material`, `no_memory_text`), plus on-disk stores and out-of-reach residuals. `test/deletion-inventory.test.ts` fails on any unlisted text-bearing column of a fresh schema and pins the AGENTS.md "never promise physical erasure" line.- `src/core/persistence/intent-redaction.ts` — accounting-aware intent redaction: `findRequestsCarrying` (intent, outcome, error detail or message, compacted rows included; the fact purge's planning read) / `findRequestsForSlugs` (index-served by `persistence_requests_slug_intent`), the page purge's preparation-time journal census `sweepRequestsCarrying` (#6511: a keyset walk of the source's journal in `JOURNAL_SWEEP_CHUNK_ROWS` chunks, every needle in raw and JSON-escaped form against intent, outcome, error detail and message, compacted rows included, the purge's own row excluded, stopped by the claim clock between chunks and at `JOURNAL_SWEEP_MATCH_CAP`; returns the carrying ids, the ids pending at the scan, the `sequence` ceiling as text and `complete`) with `recheckRequestsCarrying` for the publication's bounded re-check of the tail past the ceiling and of the rows that were pending, `redactRequestIntents` locks counters then request rows, refuses on a non-terminal or recovering request (unless `skipPending`), nulls `intent`/`error_message` and replaces every outcome or error-detail string carrying a needle with `"[purged]"` (`redactJson`), with compaction's terminal-byte accounting, so replay keeps returning the (redacted) stored outcome. `findRequestsHoldingStagings` / `cancelRequestsHoldingStagings`: the queued requests whose `intent.body_ref.staging_id` names a staging a fact purge aborts are completed `cancelled` with `purged_content`.- `src/core/persistence/purged-intent.ts` — `intentCarriesPurgedContent`: `completeWrite` (journal.ts) nulls the intent of any terminal request whose content (`fact`, `claim`, page fence rows, or the page's content hash) matches a subject-scoped purge tombstone, and of any refusal coded `purged_content`; a write refused for another reason, or committed as a no-op after the overlay dropped purged rows, keeps no copy. Only content-bearing intents are checked, and whether the source holds any tombstone is selected by completeWrite's terminal statement itself (`PURGE_PRESENCE_COLUMNS`), so the hook adds no statement to a write on a source without tombstones (#6007 budget). `purged_content` is a write error code, so receipts and the frozen verb path (wire `invalid_params`, canonical `purged_content`) keep it typed.-- `src/core/persistence/page-purge.ts` — `purgePageInTransaction`, called by the `delete_page purge:true` apply in `page-prepare.ts`: records in `page_purges` the content hash of the page and of every retained version (up to 1000), each as imported and as purge-overlaid, so an older version is refused too; drops the decide rows, trust proposals, gate holds (by slug) and gate receipts naming the page or its rows and clears legacy `query_cache`; tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices and `files` rows, the page's `page_aliases` and the `slug_aliases` redirects whose `canonical_slug` is the page (#6619; a redirect from this slug to another page stays; counted in `removed` and checked by slug in the receipt), redacts finished intents for the slug and the carrying ids the preparation sweep found plus the publication's tail and pending re-check (#6511: `preparePagePurge` runs `readPurgeClaims` and `sweepRequestsCarrying` under the preparation budget at steps `purge_claims` / `purge_journal_sweep`, so the O(journal) substring scan is a charged `preparation_deadline` release and `preparation_stalled` at the attempt limit, never a transaction timeout; the lookups that stay inside the transaction go through `lookup`, which maps a 57014 to the terminal, non-retryable `purge_lookup_timeout` naming `gbrain repair request-indexes` only when `persistence_requests_slug_intent` is missing or INVALID; the receipt's `journal_sweep` reports `ceiling`, `scanned`, `tail`, `pending_rechecked` and `complete`), then deletes the page (FK cascades). `PURGE_RESIDUALS` names what stays out of reach. `finishPagePurge` deletes stored blobs after commit, lists any left by storage path, and attaches `receipt`, the store-by-store receipt from `verifyPagePurge` (same shape as the fact receipt: residuals first, every swept inventory store, other pages' prose naming a purged claim as `source_prose`); the page's claims used as needles live only in process memory, and a same-id replay returns the result built when the purge ran. `residuals` stays the prose string. `readPagePurgeTombstones` feeds `screenImportContent({ purgedPages })` from managed sync's freeze-time screen (`sync-screen.ts`, one read per run) and publication (`sync-prepare.ts`), which hold a matching file as `purged_content`; direct imports and `put_page` hit the pages guard instead; `listPagePurges` / `unpurgePage` (also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned by `test/page-purge.test.ts` and `test/page-purge-journal-timeout-6511.test.ts` (both engines; seams `purge:*` in `fault-points.ts`). #6368: a purge of a tombstone whose file matches `sync.exclude` (discovery's globs via `syncExcludePatterns` in `sync-discovery.ts`, matched relative to the source root) owns no file: `prepareFileTarget`'s `excludeTombstone` option returns no target, the purge is database-only and the receipt says `write_through.skipped: 'sync_excluded'`; the file is neither compared nor removed (an unchanged excluded file used to be deleted, an edited one refused forever). The apply re-reads the exclusion inside the publication transaction and refuses `source_changed` if it was removed meanwhile. Live-page purges and soft deletes are unchanged. A segmented page or version is never loaded whole: its stored `content_hash` and the purge-overlaid hash streamed by `rewrittenContentHash` are tombstoned; its stagings (by slug or page id) and the segment texts only its manifests referenced are deleted in the purge transaction (`removed.page_body_manifest` / `page_body_stagings` / `page_segment_texts`), except a text another page's live staging recorded in `page_body_staging_texts` (an unpublished create or replace still needs it; `stagingNeedsTextSql`, also applied by the 72-hour hard delete and the receipt's text probe).+- `src/core/persistence/page-purge.ts` — `purgePageInTransaction`, called by the `delete_page purge:true` apply in `page-prepare.ts`: records in `page_purges` the content hash of the page and of every retained version (up to 1000), each as imported and as purge-overlaid, so an older version is refused too; drops the decide rows, trust proposals, gate holds (by slug) and gate receipts naming the page or its rows and clears legacy `query_cache`; tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices and `files` rows, the page's `page_aliases` and the `slug_aliases` redirects whose `canonical_slug` is the page (#6619; a redirect from this slug to another page stays; counted in `removed` and checked by slug in the receipt), redacts finished intents for the slug and the carrying ids the preparation sweep found plus the publication's tail and pending re-check (#6511: `preparePagePurge` runs `readPurgeClaims` and `sweepRequestsCarrying` under the preparation budget at steps `purge_claims` / `purge_journal_sweep`, so the O(journal) substring scan is a charged `preparation_deadline` release and `preparation_stalled` at the attempt limit, never a transaction timeout; the lookups that stay inside the transaction go through `lookup`, which maps a 57014 to the terminal, non-retryable `purge_lookup_timeout` naming `gbrain repair request-indexes` only when `persistence_requests_slug_intent` is missing or INVALID; the receipt's `journal_sweep` reports `ceiling`, `scanned`, `tail`, `pending_rechecked` and `complete`), then deletes the page (FK cascades). `PURGE_RESIDUALS` names what stays out of reach. `finishPagePurge` deletes stored blobs after commit, lists any left by storage path, and attaches `receipt`, the store-by-store receipt from `verifyPagePurge` (same shape as the fact receipt: residuals first, every swept inventory store, other pages' prose naming a purged claim as `source_prose`); the page's claims used as needles live only in process memory, and a same-id replay returns the result built when the purge ran. `residuals` stays the prose string. `readPagePurgeTombstones` feeds `screenImportContent({ purgedPages })` from managed sync's freeze-time screen (`sync-screen.ts`, one read per run) and publication (`sync-prepare.ts`), which hold a matching file as `purged_content`; direct imports and `put_page` hit the pages guard instead; `listPagePurges` / `unpurgePage` (also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned by `test/page-purge.test.ts` and `test/page-purge-journal-timeout-6511.test.ts` (both engines; seams `purge:*` in `fault-points.ts`). #6368: a purge of a tombstone whose file matches `sync.exclude` (discovery's globs via `syncExcludePatterns` in `sync-discovery.ts`, matched relative to the source root) owns no file: `prepareFileTarget`'s `excludeTombstone` option returns no target, the purge is database-only and the receipt says `write_through.skipped: 'sync_excluded'`; the file is neither compared nor removed (an unchanged excluded file used to be deleted, an edited one refused forever). The apply re-reads the exclusion inside the publication transaction and refuses `source_changed` if it was removed meanwhile. Live-page purges and soft deletes are unchanged. A segmented page or version is never loaded whole: its stored `content_hash` and the purge-overlaid hash streamed by `rewrittenContentHash` are tombstoned; its stagings (by slug or page id) and the segment texts only its manifests referenced are deleted in the purge transaction with the page (`deletePageWithSegments`, shared with the restore-time page-scope replay; `removed.page_body_manifest` / `page_body_stagings` / `page_segment_texts`), except a text another page's live staging recorded in `page_body_staging_texts` (an unpublished create or replace still needs it; `stagingNeedsTextSql`, also applied by the 72-hour hard delete and the receipt's text probe).- `src/core/ops/purge.ts` — `purge_fact`, `list_page_purges`, `unpurge_page`: admin scope, `cliOnly` (every MCP route gets `trusted_local_only`). The resident owner runs them only for its verified local CLI registration (`LOCAL_CLI_OWNER_OPERATIONS` in `persistence/ipc.ts`, checked in `persistence/provider.ts`).- `src/commands/forget-purge.ts` + `src/commands/pages-purges.ts` — the CLI fronts. `runForgetPurge` always runs the dry run, then a typed token on a terminal or `--yes` plus `--request-id` without one; `--match` lists ids, `--status` polls completion; `PURGE_FAMILY_HELP` is the purge-family table shown by `gbrain forget --help`. `gbrain pages purges list` and `gbrain pages unpurge <slug>` run the page-tombstone ops as the trusted CLI.diff --git a/src/core/belief/purge-mirror.ts b/src/core/belief/purge-mirror.tsindex 44e2f8ab74..22ba3ec413 100644--- a/src/core/belief/purge-mirror.ts+++ b/src/core/belief/purge-mirror.ts@@ -138,7 +138,8 @@ async function replayOne(tx: BrainEngine, intent: PurgeMirrorIntent, ledger: booinputs = [{ table: 'pages', id: restored.id }, ...owned.map(r => ({ table: r.t, id: Number(r.id) }))];removeRows = async () => {await tx.executeRaw('DELETE FROM facts WHERE source_id = $1 AND source_markdown_slug = $2', [src, restored.slug]);- await tx.deletePage(restored.slug, { sourceId: src });+ const { deletePageWithSegments } = await import('../persistence/page-purge.ts');+ await deletePageWithSegments(tx, src, restored.slug, restored.id);};}} else {@@ -150,13 +151,22 @@ async function replayOne(tx: BrainEngine, intent: PurgeMirrorIntent, ledger: booclaims = [...new Set([...rows.map(r => r.fact), ...takes.map(t => t.claim)])];inputs = [...rows.map(r => ({ table: 'facts', id: Number(r.id) })), ...takes.map(t => ({ table: 'takes', id: Number(t.id) }))];if (claims.length) removeRows = async () => {- const { rewritePageBodies, redactPageVersions } = await import('../facts/purge.ts');+ const { rewritePageBodies, redactPageVersions, purgeSegmentStorage, stagingsHoldingClaim } = await import('../facts/purge.ts');const pages = await tx.executeRaw<{ slug: string; page_id: number; revision: string }>(`SELECT slug, id AS page_id, knowledge_revision::text AS revision FROM pagesWHERE source_id = $1 AND (slug = ANY($2::text[]) OR id = ANY($3::int[]))`, [src, rows.map(r => r.slug).filter(Boolean), takes.map(t => Number(t.page_id))]);+ const staged = [];+ for (const claim of claims) staged.push(await stagingsHoldingClaim(tx, src, claim));await tx.executeRaw('DELETE FROM takes WHERE id = ANY($1::bigint[])', [takes.map(t => Number(t.id))]);await tx.executeRaw('DELETE FROM facts WHERE id = ANY($1::bigint[])', [rows.map(r => Number(r.id))]);- await rewritePageBodies(tx, src, pages.map(p => ({ ...p, page_id: Number(p.page_id) })));- for (const claim of claims) await redactPageVersions(tx, src, claim, pages.map(p => Number(p.page_id)));+ const bodies = await rewritePageBodies(tx, src, pages.map(p => ({ ...p, page_id: Number(p.page_id) })));+ const segmented = new Set(bodies.segmented), replaced = [...bodies.replaced];+ for (const claim of claims) {+ const versions = await redactPageVersions(tx, src, claim, pages.map(p => Number(p.page_id)));+ for (const id of versions.segmentedPages) segmented.add(id);+ replaced.push(...versions.replaced);+ }+ // As purge_fact does (spec 11): segment texts that held the claim go now, not at GC, with the stagings holding them.+ for (const [i, claim] of claims.entries()) await purgeSegmentStorage(tx, src, claim, staged[i]!, [...segmented], replaced, intent.request);};}const walkable = (await tx.executeRaw<{ present: boolean }>("SELECT to_regclass('derivation_inputs') IS NOT NULL AS present"))[0]?.present === true;diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.tsindex 3d516a668a..c7fe239973 100644--- a/src/core/facts/purge.ts+++ b/src/core/facts/purge.ts@@ -141,6 +141,24 @@ async function stagingsWithClaimAcrossParts(engine: BrainEngine, sourceId: strinreturn [...hits];}+/**+ * The live stagings of the source holding `claim` (aborted by a purge of it) and the unfinished requests that would+ * publish them. A live staging that recorded a text holding the claim, plain or as a fence cell (page_body_staging_texts:+ * a create holds its manifest rows in memory until it publishes), is one of them: the purge deletes that text and the+ * create refuses cleanly (body_staging_expired) instead of failing on the manifest's text foreign key.+ */+export async function stagingsHoldingClaim(engine: BrainEngine, sourceId: string, claim: string): Promise<Pick<PurgePlan, 'stagings' | 'held'>> {+ const stagings = [...new Set([...(await engine.executeRaw<{ id: string }>(`SELECT s.id::text AS id FROM page_body_stagings s+ WHERE s.source_id=$1 AND ((s.state IN ('open','sealed','prepared') AND (EXISTS (SELECT 1 FROM page_body_manifest m+ JOIN page_segment_texts t ON t.source_id=m.source_id AND t.sha256=m.sha256 WHERE m.staging_id=s.id AND strpos(lower(convert_from(t.body,'UTF8')),$2)>0)+ OR EXISTS (SELECT 1 FROM page_body_staging_parts pt WHERE pt.staging_id=s.id AND position(convert_to($3::text,'UTF8') in pt.body)>0)))+ OR (${liveStagingSql('s')} AND EXISTS (SELECT 1 FROM page_body_staging_texts r JOIN page_segment_texts t ON t.source_id=r.source_id AND t.sha256=r.sha256+ WHERE r.staging_id=s.id AND (strpos(lower(convert_from(t.body,'UTF8')),$2)>0 OR strpos(lower(convert_from(t.body,'UTF8')),$4)>0))))+ ORDER BY s.id`, [sourceId, claim.toLowerCase(), claim, escapeFenceCell(claim).toLowerCase()])).map(row => row.id),+ ...await stagingsWithClaimAcrossParts(engine, sourceId, claim)])].sort();+ return { stagings, held: await findRequestsHoldingStagings(engine, sourceId, stagings) };+}+/** 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 ?? '*';@@ -161,18 +179,7 @@ export async function planFactPurge(engine: BrainEngine, target: PurgeTarget, alconst [versions] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_idWHERE p.source_id=$1 AND (${carriesClaimSql('v', 2)}OR (v.body_storage='segmented' AND ${SEGMENTED_VERSION_CARRIES}))`, [target.source_id, ...claimNeedles(target.fact)]);- // A live staging that recorded a text holding the claim, plain or as a fence cell (page_body_staging_texts: a create- // holds its manifest rows in memory until it publishes), is aborted with the rest: the purge deletes that text and the- // create refuses cleanly (body_staging_expired) instead of failing on the manifest's text foreign key.- const stagings = [...new Set([...(await engine.executeRaw<{ id: string }>(`SELECT s.id::text AS id FROM page_body_stagings s- WHERE s.source_id=$1 AND ((s.state IN ('open','sealed','prepared') AND (EXISTS (SELECT 1 FROM page_body_manifest m- JOIN page_segment_texts t ON t.source_id=m.source_id AND t.sha256=m.sha256 WHERE m.staging_id=s.id AND strpos(lower(convert_from(t.body,'UTF8')),$2)>0)- OR EXISTS (SELECT 1 FROM page_body_staging_parts pt WHERE pt.staging_id=s.id AND position(convert_to($3::text,'UTF8') in pt.body)>0)))- OR (${liveStagingSql('s')} AND EXISTS (SELECT 1 FROM page_body_staging_texts r JOIN page_segment_texts t ON t.source_id=r.source_id AND t.sha256=r.sha256- WHERE r.staging_id=s.id AND (strpos(lower(convert_from(t.body,'UTF8')),$2)>0 OR strpos(lower(convert_from(t.body,'UTF8')),$4)>0))))- ORDER BY s.id`, [target.source_id, target.fact.toLowerCase(), target.fact, escapeFenceCell(target.fact).toLowerCase()])).map(row => row.id),- ...await stagingsWithClaimAcrossParts(engine, target.source_id, target.fact)])].sort();- const held = await findRequestsHoldingStagings(engine, target.source_id, stagings);+ const { stagings, held } = await stagingsHoldingClaim(engine, target.source_id, target.fact);// #6511 [R5]: a statement timeout of this unindexable substring search is deterministic on a large journal, not contention: the typed code, not a retry.const requests = await faultPoint('purge:carrying_lookup', { sourceId: target.source_id, operation: PURGE_OPERATION }).then(() => findRequestsCarrying(engine, target.source_id, target.fact)).catch(error => {@@ -240,9 +247,9 @@ const SEGMENTED_VERSION_CARRIES = `EXISTS (SELECT 1 FROM page_body_manifest m JOinterface BodyRewrites { rewritten: string[]; segmented: number[]; unsealed: string[]; replaced: Uint8Array[] }/**- * Drop purged rows from each affected page's stored body. Each inline page is versioned first (the rewrite advances its+ * Drop purged rows from each affected page's stored body. Each page is versioned first (the rewrite advances its* revision), and `redactPageVersions` then redacts that version like every other one; a segmented page publishes a new- * generation (spec 11).+ * generation (spec 11), and its version of the old revision references that generation.*/export async function rewritePageBodies(tx: BrainEngine, sourceId: string, pages: PurgePlan['pages']): Promise<BodyRewrites> {const out: BodyRewrites = { rewritten: [], segmented: [], unsealed: [], replaced: [] };@@ -253,8 +260,12 @@ export async function rewritePageBodies(tx: BrainEngine, sourceId: string, pagesif (row.body_storage === 'segmented') {const slug = String(row.slug);out.segmented.push(Number(row.id));+ const preimage = await tx.readPageSnapshot(slug, { sourceId, includeDeleted: true });const done = await rewriteLiveSegmentedFences(tx, Number(row.id), fence => dropPurgedFenceRows(tx, sourceId, fence, slug));if (!done) continue;+ // The version of the revision the flip moved off references the new generation: that is the revision's body as a+ // reader sees it under this purge's tombstone, as the inline preimage is read, so no generation holding the claim stays pinned.+ if (preimage) await createPageVersion(tx, slug, sourceId, preimage);out.rewritten.push(slug);out.replaced.push(...done.replaced);if (!done.sealed) out.unsealed.push(slug);@@ -336,9 +347,10 @@ export async function redactPageVersions(tx: BrainEngine, sourceId: string, clai* deleted, requests that reference them cancelled with purged_content), closed manifest rows outside every GC root* go, and every segment text the rewrites replaced, or that still holds the claim, is deleted once nothing* references it, in this transaction (purge never waits for GC). A live staging that recorded such a text was aborted- * by the plan (planFactPurge), so no write in flight still needs it.+ * by the plan (`stagingsHoldingClaim`), so no write in flight still needs it. The restore-time purge replay runs it too.*/-async function purgeSegmentStorage(tx: BrainEngine, sourceId: string, claim: string, plan: PurgePlan, pageIds: number[], replaced: Uint8Array[], ownRequest: string):+export async function purgeSegmentStorage(tx: BrainEngine, sourceId: string, claim: string, plan: Pick<PurgePlan, 'stagings' | 'held'>, pageIds: number[],+ replaced: Uint8Array[], ownRequest: string):Promise<{ texts: number; stagings: number; parts: number; cancelled: number }> {const cancelled = await cancelRequestsHoldingStagings(tx, plan.held, ownRequest);let parts = 0;diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.tsindex 033f4766d9..16a0dfa197 100644--- a/src/core/persistence/page-purge.ts+++ b/src/core/persistence/page-purge.ts@@ -262,16 +262,8 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,derived_hidden: await appendDerivedHidden(tx, { sourceId, request: row.id, publicationId: row.id, op: 'delete_page', targets: heldTargets, truncated: walk === 'truncated' }),derived_walk: walk })) : null;if (ledger) removed.belief_events = ledger.purged_events + ledger.redacted_fields.length;- // Wave B (spec 11): the segment texts only this page's manifests reference go with it, in this transaction, and so do- // its stagings (one of a create has no page row to cascade from).- const shas = (await tx.executeRaw<{ sha: string }>(`SELECT DISTINCT encode(sha256,'hex') AS sha FROM page_body_manifest WHERE page_id=$1`, [page.id])).map(r => r.sha);- removed.page_body_manifest = (await tx.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_body_manifest WHERE page_id=$1', [page.id]))[0]?.n ?? 0;- removed.page_body_stagings = await count('DELETE FROM page_body_stagings WHERE source_id=$1 AND (slug=$2 OR page_id=$3) RETURNING 1', [sourceId, slug, page.id]);- await tx.deletePage(slug, { sourceId });- // A text another page still references stays, and so does one an unpublished write of another page staged or deduped- // onto (a create holds its manifest rows in memory until it publishes): that write's copy, not this page's.- removed.page_segment_texts = shas.length ? await count(`DELETE FROM page_segment_texts t WHERE t.source_id=$1 AND t.sha256=ANY(SELECT decode(h,'hex') FROM unnest($2::text[]) AS h)- AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id=t.source_id AND m.sha256=t.sha256) AND NOT ${stagingNeedsTextSql('t')} RETURNING 1`, [sourceId, shas]) : 0;+ const { shas, ...segmentRows } = await deletePageWithSegments(tx, sourceId, slug, page.id);+ Object.assign(removed, segmentRows);if (!retention) appendPurgeIntent({ request: row.id, request_id: row.request_id, source_id: sourceId, source_incarnation: row.source_incarnation,scope: 'page', slug, purge_epoch: epoch, content_hashes: [...hashes], facts: mirrorFacts, takes: mirrorTakes, lifetimes });const key = `${sourceId}:${row.request_id}`;@@ -346,3 +338,21 @@ export async function unpurgePage(ctx: OperationContext, p: Record<string, unknonext: cleared.length ? `The next import of ${slug} with its old content is accepted (gbrain sync --source ${sourceId} --no-pull). Nothing was restored.` : `No purge tombstone is recorded for ${slug} in source ${sourceId}.` };});}++/**+ * Delete a purged page with its segment storage (Wave B, spec 11), in the caller's transaction: the segment texts only+ * its manifests referenced go with it, and so do its stagings (one of a create has no page row to cascade from). A text+ * another page still references stays, and so does one an unpublished write of another page staged or deduped onto (a+ * create holds its manifest rows in memory until it publishes): that write's copy, not this page's. The restore-time+ * purge replay deletes a page this way too.+ */+export async function deletePageWithSegments(tx: BrainEngine, sourceId: string, slug: string, pageId: number):+ Promise<{ shas: string[]; page_body_manifest: number; page_body_stagings: number; page_segment_texts: number }> {+ const shas = (await tx.executeRaw<{ sha: string }>(`SELECT DISTINCT encode(sha256,'hex') AS sha FROM page_body_manifest WHERE page_id=$1`, [pageId])).map(r => r.sha);+ const manifest = (await tx.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_body_manifest WHERE page_id=$1', [pageId]))[0]?.n ?? 0;+ const stagings = (await tx.executeRaw('DELETE FROM page_body_stagings WHERE source_id=$1 AND (slug=$2 OR page_id=$3) RETURNING 1', [sourceId, slug, pageId])).length;+ await tx.deletePage(slug, { sourceId });+ const texts = shas.length ? (await tx.executeRaw(`DELETE FROM page_segment_texts t WHERE t.source_id=$1 AND t.sha256=ANY(SELECT decode(h,'hex') FROM unnest($2::text[]) AS h)+ AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id=t.source_id AND m.sha256=t.sha256) AND NOT ${stagingNeedsTextSql('t')} RETURNING 1`, [sourceId, shas])).length : 0;+ return { shas, page_body_manifest: manifest, page_body_stagings: stagings, page_segment_texts: texts };+}diff --git a/test/large-pages/purge-fact-segmented-preimage.test.ts b/test/large-pages/purge-fact-segmented-preimage.test.tsnew file mode 100644index 0000000000..c660899e43--- /dev/null+++ b/test/large-pages/purge-fact-segmented-preimage.test.ts@@ -0,0 +1,132 @@+/**+ * Wave B PR 2 fix lane R, gap 1: purge_fact versions a segmented page before rewriting it, as it versions the inline twin.+ *+ * 1. Protects: master's preimage rule (docs/designs/BELIEF_LEDGER.md section 14 item 8, "purge_fact saves each rewritten+ * page as a version first") on a page stored in segments. After purge_fact of a claim in a facts fence, the segmented+ * page has the inline twin's version and ledger artifacts: one more version, holding the revision the purge moved the+ * page off (so page-at-time resolves it), whose body is the pre-purge body with the purged row dropped (version+ * redaction ran on it too; it never holds the claim), the same belief events, and the same receipt counts. The+ * segmented version is a reference to a generation, never a copy of the body as one string.+ * 2. Fails when: the segmented purge publishes a new generation without a version of the revision it moved off, or the+ * version keeps the purged row.+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt). pages.segmented_storage is forced+ * on for the segmented twin's writes and off for the inline twin's.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { enableBeliefLedger } from '../../src/core/belief/coverage.ts';+import { readSegmentedBody } from '../../src/core/page-body/ingest.ts';+import { openTwinBrain, type TwinBrain } from '../helpers/segmented-twins.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { withEnv } from '../helpers/with-env.ts';++const INLINE = 'people/ina-example';+const SEGMENTED = 'people/sei-example';+/** Each twin's claim has its own fingerprint, so one twin's purge never reaches the other's rows, events or requests. */+const CLAIMS: Record<string, string> = { [INLINE]: 'Twin Example door code is 4417', [SEGMENTED]: 'Twin Example door code is 5528' };+const KEPT = 'Twin Example adopted a narwhalbot';+const utf8 = new TextDecoder();++for (const kind of testBackends()) {+ describe(kind + ': purge_fact versions a segmented page before rewriting it', () => {+ let brain: TwinBrain;++ beforeAll(async () => {+ brain = await openTwinBrain(kind, [INLINE], async seed => {+ await seed.setSwitch(false);+ await seed.put(INLINE, 1_100_000);+ await seed.setSwitch(true);+ await seed.put(SEGMENTED, 1_100_000);+ });+ await withEnv(brain.env(), () => enableBeliefLedger(brain.engine, brain.sourceId));+ for (const slug of [INLINE, SEGMENTED]) {+ brain.setChatReply(JSON.stringify({ facts: [CLAIMS[slug]!, KEPT].map(fact => ({ fact, kind: 'fact', entity: slug, confidence: 1, notability: 'high' })) }));+ expect(await brain.call('extract_facts', { turn_text: 'Synthetic meeting record. ' + CLAIMS[slug] + '. ' + KEPT + '.', visibility: 'world', valid_from: '2026-10-15T00:00:00Z' }, slug))+ .toMatchObject({ inserted: 2 });+ }+ expect([await brain.storageOf(INLINE), await brain.storageOf(SEGMENTED)]).toEqual(['inline', 'segmented']);+ }, 600_000);++ afterAll(() => brain.close(), 120_000);++ /** A page's versions (body as stored, read by generation for a segmented one) and belief events, slug-neutral. */+ const artifacts = async (slug: string) => {+ const { engine, sourceId } = brain;+ const [page] = await engine.executeRaw<{ id: number; revision: string }>('SELECT id, knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);+ const pageId = Number(page!.id);+ const rows = await engine.executeRaw<{ id: number; body_storage: string; body_generation: number | null; revision: string; compiled_truth: string | null; timeline: string | null;+ title: string; type: string; tags: unknown; is_deleted: boolean }>(`SELECT id, body_storage, body_generation, knowledge_revision::text AS revision, compiled_truth, timeline,+ title, type, tags, is_deleted FROM page_versions WHERE page_id=$1 ORDER BY id`, [pageId]);+ const versions = [];+ for (const v of rows) {+ let body = (v.compiled_truth ?? '') + '\u0000' + (v.timeline ?? '');+ if (v.body_storage === 'segmented') {+ const parts: Record<string, string[]> = { truth: [], timeline: [] };+ for await (const part of readSegmentedBody(engine, pageId, sourceId, { generation: Number(v.body_generation) })) parts[part.region]!.push(utf8.decode(part.bytes));+ body = parts.truth!.join('') + '\u0000' + parts.timeline!.join('');+ }+ versions.push({ revision: v.revision, title: v.title, type: v.type, tags: v.tags, is_deleted: v.is_deleted, body: body.split(slug).join('<slug>'),+ claim: body.toLowerCase().includes(CLAIMS[slug]!.toLowerCase()), kept: body.includes(KEPT) });+ }+ const events = (await engine.executeRaw<{ event_type: string; subject_kind: string; purged: boolean; cause: unknown; value: unknown }>(+ 'SELECT event_type, subject_kind, purged, cause, value FROM belief_events WHERE source_id=$1 AND slug=$2 ORDER BY id', [sourceId, slug]))+ .map(e => {+ const cause = (typeof e.cause === 'string' ? JSON.parse(e.cause) : e.cause) as Record<string, unknown> | null;+ const value = (typeof e.value === 'string' ? JSON.parse(e.value) : e.value) as Record<string, unknown> | null;+ const before = value?.revision_before as string | undefined, after = value?.revision_after as string | undefined;+ return { event_type: e.event_type, subject_kind: e.subject_kind, purged: e.purged, op: cause?.op ?? null,+ moved: !!before && before !== after, preimage: before ? rows.some(v => v.revision === before) : null };+ });+ return { revision: page!.revision, versions, events };+ };++ const purge = async (slug: string) => {+ const [fact] = await brain.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND fact=$3', [brain.sourceId, slug, CLAIMS[slug]]);+ const dry = await brain.call('purge_fact', { id: Number(fact!.id), dry_run: true }, slug);+ expect(dry.confirm_token).toBeString();+ const done = await brain.call('purge_fact', { id: Number(fact!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision }, slug);+ expect(done.state).toBe('committed');+ return done;+ };++ test('the segmented twin gets the inline twin\'s preimage version, events and receipt', async () => {+ const before = { inline: await artifacts(INLINE), segmented: await artifacts(SEGMENTED) };+ expect(before.segmented.versions.map(v => v.claim)).toEqual(before.inline.versions.map(v => v.claim));+ const receipts = { inline: await purge(INLINE), segmented: await purge(SEGMENTED) };+ const after = { inline: await artifacts(INLINE), segmented: await artifacts(SEGMENTED) };++ // The inline twin, as master writes it: one more version, holding the revision the purge moved off, without the claim.+ expect(after.inline.versions).toHaveLength(before.inline.versions.length + 1);+ const inlinePreimage = after.inline.versions.at(-1)!;+ expect(inlinePreimage.revision).toBe(before.inline.revision);+ expect({ claim: inlinePreimage.claim, kept: inlinePreimage.kept }).toEqual({ claim: false, kept: true });++ // The segmented twin: the same, as a reference to the generation it moved off (rebuilt without the purged row).+ expect(after.segmented.versions).toHaveLength(before.segmented.versions.length + 1);+ const segmentedPreimage = after.segmented.versions.at(-1)!;+ expect(segmentedPreimage.revision).toBe(before.segmented.revision);+ const [stored] = await brain.engine.executeRaw<{ body_storage: string; compiled_truth: string | null }>(`SELECT v.body_storage, v.compiled_truth FROM page_versions v+ JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1 AND p.slug=$2 ORDER BY v.id DESC LIMIT 1`, [brain.sourceId, SEGMENTED]);+ expect(stored).toEqual({ body_storage: 'segmented', compiled_truth: null });++ // Page events compare in order; one extraction's fact events are ordered by fingerprint, so they compare as a set.+ const strip = (a: Awaited<ReturnType<typeof artifacts>>) => ({ versions: a.versions.map(({ revision, ...v }) => v),+ pages: a.events.filter(e => e.subject_kind === 'page'), others: a.events.filter(e => e.subject_kind !== 'page').map(e => JSON.stringify(e)).sort() });+ expect(strip(after.segmented)).toEqual(strip(after.inline));+ expect(after.segmented.events.filter(e => e.moved).every(e => e.preimage === true)).toBe(true);+ expect(after.segmented.versions.some(v => v.claim)).toBe(false);+ // The canonical file is left out: the purge's withdrawal-mirror effect does not rewrite a segmented page's file yet+ // (src/core/persistence/effects.ts mirrorPage skips it with page_body_segmented), a gap outside this test.+ const view = async (slug: string) => { const { file, ...rest } = await brain.view(slug); return rest; };+ expect(await view(SEGMENTED)).toEqual(await view(INLINE));+ expect(JSON.stringify(await view(SEGMENTED))).not.toContain(CLAIMS[SEGMENTED]);++ // Chunk and segment-text counts differ by storage: the inline rewrite rebuilds every chunk, the segmented one only the rewritten segments'.+ const receipt = (r: Record<string, any>) => ({ removed: { ...r.purge.removed, chunks: undefined, page_segment_texts: undefined }, ledger: r.purge.ledger,+ stores: r.stores.filter((s: any) => ['pages', 'page_versions', 'facts', 'belief_events'].includes(s.store)), residuals: r.residuals.filter((x: any) => x.reason === 'source_prose') });+ expect(receipt(receipts.segmented)).toEqual(receipt(receipts.inline));+ expect(receipts.segmented.purge.ledger.purged_events).toBeGreaterThan(0);+ expect(receipts.segmented.residuals.filter((x: any) => x.reason === 'source_prose')).toEqual([]);+ expect(JSON.stringify(receipts.segmented)).not.toContain(CLAIMS[SEGMENTED]);+ }, 600_000);+ });+}diff --git a/test/large-pages/purge-replay-segments.test.ts b/test/large-pages/purge-replay-segments.test.tsnew file mode 100644index 0000000000..f88d563e22--- /dev/null+++ b/test/large-pages/purge-replay-segments.test.ts@@ -0,0 +1,166 @@+/**+ * Wave B PR 2 fix lane R, gap 2: a restore-time purge replay cleans segment storage as purge_fact does.+ *+ * 1. Protects: replaying a committed fact purge into a restored brain (replayPurgesInRestore, the step both the PGLite+ * restore and gbrain beliefs replay-purges run) rewrites a segmented page's live body and retained generation and then+ * deletes, in the same transaction, every segment text that held the purged claim and is no longer referenced: the+ * texts the rewrites replaced, and a text only an in-flight create recorded (page_body_staging_texts), whose staging+ * is aborted as purge_fact aborts it. An unrelated in-flight create keeps its staging and texts. Afterwards no row of+ * page_segment_texts holds the claim, and the purge receipt's page_segment_texts probe reads clean. A replayed page+ * purge deletes the texts only that page's manifests referenced with it, as delete_page purge:true does.+ * 2. Fails when: the replay rewrites segmented bodies but leaves the replaced texts or the staging-held text to segment+ * GC (or forever, while the staging pins it): the probe reads incomplete; or a replayed page purge deletes the page+ * row and leaves its segment texts behind.+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt). pages.segmented_storage is forced on.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { parseMarkdown } from '../../src/core/markdown.ts';+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';+import { segmentedBodyContains } from '../../src/core/page-body/segment-rewrite.ts';+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { stageSegmentedImport } from '../../src/core/persistence/segmented-apply.ts';+import { replayPurgesInRestore, type PurgeMirrorLine } from '../../src/core/belief/purge-mirror.ts';+import { planFactPurge, type PurgeTarget } from '../../src/core/facts/purge.ts';+import { verifyFactPurge } from '../../src/core/facts/purge-verify.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { segmentedPageRow } from '../helpers/segmented-page-checks.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';+import { withEnv } from '../helpers/with-env.ts';++const CLAIM = ['Vault', 'code', 'is', '9046'].join(' ');+const FENCE = [+ '<!--- gbrain:facts:begin -->',+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',+ '| 1 | ' + CLAIM + ' | fact | 1.0 | world | medium | 2026-01-01 | | chat | |',+ '| 2 | Likes green tea | preference | 1.0 | world | medium | 2026-01-01 | | chat | |',+ '<!--- gbrain:facts:end -->',+].join('\n');+const home = mkdtempSync(join(tmpdir(), 'gbrain-purge-replay-segments-'));+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+const coordinated = <T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>) =>+ engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => fn(tx), TEST_WRITE_ATTRIBUTION));++function filler(bytes: number, tag: string): string {+ const parts: string[] = [];+ for (let i = 0, n = 0; n < bytes; i++) {+ const part = '## Section ' + tag + ' ' + i + '\n\n' + ('Notes on launch planning, pricing and roadmap review for week ' + i + '. ').repeat(30) + '\n\n';+ parts.push(part);+ n += part.length;+ }+ return parts.join('');+}+const page = (title: string, body: string) => '---\ntitle: ' + title + '\ntype: note\n---\n\n' + body;+const withFence = (tag: string, tail: string) => '# Shared notes\n\nIntro paragraph.\n\n## Facts\n\n' + FENCE + '\n\n' + filler(1_300_000, tag) + '## Tail\n\n' + tail + '\n';++afterAll(() => { rmSync(home, { recursive: true, force: true }); });++for (const kind of testBackends()) {+ describe('restore-time purge replay on segmented pages (' + kind + ')', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ beforeAll(async () => withEnv(env, async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }+ await registerLocalWriter(engine, 'cli');+ await engine.setConfig('pages.segmented_storage', 'on');+ }), 120_000);+ afterAll(async () => withEnv(env, async () => { await disposePersistenceConsumer(engine); await close?.(); }));++ /** A create whose preparation finished (texts staged and recorded in page_body_staging_texts) and has not published. */+ async function inFlightCreate(slug: string, content: string): Promise<string> {+ const parsed = parseMarkdown(content, slug + '.md');+ const staged = await stageSegmentedImport(engine, { slug, sourceId: 'default', existing: null,+ page: { title: parsed.title, type: parsed.type, compiled_truth: parsed.compiled_truth, timeline: parsed.timeline, frontmatter: parsed.frontmatter, tags: parsed.tags },+ policy: await readPageBodyPolicy(engine), chunking: { quarantined: false, corpusGeneration: null, tier: 'none' }, baseRevision: null });+ return staged.prepared.stagingId;+ }+ const stagingState = async (id: string) => (await engine.executeRaw<{ state: string }>('SELECT state FROM page_body_stagings WHERE id=$1::uuid', [id]))[0]?.state;+ const carryingTexts = async () => Number((await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_segment_texts+ WHERE position(convert_to($1::text,'UTF8') in body)>0 OR strpos(lower(convert_from(body,'UTF8')),lower($1))>0`, [CLAIM]))[0]!.n);++ test('a replayed fact purge deletes the segment texts that held the claim, staging-held ones included, and the probe reads clean', async () => withEnv(env, async () => {+ const tag = randomUUID().slice(0, 8);+ const slug = 'notes/replayed-' + tag;+ // The restored brain: a segmented page whose live body and a retained generation hold the claim's fence row,+ // the fact row, an in-flight create that recorded a claim-bearing text, and an unrelated in-flight create.+ await importFromContent(engine, slug, page('Replayed', withFence(tag, 'First tail.')), { sourceId: 'default', noEmbed: true });+ await coordinated(engine, tx => tx.createVersion(slug, { sourceId: 'default' }));+ await importFromContent(engine, slug, page('Replayed', withFence(tag, 'Second tail, rewritten.')), { sourceId: 'default', noEmbed: true });+ const row = await segmentedPageRow(engine, slug);+ expect(row.body_storage).toBe('segmented');+ const [version] = await engine.executeRaw<{ body_generation: number }>(`SELECT body_generation FROM page_versions WHERE page_id=$1 AND body_storage='segmented'+ ORDER BY id LIMIT 1`, [row.id]);+ expect(Number(version!.body_generation)).toBeLessThan(row.body_generation);+ const [fact] = await coordinated(engine, tx => tx.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,fact,entity_slug,visibility,source,source_markdown_slug,row_num)+ VALUES ('default',$1,NULL,'world','test',$2,1) RETURNING id`, [CLAIM, slug]));+ const holder = await inFlightCreate('notes/holder-' + tag, page('Holder', withFence(tag + '-holder', 'The in-flight create tail.')));+ const bystander = await inFlightCreate('notes/bystander-' + tag, page('Bystander', '# Other notes\n\n' + filler(1_300_000, tag + '-bystander') + '## Tail\n\nThe bystander tail.\n'));+ const bystanderShas = (await engine.executeRaw<{ sha: string }>("SELECT encode(sha256,'hex') AS sha FROM page_body_staging_texts WHERE staging_id=$1::uuid", [bystander])).map(r => r.sha);+ expect(bystanderShas.length).toBeGreaterThan(0);+ expect(await carryingTexts()).toBeGreaterThan(0);++ const [target] = 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`, [fact!.id]);+ const purged = { ...target!, id: Number(target!.id) };+ const plan = await planFactPurge(engine, purged, false);+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ const request = randomUUID();+ const lines: PurgeMirrorLine[] = [+ { kind: 'intent', request, request_id: request, source_id: 'default', source_incarnation: source!.incarnation, scope: 'fact', recorded_at: new Date().toISOString(),+ purge_epoch: 1, facts: [{ fact_hash: purged.fact_hash, visibility: 'world', subject: '*' }], takes: [], lifetimes: [] },+ { kind: 'committed', request, recorded_at: new Date().toISOString() },+ ];+ const result = await engine.transaction(tx => replayPurgesInRestore(tx, { lines, archivedAt: new Date(Date.now() - 60_000).toISOString(), restoreId: randomUUID() }));+ expect(result.replays.map(r => [r.request, r.outcome])).toEqual([[request, 'complete']]);++ expect(await segmentedBodyContains(engine, row.id, 'default', [CLAIM])).toBe(false);+ expect(await segmentedBodyContains(engine, row.id, 'default', [CLAIM], { generation: Number(version!.body_generation) })).toBe(false);+ expect(await segmentedBodyContains(engine, row.id, 'default', ['likes green tea'])).toBe(true);+ expect(await carryingTexts()).toBe(0);+ expect(await stagingState(holder)).toBe('aborted');+ expect(await stagingState(bystander)).toBe('prepared');+ expect(Number((await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_segment_texts+ WHERE source_id='default' AND sha256=ANY(SELECT decode(h,'hex') FROM unnest($1::text[]) AS h)`, [bystanderShas]))[0]!.n)).toBe(bystanderShas.length);+ const receipt = await verifyFactPurge(engine, { target: purged, plan, dryRun: false, removed: {} });+ expect(receipt.stores.find(s => s.store === 'page_segment_texts')).toMatchObject({ status: 'not_present' });+ for (const store of ['pages', 'page_versions', 'facts']) expect({ store, status: receipt.stores.find(s => s.store === store)?.status }).toEqual({ store, status: 'not_present' });+ }), 300_000);++ test('a replayed page purge deletes the segment texts only that page referenced', async () => withEnv(env, async () => {+ const tag = randomUUID().slice(0, 8);+ const slug = 'notes/page-replayed-' + tag;+ const marker = 'Page scope tail ' + tag;+ await importFromContent(engine, slug, page('Page replayed', withFence(tag + '-page', marker + ' one.')), { sourceId: 'default', noEmbed: true });+ await coordinated(engine, tx => tx.createVersion(slug, { sourceId: 'default' }));+ await importFromContent(engine, slug, page('Page replayed', withFence(tag + '-page', marker + ' two.')), { sourceId: 'default', noEmbed: true });+ const row = await segmentedPageRow(engine, slug);+ expect(row.body_storage).toBe('segmented');+ const shas = (await engine.executeRaw<{ sha: string }>("SELECT DISTINCT encode(sha256,'hex') AS sha FROM page_body_manifest WHERE page_id=$1", [row.id])).map(r => r.sha);+ const texts = async () => Number((await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_segment_texts+ WHERE source_id='default' AND sha256=ANY(SELECT decode(h,'hex') FROM unnest($1::text[]) AS h)`, [shas]))[0]!.n);+ expect(await texts()).toBe(shas.length);+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ const request = randomUUID();+ const lines: PurgeMirrorLine[] = [+ { kind: 'intent', request, request_id: request, source_id: 'default', source_incarnation: source!.incarnation, scope: 'page', slug, content_hashes: [row.content_hash],+ recorded_at: new Date().toISOString(), purge_epoch: 1, facts: [], takes: [], lifetimes: [] },+ { kind: 'committed', request, recorded_at: new Date().toISOString() },+ ];+ await engine.transaction(tx => replayPurgesInRestore(tx, { lines, archivedAt: new Date(Date.now() - 60_000).toISOString(), restoreId: randomUUID() }));+ expect(await engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2', ['default', slug])).toHaveLength(0);+ expect(await texts()).toBe(0);+ expect(await engine.executeRaw("SELECT 1 FROM page_segment_texts WHERE position(convert_to($1::text,'UTF8') in body)>0", [marker])).toHaveLength(0);+ }), 300_000);+ });+}diff --git a/test/large-pages/purge-segmented-versions-batch.test.ts b/test/large-pages/purge-segmented-versions-batch.test.tsindex c83c81cfd8..4acb941469 100644--- a/test/large-pages/purge-segmented-versions-batch.test.ts+++ b/test/large-pages/purge-segmented-versions-batch.test.ts@@ -12,7 +12,9 @@* 3. Fixture: 5,000 extra version rows of the first page reference generation* 0, which no manifest row covers (an empty, 0-byte generation, so each costs* one manifest read and its rows tile it),- * and push the second page's real version past the first batch.+ * and push the second page's real version past the first batch. purge_fact versions each page before rewriting it,+ * and every segmented version insert prunes the page's history to `versions.segmented_max_per_page`, so the fixture+ * raises that cap above the 5,000 extra rows: the redaction still walks them.* Runs on PGLite, and on Postgres when DATABASE_URL is set.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';@@ -65,7 +67,11 @@ const coordinated = <T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>beforeAll(async () => withEnv({ GBRAIN_HOME: home }, async () => {const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }- for (const engine of engines) { await registerLocalWriter(engine, 'cli'); await engine.setConfig('pages.segmented_storage', 'on'); }+ for (const engine of engines) {+ await registerLocalWriter(engine, 'cli');+ await engine.setConfig('pages.segmented_storage', 'on');+ await engine.setConfig('versions.segmented_max_per_page', '10000');+ }}), 120_000);afterAll(async () => { for (const engine of engines) await engine.disconnect(); await closePostgres?.(); rmSync(home, { recursive: true, force: true }); });diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex b4391dbd95..865438b37f 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -96,7 +96,9 @@ test/large-pages/pinned-segmented-reads.test.tstest/large-pages/projection-demotion-race.test.tstest/large-pages/projection-parity.test.tstest/large-pages/purge-fact-inflight-staging.test.ts+test/large-pages/purge-fact-segmented-preimage.test.tstest/large-pages/purge-inflight-create.test.ts+test/large-pages/purge-replay-segments.test.tstest/large-pages/purge-segment-residue.test.tstest/large-pages/purge-segmented-versions-batch.test.tstest/large-pages/purge-segments.test.ts