Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
gbrain core CLI, delivery sensitivity policy, pending remote-edit notices in the core block
garrytan0cd71b9f057a
diff --git a/src/cli/command-table.ts b/src/cli/command-table.tsindex 243b738041..ce411ee273 100644--- a/src/cli/command-table.ts+++ b/src/cli/command-table.ts@@ -362,6 +362,8 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp// CLI_ONLY: Open-loop engine CLI (engine-bound; trusted-local op dispatch).{ name: 'waiting', phase: 'post-connect', thinClient: 'none', selfHelp: true, routes_source: true, load: () => import('./commands/waiting.ts') },{ name: 'loops', phase: 'post-connect', thinClient: 'none', selfHelp: true, routes_source: true, load: () => import('./commands/loops.ts') },+ // selfHelp: core prints its own usage (commands/core.ts). Always-loaded core memory, docs/guides/core-memory.md.+ { name: 'core', phase: 'post-connect', thinClient: 'none', selfHelp: true, jsonSubcommands: { list: 'document', show: 'document', status: 'document', diff: 'document', suggest: 'document' }, load: () => import('./commands/core.ts') },// selfHelp: connectors ships its own printHelp (commands/connectors/index.ts) with the// per-subcommand usage; keep the generic short-circuit from hiding it.{ name: 'connectors', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/connectors.ts') },diff --git a/src/cli/commands/core.ts b/src/cli/commands/core.tsnew file mode 100644index 0000000000..e7b6891841--- /dev/null+++ b/src/cli/commands/core.ts@@ -0,0 +1,10 @@+/**+ * `gbrain core`: post-connect dispatch for always-loaded core memory; the+ * record lives in src/cli/command-table.ts.+ */+import type { BrainEngine } from '../../core/engine.ts';++export async function run(engine: BrainEngine, args: string[]): Promise<void> {+ const { runCore } = await import('../../commands/core.ts');+ await runCore(engine, args);+}diff --git a/src/commands/core.ts b/src/commands/core.tsnew file mode 100644index 0000000000..a2aea6591e--- /dev/null+++ b/src/commands/core.ts@@ -0,0 +1,254 @@+/**+ * `gbrain core`: manage always-loaded core memory (docs/guides/core-memory.md).+ *+ * gbrain core list [--source <id>] [--json] core pages, priority order, rendered size+ * gbrain core show [--source <id>] [--json] the exact block a session receives+ * gbrain core status [--json] usage against the budget, notices, settings+ * gbrain core add <slug> [--source <id>] [--priority <n>]+ * gbrain core remove <slug> [--source <id>]+ * gbrain core diff <slug> [--source <id>] what remote edits changed since the last ack+ * gbrain core ack <slug> [--source <id>] --revision <token>+ * gbrain core init [--source <id>] [--slug <slug>] starter profile page, marked core+ * gbrain core suggest [--source <id>] [--apply] [--json]+ *+ * Marking writes go through put_page as the trusted local owner, so the+ * write-path guard (budget, page cap) applies to them like any other write.+ */+import type { BrainEngine } from '../core/engine.ts';+import { handleToolCall } from '../mcp/server.ts';+import {+ CORE_DEFAULT_PRIORITY, CORE_DOCS, coreNoticeLine, coreUsage, isCoreFrontmatter, loadCoreBlock,+ pendingCoreNotices, readCoreSettings, renderCorePage,+} from '../core/core-memory.ts';+import { serializePageToMarkdown } from '../core/markdown.ts';+import { setCliExitVerdict } from '../core/cli-force-exit.ts';++const USAGE = `Usage: gbrain core <list|show|status|add|remove|diff|ack|init|suggest> [options]+ list [--source <id>] [--json]+ show [--source <id>] [--json]+ status [--json]+ add <slug> [--source <id>] [--priority <n>]+ remove <slug> [--source <id>]+ diff <slug> [--source <id>]+ ack <slug> [--source <id>] --revision <token>+ init [--source <id>] [--slug <slug>]+ suggest [--source <id>] [--apply] [--json]+Docs: ${CORE_DOCS}`;++function flag(args: string[], name: string): string | undefined {+ const i = args.indexOf(name);+ return i !== -1 ? args[i + 1] : undefined;+}++function positional(args: string[]): string | undefined {+ for (let i = 1; i < args.length; i++) {+ const a = args[i]!;+ if (a.startsWith('--')) { if (!['--json', '--apply'].includes(a)) i++; continue; }+ return a;+ }+ return undefined;+}++function fail(message: string, next?: string): void {+ console.error(`[core] ${message}`);+ if (next) console.error(`[core] Next: ${next}`);+ setCliExitVerdict(1);+}++/** Rewrites a page's core marking through put_page as the local owner. */+async function setMarking(engine: BrainEngine, sourceId: string, slug: string, marking: { core: boolean; priority?: number }): Promise<'changed' | 'unchanged' | 'missing'> {+ const snap = await engine.readPageSnapshot(slug, { sourceId });+ if (!snap || snap.page.deleted_at) return 'missing';+ const fm = { ...((snap.page.frontmatter ?? {}) as Record<string, unknown>) };+ const was = isCoreFrontmatter(fm);+ const wasPriority = fm.core_priority;+ delete fm.always_load;+ delete fm.core_priority;+ if (marking.core) {+ fm.always_load = true;+ const priority = marking.priority ?? (typeof wasPriority === 'number' ? wasPriority : undefined);+ if (priority !== undefined && priority !== CORE_DEFAULT_PRIORITY) fm.core_priority = priority;+ }+ if (was === marking.core && (!marking.core || fm.core_priority === wasPriority)) return 'unchanged';+ const tags = await engine.getTags(slug, { sourceId });+ const content = serializePageToMarkdown({ ...snap.page, frontmatter: fm }, tags);+ const receipt = await handleToolCall(engine, 'put_page', { slug, content, source_id: sourceId, expected_revision: snap.revision }, { sourceId }) as { state?: string; write_request?: { state?: string } };+ const state = receipt?.state ?? receipt?.write_request?.state;+ if (state && state !== 'committed') throw new Error(`the write is ${state}; check it with gbrain sources writer status --json`);+ return 'changed';+}++const STARTER_SLUG = 'core/about-the-user';+const STARTER_BODY = `- Who the user is and what they do: (fill in)+- How they like answers: (fill in, e.g. short, direct, with commands to run)+- Current focus: (fill in the projects that matter this month)+- Standing preferences: (fill in tools, conventions, things to avoid)`;++/** Zero-LLM candidates: small pages whose title or slug reads like a profile, preference or convention page, plus the most linked-to small pages. */+async function suggestCandidates(engine: BrainEngine, sourceId: string, room: number): Promise<Array<{ slug: string; title: string; chars: number; why: string }>> {+ const rows = await engine.executeRaw<{ slug: string; title: string | null; compiled_truth: string | null; frontmatter: unknown; inbound: number }>(+ `SELECT p.slug, p.title, p.compiled_truth, p.frontmatter,+ (SELECT count(*)::int FROM links l WHERE l.to_page_id = p.id) AS inbound+ FROM pages p+ WHERE p.source_id = $1 AND p.deleted_at IS NULL AND length(coalesce(p.compiled_truth, '')) BETWEEN 40 AND 1500+ ORDER BY inbound DESC, p.updated_at DESC LIMIT 400`, [sourceId]);+ const named = /(about[-_ ]?me|profile|preference|working[-_ ]?style|conventions?|how[-_ ]?i[-_ ]?work|user[-_ ]?context|standing[-_ ]?instructions)/i;+ const out: Array<{ slug: string; title: string; chars: number; why: string }> = [];+ for (const r of rows) {+ const fm = typeof r.frontmatter === 'string' ? JSON.parse(r.frontmatter) : r.frontmatter;+ if (isCoreFrontmatter(fm) || (fm as { visibility?: string } | null)?.visibility === 'private') continue;+ const title = r.title ?? r.slug;+ const chars = renderCorePage({ source_id: sourceId, slug: r.slug, title, compiled_truth: r.compiled_truth ?? '' }).length;+ const why = named.test(`${r.slug} ${title}`) ? 'profile/preference page' : r.inbound >= 5 ? `${r.inbound} pages link to it` : '';+ if (why && chars <= room) out.push({ slug: r.slug, title, chars, why });+ }+ return out.sort((a, b) => Number(b.why.startsWith('profile')) - Number(a.why.startsWith('profile'))).slice(0, 10);+}++/** Minimal line diff (longest common subsequence) for small core pages. */+function lineDiff(before: string, after: string): string {+ const a = before.split('\n');+ const b = after.split('\n');+ const dp = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0));+ for (let i = a.length - 1; i >= 0; i--) for (let j = b.length - 1; j >= 0; j--) dp[i]![j] = a[i] === b[j] ? dp[i + 1]![j + 1]! + 1 : Math.max(dp[i + 1]![j]!, dp[i]![j + 1]!);+ const out: string[] = [];+ let i = 0, j = 0;+ while (i < a.length && j < b.length) {+ if (a[i] === b[j]) { out.push(` ${a[i]}`); i++; j++; } else if (dp[i + 1]![j]! >= dp[i]![j + 1]!) out.push(`- ${a[i++]}`); else out.push(`+ ${b[j++]}`);+ }+ while (i < a.length) out.push(`- ${a[i++]}`);+ while (j < b.length) out.push(`+ ${b[j++]}`);+ return out.join('\n');+}++export async function runCore(engine: BrainEngine, args: string[]): Promise<void> {+ const sub = args[0];+ const json = args.includes('--json');+ const sourceId = flag(args, '--source') ?? 'default';+ const slug = positional(args);+ const print = (value: unknown, text: () => string) => console.log(json ? JSON.stringify(value, null, 2) : text());++ switch (sub) {+ case 'list': {+ const pages = (await coreUsage(engine)).pages.filter(p => !flag(args, '--source') || p.source_id === sourceId);+ print({ pages: pages.map(p => ({ source_id: p.source_id, slug: p.slug, title: p.title, priority: p.priority, chars: p.chars })) },+ () => pages.length ? pages.map(p => `${String(p.priority).padStart(4)} ${p.source_id}:${p.slug} ${p.chars} chars ${p.title}`).join('\n')+ : 'No core pages. Mark one with: gbrain core add <slug> (or start with: gbrain core init)');+ return;+ }+ case 'show': {+ const block = await loadCoreBlock(engine, { sessionSourceId: sourceId, excludePrivate: true });+ print(block, () => block.text || (block.enabled ? '(core memory is empty)' : '(core memory is disabled: memory.core.enabled=false)'));+ return;+ }+ case 'status': {+ const settings = await readCoreSettings(engine);+ const usage = await coreUsage(engine);+ const notices = await pendingCoreNotices(engine);+ const block = await loadCoreBlock(engine, { sessionSourceId: sourceId, excludePrivate: true });+ const status = {+ enabled: settings.enabled, chars_used: usage.chars, chars_limit: settings.maxChars, over_budget: usage.chars > settings.maxChars,+ pages: usage.pages.length, remote_edit: settings.remoteEdit, revision: block.revision,+ largest: [...usage.pages].sort((a, b) => b.chars - a.chars).slice(0, 5).map(p => ({ source_id: p.source_id, slug: p.slug, chars: p.chars })),+ withheld: block.omitted.filter(o => o.reason === 'withheld'),+ pending_notices: notices.map(n => ({ ...n, next: coreNoticeLine(n) })),+ delivery: {+ 'claude-code': 'session-start hook (core printed first)', openclaw: 'context engine, every turn',+ mcp: 'context_pack core field', 'static files': 'gbrain compile-context --include-core',+ },+ docs: CORE_DOCS,+ };+ print(status, () => [+ `Core memory: ${settings.enabled ? 'enabled' : 'disabled'} — ${usage.chars.toLocaleString('en-US')}/${settings.maxChars.toLocaleString('en-US')} chars, ${usage.pages.length} page(s), remote edits: ${settings.remoteEdit}`,+ ...(status.over_budget ? [`OVER BUDGET by ${usage.chars - settings.maxChars} chars: shorten a page (move detail into a linked page) or gbrain config set memory.core.max_chars <n>`] : []),+ ...status.largest.map(p => ` ${p.source_id}:${p.slug} ${p.chars} chars`),+ ...status.withheld.map(w => ` withheld from delivery: ${w.source_id}:${w.slug} (sensitive content)`),+ ...notices.map(n => ` notice: ${coreNoticeLine(n)}`),+ ].join('\n'));+ return;+ }+ case 'add':+ case 'remove': {+ if (!slug) { fail(`${sub} needs a page slug.`, `gbrain core ${sub} <slug> [--source <id>]`); return; }+ const rawPriority = flag(args, '--priority');+ const priority = rawPriority === undefined ? undefined : Number(rawPriority);+ if (priority !== undefined && !Number.isInteger(priority)) { fail('--priority must be an integer (lower renders first; default 100).'); return; }+ try {+ const result = await setMarking(engine, sourceId, slug, { core: sub === 'add', ...(priority !== undefined ? { priority } : {}) });+ if (result === 'missing') { fail(`No live page ${sourceId}:${slug}.`, 'check the slug with gbrain get <slug> or create the page first'); return; }+ if (sub === 'remove') await engine.executeRaw('UPDATE core_edit_notices SET acked_at = now() WHERE source_id = $1 AND slug = $2 AND acked_at IS NULL', [sourceId, slug]);+ const usage = await coreUsage(engine);+ const settings = await readCoreSettings(engine);+ console.log(`${result === 'unchanged' ? 'Already' : 'Now'} ${sub === 'add' ? 'in' : 'out of'} core: ${sourceId}:${slug}. Core uses ${usage.chars}/${settings.maxChars} chars.`);+ } catch (e) {+ fail((e as Error).message, sub === 'add' ? 'run gbrain core status to see where the budget goes' : undefined);+ }+ return;+ }+ case 'diff': {+ if (!slug) { fail('diff needs a page slug.', 'gbrain core diff <slug> [--source <id>]'); return; }+ const [oldest] = await engine.executeRaw<{ base_text: string | null; actor: string; created_at: string }>(+ `SELECT base_text, actor, created_at::text AS created_at FROM core_edit_notices WHERE source_id = $1 AND slug = $2 AND acked_at IS NULL ORDER BY id LIMIT 1`, [sourceId, slug]);+ const snap = await engine.readPageSnapshot(slug, { sourceId });+ const current = snap ? renderCorePage({ source_id: sourceId, slug, title: snap.page.title, compiled_truth: snap.page.compiled_truth }) : '';+ if (!oldest) { print({ pending: false }, () => `No unacknowledged remote edits to ${sourceId}:${slug}.`); return; }+ print({ pending: true, since: oldest.created_at, actor: oldest.actor, before: oldest.base_text, after: current, revision: snap?.revision ?? null },+ () => `Remote edits to ${sourceId}:${slug} since ${oldest.created_at} (first by ${oldest.actor}):\n${lineDiff(oldest.base_text ?? '', current)}\n\nIf this is fine: gbrain core ack --source ${sourceId} ${slug} --revision ${snap?.revision ?? 'latest'}`);+ return;+ }+ case 'ack': {+ const revision = flag(args, '--revision');+ if (!slug || !revision) { fail('ack needs a slug and --revision (from gbrain core diff or the notice).', 'gbrain core ack <slug> --revision <token>'); return; }+ const snap = await engine.readPageSnapshot(slug, { sourceId });+ if (revision !== 'latest' && snap && snap.revision !== revision) {+ const [known] = await engine.executeRaw<{ id: number }>('SELECT id FROM core_edit_notices WHERE source_id = $1 AND slug = $2 AND revision = $3 ORDER BY id DESC LIMIT 1', [sourceId, slug, revision]);+ if (!known) { fail(`Revision ${revision} is not a reviewed edit of ${sourceId}:${slug}.`, `gbrain core diff --source ${sourceId} ${slug}`); return; }+ const rows = await engine.executeRaw<{ n: number }>('WITH a AS (UPDATE core_edit_notices SET acked_at = now() WHERE source_id = $1 AND slug = $2 AND acked_at IS NULL AND id <= $3 RETURNING 1) SELECT count(*)::int AS n FROM a', [sourceId, slug, known.id]);+ console.log(`Acknowledged ${rows[0]?.n ?? 0} edit(s) up to ${revision}; later edits stay pending.`);+ return;+ }+ const rows = await engine.executeRaw<{ n: number }>('WITH a AS (UPDATE core_edit_notices SET acked_at = now() WHERE source_id = $1 AND slug = $2 AND acked_at IS NULL RETURNING 1) SELECT count(*)::int AS n FROM a', [sourceId, slug]);+ console.log(`Acknowledged ${rows[0]?.n ?? 0} edit(s) to ${sourceId}:${slug}.`);+ return;+ }+ case 'init': {+ const target = flag(args, '--slug') ?? STARTER_SLUG;+ const existing = await engine.readPageSnapshot(target, { sourceId });+ if (existing && !existing.page.deleted_at) {+ const result = await setMarking(engine, sourceId, target, { core: true, priority: 10 }).catch((e: Error) => { fail(e.message); return null; });+ if (result) console.log(`${sourceId}:${target} exists and is ${result === 'unchanged' ? 'already' : 'now'} in core.`);+ return;+ }+ const content = `---\ntitle: About the user\nalways_load: true\ncore_priority: 10\n---\n\n${STARTER_BODY}\n`;+ try {+ await handleToolCall(engine, 'put_page', { slug: target, content, source_id: sourceId }, { sourceId });+ } catch (e) { fail((e as Error).message); return; }+ console.log(`Created ${sourceId}:${target} in core. Next: ask the user the four questions on that page and replace each "(fill in)" with edit_page, keeping it short.`);+ return;+ }+ case 'suggest': {+ const settings = await readCoreSettings(engine);+ const usage = await coreUsage(engine);+ const room = settings.maxChars - usage.chars;+ const candidates = await suggestCandidates(engine, sourceId, room);+ if (!args.includes('--apply')) {+ print({ room, candidates }, () => candidates.length+ ? `Candidates that fit the ${room} chars left (read-only; ask the user before applying):\n${candidates.map(c => ` ${sourceId}:${c.slug} ${c.chars} chars ${c.why}`).join('\n')}\nApply one: gbrain core add <slug> (or all that fit: gbrain core suggest --apply)`+ : `No candidates fit the ${room} chars left. Start with: gbrain core init`);+ return;+ }+ let left = room;+ const applied: string[] = [];+ for (const c of candidates) {+ if (c.chars + 2 > left) continue;+ try { if (await setMarking(engine, sourceId, c.slug, { core: true }) === 'changed') { applied.push(c.slug); left -= c.chars + 2; } } catch { /* budget moved: skip */ }+ }+ print({ applied }, () => applied.length ? `Added to core: ${applied.map(s => `${sourceId}:${s}`).join(', ')}` : 'Nothing applied.');+ return;+ }+ default:+ console.log(USAGE);+ if (sub && sub !== '--help' && sub !== 'help') setCliExitVerdict(1);+ }+}+diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 742267af39..2d5e29ccc5 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -39,10 +39,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'code-def': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],'code-refs': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],'compile-context': ['--brain', '--budget', '--check', '--help', '--include', '--json', '--out', '--source', '--stdout', '--target'],- 'config': ['--accept-pending', '--admin-intent', '--all', '--all-from', '--background', '--brain', '--call-site', '--coverage-override', '--dataset', '--db-url', '--dim', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expected-state', '--explain', '--follow', '--force', '--from', '--harness', '--help', '--http', '--input', '--json', '--limit', '--markdown', '--min', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--no-hooks', '--only', '--out', '--path', '--pattern', '--probe', '--progress-interval', '--progress-json', '--provider', '--query', '--quiet', '--raw', '--recommended', '--session', '--shadow', '--since', '--slot', '--source', '--stale', '--status', '--suite', '--surface', '--target', '--threshold', '--timeout', '--to', '--url', '--wait', '--what-if-threshold', '--yes'],+ 'config': ['--accept-pending', '--admin-intent', '--all', '--all-from', '--background', '--brain', '--call-site', '--coverage-override', '--dataset', '--db-url', '--dim', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expected-state', '--explain', '--follow', '--force', '--from', '--harness', '--help', '--http', '--input', '--json', '--limit', '--markdown', '--min', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--no-hooks', '--only', '--out', '--path', '--pattern', '--probe', '--progress-interval', '--progress-json', '--provider', '--query', '--quiet', '--raw', '--recommended', '--revision', '--session', '--shadow', '--since', '--slot', '--source', '--stale', '--status', '--suite', '--surface', '--target', '--threshold', '--timeout', '--to', '--url', '--wait', '--what-if-threshold', '--yes'],'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--fresh-token', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],'connectors': ['--accept-pending', '--all', '--background', '--brain', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-accept-pending', '--no-browser', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--token', '--try-oauth', '--wait', '--window-days', '--yes'],'conversation-parser': ['--brain', '--help', '--json', '--source'],+ 'core': ['--apply', '--brain', '--fail-fast', '--help', '--include-core', '--json', '--priority', '--revision', '--slug', '--source', '--tools-json'],'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],@@ -157,6 +158,7 @@ export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {'config': ['--brain'],'connectors': ['--brain'],'conversation-parser': ['--brain'],+ 'core': ['--brain'],'db-repair': ['--brain'],'decide': ['--brain'],'doctor': ['--brain'],diff --git a/src/core/context/sensitivity-scan.ts b/src/core/context/sensitivity-scan.tsindex 44267a8060..afdedefeec 100644--- a/src/core/context/sensitivity-scan.ts+++ b/src/core/context/sensitivity-scan.ts@@ -98,7 +98,7 @@ export interface SensitivityScanConfig {// ── Path-shape family (ported from check-no-pii-in-agent-voice.sh) ──────────/** Hardcoded private filesystem prefixes. Extend as new deployment shapes emerge. */-const PATH_SHAPE_RES: readonly RegExp[] = [+export const PATH_SHAPE_RES: readonly RegExp[] = [/\/data\/\.openclaw\//g,/\/private\/[a-z0-9_-]+\/workspace\//g,];diff --git a/src/core/core-memory-schema.ts b/src/core/core-memory-schema.tsindex 8241b58072..f41a2c6056 100644--- a/src/core/core-memory-schema.ts+++ b/src/core/core-memory-schema.ts@@ -5,7 +5,9 @@* core_edit_notices records each remote edit to an always-loaded core page* (memory.core.remote_edit = notify). The rendered core block shows pending* rows until the owner acknowledges them up to a reviewed revision with- * `gbrain core ack <slug> --revision <token>`. No foreign key to pages: a+ * `gbrain core ack <slug> --revision <token>`. base_text keeps the rendered+ * page before the edit (bounded by the core budget) so `gbrain core diff`+ * can show what changed. No foreign key to pages: a* notice outlives a rename (page_id) and is closed when the page is* un-cored or deleted.*/@@ -18,6 +20,7 @@ CREATE TABLE IF NOT EXISTS core_edit_notices (page_id BIGINT,revision TEXT,base_revision TEXT,+ base_text TEXT,actor TEXT NOT NULL,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),acked_at TIMESTAMPTZdiff --git a/src/core/core-memory.ts b/src/core/core-memory.tsindex 88b112cdda..308ea93eb1 100644--- a/src/core/core-memory.ts+++ b/src/core/core-memory.ts@@ -215,9 +215,8 @@ export interface ListCorePagesOpts {interface CoreRow { source_id: string; slug: string; title: string | null; compiled_truth: string | null; frontmatter: unknown; withdrawn: boolean }/**- * Live core pages. Bounded: the partial index `idx_pages_always_load`- * serves the filter, and the cap leaves headroom over CORE_MAX_PAGES so the- * renderer can still report what it left out.+ * Live core pages. Bounded: the cap leaves headroom over CORE_MAX_PAGES so+ * the renderer can still report what it left out.*/export async function listCorePages(exec: RawExec, opts: ListCorePagesOpts = {}): Promise<CorePage[]> {const params: unknown[] = [];@@ -268,17 +267,67 @@ export interface LoadCoreBlockOpts {settings?: CoreSettings;}+/** Credential-like PII withholds the page; contact details and private paths are redacted in place. */+const REDACT_IN_PLACE = new Set(['pii:email', 'pii:phone', 'path']);++/**+ * Delivery sensitivity policy (sensitivity-scan.ts, the compile-context+ * detector): a page with a secret, blocklist, operator-pattern or+ * credential-shaped PII hit is withheld with a visible line naming the+ * family; email, phone and private-path hits are redacted in place.+ */+export async function applyCoreSensitivity(pages: readonly CorePage[]): Promise<{ pages: CorePage[]; withheld: Array<{ source_id: string; slug: string; family: string }> }> {+ const { loadSensitivityConfig, scanSensitive, PATH_SHAPE_RES } = await import('./context/sensitivity-scan.ts');+ const { findPii } = await import('./eval-capture-scrub.ts');+ let config: ReturnType<typeof loadSensitivityConfig>;+ // A broken operator pattern file must not switch the secret scan off: fall back to the built-in detectors.+ try { config = loadSensitivityConfig({}); } catch { config = { allowlist: [], blocklistRe: null, patterns: [] } as unknown as ReturnType<typeof loadSensitivityConfig>; }+ const out: CorePage[] = [];+ const withheld: Array<{ source_id: string; slug: string; family: string }> = [];+ for (const page of pages) {+ const findings = scanSensitive(page.rendered, config);+ // The operator pattern file also matches contact details; the same value found as email/phone is redacted, not withheld.+ const redactable = new Set(findings.filter(f => REDACT_IN_PLACE.has(f.family)).map(f => f.fingerprint));+ const blocking = findings.find(f => !REDACT_IN_PLACE.has(f.family) && !redactable.has(f.fingerprint));+ if (blocking) { withheld.push({ source_id: page.source_id, slug: page.slug, family: blocking.family }); continue; }+ if (!findings.length) { out.push(page); continue; }+ let text = page.compiled_truth;+ for (const f of findPii(text).filter(x => x.family === 'email' || x.family === 'phone').sort((a, b) => b.start - a.start)) {+ text = `${text.slice(0, f.start)}[redacted ${f.family}]${text.slice(f.end)}`;+ }+ for (const re of PATH_SHAPE_RES) text = text.replace(new RegExp(re.source, 'g'), '[redacted path]/');+ out.push({ ...toCorePage({ ...page, compiled_truth: text }), priority: page.priority });+ }+ return { pages: out, withheld };+}++/** Pending remote-edit notices for the given sources, newest first (notify policy). */+export async function pendingCoreNotices(exec: Pick<BrainEngine, 'executeRaw'>, sourceIds?: readonly string[]): Promise<Array<{ source_id: string; slug: string; revision: string | null; actor: string; created_at: string }>> {+ try {+ return await exec.executeRaw(+ `SELECT DISTINCT ON (source_id, slug) source_id, slug, revision, actor, created_at::text AS created_at+ FROM core_edit_notices WHERE acked_at IS NULL ${sourceIds ? 'AND source_id = ANY($1::text[])' : ''}+ ORDER BY source_id, slug, id DESC LIMIT 50`, sourceIds ? [[...sourceIds]] : []);+ } catch {+ return [];+ }+}++export function coreNoticeLine(n: { source_id: string; slug: string; revision: string | null; actor: string }): string {+ return `Core page ${n.source_id}:${n.slug} was edited remotely by ${n.actor}. The user should review it: gbrain core diff --source ${n.source_id} ${n.slug}, then gbrain core ack --source ${n.source_id} ${n.slug} --revision ${n.revision ?? 'latest'}.`;+}+/** The block a session receives; empty text when core is disabled or empty. */export async function loadCoreBlock(engine: Pick<BrainEngine, 'executeRaw' | 'readPageSnapshot' | 'getConfig'>, opts: LoadCoreBlockOpts = {}): Promise<CoreBlock & { enabled: boolean }> {const settings = opts.settings ?? await readCoreSettings(engine);if (!settings.enabled) {return { text: '', chars_used: 0, chars_limit: settings.maxChars, pages: [], truncated: false, omitted: [], revision: 'disabled', enabled: false };}- const pages = await listCorePages(engine, {- sourceIds: sessionCoreSources(opts.sessionSourceId, opts.allowedSources ?? null),- excludePrivate: opts.excludePrivate ?? true,- });- return { ...renderCoreBlock(pages, { maxChars: settings.maxChars, notices: opts.notices }), enabled: true };+ const sourceIds = sessionCoreSources(opts.sessionSourceId, opts.allowedSources ?? null);+ const listed = await listCorePages(engine, { sourceIds, excludePrivate: opts.excludePrivate ?? true });+ const { pages, withheld } = await applyCoreSensitivity(listed);+ const notices = opts.notices ?? (listed.length ? (await pendingCoreNotices(engine, sourceIds)).map(coreNoticeLine) : []);+ return { ...renderCoreBlock(pages, { maxChars: settings.maxChars, notices, withheld }), enabled: true };}/** Brain-wide accounting used by the write-path guard and `gbrain core status`. */diff --git a/src/core/persistence/core-guard.ts b/src/core/persistence/core-guard.tsindex 5af2ce402c..5712c1e015 100644--- a/src/core/persistence/core-guard.ts+++ b/src/core/persistence/core-guard.ts@@ -172,8 +172,8 @@ export async function prepareCoreGuard(engine: BrainEngine, input: CoreGuardInpurecord: async (tx, revision) => {if (!remote || !before.core || !contentChanged || settings.remoteEdit !== 'notify') return;const actor = `${row.authority.principal.kind}:${row.authority.principal.id}`;- await tx.executeRaw(`INSERT INTO core_edit_notices (source_id, slug, page_id, revision, base_revision, actor) VALUES ($1, $2, $3, $4, $5, $6)`,- [row.source_id, row.slug, live?.page.id ?? null, revision, live?.revision ?? null, actor]);+ await tx.executeRaw(`INSERT INTO core_edit_notices (source_id, slug, page_id, revision, base_revision, base_text, actor) VALUES ($1, $2, $3, $4, $5, $6, $7)`,+ [row.source_id, row.slug, live?.page.id ?? null, revision, live?.revision ?? null, beforeRendered, actor]);},};}diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 56a2f756c1..aea3aa9057 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -1834,6 +1834,7 @@ CREATE TABLE IF NOT EXISTS core_edit_notices (page_id BIGINT,revision TEXT,base_revision TEXT,+ base_text TEXT,actor TEXT NOT NULL,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),acked_at TIMESTAMPTZdiff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex ef1c12b97f..052756402a 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -2556,6 +2556,7 @@ CREATE TABLE IF NOT EXISTS core_edit_notices (page_id BIGINT,revision TEXT,base_revision TEXT,+ base_text TEXT,actor TEXT NOT NULL,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),acked_at TIMESTAMPTZdiff --git a/src/schema.sql b/src/schema.sqlindex 353985ec4c..8ccb3410e7 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -2552,6 +2552,7 @@ CREATE TABLE IF NOT EXISTS core_edit_notices (page_id BIGINT,revision TEXT,base_revision TEXT,+ base_text TEXT,actor TEXT NOT NULL,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),acked_at TIMESTAMPTZ