Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(write-gate): read-only exposure scan and owner dry-run script (#5575 CEO-25, ENG-17)

garrytan717949e4e5f6
diff --git a/scripts/trust-dry-run-scan.ts b/scripts/trust-dry-run-scan.ts
new file mode 100644
index 0000000000..ce3d65d200
--- /dev/null
+++ b/scripts/trust-dry-run-scan.ts
@@ -0,0 +1,100 @@
+#!/usr/bin/env bun
+/**
+ * #5575 owner-custody dry run (CEO-25 / ENG-17): what the write gate would
+ * flag or quarantine in an existing brain, by projected trust tier and reason
+ * family. Strictly read-only:
+ * - Postgres: every read runs inside one REPEATABLE READ READ ONLY
+ * transaction, so the server refuses any write; no migrations run.
+ * - PGLite: the data directory is copied to a temp dir first and only the
+ * copy is opened (opening a PGLite directory can write WAL files), then
+ * the copy is deleted.
+ * No receipts, holds, markers or config are written. The report has counts
+ * and pattern names only, never content, slugs or ids.
+ *
+ * Usage:
+ * bun scripts/trust-dry-run-scan.ts [--json] [--source <id>] [--limit <rows per table>]
+ * [--tables pages,facts,takes,timeline_entries] [--batch <n>] [--database-url <url>]
+ */
+import { cpSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { loadConfig, toEngineConfig } from '../src/core/config.ts';
+import { createEngine } from '../src/core/engine-factory.ts';
+import type { EngineConfig } from '../src/core/types.ts';
+import { scanWriteGateExposure, WRITE_GATE_SCAN_TABLES, type WriteGateScanReport, type WriteGateScanTable } from '../src/core/write-gate-scan.ts';
+
+function flag(args: string[], name: string): string | undefined {
+ const i = args.indexOf(name);
+ return i >= 0 ? args[i + 1] : undefined;
+}
+
+function pct(n: number, d: number): string {
+ return d ? `${((100 * n) / d).toFixed(2)}%` : '-';
+}
+
+export function renderReport(r: WriteGateScanReport): string {
+ const lines = [`write-gate dry run (detector v${r.detector_version}, external_mode=${r.config.externalMode}, agent_mode=${r.config.agentMode}${r.source_id ? `, source ${r.source_id}` : ''}); nothing was written.`];
+ for (const [table, t] of Object.entries(r.tables)) {
+ if (!t) continue;
+ lines.push('', `${table}: ${t.scanned} rows${t.truncated ? ' (limit reached)' : ''}`);
+ lines.push(' tier rows detector hits flag quarantine families');
+ for (const [tier, s] of Object.entries(t.by_tier)) {
+ if (!s.rows) continue;
+ const fam = Object.entries(s.families).filter(([, n]) => n).map(([f, n]) => `${f}=${n}`).join(' ');
+ lines.push(` ${tier.padEnd(20)} ${String(s.rows).padEnd(9)} ${`${s.detector_hits} (${pct(s.detector_hits, s.rows)})`.padEnd(15)} ${`${s.verdicts.flag}`.padEnd(9)} ${`${s.verdicts.quarantine}`.padEnd(11)} ${fam}`);
+ }
+ const top = Object.entries(t.patterns).sort((a, b) => b[1] - a[1]).slice(0, 8).map(([p, n]) => `${p}=${n}`).join(' ');
+ if (top) lines.push(` top patterns: ${top}`);
+ }
+ const tt = r.totals;
+ lines.push('', `total: ${tt.rows} rows; would flag ${tt.flagged} (${pct(tt.flagged, tt.rows)}), quarantine ${tt.quarantined} (${pct(tt.quarantined, tt.rows)}); detector hit rate if every row were agent-written ${pct(tt.detector_hits, tt.rows)}.`);
+ return lines.join('\n');
+}
+
+async function main(): Promise<number> {
+ const args = process.argv.slice(2);
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log('Usage: bun scripts/trust-dry-run-scan.ts [--json] [--source <id>] [--limit <rows per table>] [--tables pages,facts,takes,timeline_entries] [--batch <n>] [--database-url <url>]');
+ return 0;
+ }
+ const tables = (flag(args, '--tables')?.split(',').map(t => t.trim()).filter(Boolean) ?? [...WRITE_GATE_SCAN_TABLES]) as WriteGateScanTable[];
+ const unknown = tables.filter(t => !WRITE_GATE_SCAN_TABLES.includes(t));
+ if (unknown.length) { console.error(`Unknown table(s): ${unknown.join(', ')}. Choose from ${WRITE_GATE_SCAN_TABLES.join(', ')}.`); return 2; }
+ const limit = flag(args, '--limit');
+ const batch = flag(args, '--batch');
+ const url = flag(args, '--database-url');
+ const config = loadConfig();
+ let engineConfig: EngineConfig;
+ if (url) engineConfig = { engine: 'postgres', database_url: url };
+ else if (config) engineConfig = toEngineConfig(config);
+ else { console.error('No GBrain config found. Pass --database-url, or run on the brain host.'); return 1; }
+ let copyDir: string | null = null;
+ if ((engineConfig.engine ?? (engineConfig.database_url ? 'postgres' : 'pglite')) === 'pglite') {
+ if (!engineConfig.database_path) { console.error('PGLite brain has no database_path in its config.'); return 1; }
+ copyDir = mkdtempSync(join(tmpdir(), 'gbrain-trust-dry-run-'));
+ const target = join(copyDir, 'brain.pglite');
+ cpSync(engineConfig.database_path, target, { recursive: true });
+ rmSync(join(target, 'postmaster.pid'), { force: true });
+ engineConfig = { ...engineConfig, database_path: target };
+ process.stderr.write(`[trust-dry-run] PGLite: scanning a copy at ${target}; the original is not opened.\n`);
+ }
+ const engine = await createEngine(engineConfig);
+ try {
+ await engine.connect(engineConfig);
+ const report = await engine.transaction(async tx => {
+ await tx.executeRaw('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
+ return scanWriteGateExposure(tx, {
+ tables, ...(flag(args, '--source') ? { sourceId: flag(args, '--source') } : {}),
+ ...(limit ? { limitPerTable: Number(limit) } : {}), ...(batch ? { batchSize: Number(batch) } : {}),
+ onBatch: (table, n) => process.stderr.write(`[trust-dry-run] ${table}: ${n} rows\n`),
+ });
+ });
+ console.log(args.includes('--json') ? JSON.stringify(report, null, 2) : renderReport(report));
+ return 0;
+ } finally {
+ await engine.disconnect().catch(() => {});
+ if (copyDir) rmSync(copyDir, { recursive: true, force: true });
+ }
+}
+
+if (import.meta.main) process.exit(await main());
diff --git a/src/core/write-gate-scan.ts b/src/core/write-gate-scan.ts
new file mode 100644
index 0000000000..a9a5c6e1bb
--- /dev/null
+++ b/src/core/write-gate-scan.ts
@@ -0,0 +1,211 @@
+/**
+ * #5575 (CEO-25 / ENG-17) read-only write-gate exposure scan: how much
+ * existing memory the gate would flag or quarantine, by projected trust tier
+ * and reason family, before any default is set.
+ *
+ * Pure reads (keyset batches over pages, facts, takes and timeline entries);
+ * it writes nothing (no receipts, holds, config or markers). The caller runs
+ * it inside a READ ONLY transaction (`scripts/trust-dry-run-scan.ts`), so the
+ * database refuses any write. The report holds counts and pattern names only,
+ * never content, slugs or ids.
+ *
+ * Tiers are projected from the same deterministic signals the backfill uses
+ * (A8, CEO-17), never guessed: connector sources, webhook and web-clipper
+ * pages are `external_untrusted`; `mcp:*` / capture / transcript pages and
+ * agent-relayed or derived rows are `agent_written`; managed sync and import
+ * requests are `operator_curated`; the lowest signal wins, and a row with no
+ * signal is `unknown`.
+ */
+import type { BrainEngine } from './engine.ts';
+import {
+ assessFactForGate, assessPageForGate, assessTakeForGate, assessTimelineForGate, DEFAULT_WRITE_GATE_CONFIG,
+ WRITE_GATE_DETECTOR_VERSION, WRITE_GATE_TIERS, isWriteGateTier,
+ type WriteGateAssessment, type WriteGateConfig, type WriteGateTier, type WriteGateVerdict,
+} from './write-gate.ts';
+import { WRITE_GATE_REASON_FAMILIES, type WriteGateReasonFamily } from './write-gate-patterns.ts';
+
+export type WriteGateScanTable = 'pages' | 'facts' | 'takes' | 'timeline_entries';
+export const WRITE_GATE_SCAN_TABLES: readonly WriteGateScanTable[] = ['pages', 'facts', 'takes', 'timeline_entries'];
+
+export interface WriteGateScanTierStats {
+ rows: number;
+ /** Rows the detector matched, whatever the tier (the rate the gate would see if it ran there). */
+ detector_hits: number;
+ /** Verdicts under the scan's config at this tier (owner tiers are always `allow`). */
+ verdicts: Record<WriteGateVerdict, number>;
+ families: Record<WriteGateReasonFamily, number>;
+}
+
+export interface WriteGateScanTableReport {
+ scanned: number;
+ /** A per-table row limit stopped the scan early. */
+ truncated: boolean;
+ by_tier: Record<WriteGateTier, WriteGateScanTierStats>;
+ /** Detector hits per pattern name across all tiers. */
+ patterns: Record<string, number>;
+}
+
+export interface WriteGateScanReport {
+ schema_version: 1;
+ detector_version: number;
+ config: WriteGateConfig;
+ read_only: true;
+ source_id: string | null;
+ tables: Partial<Record<WriteGateScanTable, WriteGateScanTableReport>>;
+ totals: {
+ rows: number;
+ flagged: number;
+ quarantined: number;
+ rejected: number;
+ detector_hits: number;
+ /** detector_hits / rows across all tiers: the flag rate if every row were agent_written. */
+ hit_rate: number;
+ };
+}
+
+export interface WriteGateScanOptions {
+ sourceId?: string;
+ tables?: readonly WriteGateScanTable[];
+ /** Max rows per table (default: all). */
+ limitPerTable?: number;
+ batchSize?: number;
+ cfg?: WriteGateConfig;
+ onBatch?: (table: WriteGateScanTable, scanned: number) => void;
+}
+
+type Exec = Pick<BrainEngine, 'executeRaw'>;
+
+const TIER_RANK: Readonly<Record<WriteGateTier, number>> = {
+ user_confirmed: 5, operator_curated: 4, tool_observed: 3, agent_written: 2, unknown: 1, external_untrusted: 0,
+};
+
+/** Lowest of the present signals; `unknown` when none. */
+export function projectTier(signals: ReadonlyArray<string | null | undefined>): WriteGateTier {
+ const tiers = signals.filter(isWriteGateTier);
+ if (!tiers.length) return 'unknown';
+ return tiers.reduce((low, t) => TIER_RANK[t] < TIER_RANK[low] ? t : low);
+}
+
+/** Page-level signal on alias `pg` (with sources alias `src`): connector/webhook/clipper -> external, agent channels -> agent. */
+const PAGE_SIGNAL = (pg: string, src: string) => `CASE
+ WHEN ${src}.config->>'kind' IN ('google','github') OR ${pg}.source_kind = 'webhook' OR COALESCE(${pg}.frontmatter, '{}'::jsonb) ? 'source_url' THEN 'external_untrusted'
+ WHEN ${pg}.source_kind LIKE 'mcp:%' OR ${pg}.ingested_via LIKE 'mcp:%' OR ${pg}.source_kind = 'capture-cli'
+ OR ${pg}.frontmatter->>'capturedVia' IS NOT NULL OR COALESCE(${pg}.frontmatter, '{}'::jsonb) ? 'transcript_import' THEN 'agent_written'
+ END`;
+
+/** Request-level signal (CEO-17) on persistence_requests alias `pr`. */
+const REQUEST_SIGNAL = (pr: string) => `CASE
+ WHEN ${pr}.id IS NULL THEN NULL
+ WHEN ${pr}.intent->>'kind' LIKE 'connector_%' OR ${pr}.intent->>'kind' LIKE 'managed_connector_%' THEN 'external_untrusted'
+ WHEN ${pr}.authority->>'remote' = 'true' THEN 'agent_written'
+ WHEN ${pr}.intent->>'kind' LIKE 'managed_sync_%' OR ${pr}.intent->>'kind' IN ('managed_file_import','managed_file_repair','canonical_reconcile','managed_grandfather') THEN 'operator_curated'
+ WHEN ${pr}.operation IN ('put_page','capture','edit_page','remember','takes_add','takes_update','takes_supersede','add_timeline_entry','extract_facts','restore_page','revert_version') THEN 'agent_written'
+ END`;
+
+/** Fact provenance tags of agent writes and derivers (extraction, backstop, hooks): capped at agent_written. */
+const FACT_SOURCE_SIGNAL = `CASE WHEN f.source LIKE 'mcp:%' OR f.source LIKE 'hook:%' OR f.source LIKE 'sweep:%' OR f.source LIKE 'cli:%'
+ OR f.source IN ('sync:import','file_upload','code_import') THEN 'agent_written' END`;
+
+interface ScanRow { id: string; source_id: string; page_signal: string | null; request_signal: string | null; row_signal?: string | null }
+
+function emptyTier(): WriteGateScanTierStats {
+ return {
+ rows: 0, detector_hits: 0, verdicts: { allow: 0, flag: 0, quarantine: 0, reject: 0 },
+ families: Object.fromEntries(WRITE_GATE_REASON_FAMILIES.map(f => [f, 0])) as Record<WriteGateReasonFamily, number>,
+ };
+}
+
+function emptyTable(): WriteGateScanTableReport {
+ return { scanned: 0, truncated: false, by_tier: Object.fromEntries(WRITE_GATE_TIERS.map(t => [t, emptyTier()])) as Record<WriteGateTier, WriteGateScanTierStats>, patterns: {} };
+}
+
+interface TableSpec<R extends ScanRow> {
+ sql: (scoped: boolean) => string;
+ assess: (row: R, tier: WriteGateTier, cfg: WriteGateConfig) => WriteGateAssessment;
+}
+
+const SPECS: { [T in WriteGateScanTable]: TableSpec<ScanRow & Record<string, unknown>> } = {
+ pages: {
+ sql: scoped => `SELECT p.id::text AS id, p.source_id, p.title, p.compiled_truth, p.timeline, p.frontmatter,
+ ${PAGE_SIGNAL('p', 's')} AS page_signal, ${REQUEST_SIGNAL('pr')} AS request_signal
+ FROM pages p LEFT JOIN sources s ON s.id = p.source_id LEFT JOIN persistence_requests pr ON pr.id = p.revision_write_request_id
+ WHERE p.deleted_at IS NULL AND p.id > $1::bigint ${scoped ? 'AND p.source_id = $3' : ''} ORDER BY p.id LIMIT $2`,
+ assess: (r, tier, cfg) => assessPageForGate({
+ title: r.title as string | null, compiled_truth: String(r.compiled_truth ?? ''), timeline: r.timeline as string | null,
+ frontmatter: (typeof r.frontmatter === 'string' ? JSON.parse(r.frontmatter) : r.frontmatter) as Record<string, unknown> | null,
+ }, { tier }, cfg),
+ },
+ facts: {
+ sql: scoped => `SELECT f.id::text AS id, f.source_id, f.fact, f.context, f.value, f.source,
+ ${PAGE_SIGNAL('sp', 's')} AS page_signal, ${REQUEST_SIGNAL('pr')} AS request_signal, ${FACT_SOURCE_SIGNAL} AS row_signal
+ FROM facts f LEFT JOIN sources s ON s.id = f.source_id
+ LEFT JOIN pages sp ON sp.source_id = f.source_id AND sp.slug = f.source_markdown_slug
+ LEFT JOIN persistence_requests pr ON pr.id = f.write_request_id
+ WHERE f.expired_at IS NULL AND f.id > $1::bigint ${scoped ? 'AND f.source_id = $3' : ''} ORDER BY f.id LIMIT $2`,
+ assess: (r, tier, cfg) => assessFactForGate({ fact: String(r.fact ?? ''), context: r.context as string | null, value: r.value as string | null, source: r.source as string | null }, { tier }, cfg),
+ },
+ takes: {
+ sql: scoped => `SELECT t.id::text AS id, p.source_id, t.claim, t.source,
+ ${PAGE_SIGNAL('p', 's')} AS page_signal, ${REQUEST_SIGNAL('pr')} AS request_signal, 'agent_written' AS row_signal
+ FROM takes t JOIN pages p ON p.id = t.page_id LEFT JOIN sources s ON s.id = p.source_id
+ LEFT JOIN persistence_requests pr ON pr.id = t.write_request_id
+ WHERE t.active AND t.id > $1::bigint ${scoped ? 'AND p.source_id = $3' : ''} ORDER BY t.id LIMIT $2`,
+ assess: (r, tier, cfg) => assessTakeForGate({ claim: String(r.claim ?? ''), source: r.source as string | null }, { tier }, cfg),
+ },
+ timeline_entries: {
+ sql: scoped => `SELECT te.id::text AS id, p.source_id, te.summary, te.detail, te.source,
+ ${PAGE_SIGNAL('p', 's')} AS page_signal, ${REQUEST_SIGNAL('pr')} AS request_signal
+ FROM timeline_entries te JOIN pages p ON p.id = te.page_id LEFT JOIN sources s ON s.id = p.source_id
+ LEFT JOIN persistence_requests pr ON pr.id = te.write_request_id
+ WHERE te.id > $1::bigint ${scoped ? 'AND p.source_id = $3' : ''} ORDER BY te.id LIMIT $2`,
+ assess: (r, tier, cfg) => assessTimelineForGate({ summary: String(r.summary ?? ''), detail: r.detail as string | null, source: r.source as string | null }, { tier }, cfg),
+ },
+};
+
+/** Scan existing memory and report what the gate would do, writing nothing. Run it inside a READ ONLY transaction. */
+export async function scanWriteGateExposure(exec: Exec, opts: WriteGateScanOptions = {}): Promise<WriteGateScanReport> {
+ const cfg = opts.cfg ?? { ...DEFAULT_WRITE_GATE_CONFIG };
+ const batch = Math.max(1, Math.min(opts.batchSize ?? 500, 5000));
+ const report: WriteGateScanReport = {
+ schema_version: 1, detector_version: WRITE_GATE_DETECTOR_VERSION, config: cfg, read_only: true, source_id: opts.sourceId ?? null, tables: {},
+ totals: { rows: 0, flagged: 0, quarantined: 0, rejected: 0, detector_hits: 0, hit_rate: 0 },
+ };
+ for (const table of opts.tables ?? WRITE_GATE_SCAN_TABLES) {
+ const spec = SPECS[table];
+ const out = emptyTable();
+ report.tables[table] = out;
+ let cursor = '0';
+ for (;;) {
+ const room = opts.limitPerTable === undefined ? batch : Math.min(batch, opts.limitPerTable - out.scanned);
+ if (room <= 0) { out.truncated = true; break; }
+ const rows = await exec.executeRaw<ScanRow & Record<string, unknown>>(spec.sql(!!opts.sourceId),
+ [cursor, room, ...(opts.sourceId ? [opts.sourceId] : [])]);
+ for (const row of rows) {
+ const tier = projectTier([row.page_signal, row.request_signal, row.row_signal]);
+ const stats = out.by_tier[tier];
+ stats.rows++;
+ const asIfGated = spec.assess(row, 'agent_written', cfg.agentMode === 'off' ? { ...cfg, agentMode: 'flag' } : cfg);
+ if (asIfGated.hits.length) {
+ stats.detector_hits++;
+ for (const h of asIfGated.hits) out.patterns[h.pattern] = (out.patterns[h.pattern] ?? 0) + 1;
+ }
+ const actual = (tier === 'agent_written' || tier === 'unknown') && cfg.agentMode !== 'off' ? asIfGated : spec.assess(row, tier, cfg);
+ stats.verdicts[actual.verdict]++;
+ for (const f of actual.families) stats.families[f]++;
+ }
+ out.scanned += rows.length;
+ opts.onBatch?.(table, out.scanned);
+ if (rows.length < room) break;
+ cursor = rows[rows.length - 1]!.id;
+ }
+ for (const stats of Object.values(out.by_tier)) {
+ report.totals.rows += stats.rows;
+ report.totals.flagged += stats.verdicts.flag;
+ report.totals.quarantined += stats.verdicts.quarantine;
+ report.totals.rejected += stats.verdicts.reject;
+ report.totals.detector_hits += stats.detector_hits;
+ }
+ }
+ report.totals.hit_rate = report.totals.rows ? Number((report.totals.detector_hits / report.totals.rows).toFixed(4)) : 0;
+ return report;
+}