Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: memory purge
Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG. User-facing contract: expire versus purge.
src/core/facts/purge.ts—submitPurgeFactMutation, the handler of the owner-onlypurge_factop (gbrain forget <id> --purge). Refuses every caller whosectx.remote !== falsewithtrusted_local_only(purgeHostOnly, actor user, the exact host command).planFactPurge(read-only) computes the scope: every fact row with the samegbrain_fact_fingerprintin the fact's source, visibility and subject (the fact'sentity_slug,'*'withall_subjects) except extraction outcome rows (outcomeMarkerSql; the receipt's fact probes,purgeCompletionand the restore replay skip them too, #7831), verbatim takes (facts.consolidated_intoplus same-fingerprint takes on the subject's page), affected pages fromdiscoverWithdrawalTargets, page_versions carrying the text, terminal request intents carrying it (findRequestsCarryingbehind thepurge:carrying_lookupseam; its 57014 is the typedpurge_lookup_timeout, nothing planned or purged, pinned bytest/fact-purge-lookup-timeout-6511.test.ts), derived rows fromderivation_inputs, the fact's P8 review rows, and arevisiondigest. A dry run returns the receipt,confirm_token(fingerprint's first 8 hex) andexpected_revision; a real run requiresconfirm === tokenand, 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: sourceFOR UPDATE(serializes with the guards'FOR SHARE), counters for the purge and every redacted request, admission, then insidewithCoordinatedWrite: pending-publication refusal (purge_blocked_pending_recovery), intent redaction, page locks, derived rows hidden before evidence goes,fact_purges/take_purgestombstones, 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, legacyquery_cachecleared, andwithdrawal-mirror/git/embeddingeffects withmode: 'purge'andcommit_subject: gbrain: purge fact <hash8>. Chunks are rebuilt before acknowledging;similar_activeis computed before deletion. Pinned bytest/purge-fact.test.ts(both engines) andtest/forget-purge-cli.test.ts; the segmented preimage version bytest/large-pages/purge-fact-segmented-preimage.test.ts(inline twin parity, both engines). Segmented pages (Wave B): live bodies are rewritten fence by fence throughrewriteLiveSegmentedFences(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 throughrewriteSegmentedGeneration; the plan (and its digest) also lists open, sealed or prepared stagings whose staged texts or parts hold the claim plus the queued requests whosebody_refnames them (stagingsHoldingClaim, which also readspage_body_staging_texts;findRequestsHoldingStagings): the stagings are aborted with their parts deleted, the requests cancelled withpurged_content(a running or recovering one refuses withpurge_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.verifyFactPurgeruns one bounded adapter per store (row bound, per-statementstatement_timeout, a total deadline;__setPurgeProbeLimitsForTests): swept stores reportdeleted,incomplete(still holds the claim) orunverified(bound hit); page-text stores report remaining text asout_of_scope: source_prose; everyprobed_reportedinventory table is probed and listed; derived rows areretained_inactive; model-derived pages without edges arederived_legacy: unverified. On-disk: page files (canonical_markdown), a quarantined<file>.tmpcarrying the claim is deleted, the facts write-failure log is reported.gitResidualCommitsscansgit log --all -p -- <page paths>output in-process (the pattern never enters argv; byte and time bounded) and lists commits;OUT_OF_REACH_RESIDUALSlead 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); queuedpersistence_effectswhose data, outcome or recovery carry it are reported;belief_eventsandfact_contextget ledger reports. The vector probe returns same-model neighbours as paraphrase candidates and is never a gate.purgeCompletionderivescommitted | complete | incompletefrom 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_textsgets an exact-bytes probe (an unreferenced text holding the claim isincomplete, a referenced oneout_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 bumpssources.purge_epoch(bumpPurgeEpoch; an append prepared at an older epoch withpreparedEpochrefusesbelief_stale_preparation) and runs three passes inside the purge transaction:redactPurgedKeys(the purged keys, byclaim_fpand 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 byquotesoverclaimForms, never SQLlower()/strpos: each carrying field fromCARRYING_FIELDSthat quotes a purged claim, plain or fence-escaped, becomesREDACTION_MARKER(<purge request>)and is listed inredacted_fields; a later event's prior_hash naming the old hash names the new one) withregisterLiveCarriers(a surviving row whose field quotes the claim entersbelief_redactionswith its field hash, so its next event writes the marker until an explicit owner edit sets a different value:publicationBeliefOptionsmarksownerEditonly on a localput_page,edit_page,takes_updateortakes_resolvewith no internal intent kind, and append still needsOWNER_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 (ceodoes not matchherbaceous; CJK and markup still match), andappendDerivedHidden(onederived.hiddenper key the derivation walk hid;readBeliefHistorythen hides that key's earlier events and every backfill event of it). A page purge's claims come frompagePurgeClaims: the page's facts and takes, every retained version's fence rows and every claim in its lifetimes' events, unbounded.releaseSuppressedFieldsis the owner releasetrust confirmruns (belief_redactions.released_hash); every release, there or in an owner-edit append, appends oneredaction.released(redactionReleasedDraft: fields, purge requests and released hashes, never the text) in the publicationreleased_bynames. The receipt'sledgerblock reports the counts andderived_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 isincomplete, another subject's recorded value quoting the claim isout_of_scopewithfield@keyitems. 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): anintentline 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 typedpurge_mirror_unwritable, with or without a ledger) and acommittedline after (appendPurgeCommitted, best effort; a page purge writes it from the coordinator'safterCommit, 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 throughrewritePageBodies/redactPageVersions, then runspurgeSegmentStoragewith each claim'sstagingsHoldingClaim; a page-scope replay deletes the page throughdeletePageWithSegments, so segment texts that held the purged content go in the replay, as in the purge), the three passes, the derived rows hidden again withderived.hiddencauserestore_replay, onefact.purged/page.purgedwith causerestore_replay; a page-scope replay matches pages by content hash or lifetime, never by slug alone; an archive from before the ledger, nobelief_events, replays tombstones and row removal and reportsledger: 'absent'; an intent whose request already has tombstones is skipped), records each ascomplete,partial(no restored row held the text, or the derivation walk could not run) orunverified(intent without committed line, not replayed), returnspurge_replayin the receipt and adds a reconnect warning unless the state isnoneorcomplete; an unreadable mirror isunavailable.coverage.restoredcarries the outcome, whichreadRestorePurgeReplayreads back for the doctor. A Postgres restore runsgbrain 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:replayPurgesruns the replay in a transaction that rolls back), whose database sourcepurgeLinesFromDatabaserebuilds the intents from every pre-restore tombstone (not bounded bypurged_at, the purge transaction's start) and skips those the archive already holds. #9469: a page-scope replay runs the live purge's sweep (page-purge.tssweepPurgedPage, thendeletePurgedPage), with one uncapped journal census per source per replay run (replayRun), and stops withpurge_replay_incompletenaming the request when a sweep cannot complete (a missing table aside). Seam:__setPurgeReplayFaultForTests(faultincomplete_census). Probes:test/belief-ledger-restore.test.ts; segment storage after a replay:test/large-pages/purge-replay-segments.test.ts(both engines).src/commands/doctor/checks/purge-mirror.ts—purge_mirror(#9469): compares the request ids of the last 30 days'page_purges,fact_purgesandtake_purges(capped at 10,000,details.capped) with the intent lines of this process's purge mirror (configDir()), and warns when any is missing; never a failure, never reads the request journal, prints counts and the mirror path only (no slug, title or text). Fix: one durableGBRAIN_HOMEfor every writer (memory boundaries). Test:test/doctor-purge-mirror.test.ts.src/core/facts/gone-page-facts.ts—expireGonePageFacts(exec, pages): in the transaction that removes a page row for good, expires (never deletes) the active facts filed on the page (ontology observations excluded: theirsource_markdown_slugis provenance) and the active facts about it that no page row holds (a soft-deleted holder keeps its fact for a restore), so they don't come back for readers once the tombstone is gone and a new page at the slug starts clean. A conversation fact's slot (dimensionset on a numbered row, GBRA-574 B2) counts as filed on the page: the row is expired and gives up its slot. Two updates, one per slug index. Facts have no foreign key to pages. Called by the bulk retention purge (engine-sql/pages.tspurgeDeletedPages) and the belief-ledger purge of a recorded source (persistence/purge-deleted.tsexpireRecordedTombstones).src/core/facts/purge-overlay.ts— purge mode of the import overlay:dropPurgedFenceRowsdrops facts-fence rows matchingfact_purgesand takes-fence rows matchingtake_purges(the takes fence re-renders with its reservation rows plus the dropped numbers reserved, so a purged number is never reused; pinned bytest/purge-overlay-reservations.test.ts) (subject = page slug; malformed fences left to the withdrawal diagnostics, which refuse a purged claim inside one). Called first bypreserveWithdrawnFenceRows, soimport-file.tsneeds no change; the snapshot overlay (page-state/snapshot.ts) and export (export-snapshot.ts) carry purge tombstones asPageWithdrawal.purged, whichoverlayWithdrawalBodydrops instead of striking.src/core/facts/purge-schema.ts—MEMORY_PURGE_SCHEMA_SQL(schema.sql fragment:fact_purges,take_purges,page_purgeskeyed(source_id, content_hash),derivation_inputs,needs_rederive) andMEMORY_PURGE_GUARD_SQL(migration only):facts_refuse_purged,takes_refuse_purgedandpages_refuse_purgedraiseP0001 purged_content: …(mapped to typedpurged_contentbypersistence/publication-failure.ts) instead of skipping the row, whateverexpired_atsays. The pages guard has no column list so it never pins columns. Since migration v264facts_refuse_purgedfires on UPDATE only; the facts insert check runs once per statement infacts/insert-guard-schema.ts.FACT_PURGE_LOOKUP_INDEX_SQL(migration v231, CONCURRENTLY on Postgres) addsfact_purges_subject_idx(a page's own tombstones, the '' lookup by fingerprint) and the partialfact_purges_all_subjects_idx(subject '' only, for the snapshot marker count).src/core/facts/insert-guard-schema.ts—FACT_INSERT_GUARD_SQL(migration v264, #7105): one statement-levelfacts_guard_insertedtrigger (AFTER INSERT ... REFERENCING NEW TABLE AS inserted_facts, functiongbrain_guard_inserted_facts) runs the purge refusal, and the withdrawal stamp of deferred inserts, once per statement instead of once per row. It takesFOR SHAREon each inserted source row, refuses a statement whose rows match afact_purgestombstone with the sameP0001 purged_contentmessage and{table, hash8}detail (the first matching row in insertion order, whatever itsexpired_at), then stamps inserted active rows still matchingfact_withdrawals(v2 or v1 fingerprint) withexpired_at = min(withdrawn_at)and a clampedvalid_until, by an UPDATE of just those rows, run under the transaction-localgbrain.fact_withdrawal_stampsetting (FACT_WITHDRAWAL_STAMP_SETTING, reset after the UPDATE) sogbrain_stamp_write_attributionkeeps thelast_write_*andlast_written_atthe INSERT stamped or supplied. By default an insert is stamped before it is written by the per-rowfacts_preserve_withdrawal_insert(BEFORE INSERT ... WHEN (NEW.expired_at IS NULL AND <deferral off>), the original function), soINSERT ... RETURNINGreads the stamp; the bulk fence insert (engine-sql/facts.tsinsertFactRows) setsgbrain.fact_withdrawal_stamp_deferred(FACT_WITHDRAWAL_STAMP_DEFERRED_SETTING) around its INSERTs, so the WHEN clause, which calls no function, skips the trigger and the statement guard stamps instead. The setting moves the stamp and never skips it: the guard stamps every still-matching active row whoever set it. A ledger with no row for the inserted sources costs one index probe. Transition tables cannot take a column list, sofacts_refuse_purgedandfacts_preserve_withdrawalstay per-row for UPDATE (BEFORE UPDATE OF ...). Differences from the per-row insert guards: (1) a row ON CONFLICT DO NOTHING skips is not checked (it is not written either); (2) a row that another per-row BEFORE trigger (for examplemanaged_writer_guard) or a constraint also refuses reports that refusal first; (3) a deferred insert is stamped after its RETURNING, soINSERT ... RETURNING expired_at, valid_until(or a CTE reading it in the same query) made under the deferral setting sees a withdrawn row unstamped while storage and every later statement see the stamp (insertFactRowsreturns only ids, slugs and row numbers). Pinned bytest/facts-insert-guards-7105.test.ts(guard calls and firings per statement, RETURNING with and without deferral, and the same refusals, stamps and attribution as the per-row guards re-installed in a rolled-back transaction, both engines). #7778 (migration v279,FACT_INSERT_GUARD_FUNCTION_SQL): the purge refusal skips an extraction outcome row (isOutcomeMarker/outcomeMarkerSqlinfacts/audit-sources.ts: a conversation-facts audit source AND the exact textEXTRACTION_COMPLETEorEXTRACTION_NOT_APPLICABLE), so a wildcard tombstone a page purge wrote before the fix no longer keeps pages from completing; a user claim with that text is still refused. Pinned bytest/conversation-facts-outcome-marker-purge-7778.test.ts.src/core/page-state/snapshot.ts— a page snapshot lists only the page's ownfact_purgestombstones; subject-'' ones come back asPageSnapshot.globalPurges(count, latestpurged_at, world-only flag; absent at count 0).resolveGlobalPurgesturns the marker into purge withdrawals for the fence rows of whatever text is overlaid (stored page, incoming file inpage-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:readPageSnapshotwithresolveAliasfirst runs the exact-slug statement (an exact hit outranks every alias), then, on a miss or forrequireUnambiguous, oneWITH chosenstatement whose candidates are a UNION ALL of the exact-slug probe and an alias-join probe (slug_aliases→pageson(source_id, canonical_slug),p.slug<>$1keeps the branches disjoint socount(*) OVER ()still counts pages). #6281: neverslug=$1 OR EXISTS(alias), which read every page of every readable source;page-snapshot-alias-plan.test.tspins fewer than 100pagesrows per statement from EXPLAIN on both engines.src/core/facts/derivation-inputs.ts—recordDerivationInputs(tx, {table, id, sourceId}, inputs): complete derived-row → input edges, written by derivers in the deriving transaction (write_originkeeps only a display sample).derivedRowsFromwalks edges breadth-first (bounded, reportstruncated);hideDerivedRowsexpires facts, deactivates takes, soft-deletes pages and upsertsneeds_rederive.src/core/deletion-inventory.ts— the deletion-target registry: every table with a text, JSON, bytes, array, lexeme or vector column, classedswept,retained_inactiveorout_of_scope(probed_reportedwith probe columns,text_free_ledger,secret_material,no_memory_text), plus on-disk stores and out-of-reach residuals.test/deletion-inventory.test.tsfails 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 bypersistence_requests_slug_intent), the page purge's preparation-time journal censussweepRequestsCarrying(#6511: a keyset walk of the source's journal inJOURNAL_SWEEP_CHUNK_ROWSchunks, 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 atJOURNAL_SWEEP_MATCH_CAP; returns the carrying ids, the ids pending at the scan, thesequenceceiling as text andcomplete; #6884:sweepRequestsForGroupsruns it once for several needle groups, each row read and lowered once and every hit attributed to the groups carrying that needle, the match cap per group, andafterstarts past an earlier ceiling) withrecheckRequestsCarryingfor the publication's bounded re-check of the tail past the ceiling and of the rows that were pending,redactRequestIntentslocks counters then request rows, refuses on a non-terminal or recovering request (unlessskipPending), nullsintent/error_messageand 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 unclaimed requests (queued, or deferred behind a refresh: GST-1602,test/refresh-barrier-purge-gst1602.test.ts) whoseintent.body_ref.staging_idnames a staging a fact purge aborts are completedcancelledwithpurged_content; a claimed one refusespurge_blocked_pending_recovery.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 codedpurged_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_contentis a write error code, so receipts and the frozen verb path (wireinvalid_params, canonicalpurged_content) keep it typed.src/core/persistence/page-purge.ts— #6884:preparePagePurgetakes its census fromsweepForPurge: a purge an earlier batch sweep covered for all of its current claims scans only the tail past that sweep's ceiling (journal_sweep.watermark); otherwise it sweeps once for its own claims and those of the next queued purges of the source (up toPURGE_SWEEP_BATCH_MEMBERS,PURGE_SWEEP_BATCH_NEEDLESclaim forms) and caches each member's result in process memory (never in the journal;journal_sweep.batchcounts the purges one sweep covered). Rows a member's cached census saw as pending, the leader's own row included, are re-tested at publication. Tests:test/page-purge-batch-sweep-6884.test.ts.purgePageInTransaction, called by thedelete_page purge:trueapply inpage-prepare.ts: records inpage_purgesthe 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 legacyquery_cache; tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices andfilesrows, the page'spage_aliasesand theslug_aliasesredirects whosecanonical_slugis the page (#6619; a redirect from this slug to another page stays; counted inremovedand 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:preparePagePurgerunsreadPurgeClaimsandsweepRequestsCarryingunder the preparation budget at stepspurge_claims/purge_journal_sweep, so the O(journal) substring scan is a chargedpreparation_deadlinerelease andpreparation_stalledat the attempt limit, never a transaction timeout; the lookups that stay inside the transaction go throughlookup, which maps a 57014 to the terminal, non-retryablepurge_lookup_timeoutnaminggbrain repair request-indexesonly whenpersistence_requests_slug_intentis missing or INVALID; the receipt'sjournal_sweepreportsceiling,scanned,tail,pending_recheckedandcomplete), then deletes the page (FK cascades).PURGE_RESIDUALSnames what stays out of reach.finishPagePurgedeletes stored blobs after commit, lists any left by storage path, and attachesreceipt, the store-by-store receipt fromverifyPagePurge(same shape as the fact receipt: residuals first, every swept inventory store, other pages' prose naming a purged claim assource_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.residualsstays the prose string.readPagePurgeTombstonesfeedsscreenImportContent({ 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 aspurged_content; direct imports andput_pagehit the pages guard instead;listPagePurges/unpurgePage(also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned bytest/page-purge.test.tsandtest/page-purge-journal-timeout-6511.test.ts(both engines; seamspurge:*infault-points.ts). #6368: a purge of a tombstone whose file matchessync.exclude(discovery's globs viasyncExcludePatternsinsync-discovery.ts, matched relative to the source root) owns no file:prepareFileTarget'sexcludeTombstoneoption returns no target, the purge is database-only and the receipt sayswrite_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 refusessource_changedif it was removed meanwhile. Live-page purges and soft deletes are unchanged. A segmented page or version is never loaded whole: its storedcontent_hashand the purge-overlaid hash streamed byrewrittenContentHashare tombstoned; its stagings (by slug or page id) and the segment texts its manifests referenced or its stagings recorded inpage_body_staging_texts(LPH (h), N14-5: a text an earlier write's sweep dropped from the manifest stays unreferenced for the GC grace window, and only the page's staging still names it) that no manifest row references, plus the source's unreferenced texts holding one of the page's claims (every fact filed on it, withdrawn ones included, and every take, not the journal sweep's first 32, tested in batches ofCLAIM_FORMS_BATCHforms; plain or as a fence cell stores it,claimTextFormsin fence-shared.ts: a text another page's write reused outlives this page's 24-hour staging record), 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 inpage_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). #7778: the page's tombstones, mirror facts and journal and segment sweeps leave out its extraction outcome rows (outcomeMarkerSql); a subject-'*' tombstone on the shared marker text would keep every page of the source from recording its outcome. #9469: the in-transaction sweep issweepPurgedPage(its stores arePURGE_SWEEP_STORES) and the deletedeletePurgedPage, both shared with the restore-time page-scope replay.src/core/ops/purge.ts—purge_fact,list_page_purges,unpurge_page: admin scope,cliOnly(every MCP route getstrusted_local_only). The resident owner runs them only for its verified local CLI registration (LOCAL_CLI_OWNER_OPERATIONSinpersistence/ipc.ts, checked inpersistence/provider.ts).src/commands/forget-purge.ts+src/commands/pages-purges.ts— the CLI fronts.runForgetPurgealways runs the dry run, then a typed token on a terminal or--yesplus--request-idwithout one;--matchlists ids,--statuspolls completion;PURGE_FAMILY_HELPis the purge-family table shown bygbrain forget --help.gbrain pages purges listandgbrain pages unpurge <slug>run the page-tombstone ops as the trusted CLI.Withdrawn-claim refusal on
remember(persistence/memory-mutations.ts,memory-prepare.ts) — admission refuses a withdrawn claim (fact_withdrawn,FACT_WITHDRAWN_MESSAGE/_SUGGESTIONinsrc/core/facts/withdrawal.ts) before a request exists, and preparation re-checks it;writeFailureDiagnosticallowlists that prefix, so a failed receipt andget_write_requestname it.replacesaccepts a target saved without an entity (links it by supersession). Test:test/remember-withdrawn-claim.test.ts. (R1, Cat 40 Hard.) The refusal carries an additivewithdrawnobject (factWithdrawnRefusalinfacts/single-prepare.ts, fromfact_withdrawalsonly: the named entity's row overall_entities, then the newest, omitted when the caller cannot read the forgotten rows);withdrawalFailureDetail/withdrawnFromDetailinfacts/withdrawal.tskeep it in the failed receipt'serror_detailforget_write_requestand replay. Tests:test/withdrawn-detail.test.ts,test/e2e/withdrawn-detail-postgres.test.ts.src/core/persistence/purge-deleted.ts—purgeDeletedPagesCoordinatedbacks the cyclepurgephase, the purge job,purge_deleted_pagesandgbrain pages purge-deleted. Unmanaged brains keep the engine bulk delete, after the belief-ledger expiry of recorded sources' tombstones: each is its own transaction and item (ItemRun sitepurge.recorded_tombstones), a run-scoped failure or a systemic run stops the purge, and any other failure lists the tombstone inblockedwith its classified code, counts it infailed(noerror, so the phase warns) and keeps it out of the bulk delete (purgeDeletedPagesexcludeIds); a content failure counts toward the same park as the managed purge, a transient one is retried next run, and parked tombstones are skipped aspurge_parkedunlessretryParked(the unmanaged preview excludes them too). A managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) throughdelete_pagewithpurge: trueand the internalretention: truebound to its revision (retention is not an owner purge; see belief ledger). Writer state is read once per run (writerOnboardingPreflight): a source whose writer isrecovery_requiredsubmits nothing and its tombstones are listed inblockedaswriter_not_active(counted ininactive). Revision races are deferred to the next run; a parked tombstone (purge-parks.ts) is skipped aspurge_parked(counted inparked) unlessretryParked, and any other failure is listed inblockedand setserror.selectPurgeCandidatesis the one eligibility selector (preview, consent,purge_deleted_pagesop, run), and its holds arepurgeHoldsSql(archived source, rename-identity, restorable-atom and derived-retirement holds), which doctorembedding_statealso counts with; #6884: the run submits only while the writer has outstanding-request room (readOutstandingRoominjournal.ts, atpersistence.capacity.background_pause_pctof the cap for a background run); the rest, and the rest after aqueue_capacityrefusal, isblockedaswrite_capacity_deferredand counted incapacity_deferred, never a failure or a park.purgePhaseStatus/purgePhaseNoteshape the cycle purge phase (fail onerror; warn onwriter_not_active, parked, capacity-deferred or an unmanagedfailedtombstone). The engine bulk delete (engine-sql/pages.tspurgeDeletedPages) also deletes, in its transaction, the purged pages' stagings (by source and slug) and the segment texts only their manifests referenced. GST-2689: every run first callsrepair/origin-carry.tscarryPrivateBeforePurge(both branches); the origins it parks are listed inblockedasderived_origin_parkedand counted inorigin_parked(the phase warns), andderivedOriginPurgeHoldis inpurgeHoldsSql, the recorded-tombstone scan and delete, and the engine bulk delete. GST-2766: a page whose owner purge was held is owed that purge (derived-origin-hold.tsrecordOwedPurge, opowed-page-purge, keyed by page id, no slug, live only while that tombstone exists); a managed run submits it as the owner purge, and an unmanaged run keeps it out of both bulk expiries and submits it throughpurgeOwedPagesas an explicitdelete_pagepurge, so the purge tombstones are written whichever run removes the page. The purge transaction (page-purge.tsdeletePurgedPage),engine-sql/pages.tsrestorePageand therestore_pageapply clear the record. Tests:test/managed-writers-w3.test.ts,test/purge-deleted-parks.test.ts,test/purge-deleted-capacity-6884.test.ts,test/pathological/a49-unmanaged-purge-tombstones.test.ts,test/derived-origin-carry-private.test.ts.src/core/persistence/derived-retirement-hold.ts— GBRA-161: the purge hold for every derived retirement.DERIVED_RETIRED_BYlists theretired_bystamps derived writers put on the pages they retire (extract-atoms, managed-reextract, stale-atoms, life-chronicle);derivedRetirementPurgeHold(alias)keeps a stamped page out of every purge route (engine bulk purge and its preview, the coordinated selection and delete) untilDERIVED_RETIREMENT_HOLD_DAYS(30) afterdeleted_at(the database clock, never theretired_attext);retireDerivedPagesversions, soft-deletes and stamps a batch in one attributed transaction (unmanaged extract_atoms).stampDerivedRetirementis the one retirement stamp every derived writer calls inside its own write (managed atom and generation retirements,gbrain repair stale-atoms, a journaled chronicle retire); it runs underwithTrustKeep, so the page keeps its stored trust tier and write origin (#9456,test/atom-retirement-keeps-trust-9456.test.ts).assertRetirementStampUnchangedis the page preparer's refusal (reserved_frontmatter_key) of a remote write that adds or changes one ofRESERVED_RETIREMENT_KEYS. The hold length followsgenerations.restore_days(RESTORE_DAYS_SQL, read inside the purge statement; 30 by default) andretireDerivedPagesInTransactionis the in-transaction form generation adapters retire through. An explicitgbrain delete --purgeis not held.src/core/generations/ledger-scrub.ts— GBRA-161: purge reaches the generation ledger. A page purge (page-purge.ts) nulls the purged item's preimages inderived_generation_itemsand every held proposal inderived_generationsnaming it, and deletes the page's fence holds (FENCE_GENERATION_KINDSunderpage:<slug>, whose rows the purge deletes;test/generations-purge-fence-hold-7774.test.ts); a fact purge (facts/purge.ts) nulls every preimage, proposal and held context carrying the claim. Both areswept(generation_ledger) in the deletion inventory, so the verification probes them;gbrain repair generationsthen refuses a scrubbed item withno_preimage.src/core/persistence/purge-name-stores.ts— #9068:scrubPurgedNameStores(engine, sourceId, slugs)deletes the source'scontext_volunteer_eventsrows (whose rationale quotes the matched name) andmention_gazetteer_entriesrows (name_norm -> target_slug) for purged slugs. Every hard delete of a page calls it inside its transaction (purgePageInTransaction,purgeDeletedPages,expireRecordedTombstones, the restore purge replay inbelief/purge-mirror.ts, and the engines' batchdeletePages); removing a source deletes the source's volunteer rows (removedSourceScrubCtesinsource-delete.ts) and its gazetteer rows by cascade; a soft delete keeps both. Both tables areswept(page_names) in the deletion inventory; the page receipt checks them by slug, and the fact receipt probes them (rationale, name_norm) and reports a match asprobed_reported, because a fact purge sweeps neither.src/core/persistence/purge-slug-stores.ts— #9146:scrubPurgedSlugStores(engine, sourceId, slugs, { ifPresent })deletes the six stores keyed to a page by source and slug with no foreign key to pages (take_proposals,open_loops,core_edit_notices,page_aliases,slug_aliasesbycanonical_slug,slug_rename_historybynew_slug) and returns rows removed per store;scrubPurgedSlugHoldsdeletes the slug'swrite_gate_holdsand theirwrite_gate_receipts, and on a tombstone expiry (deletedAtgiven) keeps a hold created or last seen after the soft delete. Every hard delete calls them inside its transaction (purgePageInTransactionfor the stores,expireRecordedTombstones, the engines' batchdeletePagesand purge path, the restore purge replay inbelief/purge-mirror.tswithifPresent); a soft delete keeps them. Source removal deletescore_edit_noticesand the holds with their receipts inremovedSourceScrubCtes; the other five cascade from sources. Test:test/purge-slug-stores-9146.test.ts.src/core/persistence/atom-retirement-hold.ts— #7013: the one SQL rule for atomsgbrain repair atoms-restorerestores.atomRetirementsSql(scope)is set-based (CTEs overpagesjoined on source and origin key, linear in the atoms in scope) and returns every non-imported atom soft-deleted withretired_by: managed-reextractwithorigin_live(a live page origin in its source, or a transcript),replaced(a live atom of the same origin carries another stripped source hash),latest(its hash is the hash of the origin's latestmanaged-reextractretirement) andrestorable(all three right);atomOriginScopeSqlnarrows it to one atom's source and origin through the frontmatter GIN index for the apply recheck;atomRetirementPurgeHold, which keeps such an atom out of every batch purge selection (enginepurgeDeletedPagespreview and delete, the belief-ledger expiry,selectPurgeCandidates) forATOM_RESTORE_HOLD_DAYS(30) afterdeleted_at, next to the #6729identityDowngradePurgeHold. An explicitdelete --purgeis not held. Static strings only, soengine-sql/pages.tsimports it.src/core/repair/atoms-restore.ts—gbrain repair atoms-restore(#7013), explicit-only and preview-bound: lists atoms an empty managed re-extraction retired (retired_by: managed-reextract) thatatomRetirementsSql(persistence/atom-retirement-hold.ts) marksrestorable, each with origin, stripped source hash andretired_at, and residualsrestorable,origins,origin_gone,replaced,older_generation;--apply --expect <hash>restores the approved set, rechecking each atom (id, incarnation, revision, origin, hash,retired_at, rule match) and reportingchanged_since_previewotherwise. Managed: onemanaged_maintenance_restore_reextract_atomrequest per atom (deleted_page: true, bound to the deleted revision, request id in the outcome detail);prepareAtomRestore(dispatched fromprepared-maintenance.ts) rechecks the rule under the atom and origin page locks and publishes a revision-boundrevert_versiontoversion_id, the newest live version of the atom at its source hash withoutretired_by(the one the coordinated delete archived; file written back,allowMissingFile); none isno_version, lowered to thederive:atomstier of its origin with taint edges. Unmanaged:createVersion,restorePageand the two keys dropped in onemaintenanceTransaction. Extraction state is not touched. Test:test/pathological/h5-atoms-restore.test.ts.src/core/repair/atom-fence-rows.ts—gbrain repair atom-fence-rows, explicit-only and preview-bound:findAtomFenceRowslists live page-boundvisibility: worldatoms whose title, body orsource_quotecontains (case and whitespace folded, claims of at leastMIN_CLAIM_CHARS) the claim of a facts row of their live source page whose visibility is not world or a takes row whose holder is not world, absent from the page'spublicBody; keyset pages of 500 atoms whose source page names a facts or takes fence, each source page read once, segmented source pages countedorigin_unread. The preview lists atom, source page and row kinds and numbers (never row text) under a saved hash;--apply --expect <hash>rechecks each atom and setsvisibility: privatethrough a revision-bound put_page (narrowed), elsechanged_since_preview. Doctoratom_fence_rowsshares the scan. Test:test/repair-atom-fence-rows.test.ts(unmanaged and managed, PGLite and Postgres).src/commands/doctor/checks/atom-fence-rows.ts— doctoratom_fence_rows(BRAIN, a host-onlyWAVE_CHECKSrepair entry cleared by the explicit-onlyatom-fence-rows, so remediation classifies itexplicit_kind_required): runsfindAtomFenceRowsper source, each statement bounded byPLAN_STATEMENT_MS;warnnames the count per source and the read-only previewgbrain repair atom-fence-rows --source <id> --jsonas an agentfix, never a slug or row text; an overrun reports the count as unknown.src/core/persistence/purge-parks.ts— #6741 C: per-tombstone purge parks in op_checkpoints (oppurge-deleted-park, key source+slug+deleted_at, so a re-deleted page starts fresh); park atPURGE_PARK_LIMIT(5) non-deferral failures, a success clears it, and parks of a source seen inactive rearm the first run its writer is active again (notePurgeSourceWriter).purgeStaleCheckpointsexempts the op;prunePurgeParksdrops parks whose tombstone is gone. A park records the gbrainversionof its last failure;isParked(the managed and unmanaged selection, doctorpurge_parked_pages) counts only the running version's, so a park another version wrote (or one with no version) gets one automatic attempt and a failure re-parks it under the running version. Tests:test/purge-deleted-parks.test.ts,test/purge-parks-version.test.ts(Postgres:test/e2e/purge-parks-version-postgres.test.ts).src/core/persistence/derived-origin-hold.ts+src/core/repair/origin-carry.ts— GST-2689: a page that reads as world by its own label but is hidden from remote callers only through a private origin (derived_from, an atom'ssource_slug, followed throughslug_aliasesandslug_rename_history, or a concept's provenance atom) keeps that privacy once the origin row is gone.origin-carry.tsfinds the dependents withprivate-labels.tsdependentsSql('remove')(it reads only the pages whose frontmatter names a removed slug, or a slug a rename moved to it, throughidx_pages_frontmatter, one jsonpath scan per 100 slugs of a source, so its cost does not grow with the source; the postimage drops the origin rows; a page that names readers is returned when its listed readers would gain it, and gets the label with itsreadable_bykept; a life-chronicle event is returned when the removal opens it, never when itsevent.depthpage is removed, since it then fails closed) and gives eachvisibility: privatethrough the label door (publishMaintenancePageswithkeepTrustand the label edit on a managed brain, batchderived-origin-carry:<request_id>;writeLabelFileorimportAtRevisionotherwise).deletePageCarryingPrivateis thedelete_pagehandler body: a soft delete (local or remote) labels after it committed and returns the unchanged receipt; a purge labels first and, when that fails, soft-deletes instead (an existing tombstone stays), parks the origin and returnspurge_held, whose message (like an owner purge the in-transaction recheck or the failed origin lookup held) namesgbrain delete <slug> --purge --source-id <id>to run as a new request once the page is labelled, since only an explicit purge writes the purge tombstones; the park records the held request (held_request_id, kept by a later park of the page) and doctor names the command (finish_argv).carryPrivateBeforePurgeruns before every expiry over all the origins (type = 'atom'or hidden byprivacyPartSql) expired or expiring withinCARRY_LEAD_HOURS(24) at once, so a page private through two of them is found and none crosses the cutoff mid-run uncarried; it publishes the labels 200 per maintenance batch, parks the blocked ones and returns the ones whose park no longer applies, whichpurgeDeletedPagesCoordinatedclears only after its purge, so an origin parked when the purge was previewed stays that run; a consented manual purge (gbrain pages purge-deleted,purge_deleted_pages) previews withforecastCarry(read-only: the parked origins the carry would free,released_origins, and the origins it would park, both judged ascarryPrivatejudges them) passed toselectPurgeCandidates, so--dry-runand the consent list exactly what--yespurges and nothing is labelled before the consent; the run passes the freed ids asrelease, andpurgeDeletedPagesCoordinatedclears those parks once its carry landed, before it purges. A soft-deleted dependent is returned too but never labelled: it blocks its origin (dependent_soft_deleted) until it is purged or restored, since a restore would bring it back with the origin row gone; a removed origin tied to another removed origin counts as such a dependent (judged on its own row), since another hold may keep it. Inside each delete transactionparkUncarriedInPurgerechecks the origins about to go (the page purge for an explicit or managed retention purge, the unmanaged bulk delete, and each recorded tombstone): an origin a page written after the carry still depends on is parked in that transaction and its row is kept (a live page is soft-deleted instead, and the receipt carriespurge_heldnaming no page), so the next purge labels the page and the one after removes the origin. The origin is looked up by the lowercased slug, assubmitPageMutationdeletes it.derived-origin-hold.tsis the park (op_checkpoints opderived-origin-park, fingerprint the page id, withblocking_slug,codeandreason),derivedOriginPurgeHold(no engine-sql imports), prune of restored or purged pages, andreadDerivedOriginParksfor doctorderived_origin_parked;purgeStaleCheckpointsexempts the op. Tests:test/derived-origin-carry-private.test.ts(repo-less, minted tokens),test/derived-origin-carry-managed.test.ts(managed Git brain),test/derived-origin-recheck-plan.test.ts(pages rows the recheck visits).src/core/repair/segmented-mirror.ts—gbrain repair segmented-mirror(LPH a), explicit-only, preview-bound, destructive consent,checks: [](no doctor scan: detection reads every segmented file).scanSegmentedMirrors(read-only, owner host; a non-owner source is heldnot_owner_host) walks livebody_storage='segmented'pages of sources with a worktree binding whose snapshot ledger applies (ledgerApplies), runsprepareFileTarget(..., null, { allowMissing })(the mirror's own drift check;file_database_driftor any otherOperationErroris held, never rewritten), then lists the page only when overlaying the ledger on the file's facts fences changes its region digests (fileBodyDigestsvsoverlaidFileBodyDigestsoverFileBytes, bounded memory) and the streamed render (unreadPageFile) hashes differently. The hash (segmented-mirror-v1) binds source selection, slug, page id, revision, path and both SHA-256s; the approved set lives inop_checkpoints. Apply re-checks revision and file hash of every page not yet admitted (preview_changed), then per page admits and commits, in one transaction like a withdrawal, arepair_segmented_mirrorrequest (request id derived from the hash; its receipt) that inserts a version-2 targetedwithdrawal-mirror+giteffect (no embedding) whosedata.approved_filecarries the preview's file and render SHA-256 (mirrorPageskips the targetpreview_changedwhen the file's before-hash or the streamed render differs, before the gate or any recovery record;publishGitPageskips it when the file is not the approved render; the outcome isrefusedpreview_changedwith a read-only fix re-running the preview); it wakes this process's consumer and waits up to the write wait for them (mirrored/mirror_queued/held/failed; a replay isreplayed). Test:test/pathological/lp-a-segmented-mirror.test.ts.