Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(pages): the purge_deleted_pages op asks first too; no consent-free side door to the D6 purge (#6114)
garrytanfcdc54471824
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex e9a68d18cb..3a2a9efedb 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -39,7 +39,7 @@ src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap insrc/core/config.ts 1920 ratchet +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rowssrc/core/bootstrap/harness.ts 2610 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option-src/core/ops/pages.ts 672 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param+src/core/ops/pages.ts 673 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts)src/core/search/mode.ts 1594 ratchet +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part)src/commands/eval-longmemeval.ts 1519 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts)src/commands/doctor/checks/extraction-sync.ts 1511 ratchet new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import)diff --git a/src/commands/pages.ts b/src/commands/pages.tsindex fc7b9becf2..c8c10fdd62 100644--- a/src/commands/pages.ts+++ b/src/commands/pages.ts@@ -7,7 +7,7 @@* page_links, chunk_relations via existing FKs.*/import type { BrainEngine } from '../core/engine.ts';-import { purgeDeletedPagesCoordinated } from '../core/persistence/purge-deleted.ts';+import { purgeConsentRequest, purgeDeletedPagesCoordinated } from '../core/persistence/purge-deleted.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';import { consentGate } from '../core/consent-cli.ts';import { strictArgsRefusal } from '../cli/strict-args.ts';@@ -66,16 +66,7 @@ async function runPurgeDeleted(engine: BrainEngine, args: string[]): Promise<voielse console.log(`No pages to purge (older than ${olderThanHours}h).`);return;}- const authorized = await consentGate({- command: 'pages purge-deleted', effects: ['destructive'], actor: 'agent',- what: `Permanently purge ${preview.count} soft-deleted page(s)`,- why: 'A hard purge removes soft-deleted pages, their chunks and links, from every source of this brain.',- risk: 'Purged pages cannot be restored with `gbrain restore`.',- user_message: `Permanently delete ${preview.count} page(s) soft-deleted more than ${olderThanHours}h ago, across every source in this brain? They cannot be restored afterwards.`,- argv: ['gbrain', 'pages', 'purge-deleted', '--older-than', `${olderThanHours}h`, ...(json ? ['--json'] : []), '--yes'],- preview_argv: ['gbrain', 'pages', 'purge-deleted', '--older-than', `${olderThanHours}h`, '--dry-run', '--json'],- args,- }, { json });+ const authorized = await consentGate(purgeConsentRequest(preview.count, olderThanHours, json, args), { json });if (!authorized) return;const result = await purgeDeletedPagesCoordinated(engine, olderThanHours);diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 98c10c81ee..66b0d20eb0 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -261,7 +261,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.100.0', text: '`gbrain doctor` has a new `fence_integrity` check: it counts malformed facts and takes fences still waiting (held files, stored pages, unsynced checkout files) by the tier that would fix them, and warns when a source had 20 or more fences normalized in 7 days. Each doctor run scans stored pages and source checkouts for up to 10 seconds (`GBRAIN_DOCTOR_FENCE_TIMEOUT_MS`) and resumes where it stopped; until a scan finishes the check reports partial instead of ok. New settings `fences.repair.max_usd_per_page` (0.05) and `fences.repair.max_usd_per_day` (1.00) cap model fence repair.' },{ since: '0.60.102.0', text: `Malformed facts and takes fences are now repaired automatically: the maintenance run repairs held files and stored pages on the owner host, and its first run after upgrading repairs every malformed fence it finds in each source, rewriting and committing those files (\`gbrain doctor --only fence_integrity\` counts them; \`gbrain repair fences\` previews the plan). A fence only a rewrite can realign sends just its header and those rows, never the rest of the page, to the repair model, within $0.30 per page and $1.00 per day (\`fences.repair.max_usd_per_page\`, \`fences.repair.max_usd_per_day\`); every rewrite passes validation gates before it is written. With \`models.fence_repair\` unset, the repair model is the first model the fence-repair eval measured as accurate enough that has a provider key on the brain host (\`gbrain models\` names it); with none, model repair stays off until the user sets \`models.fence_repair\`. ${FENCE_REPAIR_MEASURED} \`gbrain config set fences.repair.llm false\` keeps fence rows away from the model; \`gbrain config set fences.repair.enabled false\` pauses automatic repair. On a managed source each repaired file is committed, so \`git revert\` undoes it (page history keeps the earlier version); turning these settings off stops future repairs and does not undo past ones.` },{ since: '0.60.103.0', text: '`gbrain pages purge-deleted`, `cache clear|prune`, `schema use|downgrade|init|remove-*`, `integrity auto|reset-progress` and `search modes --reset` refuse an argument they would ignore (exit 2), and `--help` never runs them; preview with `gbrain pages purge-deleted --dry-run --json`.' },- { since: '0.60.103.0', text: '`gbrain pages purge-deleted` asks first: without a terminal it exits 3 with an ask_user payload naming the `--yes` command.' },+ { since: '0.60.103.0', text: '`gbrain pages purge-deleted` asks first: without a terminal it exits 3 with an ask_user payload naming the `--yes` command. `gbrain call purge_deleted_pages` asks the same way; the top-level `gbrain purge-deleted` is gone.' },{ since: '0.60.103.0', text: '`gbrain apply-migrations` exits 1 (`migrations_pending`) when it leaves the schema behind; run `gbrain apply-migrations --yes`, then `gbrain doctor --json` if that fails.' },{ since: '0.60.103.0', text: 'Remote put_page and put_pages content with no Timeline section is refused (`timeline_rows_would_be_removed`) when it would delete dated rows; keep the section or pass `drop_timeline: true`.' },{ since: '0.60.103.0', text: '`gbrain schema active --json` exits nonzero on `unknown_source` or `database_error`; check `gbrain sources list --json`.' },diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 49d8960b9c..d3d0d59985 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -429,20 +429,21 @@ const purge_deleted_pages: Operation = {name: 'purge_deleted_pages',idempotent: false,outputRedaction: 'no_stored_text',- description: 'Admin-only. Hard-deletes pages whose deleted_at is older than older_than_hours (default 72). Cascades through content_chunks, page_links, chunk_relations. Local CLI only (not exposed over HTTP MCP). Manual escape hatch alongside the autopilot purge phase.',+ description: 'Admin-only. Hard-deletes pages whose deleted_at is older than older_than_hours (default 72), in every source. Cascades through content_chunks, page_links, chunk_relations. Trusted local CLI only; the command is `gbrain pages purge-deleted`, which asks first (yes: true is the consent). Manual escape hatch alongside the autopilot purge phase.',params: {older_than_hours: { type: 'number', description: 'Age cutoff in hours. Default 72.' },+ yes: { type: 'boolean', description: 'Consent to the irreversible brain-wide purge. Ask the user first.' },},mutating: true,scope: 'admin',- localOnly: true,+ localOnly: true, cliOnly: { argv: ['gbrain', 'pages', 'purge-deleted', '--dry-run', '--json'] },handler: async (ctx, p) => {const olderThanHours = (p.older_than_hours as number | undefined) ?? 72;if (ctx.dryRun) return { dry_run: true, action: 'purge_deleted_pages', older_than_hours: olderThanHours };- const result = await (await import('../persistence/purge-deleted.ts')).purgeDeletedPagesCoordinated(ctx.engine, olderThanHours);- return { status: result.failed ? 'partial' : 'purged', count: result.count, slugs: result.slugs, ...(result.blocked.length ? { blocked: result.blocked } : {}) };+ if (ctx.remote !== false) throw (await import('./callable.ts')).cliOnlyRefusal(purge_deleted_pages);+ return (await import('../persistence/purge-deleted.ts')).consentedPurgeDeletedPages(ctx.engine, olderThanHours, p.yes === true);},- cliHints: { name: 'purge-deleted' },+ cliHints: { name: 'purge-deleted', hidden: true },};const LIST_PAGES_SORT_VALUES = ['updated_desc', 'updated_asc', 'created_desc', 'slug'] as const;diff --git a/src/core/persistence/purge-deleted.ts b/src/core/persistence/purge-deleted.tsindex cd4791c27d..37f898e926 100644--- a/src/core/persistence/purge-deleted.ts+++ b/src/core/persistence/purge-deleted.ts@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../engine.ts';import { loadConfig } from '../config.ts';import type { OperationContext } from '../ops/contract.ts';+import { requireConsent, type ConsentRequest } from '../consent.ts';import { managedPersistenceEnabled } from './ownership.ts';import { submitPageMutation } from './page-mutations.ts';@@ -21,6 +22,35 @@ export interface DeletedPagePurge {error?: { class: string; code: string; message: string };}+/**+ * D6 (#6114): the one consent request for a manual hard purge, used by+ * `gbrain pages purge-deleted` and by the `purge_deleted_pages` op (reached+ * through `gbrain call`), so no manual entry point purges without it. The+ * approved command is always the gated `pages purge-deleted --yes`. The+ * autopilot purge phase calls `purgeDeletedPagesCoordinated` directly.+ */+export function purgeConsentRequest(count: number, olderThanHours: number, json: boolean, args: readonly string[]): ConsentRequest {+ return {+ command: 'pages purge-deleted', effects: ['destructive'], actor: 'agent',+ what: `Permanently purge ${count} soft-deleted page(s)`,+ why: 'A hard purge removes soft-deleted pages, their chunks and links, from every source of this brain.',+ risk: 'Purged pages cannot be restored with `gbrain restore`.',+ user_message: `Permanently delete ${count} page(s) soft-deleted more than ${olderThanHours}h ago, across every source in this brain? They cannot be restored afterwards.`,+ argv: ['gbrain', 'pages', 'purge-deleted', '--older-than', `${olderThanHours}h`, ...(json ? ['--json'] : []), '--yes'],+ preview_argv: ['gbrain', 'pages', 'purge-deleted', '--older-than', `${olderThanHours}h`, '--dry-run', '--json'],+ args,+ };+}++/** The `purge_deleted_pages` op (`gbrain call`): the D6 consent first (`yes` is `--yes`); an empty purge set needs none. */+export async function consentedPurgeDeletedPages(engine: BrainEngine, olderThanHours: number, yes: boolean) {+ const preview = await engine.purgeDeletedPages(olderThanHours, { dryRun: true });+ if (preview.count === 0) return { status: 'purged', count: 0, slugs: [] };+ await requireConsent(purgeConsentRequest(preview.count, olderThanHours, false, yes ? ['--yes'] : []));+ const result = await purgeDeletedPagesCoordinated(engine, olderThanHours);+ return { status: result.failed ? 'partial' : 'purged', count: result.count, slugs: result.slugs, ...(result.blocked.length ? { blocked: result.blocked } : {}) };+}+/*** #5405: hard-delete tombstones older than the recovery window. An unmanaged* brain keeps the engine's bulk delete. A managed brain refuses that bulkdiff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 466b32a50f..a3b4b1e27a 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 208391,- "stdoutSha256": "bc381e0b30d5f4929756f1f781edaf9e9f22ea2490ad437556693a2457fca542",+ "stdoutBytes": 208653,+ "stdoutSha256": "0df2586d0d82b9edbeb6bc242a687ab5ca01bdbccca68fe1dddc3c8eceaf79bb","toolNames": ["remember","entity",@@ -656,13 +656,14 @@"scope": "write"},{- "description": "Admin-only. Hard-deletes pages whose deleted_at is older than older_than_hours (default 72). Cascades through content_chunks, page_links, chunk_relations. Local CLI only (not exposed over HTTP MCP). Manual escape hatch alongside the autopilot purge phase.",+ "description": "Admin-only. Hard-deletes pages whose deleted_at is older than older_than_hours (default 72), in every source. Cascades through content_chunks, page_links, chunk_relations. Trusted local CLI only; the command is `gbrain pages purge-deleted`, which asks first (yes: true is the consent). Manual escape hatch alongside the autopilot purge phase.","idempotent": false,"local_only": true,"mutating": true,"name": "purge_deleted_pages","parameters": {- "older_than_hours": "number?"+ "older_than_hours": "number?",+ "yes": "boolean?"},"required_scopes": [],"schema": {@@ -670,6 +671,10 @@"older_than_hours": {"description": "Age cutoff in hours. Default 72.","type": "number"+ },+ "yes": {+ "description": "Consent to the irreversible brain-wide purge. Ask the user first.",+ "type": "boolean"}},"required": [],diff --git a/test/pages-purge-deleted-args.test.ts b/test/pages-purge-deleted-args.test.tsindex 35cb8c2705..29421d1a7e 100644--- a/test/pages-purge-deleted-args.test.ts+++ b/test/pages-purge-deleted-args.test.ts@@ -11,7 +11,9 @@import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { parsePurgeArgs, runPages } from '../src/commands/pages.ts';-import { OperationError } from '../src/core/ops/contract.ts';+import { OperationError, type OperationContext } from '../src/core/ops/contract.ts';+import { operations } from '../src/core/operations.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { withEnv } from './helpers/with-env.ts';@@ -140,3 +142,30 @@ describe('runPages', () => {expect(currentExitCode()).toBe(0);});});++describe('the purge_deleted_pages op is not a consent-free side door (security review)', () => {+ const op = operations.find(o => o.name === 'purge_deleted_pages')!;+ const local = (p: Record<string, unknown>) => withEnv({ GBRAIN_NON_INTERACTIVE: '1' }, () =>+ op.handler({ engine, config: { engine: 'pglite' }, remote: false, dryRun: false, sourceId: 'default',+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext, p));++ test('gbrain call without yes refuses with the D6 consent payload and purges nothing', async () => {+ const refused = await local({ older_than_hours: 72 }).then(() => null, (e: unknown) => e as OperationError);+ expect(refused?.code).toBe('confirmation_required');+ expect(await slugs()).toEqual(['notes/live', 'notes/old-deleted']);+ });++ test('yes: true is the consent, and an empty purge set needs none', async () => {+ expect(await local({ older_than_hours: 99999 })).toMatchObject({ count: 0 });+ expect(await local({ older_than_hours: 72, yes: true })).toMatchObject({ status: 'purged', count: 1 });+ expect(await slugs()).toEqual(['notes/live']);+ });++ test('no top-level `gbrain purge-deleted`, and the stdio MCP pipe gets the trusted-CLI refusal', async () => {+ expect(op.cliHints?.hidden).toBe(true);+ const res = await dispatchToolCall(engine, 'purge_deleted_pages', { older_than_hours: 72, yes: true }, { remote: true, transport: 'stdio', sourceId: 'default' });+ expect(res.isError).toBe(true);+ expect(JSON.stringify(res.content)).toContain('trusted_local_only');+ expect(await slugs()).toEqual(['notes/live', 'notes/old-deleted']);+ });+});