Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

belief ledger lane A: restore probes via file-brain helper, body-reader rows, Postgres arms, docs

garrytan90939aecbb6c
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index 5322f4625b..709da51ddd 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -23,7 +23,7 @@ Managed connector ingestion, connector item holds and the no-op kernel (checkpoi
- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.
- `src/core/persistence/{database-write,manual-links}.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `coordinatedManualLinkWrite` (`add_link` / `remove_link`) and `ontology_propose` (one entity page key) use it. On a managed brain it checks the caller's durable write authority for the authority page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits inside `withCoordinatedWrite` holding the given page keys (both link endpoints). Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`, `test/managed-ontology-propose.test.ts`.
- `src/core/persistence/{attribution,attribution-schema,context}.ts` — write attribution. `withCoordinatedWrite(engine, sourceIds, fn, attribution)` sets `gbrain.write_sources` and the transaction-local actor (`gbrain.write_request`, `gbrain.write_principal_kind`, `gbrain.write_principal_id`) in one round trip and restores them on exit; a nested scope keeps the outer actor. The argument is required: `requestAttribution(row)` for journaled publication (coordinator, forget), `maintenanceAttribution(engine)` (verified local writer, else the CLI registration, else `application`/`host:<id>`; no request) for derived facts, takes/timeline/link extraction, materialization, concept provenance, connector freshness and verify cleanup, `principalAttribution` for manual links (the caller) and source lifecycle (the topology principal). `withWriteAttribution` sets only the actor, for unmanaged legacy transactions; `maintenanceTransaction(engine, fn)` wraps it in one transaction, and every unmanaged direct writer runs its write (or one bounded batch) in it (the `system-of-record.md` "unattributed" list is empty; derivers pass their taint as `maintenanceTransaction(engine, fn, trust)`, see `trust/taint.ts`). `attribution-schema.ts` (migration `f1_write_attribution`; migration-only like the facts DDL, so columns land last on fresh and upgraded brains) adds nullable columns and BEFORE ROW triggers: `facts`/`takes`/`timeline_entries` carry `write_*` (created_by, immutable once set) and `last_write_*` + `last_written_at` (moved only when a classified content column changes; a NULL actor records an unattributed writer); `pages.revision_*` is stamped when `knowledge_revision` changes; `page_versions.write_*` copies the snapshotted revision's actor and `archived_*` names the archiving write. `write_request_id` is `persistence_requests.id` with no foreign key; all-NULL reads as unrecorded. Every column of the three tables is classified content, projection (embeddings, `takes.updated_at`) or attribution, and a new column must be classified and the function re-created; the writer guard treats attribution-only facts/takes updates as projections. Tests: `test/write-attribution.test.ts`, `test/write-attribution-legacy.test.ts` (writer inventory) and `test/write-attribution-<family>.test.ts` (each routed unmanaged writer path; `write-attribution-timeline-10k.slow.test.ts` checks bounded batches at 10k pages) on PGLite; Postgres direct and PgBouncer through `test/e2e/write-attribution-postgres.test.ts`.
-- `src/core/persistence/purge-deleted.ts` — `purgeDeletedPagesCoordinated` backs the cycle `purge` phase, the purge job, `purge_deleted_pages` and `gbrain pages purge-deleted`. Unmanaged brains keep the engine bulk delete; a managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) through `delete_page` with `purge: true` bound to its revision. Revision races are deferred to the next run; any other failure is listed in `blocked` and sets `error`, which fails the purge phase. Tests: `test/managed-writers-w3.test.ts`.
+- `src/core/persistence/purge-deleted.ts` — `purgeDeletedPagesCoordinated` backs the cycle `purge` phase, the purge job, `purge_deleted_pages` and `gbrain pages purge-deleted`. Unmanaged brains keep the engine bulk delete; a managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) through `delete_page` with `purge: true` and the internal `retention: true` bound to its revision (W1, BELIEF_LEDGER.md 6.5: retention is not an owner purge, so it writes no content tombstone, redacts no history, appends no purge-mirror line and records `page.expired`; `purge-params.ts` accepts `retention` only from a local caller with `purge: true`). On an unmanaged brain each expired tombstone of a source with belief coverage is first deleted under its page key in a belief batch that appends `page.expired`; the bulk delete takes the rest. Revision races are deferred to the next run; any other failure is listed in `blocked` and sets `error`, which fails the purge phase. Tests: `test/managed-writers-w3.test.ts`.
- `src/core/persistence/loop-fact-retirement.ts` — #5869 commitment-fact retirement for closed loops, one coordinator mutation on every brain (operation `loops_close`, intent `retire_loop_fact`, dispatched from `service.ts`): expires the fact and strikes its `## Facts` fence row (context `loop closed: <status>`) through the entity page publication in one transaction; no withdrawal tombstone. The shared rule (also `loopFactDrift`, used by doctor `loop_facts_drift` and `gbrain repair loop-facts`): only a fact in the loop's source that no other open loop references, re-checked under row locks at publication (`shared_with_open_loop`, `source_mismatch` otherwise). `retireLoopFact(ctx, loopId)` submits with the caller's grant and maps a refusal or pending write to `fact_expired: false, retryable: true, reason`. Tests: `test/loops-close-fact.serial.test.ts` (+ Postgres twin).
- `src/core/persistence/connector-authority.ts` -- classifies each Google/GitHub source as `connector_database` (managed, unbound), `bound` or `unmanaged` from `persistence_brain.enabled` and the source binding row. File-lane audits (doctor `undeclared_db_only_pages`, backup coverage) read it so a leftover cache directory at `local_path` is never taken for canonical files. Tests: `test/doctor-silent-death-checks.test.ts`, `test/backup-coverage.serial.test.ts`.
- `src/core/persistence/connector-sync.ts` — managed Google/GitHub API ingestion through source-scoped journaled `connector_v2_import`/`_delete`/`_checkpoint`/`_google_receipts` intents and `managed-connector` checkpoint CAS, not Git cursors. The checkpoint key, admission `configHash`, mid-sweep change check and publication `source_changed` check all use the parsed-config identity from `connector-identity.ts`, so cycle stamps in `sources.config` never rotate them. Unbound connectors use reviewed `connector_database` SQL-only authority; bound connectors retain canonical file publication with guarded root/hash/revision/epoch. Every managed run checks the credential's resolved account against the pin in the connector state row before reading its checkpoint (`assertAccount`), then applies a requested `--reset-checkpoint` (pending writes resolved first, pin kept). Each import or delete is first screened by running `prepareConnectorMutation` on an unadmitted request through the no-op kernel; unchanged items take no admission. An unchanged checkpoint save is skipped and, when it would have stamped freshness, `last_sync_at` is stamped directly inside a lease-asserted coordinated write. Accepted-pending writes are progress: a 30-second total wait budget (writes committing within one second are free), at most one in-flight write per page, outstanding writes kept under the principal's outstanding and intent-byte limits, and `ConnectorWaitBudgetStop` (a `write_pending` error) when the budget is spent. The checkpoint never advances past a pending page; the run records its pending set in the state row, and the next run resolves it first (committed dropped, failed retried automatically through the retry-pointer path without `--retry-failed`, unreached failures after a complete sweep dropped and counted). Retired `managed_connector_*` intents route to `prepareOutdatedConnectorMutation`, which fails them `connector_intent_outdated` (detail `pre_upgrade` before the v176 cutoff). Standalone entry, page reads and submissions authenticate the current source, local grant and canonical owner and settle retained worktree publications before deriving request identity. Explicit `--retry-failed` atomically admits a linked attempt and stores a per-base-request `managed-connector-retry` pointer. Durable connector cursors, retry pointers and state rows survive generic seven-day checkpoint GC. Tests: `test/persistence-connectors.test.ts`, `test/persistence-connector-retry.test.ts`, `test/connector-checkpoint-identity.test.ts`, `test/connector-wave3.test.ts` and `test/helpers/connector-restart.ts` on PGLite and disposable Postgres.
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index b61eee4500..6da1862239 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -5,7 +5,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#purge).
- `src/core/facts/purge.ts` — `submitPurgeFactMutation`, the handler of the owner-only `purge_fact` op (`gbrain forget <id> --purge`). Refuses every caller whose `ctx.remote !== false` with `trusted_local_only` (`purgeHostOnly`, actor user, the exact host command). `planFactPurge` (read-only) computes the scope: every fact row with the same `gbrain_fact_fingerprint` in the fact's source, visibility and subject (the fact's `entity_slug`, `'*'` with `all_subjects`), verbatim takes (`facts.consolidated_into` plus same-fingerprint takes on the subject's page), affected pages from `discoverWithdrawalTargets`, page_versions carrying the text, terminal request intents carrying it (`findRequestsCarrying` behind the `purge:carrying_lookup` seam; its 57014 is the typed `purge_lookup_timeout`, nothing planned or purged, pinned by `test/fact-purge-lookup-timeout-6511.test.ts`), derived rows from `derivation_inputs`, the fact's P8 review rows, and a `revision` digest. A dry run returns the receipt, `confirm_token` (fingerprint's first 8 hex) and `expected_revision`; a real run requires `confirm === token` and, when given, an unchanged revision. The journaled intent is `{id, reason, all_subjects, fact_hash}`, never claim text; replay by request id returns the stored outcome. One transaction in the global lock order: source `FOR UPDATE` (serializes with the guards' `FOR SHARE`), counters for the purge and every redacted request, admission, then inside `withCoordinatedWrite`: pending-publication refusal (`purge_blocked_pending_recovery`), intent redaction, page locks, derived rows hidden before evidence goes, `fact_purges`/`take_purges` tombstones, deletes (takes, review rows, open loops by fact id, take proposals by fingerprint, facts), core-notice base text nulled, page bodies rewritten through the purge overlay, chunks deleted, versions redacted in place, legacy `query_cache` cleared, and `withdrawal-mirror`/`git`/`embedding` effects with `mode: 'purge'` and `commit_subject: gbrain: purge fact <hash8>`. Chunks are rebuilt before acknowledging; `similar_active` is computed before deletion. Pinned by `test/purge-fact.test.ts` (both engines) and `test/forget-purge-cli.test.ts`.
-- `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. 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/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/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/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index 3cbf922776..fe4ac493d4 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -70,6 +70,8 @@ src/core/ai/decide/review-lane.ts pagePairAnchor field LEAD bounded prefix row
src/core/ai/decide/review-lane.ts pagePairAnchor sql LEAD boundedBodyPrefixSql (truth_lead for segmented), sliced to PAGE_TEXT_LIMIT
src/core/attendance-repair.ts prepareOrigin field META
src/core/attendance-repair.ts readOrigin sql META
+src/core/belief/purge.ts pagePurgeClaims field STREAM segmented version: NULL body parses no fence claims; the live rows' and the lifetimes' event claims still cover it
+src/core/belief/purge.ts pagePurgeClaims sql STREAM segmented version: NULL body parses no fence claims; the live rows' and the lifetimes' event claims still cover it
src/core/belief/state.ts readBeliefState sql META size only (the over-1 MiB creation rule); a segmented page counts as large by body_storage
src/core/brainstorm/domain-bank.ts fetchFar field LEAD
src/core/brainstorm/orchestrator.ts _runBrainstormInner field LEAD
@@ -396,9 +398,11 @@ src/core/persistence/page-prepare.ts canonical field SEGW lane 1d file; segmente
src/core/persistence/page-prepare.ts fileMatchesSnapshot field SEGW lane 1d file; segmented page: getter throws page_body_segmented
src/core/persistence/page-prepare.ts preparePageMutation call:serializePageToMarkdown SEGW lane 1d file
src/core/persistence/page-prepare.ts preparePageMutation field SEGW lane 1d file: preserveProtectedTakes reads the snapshot body; segmented page: getter throws page_body_segmented
-src/core/persistence/page-purge.ts purgePageInTransaction call:contentHash META
src/core/persistence/page-purge.ts purgePageInTransaction field STREAM
src/core/persistence/page-purge.ts purgePageInTransaction sql STREAM
+src/core/persistence/page-purge.ts tombstonePage call:contentHash META
+src/core/persistence/page-purge.ts tombstonePage field STREAM
+src/core/persistence/page-purge.ts tombstonePage sql STREAM
src/core/persistence/prepared-maintenance.ts stampMaintenancePage call:serializePageToMarkdown SEGW
src/core/persistence/prepared-maintenance.ts verifyMaintenanceOutputs call:serializePageToMarkdown SEGW
src/core/persistence/purged-intent.ts intentCarriesPurgedContent call:contentHash META
diff --git a/test/belief-ledger-restore.test.ts b/test/belief-ledger-restore.test.ts
index f3aba8f032..e72dcd835a 100644
--- a/test/belief-ledger-restore.test.ts
+++ b/test/belief-ledger-restore.test.ts
@@ -8,25 +8,19 @@
*/
import { afterEach, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { existsSync, readFileSync, 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 { createPgliteBackup, restorePgliteBackup } from '../src/core/backup/snapshot.ts';
import type { BrainEngine } from '../src/core/engine.ts';
-import type { OperationContext } from '../src/core/ops/contract.ts';
import { operations } from '../src/core/operations.ts';
-import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { PostgresEngine } from '../src/core/postgres-engine.ts';
-import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { purgeDeletedPagesCoordinated } from '../src/core/persistence/purge-deleted.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
-import { enableBeliefLedger } from '../src/core/belief/coverage.ts';
-import { brainApi, beliefBrain, beliefEngineCase, beliefPage, type BeliefBrain } from './helpers/belief-ledger.ts';
+import { beliefBrain, beliefEngineCase, beliefPage, openFileBeliefBrain, withFileBeliefBrain, type BeliefBrain, type FileBeliefBrain } from './helpers/belief-ledger.ts';
import { testBackends } from './helpers/test-backends.ts';
-import { withEnv } from './helpers/with-env.ts';
afterEach(() => { __setPurgeReplayFaultForTests(null); __setBeliefEmitterFaultForTests(null); });
@@ -35,37 +29,6 @@ const SOURCE = 'belief-restore';
const purgeOp = operations.find(o => o.name === 'purge_fact')!;
const deleteOp = operations.find(o => o.name === 'delete_page')!;
-/** A file-configured PGLite brain at `<home>/.gbrain/brain.pglite` (the backup format), reopened around each backup. */
-interface FileBrain { home: string; open<T>(fn: (b: BeliefBrain) => Promise<T>): Promise<T> }
-
-async function withFileBrain(run: (fb: FileBrain) => Promise<void>): Promise<void> {
- const home = mkdtempSync(join(tmpdir(), 'gbrain-belief-restore-'));
- const dbPath = join(home, '.gbrain', 'brain.pglite');
- mkdirSync(join(home, '.gbrain'), { recursive: true, mode: 0o700 });
- writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: dbPath }), { mode: 0o600 });
- const open = async <T>(fn: (b: BeliefBrain) => Promise<T>, initialize = false): Promise<T> => {
- const engine = new PGLiteEngine();
- await engine.connect({ engine: 'pglite', database_path: dbPath });
- try {
- if (initialize) await engine.initSchema();
- const ctx: OperationContext = { engine, sourceId: SOURCE, remote: false, dryRun: false,
- config: { engine: 'pglite', embedding_disabled: true } as never, logger: { info() {}, warn() {}, error() {} } as never };
- return await fn(brainApi(engine, ctx, join(home, 'content'), SOURCE));
- } finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }
- };
- try {
- await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
- mkdirSync(join(home, 'content'));
- await open(async b => {
- await b.engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [SOURCE, join(home, 'content')]);
- await claimWorktree(b.engine, SOURCE, join(home, 'content'));
- await enableBeliefLedger(b.engine, SOURCE);
- }, true);
- await run({ home, open: fn => open(fn) });
- });
- } finally { rmSync(home, { recursive: true, force: true }); }
-}
-
async function purgeFact(b: BeliefBrain, claim: string): Promise<Record<string, any>> {
const [row] = await b.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id = $1 AND fact = $2 AND expired_at IS NULL ORDER BY id LIMIT 1', [b.sourceId, claim]);
const dry = await purgeOp.handler(b.ctx, { id: Number(row!.id), dry_run: true }) as Record<string, any>;
@@ -85,19 +48,15 @@ async function carriers(b: BeliefBrain, claim: string): Promise<string[]> {
return found;
}
-async function backupAndRestore(fb: FileBrain, between: () => Promise<void>, opts: { purgeMirror?: string } = {}) {
+async function backupAndRestore(fb: FileBeliefBrain, between: () => Promise<void>, opts: { purgeMirror?: string } = {}) {
const archive = join(fb.home, `archive-${randomUUID().slice(0, 8)}.gbrain-backup`);
const archived = await fb.open(b => ledgerRows(b.engine));
await createPgliteBackup({ root: fb.home, output: archive });
await between();
const into = join(fb.home, `restored-${randomUUID().slice(0, 8)}`);
const result = await restorePgliteBackup({ archive, into, ...opts });
- const engine = new PGLiteEngine();
- await engine.connect({ engine: 'pglite', database_path: join(into, '.gbrain', 'brain.pglite') });
- const ctx = { engine, sourceId: SOURCE, remote: false, dryRun: false, config: { engine: 'pglite', embedding_disabled: true } as never,
- logger: { info() {}, warn() {}, error() {} } as never } as OperationContext;
- const restored = brainApi(engine, ctx, join(into, 'content'), SOURCE);
- return { archived, result, restored, receipt: JSON.parse(readFileSync(join(into, 'restore-receipt.json'), 'utf8')), close: () => engine.disconnect() };
+ const { brain: restored, close } = await openFileBeliefBrain(join(into, '.gbrain', 'brain.pglite'), SOURCE, join(into, 'content'));
+ return { archived, result, restored, receipt: JSON.parse(readFileSync(join(into, 'restore-receipt.json'), 'utf8')), close };
}
/** Runs a brain scenario to completion (teardown included, so withEnv scopes never overlap) and returns what it reported. */
@@ -122,7 +81,7 @@ const replayFault = (fault: PurgeReplayFault) => () => __setPurgeReplayFaultForT
describe('belief ledger restore (pglite archive)', () => {
test('probe 11: the restored ledger is the archive\'s plus one coverage.restored; a later purge is replayed; no mirror records unavailable', async () => {
- const scenario = () => collect<Record<string, unknown>>(resolve => withFileBrain(async fb => {
+ const scenario = () => 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'] }));
@@ -160,7 +119,7 @@ describe('belief ledger restore (pglite archive)', () => {
}, 300_000);
test('probe 32: an archive holding only another subject\'s quote of a claim asserted and purged later replays partial and warns', async () => {
- const scenario = () => collect<Record<string, unknown>>(resolve => withFileBrain(async fb => {
+ const scenario = () => collect<Record<string, unknown>>(resolve => withFileBeliefBrain(SOURCE, async fb => {
await fb.open(async b => {
await b.put('notes/quotes-example', beliefPage({ prose: 'Quotes.' }));
await b.put('notes/quotes-example', beliefPage({ facts: [{ claim: 'Quote one', context: `heard ${X}` }] }));
@@ -179,7 +138,7 @@ describe('belief ledger restore (pglite archive)', () => {
}, 300_000);
test('probe 34: a purge whose committed line never landed, after complete ones, is reported unverified and warns', async () => {
- const scenario = () => collect<Record<string, unknown>>(resolve => withFileBrain(async fb => {
+ const scenario = () => 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 has two offices'] }));
@@ -204,7 +163,7 @@ describe('belief ledger restore (pglite archive)', () => {
}, 300_000);
test('probe 36: backup, soft delete, retention cleanup (page.expired), then restore: no tombstone, no redaction, nothing replayed', async () => {
- const scenario = () => collect<Record<string, unknown>>(resolve => withFileBrain(async fb => {
+ const scenario = () => collect<Record<string, unknown>>(resolve => withFileBeliefBrain(SOURCE, async fb => {
const slug = 'notes/old-example';
await fb.open(async b => {
await b.put(slug, beliefPage({ prose: 'Old.' }));
diff --git a/test/helpers/belief-ledger.ts b/test/helpers/belief-ledger.ts
index c80dacd7eb..76f98946c5 100644
--- a/test/helpers/belief-ledger.ts
+++ b/test/helpers/belief-ledger.ts
@@ -6,7 +6,7 @@
* (`beliefEngineCase`), so every probe asserts the same values on both.
*/
import { randomUUID } from 'node:crypto';
-import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../../src/core/engine.ts';
@@ -104,6 +104,43 @@ export async function beliefBrain(run: (brain: BeliefBrain) => Promise<void>,
}
}
+/** A file-configured PGLite brain at `<home>/.gbrain/brain.pglite` (the backup format); `open` connects it for one step, so backups run between steps. */
+export interface FileBeliefBrain { home: string; open<T>(fn: (brain: BeliefBrain) => Promise<T>): Promise<T> }
+
+/** Connects the PGLite brain at `databasePath` (a restored one, say) as a probe brain; `close` disconnects it. */
+export async function openFileBeliefBrain(databasePath: string, sourceId: string, root: string): Promise<{ brain: BeliefBrain; close: () => Promise<void> }> {
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite', database_path: databasePath });
+ const ctx: OperationContext = { engine, sourceId, remote: false, dryRun: false,
+ config: { engine: 'pglite', embedding_disabled: true } as never, logger: { info() {}, warn() {}, error() {} } as never };
+ return { brain: brainApi(engine, ctx, root, sourceId), close: async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); } };
+}
+
+/** Runs `run` with GBRAIN_HOME at a new file-configured PGLite brain whose source `sourceId` has coverage enabled. */
+export async function withFileBeliefBrain(sourceId: string, run: (brain: FileBeliefBrain) => Promise<void>): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-belief-file-'));
+ const databasePath = join(home, '.gbrain', 'brain.pglite');
+ const root = join(home, 'content');
+ mkdirSync(join(home, '.gbrain'), { recursive: true, mode: 0o700 });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: databasePath }), { mode: 0o600 });
+ const open = async <T>(fn: (brain: BeliefBrain) => Promise<T>): Promise<T> => {
+ const { brain, close } = await openFileBeliefBrain(databasePath, sourceId, root);
+ try { return await fn(brain); } finally { await close(); }
+ };
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ mkdirSync(root);
+ await open(async brain => {
+ await brain.engine.initSchema();
+ await brain.engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await claimWorktree(brain.engine, sourceId, root);
+ await enableBeliefLedger(brain.engine, sourceId);
+ });
+ await run({ home, open });
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
/** A page body with a facts fence, a takes fence, prose and wikilinks. */
export function beliefPage(o: { title?: string; type?: string; prose?: string; facts?: Array<string | { claim: string; context?: string; confidence?: string; visibility?: string }>;
takes?: Array<string | { claim: string; weight?: string; since?: string }>; links?: string[]; frontmatter?: Record<string, string> } = {}): string {
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index a9073b3366..5a340a8d2a 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -18,6 +18,8 @@ test/backstop-same-page-shadow-managed-6333.test.ts
test/behavior-change-notice.test.ts
test/belief-ledger-lifecycle.test.ts
test/belief-ledger-privacy.test.ts
+test/belief-ledger-purge.test.ts
+test/belief-ledger-restore.test.ts
test/capture-consent-admission.test.ts
test/capture-dispatch-provenance-6524.test.ts
test/chronicle-backfill-max-usd.test.ts