Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(cli): observational startup for consent-gated commands
garrytanf20479538e58
diff --git a/docs/architecture/key-files/entrypoints-and-docs.md b/docs/architecture/key-files/entrypoints-and-docs.mdindex 399733b315..b88b0de93e 100644--- a/docs/architecture/key-files/entrypoints-and-docs.md+++ b/docs/architecture/key-files/entrypoints-and-docs.md@@ -120,7 +120,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELSize ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers `handleCliOnly`'s explicit ordered pipeline (`@cliPipelineStage` functions: thin-client guard, deferred-persistence routing, subcommand and help routes, read-only timeout path, sync watchdog and delegation, connectEngine terminator with degraded-serve recovery, teardown), thin-client routing and refusal, help and self-help text, strict flag parsing and process-exit teardown. Per-command dispatch (pre- and post-connect) lives in the command table (entry below), not in `src/cli.ts`.- `src/cli/remember-format.ts` — the `remember` human formatter (`formatRememberResult`: status, entity with `(inferred from mention)`, expiry, degraded dedup, `warnings` + `hint`), kept out of `src/cli.ts`; `--json` prints the raw envelope. Pinned by `test/remember-entity-inference.test.ts`.-- `src/cli/command-table.ts` + `src/cli/commands/<name>.ts` — one record per CLI-only command (`name`, `phase`, `thinClient`, `selfHelp`, `skipStartupHooks`, `load: () => import('<literal>')`). The records derive `CLI_ONLY`, `CLI_ONLY_SELF_HELP`, `THIN_CLIENT_REFUSED_COMMANDS` and `STARTUP_HOOK_SKIP_COMMANDS` (re-exported from `src/cli.ts`); `cliAliases`' collision check runs over the derived `CLI_ONLY`. Each module holds the body its switch case or plain branch had, moved verbatim, and receives dispatcher-owned pieces through `CliDispatchContext`. Master's membership inconsistencies are preserved (the dead second `auth` branch, the unreachable `capture --help` branch, `connectors`' never-reached refuse hint, `watch` refused without a hint, `eval whoknows` shadowed by the refusal) and pinned by `test/fixtures/goldens/cli/membership-sets.json`. Contract: `test/cli-command-table.test.ts`; engine lifecycle per path: `test/cli-dispatch-lifecycle.serial.test.ts`.+- `src/cli/command-table.ts` + `src/cli/commands/<name>.ts` — one record per CLI-only command (`name`, `phase`, `thinClient`, `selfHelp`, `skipStartupHooks`, `load: () => import('<literal>')`). The records derive `CLI_ONLY`, `CLI_ONLY_SELF_HELP`, `THIN_CLIENT_REFUSED_COMMANDS` and `STARTUP_HOOK_SKIP_COMMANDS` (re-exported from `src/cli.ts`); `cliAliases`' collision check runs over the derived `CLI_ONLY`. Each module holds the body its switch case or plain branch had, moved verbatim, and receives dispatcher-owned pieces through `CliDispatchContext`. A record with `startup: 'observational'` (A4) connects probe-only (no migrations, retired-marker cleanup or DB-plane config merge) and its handler calls `ctx.completeStartup(engine)` only after `requireConsent` authorizes the run. Master's membership inconsistencies are preserved (the dead second `auth` branch, the unreachable `capture --help` branch, `connectors`' never-reached refuse hint, `watch` refused without a hint, `eval whoknows` shadowed by the refusal) and pinned by `test/fixtures/goldens/cli/membership-sets.json`. Contract: `test/cli-command-table.test.ts`; engine lifecycle per path: `test/cli-dispatch-lifecycle.serial.test.ts`.- `scripts/lib/cli-pipeline.ts` — flattens `handleCliOnly` (inlining `@cliPipelineStage` functions) and reads the command table by AST, for the W0 dispatch-shape extractor (`test/helpers/cli-dispatch-extract.ts`) and `scripts/generate-flag-registry.ts`.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex df33849937..ce7b18ca38 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,7 +3,7 @@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note-src/cli.ts 3209 ratchet +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult+src/cli.ts 3211 ratchet +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResultsrc/commands/autopilot.ts 1639 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts)src/commands/doctor.ts 653 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.tssrc/commands/embed.ts 2217 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts)diff --git a/scripts/serial-weights.json b/scripts/serial-weights.jsonindex 85c89e694e..9c113493f1 100644--- a/scripts/serial-weights.json+++ b/scripts/serial-weights.json@@ -176,6 +176,7 @@"test/models-per-task-extract-atoms.serial.test.ts": 1,"test/models-probe-max-output-tokens.serial.test.ts": 17,"test/native-base-url-fold.serial.test.ts": 1,+ "test/observational-startup.serial.test.ts": 5,"test/openai-latest.serial.test.ts": 0,"test/ops-run-onboard-scope-gate.serial.test.ts": 0,"test/page-summary-length.serial.test.ts": 0,diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.jsonindex 83eb9d43e9..c25f76882e 100644--- a/scripts/ubicloud/weights.json+++ b/scripts/ubicloud/weights.json@@ -468,6 +468,7 @@"serial:test/models-probe-max-output-tokens.serial.test.ts": 7640,"serial:test/native-base-url-fold.serial.test.ts": 412,"serial:test/oauth-client-setup.serial.test.ts": 2129,+ "serial:test/observational-startup.serial.test.ts": 5000,"serial:test/openai-latest.serial.test.ts": 362,"serial:test/openclaw-context-engine-native.serial.test.ts": 335,"serial:test/ops-run-onboard-scope-gate.serial.test.ts": 566,diff --git a/src/cli.ts b/src/cli.tsindex 77feb9d737..b4efadddf7 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -1934,6 +1934,7 @@ function refuseThinClient(command: string, mcpUrl: string): never {/** Dispatcher-owned pieces the command modules under src/cli/commands/ receive (see CliDispatchContext). */const CLI_DISPATCH_CONTEXT: CliDispatchContext = {connectEngine,+ completeStartup: completeEngineStartup,dbMarkerBrainId,SELECTED_CONFIG_BY_ENGINE,cliModuleUrl: import.meta.url,@@ -2584,7 +2585,8 @@ async function connectCliOnlyEngine(command: string, args: string[]): Promise<Br// TODOS 1050, out of scope). Kill switch: GBRAIN_SERVE_DEGRADED=0.let engine: BrainEngine;try {- engine = await connectEngine({ probeOnly: command === 'jobs' && args[0] === 'supervisor' && args[1] === 'status' });+ // A4: an observational command connects probe-only and completes startup only after consent.+ engine = await connectEngine({ probeOnly: findCliCommand(command)?.startup === 'observational' || (command === 'jobs' && args[0] === 'supervisor' && args[1] === 'status') });} catch (serveConnectError) {if (command === 'jobs' && args[0] === 'child-readiness') {const { writeChildReadinessFailure } = await import('./core/minions/child-readiness.ts');@@ -2795,6 +2797,14 @@ async function connectEngine(opts?: { probeOnly?: boolean }): Promise<BrainEnginif (opts?.probeOnly === true) {return engine;}+ await completeEngineStartup(engine);+ return engine;+}++/** Startup after the probe-only connect: migrations, retired-marker cleanup, DB-plane config merge. Mounts: none. */+async function completeEngineStartup(engine: BrainEngine): Promise<void> {+ const config = SELECTED_CONFIG_BY_ENGINE.get(engine);+ if (!config || MOUNT_ENGINES.has(engine)) return;// v0.41.6.0 D4: race-tolerant CLI-side migration runner. Replaces the// pre-v0.41.6.0 `try { hasPendingMigrations && initSchema() } catch warn`@@ -2864,7 +2874,7 @@ async function connectEngine(opts?: { probeOnly?: boolean }): Promise<BrainEngin// was set); that coupled the gate to the field set and would silently// miss future DB-mutable gateway fields. One extra cache+shrinkState// clear per startup is microseconds, no hot path.- configureGateway(buildGatewayConfig(merged));+ (await import('./core/ai/gateway.ts')).configureGateway(buildGatewayConfig(merged));}// v0.31.12: re-resolve gateway defaults through resolveModel so// `models.tier.*` and `models.default` overrides apply to expansion +@@ -2875,8 +2885,6 @@ async function connectEngine(opts?: { probeOnly?: boolean }): Promise<BrainEngin} catch {// Non-fatal. Pre-v39 brains may not have a usable config table yet.}-- return engine;}/** CLI-only usage examples appended to `gbrain <command> --help`. */diff --git a/src/cli/command-table.ts b/src/cli/command-table.tsindex 7085a76e0e..f23e8d2014 100644--- a/src/cli/command-table.ts+++ b/src/cli/command-table.ts@@ -42,6 +42,8 @@ export type CliThinClientMode = 'none' | 'refuse' | 'route-then-refuse';/** What handleCliOnly hands a command module: the dispatcher-owned pieces a moved body used to close over. */export interface CliDispatchContext {connectEngine(opts?: { probeOnly?: boolean }): Promise<BrainEngine>;+ /** A4: finish startup (migrations, marker cleanup, config merge) on an observational command's engine once consent is granted. */+ completeStartup?(engine: BrainEngine): Promise<void>;dbMarkerBrainId(): string | undefined;SELECTED_CONFIG_BY_ENGINE: Pick<WeakMap<BrainEngine, GBrainConfig>, 'get'>;/** import.meta.url of src/cli.ts, for paths the moved bodies resolved relative to it. */diff --git a/test/observational-startup.serial.test.ts b/test/observational-startup.serial.test.tsnew file mode 100644index 0000000000..070a45a0fe--- /dev/null+++ b/test/observational-startup.serial.test.ts@@ -0,0 +1,155 @@+/**+ * A4 Tier 1 fixture: observational startup before consent.+ *+ * Protects: a command declaring `startup: 'observational'` connects probe-only+ * (no schema migrations, no retired-marker cleanup, no DB-plane config merge),+ * so when its consent check refuses, a brain with a pending migration keeps+ * its schema version. An authorized run completes startup through+ * `ctx.completeStartup` and the migration applies. The control proves the+ * fixture really has a pending migration that a normal startup applies.+ *+ * Seam: the real dispatcher (`__testing.main`) against a real on-disk PGLite+ * brain. The synthetic command is the `repair` record with `startup` set for+ * the test and its module replaced by a consent-gated handler (mock.module,+ * hence the serial lane).+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { LATEST_VERSION, hasPendingMigrations } from '../src/core/migrate.ts';+import { isConsentRefusal, printConsentRefusal, requireConsent } from '../src/core/consent.ts';+import { findCliCommand, type CliDispatchContext } from '../src/cli/command-table.ts';+import type { BrainEngine } from '../src/core/engine.ts';++const seen: { atHandler?: string | null; afterStartup?: string | null } = {};++mock.module('../src/cli/commands/repair.ts', () => ({+ run: async (engine: BrainEngine, args: string[], ctx: CliDispatchContext) => {+ seen.atHandler = await engine.getConfig('version');+ try {+ await requireConsent({+ command: 'repair', effects: ['paid'], actor: 'agent', what: 'gbrain repair', why: 'Synthetic paid work.',+ risk: 'Spends up to the cap.', user_message: 'Spend about $0.10?', argv: ['gbrain', 'repair'], est_usd: 0.1, args,+ }, { interactive: false, preapprovals: {}, note: () => {} });+ } catch (e) {+ if (isConsentRefusal(e)) process.exit(printConsentRefusal(e, { json: args.includes('--json') }));+ throw e;+ }+ await ctx.completeStartup?.(engine);+ seen.afterStartup = await engine.getConfig('version');+ },+}));++class ExitSignal extends Error {+ constructor(readonly code: number) { super(`process.exit(${code})`); }+}++const PENDING = String(LATEST_VERSION - 1);+const ENV_KEYS = ['HOME', 'GBRAIN_HOME', 'GBRAIN_DATABASE_URL', 'DATABASE_URL', 'GBRAIN_NO_RETRY_CONNECT'];+const savedEnv: Record<string, string | undefined> = {};+let home: string;+let brainPath: string;+let main: () => Promise<void>;+let stdout: string;++async function withBrain<T>(fn: (engine: PGLiteEngine) => Promise<T>): Promise<T> {+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite', database_path: brainPath });+ try {+ return await fn(engine);+ } finally {+ await engine.disconnect();+ }+}++async function run(argv: string[]): Promise<string> {+ const savedArgv = process.argv;+ process.argv = [savedArgv[0]!, 'gbrain', ...argv];+ try {+ await main();+ return 'returned';+ } catch (e) {+ if (e instanceof ExitSignal) return `exit:${e.code}`;+ throw e;+ } finally {+ process.argv = savedArgv;+ }+}++beforeAll(async () => {+ for (const k of ENV_KEYS) savedEnv[k] = process.env[k];+ home = mkdtempSync(join(tmpdir(), 'gbrain-observational-'));+ process.env.HOME = home;+ process.env.GBRAIN_HOME = home;+ delete process.env.GBRAIN_DATABASE_URL;+ delete process.env.DATABASE_URL;+ process.env.GBRAIN_NO_RETRY_CONNECT = '1';+ brainPath = join(home, '.gbrain', 'brain.pglite');+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: brainPath }, null, 2));+ await withBrain(engine => engine.initSchema());+ main = (await import('../src/cli.ts')).__testing.main;+});++afterAll(() => {+ for (const k of ENV_KEYS) {+ if (savedEnv[k] === undefined) delete process.env[k];+ else process.env[k] = savedEnv[k];+ }+ rmSync(home, { recursive: true, force: true });+});++let restores: Array<() => void> = [];+beforeEach(async () => {+ await withBrain(engine => engine.setConfig('version', PENDING));+ delete seen.atHandler;+ delete seen.afterStartup;+ stdout = '';+ const exit = spyOn(process, 'exit').mockImplementation(((code?: number) => { throw new ExitSignal(code ?? 0); }) as never);+ const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation((async () => { throw new TypeError('no network in this test'); }) as never);+ const write = spyOn(process.stdout, 'write').mockImplementation(((chunk: string | Uint8Array) => {+ stdout += typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk);+ return true;+ }) as never);+ const errWrite = spyOn(process.stderr, 'write').mockImplementation((() => true) as never);+ const quiet = (['log', 'error', 'warn'] as const).map(m => spyOn(console, m).mockImplementation(() => {}));+ restores = [() => exit.mockRestore(), () => fetchSpy.mockRestore(), () => write.mockRestore(), () => errWrite.mockRestore(), ...quiet.map(q => () => q.mockRestore())];+});++afterEach(() => {+ for (const r of restores) r();+ delete (findCliCommand('repair') as { startup?: string }).startup;+ process.exitCode = 0;+});++const markObservational = () => { (findCliCommand('repair') as { startup?: string }).startup = 'observational'; };++describe('observational startup before consent (pending-migration fixture)', () => {+ test('control: a normal post-connect command applies the pending migration before its handler', async () => {+ expect(await run(['repair', '--yes'])).toBe('returned');+ expect(seen.atHandler).toBe(String(LATEST_VERSION));+ expect(await withBrain(engine => engine.getConfig('version'))).toBe(String(LATEST_VERSION));+ });++ test('observational + refused consent: exit 3 with the payload, schema version unchanged', async () => {+ markObservational();+ expect(await run(['repair', '--json'])).toBe('exit:3');+ expect(seen.atHandler).toBe(PENDING);+ expect(seen.afterStartup).toBeUndefined();+ expect(JSON.parse(stdout)).toMatchObject({ status: 'confirmation_required', code: 'confirmation_required', effects: ['paid'] });+ await withBrain(async engine => {+ expect(await engine.getConfig('version')).toBe(PENDING);+ expect(await hasPendingMigrations(engine)).toBe(true);+ });+ });++ test('observational + authorized: startup completes after consent and the migration applies', async () => {+ markObservational();+ expect(await run(['repair', '--yes'])).toBe('returned');+ expect(seen.atHandler).toBe(PENDING);+ expect(seen.afterStartup).toBe(String(LATEST_VERSION));+ expect(await withBrain(engine => engine.getConfig('version'))).toBe(String(LATEST_VERSION));+ });+});