Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(advisor): --apply <id> --yes runs non-interactively; the refusal names the command and its cost (C4)

garrytane962f899abeb
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.md
index 963644569c..461a80f4a6 100644
--- a/docs/architecture/key-files/core-services-1.md
+++ b/docs/architecture/key-files/core-services-1.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` + `src/commands/advisor.ts` — `gbrain advisor`: read-only ranked actions from brain state. `run.runAdvisor` executes the hardcoded COLLECTORS array (version [cache-only], migration, schema-pack, stalled-jobs [absent-table tolerant], usage-shape, setup-smells, uninstalled-brain-pack, uninstalled-bundled, chronicle, mcp-client-fit), each in its own try/catch; `collect-mcp-client-fit.ts` (E3) flags full-surface MCP clients whose 30d usage fits STARTER_OPS (exact `rescope-client --surface starter` fix; ≥10-call threshold; automation-shaped clients excluded per D12) plus STARTER_OPS drift (top-used ops missing; starter members unused 90d) via the shared `src/core/mcp-usage.ts` reader — starter membership is judged against the exported `ALWAYS_INCLUDED_STARTER_OPS` (surface.ts) so the always-included lane never reads as unused, and the missing-from-starter arm excludes `localOnly` ops (never proposable for a network surface, mirroring derive-starter-ops) — REMOTE runs redact client identifiers to aggregate counts (amendment 29), and its dismiss/snooze rides the nag-state engine with its own `~/.gbrain/advisor-usage-nag-state.json` (local runs only); `rankFindings` orders critical>warn>info then collector order, caps the info tail, and drops `workspace_dependent` findings when `remote` (A1). `render.ts` is the shared `=`-bar renderer used by the advisor AND `post-install-advisory.ts` (generalized to a single current-state `recommended-set.RECOMMENDED`, `install`→`scaffold`). `history.ts` appends bounded `~/.gbrain/advisor-history.jsonl` (no DB migration) for since-last-run deltas; local-only. `apply.resolveApplyTarget` is the allowlist+injection guard for `commands/advisor.ts --apply <id>` (structured argv, never a shell; local-only). The `advisor` op (`operations.ts`) is read-scoped, NOT localOnly, gated by `mcp.publish_advisor` (config.ts; default off) and strictly read-only on remote. CLI wired in `cli.ts` (`CLI_ONLY` + dispatch). Bundled skill `skills/gbrain-advisor/` + weekly cron recipe. Tests: `test/advisor-{core,apply,op-gate,ranking-eval}.test.ts`.
+- `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` + `src/commands/advisor.ts` — `gbrain advisor`: read-only ranked actions from brain state. `run.runAdvisor` executes the hardcoded COLLECTORS array (version [cache-only], migration, schema-pack, stalled-jobs [absent-table tolerant], usage-shape, setup-smells, uninstalled-brain-pack, uninstalled-bundled, chronicle, mcp-client-fit), each in its own try/catch; `collect-mcp-client-fit.ts` (E3) flags full-surface MCP clients whose 30d usage fits STARTER_OPS (exact `rescope-client --surface starter` fix; ≥10-call threshold; automation-shaped clients excluded per D12) plus STARTER_OPS drift (top-used ops missing; starter members unused 90d) via the shared `src/core/mcp-usage.ts` reader — starter membership is judged against the exported `ALWAYS_INCLUDED_STARTER_OPS` (surface.ts) so the always-included lane never reads as unused, and the missing-from-starter arm excludes `localOnly` ops (never proposable for a network surface, mirroring derive-starter-ops) — REMOTE runs redact client identifiers to aggregate counts (amendment 29), and its dismiss/snooze rides the nag-state engine with its own `~/.gbrain/advisor-usage-nag-state.json` (local runs only); `rankFindings` orders critical>warn>info then collector order, caps the info tail, and drops `workspace_dependent` findings when `remote` (A1). `render.ts` is the shared `=`-bar renderer used by the advisor AND `post-install-advisory.ts` (generalized to a single current-state `recommended-set.RECOMMENDED`, `install`→`scaffold`). `history.ts` appends bounded `~/.gbrain/advisor-history.jsonl` (no DB migration) for since-last-run deltas; local-only. `apply.resolveApplyTarget` is the allowlist+injection guard for `commands/advisor.ts --apply <id>` (structured argv via `spawnCliChild`, never a shell; local-only; asks through `requireConsent` with per-dispatch-id effects and cost text, so `--apply <id> --yes` is the non-interactive approval and a refusal exits 3 with the consent payload naming the command and its cost). The `advisor` op (`operations.ts`) is read-scoped, NOT localOnly, gated by `mcp.publish_advisor` (config.ts; default off) and strictly read-only on remote. CLI wired in `cli.ts` (`CLI_ONLY` + dispatch). Bundled skill `skills/gbrain-advisor/` + weekly cron recipe. Tests: `test/advisor-{core,apply,op-gate,ranking-eval}.test.ts`.
- `src/core/audit/audit-writer.ts` — shared JSONL audit primitive behind the audit modules. Exports `createAuditWriter({kind, recordSchema})` returning `{log, readRecent}` plus shared helpers `computeIsoWeekFilename(kind, now?)` and `resolveAuditDir()` (honors `GBRAIN_AUDIT_DIR`). ISO-week file rotation; best-effort writes (stderr warn on failure, never throws); read-path scans current-week + previous-week files for boundary spans. Built on it: `src/core/rerank-audit.ts`, `src/core/audit-slug-fallback.ts`, `src/core/minions/handlers/shell-audit.ts`, `src/core/minions/handlers/supervisor-audit.ts`, `src/core/facts/phantom-audit.ts`. The `graph-signals-failures` audit (`logGraphSignalsFailure`) uses the same primitive. `src/core/skillpack/audit.ts` is the one audit that does not use it. Pinned by `test/audit/audit-writer.test.ts`.
diff --git a/scripts/agent-contract-baselines/stdio-inherit.tsv b/scripts/agent-contract-baselines/stdio-inherit.tsv
index f7b24fc2c6..1faf173291 100644
--- a/scripts/agent-contract-baselines/stdio-inherit.tsv
+++ b/scripts/agent-contract-baselines/stdio-inherit.tsv
@@ -1,6 +1,5 @@
# shrink-only baseline for scripts/check-agent-contract.ts rule stdio-inherit: path<TAB>count
src/cli/commands/smoke-test.ts 1
-src/commands/advisor.ts 1
src/commands/autopilot.ts 1
src/commands/migrations/v0_11_0.ts 2
src/commands/skillopt.ts 1
diff --git a/src/commands/advisor.ts b/src/commands/advisor.ts
index 27290bbe19..ea0148c932 100644
--- a/src/commands/advisor.ts
+++ b/src/commands/advisor.ts
@@ -7,15 +7,18 @@
*
* The advisor itself never mutates. `--apply` is the only path that runs a fix,
* and it: refuses over MCP (CLI is always local), only acts on allowlisted
- * findings (those carrying a dispatch_id), executes the fix as STRUCTURED ARGV
- * via a child process (never a shell — no injection), and confirms first.
+ * findings (those carrying a dispatch_id), asks through requireConsent first
+ * (`--apply <id> --yes` non-interactively), and executes the fix as STRUCTURED
+ * ARGV via a child process (never a shell — no injection).
*/
-import { spawnSync } from 'child_process';
-import { createInterface } from 'readline';
import { resolve as resolvePath } from 'path';
import type { BrainEngine } from '../core/engine.ts';
+import type { Effect } from '../core/agent-output.ts';
+import { spawnCliChild } from '../core/cli-force-exit.ts';
+import { consentGate, engineConsentEnv } from '../core/consent-cli.ts';
+import { CONFIRMATION_REQUIRED_EXIT_CODE } from '../core/exit-codes.ts';
import { VERSION } from '../version.ts';
import { loadConfig } from '../core/config.ts';
import { autoDetectSkillsDir } from '../core/repo-root.ts';
@@ -26,7 +29,8 @@ import { resolveApplyTarget } from '../core/advisor/apply.ts';
import type { AdvisorContext, AdvisorReport } from '../core/advisor/types.ts';
export interface AdvisorCliResult {
- exitCode: 0 | 1 | 2;
+ /** 0 clean / 1 warn / 2 critical or a failed fix / 3 consent required (--apply). */
+ exitCode: 0 | 1 | 2 | 3;
}
function buildContext(engine: BrainEngine): AdvisorContext {
@@ -57,9 +61,11 @@ export async function runAdvisorCli(engine: BrainEngine, args: string[]): Promis
'gbrain advisor [--json] [--apply <finding-id>]\n\n' +
' (no flags) Ranked, agent-readable list of high-leverage actions for this brain.\n' +
' --json Structured findings. Exit code: 0 clean / 1 warn / 2 critical.\n' +
- ' --apply <id> Run ONE finding\'s fix (local-only, confirms first). Only findings\n' +
- ' that report an apply id are runnable.\n\n' +
- 'Read-only by default; never mutates without --apply + your confirmation.',
+ ' --apply <id> Run ONE finding\'s fix (local-only). Only findings that report an\n' +
+ ' apply id are runnable. It asks first; --yes is the user\'s approval.\n' +
+ ' Without it a non-interactive run changes nothing and exits 3 with the\n' +
+ ' consent payload (the command it would run and its cost).\n\n' +
+ 'Read-only by default; never mutates without --apply + the user\'s approval.',
);
return { exitCode: 0 };
}
@@ -72,7 +78,7 @@ export async function runAdvisorCli(engine: BrainEngine, args: string[]): Promis
const report = await runAdvisor(ctx);
if (applyId) {
- return applyFinding(report, applyId);
+ return applyFinding(engine, report, applyId, args);
}
// Record run history (local-only) for "since last run" deltas.
@@ -94,11 +100,26 @@ export async function runAdvisorCli(engine: BrainEngine, args: string[]): Promis
}
/**
- * E5: run a single finding's fix. Allowlist = findings carrying a dispatch_id.
- * Local-only (refused over MCP by construction — this is the CLI path). Executes
- * the structured argv via a child process with NO shell.
+ * What running each allowlisted fix does, for the consent request (C4). An
+ * unknown dispatch id is treated as destructive (never preapprovable).
*/
-function applyFinding(report: AdvisorReport, id: string): AdvisorCliResult {
+const APPLY_CONSENT: Readonly<Record<string, { effects: Effect[]; risk: string; cost: string }>> = {
+ apply_migrations: {
+ effects: ['persistent_install'],
+ risk: 'Applies the pending schema and data migrations to this brain (forward-only; take a backup first with gbrain backup if one matters) '
+ + 'and may install the autopilot background service.',
+ cost: 'no model spend (a migration that needs paid re-embedding asks separately)',
+ },
+};
+
+/**
+ * E5/C4: run a single finding's fix. Allowlist = findings carrying a dispatch_id.
+ * Local-only (refused over MCP by construction — this is the CLI path). Asks
+ * through requireConsent first: `--yes` or a TTY prompt; otherwise exit 3 with
+ * the consent payload naming the command and its cost. Executes the
+ * structured argv via spawnCliChild with NO shell.
+ */
+async function applyFinding(engine: BrainEngine, report: AdvisorReport, id: string, args: string[]): Promise<AdvisorCliResult> {
const target = resolveApplyTarget(report, id);
if (!target.ok) {
console.error(
@@ -108,33 +129,27 @@ function applyFinding(report: AdvisorReport, id: string): AdvisorCliResult {
return { exitCode: 2 };
}
+ const finding = report.findings.find((f) => f.fix.dispatch_id === id);
+ const known = APPLY_CONSENT[id];
console.error(`About to run: ${target.display}`);
- if (!confirmTty('Proceed? [y/N]: ')) {
- console.error('Aborted. Nothing was run.');
- return { exitCode: 1 };
- }
+ const auth = await consentGate({
+ command: 'advisor --apply', effects: known?.effects ?? ['destructive'], actor: 'agent',
+ what: `Run the advisor fix ${id}: ${target.display}`,
+ why: finding?.title ?? `The advisor recommends ${id}.`,
+ risk: `${known?.risk ?? 'Runs a gbrain maintenance command that changes this brain.'} Cost: ${known?.cost ?? 'unknown'}.`,
+ user_message: `Run ${target.display} now (${known?.cost ?? 'cost unknown'})? ${finding?.title ?? ''}`.trim(),
+ argv: ['gbrain', 'advisor', '--apply', id, ...(args.includes('--json') ? ['--json'] : [])],
+ preview_argv: ['gbrain', 'advisor', '--json'],
+ // `--apply <id>` selects the finding here; it is not the consent flag.
+ args: args.filter((a, i) => a !== '--apply' && args[i - 1] !== '--apply'),
+ }, { json: args.includes('--json'), env: engineConsentEnv(engine) });
+ if (!auth) return { exitCode: CONFIRMATION_REQUIRED_EXIT_CODE };
const [cmd, ...rest] = target.argv;
- const res = spawnSync(cmd!, rest, { stdio: 'inherit', shell: false });
- return { exitCode: (res.status ?? 1) === 0 ? 0 : 2 };
-}
-
-/** Synchronous y/N TTY confirm. Non-TTY → false (never auto-run). */
-function confirmTty(prompt: string): boolean {
- if (!process.stdin.isTTY) return false;
- // Bun supports a synchronous prompt via readline only async; use a tiny
- // blocking read on the TTY fd instead.
- process.stderr.write(prompt);
- const buf = Buffer.alloc(8);
- try {
- const fs = require('fs') as typeof import('fs');
- const n = fs.readSync(0, buf, 0, 8, null);
- const ans = buf.toString('utf8', 0, n).trim().toLowerCase();
- return ans === 'y' || ans === 'yes';
- } catch {
- return false;
- }
+ const child = spawnCliChild(cmd!, rest, { shell: false });
+ const status = await new Promise<number>((resolveStatus) => {
+ child.once('error', () => resolveStatus(1));
+ child.once('close', (code) => resolveStatus(code ?? 1));
+ });
+ return { exitCode: status === 0 ? 0 : 2 };
}
-
-// readline imported for type-compat with other commands; not used directly.
-void createInterface;
diff --git a/test/advisor-cli.test.ts b/test/advisor-cli.test.ts
index 4db60d9ccd..15383ab97b 100644
--- a/test/advisor-cli.test.ts
+++ b/test/advisor-cli.test.ts
@@ -9,9 +9,10 @@
* `critical`) keys on engine.getConfig('version') vs LATEST_VERSION,
* collect-chronicle emits `warn` from engine.findOntologyConflicts, and
* collect-stalled-jobs emits `info` (stale_sync) from engine.executeRaw.
- * - --apply's TTY gate (confirmTty checks process.stdin.isTTY BEFORE any
- * read) and its spawn seam (child_process.spawnSync, spied via the module
- * namespace — Bun named imports are live bindings, so no mock.module).
+ * - --apply's consent gate (requireConsent: exit 3 with the payload when
+ * non-interactive without --yes) and its spawn seam (child_process.spawn
+ * behind spawnCliChild, spied via the module namespace — Bun named imports
+ * are live bindings, so no mock.module).
*
* Hermeticity (non-serial rules): no bare process.env mutation — withEnv +
* emptyHome() point GBRAIN_HOME at a fresh temp dir per call, which isolates
@@ -25,6 +26,7 @@
import { describe, test, expect, spyOn } from 'bun:test';
import * as childProcess from 'child_process';
+import { setCliExitVerdict } from '../src/core/cli-force-exit.ts';
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
@@ -93,7 +95,7 @@ function fakeEngine(opts: FakeEngineOpts = {}): BrainEngine {
}
interface CapturedRun {
- exitCode: 0 | 1 | 2;
+ exitCode: 0 | 1 | 2 | 3;
stdout: string;
stderrLines: string[];
}
@@ -122,6 +124,7 @@ async function runCaptured(engine: BrainEngine, args: string[]): Promise<Capture
process.stdout.write = origStdoutWrite;
stdin.isTTY = origIsTTY;
errSpy.mockRestore();
+ setCliExitVerdict(0); // a consent refusal records exit 3 for the CLI seam
}
}
@@ -170,24 +173,46 @@ describe('runAdvisorCli exit-verdict mapping (E2 contract: 0 clean / 1 warn / 2
});
describe('runAdvisorCli --apply', () => {
- test('non-TTY stdin → confirm refused: exit 1, "Aborted. Nothing was run.", spawnSync never invoked', async () => {
- const spawnSpy = spyOn(childProcess, 'spawnSync').mockImplementation(
- (() => ({ status: 0 })) as never,
- );
+ test('C4: non-interactive without --yes → exit 3, consent payload names the command and its cost, nothing spawned', async () => {
+ const spawned: string[][] = [];
+ const realSpawn = childProcess.spawn;
+ const spawnSpy = spyOn(childProcess, 'spawn').mockImplementation(((cmd: string, args: string[], opts: unknown) => {
+ spawned.push([cmd, ...(args ?? [])]);
+ return (realSpawn as (...a: unknown[]) => unknown)(cmd, args, opts);
+ }) as never);
try {
- await withEnv(hermeticEnv(), async () => {
+ await withEnv({ ...hermeticEnv(), GBRAIN_NON_INTERACTIVE: '1' }, async () => {
// pending_migration is the runnable finding (dispatch_id apply_migrations).
- const run = await runCaptured(fakeEngine({ schemaVersion: '1' }), [
- '--apply',
- 'apply_migrations',
- ]);
+ const run = await runCaptured(fakeEngine({ schemaVersion: '1' }), ['--apply', 'apply_migrations', '--json']);
expect(run.stderrLines).toContain('About to run: gbrain apply-migrations --yes');
- expect(run.stderrLines).toContain('Aborted. Nothing was run.');
- expect(run.exitCode).toBe(1);
- // The spy intercepts advisor.ts's own `spawnSync` binding (live-binding
- // interop, verified by the mocked return above: had the spawn path run,
- // status 0 would have produced exit 0, not 1).
- expect(spawnSpy.mock.calls.length).toBe(0);
+ expect(run.exitCode).toBe(3);
+ const payload = JSON.parse(run.stdout);
+ expect(payload).toMatchObject({ code: 'confirmation_required', effects: ['persistent_install'] });
+ expect(payload.fix.argv).toEqual(['gbrain', 'advisor', '--apply', 'apply_migrations', '--json', '--yes']);
+ expect(payload.user_message).toContain('gbrain apply-migrations --yes');
+ expect(payload.risk).toContain('Cost: no model spend');
+ expect(spawned.filter((c) => c[0] === 'gbrain')).toEqual([]);
+ });
+ } finally {
+ spawnSpy.mockRestore();
+ }
+ });
+
+ test('C4: --apply <id> --yes runs the fix non-interactively (structured argv, no shell)', async () => {
+ const calls: Array<{ cmd: string; args: string[]; opts: { shell?: boolean } }> = [];
+ const spawnSpy = spyOn(childProcess, 'spawn').mockImplementation(((cmd: string, args: string[], opts: { shell?: boolean }) => {
+ calls.push({ cmd, args, opts });
+ const { EventEmitter } = require('node:events') as typeof import('node:events');
+ const child = new EventEmitter();
+ setTimeout(() => child.emit('close', 0), 0);
+ return child;
+ }) as never);
+ try {
+ await withEnv({ ...hermeticEnv(), GBRAIN_NON_INTERACTIVE: '1' }, async () => {
+ const run = await runCaptured(fakeEngine({ schemaVersion: '1' }), ['--apply', 'apply_migrations', '--yes']);
+ expect(run.exitCode).toBe(0);
+ expect(calls).toHaveLength(1);
+ expect(calls[0]).toMatchObject({ cmd: 'gbrain', args: ['apply-migrations', '--yes'], opts: { shell: false } });
});
} finally {
spawnSpy.mockRestore();