Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(connect): --install and sources connect ask through the consent primitive (C2)
garrytanc9c81286a81c
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex 9642b10df2..7d5a421c44 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -37,6 +37,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/code-scope.ts` — shared `--source`/`--all-sources` resolution for the four code-* CLI commands (code-def, code-refs, code-callers, code-callees), extracted so the four can't drift. `positionalArgs` skips value-taking flags AND their values (`--source`, `--limit`, `--lang` — a naive scan looked up the flag's value as the symbol); inline `name=value` spellings are one token and consume nothing. A bad `.gbrain-source`/`GBRAIN_SOURCE` pin is recognized through the shared `isResolverUserError` predicate (exported by `src/core/source-resolver.ts`, next to the messages it matches) and exits 2 with a clean `invalid_source_pin` envelope instead of an uncaught stack. Also exports `pushSourcePredicate(params, opts)`, the source-scope SQL fragment builder code-def/code-refs share.-- `src/commands/connect.ts` + `src/core/connect-probe.ts` — `gbrain connect <mcp-url> [--token <bearer>]` one-command coding-agent onboarding from a bearer token. Turns an MCP URL + token into a paste-ready `claude mcp add ... -H "Authorization: Bearer ..."` block (default) or, with `--install`, runs it directly and smoke-tests the token. Direct HTTP MCP — Claude Code talks straight to a remote `gbrain serve --http`, no local install needed. Token resolution: `--token` > `$GBRAIN_REMOTE_TOKEN` > placeholder (print) / error (install). The generated block tells the agent to call `get_brain_identity` + `list_skills` (the `LEARN_INSTRUCTION` export, which names `capture` — a starter-surface MCP op — alongside `put_page` for full-control writes) with a core-tools fallback for hosts without skill publishing. URL normalization appends `/mcp` to a bare host but REJECTS a scheme-less host; the pure registration helpers (`normalizeMcpUrl`, `isLinkLocalOrMetadata`, `buildClaudeMcpAddArgv` with its optional scope param — claude's default is `local`, so the harness lane passes `user` explicitly — `buildCodexMcpAddArgv`, `validateToken`, `redactToken`, `shellQuote`/`cmdString`, `issuerFromMcpUrl`, the `OAUTH_SECRET_NOTE` secret-hygiene constant, and `openclawThinClientBlock` — the honest openclaw wiring print: a scoped `gbrain init --mcp-only` thin-client block, deliberately NOT a stdio mcpServers config since that grants full local DB access) live in `src/core/mcp-registration.ts` (core must not import from commands; connect.ts re-exports them — `OAUTH_SECRET_NOTE` included — so its surface and tests are unchanged) and are unit-tested. Flags: `--token`, `--name <id>` (default `gbrain`, validated against `NAME_RE`), `--agent claude-code|codex|opencode|perplexity|generic`, `--install`, `--yes` (required for `--install` in non-TTY), `--force`, `--json` (token redacted unless `--show-token`), `--timeout-ms`. `connect` is in `CLI_ONLY` + `CLI_ONLY_SELF_HELP`; dispatched in `cli.ts:handleCliOnly` with no local DB connect. `AGENT_SPECS` drives per-agent rendering + `--install`: `claude-code` → `buildClaudeMcpAddArgv` (literal `-H "Authorization: Bearer <tok>"`); `codex` → `buildCodexMcpAddArgv` = `codex mcp add <name> --url <url> --bearer-token-env-var GBRAIN_REMOTE_TOKEN` (on the CONNECT lane Codex reads the token from the env var at runtime, never written to config — the harness lane in `src/core/bootstrap/harness.ts` is the deliberate exception, writing a managed block with the inline `http_headers = { Authorization = "Bearer <t>" }` credential (codex-cli >=0.149 rejects inline `bearer_token` for streamable_http at config load) because framework-spawned codex inherits no shell profile; `--install` runs it and prints an `export GBRAIN_REMOTE_TOKEN` hint when missing); `opencode` → `buildOpencodeMcpAddArgv` = `opencode mcp add <name> --url <url> --header "Authorization=Bearer {env:GBRAIN_REMOTE_TOKEN}"` (the interpolation is stored LITERALLY and resolved by opencode at read time — token never in argv/config/--json; `--install` writes the entry directly through `ConnectDeps.writeOpencodeRemoteEntry` → `opencode-json.ts` in env token mode, no binary required; `--force` maps to the writer's `allowReplaceOtherSource` so an OURS entry at an old url — a rotated serve — is replaceable, mirroring the exec lanes' `--force` semantics, while foreign same-name entries still refuse with url-appropriate copy: pick `--name`); `perplexity` + `generic` are `installable:false` and reject `--install`. `--oauth` (`supportsOAuth:true` = perplexity/generic only) emits an OAuth 2.1 client-credentials connector block (Issuer URL via `issuerFromMcpUrl` = mcp-url minus `/mcp`, Client ID, Client Secret) — least-privilege scopes + short-lived rotating tokens vs a long-lived full-access secret. Creds from `--client-id`/`--client-secret` (BYO) or `--register` (`deps.registerOAuthClient` shells `gbrain auth register-client <name> --grant-types client_credentials --scopes <DEFAULT_SCOPES="read write"> --token-endpoint-auth-method client_secret_post` and parses `Client ID:`/`Client Secret:`); `--oauth` rejected for claude-code/codex and incompatible with `--install`. `buildJson` is a generic shape (`agent`, `command`/`command_argv` null for perplexity/generic, `header`, `env_var`, oauth fields with redaction); the codex `command` carries only the env-var name, never the token. `cmdString(binary, argv)` POSIX-single-quotes args. `ConnectDeps` = `{isTTY, promptYesNo, hasBinary(bin), runBinary(bin, argv), probe, env(name), registerOAuthClient, writeOpencodeRemoteEntry}` — binary-generic so `claude` and `codex` share the exec path while opencode rides the writer member; `env` injectable for tests. Security: rendered command single-quotes the token so shell metacharacters can't run code when pasted; token validated before it lands in an HTTP header; link-local / cloud-metadata addresses (incl. IPv4-mapped IPv6 `::ffff:169.254.x.x` and AWS IMDSv2-over-IPv6 `fd00:ec2::254`) refused as a token-exfil guard while localhost/RFC1918/LAN stay allowed; token redacted from all error output. `src/core/connect-probe.ts` is the raw-bearer MCP smoke probe backing `--install`: connects the official MCP SDK `Client` over `StreamableHTTPClientTransport` with a STATIC `Authorization` header (no OAuth/discovery — distinct from `mcp-client.ts:callRemoteTool` which is OAuth-only and `remote-mcp-probe.ts:smokeTestMcp` which only sends `initialize`), runs the full `initialize` handshake via `client.connect()`, then calls `get_brain_identity` (read-scope, non-localOnly) to prove a tool call round-trips. Never throws — every failure maps to `{ ok: false, reason: 'auth' | 'unreachable' | 'timeout' | 'tool_error' | 'unknown', message }` so a wrong/expired token fails at setup, not on the agent's first request. `DEFAULT_PROBE_TIMEOUT_MS = 15_000` shared with `connect.ts`. `serve-http.ts` adds exported pure `skillPublishStatus(publishSkills)` for the startup banner `Skills: published / not published` line + a one-line `gbrain config set mcp.publish_skills true` stderr nudge when publishing is OFF. Docs: `docs/mcp/CODEX.md`, `docs/mcp/PERPLEXITY.md`, `docs/mcp/CLAUDE_CODE.md`, `docs/tutorials/connect-coding-agent.md`. Pinned by `test/connect.test.ts` (pure-helper + render, all five agents incl. the opencode writer-install lane) + `test/connect-bearer.test.ts` (raw-bearer probe + full OAuth chain register→connect→discovery→`/token` mint→`get_brain_identity`, client registered in `beforeAll` before serve takes the PGLite single-writer lock; drives real `claude` + `codex` binaries through `connect --install` with sandboxed `HOME`/`CODEX_HOME`, asserts registration + token never in Codex config, skips when a binary is absent) + `test/serve-stdio-roundtrip.test.ts` (spawns real `gbrain serve` stdio against a fresh `init --pglite` brain, drives the SDK client through `initialize`→`tools/list`→`tools/call`, asserts the advertised core-tool set including `capture`, a starter-surface MCP op) + `test/serve-skills-publish-nudge.test.ts`.+- `src/commands/connect.ts` + `src/core/connect-probe.ts` — `gbrain connect <mcp-url> [--token <bearer>]` one-command coding-agent onboarding from a bearer token. Turns an MCP URL + token into a paste-ready `claude mcp add ... -H "Authorization: Bearer ..."` block (default) or, with `--install`, runs it directly and smoke-tests the token. Direct HTTP MCP — Claude Code talks straight to a remote `gbrain serve --http`, no local install needed. Token resolution: `--token` > `$GBRAIN_REMOTE_TOKEN` > placeholder (print) / error (install). The generated block tells the agent to call `get_brain_identity` + `list_skills` (the `LEARN_INSTRUCTION` export, which names `capture` — a starter-surface MCP op — alongside `put_page` for full-control writes) with a core-tools fallback for hosts without skill publishing. URL normalization appends `/mcp` to a bare host but REJECTS a scheme-less host; the pure registration helpers (`normalizeMcpUrl`, `isLinkLocalOrMetadata`, `buildClaudeMcpAddArgv` with its optional scope param — claude's default is `local`, so the harness lane passes `user` explicitly — `buildCodexMcpAddArgv`, `validateToken`, `redactToken`, `shellQuote`/`cmdString`, `issuerFromMcpUrl`, the `OAUTH_SECRET_NOTE` secret-hygiene constant, and `openclawThinClientBlock` — the honest openclaw wiring print: a scoped `gbrain init --mcp-only` thin-client block, deliberately NOT a stdio mcpServers config since that grants full local DB access) live in `src/core/mcp-registration.ts` (core must not import from commands; connect.ts re-exports them — `OAUTH_SECRET_NOTE` included — so its surface and tests are unchanged) and are unit-tested. Flags: `--token`, `--name <id>` (default `gbrain`, validated against `NAME_RE`), `--agent claude-code|codex|opencode|perplexity|generic`, `--install`, `--yes` (the user's approval for `--install`: `installConsent` asks through `requireConsent`, effects `credentials` + `persistent_install`, via the `isTTY`/`promptYesNo` seams; non-TTY without it exits 3 with the consent payload, whose argv omits the token value), `--force`, `--json` (token redacted unless `--show-token`), `--timeout-ms`. `connect` is in `CLI_ONLY` + `CLI_ONLY_SELF_HELP`; dispatched in `cli.ts:handleCliOnly` with no local DB connect. `AGENT_SPECS` drives per-agent rendering + `--install`: `claude-code` → `buildClaudeMcpAddArgv` (literal `-H "Authorization: Bearer <tok>"`); `codex` → `buildCodexMcpAddArgv` = `codex mcp add <name> --url <url> --bearer-token-env-var GBRAIN_REMOTE_TOKEN` (on the CONNECT lane Codex reads the token from the env var at runtime, never written to config — the harness lane in `src/core/bootstrap/harness.ts` is the deliberate exception, writing a managed block with the inline `http_headers = { Authorization = "Bearer <t>" }` credential (codex-cli >=0.149 rejects inline `bearer_token` for streamable_http at config load) because framework-spawned codex inherits no shell profile; `--install` runs it and prints an `export GBRAIN_REMOTE_TOKEN` hint when missing); `opencode` → `buildOpencodeMcpAddArgv` = `opencode mcp add <name> --url <url> --header "Authorization=Bearer {env:GBRAIN_REMOTE_TOKEN}"` (the interpolation is stored LITERALLY and resolved by opencode at read time — token never in argv/config/--json; `--install` writes the entry directly through `ConnectDeps.writeOpencodeRemoteEntry` → `opencode-json.ts` in env token mode, no binary required; `--force` maps to the writer's `allowReplaceOtherSource` so an OURS entry at an old url — a rotated serve — is replaceable, mirroring the exec lanes' `--force` semantics, while foreign same-name entries still refuse with url-appropriate copy: pick `--name`); `perplexity` + `generic` are `installable:false` and reject `--install`. `--oauth` (`supportsOAuth:true` = perplexity/generic only) emits an OAuth 2.1 client-credentials connector block (Issuer URL via `issuerFromMcpUrl` = mcp-url minus `/mcp`, Client ID, Client Secret) — least-privilege scopes + short-lived rotating tokens vs a long-lived full-access secret. Creds from `--client-id`/`--client-secret` (BYO) or `--register` (`deps.registerOAuthClient` shells `gbrain auth register-client <name> --grant-types client_credentials --scopes <DEFAULT_SCOPES="read write"> --token-endpoint-auth-method client_secret_post` and parses `Client ID:`/`Client Secret:`); `--oauth` rejected for claude-code/codex and incompatible with `--install`. `buildJson` is a generic shape (`agent`, `command`/`command_argv` null for perplexity/generic, `header`, `env_var`, oauth fields with redaction); the codex `command` carries only the env-var name, never the token. `cmdString(binary, argv)` POSIX-single-quotes args. `ConnectDeps` = `{isTTY, promptYesNo, hasBinary(bin), runBinary(bin, argv), probe, env(name), registerOAuthClient, writeOpencodeRemoteEntry}` — binary-generic so `claude` and `codex` share the exec path while opencode rides the writer member; `env` injectable for tests. Security: rendered command single-quotes the token so shell metacharacters can't run code when pasted; token validated before it lands in an HTTP header; link-local / cloud-metadata addresses (incl. IPv4-mapped IPv6 `::ffff:169.254.x.x` and AWS IMDSv2-over-IPv6 `fd00:ec2::254`) refused as a token-exfil guard while localhost/RFC1918/LAN stay allowed; token redacted from all error output. `src/core/connect-probe.ts` is the raw-bearer MCP smoke probe backing `--install`: connects the official MCP SDK `Client` over `StreamableHTTPClientTransport` with a STATIC `Authorization` header (no OAuth/discovery — distinct from `mcp-client.ts:callRemoteTool` which is OAuth-only and `remote-mcp-probe.ts:smokeTestMcp` which only sends `initialize`), runs the full `initialize` handshake via `client.connect()`, then calls `get_brain_identity` (read-scope, non-localOnly) to prove a tool call round-trips. Never throws — every failure maps to `{ ok: false, reason: 'auth' | 'unreachable' | 'timeout' | 'tool_error' | 'unknown', message }` so a wrong/expired token fails at setup, not on the agent's first request. `DEFAULT_PROBE_TIMEOUT_MS = 15_000` shared with `connect.ts`. `serve-http.ts` adds exported pure `skillPublishStatus(publishSkills)` for the startup banner `Skills: published / not published` line + a one-line `gbrain config set mcp.publish_skills true` stderr nudge when publishing is OFF. Docs: `docs/mcp/CODEX.md`, `docs/mcp/PERPLEXITY.md`, `docs/mcp/CLAUDE_CODE.md`, `docs/tutorials/connect-coding-agent.md`. Pinned by `test/connect.test.ts` (pure-helper + render, all five agents incl. the opencode writer-install lane) + `test/connect-bearer.test.ts` (raw-bearer probe + full OAuth chain register→connect→discovery→`/token` mint→`get_brain_identity`, client registered in `beforeAll` before serve takes the PGLite single-writer lock; drives real `claude` + `codex` binaries through `connect --install` with sandboxed `HOME`/`CODEX_HOME`, asserts registration + token never in Codex config, skips when a binary is absent) + `test/serve-stdio-roundtrip.test.ts` (spawns real `gbrain serve` stdio against a fresh `init --pglite` brain, drives the SDK client through `initialize`→`tools/list`→`tools/call`, asserts the advertised core-tool set including `capture`, a starter-surface MCP op) + `test/serve-skills-publish-nudge.test.ts`.- `src/commands/db-repair.ts` — `gbrain db-repair [--yes] [--apply-rewrites] [--json] [--force] [--undo-last-rewrite] [--dry-run]`: ENGINE-FREE Postgres-access repair, sibling of pglite-repair (PGLite brains are redirected there). Never calls connectEngine; default invocation is DIAGNOSE-ONLY (`--dry-run` is an explicit alias). Consent is tiered and flag-gated, never TTY-dependent: auto tier under `--yes` (bounded reconnects, pending migrations in-process, `CREATE EXTENSION vector`, `docker start` of gbrain's own container via `docker-postgres.ts`); rewrite tier under `--yes --apply-rewrites` only (config-file `database_url` rewrites — pooler form, session pooler, `?sslmode=require` — printed first, candidate connect-probed BEFORE persisting, receipted, undo-able); manual tier never applied (credentials/paused-project/env recipes printed — relaying the recipe IS the repair). `--apply-rewrites` without `--yes` is an error. Invariants: fix targets derive only from the CURRENT config URL, never error text; the prober uses exactly ONE connection (`poolSize: 1` — diagnosing pool exhaustion with a 10-connection pool would worsen the outage); rewrite cooldown is ≤24h per (reason, action) with `--force` bypass while auto-tier fixes are NEVER cooldown-blocked (availability first); every rewrite stores the prior URL in the 0600 `~/.gbrain/db-repair-undo.json` (a secret — never the redacted receipts) and `--undo-last-rewrite` (`--yes`-gated) restores it — undo runs INSIDE the advisory lock, emits the same `--json` envelope, validates the record's postgres:// scheme before restoring, and is itself reversible (the outgoing URL becomes the new undo record); an `O_EXCL`-created advisory lockfile blocks concurrent double-rewrites (check-then-write race closed; one stale-holder retry; other write failures stay fail-open); a healthy probe exits 0 "nothing to fix" (the forged-marker defense) and additionally REPORTS (never rewrites) stale DB-plane `engine`/`database_url` rows; the schema probe treats a ZERO-ROW `pg_extension` result as `pgvector_missing` (the query never errors on an absent extension); the docker arm matches the container's REAL inspected host port (`deps.docker.hostPort`) as well as the default 5434; a successful rewrite prints the "restart long-lived gbrain processes" note (config rewrites reach NEW processes only). Refusals: thin-client (no local DB), non-host brain resolution (a mount outage must never rewrite host config — mount-targeted repair is a filed TODO), PGLite (→ pglite-repair). Injectable `DbRepairDeps` prober/executor seam for tests; `defaultDeps.probeAccess` is also reused by the init ladder (one prober, one contract). Pinned by `test/db-repair.serial.test.ts`.diff --git a/scripts/agent-contract-baselines/interactive-io.tsv b/scripts/agent-contract-baselines/interactive-io.tsvindex fd71ef10d3..c4a6b63a34 100644--- a/scripts/agent-contract-baselines/interactive-io.tsv+++ b/scripts/agent-contract-baselines/interactive-io.tsv@@ -1,7 +1,6 @@# shrink-only baseline for scripts/check-agent-contract.ts rule interactive-io: path<TAB>countsrc/commands/book-mirror.ts 1src/commands/capture.ts 1-src/commands/company-brain-connect.ts 1src/commands/connectors/auth.ts 1src/commands/hook.ts 3src/commands/init.ts 4diff --git a/scripts/agent-contract-baselines/yes-rerun-string.tsv b/scripts/agent-contract-baselines/yes-rerun-string.tsvindex 115f252de0..bea7190959 100644--- a/scripts/agent-contract-baselines/yes-rerun-string.tsv+++ b/scripts/agent-contract-baselines/yes-rerun-string.tsv@@ -1,7 +1,6 @@# shrink-only baseline for scripts/check-agent-contract.ts rule yes-rerun-string: path<TAB>countsrc/cli.ts 3src/commands/apply-migrations.ts 3-src/commands/company-brain-connect.ts 1src/commands/config.ts 1src/commands/db-repair.ts 1src/commands/doctor/checks/memory-writeback.ts 2diff --git a/src/commands/company-brain-connect.ts b/src/commands/company-brain-connect.tsindex 08c09afa1f..6a6232e718 100644--- a/src/commands/company-brain-connect.ts+++ b/src/commands/company-brain-connect.ts@@ -1,6 +1,7 @@import { constants, closeSync, fstatSync, openSync, readFileSync } from 'node:fs';import { randomUUID } from 'node:crypto';-import { createInterface } from 'node:readline/promises';+import { isInteractive, readLine } from '../core/interaction.ts';+import { CONFIRMATION_REQUIRED_EXIT_CODE } from '../core/exit-codes.ts';import type { BrainEngine } from '../core/engine.ts';import { getCliOptions } from '../core/cli-options.ts';import { isThinClient, loadConfig } from '../core/config.ts';@@ -21,7 +22,8 @@ export const COMPANY_BRAIN_CONNECT_HELP = `Connect a reviewed company repositoryBoth destination flags are required. A saved plan and a repository path are mutually exclusive.Connect previews the destination and asks before registering/indexing a new source.-Non-interactive use requires --yes; it never bypasses validation or access checks.+Non-interactive use needs the user's approval (--yes); without it the command exits 3.+--yes never bypasses validation or access checks.No embeddings, Git pull/push, source edits, grants, skills, or schedules are enabled.Use sources inspect to create a private review plan before connecting.Resume incomplete work with: gbrain sync --brain <id> --source <id> --no-embed --no-pull@@ -128,16 +130,17 @@ export async function runCompanyBrainConnect(args: string[], connectEngine: () =const preview = delegated.handled ? delegated.result : await (await import('../core/company-brain/runtime.ts')).previewCompanyBrain(engine = await connectEngine(), local);console.error(`Company source preview: ${JSON.stringify(preview, (_key, item) => typeof item === 'bigint' ? item.toString() : item)}`);console.error('This indexes the reviewed committed files. It does not change source files, access grants, or enable paid/background capabilities.');- if (!options.yes && !process.stdin.isTTY) {- if (json) await emit({ schema_version: 1, status: 'blocked', code: 'confirmation_required', brain_id: options.brainId, source_id: options.sourceId, request_id: options.requestId, preview, plan });- else console.error('Connect requires confirmation. Review this preview, then rerun with --yes for non-interactive use.');- setCliExitVerdict(2);+ if (!options.yes && !isInteractive()) {+ // Exit 3 is confirmation_required's only meaning (agent operator contract v1).+ const userMessage = `Connect the reviewed repository as source ${options.sourceId} in brain ${options.brainId}? It indexes its committed files; nothing else is enabled.`;+ if (json) await emit({ schema_version: 1, status: 'blocked', code: 'confirmation_required', brain_id: options.brainId, source_id: options.sourceId, request_id: options.requestId, preview, plan, user_message: userMessage });+ else console.error(`Connect needs the user's approval. Ask the user: ${userMessage} If they agree, run the same command with --yes and --request-id ${options.requestId}.`);+ setCliExitVerdict(CONFIRMATION_REQUIRED_EXIT_CODE);return;}if (!options.yes) {- const input = createInterface({ input: process.stdin, output: process.stderr });- let answer: string;- try { answer = await input.question('Connect this source? [y/N] '); } finally { input.close(); }+ const read = await readLine({ prompt: 'Connect this source? [y/N] ' });+ const answer = read.kind === 'line' ? read.text : '';if (!/^y(?:es)?$/i.test(answer.trim())) {if (json) await emit({ schema_version: 1, status: 'cancelled', code: 'declined', brain_id: options.brainId, source_id: options.sourceId });else await writeStdoutFinal('Cancelled. No source was connected.\n');diff --git a/src/commands/connect.ts b/src/commands/connect.tsindex 4fab055e79..48100bd416 100644--- a/src/commands/connect.ts+++ b/src/commands/connect.ts@@ -50,6 +50,7 @@ import {writeOpencodeMcpEntry,} from '../core/bootstrap/opencode-json.ts';import { promptLine } from '../core/cli-util.ts';+import { consentGateOrExit } from '../core/consent-cli.ts';import {NAME_RE,OAUTH_SECRET_NOTE,@@ -174,7 +175,8 @@ Flags:--install Run the agent's MCP-add command, then smoke-test the token(claude-code + codex + opencode; opencode installs via a directconfig write — no binary needed, token stays out of the file)- --yes Skip the install confirmation prompt+ --yes The user's approval for --install (writes a credential-+ bearing MCP entry); without it a non-interactive run exits 3--force On --install, replace an existing server of the same name--json Emit machine-readable JSON (secret redacted)--show-token With --json, include the literal token/secret (avoid in logs)@@ -613,6 +615,39 @@ function fail(msg: string): never {process.exit(1);}+/**+ * A4 consent for `--install`: it writes a credential-bearing MCP entry into+ * the agent's config (persistent_install) and sends the token to the remote+ * host (credentials). `--yes` or a TTY prompt (deps seams) authorizes it;+ * otherwise exit 3 with the consent payload. The approved argv never carries+ * the token value: it names GBRAIN_REMOTE_TOKEN instead.+ */+async function installConsent(args: string[], f: ParsedFlags, url: string, destination: string, deps: ConnectDeps): Promise<void> {+ const argv = ['gbrain', 'connect'];+ for (let i = 0; i < args.length; i++) {+ const a = args[i]!;+ if (a === '--yes' || a === '-y') continue;+ if (a === '--token') { i++; continue; }+ if (a.startsWith('--token=')) continue;+ argv.push(a);+ }+ await consentGateOrExit({+ command: 'connect --install',+ effects: ['credentials', 'persistent_install'],+ actor: 'agent',+ what: `Register the MCP server '${f.name}' -> ${url} in ${destination}`,+ why: 'Wires this agent to the remote brain so its memory tools are available in new sessions.',+ risk: `Writes a credential-bearing MCP entry into ${destination} and sends the token to ${url} for a smoke test. `+ + `Undo: remove the '${f.name}' MCP server from that agent. The approved command reads the token from GBRAIN_REMOTE_TOKEN (or the same --token).`,+ user_message: `Add the brain at ${url} to ${destination} as MCP server '${f.name}' (it stores an access token there)?`,+ argv,+ args,+ }, {+ json: f.json,+ env: { interactive: deps.isTTY(), readLine: async ({ prompt }) => ({ kind: 'line', text: (await deps.promptYesNo(prompt.replace(/ \[y\/N\] $/, ''))) ? 'y' : 'n' }) },+ });+}+/** Resolve OAuth creds from explicit flags or by registering a client on the host. */function resolveOAuthCreds(f: ParsedFlags, url: string, deps: ConnectDeps): OAuthCreds {const issuer = issuerFromMcpUrl(url);@@ -704,13 +739,7 @@ export async function runConnect(args: string[], deps: ConnectDeps = defaultDeps// --force maps to the writer's allowReplaceOtherSource so an OURS entry// at an old url (a rotated serve) is replaceable, mirroring the exec// lanes' documented --force semantics.- if (!f.yes) {- if (!deps.isTTY()) {- fail('--install in a non-interactive shell requires --yes (refusing to register a credential-bearing MCP server without confirmation).');- }- const ok = await deps.promptYesNo(`Add MCP entry '${f.name}' -> ${url} to the opencode user-global config?`);- if (!ok) fail('Aborted.');- }+ await installConsent(args, f, url, 'the opencode user-global config', deps);let w: { configPath: string; replacedPrior: boolean };try {w = await deps.writeOpencodeRemoteEntry(f.name, url, { allowReplaceOtherSource: f.force });@@ -749,16 +778,7 @@ export async function runConnect(args: string[], deps: ConnectDeps = defaultDepsfail(`An MCP server named '${f.name}' already exists in ${spec.label}. Run '${binary} mcp remove ${f.name}' first, pass --name <other>, or --force to replace it.`);}- if (!f.yes) {- if (!deps.isTTY()) {- // Non-interactive --install registers a credential-bearing MCP server and- // fires the token at a remote host — require an explicit --yes rather than- // silently proceeding when there's no TTY to confirm at.- fail('--install in a non-interactive shell requires --yes (refusing to register a credential-bearing MCP server without confirmation).');- }- const ok = await deps.promptYesNo(`Add MCP server '${f.name}' -> ${url} to ${spec.label}?`);- if (!ok) fail('Aborted.');- }+ await installConsent(args, f, url, spec.label, deps);let removedExisting = false;if (exists && f.force) {diff --git a/src/core/consent-cli.ts b/src/core/consent-cli.tsindex 87d9ee2239..84ca248c95 100644--- a/src/core/consent-cli.ts+++ b/src/core/consent-cli.ts@@ -33,9 +33,12 @@ export async function consentGate(req: ConsentRequest, opts: ConsentGateOpts): P}export async function consentGateOrExit(req: ConsentRequest, opts: ConsentGateOpts): Promise<Authorization> {- const auth = await consentGate(req, opts);- if (auth) return auth;- process.exit(3);+ try {+ return await requireConsent(req, opts.env ?? {});+ } catch (e) {+ if (!isConsentRefusal(e)) throw e;+ process.exit(printConsentRefusal(e, { json: opts.json }));+ }}/** The DB-plane `spend.posture` read requireConsent needs to honour `tokenmax`. */diff --git a/test/company-brain-connect-cli.serial.test.ts b/test/company-brain-connect-cli.serial.test.tsindex 10beffcb4e..bc7a23b26b 100644--- a/test/company-brain-connect-cli.serial.test.ts+++ b/test/company-brain-connect-cli.serial.test.ts@@ -83,7 +83,7 @@ describe('company connect public CLI', () => {expect(inspected.code).toBe(0);const command = ['sources', 'connect', '--plan', out, '--brain', 'host', '--source', 'wiki', '--json'];const preview = run(f.home, command);- expect(preview.code).toBe(2);+ expect(preview.code).toBe(3); // exit 3 is confirmation_required's only meaning (contract v1)expect(JSON.parse(preview.out)).toMatchObject({ schema_version: 1, code: 'confirmation_required', preview: { sourceId: 'wiki', managed: false } });expect(await sources(f)).toEqual([{ id: 'default' }]);expect(readFileSync(f.configFile)).toEqual(config);diff --git a/test/connect.test.ts b/test/connect.test.tsindex 468eacb274..378d92b282 100644--- a/test/connect.test.ts+++ b/test/connect.test.ts@@ -617,8 +617,8 @@ describe('runConnect --install', () => {runBinary: (_b, argv) => { calls.push(argv); return { code: argv[1] === 'get' ? 1 : 0, stdout: '', stderr: '' }; },}),);- expect(r.exitCode).toBe(1);- expect(r.err.join('\n')).toMatch(/Aborted/);+ // A4: a declined prompt is a consent refusal (exit 3), nothing registered.+ expect(r.exitCode).toBe(3);expect(calls.some((a) => a[1] === 'add')).toBe(false);});@@ -668,13 +668,26 @@ describe('runConnect --install', () => {expect(r.err.join('\n')).not.toMatch(/Add this to your shell profile/);});- test('non-interactive --install without --yes is refused', async () => {- const r = await runWithExitCapture(- ['https://brain.example.com/mcp', '--token', 'tok', '--install'], // isTTY false (default), no --yes- installDeps(),- );- expect(r.exitCode).toBe(1);- expect(r.err.join('\n')).toMatch(/requires --yes/);+ test('non-interactive --install without --yes is refused: exit 3, consent payload without the token', async () => {+ const calls: string[][] = [];+ let stdout = '';+ const write = process.stdout.write;+ process.stdout.write = ((c: string | Uint8Array) => { stdout += String(c); return true; }) as typeof process.stdout.write;+ let r;+ try {+ r = await runWithExitCapture(+ ['https://brain.example.com/mcp', '--token', 'gbrain_secret_tok', '--install', '--json'], // isTTY false (default), no --yes+ installDeps({ runBinary: (_b, argv) => { calls.push(argv); return { code: argv[1] === 'get' ? 1 : 0, stdout: '', stderr: '' }; } }),+ );+ } finally {+ process.stdout.write = write;+ }+ expect(r.exitCode).toBe(3);+ expect(calls.some((a) => a[1] === 'add')).toBe(false);+ const payload = JSON.parse(stdout);+ expect(payload).toMatchObject({ code: 'confirmation_required', effects: ['credentials', 'persistent_install'] });+ expect(payload.fix.argv).toEqual(['gbrain', 'connect', 'https://brain.example.com/mcp', '--install', '--json', '--yes']);+ expect(stdout).not.toContain('gbrain_secret_tok');});test('a flag-shaped --token value is rejected (no silent swallow)', async () => {@@ -1035,7 +1048,7 @@ describe('opencode lane', () => {expect(r.err.join('\n')).toMatch(/connector-style agents/);});- test('--install non-TTY without --yes → exit 1, requires --yes, writer NEVER called', async () => {+ test('--install non-TTY without --yes → exit 3 (confirmation_required), writer NEVER called', async () => {let called = false;const r = await runWithExitCapture(['https://brain.example.com/mcp', '--token', 'gbrain_tok', '--agent', 'opencode', '--install'],@@ -1047,12 +1060,11 @@ describe('opencode lane', () => {},}),);- expect(r.exitCode).toBe(1);- expect(r.err.join('\n')).toMatch(/requires --yes/);+ expect(r.exitCode).toBe(3);expect(called).toBe(false);});- test('--install TTY prompt declined → Aborted, writer NEVER called', async () => {+ test('--install TTY prompt declined → consent refusal (exit 3), writer NEVER called', async () => {let called = false;const r = await runWithExitCapture(['https://brain.example.com/mcp', '--token', 'gbrain_tok', '--agent', 'opencode', '--install'],@@ -1065,8 +1077,7 @@ describe('opencode lane', () => {},}),);- expect(r.exitCode).toBe(1);- expect(r.err.join('\n')).toMatch(/Aborted/);+ expect(r.exitCode).toBe(3);expect(called).toBe(false);});});diff --git a/test/v0_37_gap_fill.serial.test.ts b/test/v0_37_gap_fill.serial.test.tsindex a7608263ae..93e575296b 100644--- a/test/v0_37_gap_fill.serial.test.ts+++ b/test/v0_37_gap_fill.serial.test.ts@@ -508,7 +508,6 @@ describe('reinit-pglite — backup + reinit', () => {// eslint-disable-next-line @typescript-eslint/no-explicit-any(process.stdout as any).write = origWrite;if (prev === undefined) delete process.env.GBRAIN_NON_INTERACTIVE; else process.env.GBRAIN_NON_INTERACTIVE = prev;- process.exitCode = 0;}});