Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(purge): gbrain forget --purge CLI with typed-token confirmation, --match, --status; pages purges list / unpurge

garrytan10d3331e53a3
diff --git a/src/cli/subcommands.ts b/src/cli/subcommands.ts
index c999fd748f..d6b40c3ad7 100644
--- a/src/cli/subcommands.ts
+++ b/src/cli/subcommands.ts
@@ -17,7 +17,7 @@
* returns before startup side effects, strict argument checks and engine
* access.
*/
-export const PAGES_SUBCOMMANDS = ['purge-deleted'] as const;
+export const PAGES_SUBCOMMANDS = ['purge-deleted', 'purges', 'unpurge'] as const;
export const CACHE_SUBCOMMANDS = ['stats', 'clear', 'prune'] as const;
export const INTEGRITY_SUBCOMMANDS = ['check', 'auto', 'review', 'reset-progress'] as const;
export const HOOK_SUBCOMMANDS = ['session-start', 'user-prompt', 'stop', 'session-end', 'compact'] as const;
diff --git a/src/commands/forget-purge.ts b/src/commands/forget-purge.ts
new file mode 100644
index 0000000000..105d6a7362
--- /dev/null
+++ b/src/commands/forget-purge.ts
@@ -0,0 +1,143 @@
+/**
+ * `gbrain forget <id> --purge` (#5575 C1, DX-11, DX-12): the CLI front of the
+ * owner-only `purge_fact` operation.
+ *
+ * gbrain forget <id> --purge [--dry-run] [--yes --request-id <uuid>] [--reason <text>]
+ * [--all-subjects] [--vacuum] [--source <id>] [--json]
+ * gbrain forget --purge --match "<text>" # list candidate ids; never purges
+ * gbrain forget --purge --status --request-id <uuid> # completion of an earlier purge
+ *
+ * It always runs the dry run first. On a terminal it prints that receipt
+ * (residuals first) and asks the user to type the fact's 8-character token;
+ * without a terminal it needs --yes and an explicit --request-id. The token
+ * and the dry run's revision travel with the real call, so the owner (this
+ * process or the resident owner behind its 0600 socket) purges exactly what
+ * the user saw. Exit codes: 0 complete, 10 committed with effects still
+ * pending, 75 incomplete (retry with the same request id), 3 not confirmed.
+ */
+
+import type { BrainEngine } from '../core/engine.ts';
+import { loadConfig, isThinClient } from '../core/config.ts';
+import { opError } from '../core/ops/contract.ts';
+import { isInteractive, readLine } from '../core/interaction.ts';
+import { setCliExitVerdict } from '../core/cli-force-exit.ts';
+import { resolveSourceId } from '../core/source-resolver.ts';
+
+export const PURGE_FAMILY_HELP = `Purge family (remove content from live stores; never physical erasure):
+ gbrain forget <id> --purge purge one fact's claim (dry-run receipt, then a typed token)
+ gbrain delete <slug> --purge purge a page and its derived rows, with a page tombstone
+ gbrain pages purge-deleted hard-delete pages soft-deleted more than 72h ago
+ gbrain sources purge <id> remove a whole source
+ gbrain pages purges list list page purge tombstones
+ gbrain pages unpurge <slug> clear a page tombstone so the content can be imported again
+`;
+
+const USAGE = `Usage: gbrain forget <fact-id> --purge [--dry-run] [--yes --request-id <uuid>] [--reason <text>] [--all-subjects] [--vacuum] [--source <id>] [--json]
+ gbrain forget --purge --match "<text>"
+ gbrain forget --purge --status --request-id <uuid>
+
+${PURGE_FAMILY_HELP}`;
+
+function flagValue(args: readonly string[], name: string): string | undefined {
+ const i = args.findIndex(a => a === name || a.startsWith(`${name}=`));
+ if (i < 0) return undefined;
+ return args[i].startsWith(`${name}=`) ? args[i].slice(name.length + 1) : args[i + 1];
+}
+
+type Invoke = (params: Record<string, unknown>) => Promise<Record<string, unknown>>;
+
+/** Run purge_fact on this host: through the resident owner when one holds the brain, else in-process as the trusted CLI. */
+function invoker(engine: BrainEngine | (() => Promise<BrainEngine>), source: string | null): Invoke {
+ return async params => {
+ const cfg = loadConfig();
+ const { maybeDelegateLocalOperation } = await import('../core/persistence/local-client.ts');
+ const { getCliOptions } = await import('../core/cli-options.ts');
+ const cli = getCliOptions();
+ const delegated = await maybeDelegateLocalOperation('purge_fact', params, cfg, { brain: cli.brain, source, timeoutMs: cli.timeoutMs ?? undefined });
+ if (delegated.handled) return delegated.result as Record<string, unknown>;
+ const connected = typeof engine === 'function' ? await engine() : engine;
+ const sourceId = await resolveSourceId(connected, source);
+ const { operations } = await import('../core/operations.ts');
+ const op = operations.find(o => o.name === 'purge_fact')!;
+ return await op.handler({ engine: connected, config: cfg ?? { engine: 'pglite' }, remote: false, dryRun: false, sourceId,
+ logger: { info: console.log, warn: console.warn, error: console.error } }, params) as Record<string, unknown>;
+ };
+}
+
+type Report = { store: string; status: string; removed?: number; remaining?: number; reason?: string; detail?: string };
+
+/** Human receipt: residuals first, then each swept store. Never prints claim text. */
+export function renderPurgeReceipt(r: Record<string, unknown>): string {
+ const lines: string[] = [];
+ lines.push(`${r.dry_run ? 'Purge dry run' : 'Purge'} for fact ${r.fact_id} (hash ${r.hash8}, subject ${r.subject}, ${r.visibility})`);
+ if (typeof r.summary === 'string') lines.push(r.summary);
+ lines.push('', 'Residuals (not removed by purge):');
+ for (const s of (r.residuals as Report[] | undefined) ?? []) {
+ lines.push(` - ${s.store}: ${s.status}${s.reason ? ` (${s.reason})` : ''}${s.remaining ? `, ${s.remaining} found` : ''}${s.detail ? ` — ${s.detail}` : ''}`);
+ }
+ lines.push('', `Live stores${r.dry_run ? ' (would remove)' : ''}:`);
+ for (const s of (r.stores as Report[] | undefined) ?? []) {
+ if (s.status === 'not_present') continue;
+ lines.push(` - ${s.store}: ${s.status}${s.removed !== undefined ? `, ${s.removed}` : ''}${s.remaining ? `, ${s.remaining} remaining` : ''}${s.reason ? ` (${s.reason})` : ''}`);
+ }
+ if (typeof r.completion === 'string') lines.push('', `Completion: ${r.completion}${r.request_id ? ` (request ${r.request_id})` : ''}`);
+ for (const n of (r.next as string[] | undefined) ?? []) lines.push(`Next: ${n}`);
+ return lines.join('\n') + '\n';
+}
+
+export async function runForgetPurge(engine: BrainEngine | (() => Promise<BrainEngine>), args: string[]): Promise<void> {
+ const json = args.includes('--json');
+ const { reportPersistenceCliError } = await import('./persistence-delegate.ts');
+ const { parseWriteRequestId } = await import('../core/persistence/preconditions.ts');
+ const { purgeHostOnly } = await import('../core/facts/purge.ts');
+ const out = (value: Record<string, unknown>, human: string) => process.stdout.write(json ? `${JSON.stringify(value, null, 2)}\n` : human);
+ try {
+ if (args.includes('--help') || args.includes('-h')) { process.stdout.write(USAGE); return; }
+ const idArg = args.find(a => /^\d+$/.test(a));
+ const cfg = loadConfig();
+ if (isThinClient(cfg)) throw purgeHostOnly(idArg);
+ const requestId = parseWriteRequestId(flagValue(args, '--request-id'));
+ const invoke = invoker(engine, flagValue(args, '--source') ?? null);
+ if (args.includes('--status')) {
+ if (!requestId) throw opError('invalid_params', '--status needs --request-id.', 'Pass the request id the purge printed.');
+ const status = await invoke({ status: true, request_id: requestId });
+ out(status, `Purge ${requestId}: ${status.completion} (${status.state})\n${((status.effects as Array<{ kind: string; state: string }>) ?? []).map(e => ` effect ${e.kind}: ${e.state}`).join('\n')}\n`);
+ setCliExitVerdict(Number(status.exit_code ?? 0));
+ return;
+ }
+ const match = flagValue(args, '--match');
+ if (match !== undefined) {
+ const found = await invoke({ match });
+ const rows = (found.candidates as Array<{ id: number; entity_slug: string | null; visibility: string; expired: boolean; fact: string }>) ?? [];
+ out(found, rows.length ? `${rows.map(c => ` #${c.id} ${c.entity_slug ?? '(no entity)'} [${c.visibility}${c.expired ? ', expired' : ''}] ${c.fact}`).join('\n')}\nPick one id: gbrain forget <id> --purge\n` : 'No fact in this source contains that text.\n');
+ return;
+ }
+ if (!idArg) { process.stderr.write(USAGE); setCliExitVerdict(1); return; }
+ const reason = flagValue(args, '--reason');
+ const base = { id: Number(idArg), ...(reason !== undefined ? { reason } : {}), ...(args.includes('--all-subjects') ? { all_subjects: true } : {}) };
+ 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')) {
+ 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) {
+ process.stderr.write('Not purged.\n');
+ setCliExitVerdict(3);
+ return;
+ }
+ } else if (!args.includes('--yes') || !requestId) {
+ throw opError('confirmation_required', 'A purge without a terminal needs --yes and --request-id.',
+ `Show the user the dry run (gbrain forget ${idArg} --purge --dry-run), then, with their agreement, run gbrain forget ${idArg} --purge --yes --request-id <new uuid>. Reuse that request id to retry.`,
+ { fix: { argv: ['gbrain', 'forget', idArg, '--purge', '--dry-run', '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Prints what the purge would remove, residuals first, without changing anything.' } });
+ }
+ const done = await invoke({ ...base, confirm: token, expected_revision: dry.expected_revision, request_id: requestId ?? dry.request_id,
+ ...(args.includes('--vacuum') ? { vacuum: true } : {}) });
+ out(done, renderPurgeReceipt(done));
+ setCliExitVerdict(Number(done.exit_code ?? 0));
+ } catch (error) {
+ if (await reportPersistenceCliError(error, json)) return;
+ throw error;
+ }
+}
diff --git a/src/commands/pages-purges.ts b/src/commands/pages-purges.ts
new file mode 100644
index 0000000000..f59eced072
--- /dev/null
+++ b/src/commands/pages-purges.ts
@@ -0,0 +1,39 @@
+/**
+ * `gbrain pages purges list` and `gbrain pages unpurge <slug>` (#5575 CEO-8,
+ * DX-11): the owner's view of page purge tombstones. Both run the owner-only
+ * operations as the trusted local CLI.
+ */
+
+import type { BrainEngine } from '../core/engine.ts';
+import { loadConfig } from '../core/config.ts';
+import { resolveSourceId } from '../core/source-resolver.ts';
+import { PURGE_FAMILY_HELP } from './forget-purge.ts';
+
+function flagValue(args: readonly string[], name: string): string | undefined {
+ const i = args.findIndex(a => a === name || a.startsWith(`${name}=`));
+ if (i < 0) return undefined;
+ return args[i].startsWith(`${name}=`) ? args[i].slice(name.length + 1) : args[i + 1];
+}
+
+export async function runPagePurges(engine: BrainEngine, sub: 'purges' | 'unpurge', args: string[]): Promise<void> {
+ const json = args.includes('--json');
+ const { operations } = await import('../core/operations.ts');
+ const explicitSource = flagValue(args, '--source');
+ const sourceId = await resolveSourceId(engine, explicitSource ?? null);
+ const ctx = { engine, config: loadConfig() ?? { engine: engine.kind }, remote: false as const, dryRun: false, sourceId,
+ logger: { info: console.log, warn: console.warn, error: console.error } };
+ if (sub === 'purges') {
+ if (args[0] !== 'list') { process.stdout.write(`Usage: gbrain pages purges list [--source <id>] [--json]\n\n${PURGE_FAMILY_HELP}`); return; }
+ const result = await operations.find(o => o.name === 'list_page_purges')!.handler(ctx, explicitSource ? { source_id: sourceId } : {}) as
+ { purges: Array<{ source_id: string; slug: string; content_hash8: string; request_id: string | null; purged_at: string }>; next: string };
+ if (json) { console.log(JSON.stringify(result, null, 2)); return; }
+ for (const p of result.purges) console.log(`${p.source_id}/${p.slug} hash ${p.content_hash8} purged ${p.purged_at}${p.request_id ? ` request ${p.request_id}` : ''}`);
+ console.log(result.next);
+ return;
+ }
+ const slug = args.find(a => !a.startsWith('--') && a !== explicitSource);
+ if (!slug) { process.stdout.write(`Usage: gbrain pages unpurge <slug> [--source <id>] [--json]\n\n${PURGE_FAMILY_HELP}`); return; }
+ const result = await operations.find(o => o.name === 'unpurge_page')!.handler(ctx, { slug, source_id: sourceId }) as Record<string, unknown>;
+ if (json) console.log(JSON.stringify(result, null, 2));
+ else console.log(`Cleared ${result.cleared} page tombstone(s) for ${slug}. ${result.next}`);
+}
diff --git a/src/commands/pages.ts b/src/commands/pages.ts
index c8c10fdd62..8b94e43e5b 100644
--- a/src/commands/pages.ts
+++ b/src/commands/pages.ts
@@ -90,6 +90,11 @@ export function printUsage(): void {
console.log(`gbrain pages — page-level operator commands (v0.26.5)
Subcommands:
+ purges list [--source <id>] [--json]
+ List page purge tombstones (slug, hash, request, time).
+ unpurge <slug> [--source <id>] [--json]
+ Clear a page's purge tombstones so its old content can be
+ imported again. Restores nothing.
purge-deleted [--older-than HOURS|Nh|Nd] [--dry-run] [--json] [--yes]
Hard-delete soft-deleted pages older than the cutoff
(default 72h) in every source of the brain (per-source
@@ -112,6 +117,7 @@ export async function runPages(engine: BrainEngine, args: string[]): Promise<voi
const sub = args[0] as (typeof PAGES_SUBCOMMANDS)[number] | undefined;
switch (sub) {
case 'purge-deleted': return runPurgeDeleted(engine, args.slice(1));
+ case 'purges': case 'unpurge': return (await import('./pages-purges.ts')).runPagePurges(engine, sub, args.slice(1));
case undefined:
printUsage();
return;
diff --git a/src/commands/recall.ts b/src/commands/recall.ts
index 054abd17e2..2e0202757e 100644
--- a/src/commands/recall.ts
+++ b/src/commands/recall.ts
@@ -14,7 +14,8 @@
* gbrain recall --as-context # prompt-injection-ready markdown
* gbrain recall --json # structured output
*
- * gbrain forget <fact-id> # shorthand for expireFact
+ * gbrain forget <fact-id> # durable withdrawal (forget_fact / forget verb)
+ * gbrain forget <fact-id> --purge # owner-only purge (src/commands/forget-purge.ts)
*
* v0.32 additions (this file):
* --since-last-run # read+advance ~/.gbrain/recall-cursors/<src>.json
@@ -826,6 +827,7 @@ function factRowToJson(r: FactRow): Record<string, unknown> {
}
export async function runForget(engine: BrainEngine | (() => Promise<BrainEngine>), args: string[]): Promise<void> {
+ if (args.includes('--purge')) return (await import('./forget-purge.ts')).runForgetPurge(engine, args);
const idArg = args.find(a => /^\d+$/.test(a));
if (!idArg) {
process.stderr.write('Usage: gbrain forget <fact-id> [--reason <text>] [--source <id>] [--request-id <uuid>] [--json]\n');