Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(decide): enable/--recommended and probe --query ask through requireConsent (C2)
garrytan733e2e6db372
diff --git a/scripts/agent-contract-baselines/yes-rerun-string.tsv b/scripts/agent-contract-baselines/yes-rerun-string.tsvindex 592575ccac..272b9a9c3c 100644--- a/scripts/agent-contract-baselines/yes-rerun-string.tsv+++ b/scripts/agent-contract-baselines/yes-rerun-string.tsv@@ -4,8 +4,6 @@ src/commands/apply-migrations.ts 3src/commands/company-brain-connect.ts 1src/commands/config.ts 1src/commands/db-repair.ts 1-src/commands/decide.ts 1-src/commands/decide/probe-query.ts 1src/commands/doctor/checks/memory-writeback.ts 2src/commands/dream-retriage.ts 1src/commands/enrich.ts 1diff --git a/src/commands/decide.ts b/src/commands/decide.tsindex 0a00afd440..4c39e6ccaf 100644--- a/src/commands/decide.ts+++ b/src/commands/decide.ts@@ -34,7 +34,8 @@ import {import { DECIDE_SLOTS, DecideError, EVIDENCE_CLASSES, type DecideQuestion, type DecideSlot } from '../core/ai/decide/types.ts';import { usageCostUsd } from '../core/budget/reservation-cost.ts';import { evidenceCoPackedSlots, resetDecideSearchCache } from '../core/search/decide-stage.ts';-import { promptYesNo } from '../core/confirm-prompt.ts';+import { currentExitCode } from '../core/cli-force-exit.ts';+import { consentGate, engineConsentEnv } from '../core/consent-cli.ts';export const DECIDE_HELP = `Usage: gbrain decide <subcommand> [options]@@ -334,11 +335,31 @@ async function resolvePinned(provider: string): Promise<string> {return `typesafe:${r.model_resolved}`;}-async function confirmed(args: string[], summary: string[]): Promise<boolean> {- for (const line of summary) console.log(line);- if (has(args, '--yes')) return true;- if (!process.stdin.isTTY) { console.error('Re-run with --yes to confirm (non-interactive).'); return false; }- return promptYesNo('Proceed? [y/N] ');+/**+ * A4 consent for turning a slot on: text leaves the machine (`egress`) and the+ * provider bills per call (`paid`, bounded by decide.budget.daily_usd). `--yes`+ * authorizes; `--json` never does. Resolves false after printing the refusal+ * (exit verdict 3) or a declined prompt.+ */+async function enableConsent(engine: BrainEngine, args: string[], req: { slots: DecideSlot[]; summary: string[]; dailyUsd: number; argv: string[] }): Promise<boolean> {+ const json = has(args, '--json');+ for (const line of req.summary) (json ? console.error : console.log)(line);+ const what = req.slots.length === 1 ? `Turn on the decide slot ${req.slots[0]}` : `Turn on the decide slots ${req.slots.join(', ')}`;+ const auth = await consentGate({+ command: 'decide enable',+ effects: ['egress', 'paid'],+ actor: 'agent',+ what,+ why: 'System One answers these routing and ranking questions with a hosted model instead of local heuristics; each slot is a measured win on the eval sets.',+ risk: `From now on, brain text named in the summary leaves this machine on every affected call, and the provider bills per call up to decide.budget.daily_usd ($${req.dailyUsd.toFixed(2)}/day). `+ + 'Undo any time: gbrain decide disable --all.',+ user_message: `${what}? Some of your brain's text (${req.summary.find(l => l.startsWith('Data that leaves')) ?? 'see the summary'}) will be sent to the provider on each call, capped at $${req.dailyUsd.toFixed(2)} a day; gbrain decide disable --all turns it off.`,+ argv: req.argv,+ preview_argv: ['gbrain', 'decide', 'status', '--json'],+ est_usd: null,+ args,+ }, { json, env: engineConsentEnv(engine, { configuredCapUsd: req.dailyUsd }) });+ return auth !== null;}async function writeConfig(engine: BrainEngine, writes: Array<[string, string]>): Promise<void> {@@ -418,8 +439,8 @@ async function cmdEnable(engine: BrainEngine, args: string[]): Promise<number> {...(cost.usd !== null ? [`Estimated cost: ~$${cost.usd.toFixed(4)} per 1,000 ${COST_UNITS[slot]?.unit ?? 'units'}; daily cap $${nextCfg.dailyUsd.toFixed(2)} (decide.budget.daily_usd${slot === 'rerank' ? '; S1 on uses reranker spend controls' : ''}).`] : []),`Writes: ${[...writes, ...(slot === 'rerank' ? [['search.reranker.model', provider], ['search.reranker.enabled', 'true']] : [])].map(([k, v]) => `${k}=${v}`).join(', ')}`,];- if (!json && !(await confirmed(args, summary))) return 1;- if (json && !has(args, '--yes')) { console.error('--json enable needs --yes'); return 1; }+ if (!(await enableConsent(engine, args, { slots: [slot], summary, dailyUsd: nextCfg.dailyUsd,+ argv: ['gbrain', 'decide', 'enable', slot, '--provider', provider, ...(mode === 'shadow' ? ['--shadow'] : []), ...(json ? ['--json'] : [])] }))) return currentExitCode() || 1;if (slot === 'rerank') writes.push(...await enableRerank(engine, state, provider, args));await writeConfig(engine, writes);const after = policyFor(nextState, slot);@@ -439,9 +460,16 @@ async function enableRecommended(engine: BrainEngine, state: DecideState, args:console.error(`no slot has a recorded win for ${model}; see docs/eval/system-one/`);return 1;}+ // One ask covers every winner; the per-slot runs then carry the approval.+ if (!has(args, '--yes')) {+ const summary = [`Enable ${winners.join(', ')} with ${provider} (the slots with a recorded win; docs/eval/system-one/).`,+ `Data that leaves this machine: the query, candidate and fact text each slot scores, to ${provider.startsWith('typesafe:') ? 'TypeSafe' : 'your configured chat provider'}; private pages stay local unless decide.egress.private=allow.`];+ if (!(await enableConsent(engine, args, { slots: winners, summary, dailyUsd: state.cfg.dailyUsd,+ argv: ['gbrain', 'decide', 'enable', '--recommended', ...(flagValue(args, '--provider') ? ['--provider', flagValue(args, '--provider')!] : []), ...(has(args, '--json') ? ['--json'] : [])] }))) return currentExitCode() || 1;+ }let code = 0;const pin = state.cfg.provider === 'none' && !flagValue(args, '--provider') ? ['--provider', provider] : [];- for (const slot of winners) code = Math.max(code, await cmdEnable(engine, ['enable', slot, ...pin, ...args.filter((a) => a !== '--recommended')]));+ for (const slot of winners) code = Math.max(code, await cmdEnable(engine, ['enable', slot, ...pin, ...args.filter((a) => a !== '--recommended' && a !== '--yes'), '--yes']));return code;}diff --git a/src/commands/decide/probe-query.ts b/src/commands/decide/probe-query.tsindex a31aa67876..6171d6cfab 100644--- a/src/commands/decide/probe-query.ts+++ b/src/commands/decide/probe-query.ts@@ -3,7 +3,7 @@* (every slot off), then asks Jev, in ONE request, for each result's rerank* score and evidence probability, and prints them next to today's order.* Changes nothing: no config write, no receipt, results untouched. Egress is- * summarized and confirmed first; private pages stay local unless+ * summarized and asked through requireConsent first (effect egress); private pages stay local unless* decide.egress.private=allow.*/import type { BrainEngine } from '../../core/engine.ts';@@ -15,7 +15,8 @@ import { refusalLine } from '../../core/ai/decide/outcomes.ts';import { RELEVANCE_LEVELS } from '../../core/ai/decide/rerank-adapter.ts';import { DecideError, type DecideQuestion, type EvidenceItem } from '../../core/ai/decide/types.ts';import { capRerankDoc } from '../../core/search/rerank.ts';-import { promptYesNo } from '../../core/confirm-prompt.ts';+import { currentExitCode } from '../../core/cli-force-exit.ts';+import { consentGate } from '../../core/consent-cli.ts';export async function runProbeQuery(engine: BrainEngine, cfg: DecideConfig, provider: string, query: string, args: string[]): Promise<number> {const json = args.includes('--json');@@ -32,11 +33,18 @@ export async function runProbeQuery(engine: BrainEngine, cfg: DecideConfig, provconst state = { query: { text: query, class: 'query' as const } };const verdict = await checkEgress(engine, previewCfg, provider, state, questions);const withheld = new Set(Object.keys(verdict.refused).map((id) => id.split(':')[1]));- console.error(`This sends your query and ${results.length - withheld.size} result snippet(s) to TypeSafe (${provider}) once; ${withheld.size} private result(s) stay local. Nothing is changed or stored.`);- if (!args.includes('--yes')) {- if (!process.stdin.isTTY) { console.error('Re-run with --yes to confirm (non-interactive).'); return 1; }- if (!(await promptYesNo('Send? [y/N] '))) return 1;- }+ const sent = results.length - withheld.size;+ console.error(`This sends your query and ${sent} result snippet(s) to TypeSafe (${provider}) once; ${withheld.size} private result(s) stay local. Nothing is changed or stored.`);+ const auth = await consentGate({+ command: 'decide probe', effects: ['egress'], actor: 'agent',+ what: `Send the query and ${sent} result snippet(s) to TypeSafe once`,+ why: 'Previews how System One would rerank and score today\'s results for this query, next to today\'s order.',+ risk: `The query text and ${sent} result snippet(s) from your brain leave this machine once (${provider}); ${withheld.size} private result(s) stay local. Nothing is changed or stored.`,+ user_message: `Send your query and ${sent} snippet(s) from your brain to TypeSafe once to preview System One? Nothing is stored or changed.`,+ argv: ['gbrain', 'decide', 'probe', '--query', query, ...(json ? ['--json'] : [])],+ args,+ }, { json, env: { getConfig: (key: string) => engine.getConfig(key) } });+ if (!auth) return currentExitCode() || 1;try {const r = await runDecide({ slot: 'evidence', callSite: 'probe', state, questions, provider, deadlineMs: 15_000, lane: 'background' }, { engine, config: previewCfg });const rows = results.map((res, i) => {diff --git a/test/decide/quickstart-doc.serial.test.ts b/test/decide/quickstart-doc.serial.test.tsindex 62b3bcf322..9abcca80a0 100644--- a/test/decide/quickstart-doc.serial.test.ts+++ b/test/decide/quickstart-doc.serial.test.ts@@ -9,7 +9,7 @@* normalized on both sides; probabilities, ranks, slugs and wording are not.* If this fails, the guide and the CLI disagree: fix whichever is wrong.*- * Serial: mock.module (confirmation prompt), GBRAIN_HOME, process.stdin.isTTY+ * Serial: mock.module (the interaction module's consent prompt), GBRAIN_HOME, process.stdin.isTTY* and the process-global gateway.*/import { afterAll, beforeAll, describe, expect, mock, test } from 'bun:test';@@ -22,7 +22,9 @@ import { configureGateway, resetGateway, __setDecideTransportForTests } from '..import { __resetDecideStoreForTests, flushDecideWrites } from '../../src/core/ai/decide/store.ts';import { resetDecideSearchCache } from '../../src/core/search/decide-stage.ts';-mock.module('../../src/core/confirm-prompt.ts', () => ({ promptYesNo: async () => true }));+// A human at the terminal answers "y" to the consent prompt (requireConsent → interaction.readLine).+const realInteraction = await import('../../src/core/interaction.ts');+mock.module('../../src/core/interaction.ts', () => ({ ...realInteraction, isInteractive: () => true, readLine: async () => ({ kind: 'line', text: 'y' }) }));const GUIDE = join(import.meta.dir, '..', '..', 'docs', 'guides', 'system-one.md');