Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(purge): page purge sweep and tombstone, inventory completeness, forget --purge CLI confirmation

garrytan9d4573062923
diff --git a/src/commands/forget-purge.ts b/src/commands/forget-purge.ts
index 105d6a7362..7dab8809fc 100644
--- a/src/commands/forget-purge.ts
+++ b/src/commands/forget-purge.ts
@@ -85,7 +85,10 @@ export function renderPurgeReceipt(r: Record<string, unknown>): string {
return lines.join('\n') + '\n';
}
-export async function runForgetPurge(engine: BrainEngine | (() => Promise<BrainEngine>), args: string[]): Promise<void> {
+/** Test seam: the terminal probe and the typed-token reader (defaults: isInteractive and a stderr prompt). */
+export interface PurgeCliIo { interactive?: () => boolean; readToken?: (prompt: string) => Promise<string | null> }
+
+export async function runForgetPurge(engine: BrainEngine | (() => Promise<BrainEngine>), args: string[], io: PurgeCliIo = {}): Promise<void> {
const json = args.includes('--json');
const { reportPersistenceCliError } = await import('./persistence-delegate.ts');
const { parseWriteRequestId } = await import('../core/persistence/preconditions.ts');
@@ -118,10 +121,11 @@ export async function runForgetPurge(engine: BrainEngine | (() => Promise<BrainE
const dry = await invoke({ ...base, dry_run: true });
if (args.includes('--dry-run')) { out(dry, renderPurgeReceipt(dry)); return; }
const token = String(dry.confirm_token);
- if (isInteractive() && !args.includes('--yes')) {
+ if ((io.interactive ?? isInteractive)() && !args.includes('--yes')) {
process.stdout.write(renderPurgeReceipt(dry));
- const answer = await readLine({ prompt: `\nType ${token} to purge fact ${idArg} from live stores (anything else cancels): `, output: process.stderr });
- if (answer.kind !== 'line' || answer.text.trim() !== token) {
+ const prompt = `\nType ${token} to purge fact ${idArg} from live stores (anything else cancels): `;
+ const answer = io.readToken ? await io.readToken(prompt) : await readLine({ prompt, output: process.stderr }).then(r => r.kind === 'line' ? r.text : null);
+ if (answer === null || answer.trim() !== token) {
process.stderr.write('Not purged.\n');
setCliExitVerdict(3);
return;
@@ -137,7 +141,10 @@ export async function runForgetPurge(engine: BrainEngine | (() => Promise<BrainE
out(done, renderPurgeReceipt(done));
setCliExitVerdict(Number(done.exit_code ?? 0));
} catch (error) {
- if (await reportPersistenceCliError(error, json)) return;
- throw error;
+ if (!await reportPersistenceCliError(error, json)) throw error;
+ // Not confirmed: 3 (ask the user). A pending write blocks the sweep: 75 (retry later with the same request id).
+ const code = (error as { canonical?: string; code?: string }).canonical ?? (error as { code?: string }).code;
+ if (code === 'confirmation_required') setCliExitVerdict(3);
+ else if (code === 'purge_blocked_pending_recovery') setCliExitVerdict(75);
}
}
diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.ts
index a05bdbe3b5..6df8f262b5 100644
--- a/src/core/persistence/page-purge.ts
+++ b/src/core/persistence/page-purge.ts
@@ -23,6 +23,8 @@ import { opError } from '../ops/contract.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import type { WriteRequest } from './model.ts';
import { findRequestsForSlugs, redactRequestIntents } from './intent-redaction.ts';
+import { dropPurgedFenceRows } from '../facts/purge-overlay.ts';
+import { contentHash } from '../utils.ts';
export const PURGE_RESIDUALS = 'Removed from live stores: the page row with its chunks, versions, takes, timeline, links and raw data, the facts filed on it (tombstoned), '
+ 'its take proposals, open loops and core notices, stored write intents for the slug and its attached file records. Still out of reach: the brain repository\'s '
@@ -39,14 +41,21 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
const page = snapshot.page, sourceId = row.source_id, slug = page.slug;
const actor = `${row.principal_kind}:${row.principal_id}`;
const [stored] = await tx.executeRaw<{ content_hash: string | null }>('SELECT content_hash FROM pages WHERE id=$1', [page.id]);
- const contentHash = stored?.content_hash ?? null;
- if (contentHash) await tx.executeRaw(`INSERT INTO page_purges(source_id,content_hash,slug,request_id) VALUES ($1,$2,$3,$4::uuid)
- ON CONFLICT (source_id,content_hash) DO UPDATE SET slug=EXCLUDED.slug,request_id=EXCLUDED.request_id,purged_at=now()`, [sourceId, contentHash, slug, row.id]);
+ const storedHash = stored?.content_hash ?? null;
+ if (storedHash) await tx.executeRaw(`INSERT INTO page_purges(source_id,content_hash,slug,request_id) VALUES ($1,$2,$3,$4::uuid)
+ ON CONFLICT (source_id,content_hash) DO UPDATE SET slug=EXCLUDED.slug,request_id=EXCLUDED.request_id,purged_at=now()`, [sourceId, storedHash, slug, row.id]);
await tx.executeRaw(`INSERT INTO fact_purges(source_id,visibility,subject,fact_hash,request_id,actor,reason)
SELECT DISTINCT source_id,visibility,COALESCE(entity_slug,'*'),gbrain_fact_fingerprint(fact),$3::uuid,$4,'page purge'
FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ON CONFLICT DO NOTHING`, [sourceId, slug, row.id, actor]);
await tx.executeRaw(`INSERT INTO take_purges(source_id,subject,claim_hash,request_id)
SELECT DISTINCT $1,$2,gbrain_fact_fingerprint(claim),$4::uuid FROM takes WHERE page_id=$3 ON CONFLICT DO NOTHING`, [sourceId, slug, page.id, row.id]);
+ // A re-import passes through the purge overlay, which now drops this page's tombstoned fence rows;
+ // its content hash is tombstoned too, so the stale file is refused either way.
+ const overlaid = { ...page, compiled_truth: await dropPurgedFenceRows(tx, sourceId, page.compiled_truth, slug),
+ timeline: await dropPurgedFenceRows(tx, sourceId, page.timeline ?? '', slug), tags: snapshot.tags };
+ const overlaidHash = contentHash(overlaid);
+ if (storedHash && overlaidHash !== storedHash) await tx.executeRaw(`INSERT INTO page_purges(source_id,content_hash,slug,request_id) VALUES ($1,$2,$3,$4::uuid)
+ ON CONFLICT (source_id,content_hash) DO UPDATE SET slug=EXCLUDED.slug,request_id=EXCLUDED.request_id,purged_at=now()`, [sourceId, overlaidHash, slug, row.id]);
const count = async (sql: string, params: unknown[]) => (await tx.executeRaw(sql, params)).length;
const facts = await count('DELETE FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 RETURNING 1', [sourceId, slug]);
const takeProposals = await count('DELETE FROM take_proposals WHERE source_id=$1 AND page_slug=$2 RETURNING 1', [sourceId, slug]);
@@ -61,7 +70,7 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
(SELECT count(*)::int FROM takes WHERE page_id=$1) AS takes, (SELECT count(*)::int FROM timeline_entries WHERE page_id=$1) AS timeline`, [page.id]);
await tx.deletePage(slug, { sourceId });
return { status: 'purged', slug, source_id: sourceId, residuals: PURGE_RESIDUALS,
- purge: { content_hash8: contentHash?.slice(0, 8) ?? null, tombstoned: contentHash !== null,
+ purge: { content_hash8: storedHash?.slice(0, 8) ?? null, tombstoned: storedHash !== null,
removed: { facts, take_proposals: takeProposals, open_loops: openLoops, core_edit_notices: notices, persistence_requests: intents,
files: files.length, content_chunks: cascade?.chunks ?? 0, page_versions: cascade?.versions ?? 0, takes: cascade?.takes ?? 0, timeline_entries: cascade?.timeline ?? 0 },
blobs: files.map(f => f.storage_path).filter(Boolean) } };
diff --git a/test/deletion-inventory.test.ts b/test/deletion-inventory.test.ts
new file mode 100644
index 0000000000..85312ed827
--- /dev/null
+++ b/test/deletion-inventory.test.ts
@@ -0,0 +1,50 @@
+/**
+ * #5575 CEO-22: the deletion-target inventory classifies every text-bearing
+ * column. A migration that adds a text, JSON, bytes, array, lexeme or vector
+ * column to any table fails here until the column is listed (and its table
+ * classified as swept, retained_inactive or out_of_scope with a reason).
+ * Also pins the docs promise: AGENTS.md still says never promise physical erasure.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { DELETION_INVENTORY, DELETION_INVENTORY_BY_TABLE } from '../src/core/deletion-inventory.ts';
+
+let engine: PGLiteEngine;
+const TEXT_BEARING = ['text', 'varchar', 'bpchar', 'jsonb', 'json', 'bytea', '_text', '_varchar', 'tsvector', 'vector', 'halfvec'];
+
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+
+describe('deletion inventory', () => {
+ test('every text-bearing column of a fresh schema is classified, and no entry names a missing table', async () => {
+ const rows = await engine.executeRaw<{ t: string; c: string }>(`SELECT c.table_name AS t, c.column_name AS c FROM information_schema.columns c
+ JOIN information_schema.tables t ON t.table_name=c.table_name AND t.table_schema=c.table_schema AND t.table_type='BASE TABLE'
+ WHERE c.table_schema='public' AND c.udt_name=ANY($1::text[]) ORDER BY 1,2`, [TEXT_BEARING]);
+ const missing = rows.filter(r => !DELETION_INVENTORY_BY_TABLE.get(r.t)?.columns.includes(r.c)).map(r => `${r.t}.${r.c}`);
+ expect(missing).toEqual([]);
+ const tables = new Set(rows.map(r => r.t));
+ expect(DELETION_INVENTORY.filter(e => !tables.has(e.table)).map(e => e.table)).toEqual([]);
+ });
+
+ test('entries are well-formed: probed stores name probe columns they list; new purge stores are classified', () => {
+ for (const entry of DELETION_INVENTORY) {
+ expect(['swept', 'retained_inactive', 'out_of_scope']).toContain(entry.class);
+ if (entry.class === 'out_of_scope') expect(['probed_reported', 'text_free_ledger', 'secret_material', 'no_memory_text']).toContain(entry.reason);
+ if (entry.reason === 'probed_reported') {
+ expect(entry.probe?.length).toBeGreaterThan(0);
+ for (const col of entry.probe!) expect(entry.columns).toContain(col);
+ }
+ }
+ for (const table of ['fact_purges', 'take_purges', 'page_purges', 'derivation_inputs', 'needs_rederive']) {
+ expect(DELETION_INVENTORY_BY_TABLE.get(table)?.reason).toBe('text_free_ledger');
+ }
+ for (const table of ['facts', 'takes', 'pages', 'content_chunks', 'page_versions', 'persistence_requests']) {
+ expect(DELETION_INVENTORY_BY_TABLE.get(table)?.class).toBe('swept');
+ }
+ });
+
+ test('AGENTS.md still says never promise physical erasure', () => {
+ expect(readFileSync(new URL('../AGENTS.md', import.meta.url), 'utf8')).toMatch(/never promise physical erasure/i);
+ });
+});
diff --git a/test/forget-purge-cli.test.ts b/test/forget-purge-cli.test.ts
new file mode 100644
index 0000000000..46e4c26511
--- /dev/null
+++ b/test/forget-purge-cli.test.ts
@@ -0,0 +1,88 @@
+/**
+ * `gbrain forget <id> --purge` (#5575 DX-11, DX-12): on a terminal the CLI
+ * prints the dry-run receipt (residuals first) and purges only after the user
+ * types the fact's token; without a terminal it needs --yes and --request-id;
+ * --match lists candidates and never purges; --status reports completion.
+ * In-process against real PGLite (no config file, so no resident owner).
+ */
+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 { importFromContent } from '../src/core/import-file.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { runForgetPurge } from '../src/commands/forget-purge.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const CLAIM = 'Garage code is 9921';
+const home = mkdtempSync(join(tmpdir(), 'gbrain-forget-purge-cli-'));
+let engine: PGLiteEngine;
+let factId: number;
+
+async function capture(fn: () => Promise<void>): Promise<{ out: string; err: string; code: number }> {
+ const out: string[] = [], err: string[] = [];
+ const o = process.stdout.write.bind(process.stdout), e = process.stderr.write.bind(process.stderr);
+ process.stdout.write = ((chunk: string) => { out.push(String(chunk)); return true; }) as typeof process.stdout.write;
+ process.stderr.write = ((chunk: string) => { err.push(String(chunk)); return true; }) as typeof process.stderr.write;
+ _resetCliExitVerdictForTests();
+ try { await withEnv({ GBRAIN_HOME: home }, fn); } finally { process.stdout.write = o; process.stderr.write = e; }
+ return { out: out.join(''), err: err.join(''), code: currentExitCode() };
+}
+
+beforeAll(async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ await registerLocalWriter(engine, 'cli');
+}), 60_000);
+afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });
+beforeEach(async () => {
+ const slug = `people/${randomUUID().slice(0, 8)}-example`;
+ await importFromContent(engine, slug, `---\ntitle: X\ntype: person\n---\n# X\n\n<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+| 1 | ${CLAIM} | fact | 1.0 | world | medium | 2026-01-01 | | chat | |
+<!--- gbrain:facts:end -->\n`, { noEmbed: true, sourceId: 'default' });
+ await runExtractFacts(engine, { slugs: [slug] });
+ [{ id: factId }] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE entity_slug=$1', [slug]);
+ factId = Number(factId);
+});
+
+describe('gbrain forget --purge', () => {
+ test('terminal: prints residuals first, a wrong token cancels with exit 3, the right token purges', async () => {
+ const cancelled = await capture(() => runForgetPurge(engine, [String(factId), '--purge'], { interactive: () => true, readToken: async () => 'nope' }));
+ expect(cancelled.code).toBe(3);
+ expect(cancelled.out.indexOf('Residuals')).toBeLessThan(cancelled.out.indexOf('Live stores'));
+ expect(cancelled.out).not.toContain(CLAIM);
+ expect(await engine.executeRaw('SELECT 1 FROM facts WHERE id=$1', [factId])).toHaveLength(1);
+ let prompt = '';
+ const done = await capture(() => runForgetPurge(engine, [String(factId), '--purge', '--json'], { interactive: () => true,
+ readToken: async p => { prompt = p; return /Type ([0-9a-f]{8})/.exec(p)![1]!; } }));
+ expect(prompt).toContain(`purge fact ${factId}`);
+ expect([0, 10]).toContain(done.code);
+ expect(await engine.executeRaw('SELECT 1 FROM facts WHERE id=$1', [factId])).toHaveLength(0);
+ }, 60_000);
+
+ test('no terminal: refuses without --yes and --request-id (exit 3); with both it purges and --status reports it', async () => {
+ const refused = await capture(() => runForgetPurge(engine, [String(factId), '--purge', '--yes', '--json'], { interactive: () => false }));
+ expect(refused.code).toBe(3);
+ expect(await engine.executeRaw('SELECT 1 FROM facts WHERE id=$1', [factId])).toHaveLength(1);
+ const requestId = randomUUID();
+ const done = await capture(() => runForgetPurge(engine, [String(factId), '--purge', '--yes', '--request-id', requestId, '--json'], { interactive: () => false }));
+ const receipt = JSON.parse(done.out);
+ expect(receipt.request_id).toBe(requestId);
+ expect(['committed', 'complete']).toContain(receipt.completion);
+ const status = await capture(() => runForgetPurge(engine, ['--purge', '--status', '--request-id', requestId, '--json'], { interactive: () => false }));
+ expect(JSON.parse(status.out)).toMatchObject({ request_id: requestId, state: 'committed', fingerprint_probe: { facts: 0, takes: 0 } });
+ }, 60_000);
+
+ test('--match lists candidate ids and never purges; --dry-run changes nothing', async () => {
+ const listed = await capture(() => runForgetPurge(engine, ['--purge', '--match', 'garage code', '--json'], { interactive: () => false }));
+ expect(JSON.parse(listed.out).candidates.map((c: { id: number }) => c.id)).toContain(factId);
+ const dry = await capture(() => runForgetPurge(engine, [String(factId), '--purge', '--dry-run'], { interactive: () => false }));
+ expect(dry.out).toContain('Purge dry run');
+ expect(await engine.executeRaw('SELECT 1 FROM facts WHERE id=$1', [factId])).toHaveLength(1);
+ }, 60_000);
+});
diff --git a/test/page-purge.test.ts b/test/page-purge.test.ts
new file mode 100644
index 0000000000..209ab34dd1
--- /dev/null
+++ b/test/page-purge.test.ts
@@ -0,0 +1,110 @@
+/**
+ * Page purge (#5575 CEO-4, CEO-8, ENG-19): `delete_page purge:true` sweeps the
+ * page's live stores, deletes its stored blobs after commit, and records a
+ * slug-free content tombstone. The same content is refused (typed
+ * purged_content) under any slug until `unpurge_page`; edited content imports.
+ * Real PGLite, local blob storage, no provider calls.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } 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 { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+let storageDir: string;
+const home = mkdtempSync(join(tmpdir(), 'gbrain-page-purge-'));
+const op = (name: string) => operations.find(o => o.name === name)!;
+const SLUG = 'notes/leaked-key';
+const CONTENT = `---\ntitle: Leaked key\ntype: note\n---\n# Leaked key\n\nThe key is AKIA-EXAMPLE-NOT-REAL.\n\n## Facts\n\n<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+| 1 | Deploy key lives in vault-a | fact | 1.0 | world | medium | 2026-01-01 | | chat | |
+<!--- gbrain:facts:end -->\n`;
+
+function context(remote = false): OperationContext {
+ return { engine, config: { engine: 'pglite', embedding_disabled: true, storage: { backend: 'local', bucket: 'b', localPath: storageDir } } as never,
+ logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote, sourceId: 'default' };
+}
+const call = (name: string, params: Record<string, unknown>, remote = false) =>
+ withEnv({ GBRAIN_HOME: home }, () => op(name).handler(context(remote), params)) as Promise<Record<string, any>>;
+async function purgePage(slug = SLUG) {
+ 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 errorText(p: Promise<unknown>): Promise<string> {
+ try { await p; return 'ok'; } catch (e) { return e instanceof OperationError ? `${e.canonical ?? e.code}: ${e.message}` : String((e as Error).message); }
+}
+
+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();
+ storageDir = mkdtempSync(join(home, 'storage-'));
+});
+
+describe('page purge', () => {
+ test('sweeps every page-keyed store, deletes the blob after commit and reports counts', async () => {
+ await importFromContent(engine, SLUG, CONTENT, { noEmbed: true, sourceId: 'default' });
+ await runExtractFacts(engine, { slugs: [SLUG] });
+ const [page] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug=$1', [SLUG]);
+ mkdirSync(join(storageDir, 'notes'), { recursive: true });
+ writeFileSync(join(storageDir, 'notes/leaked.png'), 'blob-bytes');
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {
+ await tx.createVersion(SLUG, { sourceId: 'default' });
+ await tx.executeRaw(`INSERT INTO takes(page_id,row_num,claim,kind,holder) VALUES ($1,1,'A take on the key','take','brain')`, [page.id]);
+ }, TEST_WRITE_ATTRIBUTION));
+ await engine.executeRaw(`INSERT INTO take_proposals(source_id,page_slug,content_hash,prompt_version,wave_version,proposal_run_id,claim_text,kind,holder,weight,status,model_id)
+ VALUES ('default',$1,'h','p','w','run-1','Proposed take','take','brain',0.5,'pending','m')`, [SLUG]);
+ await engine.executeRaw(`INSERT INTO open_loops(source_id,dedup_key,loop_type,summary,page_slug,status,detector,confidence)
+ VALUES ('default','k1','commitment_owed_by_me','Rotate the key',$1,'open','manual',0.9)`, [SLUG]);
+ await engine.executeRaw(`INSERT INTO core_edit_notices(source_id,slug,base_text,actor) VALUES ('default',$1,'old body','agent')`, [SLUG]);
+ await engine.executeRaw(`INSERT INTO files(source_id,page_slug,page_id,filename,storage_path,mime_type,size_bytes,content_hash)
+ VALUES ('default',$1,$2,'leaked.png','notes/leaked.png','image/png',10,'fh')`, [SLUG, page.id]);
+ const result = await purgePage();
+ expect(result.status).toBe('purged');
+ expect(result.purge.removed).toMatchObject({ facts: 1, take_proposals: 1, open_loops: 1, core_edit_notices: 1, files: 1, takes: 1, page_versions: 1 });
+ expect(result.purge.blobs_remaining).toEqual([]);
+ expect(existsSync(join(storageDir, 'notes/leaked.png'))).toBe(false);
+ expect(String(result.residuals)).toContain('git history');
+ for (const sql of ['SELECT 1 FROM pages WHERE slug=$1', 'SELECT 1 FROM facts WHERE source_markdown_slug=$1', 'SELECT 1 FROM take_proposals WHERE page_slug=$1',
+ 'SELECT 1 FROM open_loops WHERE page_slug=$1', 'SELECT 1 FROM core_edit_notices WHERE slug=$1', 'SELECT 1 FROM files WHERE page_slug=$1']) {
+ expect(await engine.executeRaw(sql, [SLUG])).toHaveLength(0);
+ }
+ expect(await engine.executeRaw(`SELECT 1 FROM content_chunks WHERE strpos(chunk_text,'AKIA-EXAMPLE')>0`)).toHaveLength(0);
+ const [tombstone] = await engine.executeRaw<{ slug: string; content_hash: string }>('SELECT slug,content_hash FROM page_purges');
+ expect(tombstone.slug).toBe(SLUG);
+ expect(await engine.executeRaw(`SELECT 1 FROM fact_purges WHERE reason='page purge'`)).toHaveLength(1);
+ }, 60_000);
+
+ test('the tombstone refuses the same content under any slug until unpurge; edited content imports', async () => {
+ await importFromContent(engine, SLUG, CONTENT, { noEmbed: true, sourceId: 'default' });
+ await runExtractFacts(engine, { slugs: [SLUG] });
+ await purgePage();
+ expect(await errorText(importFromContent(engine, SLUG, CONTENT, { noEmbed: true, sourceId: 'default' }))).toContain('purged_content');
+ expect(await errorText(importFromContent(engine, 'notes/renamed-copy', CONTENT, { noEmbed: true, sourceId: 'default' }))).toContain('purged_content');
+ expect(await errorText(call('put_page', { slug: SLUG, content: CONTENT, request_id: randomUUID() }))).toContain('purged_content');
+ await importFromContent(engine, 'notes/edited', CONTENT.replace('AKIA-EXAMPLE-NOT-REAL', 'rotated'), { noEmbed: true, sourceId: 'default' });
+ expect(await engine.executeRaw('SELECT 1 FROM pages WHERE slug=$1', ['notes/edited'])).toHaveLength(1);
+ const listed = await call('list_page_purges', {});
+ expect(listed.purges.length).toBeGreaterThanOrEqual(1);
+ expect(listed.purges.every((p: { slug: string }) => p.slug === SLUG)).toBe(true);
+ expect(JSON.stringify(listed)).not.toContain('AKIA');
+ expect(await errorText(call('unpurge_page', { slug: SLUG }, true))).toContain('trusted_local_only');
+ const cleared = await call('unpurge_page', { slug: SLUG });
+ expect(cleared).toMatchObject({ cleared: listed.purges.length, fact_tombstones_cleared: 1 });
+ await importFromContent(engine, SLUG, CONTENT, { noEmbed: true, sourceId: 'default' });
+ await runExtractFacts(engine, { slugs: [SLUG] });
+ expect(await engine.executeRaw(`SELECT 1 FROM facts WHERE fact='Deploy key lives in vault-a'`)).toHaveLength(1);
+ }, 60_000);
+});