Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(purge): Cat 39 deletion-audit regressions (39-2..39-7); docs for receipts, version tombstones and journal redaction

garrytane52f1c168609
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index ceff7e0d63..05ebaf2d97 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -10,7 +10,8 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu
- `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.
- `src/core/facts/derivation-inputs.ts` — `recordDerivationInputs(tx, {table, id, sourceId}, inputs)`: complete derived-row → input edges, written by derivers in the deriving transaction (`write_origin` keeps only a display sample). `derivedRowsFrom` walks edges breadth-first (bounded, reports `truncated`); `hideDerivedRows` expires facts, deactivates takes, soft-deletes pages and upserts `needs_rederive`.
- `src/core/deletion-inventory.ts` — the deletion-target registry: every table with a text, JSON, bytes, array, lexeme or vector column, classed `swept`, `retained_inactive` or `out_of_scope` (`probed_reported` with probe columns, `text_free_ledger`, `secret_material`, `no_memory_text`), plus on-disk stores and out-of-reach residuals. `test/deletion-inventory.test.ts` fails on any unlisted text-bearing column of a fresh schema and pins the AGENTS.md "never promise physical erasure" line.
-- `src/core/persistence/intent-redaction.ts` — accounting-aware intent redaction: `findRequestsCarrying` / `findRequestsForSlugs`, `redactRequestIntents` locks counters then request rows, refuses on a non-terminal or recovering request (unless `skipPending`), and nulls `intent`/`error_message` with compaction's terminal-byte accounting so replay keeps returning the stored outcome.
-- `src/core/persistence/page-purge.ts` — `purgePageInTransaction`, called by the `delete_page purge:true` apply in `page-prepare.ts`: records the stored and purge-overlaid content hashes in `page_purges`, tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices and `files` rows, redacts finished intents for the slug, then deletes the page (FK cascades). `PURGE_RESIDUALS` names what stays out of reach. `finishPagePurge` deletes stored blobs after commit and lists any left by storage path. `readPagePurgeTombstones` feeds `screenImportContent({ purgedPages })` from managed sync's freeze-time screen (`sync-screen.ts`, one read per run) and publication (`sync-prepare.ts`), which hold a matching file as `purged_content`; direct imports and `put_page` hit the pages guard instead; `listPagePurges` / `unpurgePage` (also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned by `test/page-purge.test.ts`.
+- `src/core/persistence/intent-redaction.ts` — accounting-aware intent redaction: `findRequestsCarrying` (intent, outcome, error detail or message, compacted rows included) / `findRequestsForSlugs`, `redactRequestIntents` locks counters then request rows, refuses on a non-terminal or recovering request (unless `skipPending`), nulls `intent`/`error_message` and replaces every outcome or error-detail string carrying a needle with `"[purged]"` (`redactJson`), with compaction's terminal-byte accounting, so replay keeps returning the (redacted) stored outcome.
+- `src/core/persistence/purged-intent.ts` — `intentCarriesPurgedContent`: `completeWrite` (journal.ts) nulls the intent of any terminal request whose content (`fact`, `claim`, page fence rows, or the page's content hash) matches a subject-scoped purge tombstone, and of any refusal coded `purged_content`; a write refused for another reason, or committed as a no-op after the overlay dropped purged rows, keeps no copy. `purged_content` is a write error code, so receipts and the frozen verb path (wire `invalid_params`, canonical `purged_content`) keep it typed.
+- `src/core/persistence/page-purge.ts` — `purgePageInTransaction`, called by the `delete_page purge:true` apply in `page-prepare.ts`: records in `page_purges` the content hash of the page and of every retained version (up to 1000), each as imported and as purge-overlaid, so an older version is refused too; drops the decide rows, trust proposals, gate holds (by slug) and gate receipts naming the page or its rows and clears legacy `query_cache`; tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices and `files` rows, redacts finished intents for the slug, then deletes the page (FK cascades). `PURGE_RESIDUALS` names what stays out of reach. `finishPagePurge` deletes stored blobs after commit, lists any left by storage path, and attaches `receipt`, the store-by-store receipt from `verifyPagePurge` (same shape as the fact receipt: residuals first, every swept inventory store, other pages' prose naming a purged claim as `source_prose`); the page's claims used as needles live only in process memory, and a same-id replay returns the result built when the purge ran. `residuals` stays the prose string. `readPagePurgeTombstones` feeds `screenImportContent({ purgedPages })` from managed sync's freeze-time screen (`sync-screen.ts`, one read per run) and publication (`sync-prepare.ts`), which hold a matching file as `purged_content`; direct imports and `put_page` hit the pages guard instead; `listPagePurges` / `unpurgePage` (also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned by `test/page-purge.test.ts`.
- `src/core/ops/purge.ts` — `purge_fact`, `list_page_purges`, `unpurge_page`: admin scope, `cliOnly` (every MCP route gets `trusted_local_only`). The resident owner runs them only for its verified local CLI registration (`LOCAL_CLI_OWNER_OPERATIONS` in `persistence/ipc.ts`, checked in `persistence/provider.ts`).
- `src/commands/forget-purge.ts` + `src/commands/pages-purges.ts` — the CLI fronts. `runForgetPurge` always runs the dry run, then a typed token on a terminal or `--yes` plus `--request-id` without one; `--match` lists ids, `--status` polls completion; `PURGE_FAMILY_HELP` is the purge-family table shown by `gbrain forget --help`. `gbrain pages purges list` and `gbrain pages unpurge <slug>` run the page-tombstone ops as the trusted CLI.
diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.md
index d73cb12c1c..1eb7773f0f 100644
--- a/docs/guides/memory-boundaries.md
+++ b/docs/guides/memory-boundaries.md
@@ -168,9 +168,13 @@ claim said.
it (tombstoned), its takes, take proposals, open loops, core notices, stored
write intents, attached file records and blobs, and the page row with its
chunks, versions, timeline, links and raw data. It records the page's content
-hash, so the same content is refused under any slug until
+hash and the hash of every saved version, so the same content or an older version of it is refused under any slug until
`gbrain pages unpurge <slug>`; `gbrain pages purges list` shows the tombstones.
-An edited file imports normally.
+An edited file imports normally. Its response carries the same store-by-store
+`receipt` as a fact purge, naming other pages whose prose still states one of
+the purged page's facts. A write refused because it carries purged content,
+or accepted as a no-op after its purged rows were dropped, keeps no copy of
+that content in its stored write request.
## Verify in the actual harness
diff --git a/test/purge-eval-fixes.test.ts b/test/purge-eval-fixes.test.ts
new file mode 100644
index 0000000000..564f953714
--- /dev/null
+++ b/test/purge-eval-fixes.test.ts
@@ -0,0 +1,155 @@
+/**
+ * #5575 Cat 39 deletion-audit findings: purge leaves no claim text in stored
+ * request outcomes (39-2); remembering a purged claim refuses with typed
+ * purged_content on the verb path (39-3); refused or no-op writes of purged
+ * content keep no copy in their journal entry (39-4); fact and page receipts
+ * list every swept inventory store, store by store (39-5, 39-6); an older
+ * version of a purged page does not import again (39-7). Real PGLite, no
+ * provider calls.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { operations, OperationError, type OperationContext } from '../src/core/operations.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { admitWrite, completeWrite } from '../src/core/persistence/journal.ts';
+import { requestPrincipalForContext } from '../src/core/persistence/page-mutations.ts';
+import { submissionAuthority } from '../src/core/persistence/authority.ts';
+import { frozenVerbWriteError, runMemoryWrite } from '../src/core/persistence/verb-errors.ts';
+import { opError } from '../src/core/ops/contract.ts';
+import { DELETION_INVENTORY } from '../src/core/deletion-inventory.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const CLAIM = 'Vault combination is 7731';
+const home = mkdtempSync(join(tmpdir(), 'gbrain-purge-eval-fixes-'));
+let engine: PGLiteEngine;
+const op = (name: string) => operations.find(o => o.name === name)!;
+const context = (): OperationContext => ({ engine, config: { engine: 'pglite', embedding_disabled: true } as never,
+ logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: 'default' });
+const call = (name: string, params: Record<string, unknown>) =>
+ withEnv({ GBRAIN_HOME: home }, () => op(name).handler(context(), params)) as Promise<Record<string, any>>;
+const fenceRow = (n: number, claim: string) => `| ${n} | ${claim} | fact | 1.0 | world | medium | 2026-01-01 | | chat | |`;
+const page = (title: string, rows: string[], prose = 'Prose.') => `---\ntitle: ${title}\ntype: person\n---\n# ${title}\n\n${prose}\n\n## Facts\n\n<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+${rows.join('\n')}
+<!--- gbrain:facts:end -->\n`;
+const CONTENT = page('Alice', [fenceRow(1, CLAIM), fenceRow(2, 'Likes jasmine tea')]);
+
+async function seed(slug = 'people/alice-example', content = CONTENT): Promise<number> {
+ await importFromContent(engine, slug, content, { noEmbed: true, sourceId: 'default' });
+ await runExtractFacts(engine, { slugs: [slug] });
+ const [row] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE fact=$1 AND source_markdown_slug=$2', [CLAIM, slug]);
+ return Number(row.id);
+}
+async function purgeFact(id: number) {
+ const dry = await call('purge_fact', { id, dry_run: true });
+ return call('purge_fact', { id, confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() });
+}
+async function purgePage(slug: string) {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true });
+ return call('delete_page', { slug, purge: true, request_id: randomUUID(), expected_revision: snapshot!.revision });
+}
+async function codeOf(p: Promise<unknown>): Promise<string> {
+ try { await p; return 'ok'; } catch (e) { return e instanceof OperationError ? (e.canonical ?? e.code) : String((e as Error).message); }
+}
+async function journalCarries(text: string): Promise<number> {
+ const rows = await engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE strpos(lower(COALESCE(intent::text,'')||COALESCE(outcome::text,'')
+ ||COALESCE(error_detail::text,'')||COALESCE(error_message,'')),lower($1))>0`, [text]);
+ return rows.length;
+}
+
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);
+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); rmSync(home, { recursive: true, force: true }); }, 60_000);
+beforeEach(async () => {
+ await disposePersistenceConsumer(engine); await resetPgliteState(engine); _resetWriteThroughCacheForTest();
+ await withEnv({ GBRAIN_HOME: home }, () => registerLocalWriter(engine, 'cli'));
+});
+
+describe('purge eval fixes', () => {
+ test('39-2: stored request outcomes carrying the claim are redacted and the receipt says so honestly', async () => {
+ const id = await seed();
+ const c = context();
+ const principal = await withEnv({ GBRAIN_HOME: home }, () => requestPrincipalForContext(c));
+ const [source] = await engine.executeRaw<{ incarnation: string }>(`SELECT incarnation FROM sources WHERE id='default'`);
+ const row = await withEnv({ GBRAIN_HOME: home }, async () => admitWrite(engine, { principal, operation: 'add_timeline_entry', sourceId: 'default',
+ sourceIncarnation: source.incarnation, slug: 'people/alice-example', requestId: randomUUID(), callerIntent: { date: '2026-01-02' },
+ intent: { date: '2026-01-02' }, authority: await submissionAuthority(c, 'add_timeline_entry', 'default', source.incarnation, 'people/alice-example') }));
+ await engine.transaction(tx => completeWrite(tx, row, 'committed', { entry: { date: '2026-01-02', summary: `Told us: ${CLAIM}` } }));
+ expect(await journalCarries(CLAIM)).toBeGreaterThan(0);
+ const done = await purgeFact(id);
+ expect(await journalCarries(CLAIM)).toBe(0);
+ const [kept] = await engine.executeRaw<{ outcome: { entry: { date: string; summary: string } } }>('SELECT outcome FROM persistence_requests WHERE id=$1::uuid', [row.id]);
+ expect(kept.outcome.entry).toEqual({ date: '2026-01-02', summary: '[purged]' });
+ expect(done.stores.find((s: { store: string }) => s.store === 'persistence_requests')).toMatchObject({ status: 'deleted' });
+ }, 60_000);
+
+ test('39-3: remembering a purged claim refuses with purged_content (verb path, local and remote mapping)', async () => {
+ const id = await seed();
+ await purgeFact(id);
+ expect(await codeOf(call('remember', { fact: CLAIM, entity: 'people/alice-example', provenance: 'test' }))).toBe('purged_content');
+ const thrown = await runMemoryWrite(async () => { throw opError('purged_content', 'purged_content: x', 'y'); }).catch(e => e as OperationError);
+ expect([thrown.code, thrown.canonical]).toEqual(['invalid_params', 'purged_content']);
+ const frozen = frozenVerbWriteError({ request_id: randomUUID(), state: 'failed', retry_after_ms: null }, 'purged_content', 'purged_content: x');
+ expect([frozen.code, frozen.canonical, frozen.detail]).toEqual(['invalid_params', 'purged_content', 'purged_content']);
+ }, 60_000);
+
+ test('39-4: refused and no-op writes of purged content keep no copy in their journal entry', async () => {
+ const id = await seed();
+ await purgeFact(id);
+ expect(await journalCarries(CLAIM)).toBe(0);
+ await codeOf(call('remember', { fact: CLAIM, entity: 'people/alice-example', provenance: 'test' }));
+ await codeOf(call('put_page', { slug: 'people/alice-example', content: CONTENT, request_id: randomUUID() }));
+ expect(await journalCarries(CLAIM)).toBe(0);
+ const [page] = await engine.executeRaw<{ compiled_truth: string }>(`SELECT compiled_truth FROM pages WHERE slug='people/alice-example'`);
+ expect(page.compiled_truth).not.toContain(CLAIM);
+ }, 60_000);
+
+ test('39-5: the fact receipt lists every swept inventory store, files and persistence_effects included', async () => {
+ const done = await purgeFact(await seed());
+ const listed = new Set([...done.stores, ...done.residuals].map((s: { store: string }) => s.store));
+ const swept = DELETION_INVENTORY.filter(e => e.class === 'swept').map(e => e.table);
+ expect(swept.filter(t => !listed.has(t))).toEqual([]);
+ expect(listed.has('files') && listed.has('persistence_effects')).toBe(true);
+ }, 60_000);
+
+ test('39-6: the page receipt is store by store, verified, and names other pages that keep a claim in prose', async () => {
+ await seed();
+ await importFromContent(engine, 'meetings/2026-03-12-sync', `---\ntitle: Sync\ntype: meeting\n---\n# Sync\n\nAlice said: ${CLAIM}.\n`, { noEmbed: true, sourceId: 'default' });
+ const purged = await purgePage('people/alice-example');
+ expect(purged.status).toBe('purged');
+ expect(String(purged.residuals)).toContain('git history');
+ const result = purged.receipt;
+ expect(Object.keys(result).indexOf('residuals')).toBeLessThan(Object.keys(result).indexOf('stores'));
+ const byStore = new Map(result.stores.map((s: { store: string }) => [s.store, s]));
+ const swept = DELETION_INVENTORY.filter(e => e.class === 'swept').map(e => e.table);
+ expect(swept.filter(t => !byStore.has(t))).toEqual([]);
+ expect(byStore.get('facts')).toMatchObject({ status: 'deleted' });
+ expect(byStore.get('pages')).toMatchObject({ status: 'out_of_scope', reason: 'source_prose', items: ['meetings/2026-03-12-sync'] });
+ for (const store of ['canonical_markdown', 'fence_tmp_evidence', 'persistence_effects']) expect(byStore.has(store)).toBe(true);
+ expect(result.stores.some((s: { status: string }) => s.status === 'incomplete')).toBe(false);
+ expect(result.page_tombstones).toBeGreaterThanOrEqual(1);
+ expect(JSON.stringify(result)).not.toContain(CLAIM);
+ }, 60_000);
+
+ test('39-7: an older version of a purged page is refused as well as its last content', async () => {
+ const v1 = page('Bob', [fenceRow(1, 'Bob keeps the spare key under the mat')], 'First draft.');
+ await importFromContent(engine, 'people/bob-example', v1, { noEmbed: true, sourceId: 'default' });
+ await importFromContent(engine, 'people/bob-example', page('Bob', [fenceRow(1, 'Bob keeps the spare key under the mat')], 'Second draft.'),
+ { noEmbed: true, sourceId: 'default' });
+ expect(await engine.executeRaw(`SELECT 1 FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.slug='people/bob-example'`)).not.toHaveLength(0);
+ await purgePage('people/bob-example');
+ for (const slug of ['people/bob-example', 'archive/bob-v1']) {
+ const error = await importFromContent(engine, slug, v1, { noEmbed: true, sourceId: 'default' }).then(() => 'imported', e => String((e as Error).message));
+ expect(error).toContain('purged_content');
+ }
+ }, 60_000);
+});