Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

belief ledger lane A: key-files docs for the review fixes; review probes in the Postgres arms

garrytan8bc4d5f370d4
diff --git a/docs/architecture/key-files/belief-ledger.md b/docs/architecture/key-files/belief-ledger.md
index 45258d79ad..d215dd3d8d 100644
--- a/docs/architecture/key-files/belief-ledger.md
+++ b/docs/architecture/key-files/belief-ledger.md
@@ -11,9 +11,9 @@ Design: [BELIEF_LEDGER.md](../../designs/BELIEF_LEDGER.md). Operator surface: `g
- `src/core/belief/ledger.ts` — the finalization contract. `withBeliefBatch` reads the state of the held page keys before and after the transaction's projections and appends the canonical diff (origin `live` on a managed brain, `unmanaged` otherwise, or the caller's override). `beliefBatchCovers` and `insideBeliefBatch` let a nested writer skip its own batch. Managed mode comes from `readManagedMode`, never a direct `persistence_brain` read.
- `src/core/belief/append.ts` — the one insert (`appendBeliefEvents`): tombstones and the redaction register first, then deterministic `event_key`s. `markBeliefCommits` writes the post-commit observation (`observed_at >= recorded_at`); `__setBeliefEmitterFaultForTests` is the forced-probe seam.
- `src/core/belief/coverage.ts` — `enableBeliefLedger` (`coverage.started`, a resumable per-page baseline, `coverage.complete` whose recorded_at is the watermark; certified only on a managed brain) and `disableBeliefLedger` (`coverage.stopped`).
-- `src/core/belief/coverage-report.ts` — readers: `coverageIntervals`, `coverageAt` (refuses `coverage_from` before the watermark, `coverage_gap` in a stopped span), `beliefEventVisibility` (an unmarked publication is `unproven` until a commit mark or a later event of the page proves it). Drift: `scanBeliefDrift` (sampled, or deep) compares each slug's current `state_hash` with its newest event; `reconcileBeliefDrift` appends `reconcile` events (the slug interval stays uncertified). `orphanLifetimes`, `unmarkedPublications`/`fillCommitMarks`, and `cycleBeliefReconcile` for the extract phase.
+- `src/core/belief/coverage-report.ts` — readers: `coverageIntervals`, `coverageAt` (refuses `coverage_from` before the watermark, `coverage_gap` in a stopped span; an interval holding a purge whose derivation walk was truncated is not certified, `uncertified_reason: 'truncated_walk'`, its requests in `truncated_walks`), `beliefEventVisibility` (an unmarked publication is `unproven` until a commit mark or a later event of the page proves it). Drift: `scanBeliefDrift` (sampled, or deep) compares each slug's current `state_hash` with its newest event; `reconcileBeliefDrift` appends `reconcile` events (the slug interval stays uncertified). `orphanLifetimes`, `unmarkedPublications`/`fillCommitMarks`, and `cycleBeliefReconcile` for the extract phase.
- `src/core/belief/projection-point.ts` — `unmanagedBeliefPoint` (and `withUnmanagedBeliefs` for one transaction): the legacy import, `extract_facts` fence reconcile, takes reextract and the derived link writers (`derived-links.ts`, the remote auto-links effect, attendance repair) lock their sorted page keys and run in an `unmanaged` batch, then mark the commit. Every other unmanaged writer is found by drift.
-- `src/core/belief/backfill.ts` — `backfillBeliefHistory`: marked history from `page_versions` only (git is not read), origin `backfill`, historical time in `source_time`, recorded_at the run time; a purge during the run retries (`belief_preparation_stale`), and the summary event says whether pruned versions left it incomplete.
+- `src/core/belief/backfill.ts` — `backfillBeliefHistory`: marked history from `page_versions` only (git is not read), origin `backfill`, historical time in `source_time`, recorded_at the run time; a purge during the run retries (`belief_preparation_stale`), and the summary event says whether pruned versions left it incomplete. A version whose own frontmatter is private (or a pinned question) publishes private events; a carrying field a purge registered from a retained version (`registerVersionCarriers`) is appended as the marker.
- `src/core/belief/history.ts` — the one history reader (`readBeliefHistory`); remote callers see only events that were world-visible when recorded on a page visible now, failing closed.
- `src/commands/beliefs.ts` — `gbrain beliefs enable|disable|status|reconcile|backfill` (local only; `--json`); an unknown source is `invalid_params`.
- `src/commands/doctor/checks/belief-ledger.ts` — doctor `belief_ledger_coverage`: intervals and certification, baseline progress, drift (sampled; complete under `--tier deep`), orphan lifetimes, unmarked publications, and a restore whose purge replay was partial, unavailable or unverified (`ask_user`). `--fix` reconciles and fills marks; a brain without coverage is information with an `ask_user` enable.
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index 6da1862239..33742428b5 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -6,8 +6,8 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu
- `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`.
- `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.
-- `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 and value_hash null, `purged`), `redactCarryingFields` (keyset batches of 1000 over fact, take and link events: 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`) 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 the owner releases it), 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`). The receipt's `ledger` block reports the counts and `derived_walk`. 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 (request, source and incarnation, scope, fingerprints, content hashes, lifetimes, epoch; never claim text) and a `committed` line after. `restorePgliteBackup` replays every committed purge newer than the archive inside its transaction (`replayPurgesInRestore`: tombstones, row removal, the three passes, one `fact.purged`/`page.purged` with cause `restore_replay`), records each as `complete`, `partial` (no restored row held the text) 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 `replayPurgesFromDatabase(restored, preRestore, archivedAt)`, which rebuilds the intents from the pre-restore database's tombstones. Seam: `__setPurgeReplayFaultForTests`. Probes: `test/belief-ledger-restore.test.ts`.
+- `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, `ownerEdit: true`, sets a different value) 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`). 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 `replayPurgesFromDatabase(restored, preRestore, archivedAt)`, which 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/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.
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 4e386bc8c8..0fbbab3faa 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -21,6 +21,7 @@ test/belief-ledger-group.test.ts
test/belief-ledger-identity.test.ts
test/belief-ledger-lifecycle.test.ts
test/belief-ledger-privacy.test.ts
+test/belief-ledger-purge-review.test.ts
test/belief-ledger-purge.test.ts
test/belief-ledger-restore.test.ts
test/belief-ledger-trust.test.ts