Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cli): refuse or route every engine-opening command on a thin client at connectEngine (#5950)
garrytance436c66f730
diff --git a/docs/architecture/key-files/entrypoints-and-docs.md b/docs/architecture/key-files/entrypoints-and-docs.mdindex b88b0de93e..10c9643be3 100644--- a/docs/architecture/key-files/entrypoints-and-docs.md+++ b/docs/architecture/key-files/entrypoints-and-docs.md@@ -117,10 +117,11 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/assets/wasm/` — 37 tree-sitter grammar WASMs + tree-sitter runtime. Committed to the repo so `bun --compile` embeds them deterministically via `import path from ... with { type: 'file' }`. The CI guard `scripts/check-wasm-embedded.sh` requires semantic TypeScript and Bash case-statement symbols in the compiled binary. Bash uses the official tree-sitter-bash v0.23.3 ABI-14 release asset, pinned by checksum in `scripts/vendor-bash-wasm.sh`; `src/assets/wasm/README.md` records provenance. Code chunker version 7 invalidates old content hashes; `gbrain sync --source <id> --full` revisits affected history in active repositories. `tree-sitter-sql.wasm` (DerekStride/tree-sitter-sql @ c2e1e08db1ea20dc23bdb8d228a81a8756e9c450, built with [email protected] --abi 14) adds SQL coverage at 11 MB — larger than peers because the grammar covers PostgreSQL + MySQL + SQLite + T-SQL basics (40 MB generated parser.c); the compiled binary grows ~6%.- `src/cli.ts` — generic thin-client mutation failures use the shared persistence reporter, retaining request IDs and typed JSON receipts while preserving SIGINT exit 130. `test/thin-client-write-errors.serial.test.ts` exercises real CLI timeout, cancellation, pending and conflict paths against a loopback MCP fixture. No-DB fallbacks announce themselves on stderr instead of degrading silently. `dream` dispatch binds the caught engine-connect error and emits `[dream] WARNING: could not connect to DB (...)` before falling through to filesystem-only phases; the `runDream(null, ...)` no-DB fallback is preserved (pinned by `test/cli-dream-engine-warn.test.ts`, 2 subprocess cases against good + bad DATABASE_URL). `doctor` dispatch does the same: when `connectEngine` OR the DB-backed `runDoctor` run throws, it emits `[doctor] DB-backed doctor run failed (...) — falling back to filesystem-only checks`, scrubbing the error message through BOTH `url-redact.ts:redactUrlsInText` and `redact-connection-info.ts:redactConnectionInfo` first, because doctor output is exactly what users paste into issues and CI logs (pinned by the fallback case in `test/doctor-minions-check.test.ts`: stderr note present, credentials absent, stdout stays parseable `--json`). `main()` opens with `await runCliPreflight()` (core/cli-preflight.ts: cwd-.env quarantine -> `~/.gbrain/.env` -> guardrails loader) before `parseGlobalFlags`; the former inline #3688 guardrails block lives in the preflight module.+ `connectEngine` is the thin-client backstop: on a config with `remote_mcp` and no `database_url` it refuses the dispatched command through `refuseThinClient` instead of building an engine, so a command without its own route never dies with "No database URL" or reads an empty in-memory PGLite. Handlers that already route over MCP (salience, anomalies, graph-query, whoknows, founder, and every recall form except an in-process `--query`/`--budget-tokens` call) run engine-free from `prepareConnectedDispatch`. Pinned by `test/thin-client-connect-engine-guard.test.ts`.Size 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`. 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`.+- `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, the `connectors` and `recall` refuse hints that only `connectEngine`'s thin-client backstop reaches (the static extractor reports them as never reached), `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/docs/architecture/thin-client.md b/docs/architecture/thin-client.mdindex 55b7e1f4ac..73a06a4955 100644--- a/docs/architecture/thin-client.md+++ b/docs/architecture/thin-client.md@@ -46,7 +46,9 @@ carries the routing-seam picture):- `src/cli.ts` — Routing seam INSIDE the existing op-dispatch path (noparallel `src/core/thin-client/` module; routing is a ~80-line conditionalin `runThinClientRouted`). Detects `isThinClient(cfg)` BEFORE `connectEngine`- so thin-client installs never open the empty PGLite. localOnly ops on+ so thin-client installs never open the empty PGLite; `connectEngine` itself+ refuses a host connect on a thin client with no `database_url`, so a command+ without its own route fails with its hint, never "No database URL". localOnly ops onthin-client refuse via `refuseThinClient` (with pinpoint hint table`THIN_CLIENT_REFUSE_HINTS`, which covers the full DB-bound command surface —sync, embed, extract, migrate, enrich, dream, jobs, sources, pages, files,@@ -70,13 +72,15 @@ carries the routing-seam picture):Full symbol-level detail: the `src/core/mcp-client.ts` entry in[`KEY_FILES.md`](./KEY_FILES.md).- `src/commands/recall.ts` — explicit `--budget-policy` calls bypass the local- engine in the CLI dispatcher and use the remote recall operation. The dispatcher- reuses the command's parser, so a query value that resembles a policy flag does- not activate this route. An explicit `--brain` is rejected as on the shared- thin route. `--source`/`--source-id`, environment and dotfile scope use the+ engine in the CLI dispatcher and use the remote recall operation, as do the+ fact-list forms (no `--query`/`--budget-tokens`). An in-process `--query` or+ `--budget-tokens` call without a policy is refused with a hint naming the+ policy flag. The dispatcher reuses the command's parser, so a query value that+ resembles a policy flag does not activate this route. An explicit `--brain` is+ rejected as on the shared thin route. `--source`/`--source-id`, environment and dotfile scope use theengine-free resolver; an explicit `default` is forwarded, not dropped.The host's declared `recall.source_id` narrows both arms through the existing- authorization resolver. Omitted-policy CLI behavior is unchanged.+ authorization resolver. Local omitted-policy CLI behavior is unchanged.- `src/core/cli-options.ts` — `parseGlobalFlags` supports `--timeout=Ns`(accepts `30s`, `2m`, `500ms`, plain ms). Default `null` = per-commanddefault (30s for most ops, 180s for `think`). `parseTimeout(s)` exporteddiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 00bb1d8df1..a3bdad4885 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 3131 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 formatResult+src/cli.ts 3162 ratchet +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +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/test-weights.json b/scripts/test-weights.jsonindex 52e9cb0c67..5e90315e82 100644--- a/scripts/test-weights.json+++ b/scripts/test-weights.json@@ -1942,6 +1942,7 @@"test/test-backends.test.ts": 1,"test/test-reads-source-smell.test.ts": 2296,"test/text-safe.test.ts": 7,+ "test/thin-client-connect-engine-guard.test.ts": 20000,"test/thin-client-launcher-routing.test.ts": 1455,"test/thin-client-routing-audit.test.ts": 46,"test/thin-client-routing.test.ts": 20,diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.jsonindex 6ff645778c..b90ed52af3 100644--- a/scripts/ubicloud/weights.json+++ b/scripts/ubicloud/weights.json@@ -2454,6 +2454,7 @@"unit:test/test-backends.test.ts": 161,"unit:test/test-reads-source-smell.test.ts": 364,"unit:test/text-safe.test.ts": 211,+ "unit:test/thin-client-connect-engine-guard.test.ts": 20000,"unit:test/thin-client-launcher-routing.test.ts": 1631,"unit:test/thin-client-routing-audit.test.ts": 163,"unit:test/thin-client-routing.test.ts": 343,diff --git a/src/cli.ts b/src/cli.tsindex cfa4fb4446..dfba8a3f6d 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -345,6 +345,7 @@ async function main() {if (command === 'ask') {command = 'query';}+ dispatchedCommand = command;// Local patch 2026-06-11 — mark one-shot CLI processes so the facts// backstop routes absorb work to the durable jobs worker instead of the@@ -1855,6 +1856,9 @@ const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {repair: 'repair runs on the brain host (it publishes coordinated page writes against the local engine). Run `gbrain repair` on the brain host.',projections: 'projections drain rebuilds text projections against the local engine. Run `gbrain projections drain` on the brain host.',quarantine: '`quarantine list` routes to the brain host automatically (quarantine_list MCP op). scan/clear are host-bound (bulk re-import; the clear trust decision) — run those on the host.',+ advisor: 'advisor ranks next actions from the host brain. Use the `advisor` MCP tool from your agent (when the host publishes it), or run `gbrain advisor` on the host.',+ export: 'export dumps the host brain to disk and has no MCP equivalent. Run `gbrain export` on the host, or read pages with the `get_page` MCP tool.',+ recall: '`recall --query`/`--budget-tokens` without `--budget-policy` runs the recall op locally. Add `--budget-policy facts_first` to send it to the brain host (`recall` MCP op).',};/**@@ -1866,16 +1870,23 @@ const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {function refuseThinClient(command: string, mcpUrl: string): never {const hint = THIN_CLIENT_REFUSE_HINTS[command];const message = hint- ? `\`gbrain ${command}\` is not routable from this thin client of ${mcpUrl}; run it on the brain host.`+ ? `\`gbrain ${command}\` is not routable (thin-client of ${mcpUrl}); run it on the brain host.`: `\`gbrain ${command}\` requires a local engine. This install is a thin client of ${mcpUrl}.`;exitCliError(opError('requires_local_engine', message,hint ?? `Run \`${command}\` on the remote host, or use the corresponding MCP tool from your agent.`, {...(hint ? { why: hint } : {}),- fix: { argv: ['gbrain', command], consent: [], actor: 'host_admin', requires_exclusive: false,+ fix: { argv: ['gbrain', command, ...thinRefusalSubcommand(command)], consent: [], actor: 'host_admin', requires_exclusive: false,why: 'The brain database lives on the brain host; this machine only forwards MCP calls.' },}), command);}+/** The refused invocation's subcommand word (id-shaped only, per A1 argv safety), for the host-side fix. */+function thinRefusalSubcommand(command: string): string[] {+ const argv = process.argv.slice(2);+ const next = argv[argv.indexOf(command) + 1] ?? '';+ return argv.includes(command) && /^[a-z][a-z0-9-]*$/.test(next) ? [next] : [];+}+const THIN_CLIENT_BRAIN_FLAG_MESSAGE = '--brain is not supported on a thin-client install: the remote server is a single brain.';/** Dispatcher-owned pieces the command modules under src/cli/commands/ receive (see CliDispatchContext). */@@ -2498,9 +2509,19 @@ async function prepareConnectedDispatch(command: string, args: string[]): Promis}}+ // These handlers already call their MCP twin on a thin client and never touch+ // the engine there; run them engine-free instead of opening one (#5102).+ if ((command === 'salience' || command === 'anomalies' || command === 'graph-query' || command === 'whoknows' || command === 'founder') &&+ isThinClient(loadConfig())) {+ await dispatchConnectedCommand(command, null as never, args);+ return null;+ }++ // Every recall form but an in-process --query/--budget-tokens call has a+ // thin-client path; that one reaches connectEngine, which refuses it.if (command === 'recall' && isThinClient(loadConfig())) {- const { hasRecallBudgetPolicy, runRecall } = await import('./commands/recall.ts');- if (hasRecallBudgetPolicy(args)) {+ const { recallNeedsLocalEngine, runRecall } = await import('./commands/recall.ts');+ if (!recallNeedsLocalEngine(args)) {if (getCliOptions().brain) exitCliError(usageError(THIN_CLIENT_BRAIN_FLAG_MESSAGE, 'Remove --brain, or run from a machine with local mounts (`gbrain mounts list`).'), command);await runRecall(null as never, args);return null;@@ -2658,6 +2679,9 @@ export { buildGatewayConfig };*/let activeBrainId: string = 'host';+/** The command main() dispatched; connectEngine's thin-client refusal names it. */+let dispatchedCommand = '';+/*** Connect to a mounted brain (brain axis, non-host). Routes through* BrainRegistry so:@@ -2721,6 +2745,13 @@ async function connectEngine(opts?: { probeOnly?: boolean }): Promise<BrainEngin}), cliCommandOf());}+ // A thin client has no local database. Every command that gets here would die+ // with "No database URL" (whose suggested init replaces remote_mcp) or answer+ // from an empty in-memory PGLite, so refuse with the routing hint (#5102).+ if (isThinClient(config) && !config.database_url) {+ refuseThinClient(dispatchedCommand, config.remote_mcp!.mcp_url);+ }+// Configure the AI gateway BEFORE engine connect — initSchema needs embedding dims.// Env is read once here; the gateway never reads process.env at call time (Codex C3).const { configureGateway } = await import('./core/ai/gateway.ts');diff --git a/src/cli/command-table.ts b/src/cli/command-table.tsindex 8552a68150..e601b9de12 100644--- a/src/cli/command-table.ts+++ b/src/cli/command-table.ts@@ -239,7 +239,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp// Post-connect: dispatched by dispatchConnectedCommand after connectEngine(), in master switch order.{ name: 'mcp', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/mcp.ts') },{ name: 'import', phase: 'post-connect', thinClient: 'none', load: () => import('./commands/import.ts') },- { name: 'export', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/export.ts') },+ { name: 'export', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/export.ts') },{ name: 'files', phase: 'post-connect', thinClient: 'refuse', load: () => import('./commands/files.ts') },{ name: 'embed', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/embed.ts') },{ name: 'serve', phase: 'post-connect', thinClient: 'refuse', load: () => import('./commands/serve.ts') },@@ -302,7 +302,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp{ name: 'salience', phase: 'post-connect', thinClient: 'none', load: () => import('./commands/salience.ts') },{ name: 'anomalies', phase: 'post-connect', thinClient: 'none', load: () => import('./commands/anomalies.ts') },{ name: 'status', phase: 'post-connect', thinClient: 'none', load: () => import('./commands/status.ts') },- { name: 'advisor', phase: 'post-connect', thinClient: 'none', load: () => import('./commands/advisor.ts') },+ { name: 'advisor', phase: 'post-connect', thinClient: 'refuse', load: () => import('./commands/advisor.ts') },{ name: 'conversation-parser', phase: 'post-connect', thinClient: 'none', load: () => import('./commands/conversation-parser.ts') },{ name: 'edges-backfill', phase: 'post-connect', thinClient: 'none', load: () => import('./commands/edges-backfill.ts') },// CLI_ONLY: #2035 class (wired the #3502 way): `case 'whoknows'` had a live handler (runWhoknows:diff --git a/src/commands/recall.ts b/src/commands/recall.tsindex 831da37e78..ec2ef96f0f 100644--- a/src/commands/recall.ts+++ b/src/commands/recall.ts@@ -163,8 +163,10 @@ function parseFlags(args: string[]): ParsedFlags {return out;}-export function hasRecallBudgetPolicy(args: string[]): boolean {- return parseFlags(args).budgetPolicy !== null;+/** Only `--query`/`--budget-tokens` without --budget-policy runs the recall op in-process; every other form has a thin-client path. */+export function recallNeedsLocalEngine(args: string[]): boolean {+ const flags = parseFlags(args);+ return flags.budgetPolicy === null && (flags.query !== null || flags.budgetTokens !== null);}function parseSinceParam(raw: string): Date | null {diff --git a/src/commands/schema.ts b/src/commands/schema.tsindex 4ed3af2d5e..02e02ff264 100644--- a/src/commands/schema.ts+++ b/src/commands/schema.ts@@ -53,7 +53,8 @@ import {import type { SchemaPackManifest, PackPrimitive } from '../core/schema-pack/manifest-v1.ts';import { PACK_PRIMITIVES } from '../core/schema-pack/manifest-v1.ts';import { bundledPackPath } from '../core/schema-pack/bundled-assets.ts';-import { gbrainPath, loadConfig, configPath, toEngineConfig, type GBrainConfig } from '../core/config.ts';+import { gbrainPath, loadConfig, configPath, toEngineConfig, isThinClient, type GBrainConfig } from '../core/config.ts';+import { opError } from '../core/ops/contract.ts';import { readDbSchemaPack } from '../core/schema-pack/best-effort.ts';import { sanitizeTypeForDisplay } from '../core/schema-pack/type-usage.ts';@@ -467,7 +468,14 @@ function parseFlags(args: string[]): ParsedFlags {async function withConnectedEngine<T>(fn: (engine: import('../core/engine.ts').BrainEngine) => Promise<T>): Promise<T> {const { createEngine } = await import('../core/engine-factory.ts');- const cfg = loadConfig() ?? { engine: 'pglite' as const };+ const cfg: GBrainConfig = loadConfig() ?? { engine: 'pglite' };+ // A thin client has no local database: refuse rather than die with "No+ // database URL" or read an empty in-memory PGLite (#5102).+ if (isThinClient(cfg) && !cfg.database_url) {+ throw opError('requires_local_engine',+ 'This `gbrain schema` subcommand reads the brain database, which lives on the brain host; it is not routable from a thin client.',+ 'Use the matching schema_* MCP tool (e.g. `schema_stats`) from your agent, or run it on the brain host.');+ }// PR #1321 (closed) defensive fix retained: build the EngineConfig once and// pass it to BOTH createEngine and engine.connect. The factory captures// config at construction; explicit re-pass at connect() is defense in depthdiff --git a/src/core/agent-output.ts b/src/core/agent-output.tsindex d459bc6773..f898c093f2 100644--- a/src/core/agent-output.ts+++ b/src/core/agent-output.ts@@ -493,7 +493,9 @@ const ROWS: Row[] = [protocol_version: d.protocol_version === 1 ? 1 : undefined,write_request: d.write_request, write_error: typeof d.write_error === 'string' ? d.write_error : undefined,notices: Array.isArray(d.notices) ? d.notices as Notice[] : undefined,- fix: d.fix && typeof d.fix === 'object' ? d.fix as Action : undefined,+ fix: d.fix && typeof d.fix === 'object' ? d.fix as Action+ : e.reason !== 'tool_error' ? { argv: ['gbrain', 'remote', 'doctor'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'remote doctor checks the remote brain URL, OAuth discovery and credentials from this machine.' } : undefined,};},},diff --git a/test/fixtures/goldens/cli/dispatch-phase.json b/test/fixtures/goldens/cli/dispatch-phase.jsonindex 73fdcfae93..1a701d250a 100644--- a/test/fixtures/goldens/cli/dispatch-phase.json+++ b/test/fixtures/goldens/cli/dispatch-phase.json@@ -8,7 +8,7 @@"hasSwitchCase": true,"phase": "post-connect","preConnectRules": [],- "thinClient": "none",+ "thinClient": "refuse","thinClientRoutedSubcommands": []},"agent": {@@ -31,7 +31,17 @@"anomalies": {"hasSwitchCase": true,"phase": "post-connect",- "preConnectRules": [],+ "preConnectRules": [+ {+ "condition": "(command === 'salience' || command === 'anomalies' || command === 'graph-query' || command === 'whoknows' || command === 'founder') && isThinClient(loadConfig())",+ "connectsEngine": false,+ "refusesThinClient": false,+ "routesThinClient": false,+ "terminates": true,+ "thinClientCheck": true,+ "unconditionalFor": []+ }+ ],"thinClient": "none","thinClientRoutedSubcommands": []},@@ -740,7 +750,7 @@"hasSwitchCase": true,"phase": "post-connect","preConnectRules": [],- "thinClient": "none",+ "thinClient": "refuse","thinClientRoutedSubcommands": []},"extract": {@@ -833,7 +843,17 @@"founder": {"hasSwitchCase": true,"phase": "post-connect",- "preConnectRules": [],+ "preConnectRules": [+ {+ "condition": "(command === 'salience' || command === 'anomalies' || command === 'graph-query' || command === 'whoknows' || command === 'founder') && isThinClient(loadConfig())",+ "connectsEngine": false,+ "refusesThinClient": false,+ "routesThinClient": false,+ "terminates": true,+ "thinClientCheck": true,+ "unconditionalFor": []+ }+ ],"thinClient": "none","thinClientRoutedSubcommands": []},@@ -897,7 +917,17 @@"graph-query": {"hasSwitchCase": true,"phase": "post-connect",- "preConnectRules": [],+ "preConnectRules": [+ {+ "condition": "(command === 'salience' || command === 'anomalies' || command === 'graph-query' || command === 'whoknows' || command === 'founder') && isThinClient(loadConfig())",+ "connectsEngine": false,+ "refusesThinClient": false,+ "routesThinClient": false,+ "terminates": true,+ "thinClientCheck": true,+ "unconditionalFor": []+ }+ ],"thinClient": "none","thinClientRoutedSubcommands": []},@@ -1488,7 +1518,17 @@"salience": {"hasSwitchCase": true,"phase": "post-connect",- "preConnectRules": [],+ "preConnectRules": [+ {+ "condition": "(command === 'salience' || command === 'anomalies' || command === 'graph-query' || command === 'whoknows' || command === 'founder') && isThinClient(loadConfig())",+ "connectsEngine": false,+ "refusesThinClient": false,+ "routesThinClient": false,+ "terminates": true,+ "thinClientCheck": true,+ "unconditionalFor": []+ }+ ],"thinClient": "none","thinClientRoutedSubcommands": []},@@ -1845,7 +1885,17 @@"whoknows": {"hasSwitchCase": true,"phase": "post-connect",- "preConnectRules": [],+ "preConnectRules": [+ {+ "condition": "(command === 'salience' || command === 'anomalies' || command === 'graph-query' || command === 'whoknows' || command === 'founder') && isThinClient(loadConfig())",+ "connectsEngine": false,+ "refusesThinClient": false,+ "routesThinClient": false,+ "terminates": true,+ "thinClientCheck": true,+ "unconditionalFor": []+ }+ ],"thinClient": "none","thinClientRoutedSubcommands": []}diff --git a/test/fixtures/goldens/cli/membership-sets.json b/test/fixtures/goldens/cli/membership-sets.jsonindex 1110dd7371..9f04050630 100644--- a/test/fixtures/goldens/cli/membership-sets.json+++ b/test/fixtures/goldens/cli/membership-sets.json@@ -63,7 +63,8 @@"cliOnlyWithoutHandler": [],"handlerNotInCliOnly": [],"refuseHintNeverReached": [- "connectors"+ "connectors",+ "recall"],"refusedNotInCliOnly": [],"refusedWithoutHint": [@@ -295,6 +296,7 @@"upgrade"],"THIN_CLIENT_REFUSED_COMMANDS": [+ "advisor","apply-migrations","call","code-callees",@@ -309,6 +311,7 @@"embeddings","enrich","eval",+ "export","extract","extract-conversation-facts","facts",@@ -332,6 +335,7 @@"watch"],"THIN_CLIENT_REFUSE_HINTS": [+ "advisor","apply-migrations","cache","call",@@ -348,6 +352,7 @@"embeddings","enrich","eval",+ "export","extract","extract-conversation-facts","facts",@@ -360,6 +365,7 @@"pricing","projections","quarantine",+ "recall","repair","repair-jsonb","retrieval-upgrade",diff --git a/test/fixtures/goldens/cli/thin-client-cases.json b/test/fixtures/goldens/cli/thin-client-cases.jsonindex 465706a76e..babd5f0455 100644--- a/test/fixtures/goldens/cli/thin-client-cases.json+++ b/test/fixtures/goldens/cli/thin-client-cases.json@@ -50,7 +50,9 @@"argv": "import","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain import` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain import",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -58,7 +60,10 @@"argv": "export","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain export` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain export",+ "Why: export dumps the host brain to disk and has no MCP equivalent. Run `gbrain export` on the host, or read pages with the `get_page` MCP tool.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -66,8 +71,10 @@"argv": "files","exitCode": 1,"stderr": [- "`gbrain files` is not routable. `files list` and `files url` MCP ops are localOnly (paths live on the host filesystem). Use `gbrain files` on the host machine.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain files` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain files",+ "Why: `files list` and `files url` MCP ops are localOnly (paths live on the host filesystem). Use `gbrain files` on the host machine.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -75,8 +82,10 @@"argv": "embed","exitCode": 1,"stderr": [- "`gbrain embed` is not routable. embed runs on the host. Run `gbrain embed` or `gbrain cycle` on the host machine.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain embed` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain embed",+ "Why: embed runs on the host. Run `gbrain embed` or `gbrain cycle` on the host machine.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -84,8 +93,10 @@"argv": "serve","exitCode": 1,"stderr": [- "`gbrain serve` is not routable. serve starts a server. Run on the host, not the thin client.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain serve` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain serve",+ "Why: serve starts a server. Run on the host, not the thin client.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -93,8 +104,10 @@"argv": "sweep","exitCode": 1,"stderr": [- "`gbrain sweep` is not routable. sweep runs the serve-resident maintenance passes against the LOCAL engine. Run it on the host (the serve process also runs it automatically).",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain sweep` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain sweep",+ "Why: sweep runs the serve-resident maintenance passes against the LOCAL engine. Run it on the host (the serve process also runs it automatically).",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -102,8 +115,10 @@"argv": "config","exitCode": 1,"stderr": [- "`gbrain config` is not routable. config reads/writes the host brain's config plane. Edit the host's .gbrain/config.json (file-plane keys) or run on the host with GBRAIN_HOME set. self_upgrade.* keys are machine-local and work here.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain config` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain config",+ "Why: config reads/writes the host brain's config plane. Edit the host's .gbrain/config.json (file-plane keys) or run on the host with GBRAIN_HOME set. self_upgrade.* keys are machine-local and work here.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -111,8 +126,10 @@"argv": "pricing","exitCode": 1,"stderr": [- "`gbrain pricing` is not routable. pricing registers model prices in the host brain's config and is trusted-local only (a remote caller could void a cost cap). Ask the brain's operator to run `gbrain pricing set <model> ...` on the host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain pricing` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain pricing",+ "Why: pricing registers model prices in the host brain's config and is trusted-local only (a remote caller could void a cost cap). Ask the brain's operator to run `gbrain pricing set <model> ...` on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -120,8 +137,10 @@"argv": "migrate","exitCode": 1,"stderr": [- "`gbrain migrate` is not routable. migrate runs on the host's local engine. Run on the host machine.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain migrate` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain migrate",+ "Why: migrate runs on the host's local engine. Run on the host machine.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -129,8 +148,10 @@"argv": "retrieval-upgrade","exitCode": 1,"stderr": [- "`gbrain retrieval-upgrade` is not routable. retrieval-upgrade (embedding migration) rebuilds the host brain's schema + re-embeds. Run on the host machine.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain retrieval-upgrade` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain retrieval-upgrade",+ "Why: retrieval-upgrade (embedding migration) rebuilds the host brain's schema + re-embeds. Run on the host machine.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -138,8 +159,10 @@"argv": "eval","exitCode": 1,"stderr": [- "`gbrain eval` is not routable. `eval` export/prune/replay touch the local engine and have no MCP equivalents. Run `gbrain eval` on the host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain eval` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain eval",+ "Why: `eval` export/prune/replay touch the local engine and have no MCP equivalents. Run `gbrain eval` on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -147,8 +170,10 @@"argv": "jobs","exitCode": 1,"stderr": [- "`gbrain jobs` is not routable. `jobs list`, `jobs get <id>`, and `jobs stats` are thin-client routable; this subcommand runs against the host queue. Use the submit_job / list_jobs / get_job / get_job_stats MCP tools from your agent, or run on the host with GBRAIN_HOME set.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain jobs` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain jobs",+ "Why: `jobs list`, `jobs get <id>`, and `jobs stats` are thin-client routable; this subcommand runs against the host queue. Use the submit_job / list_jobs / get_job / get_job_stats MCP tools from your agent, or run on the host with GBRAIN_HOME set.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -156,7 +181,9 @@"argv": "agent","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain agent` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain agent",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -164,7 +191,9 @@"argv": "book-mirror","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain book-mirror` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain book-mirror",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -172,8 +201,10 @@"argv": "sync","exitCode": 1,"stderr": [- "`gbrain sync` is not routable. sync runs on the host. Use the dedicated `sync_brain` MCP operation, or run `gbrain sync` on the host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain sync` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain sync",+ "Why: sync runs on the host. Use the dedicated `sync_brain` MCP operation, or run `gbrain sync` on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -181,8 +212,10 @@"argv": "extract","exitCode": 1,"stderr": [- "`gbrain extract` is not routable. extract runs on the host. Run `gbrain extract` or `gbrain cycle` on the host machine.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain extract` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain extract",+ "Why: extract runs on the host. Run `gbrain extract` or `gbrain cycle` on the host machine.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -190,8 +223,10 @@"argv": "extract-conversation-facts","exitCode": 1,"stderr": [- "`gbrain extract-conversation-facts` is not routable. extract-conversation-facts runs on the host (requires local engine + chat gateway). Run on the host machine.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain extract-conversation-facts` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain extract-conversation-facts",+ "Why: extract-conversation-facts runs on the host (requires local engine + chat gateway). Run on the host machine.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -199,8 +234,10 @@"argv": "enrich","exitCode": 1,"stderr": [- "`gbrain enrich` is not routable. enrich runs on the host (requires local engine + chat gateway for grounded synthesis). Run on the host machine.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain enrich` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain enrich",+ "Why: enrich runs on the host (requires local engine + chat gateway for grounded synthesis). Run on the host machine.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -208,7 +245,9 @@"argv": "features","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain features` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain features",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -216,23 +255,59 @@"argv": "autopilot","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain autopilot` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain autopilot",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},{"argv": "graph-query","exitCode": 1,- "stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"- ],- "stdout": []+ "stderr": [],+ "stdout": [+ "Usage: gbrain graph-query <slug> [options]",+ "",+ "Traverse the link graph from a page. Returns an indented tree of edges.",+ "Per-edge type filter: traversal only follows matching links.",+ "",+ "Options:",+ " --type <link_type> Filter to one link type (attended, works_at, invested_in,",+ " founded, advises, mentions, source).",+ " --depth <N> Max traversal depth (default 5).",+ " --direction <dir> 'out' (default), 'in', or 'both'.",+ " --source <id> Scope the walk to this source. Defaults to the",+ " resolved source (GBRAIN_SOURCE, .gbrain-source,",+ " path match, brain default); __all__ spans every",+ " source. An unknown source is a hard error. Local",+ " installs only: a thin client rejects it (the server",+ " scopes the walk to your grant).",+ " --include-foreign Include edges to pages in other sources (v0.37.7.0).",+ " Off by default; the walk stays inside the resolved",+ " source, and a footer reports the count of",+ " foreign-source edges hidden so users discover they exist.",+ " Not forwarded on a thin client.",+ " -h, --help Show this message.",+ "",+ "Examples:",+ " gbrain graph-query people/alice --type attended --depth 2",+ " -> who attended meetings with Alice (multi-hop)",+ " gbrain graph-query companies/acme --type works_at --direction in",+ " -> who works at Acme",+ " gbrain graph-query people/bob --depth 1",+ " -> Bob's direct connections",+ " gbrain graph-query people/bob --include-foreign",+ " -> include edges to pages in other sources",+ ""+ ]},{"argv": "reconcile-links","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain reconcile-links` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain reconcile-links",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -240,8 +315,10 @@"argv": "repair","exitCode": 1,"stderr": [- "`gbrain repair` is not routable. repair runs on the brain host (it publishes coordinated page writes against the local engine). Run `gbrain repair` on the brain host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain repair` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain repair",+ "Why: repair runs on the brain host (it publishes coordinated page writes against the local engine). Run `gbrain repair` on the brain host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -249,8 +326,10 @@"argv": "orphans","exitCode": 1,"stderr": [- "`gbrain orphans` is not routable. orphans needs the host's brain. Run on the host or use the `find_orphans` MCP tool from your agent.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain orphans` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain orphans",+ "Why: orphans needs the host's brain. Run on the host or use the `find_orphans` MCP tool from your agent.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -258,7 +337,9 @@"argv": "maintain","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain maintain` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain maintain",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -266,7 +347,9 @@"argv": "reindex","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain reindex` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain reindex",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -274,7 +357,9 @@"argv": "salience","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [unavailable]: OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?",+ "Fix: gbrain remote doctor",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#unavailable"],"stdout": []},@@ -282,7 +367,9 @@"argv": "anomalies","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [unavailable]: OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?",+ "Fix: gbrain remote doctor",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#unavailable"],"stdout": []},@@ -310,7 +397,10 @@"argv": "advisor","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain advisor` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain advisor",+ "Why: advisor ranks next actions from the host brain. Use the `advisor` MCP tool from your agent (when the host publishes it), or run `gbrain advisor` on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -342,15 +432,33 @@"argv": "edges-backfill","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain edges-backfill` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain edges-backfill",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},{"argv": "whoknows",- "exitCode": 1,+ "exitCode": 2,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "gbrain whoknows: topic argument required",+ "Usage: gbrain whoknows <topic> [options]",+ "",+ "Ask your brain who knows about a topic. Returns ranked person/company",+ "pages by expertise depth, relationship recency, and salience.",+ "",+ "Options:",+ " --limit N Max results (default 5)",+ " --explain Show the ranking factor breakdown per result",+ " --json JSON output for agents",+ " --help, -h Show this help",+ "",+ "Examples:",+ " gbrain whoknows \"lab automation\"",+ " gbrain whoknows fintech compliance --explain",+ " gbrain whoknows \"ai agents\" --limit 10 --json",+ ""],"stdout": []},@@ -358,7 +466,9 @@"argv": "brainstorm","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain brainstorm` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain brainstorm",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -366,7 +476,9 @@"argv": "lsd","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain lsd` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain lsd",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -374,7 +486,9 @@"argv": "skillopt","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain skillopt` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain skillopt",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -382,7 +496,9 @@"argv": "calibration","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain calibration` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain calibration",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -390,8 +506,10 @@"argv": "transcripts","exitCode": 1,"stderr": [- "`gbrain transcripts` is not routable. transcripts is server-private (raw chat exports stay on the host). Read transcripts on the host machine.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain transcripts` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain transcripts",+ "Why: transcripts is server-private (raw chat exports stay on the host). Read transcripts on the host machine.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -399,7 +517,9 @@"argv": "models","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain models` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain models",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -407,8 +527,10 @@"argv": "takes","exitCode": 1,"stderr": [- "`gbrain takes` is not routable. takes list/search/scorecard/calibration + add/update/resolve/supersede route to the brain host automatically (takes_* MCP ops). This subcommand (extract/revisit) is host-bound: run it on the host machine.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain takes` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain takes",+ "Why: takes list/search/scorecard/calibration + add/update/resolve/supersede route to the brain host automatically (takes_* MCP ops). This subcommand (extract/revisit) is host-bound: run it on the host machine.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -416,7 +538,9 @@"argv": "onboard","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain onboard` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain onboard",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -424,7 +548,24 @@"argv": "founder","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Unknown founder subcommand: (none). Did you mean \"founder scorecard\"?",+ "",+ "Usage: gbrain founder scorecard <entity-slug> [options]",+ "",+ "Rolls up the entity's typed-claim trajectory + resolved-take outcomes into",+ "the four founder-evaluation metrics: claim accuracy, consistency, growth",+ "trajectory, red flags.",+ "",+ "Options:",+ " --since YYYY-MM-DD Lower bound on valid_from / take created_at (default: 1 year ago)",+ " --until YYYY-MM-DD Upper bound (default: today)",+ " --json JSON output (stable schema_version: 1)",+ " --help, -h Show this help",+ "",+ "Examples:",+ " gbrain founder scorecard companies/acme-example",+ " gbrain founder scorecard companies/acme-example --since 2025-05-17 --json",+ ""],"stdout": []},@@ -468,7 +609,9 @@"argv": "recall","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [unavailable]: OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?",+ "Fix: gbrain remote doctor",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#unavailable"],"stdout": []},@@ -476,7 +619,9 @@"argv": "notability-eval","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain notability-eval` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain notability-eval",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -484,8 +629,10 @@"argv": "sources","exitCode": 1,"stderr": [- "`gbrain sources` is not routable. sources commands manage local DB + config rows. Per-subcommand thin-client routing lands in v0.31.x. For now: use `sources_list` / `sources_status` MCP tools, or run on the host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain sources` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain sources",+ "Why: sources commands manage local DB + config rows. Per-subcommand thin-client routing lands in v0.31.x. For now: use `sources_list` / `sources_status` MCP tools, or run on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -493,7 +640,9 @@"argv": "waiting","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain waiting` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain waiting",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -501,7 +650,9 @@"argv": "loops","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain loops` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain loops",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -509,7 +660,10 @@"argv": "connectors","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain connectors` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain connectors",+ "Why: connectors manage provider session credentials in ~/.gbrain/connectors and sync your chat history on the host. Credentials never cross the wire — run on the host machine.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -517,8 +671,10 @@"argv": "pages","exitCode": 1,"stderr": [- "`gbrain pages` is not routable. `pages purge-deleted` is admin+localOnly (hard-deletes from the local DB). Run on the host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain pages` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain pages",+ "Why: `pages purge-deleted` is admin+localOnly (hard-deletes from the local DB). Run on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -526,8 +682,10 @@"argv": "quarantine","exitCode": 1,"stderr": [- "`gbrain quarantine` is not routable. `quarantine list` routes to the brain host automatically (quarantine_list MCP op). scan/clear are host-bound (bulk re-import; the clear trust decision) — run those on the host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain quarantine` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain quarantine",+ "Why: `quarantine list` routes to the brain host automatically (quarantine_list MCP op). scan/clear are host-bound (bulk re-import; the clear trust decision) — run those on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -535,8 +693,9 @@"argv": "watch","exitCode": 1,"stderr": [- "`gbrain watch` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",- "Run `watch` on the remote host, or use the corresponding MCP tool from your agent."+ "Error [requires_local_engine]: `gbrain watch` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain watch",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -544,8 +703,10 @@"argv": "storage","exitCode": 1,"stderr": [- "`gbrain storage` is not routable. storage operates on the local repo on disk. Run on the host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain storage` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain storage",+ "Why: storage operates on the local repo on disk. Run on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -553,8 +714,10 @@"argv": "code-def","exitCode": 1,"stderr": [- "`gbrain code-def` is not routable. `code-def` needs symbol-aware lookup that has no MCP op yet. Run on the host or use `search` from your agent with a symbol-shaped query.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain code-def` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain code-def",+ "Why: `code-def` needs symbol-aware lookup that has no MCP op yet. Run on the host or use `search` from your agent with a symbol-shaped query.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -562,8 +725,10 @@"argv": "code-refs","exitCode": 1,"stderr": [- "`gbrain code-refs` is not routable. `code-refs` has no MCP op yet. Run on the host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain code-refs` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain code-refs",+ "Why: `code-refs` has no MCP op yet. Run on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -571,7 +736,9 @@"argv": "reindex-code","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain reindex-code` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain reindex-code",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -579,7 +746,9 @@"argv": "reindex-search-vector","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain reindex-search-vector` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain reindex-search-vector",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -587,7 +756,9 @@"argv": "reindex-frontmatter","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain reindex-frontmatter` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain reindex-frontmatter",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -595,7 +766,9 @@"argv": "backfill","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain backfill` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain backfill",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -603,8 +776,10 @@"argv": "code-callers","exitCode": 1,"stderr": [- "`gbrain code-callers` is not routable. `code-callers` has no MCP op yet. Run on the host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain code-callers` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain code-callers",+ "Why: `code-callers` has no MCP op yet. Run on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -612,8 +787,10 @@"argv": "code-callees","exitCode": 1,"stderr": [- "`gbrain code-callees` is not routable. `code-callees` has no MCP op yet. Run on the host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain code-callees` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain code-callees",+ "Why: `code-callees` has no MCP op yet. Run on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -621,7 +798,9 @@"argv": "repos","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [requires_local_engine]: `gbrain repos` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",+ "Fix: gbrain repos",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []}diff --git a/test/fixtures/goldens/cli/thin-client-routing.json b/test/fixtures/goldens/cli/thin-client-routing.jsonindex 5f6b00cf87..22c5e53b37 100644--- a/test/fixtures/goldens/cli/thin-client-routing.json+++ b/test/fixtures/goldens/cli/thin-client-routing.json@@ -4,7 +4,9 @@"argv": "takes list","exitCode": 1,"stderr": [- "OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?"+ "Error [unavailable]: OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?",+ "Fix: gbrain remote doctor",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#unavailable"],"stdout": []},@@ -12,8 +14,10 @@"argv": "takes extract","exitCode": 1,"stderr": [- "`gbrain takes` is not routable. takes list/search/scorecard/calibration + add/update/resolve/supersede route to the brain host automatically (takes_* MCP ops). This subcommand (extract/revisit) is host-bound: run it on the host machine.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain takes` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain takes",+ "Why: takes list/search/scorecard/calibration + add/update/resolve/supersede route to the brain host automatically (takes_* MCP ops). This subcommand (extract/revisit) is host-bound: run it on the host machine.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -29,7 +33,9 @@"argv": "cache stats","exitCode": 1,"stderr": [- "OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?"+ "Error [unavailable]: OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?",+ "Fix: gbrain remote doctor",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#unavailable"],"stdout": []},@@ -37,8 +43,10 @@"argv": "cache clear","exitCode": 1,"stderr": [- "`gbrain cache` is not routable. `cache stats` routes to the brain host automatically (cache_stats MCP op). clear/prune mutate the host cache — run those on the host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain cache` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain cache",+ "Why: `cache stats` routes to the brain host automatically (cache_stats MCP op). clear/prune mutate the host cache — run those on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -46,7 +54,9 @@"argv": "quarantine list","exitCode": 1,"stderr": [- "OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?"+ "Error [unavailable]: OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?",+ "Fix: gbrain remote doctor",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#unavailable"],"stdout": []},@@ -54,8 +64,10 @@"argv": "quarantine scan","exitCode": 1,"stderr": [- "`gbrain quarantine` is not routable. `quarantine list` routes to the brain host automatically (quarantine_list MCP op). scan/clear are host-bound (bulk re-import; the clear trust decision) — run those on the host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain quarantine` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain quarantine",+ "Why: `quarantine list` routes to the brain host automatically (quarantine_list MCP op). scan/clear are host-bound (bulk re-import; the clear trust decision) — run those on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -63,7 +75,9 @@"argv": "jobs list","exitCode": 1,"stderr": [- "OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?"+ "Error [unavailable]: OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?",+ "Fix: gbrain remote doctor",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#unavailable"],"stdout": []},@@ -71,7 +85,9 @@"argv": "jobs get 1","exitCode": 1,"stderr": [- "OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?"+ "Error [unavailable]: OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?",+ "Fix: gbrain remote doctor",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#unavailable"],"stdout": []},@@ -79,7 +95,9 @@"argv": "jobs stats","exitCode": 1,"stderr": [- "OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?"+ "Error [unavailable]: OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?",+ "Fix: gbrain remote doctor",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#unavailable"],"stdout": []},@@ -87,8 +105,10 @@"argv": "jobs work","exitCode": 1,"stderr": [- "`gbrain jobs` is not routable. `jobs list`, `jobs get <id>`, and `jobs stats` are thin-client routable; this subcommand runs against the host queue. Use the submit_job / list_jobs / get_job / get_job_stats MCP tools from your agent, or run on the host with GBRAIN_HOME set.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain jobs` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain jobs",+ "Why: `jobs list`, `jobs get <id>`, and `jobs stats` are thin-client routable; this subcommand runs against the host queue. Use the submit_job / list_jobs / get_job / get_job_stats MCP tools from your agent, or run on the host with GBRAIN_HOME set.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -96,7 +116,9 @@"argv": "search modes","exitCode": 1,"stderr": [- "OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?"+ "Error [unavailable]: OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?",+ "Fix: gbrain remote doctor",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#unavailable"],"stdout": []},@@ -104,8 +126,10 @@"argv": "search diagnose q","exitCode": 1,"stderr": [- "`gbrain search` is not routable. `search modes|stats|tune` route to the brain host automatically (search_modes / search_stats / search_tune MCP ops). The modes reset form, modes with the source flag (the reset dry-run), and tune apply mutate or preview host config, and `diagnose` runs live retrieval — run those on the host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain search` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain search",+ "Why: `search modes|stats|tune` route to the brain host automatically (search_modes / search_stats / search_tune MCP ops). The modes reset form, modes with the source flag (the reset dry-run), and tune apply mutate or preview host config, and `diagnose` runs live retrieval — run those on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -113,8 +137,10 @@"argv": "sources list","exitCode": 1,"stderr": [- "`gbrain sources` is not routable. sources commands manage local DB + config rows. Per-subcommand thin-client routing lands in v0.31.x. For now: use `sources_list` / `sources_status` MCP tools, or run on the host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain sources` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain sources",+ "Why: sources commands manage local DB + config rows. Per-subcommand thin-client routing lands in v0.31.x. For now: use `sources_list` / `sources_status` MCP tools, or run on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -122,8 +148,10 @@"argv": "sources add alice-example","exitCode": 1,"stderr": [- "`gbrain sources` is not routable. sources commands manage local DB + config rows. Per-subcommand thin-client routing lands in v0.31.x. For now: use `sources_list` / `sources_status` MCP tools, or run on the host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain sources` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain sources",+ "Why: sources commands manage local DB + config rows. Per-subcommand thin-client routing lands in v0.31.x. For now: use `sources_list` / `sources_status` MCP tools, or run on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -149,8 +177,10 @@"argv": "call get_page","exitCode": 1,"stderr": [- "`gbrain call` is not routable. `call` dispatches against a local engine. Use the named CLI command or an authorized MCP tool through your agent, or run `gbrain call` on the host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain call` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain call",+ "Why: `call` dispatches against a local engine. Use the named CLI command or an authorized MCP tool through your agent, or run `gbrain call` on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -166,8 +196,10 @@"argv": "eval whoknows","exitCode": 1,"stderr": [- "`gbrain eval` is not routable. `eval` export/prune/replay touch the local engine and have no MCP equivalents. Run `gbrain eval` on the host.",- "(thin-client of http://127.0.0.1:1/mcp)"+ "Error [requires_local_engine]: `gbrain eval` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",+ "Fix: gbrain eval",+ "Why: `eval` export/prune/replay touch the local engine and have no MCP equivalents. Run `gbrain eval` on the host.",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"],"stdout": []},@@ -199,7 +231,9 @@"argv": "think q","exitCode": 1,"stderr": [- "OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?"+ "Error [unavailable]: OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?",+ "Fix: gbrain remote doctor",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#unavailable"],"stdout": []},@@ -207,7 +241,9 @@"argv": "recall q","exitCode": 1,"stderr": [- "No database URL: database_url is missing from config. Fix: Run gbrain init --supabase or gbrain init --url <connection_string>"+ "Error [unavailable]: OAuth discovery failed: OAuth discovery network error: Unable to connect. Is the computer able to access the url?",+ "Fix: gbrain remote doctor",+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#unavailable"],"stdout": []},diff --git a/test/recall-budget-policy-thin-cli.test.ts b/test/recall-budget-policy-thin-cli.test.tsindex dcf30234d5..f9669fcaf7 100644--- a/test/recall-budget-policy-thin-cli.test.ts+++ b/test/recall-budget-policy-thin-cli.test.ts@@ -92,7 +92,7 @@ test.each([test('a query value spelling the policy flag does not opt a legacy thin call into new routing', async () => {const result = await thinCall('postgres', ['--query', '--budget-policy', '--json']);expect(result.exitCode).toBe(1);- expect(result.stderr).toContain('database_url is missing');+ expect(result.stderr).toContain('`gbrain recall` is not routable');expect(result.calls).toEqual([]);expect(result.localStoreCreated).toBe(false);});diff --git a/test/thin-client-connect-engine-guard.test.ts b/test/thin-client-connect-engine-guard.test.tsnew file mode 100644index 0000000000..7263240bc5--- /dev/null+++ b/test/thin-client-connect-engine-guard.test.ts@@ -0,0 +1,130 @@+/**+ * Thin-client installs (remote_mcp set, no database_url) must never fall+ * through to the local engine (#5102). A command that does died with+ * "No database URL ... Fix: Run gbrain init --supabase", and following that+ * hint replaces the remote config; a PGLite-keyed thin client instead opened+ * an empty in-memory brain and answered from it.+ *+ * Covers: every post-connect CLI-only command the table does not refuse+ * either routes or refuses (the connectEngine backstop closes the class for+ * commands added later); the handlers that already carry a thin-client+ * branch reach their MCP op engine-free; the rest refuse with a hint.+ *+ * Nothing leaves the machine: the unreachable rows point at 127.0.0.1:9 and+ * the routed rows at a loopback OAuth + MCP fixture.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { CLI_COMMANDS } from '../src/cli/command-table.ts';+import { runCliBatch, type CliResult } from './helpers/cli-spawn.ts';++const ENV = { GBRAIN_REMOTE_CLIENT_SECRET: undefined, GBRAIN_NO_BANNER: '1', GBRAIN_SOURCE: undefined, GBRAIN_BRAIN_ID: 'host' };+const NO_DATABASE = /No database URL|database_url is missing/;+const SCRATCH_STORE = /Setting up brain schema|migration\(s\) applied/;+const homes: string[] = [];++function thinHome(engine: 'postgres' | 'pglite', base: string): string {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-thin-guard-'));+ homes.push(home);+ mkdirSync(join(home, '.gbrain'));+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine, remote_mcp: {+ issuer_url: base, mcp_url: `${base}/mcp`, oauth_client_id: 'fixture', oauth_client_secret: 'fixture',+ } }));+ return home;+}++function run(rows: string[][], home: string): Promise<CliResult[]> {+ return runCliBatch(rows, { home, cwd: home, env: ENV, timeoutMs: 30_000 });+}++afterAll(() => { for (const home of homes) rmSync(home, { recursive: true, force: true }); });++describe('no post-connect command reaches the local engine on a thin client', () => {+ const rows = CLI_COMMANDS.filter(c => c.phase === 'post-connect' && c.thinClient === 'none').map(c => [c.name]);+ let results: CliResult[];++ beforeAll(async () => {+ results = await run(rows, thinHome('postgres', 'http://127.0.0.1:9'));+ }, 180_000);++ test('the table still has unrefused post-connect commands to check', () => {+ expect(rows.length).toBeGreaterThan(20);+ });++ test('none of them dies asking for a database URL', () => {+ const fellThrough = rows.filter((_, i) => NO_DATABASE.test(results[i]!.stdout + results[i]!.stderr)).map(r => r[0]);+ expect(fellThrough).toEqual([]);+ });+});++describe('self-routing handlers reach their MCP op without opening an engine', () => {+ const calls: string[] = [];+ const replies: Record<string, unknown> = {+ get_recent_salience: [], find_anomalies: [], traverse_graph: [], find_experts: [],+ find_trajectory: { points: [] }, recall: { facts: [], total: 0 },+ };+ let server: ReturnType<typeof Bun.serve>;+ const routed: Array<[string[], string]> = [+ [['salience'], 'get_recent_salience'],+ [['anomalies'], 'find_anomalies'],+ [['graph-query', 'example-page'], 'traverse_graph'],+ [['whoknows', 'example topic'], 'find_experts'],+ [['founder', 'scorecard', 'example-co'], 'find_trajectory'],+ [['recall', '--grep', 'needle', '--json'], 'recall'],+ ];++ beforeAll(() => {+ server = Bun.serve({ hostname: '127.0.0.1', port: 0, async fetch(request): Promise<Response> {+ const path = new URL(request.url).pathname;+ const base = `http://127.0.0.1:${server.port}`;+ if (path === '/.well-known/oauth-authorization-server') return Response.json({ issuer: base, token_endpoint: `${base}/token` });+ if (path === '/token') return Response.json({ access_token: 'fixture', token_type: 'bearer', expires_in: 3600, scope: 'read' });+ if (path !== '/mcp' || request.method !== 'POST') return new Response(null, { status: 405 });+ const body = await request.json() as { id?: number; method: string; params?: { protocolVersion?: string; name?: string } };+ if (body.id === undefined) return new Response(null, { status: 202 });+ if (body.method === 'initialize') return Response.json({ jsonrpc: '2.0', id: body.id, result: {+ protocolVersion: body.params?.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'fixture', version: '1' },+ } });+ const name = body.params?.name ?? '';+ calls.push(name);+ return Response.json({ jsonrpc: '2.0', id: body.id, result: { content: [{ type: 'text', text: JSON.stringify(replies[name] ?? {}) }] } });+ } });+ });++ afterAll(async () => { await server.stop(true); });++ for (const engine of ['postgres', 'pglite'] as const) {+ test(`${engine}-keyed thin client: each command calls its op and exits 0`, async () => {+ calls.length = 0;+ const results = await run(routed.map(([argv]) => argv), thinHome(engine, `http://127.0.0.1:${server.port}`));+ results.forEach((r, i) => {+ const output = r.stdout + r.stderr;+ expect({ argv: routed[i]![0], code: r.exitCode, output: NO_DATABASE.test(output) || SCRATCH_STORE.test(output) })+ .toEqual({ argv: routed[i]![0], code: 0, output: false });+ });+ expect([...calls].sort()).toEqual(routed.map(([, op]) => op).sort());+ }, 120_000);+ }+});++describe('commands with no engine-free path refuse with a pinpoint hint', () => {+ const refused: Array<[string[], string]> = [+ [['advisor'], '`advisor` MCP tool'],+ [['export'], 'Run `gbrain export` on the host'],+ [['recall', '--query', 'example'], '--budget-policy facts_first'],+ [['schema', 'stats'], 'schema_stats'],+ ];++ for (const engine of ['postgres', 'pglite'] as const) {+ test(`${engine}-keyed thin client`, async () => {+ const results = await run(refused.map(([argv]) => argv), thinHome(engine, 'http://127.0.0.1:9'));+ results.forEach((r, i) => {+ expect({ argv: refused[i]![0], code: r.exitCode, hinted: r.stderr.includes(refused[i]![1]) })+ .toEqual({ argv: refused[i]![0], code: 1, hinted: true });+ expect(r.stdout + r.stderr).not.toMatch(SCRATCH_STORE);+ });+ }, 120_000);+ }+});