Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

belief ledger lane A: backup restore --purge-mirror and a warning that names it (#9); Postgres replay is not bounded by purged_at and skips archived purges (#10)

garrytanda759b8e6b39
diff --git a/src/commands/backup.ts b/src/commands/backup.ts
index 2b4566f0f3..ed7cd4bfe8 100644
--- a/src/commands/backup.ts
+++ b/src/commands/backup.ts
@@ -15,6 +15,7 @@
* back to the cached verdict + age (cache-derived exit code), never a crash;
*/
+import { isAbsolute } from 'node:path';
import { OperationError, opError } from '../core/ops/contract.ts';
import { redactUrlsInText } from '../core/url-redact.ts';
import { redactConnectionInfo } from '../core/audit/redact-connection-info.ts';
@@ -36,7 +37,7 @@ import {
const BACKUP_USAGE: Record<string, { usage: string; example: string }> = {
create: { usage: 'gbrain backup create --output /absolute/private/path/archive.gbrain-backup [--json]',
example: 'gbrain backup create --output /srv/private/brain-2026-10-03.gbrain-backup' },
- restore: { usage: 'gbrain backup restore ARCHIVE --into /absolute/new-root [--mode new-brain|recovery] [--confirm-quiesced] [--confirm-backup-compatible] [--confirm-authority-reviewed] [--json]',
+ restore: { usage: 'gbrain backup restore ARCHIVE --into /absolute/new-root [--mode new-brain|recovery] [--purge-mirror /absolute/purge-events.jsonl] [--confirm-quiesced] [--confirm-backup-compatible] [--confirm-authority-reviewed] [--json]',
example: 'gbrain backup restore /srv/private/brain-2026-10-03.gbrain-backup --into /srv/gbrain-restored' },
};
@@ -88,7 +89,10 @@ const HELP =
' --confirm-authority-reviewed. Old service exclusion is\n' +
' operator-enforced, not verified by these attestations.\n' +
' Both modes revoke archived authority and disable publication.\n' +
- ' Quarantine unfinished jobs; never start automation.\n\n' +
+ ' Quarantine unfinished jobs; never start automation.\n' +
+ ' Replays purges made after the archive from the original\n' +
+ ' brain\'s .gbrain/purge-events.jsonl, or the copy named by\n' +
+ ' --purge-mirror ABS when that root is gone.\n\n' +
' --json Structured verdict (includes the recovery field).\n\n' +
'Exit codes: 0 ok / 1 warn / 2 usage error. Off switches: GBRAIN_BACKUP_CHECK=0 or\n' +
'`gbrain config set backup.check_enabled false`. Interval:\n' +
@@ -164,7 +168,7 @@ export async function runBackupCli(
for (let i = 1; i < args.length; i++) {
const arg = args[i];
if (arg === '--json') continue;
- if (arg === '--output' || arg === '--into' || arg === '--mode') {
+ if (arg === '--output' || arg === '--into' || arg === '--mode' || arg === '--purge-mirror') {
if (!args[i + 1] || args[i + 1].startsWith('--')) throw backupUsageError(sub, `Missing value for ${arg}.`);
values[arg] = args[++i];
} else if (['--confirm-quiesced', '--confirm-backup-compatible', '--confirm-authority-reviewed'].includes(arg)) confirmations.add(arg);
@@ -173,16 +177,17 @@ export async function runBackupCli(
}
const { createPgliteBackup, restorePgliteBackup } = await import('../core/backup/snapshot.ts');
if (sub === 'create') {
- if (!values['--output'] || values['--into'] || values['--mode'] || confirmations.size || positional.length) throw backupUsageError(sub, 'gbrain backup create takes exactly --output <absolute archive path>.');
+ if (!values['--output'] || values['--into'] || values['--mode'] || values['--purge-mirror'] || confirmations.size || positional.length) throw backupUsageError(sub, 'gbrain backup create takes exactly --output <absolute archive path>.');
const result = await createPgliteBackup({ output: values['--output'] });
if (json) console.log(JSON.stringify({ ok: true, ...result }));
else console.log(`Backup created: ${result.archive}\nSensitive full database state; protect any off-VM copy.\nExcluded assets: ${(result.manifest.omitted as string[]).join('; ')}`);
} else {
if (!values['--into'] || values['--output'] || positional.length !== 1) throw backupUsageError(sub, 'gbrain backup restore takes one ARCHIVE and --into <absolute new root>.');
if (values['--mode'] !== undefined && !['new-brain', 'recovery'].includes(values['--mode'])) throw new Error('Restore --mode must be new-brain or recovery.');
+ if (values['--purge-mirror'] !== undefined && !isAbsolute(values['--purge-mirror'])) throw backupUsageError(sub, '--purge-mirror takes an absolute path to a copy of the original brain\'s .gbrain/purge-events.jsonl.');
const result = await restorePgliteBackup({ archive: positional[0], into: values['--into'], mode: values['--mode'] === 'recovery' ? 'recovery' : 'new_brain',
confirmQuiesced: confirmations.has('--confirm-quiesced'), confirmBackupCompatible: confirmations.has('--confirm-backup-compatible'),
- confirmAuthorityReviewed: confirmations.has('--confirm-authority-reviewed') });
+ confirmAuthorityReviewed: confirmations.has('--confirm-authority-reviewed'), ...(values['--purge-mirror'] ? { purgeMirror: values['--purge-mirror'] } : {}) });
if (json) console.log(JSON.stringify({ ok: true, ...result }));
else console.log(`Restored memory: ${result.root}\n${result.quarantined_jobs} unfinished jobs quarantined; no automation started.\n${result.reconnect_required.join('\n')}\nRun setup-in-agent.sh for this root to restore its runtime, then reconnect excluded credentials/services and verify memory.`);
}
diff --git a/src/core/backup/snapshot.ts b/src/core/backup/snapshot.ts
index e7fb125694..5c7ebe0a22 100644
--- a/src/core/backup/snapshot.ts
+++ b/src/core/backup/snapshot.ts
@@ -336,7 +336,7 @@ export async function restorePgliteBackup(options: { archive: string; into: stri
renameSync(join(restored, name), join(root, name));
}
const replayWarning = purgeReplay.state === 'none' || purgeReplay.state === 'complete' ? [] : [purgeReplay.state === 'unavailable'
- ? `Purges made after the archive (${metadata.created_at}) were not replayed: no purge mirror could be read under ${metadata.original_root}. Restore again with the original brain's .gbrain/${PURGE_MIRROR_FILE} available (purgeMirror), or purge the content again.`
+ ? `Purges made after the archive (${metadata.created_at}) were not replayed: no purge mirror could be read under ${metadata.original_root}. Restore again into a new root with the original brain's .gbrain/${PURGE_MIRROR_FILE} in place, or name a copy of it with gbrain backup restore --purge-mirror <absolute path>; otherwise purge the content again.`
: `Purge replay is ${purgeReplay.state} for request(s) ${purgeReplay.replays.filter(r => r.outcome !== 'complete').map(r => `${r.request_id} (${r.outcome})`).join(', ')}: review them and run those purges again if the content is still present.`];
const reconnect = [...new Set([...metadata.credential_references.map(key => `Configure credential: ${key}`), ...metadata.omitted, ...detachedConfig, ...execution!.reconnect, ...replayWarning, 'Autopilot is paused; review .gbrain/restore-detached.json before explicitly resuming automation.'])];
privateWrite(receiptPath, JSON.stringify({ format_version: 1, restore_id: restoreId, state: 'ready', original_root: metadata.original_root, shared_skills: sharedSkills, quarantined_jobs: quarantined, reconnect_required: reconnect, purge_replay: purgeReplay, launcher_ready: false, setup_required: true, native_automation_started: false }, null, 2) + '\n');
diff --git a/src/core/belief/purge-mirror.ts b/src/core/belief/purge-mirror.ts
index 35a2040148..a297284e22 100644
--- a/src/core/belief/purge-mirror.ts
+++ b/src/core/belief/purge-mirror.ts
@@ -201,9 +201,12 @@ export interface PurgeReplayResult { state: PurgeReplayState; replays: ReplayRec
* Replays the purges newer than `archivedAt` for the restored database's sources (matching incarnation), in
* recorded order, then appends `coverage.restored` naming the archive time and the outcome on every source with
* coverage. `lines` null means no mirror could be read: `purge_replay: 'unavailable'`. An archive older than the
- * ledger (no `belief_events`) replays tombstones and row removal only and reports `ledger: 'absent'`.
+ * ledger (no `belief_events`) replays tombstones and row removal only and reports `ledger: 'absent'`. A purge whose
+ * tombstones the restored database already holds (same request) is in the archive and is skipped. `allTimes` drops
+ * the archive-time filter: the Postgres path reads a complete pre-restore database, where a purge that started
+ * before the dump and committed after it has a `purged_at` below the archive time (review #10).
*/
-export async function replayPurgesInRestore(tx: BrainEngine, input: { lines: PurgeMirrorLine[] | null; archivedAt: string; restoreId: string }):
+export async function replayPurgesInRestore(tx: BrainEngine, input: { lines: PurgeMirrorLine[] | null; archivedAt: string; restoreId: string; allTimes?: boolean }):
Promise<PurgeReplayResult> {
const ledger = (await tx.executeRaw<{ present: boolean }>("SELECT to_regclass('belief_events') IS NOT NULL AS present"))[0]?.present === true;
const sources = await tx.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources ORDER BY id');
@@ -211,11 +214,14 @@ export async function replayPurgesInRestore(tx: BrainEngine, input: { lines: Pur
if (input.lines) {
const committed = new Set(input.lines.filter(l => l.kind === 'committed').map(l => l.request));
const seen = new Set<string>();
- const newer = input.lines.filter((l): l is PurgeMirrorIntent => l.kind === 'intent' && l.recorded_at > input.archivedAt
+ const newer = input.lines.filter((l): l is PurgeMirrorIntent => l.kind === 'intent' && (input.allTimes || l.recorded_at > input.archivedAt)
&& sources.some(s => s.id === l.source_id && s.incarnation === l.source_incarnation));
for (const intent of newer) {
if (seen.has(intent.request)) continue;
seen.add(intent.request);
+ const [archived] = await tx.executeRaw<{ present: boolean }>(`SELECT (EXISTS (SELECT 1 FROM fact_purges WHERE request_id = $1::uuid)
+ OR EXISTS (SELECT 1 FROM take_purges WHERE request_id = $1::uuid) OR EXISTS (SELECT 1 FROM page_purges WHERE request_id = $1::uuid)) AS present`, [intent.request]);
+ if (archived?.present === true) continue;
if (replayFault === 'skip_replay') continue;
const outcome = committed.has(intent.request) || replayFault === 'replay_uncommitted' ? await replayOne(tx, intent, ledger) : 'unverified';
replays.push({ request: intent.request, request_id: intent.request_id, scope: intent.scope, outcome });
@@ -251,18 +257,17 @@ export async function readRestorePurgeReplay(engine: Pick<BrainEngine, 'executeR
}
/**
- * Postgres restores happen outside gbrain: `gbrain beliefs replay-purges --from <pre-restore database url> --since <archive time>`
- * runs this against the restored database. The pre-restore database is complete by construction: its tombstones
- * (fact_purges, take_purges, page_purges) newer than the archive, grouped by request, are the purges to replay.
+ * 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`.
*/
-export async function replayPurgesFromDatabase(restored: BrainEngine, preRestore: Pick<BrainEngine, 'executeRaw'>, archivedAt: string):
- Promise<{ state: PurgeReplayState; replays: ReplayRecord[] }> {
+export async function replayPurgesFromDatabase(restored: BrainEngine, preRestore: Pick<BrainEngine, 'executeRaw'>, archivedAt: string): Promise<PurgeReplayResult> {
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 purged_at > $1::timestamptz AND request_id IS NOT NULL`, [archivedAt]);
+ 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,
- purged_at::text AS at FROM take_purges WHERE purged_at > $1::timestamptz AND request_id IS NOT NULL`, [archivedAt]);
+ purged_at::text AS at FROM take_purges WHERE request_id IS NOT NULL`);
const pages = await preRestore.executeRaw<{ request: string; source_id: string; slug: string; content_hash: string; at: string }>(`SELECT request_id::text AS request,
- source_id, slug, content_hash, purged_at::text AS at FROM page_purges WHERE purged_at > $1::timestamptz AND request_id IS NOT NULL`, [archivedAt]);
+ source_id, slug, content_hash, purged_at::text AS at FROM page_purges WHERE request_id IS NOT NULL`);
const incarnations = new Map((await preRestore.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources'))
.map(s => [s.id, s.incarnation]));
const intents = new Map<string, PurgeMirrorIntent>();
@@ -279,5 +284,5 @@ export async function replayPurgesFromDatabase(restored: BrainEngine, preRestore
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)
.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() }));
+ return restored.transaction(tx => replayPurgesInRestore(tx, { lines, archivedAt: new Date(archivedAt).toISOString(), restoreId: randomUUID(), allTimes: true }));
}
diff --git a/test/belief-ledger-restore.test.ts b/test/belief-ledger-restore.test.ts
index 7304826d92..a04f2b1a22 100644
--- a/test/belief-ledger-restore.test.ts
+++ b/test/belief-ledger-restore.test.ts
@@ -14,6 +14,7 @@ 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 { createPgliteBackup, restorePgliteBackup } from '../src/core/backup/snapshot.ts';
+import { runBackupCli } from '../src/commands/backup.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import { operations } from '../src/core/operations.ts';
import { PostgresEngine } from '../src/core/postgres-engine.ts';
@@ -229,6 +230,31 @@ describe('belief ledger restore (pglite archive)', () => {
cleanup: { events: [['page', 'page.expired', false, null]], tombstones: 0, redacted: 0, mirror: false }, state: 'none', restoredRedacted: 0 }),
() => __setBeliefEmitterFaultForTests(drafts => drafts.map(d => d.eventType === 'page.expired' ? { ...d, eventType: 'page.purged', purged: true } : d)));
}, 300_000);
+ test('#9: gbrain backup restore --purge-mirror replays from a named copy of the mirror, and the warning names that flag', async () => {
+ const r = await collect<Record<string, unknown>>(resolve => withFileBeliefBrain(SOURCE, async fb => {
+ await fb.open(async b => {
+ await b.put('companies/acme-example', beliefPage({ prose: 'Acme.' }));
+ await b.put('companies/acme-example', beliefPage({ facts: [X, 'Acme sells widgets'] }));
+ });
+ const archive = join(fb.home, 'cli.gbrain-backup');
+ await createPgliteBackup({ root: fb.home, output: archive });
+ await fb.open(async b => { await purgeFact(b, X); });
+ const copy = join(fb.home, 'mirror-copy.jsonl');
+ renameSync(join(fb.home, '.gbrain', PURGE_MIRROR_FILE), copy);
+ const cli = async (args: string[]) => {
+ const logged: string[] = [];
+ const original = console.log;
+ console.log = (...a: unknown[]) => { logged.push(a.map(String).join(' ')); };
+ try { const { exitCode } = await runBackupCli(args, async () => { throw new Error('restore opens no brain'); }); return { exitCode, out: JSON.parse(logged.at(-1)!) }; }
+ finally { console.log = original; }
+ };
+ const named = await cli(['restore', archive, '--into', join(fb.home, 'restored-named'), '--purge-mirror', copy, '--json']);
+ const lost = await restorePgliteBackup({ archive, into: join(fb.home, 'restored-lost'), purgeMirror: join(fb.home, 'missing', '.gbrain', PURGE_MIRROR_FILE) });
+ resolve({ exitCode: named.exitCode, state: named.out.purge_replay.state, warning: lost.reconnect_required.find(l => l.includes('were not replayed'))?.includes('--purge-mirror') });
+ }));
+ expect(r).toEqual({ exitCode: 0, state: 'complete', warning: true });
+ }, 300_000);
+
test('#3: a replayed purge hides its derived rows again and appends derived.hidden', async () => {
const scenario = () => collect<Record<string, unknown>>(resolve => withFileBeliefBrain(SOURCE, async fb => {
await fb.open(seedDerived);
@@ -313,6 +339,39 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
}, 240_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 => {
+ await b.put('companies/acme-example', beliefPage({ prose: 'Acme.' }));
+ await b.put('companies/acme-example', beliefPage({ facts: [X, 'Acme has two offices'] }));
+ await b.put('companies/widgets-example', beliefPage({ prose: 'Widgets.' }));
+ await b.put('companies/widgets-example', beliefPage({ facts: ['Acme sells widgets'] }));
+ await purgeFact(b, 'Acme sells widgets');
+ const url = new URL(engineCase.databaseUrl!);
+ const [{ db }] = await b.engine.executeRaw<{ db: string }>('SELECT current_database() AS db');
+ const clone = `gbrain_test_restore_${randomUUID().replace(/-/g, "").slice(0, 16)}`;
+ 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()`);
+ await admin.unsafe(`CREATE DATABASE ${clone} TEMPLATE ${db}`);
+ const archivedAt = new Date().toISOString();
+ const restored = new PostgresEngine();
+ try {
+ const result = await purgeFact(b, X);
+ const request = (await b.engine.executeRaw<{ id: string }>('SELECT id::text AS id FROM persistence_requests WHERE request_id = $1::uuid', [result.request_id]))[0]!.id;
+ for (const table of ['fact_purges', 'take_purges'])
+ await b.engine.executeRaw(`UPDATE ${table} SET purged_at = $2::timestamptz - interval '1 second' WHERE request_id = $1::uuid`, [request, archivedAt]);
+ url.pathname = `/${clone}`;
+ await restored.connect({ database_url: url.toString(), poolSize: 2 });
+ const replay = await replayPurgesFromDatabase(restored, b.engine, archivedAt);
+ resolve({ replays: replay.replays.map(x => [x.request === request, x.outcome]), left: await carriers({ ...b, engine: restored }, X) });
+ } finally {
+ await restored.disconnect();
+ await admin.unsafe(`DROP DATABASE IF EXISTS ${clone} WITH (FORCE)`);
+ await admin.end();
+ }
+ }, { databaseUrl: engineCase.databaseUrl }));
+ expect(r).toEqual({ replays: [[true, 'complete']], left: [] });
+ }, 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);