Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

belief ledger lane A: gbrain beliefs replay-purges for Postgres restores (dry run by default, --apply; purge mirror or pre-restore database) (#9); section 13 deviations

garrytana8ae6208bd40
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index 33742428b5..e85f2932a0 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, 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/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`). 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/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/docs/designs/BELIEF_LEDGER.md b/docs/designs/BELIEF_LEDGER.md
index d6a35aae85..4649b838ae 100644
--- a/docs/designs/BELIEF_LEDGER.md
+++ b/docs/designs/BELIEF_LEDGER.md
@@ -1408,3 +1408,22 @@ Garry accepted those answers. Questions 5, 6, 7 and 8 are decided.
10. **Ontology rows** are keyed into their provenance stream (the
observation's `source_markdown_slug`) as database-only subjects, not into
the entity's stream.
+11. **Purge carrier registration resolves lifetimes outside the purge's page
+ locks.** `registerLiveCarriers` and `registerVersionCarriers` key the
+ carrying fields of pages the purge does not lock (any page quoting the
+ claim) and may mint their open lifetime without that page's key. Taking
+ those keys inside the purge transaction would break the global lock
+ order, so a concurrent rename of such a page can mint a second lifetime.
+12. **Owner release reach (6.5).** A publication is an owner edit only when a
+ local caller journals a direct edit (`put_page`, `edit_page`,
+ `takes_update`, `takes_resolve`) with no internal intent kind; append
+ still requires the writer tier at or above `OWNER_TIER_FLOOR`. The trust
+ channel records those verbs as `agent_written` even from the local CLI,
+ so in W1 the release that reaches the floor is the owner confirm action
+ (`trust confirm`).
+13. **Short claims quote a field only as a word.** A claim shorter than eight
+ characters matches a carrying field only where no letter or digit of a
+ space-separated script (Latin, Greek, Cyrillic, Armenian, Georgian) is
+ glued to it; CJK, Thai, punctuation and markup still match as
+ substrings. The inventory of claims stays exhaustive; only a short claim
+ inside a longer word (`ceo` in `herbaceous`) no longer redacts.
diff --git a/src/commands/beliefs-replay-purges.ts b/src/commands/beliefs-replay-purges.ts
new file mode 100644
index 0000000000..6696159bc2
--- /dev/null
+++ b/src/commands/beliefs-replay-purges.ts
@@ -0,0 +1,60 @@
+/**
+ * `gbrain beliefs replay-purges` (docs/designs/BELIEF_LEDGER.md section 8): a
+ * Postgres restore happens outside gbrain, so the purges made after the backup
+ * are replayed into the restored database here, from a purge mirror
+ * (`--purge-mirror <absolute path>`) or from the pre-restore database
+ * (`--from-url-env <VAR>`, the URL never on argv). A dry run by default: the
+ * replay runs and rolls back, and `--apply` writes it.
+ */
+import { isAbsolute } from 'node:path';
+import type { BrainEngine } from '../core/engine.ts';
+import { opError } from '../core/ops/contract.ts';
+import { purgeLinesFromDatabase, readPurgeMirror, replayPurges, type PurgeReplayResult } from '../core/belief/purge-mirror.ts';
+
+const flag = (args: string[], name: string): string | undefined => {
+ const at = args.indexOf(name);
+ if (at >= 0) return args[at + 1];
+ return args.find(a => a.startsWith(`${name}=`))?.slice(name.length + 1);
+};
+
+export interface ReplayPurgesReport extends PurgeReplayResult { applied: boolean; archived_at: string; from: 'purge_mirror' | 'database'; apply_argv?: string[] }
+
+export async function replayPurgesCli(engine: BrainEngine, args: string[]): Promise<{ value: ReplayPurgesReport; text: string }> {
+ if (engine.kind !== 'postgres') {
+ throw opError('invalid_params', 'gbrain beliefs replay-purges replays purges into a restored Postgres brain; a PGLite restore replays them itself.',
+ 'On PGLite, run gbrain backup restore --purge-mirror <absolute path> to name a purge mirror other than the brain home\'s.');
+ }
+ const archivedAt = flag(args, '--archived-at');
+ if (!archivedAt || Number.isNaN(Date.parse(archivedAt))) {
+ throw opError('invalid_params', '--archived-at <ISO time> is required: the time the restored backup was taken.', 'Pass the backup\'s creation time, e.g. --archived-at 2026-10-01T12:00:00Z.');
+ }
+ const mirror = flag(args, '--purge-mirror');
+ const urlEnv = flag(args, '--from-url-env');
+ if (!mirror === !urlEnv) {
+ throw opError('invalid_params', 'Name exactly one replay source: --purge-mirror <absolute path> or --from-url-env <VAR>.',
+ 'The purge mirror is <brain home>/.gbrain/purge-events.jsonl on the host that ran the purges; --from-url-env names an environment variable holding the pre-restore database URL.');
+ }
+ if (mirror && !isAbsolute(mirror)) throw opError('invalid_params', `--purge-mirror must be an absolute path (got ${mirror}).`, 'Pass the mirror file\'s absolute path.');
+ let lines;
+ if (mirror) {
+ lines = readPurgeMirror(mirror);
+ if (!lines) throw opError('invalid_params', `The purge mirror ${mirror} does not exist or cannot be read.`, 'Check the path and its permissions (the mirror is 0600, owned by the brain\'s user).');
+ } else {
+ const url = process.env[urlEnv!];
+ if (!url) throw opError('invalid_params', `Environment variable ${urlEnv} is not set.`, `Set ${urlEnv} to the pre-restore database URL, then run the command again.`);
+ const { createEngine } = await import('../core/engine-factory.ts');
+ const pre = await createEngine({ engine: 'postgres', database_url: url });
+ try {
+ await pre.connect({ engine: 'postgres', database_url: url });
+ lines = await purgeLinesFromDatabase(pre);
+ } finally { await pre.disconnect().catch(() => undefined); }
+ }
+ const apply = args.includes('--apply');
+ const result = await replayPurges(engine, { lines, archivedAt, apply });
+ const applyArgv = ['gbrain', 'beliefs', 'replay-purges', '--archived-at', archivedAt, ...(mirror ? ['--purge-mirror', mirror] : ['--from-url-env', urlEnv!]), '--apply'];
+ const value: ReplayPurgesReport = { ...result, applied: apply, archived_at: new Date(archivedAt).toISOString(), from: mirror ? 'purge_mirror' : 'database', ...(apply ? {} : { apply_argv: applyArgv }) };
+ const counts = `${result.replays.length} purge(s) (${result.state}${result.ledger === 'absent' ? ', no belief ledger in the restored database' : ''})`;
+ const text = apply ? `Replayed ${counts} into the restored database.`
+ : `Dry run: ${counts} would be replayed; nothing was written. Ask the user, then run ${applyArgv.join(' ')}.`;
+ return { value, text };
+}
diff --git a/src/commands/beliefs.ts b/src/commands/beliefs.ts
index 7ed0736ea0..6c1fb61ea1 100644
--- a/src/commands/beliefs.ts
+++ b/src/commands/beliefs.ts
@@ -16,9 +16,10 @@ import { coverageIntervals, coveredSources, fillCommitMarks, orphanLifetimes, re
import { backfillBeliefHistory } from '../core/belief/backfill.ts';
import { readLedgerSource } from '../core/belief/ledger.ts';
import { readManagedMode } from '../core/persistence/managed-mode.ts';
+import { replayPurgesCli } from './beliefs-replay-purges.ts';
export const BELIEFS_USAGE = [
- 'Usage: gbrain beliefs <enable|disable|status|reconcile|backfill> [--source <id>] [--json]',
+ 'Usage: gbrain beliefs <enable|disable|status|reconcile|backfill|replay-purges> [--source <id>] [--json]',
' enable Start recording the belief ledger on a source: baselines every page (resumable) and sets the watermark.',
' Only a managed source\'s coverage is certified; an unmanaged source is recorded but uncertified.',
' disable Stop recording (appends coverage.stopped); enabling again starts a new interval with a new baseline.',
@@ -26,10 +27,12 @@ export const BELIEFS_USAGE = [
' reconcile Appends reconcile events for slugs whose state drifted from their newest event, and fills missing commit marks.',
' A drifted slug\'s interval stays uncertified on a managed source.',
' backfill Seeds best-effort history before the coverage start from retained page versions (never certified).',
+ ' replay-purges --archived-at <iso> (--purge-mirror <abs path> | --from-url-env <VAR>) [--apply]',
+ ' After a Postgres restore, replays the purges the restored backup does not hold (dry run unless --apply).',
' --source <id> The source (default: every covered source for status and reconcile, "default" for the others).',
].join('\n');
-const SUBCOMMANDS = ['enable', 'disable', 'status', 'reconcile', 'backfill'] as const;
+const SUBCOMMANDS = ['enable', 'disable', 'status', 'reconcile', 'backfill', 'replay-purges'] as const;
function sourceArg(args: string[]): string | undefined {
const at = args.indexOf('--source');
@@ -65,7 +68,7 @@ export async function runBeliefs(engine: BrainEngine, args: string[]): Promise<v
if (args.includes('--help') || args.includes('-h') || !sub) { console.log(BELIEFS_USAGE); return; }
try {
if (!(SUBCOMMANDS as readonly string[]).includes(sub)) {
- throw opError('invalid_params', `Unknown beliefs subcommand '${sub}'.`, 'gbrain beliefs --help lists enable, disable, status, reconcile and backfill.');
+ throw opError('invalid_params', `Unknown beliefs subcommand '${sub}'.`, 'gbrain beliefs --help lists enable, disable, status, reconcile, backfill and replay-purges.');
}
const named = sourceArg(args);
if (named !== undefined && !await readLedgerSource(engine, named)) throw unknownSource(named);
@@ -90,6 +93,11 @@ export async function runBeliefs(engine: BrainEngine, args: string[]): Promise<v
+ `${incomplete.length ? `; ${incomplete.length} page(s) incomplete (${[...new Set(incomplete.flatMap(p => p.reasons))].join(', ')})` : ''}.`);
return;
}
+ if (sub === 'replay-purges') {
+ const { value, text } = await replayPurgesCli(engine, args);
+ await report(args, value, text);
+ return;
+ }
const sources = named ? [named] : await coveredSources(engine);
if (sub === 'status') {
const statuses = [];
diff --git a/src/core/belief/purge-mirror.ts b/src/core/belief/purge-mirror.ts
index a297284e22..44e2f8ab74 100644
--- a/src/core/belief/purge-mirror.ts
+++ b/src/core/belief/purge-mirror.ts
@@ -257,11 +257,10 @@ export async function readRestorePurgeReplay(engine: Pick<BrainEngine, 'executeR
}
/**
- * Postgres restores happen outside gbrain: `gbrain beliefs replay-purges --from-url-env <VAR> --archived-at <time>` runs this against the
- * restored database. The pre-restore database is complete by construction: every purge its tombstones (fact_purges, take_purges,
- * page_purges) record, grouped by request, that the restored database does not already hold is replayed, whatever its `purged_at`.
+ * The text-free intents of every purge a pre-restore database's tombstones (fact_purges, take_purges, page_purges) record,
+ * grouped by request, each with its committed line. The database is complete by construction, so `purged_at` bounds nothing.
*/
-export async function replayPurgesFromDatabase(restored: BrainEngine, preRestore: Pick<BrainEngine, 'executeRaw'>, archivedAt: string): Promise<PurgeReplayResult> {
+export async function purgeLinesFromDatabase(preRestore: Pick<BrainEngine, 'executeRaw'>): Promise<PurgeMirrorLine[]> {
const facts = await preRestore.executeRaw<{ request: string; source_id: string; visibility: string; subject: string; fact_hash: string; at: string }>(`SELECT
request_id::text AS request, source_id, visibility, subject, fact_hash, purged_at::text AS at FROM fact_purges WHERE request_id IS NOT NULL`);
const takes = await preRestore.executeRaw<{ request: string; source_id: string; claim_hash: string; at: string }>(`SELECT request_id::text AS request, source_id, claim_hash,
@@ -282,7 +281,29 @@ export async function replayPurgesFromDatabase(restored: BrainEngine, preRestore
for (const p of pages) { const i = intentFor(p.request, p.source_id, p.at); i.scope = 'page'; i.slug = p.slug; i.content_hashes = [...(i.content_hashes ?? []), p.content_hash]; }
for (const f of facts) intentFor(f.request, f.source_id, f.at).facts.push({ fact_hash: f.fact_hash, visibility: f.visibility, subject: f.subject });
for (const t of takes) intentFor(t.request, t.source_id, t.at).takes.push(t.claim_hash);
- const lines: PurgeMirrorLine[] = [...intents.values()].sort((a, b) => a.recorded_at < b.recorded_at ? -1 : 1)
+ return [...intents.values()].sort((a, b) => a.recorded_at < b.recorded_at ? -1 : 1)
.flatMap(i => [i, { kind: 'committed' as const, request: i.request, recorded_at: i.recorded_at }]);
- return restored.transaction(tx => replayPurgesInRestore(tx, { lines, archivedAt: new Date(archivedAt).toISOString(), restoreId: randomUUID(), allTimes: true }));
+}
+
+/**
+ * Postgres restores happen outside gbrain: `gbrain beliefs replay-purges` replays `lines` (a purge mirror or a pre-restore
+ * database's tombstones) into the restored database, every purge the restored database does not already hold, whatever its
+ * time; `archivedAt` is the archive time `coverage.restored` names. Without `apply` the same replay runs in a transaction
+ * that rolls back, so the preview is exactly what `--apply` writes.
+ */
+export async function replayPurges(restored: BrainEngine, input: { lines: PurgeMirrorLine[] | null; archivedAt: string; apply: boolean }): Promise<PurgeReplayResult> {
+ const preview = new Error('replay preview rolled back');
+ let result: PurgeReplayResult | undefined;
+ try {
+ await restored.transaction(async tx => {
+ result = await replayPurgesInRestore(tx, { lines: input.lines, archivedAt: new Date(input.archivedAt).toISOString(), restoreId: randomUUID(), allTimes: true });
+ if (!input.apply) throw preview;
+ });
+ } catch (error) { if (error !== preview) throw error; }
+ return result!;
+}
+
+/** `replayPurges` from a pre-restore database, applied. */
+export async function replayPurgesFromDatabase(restored: BrainEngine, preRestore: Pick<BrainEngine, 'executeRaw'>, archivedAt: string): Promise<PurgeReplayResult> {
+ return replayPurges(restored, { lines: await purgeLinesFromDatabase(preRestore), archivedAt, apply: true });
}
diff --git a/test/belief-ledger-restore.test.ts b/test/belief-ledger-restore.test.ts
index a04f2b1a22..6a2f238a37 100644
--- a/test/belief-ledger-restore.test.ts
+++ b/test/belief-ledger-restore.test.ts
@@ -12,7 +12,8 @@ import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import postgres from '#postgres';
import { __setBeliefEmitterFaultForTests } from '../src/core/belief/append.ts';
-import { __setPurgeReplayFaultForTests, PURGE_MIRROR_FILE, readRestorePurgeReplay, replayPurgesFromDatabase, type PurgeReplayFault } from '../src/core/belief/purge-mirror.ts';
+import { __setPurgeReplayFaultForTests, PURGE_MIRROR_FILE, purgeMirrorPath, readRestorePurgeReplay, replayPurgesFromDatabase, type PurgeReplayFault } from '../src/core/belief/purge-mirror.ts';
+import { replayPurgesCli } from '../src/commands/beliefs-replay-purges.ts';
import { createPgliteBackup, restorePgliteBackup } from '../src/core/backup/snapshot.ts';
import { runBackupCli } from '../src/commands/backup.ts';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -338,6 +339,16 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
() => __setBeliefEmitterFaultForTests(drafts => drafts.map(d => d.eventType === 'page.expired' ? { ...d, eventType: 'page.purged', purged: true } : d)));
}, 240_000);
+ test('#9: beliefs replay-purges refuses on PGLite (the restore replays itself) and refuses without one replay source', async () => {
+ const r = await collect<string[]>(resolve => beliefBrain(async b => {
+ const codes: string[] = [];
+ for (const args of [['replay-purges', '--archived-at', '2026-01-01T00:00:00Z'], ['replay-purges', '--archived-at', '2026-01-01T00:00:00Z', '--purge-mirror', 'relative.jsonl']])
+ codes.push(await replayPurgesCli(b.engine, args).then(() => 'ok', (e: { code?: string; message: string }) => `${e.code}:${/PGLite|exactly one|absolute/.exec(e.message)?.[0]}`));
+ resolve(codes);
+ }, { databaseUrl: engineCase.databaseUrl }));
+ expect(r).toEqual(engineCase.name === 'postgres' ? ['invalid_params:exactly one', 'invalid_params:absolute'] : ['invalid_params:PGLite', 'invalid_params:PGLite']);
+ }, 120_000);
+
if (engineCase.name !== 'postgres') return;
test('#10 (postgres): a purge that started before the dump and committed after it is replayed; one already in the archive is not', async () => {
const r = await collect<Record<string, unknown>>(resolve => beliefBrain(async b => {
@@ -372,6 +383,44 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
}, { databaseUrl: engineCase.databaseUrl }));
expect(r).toEqual({ replays: [[true, 'complete']], left: [] });
}, 300_000);
+ test('#9 (postgres): beliefs replay-purges previews without writing, then --apply replays from the pre-restore database or the purge mirror', async () => {
+ const r = await collect<Record<string, unknown>>(resolve => beliefBrain(async b => {
+ await b.put('companies/acme-example', beliefPage({ prose: 'Acme.' }));
+ await b.put('companies/acme-example', beliefPage({ facts: [X, 'Acme has two offices'] }));
+ const url = new URL(engineCase.databaseUrl!);
+ const [{ db }] = await b.engine.executeRaw<{ db: string }>('SELECT current_database() AS db');
+ const admin = postgres(engineCase.databaseUrl!, { max: 1, prepare: false });
+ await disposePersistenceConsumer(b.engine);
+ await admin.unsafe(`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '${db}' AND pid <> pg_backend_pid()`);
+ const clones = [0, 1].map(() => `gbrain_test_restore_${randomUUID().replace(/-/g, "").slice(0, 16)}`);
+ for (const clone of clones) await admin.unsafe(`CREATE DATABASE ${clone} TEMPLATE ${db}`);
+ const archivedAt = new Date().toISOString();
+ const engines = clones.map(() => new PostgresEngine());
+ const env = `GBRAIN_TEST_PRE_RESTORE_URL_${randomUUID().slice(0, 8).toUpperCase()}`;
+ try {
+ await purgeFact(b, X);
+ url.pathname = `/${db}`;
+ process.env[env] = url.toString();
+ for (const [i, clone] of clones.entries()) { url.pathname = `/${clone}`; await engines[i]!.connect({ database_url: url.toString(), poolSize: 2 }); }
+ const [fromDb, fromMirror] = engines.map(e => ({ ...b, engine: e }));
+ const dbArgs = ['replay-purges', '--archived-at', archivedAt, '--from-url-env', env];
+ const dry = await replayPurgesCli(fromDb!.engine, dbArgs);
+ const afterDry = (await carriers(fromDb!, X)).length;
+ const applied = await replayPurgesCli(fromDb!.engine, [...dbArgs, '--apply']);
+ const mirror = await replayPurgesCli(fromMirror!.engine, ['replay-purges', '--archived-at', archivedAt, '--purge-mirror', purgeMirrorPath(), '--apply']);
+ resolve({ dry: [dry.value.applied, dry.value.replays.length, dry.value.apply_argv?.at(-1)], afterDry: afterDry > 0,
+ applied: [applied.value.applied, applied.value.state], leftDb: await carriers(fromDb!, X),
+ mirror: [mirror.value.from, mirror.value.state], leftMirror: await carriers(fromMirror!, X) });
+ } finally {
+ delete process.env[env];
+ for (const e of engines) await e.disconnect().catch(() => undefined);
+ for (const clone of clones) await admin.unsafe(`DROP DATABASE IF EXISTS ${clone} WITH (FORCE)`);
+ await admin.end();
+ }
+ }, { databaseUrl: engineCase.databaseUrl }));
+ expect(r).toEqual({ dry: [false, 1, '--apply'], afterDry: true, applied: [true, 'complete'], leftDb: [], mirror: ['purge_mirror', 'complete'], leftMirror: [] });
+ }, 300_000);
+
test('#3 (postgres): replayPurgesFromDatabase hides the purge\'s derived rows again and appends derived.hidden', async () => {
const scenario = () => collect<Record<string, unknown>>(resolve => beliefBrain(async b => {
await seedDerived(b);