Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Thin-client `gbrain serve` relays stdio MCP to the remote brain (GST-2104) (#9372)

Garry Tan029859a295f4
diff --git a/behavior-changes.d/thin_client_serve_stdio_bridge_8543.md b/behavior-changes.d/thin_client_serve_stdio_bridge_8543.md
new file mode 100644
index 0000000000..597788a072
--- /dev/null
+++ b/behavior-changes.d/thin_client_serve_stdio_bridge_8543.md
@@ -0,0 +1 @@
+On a thin client (gbrain init --mcp-only), plain `gbrain serve` no longer refuses: it is now a stdio MCP server that relays every call to the brain host with the stored OAuth client's grant, opens no local database and adds no access. A harness entry that runs `gbrain serve` on a thin client now connects to the remote brain instead of exiting with requires_local_engine. `gbrain serve --http`, `--access` and the other host flags still refuse there. `gbrain doctor` on a read or read+write client now reports the missing admin scope as expected (ok) instead of a warning that suggested re-registering with admin.
diff --git a/changelog.d/capy-thin-client-serve-stdio-bridge.md b/changelog.d/capy-thin-client-serve-stdio-bridge.md
new file mode 100644
index 0000000000..7b8c4d930c
--- /dev/null
+++ b/changelog.d/capy-thin-client-serve-stdio-bridge.md
@@ -0,0 +1,13 @@
+**On a thin client, `gbrain serve` now connects a stdio-only agent harness to your remote brain instead of refusing.**
+
+Install the gbrain CLI on the agent's machine, run `gbrain init --mcp-only` with an OAuth client from the brain host, and register `gbrain serve` as the harness's stdio MCP server, the same entry a local brain uses. Every call goes to the brain host with that client's grant and comes back unchanged, refusals included; the bridge opens no local database, stores no page text and adds no access. Reported and first proposed by @jel405 (#8543).
+
+### Itemized changes
+
+- Bare `gbrain serve` on a thin client is a stdio bridge. It accepts `--surface`, `--advertise` and `--source-guard` (the argv gbrain's plugins register); `request_tools {surface}` widens only the session and writes nothing on the host. `serve --http`, `--access` and the other host flags still refuse with `requires_local_engine`, with a fix that keeps the flags (`--access` points at registering a narrow read-only client instead).
+- Bridge failures are v1 agent envelopes with a bounded recovery and a fix that never adds a scope. A write whose answer was lost keeps its `request_id` (`write_outcome_unknown`) so it can be checked or resent without writing twice. URLs in envelopes and stderr lose their userinfo, query and fragment.
+- A call that names an audience (`_meta.on_behalf_of`) is relayed only to a host that enforces it (gbrain 0.60.543.0 or newer); otherwise the bridge answers `host_upgrade_required`.
+- `gbrain doctor` on a read or read+write thin client reports the missing admin scope as expected instead of advising a re-register with admin.
+- `gbrain agent register --harness openclaw` prints the lines to run on the OpenClaw machine: `gbrain init --mcp-only …` then `openclaw mcp add gbrain --command "$(command -v gbrain)" --arg serve …`.
+
+<!-- behavior-change: thin_client_serve_stdio_bridge_8543 -->
diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.md
index 7d4dc6dcc4..cd7eff2164 100644
--- a/docs/architecture/key-files/mcp.md
+++ b/docs/architecture/key-files/mcp.md
@@ -3,32 +3,36 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)` (a read op (`mutating === false`) runs inside `withRequestConfigSnapshot`, a write op under `withoutRequestConfigSnapshot`; `src/core/config-snapshot.ts`), `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts`; for a read op on a live engine it runs beside the handler instead of after it (GBRA-156), and reads its withdrawal watermark and trust generation in one round trip — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash + eligibility + the `sessionOnly` scope (a session with no facts of its own falls back to the source's newest 24h facts unless the caller passes `sessionOnly`, which the IPC handlers do when `context.hot_memory.session_only` is on; MCP callers never pass it), so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served, the key folds the effective read eligibility and each hit revalidates the trust policy generation (`src/core/eligibility/generation.ts`, migration v230: deferred triggers bump `trust_policy_state` on tier changes, quarantine transitions, read floor and `trust.%` config changes, purges and `needs_rederive`), read before the rows; an unreadable generation delivers nothing; facts read through the `hot_memory` proactive eligibility and `partitionForActivation`, carry `trust_tier` and `origin`, and the payload's `suppressed` counts what activation control withheld), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` marks a saved fact that carries `corrected_by` with "corrected by a newer saved fact above" in its bracket and caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope. `sessionSafetyNotices` adds the one-time `behavior_changes` disclosure (stdio: once per brain; HTTP: once per authenticated client, remote view) and, on stdio only, the queued `chat_fallback_hop` notice, on success and failure results alike. `requestMetaSessionId(request.params)` is the one reader of the request-level `_meta.session_id` (beside `arguments`); stdio (`server.ts`) and HTTP (`serve-http-mcp.ts`) both pass it as `opts.sessionId`, which wins over an arguments-level `_meta` and is clamped to `SESSION_ID_MAX_CHARS` (256). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`). Large pages: after a read's result is assembled (notices and `_meta` included), `frameOverCap` measures the final encoded frame against the connection's cap and replaces an oversized read with `result_too_large` (writes are never replaced); `DispatchOpts.thinClient` (from `X-Gbrain-Client` on both HTTP transports) reaches `OperationContext.thinClient`, a default-body-mode hint, never authority. GBRA-156: `hotMemoryOffIn(params)` reads `_meta.hot_memory: "off"`. Both transports pass the request-level value as `opts.hotMemoryOff`, and dispatch also reads it from the arguments' `_meta`. Either one skips the `metaHook` for that call, so the response carries no `brain_hot_memory` (`test/mcp-hot-memory-opt-out.test.ts`). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`). Large pages: after a read's result is assembled (notices and `_meta` included), `frameOverCap` measures the final encoded frame against the connection's cap and replaces an oversized read with `result_too_large` (writes are never replaced); `DispatchOpts.thinClient` (from `X-Gbrain-Client` on both HTTP transports) reaches `OperationContext.thinClient`, a default-body-mode hint, never authority. GBRA-156: a remote non-mutating op runs inside `withPrivateReadableSources(auth.privatePages.sources)`; writes, local calls and `context_pack` / `delta` (`WORLD_ONLY_PACK_OPS`) run with an empty set. GST-359 C1: `opts.actor` carries the `x-qm-actor` header from both HTTP transports (stdio never attests); `resolveAttestedActor` (`src/core/access/actor.ts`) decides before any work, and `actorRefusal` returns its refusals with `structuredContent.error` beside the JSON text block, the one seam where layer D's `memory_recall` will answer `actor_unlinked` as empty content plus `structuredContent {facts: [], truncated: false, code: 'actor_unlinked'}`. Every MCP server's `serverInfo.description` is `MCP_SERVER_DESCRIPTION` (`instructions.ts`, at most 120 characters); `instructions` are unchanged. `asAgentToolError(e, op, ctx, allowedOps)` renders a failed read as the error text an HTTP read-scope MCP caller gets for the same call (code, message, suggestion, `fix` limited to `allowedOps`) for SkillOpt's tool loops, which throw it with `code` kept; an AI invocation policy stop passes through unchanged. On a remote read it runs the requester-scope gate (`src/core/access/requester-scope.ts`) right after access resolves: refusals come back structured with `structuredContent.error`, grace notices in `_meta.access.requester_scope`.
+- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)` (a read op (`mutating === false`) runs inside `withRequestConfigSnapshot`, a write op under `withoutRequestConfigSnapshot`; `src/core/config-snapshot.ts`), `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts`; for a read op on a live engine it runs beside the handler instead of after it (GBRA-156), and reads its withdrawal watermark and trust generation in one round trip — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash + eligibility + the `sessionOnly` scope (a session with no facts of its own falls back to the source's newest 24h facts unless the caller pas... (line truncated to 2000 chars)
- `src/core/egress-budget.ts` — the per-connection result cap: `resultByteCap` (Infinity for the trusted local CLI; else `mcp.max_result_bytes_stdio` 4 MiB / `mcp.max_result_bytes_http` 1 MiB, DB plane then file plane, clamped to 256 KiB–9 MiB), `encodedFrameBytes` (the complete JSON-RPC frame plus a framing reserve), and the dispatcher backstop pair `frameOverCap` / `resultTooLargeError`.
-- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract, compile-time source text (no runtime filesystem dependency) shared by the stdio SDK server, the OAuth HTTP SDK server and the legacy raw HTTP initialize path. `buildMcpInstructions({writeback?, tools?})` GENERATES the contract from the caller's callable set (`tools.callable`, the tools/list predicate): a clause naming a tool (search/query/get_page, skills catalog, put_page, whoami, join/sync skills, put/delete skill, the memory loop's `context_pack`/`volunteer_context`/`remember`/`forget`) appears only when that tool is listed, so every tool named is in that surface's tools/list (`test/mcp-initialize-instructions.test.ts`). When callable tools are left out of the listed set (`hiddenCallable`) and `request_tools` is callable, the hidden-tool sentence leads the contract, inside the 2,048 characters capped harnesses read (D1). It always carries the error protocol (follow `fix.next`, then `fix.verify`) and the notice prefix, then the optional status-only line (F4), the opt-in ambient-writeback section (`src/core/facts/writeback-instructions.ts`) and the readiness tail (top two `missing`/`degraded` gaps among embeddings, chat_llm, migrations, worker — never a by-choice state). With no `tools` and no writeback it equals `GBRAIN_MCP_INSTRUCTIONS` (the every-tool rendering bootstrap writes to GBRAIN-INSTRUCTIONS.md). `resolveMcpInstructions(config, env?, opts)` appends the operator-set deployment identity LAST under `Deployment identity:` (`GBRAIN_MCP_INSTRUCTIONS` env when non-blank, else file-plane `mcp.instructions`). `installInstructionsResolver(server, compute)` swaps the SDK Server's initialize handler so the stdio and OAuth servers compute the contract (callable set + readiness tail via `src/mcp/initialize-context.ts`) when the client initializes; the constructor value stays the fallback on a throw. The legacy bearer transport builds it inline per initialize. Transport tests compare against the contract for that connection's own tools/list (`test/helpers/instructions-parity.ts`): `test/serve-stdio-roundtrip.test.ts`, `test/http-transport.test.ts`, `test/connect-bearer.test.ts`, `test/mcp-instructions-writeback.test.ts`; identity composition in `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`. #6170: `contractClauses(c, writeback)` puts the short `Ambient writeback is ON (<mode>)` line (with `visibility "private"` under a private posture) in the memory clause when writeback is on, follows the data-not-instructions clause with the shortened error protocol and moves the forget caveat after the scope clause, so the writeback line, `Follow \`fix.next\``, `[gbrain notice`, `context_pack`, `put_page REPLACES` and `Writing:` end inside the first 2,048 characters on every surface (pinned per surface × mode × extract_facts × visibility in `test/mcp-initialize-instructions.test.ts`); the full writeback section stays appended last. Cat 40's measured "Answering from the brain" clause is verbatim; the change needs the D12 Cat 40 smoke before merge. The brief clause puts the `referenced_by` walk on the single-name `entity` card and names only the fields compact `names` rows carry on the brain (`references: {namesRow, records}`, read at every per-initialize call site by `readInstructionContent` from `src/core/entity-references-config.ts`; the static contract is the defaults rendering; `test/mcp-instructions-references.test.ts`). Instruction 7's governing rule (`mcp.instructions_governing_rule`: `in_effect` default, `newest` the earlier recency sentence) leads the answering clause so it ends inside the first 2,048 characters (`test/mcp-instructions-governing-rule.test.ts` records its offset per surface).
+- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract, compile-time source text (no runtime filesystem dependency) shared by the stdio SDK server, the OAuth HTTP SDK server and the legacy raw HTTP initialize path. `buildMcpInstructions({writeback?, tools?})` GENERATES the contract from the caller's callable set (`tools.callable`, the tools/list predicate): a clause naming a tool (search/query/get_page, skills catalog, put_page, whoami, join/sync skills, put/delete skill, the memory loop's `context_pack`/`volunteer_context`/`remember`/`forget`) appears only when that tool is listed, so every tool named is in that surface's tools/list (`test/mcp-initialize-instructions.test.ts`). When callable tools are left out of the listed set (`hiddenCallable`) and `request_tools` is callable, the hidden-tool sentence leads the contract, inside the 2,048 characters capped harnesses read (D1). It always carries the error protocol (follow `fix.next`, then `fix.verify`) and the notice prefix, then the optional status-only line (F4), the opt-in ambient-writeback section (`src/core/facts/writeback-instructions.ts`) and the readiness tail (top two `missing`/`degraded` gaps among embeddings, chat_llm, migrations, worker — never a by-choice state). With no `tools` and no writeback it equals `GBRAIN_MCP_INSTRUCTIONS` (the every-tool rendering bootstrap writes to GBRAIN-INSTRUCTIONS.md). `resolveMcpInstructions(config, env?, opts)` appends the operator-set deployment identity LAST under `Deployment identity:` (`GBRAIN_MCP_INSTRUCTIONS` env when non-blank, else file-plane `mcp.instructions`). `installInstructionsResolver(server, compute)` swaps the SDK Server's initialize handler so the stdio and OAuth servers compute the contract (callable set + readiness tail via `src/mcp/initialize-context.ts`) when the client initializes; the constructor value stays the fallback on a throw. The legacy bearer transport builds it inline per initialize. Transport tests compare... (line truncated to 2000 chars)
- `src/mcp/publish-gates.ts` — publish-gate resolution for the honest tools/list. `readPublishGate(engine, config, key)`: dual-plane (DB > file > false), never throws — a FAILED read resolves false (hide-on-doubt matches the default-off consent posture). `disabledOpsForPublishGates(engine, config)`: the op-name set tools/list subtracts; one getConfig read per distinct gate key per call, deliberately NOT memoized so `gbrain config set mcp.publish_skills true` takes effect on the next list without a restart. Call-time gates inside the handlers stay as the fail-closed backstop (their denials carry `detail: 'config_key=<key>'` — the machine-readable denial grammar). Pinned by test/publish-gates.test.ts. `PUBLISH_GATE_KEYS` (every operation's gate key) is the set `gbrain config get` resolves DB-first, matching this resolver (`test/config-get-plane.test.ts`).
- `src/mcp/rate-limit.ts` — Bounded-LRU token-bucket limiter. `buildDefaultLimiters()` returns the two-bucket pipeline: pre-auth IP (30/60s, fires BEFORE the DB lookup so brute-force load against `access_tokens` is capped) + post-auth token-id (60/60s). Tracks `lastTouchedMs` separately from `lastRefillMs` so an exhausted key can't be reset by hammering past the TTL. LRU cap bounds memory under attacker-controlled key growth. `refund(key)` returns one consumed token (capped at the limit) — the `request_tools` persist path refunds when a race-lost 0-row UPDATE (concurrent operator pin) means no write actually happened; dry-run previews never draw a token at all (the limiter meters actual writes only).
+- `src/mcp/remote-bridge.ts` — the thin-client stdio bridge (`startRemoteStdioBridge`): bare `gbrain serve` on a thin client, engine-free. tools/list is the host's list for the stored OAuth client (`listRemoteToolDefs`), narrowed only by the local `--surface`/`--advertise` through the same `StdioSurfaceState` and `stdioToolListing` as local stdio; a narrowed listing drops host tools this build does not know (logged once). tools/call goes through `forwardRemoteToolCall` with client name `gbrain-stdio-bridge` and `_meta` unchanged; localOnly/cliOnly and out-of-surface names are refused as `unknown_tool` before forwarding. `request_tools {surface}` widens only this session (never forwarded); a relayed `request_tools {tools}` answer reveals in-surface names (then `tools/list_changed`) and gets a session note. An audience call (`_meta.on_behalf_of`) needs a host at `AUDIENCE_MIN_HOST_VERSION` (`hostAtLeast` on serverInfo) and a read answer that reports `_meta.access.audience`, else `host_upgrade_required`. Lifecycle via `installStdioShutdownTriggers`; the EOF drain bound is the call timeout, an expired drain with a write in flight logs it and exits 1, and `MCP_STDIO=1` keeps the process alive. Seams: `transport`, `lifecycle`, `list`, `forward`. Pinned by `test/remote-stdio-bridge.serial.test.ts` (real `serve --http` host) and `test/remote-bridge-errors.test.ts`.
+- `src/mcp/remote-bridge-errors.ts` — the bridge's v1 envelopes: a per-`RemoteMcpError` reason fix table (exhaustive), `writeIdentity` (`not_sent` resends; an accepted journaled mutation is `write_outcome_unknown` with its `request_id` and a `get_write_request` fix; `submit_*` points at `list_jobs`), `bridgeCallFailure`/`bridgeListFailure` (list: JSON-RPC InternalError whose `data` is the envelope plus stage, `side_effects: none` and bounded recovery), `writeBridgeTrace` (0600 under `bridge-traces/`), `bridgeRefusal`. No fix ever adds a scope; every string passes `stripUrlSecrets`.
+- `src/mcp/remote-bridge-args.ts` — `parseBridgeServeArgs` (bare, `--surface`, `--advertise`, `--source-guard` bridge; a repeat takes the narrowest; a bad value is `invalid_params`) and `serveThinClientRefusal` (`requires_local_engine`; the fix keeps the refused flags, unsafe values masked; `--access` gets the narrow read-only client recipe). Engine- and SDK-free, loaded by `src/commands/thin-client-routing.ts`. Pinned by `test/remote-bridge-args.test.ts` and the thin-client goldens.
- `src/mcp/result-rows.ts` — the transport side of the `search`/`query` row shape. `resolveResultRowsMode(engine, config)`: dual-plane `mcp.result_rows` (DB > file > 'lean'; a failed DB read falls to the file plane). `resultRowsForRequest(header, hostMode)`: the `X-Gbrain-Client` header naming `gbrain-remote-cli` (sent by `src/core/mcp-client.ts`) selects full rows, otherwise the host mode. The OAuth HTTP transport resolves both per request, the legacy bearer transport per tools/call, and stdio once at start (file plane only when the engine is degraded). The header is unverified and selects a row shape only; it must never gate anything security-relevant. Pinned by `test/mcp-result-rows-skew.test.ts`.
-- `src/mcp/resolve-ipc-binding.ts` — shared resolve-IPC listener wiring for BOTH serve transports. `bindResolveIpcForServe(engine, defaultSource)` binds the retrieval-reflex `resolve`, `turn_context`, and `context_pack` kinds (on Postgres the socket is keyed by `hash12(database_url)` plus `hash12(source)` of the serve's bound source under `~/.gbrain/run`, and the legacy URL-only socket is also bound when free; hooks pick theirs with `hookResolveSocketForConfig` — own source first, legacy fallback; the secret stays URL-keyed and the persistence socket brain-keyed; the bound-source posture rejects requests naming any other source; pinned by `test/resolve-ipc-source-keyed.test.ts`) plus the serve-delegated sync (`sync_start`/`sync_status`/`sync_abort` → `src/core/serve-sync-runner.ts`) and maintenance-sweep (`sweep_start`/`sweep_status` → `src/core/serve-sweep-runner.ts`) kinds — each delegation family in its OWN try/catch, so a runner failure logs `[serve-sync]`/`[serve-sweep] handlers unavailable` and the core kinds still start; both families share the `GBRAIN_SERVE_SYNC_IPC=0` kill switch. Engine-uniform: Postgres brains listen too (the hook lane is engine-free by design, so IPC through a serve is its only DB path there). Best-effort by contract — a bind failure never blocks the serve, and a socket already owned by a live or unresponsive listener (another serve) is left to it (that serve is the IPC provider, #4896). Each socket the serve could not bind (its source socket, the legacy socket, also when only the persistence listener came up) is retried on its own unref'd timer (`RESOLVE_IPC_REBIND_INTERVAL_MS` = 30 s plus up to 5 s jitter, `rebindDelayMs` injectable) through the same `startResolveIpcServer`, so a surviving serve takes over once the owner probes dead and logs `[resolve-ipc] took over <path>`; bind attempts are serialized per serve, `close()` clears the timers and closes a bind that lands after it, and persistence is never re-set-up (#6647, pinned by `test/resolve-ipc-rebind.serial.test.ts`). Reflex-channel event logging fires at DELIVERY (`onDelivered`/`onTurnContextDelivered`), never inside the resolver. `turn_context` and `context_pack` (`context-pack-handler.ts`) read `context.hot_memory.session_only` per request (`readHotMemorySessionOnly`) and pass it as `sessionOnly` to the assembler (pinned by `test/hot-memory-session-only-7026.test.ts`). Pinned by `test/resolve-ipc-binding.test.ts`. #7612: a lean serve (`lean`, a read-only stdio serve on Postgres) binds only its read socket (`resolveSocketPathForConfig(cfg, 'read', source)`: resolve, turn_context and context_pack), never the source or legacy socket, so a read-write serve started later for the same source holds both and answers delegated sync instead of `unsupported_kind`. Hooks try the source socket, then the read socket, then legacy; `src/commands/sync-delegate.ts` passes `{ delegation: true }` to skip the read socket (pinned by `test/resolve-ipc-source-keyed.test.ts` and `test/e2e/serve-read-only-session-lane-postgres.test.ts`).
+- `src/mcp/resolve-ipc-binding.ts` — shared resolve-IPC listener wiring for BOTH serve transports. `bindResolveIpcForServe(engine, defaultSource)` binds the retrieval-reflex `resolve`, `turn_context`, and `context_pack` kinds (on Postgres the socket is keyed by `hash12(database_url)` plus `hash12(source)` of the serve's bound source under `~/.gbrain/run`, and the legacy URL-only socket is also bound when free; hooks pick theirs with `hookResolveSocketForConfig` — own source first, legacy fallback; the secret stays URL-keyed and the persistence socket brain-keyed; the bound-source posture rejects requests naming any other source; pinned by `test/resolve-ipc-source-keyed.test.ts`) plus the serve-delegated sync (`sync_start`/`sync_status`/`sync_abort` → `src/core/serve-sync-runner.ts`) and maintenance-sweep (`sweep_start`/`sweep_status` → `src/core/serve-sweep-runner.ts`) kinds — each delegation family in its OWN try/catch, so a runner failure logs `[serve-sync]`/`[serve-sweep] handlers unavailable` and the core kinds still start; both families share the `GBRAIN_SERVE_SYNC_IPC=0` kill switch. Engine-uniform: Postgres brains listen too (the hook lane is engine-free by design, so IPC through a serve is its only DB path there). Best-effort by contract — a bind failure never blocks the serve, and a socket already owned by a live or unresponsive listener (another serve) is left to it (that serve is the IPC provider, #4896). Each socket the serve could not bind (its source socket, the legacy socket, also when only the persistence listener came up) is retried on its own unref'd timer (`RESOLVE_IPC_REBIND_INTERVAL_MS` = 30 s plus up to 5 s jitter, `rebindDelayMs` injectable) through the same `startResolveIpcServer`, so a surviving serve takes over once the owner probes dead and logs `[resolve-ipc] took over <path>`; bind attempts are serialized per serve, `close()` clears the timers and closes a bind that lands after it, and persistence is never re-set-up (#6647, pinned by `te... (line truncated to 2000 chars)
-- `src/mcp/server.ts` — MCP stdio server. initialize and tools/list are built from `OPERATION_MANIFEST` (`src/core/operation-manifest.generated.ts`, every op minus its handler) so the handler graph behind `src/core/operations.ts` stays unloaded until it is needed; byte-identity with the eager registry across surfaces, strict params, read-only access, publish gates and the advertised surface is pinned by `test/mcp-tool-list-snapshot.test.ts`. Engine-dependent boot (`bootEngineDependents`: source scope, persistence consumer, resolve-IPC bind, startup sweep; #7599: a read-only stdio serve on Postgres (`readOnlyServeSkipsResidentDuties`) binds IPC with no delegation kinds (`lean`), starts no consumer, runs no session-cursor GC or startup sweep and writes `READ_ONLY_SERVE_NOTE` to stderr; PGLite keeps all of it) and the dispatch/hot-memory imports wait for the handshake (`deferredBoot`, boot phase `initialize_wait`): they start when the first tools/list is answered, `BOOT_LIST_GRACE_MS` after initialize with no tools/list in flight, or `BOOT_WITHOUT_INITIALIZE_MS` after connect for a client that never initializes. Every tools/call and skill resource read awaits that boot, and a boot failure rejects them with the boot error while `startMcpServer` still rejects with it. Status-only mode (F4, `src/mcp/status-mode.ts`): over a status engine it lists only `gbrain_status`, answers other tools with one `serve_status_only` block, and every tool call re-probes and may recover in place (then `tools/list_changed`). `gbrain://capabilities` carries readiness[], the probed worker status (`stdioCapabilityReadiness`), and `surface`/`surface_source`. One `StdioSurfaceState` (`createStdioSurfaceState` in `surface.ts`) per process is the allow-set tools/list, dispatch (`allowedOps`, `stdioSurface`), skill resources and `gbrain_status` read; `request_tools {surface}` widens it for the session (stderr `surface_widened` audit line, then `tools/list_changed`), and `mcp.allow_session_widen` is resolved at boot. An ignored `GBRAIN_SURFACE` (`invalidSurfaceEnv`) adds one `surface_env_invalid` notice to the first successful tool result. After the engine boots it starts the onboarding cache (`startOnboardingRefresher` from `src/core/onboard/mcp-onboarding.ts`) with an idle gate on the in-flight RPC counter. `startMcpServer`'s optional `onBootPhase` reports each boot phase (`source_preflight` … `startup_sweep`) so `serve`'s boot-deadline line can name the one that never finished. Its SDK `Server` is initialized with the shared contract from `src/mcp/instructions.ts`, so a real client's `getInstructions()` is populated during the initialize handshake. `createDefaultWriteAdvisory(engine, {enabled, write?})` is the stdio lane's once-per-process unscoped-default-write advisory: on a mutating call whose source resolved to tier `seed_default` it runs `assessUnscopedDefaultWrite` (`src/core/source-resolver.ts`) and prints the warning to stderr; it latches on the first SUCCESSFUL assessment whatever the verdict (the aggregate is expensive and its inputs are process-stable), never latches on a failed one (fail-open for that write; the next mutating seed_default call retries), coalesces concurrent calls onto one in-flight assessment, and never blocks a write (a throwing writer still counts as assessed). Non-mutating calls and non-seed tiers return early without latching. Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. The resolve-IPC listener (retrieval-reflex resolve / turn_context / context_pack + the serve-delegated sync and sweep kinds) binds through `src/mcp/resolve-ipc-binding.ts` (next entry) on BOTH serve transports — stdio here and `gbrain serve --http`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts` and `test/serve-stdio-roundtrip.test.ts`. Each tool call resolves its source inside one request config snapshot that dispatch reuses for a read op (the config table is read alongside the source rows), so the pre-op reads cost one round trip (GBRA-156).
+- `src/mcp/server.ts` — MCP stdio server. initialize and tools/list are built from `OPERATION_MANIFEST` (`src/core/operation-manifest.generated.ts`, every op minus its handler) so the handler graph behind `src/core/operations.ts` stays unloaded until it is needed; byte-identity with the eager registry across surfaces, strict params, read-only access, publish gates and the advertised surface is pinned by `test/mcp-tool-list-snapshot.test.ts`. Engine-dependent boot (`bootEngineDependents`: source scope, persistence consumer, resolve-IPC bind, startup sweep; #7599: a read-only stdio serve on Postgres (`readOnlyServeSkipsResidentDuties`) binds IPC with no delegation kinds (`lean`), starts no consumer, runs no session-cursor GC or startup sweep and writes `READ_ONLY_SERVE_NOTE` to stderr; PGLite keeps all of it) and the dispatch/hot-memory imports wait for the handshake (`deferredBoot`, boot phase `initialize_wait`): they start when the first tools/list is answered, `BOOT_LIST_GRACE_MS` after initialize with no tools/list in flight, or `BOOT_WITHOUT_INITIALIZE_MS` after connect for a client that never initializes. Every tools/call and skill resource read awaits that boot, and a boot failure rejects them with the boot error while `startMcpServer` still rejects with it. Status-only mode (F4, `src/mcp/status-mode.ts`): over a status engine it lists only `gbrain_status`, answers other tools with one `serve_status_only` block, and every tool call re-probes and may recover in place (then `tools/list_changed`). `gbrain://capabilities` carries readiness[], the probed worker status (`stdioCapabilityReadiness`), and `surface`/`surface_source`. One `StdioSurfaceState` (`createStdioSurfaceState` in `surface.ts`) per process is the allow-set tools/list, dispatch (`allowedOps`, `stdioSurface`), skill resources and `gbrain_status` read; `request_tools {surface}` widens it for the session (stderr `surface_widened` audit line, then `tools/list_changed`), and `mcp.allow_session_widen` is ... (line truncated to 2000 chars)
- `src/mcp/source-preflight.ts` — `assertStdioSourceBindable(engine, env?)`: stdio-lane boot preflight called first thing in `startMcpServer`, before any transport attaches. A well-formed `GBRAIN_SOURCE` that names no ACTIVE source row (`SELECT id FROM sources WHERE id = $1 AND archived = false`, the same predicate as `assertSourceExists` in `src/core/source-resolver.ts`) throws a message naming the value and the fix (`gbrain sources list`), so serve exits 1 instead of binding every call to a phantom scope where reads return `[]` and writes die on the sources FK while health stays green. An inherited `__all__` emits an engine-free stderr warning with a source-binding recovery action, without widening its fail-closed scope. Unset env and malformed values are left to the resolver; an engine error fail-opens (guards config, not connectivity); a degraded engine (`isEngineDegraded`) is never touched so the boot does not spend the proxy's reconnect attempt. HTTP is out of scope (tokens carry their own source grant). Pinned by `test/mcp-stdio-source-preflight.test.ts` and real PostgreSQL/PGLite processes in `test/e2e/mcp-search-transport-matrix.test.ts`.
+- `src/mcp/stdio-lifecycle.ts` — engine-free stdio plumbing shared by local serve and the bridge: `mcpStdioTransport`/`MCP_STDIO_MAX_MESSAGE_BYTES`, `resolveEofDrainMs`, `isPidAlive`/`readLiveParentPid`/`probeWatchdogAvailable`, and `installStdioShutdownTriggers` (signals, the bounded stdin-EOF drain with `onDrainExpired`, the `MCP_STDIO=1` and TTY skips, the parent watchdog). Pinned by `test/serve-stdio-lifecycle.test.ts` and `test/serve-stdin-eof-drain.test.ts`.
- `src/core/mcp-registration.ts` — `REGISTRATION_SURFACE` (`full` since S0, wave 0: callable and advertised; README, docs/mcp, INSTALL_FOR_AGENTS.md and the plugin manifests name the same value, which the S0 grep test in `test/mcp-registration.test.ts` keeps so), `stdioServeArgv(bin, surface = REGISTRATION_SURFACE)` (`null` → bare `serve`) and `registeredSurface(text)` (an existing entry's pinned surface, `null` for bare, `undefined` when no serve command is visible): every stdio registration gbrain writes builds from them (readiness `harness_wiring`, init's quickstart, `bootstrap hooks` for Claude Code / Codex / opencode, the plugin generator, which also refuses root plugin manifests pinned elsewhere). The OpenClaw manifest stays a bare `serve`. Also the HTTP+bearer wiring helpers `connect.ts` re-exports. Test: `test/mcp-registration.test.ts`.
- `src/core/serve-log.ts` — serve's own log hygiene (#7246), installed by `src/cli/commands/serve.ts` before `runServe`. For each of stderr, and stdout under `--http` only (stdio serve's stdout is the JSON-RPC channel), whose descriptor is a regular file, it routes console and stream writes through a `ServeLogFile`: `LineDeduper` writes the first occurrence of a line at once and counts repeats inside the window (a leading timestamp ignored), then writes one `[gbrain serve-log] repeated N more time(s) in the last Ws: <line>` line when the window ends or the process exits; rotation is copy-then-truncate on the inherited append-mode descriptor (`<log>.N-1` → `<log>.N`, `<log>` → `<log>.1`, truncate), each write placed at the file's current end, and only when the descriptor's path is known (`/proc/self/fd` or the `serveLogPath`/`serveErrPath` inode) and still names the same inode. TTYs, pipes and journald are untouched. `GBRAIN_SERVE_LOG_MAX_BYTES` (10 MiB; 0 off), `GBRAIN_SERVE_LOG_MAX_FILES` (5), `GBRAIN_SERVE_LOG_DEDUPE_SECONDS` (600; 0 off). Tests: `test/serve-log-7246.test.ts`.
- `src/core/ops/request-tools.ts` — `request_tools`: catalog (no args), descriptors (`{tools}`; D1: an empty list or one with no caller-visible name returns the catalog plus `did_you_mean` drawn only from `visibleOpsForCaller`, never echoing the requested names, so an invisible existing op and a nonexistent one answer byte-identically), and `{surface}`: per OAuth client on HTTP (ceiling, operator lock, rate limit, audit), and on the owner's stdio pipe `widenStdioSession` widens `ctx.stdioSurface` for the session (refused with the persistent route when `mcp.allow_session_widen` is off; clamped by `GBRAIN_MCP_FORCE_SURFACE`; returns `persisted:false, scope:'session'` and the new tools' schemas). A widenable stdio session's catalog lists the full surface. `{tools}` returns each visible op's registry schema, so a starter client also gets the `fullSurfaceOnly` params its tools/list leaves out (dispatch accepts them on every surface). `{surface, tools}` together (GBRA-449) runs the `{surface}` branch first, exactly as alone (refusals included), then the `{tools}` branch against the resulting surface, and answers the descriptor shape plus `surface_change` (the surface answer). Tests: `test/request-tools.test.ts`, `test/request-tools-stdio.test.ts`, `test/request-tools-combined-gbra449.test.ts`.
-- `src/mcp/surface.ts` — MCP tool-surface modes: `'verbs'` (exactly the ops marked `verb: true`) | `'starter'` (the ~27-op daily-driver set) | `'full'` (default — identity; existing installs unchanged). `STARTER_OPS` is composed PROGRAMMATICALLY: a spread of `VERB_NAMES` (never a hand-count) + the fallback daily slice (`BRAIN_TOOL_ALLOWLIST` + the agent lane `submit_agent`/`get_agent_job`) + `whoami` + `request_tools` + `capture` (a DIRECT literal, deliberately NOT via the allowlist); re-derived from production usage via `scripts/derive-starter-ops.ts` (paste-in proposal, never an auto-edit). `ALWAYS_INCLUDED_STARTER_OPS` (verbs + `whoami` + `request_tools` + the agent lane + `capture`) is the exported always-set consumed by BOTH `derive-starter-ops.ts` and the advisor starter-fit collector, so neither re-types the composition. `parseSurfaceFlag` (strict, loud reject; reads `--surface v` and `--surface=v` through `flagValues` in `src/core/direct-pool-profile.ts`, and a repeated flag takes the narrowest), `resolveSurface`/`resolveSurfaceWithSource` (flag > config `mcp_surface` > full, the `serve --http` order), `resolveStdioSurface` (stdio: `GBRAIN_SURFACE` > flag > config > full; an invalid env value is returned as `invalidEnv`, never fatal; `surfaceEnvInvalidNotice` builds its notice), `SURFACE_SOURCE_LABEL`, `filterOpsForSurface`, `allowedOpNames`, `createStdioSurfaceState` (the stdio session's one mutable allow-set; `widen(to)` recomputes it, read-only stays read-only), `sessionWidenAllowed` (`mcp.allow_session_widen`, DB > file, default true). `STARTER_OPS` also carries `mute_notice`, the dismissal for the coaching notices starter sessions receive. Enforcement is TWO-layer and fail-closed: the advertised list AND `dispatchToolCall`'s `allowedOps` set (a hidden op returns `unknown_tool` even when called by name) — applied on stdio (server.ts) and BOTH HTTP paths (serve-http.ts after `!localOnly`, and the second transport http-transport.ts). Per-client ceiling machinery (OAuth transport only): `effectiveSurfaceForClient` is the pure composition `clamp(min(server ceiling, client row surface ?? mcp.default_surface_dcr ?? ceiling))`; the per-REQUEST application lives in serve-http.ts's `resolveEffectiveSurface`, which short-circuits a `verbs` ceiling (min() cannot go lower, so the config read is skipped), gives a legacy bearer token (`principal.kind === 'legacy_token'`, no client row) the clamped ceiling instead of the DCR default (#9266), and, on a default-surface read failure, applies the LAST successfully read default (held per process, fail-closed) so a transient config outage cannot silently widen a NULL-surface client to the ceiling; `resolveClientRowSurface` ignores unknown row values with a bounded warn-once (the column's value space is documented OPEN for future tier names); `resolveDefaultClientSurface` reads the DCR default dual-plane (DB > file > null) and never throws; `clampSurface`/`readForceSurfaceEnv` fold in the `GBRAIN_MCP_FORCE_SURFACE` kill switch — NARROW-ONLY by construction (min(); can never widen past the ceiling). `minSurface`/`surfaceWiderThan` own the verbs < starter < full rank math. Pinned by test/mcp-surface.test.ts (membership, monotonicity verbs ⊆ starter ⊆ full, ceiling + force-narrow cases). `--access read-only` (`parseAccessFlag`, either form through `flagValues`, any read-only value wins; stdio only; HTTP refuses it) intersects the surface with `isReadOnlyOperation` (read scope, not mutating, no required capability scope); `src/mcp/server.ts` uses that one set for tools/list, the capabilities resource (`access`), skill resources and dispatch `allowedOps`. Pinned by `test/serve-stdio-read-only.test.ts`. `mcp.advertised_surface` (`resolveAdvertisedSurface`, DB plane > file plane) narrows only what `tools/list` shows (`advertisedOps`, never wider than the callable set); dispatch keeps the ceiling. Stdio lists the advertised set plus tools `request_tools` described in this session (`OperationContext.revealTools` → `tools/list_changed`); the OAuth HTTP server lists a client's own row surface in full and otherwise the advertised set; the simple bearer transport reads the file plane once at startup. Initialize instructions carry `hiddenCallable` and name `request_tools` when tools are unlisted. `NEW_INSTALL_ADVERTISED_SURFACE` is what a fresh `gbrain init` writes (`'full'` writes nothing; the held-out agent benchmark picks verbs or starter). Pinned by `test/mcp-advertised-surface.test.ts`. Once a session widens (`request_tools {surface}`), the whole widened surface is listed.
+- `src/mcp/surface.ts` — MCP tool-surface modes: `'verbs'` (exactly the ops marked `verb: true`) | `'starter'` (the ~27-op daily-driver set) | `'full'` (default — identity; existing installs unchanged). `STARTER_OPS` is composed PROGRAMMATICALLY: a spread of `VERB_NAMES` (never a hand-count) + the fallback daily slice (`BRAIN_TOOL_ALLOWLIST` + the agent lane `submit_agent`/`get_agent_job`) + `whoami` + `request_tools` + `capture` (a DIRECT literal, deliberately NOT via the allowlist); re-derived from production usage via `scripts/derive-starter-ops.ts` (paste-in proposal, never an auto-edit). `ALWAYS_INCLUDED_STARTER_OPS` (verbs + `whoami` + `request_tools` + the agent lane + `capture`) is the exported always-set consumed by BOTH `derive-starter-ops.ts` and the advisor starter-fit collector, so neither re-types the composition. `parseSurfaceFlag` (strict, loud reject; reads `--surface v` and `--surface=v` through `flagValues` in `src/core/direct-pool-profile.ts`, and a repeated flag takes the narrowest), `resolveSurface`/`resolveSurfaceWithSource` (flag > config `mcp_surface` > full, the `serve --http` order), `resolveStdioSurface` (stdio: `GBRAIN_SURFACE` > flag > config > full; an invalid env value is returned as `invalidEnv`, never fatal; `surfaceEnvInvalidNotice` builds its notice), `SURFACE_SOURCE_LABEL`, `filterOpsForSurface`, `allowedOpNames`, `createStdioSurfaceState` (the stdio session's one mutable allow-set; `widen(to)` recomputes it, read-only stays read-only), `sessionWidenAllowed` (`mcp.allow_session_widen`, DB > file, default true). `STARTER_OPS` also carries `mute_notice`, the dismissal for the coaching notices starter sessions receive. Enforcement is TWO-layer and fail-closed: the advertised list AND `dispatchToolCall`'s `allowedOps` set (a hidden op returns `unknown_tool` even when called by name) — applied on stdio (server.ts) and BOTH HTTP paths (serve-http.ts after `!localOnly`, and the second transport http-transport.ts). Per-client ceiling mac... (line truncated to 2000 chars)
- `src/mcp/tool-catalog.ts` — `renderToolCatalogMarkdown()`: the docs/TOOL_CATALOG.md renderer. Config-independent + deterministic (no engine/config reads, no timestamps): non-localOnly ops grouped one section per `Operation.area`, per-op first-sentence description (from `buildToolDefs`'s non-strict shape), scope, STARTER_OPS membership, publish-gate key. Generated by `scripts/generate-tool-catalog.ts`; freshness-guarded by `scripts/check-tool-catalog-fresh.sh` in `bun run verify` (the METRIC_GLOSSARY pattern). Pinned by test/tool-catalog.test.ts.
- `src/mcp/tool-defs.ts` — `buildToolDefs(ops, opts?)` helper; the stdio MCP server, the OAuth HTTP `tools/list`, and the subagent tool registry all consume it, byte-for-byte equivalence pinned by `test/mcp-tool-defs.test.ts`. `opts.strictParams: true` (when `mcp.strict_params` resolves `'reject'`) additionally declares the `_meta`/`dry_run`/`room` passthrough keys in `properties` and closes each schema with `additionalProperties: false` (schema-validating clients must not strip `_meta.session_id`); both emission states pinned. Exports the recursive `paramDefToSchema(p: ParamDef)` — single source of truth for ParamDef→JSON Schema mapping shared by `buildToolDefs` and `src/core/minions/tools/brain-allowlist.ts` (subagent registry). Recursive on `items` so nested array-of-arrays preserves inner shape on the wire, and on object `properties` (closed with `additionalProperties: false`, member `required` keys). Key ordering (type, description, enum, default, items, properties) is intentional so `JSON.stringify` output stays byte-stable. `toolAnnotations(op)` is the one annotation rule: curated op annotations win; else `readOnlyHint: true` for a read-scope op tagged `mutating: false`, `readOnlyHint: false` for one tagged `mutating: true`, nothing for untagged ops. `test/mcp-tool-defs.test.ts` has a `findArrayWithoutItems` walker that fails on any `type: 'array'` lacking `items.type`. Annotations: curated `op.annotations` win; else `readOnlyHint: true` iff `mutating === false`, `readOnlyHint: false` (+ `idempotentHint: true` when `idempotent`) iff `mutating === true`; every op declares both tags (`test/ops-mutation-tags.test.ts`).
-- `src/mcp/validate-params.ts` — param normalization + validation for dispatch (direct unit surface). `validateParams` (required/type/enum — enum membership is a TYPE error in BOTH strict modes; the caller's raw value is never echoed into the message), `normalizeOptionalParams` (null/`''` optional-param idioms become truly absent, and so do the values a param's schema rules out: `0` below `minimum`/`exclusiveMinimum`, `[]` under `minItems`, `{}` on an object with a required member, `false` on an `actsWhenTrue` flag, then any param whose `appliesWith` param is absent (GST-927); required params untouched, copy-on-write), `findUnknownParams` (unknown top-level keys on the NORMALIZED object; `UNKNOWN_PARAM_ALLOWLIST` = `_meta` + `dry_run`; per-op did-you-mean from the op's OWN declared params only, plus the explicit `PARAM_ALIAS_HINTS` aliases edit distance cannot reach, e.g. `add_timeline_entry` `content` → `detail` and `remember` `facts` → `items`, `text` → `fact`; dispatch rejects unknown keys on every `mutating` op regardless of `mcp.strict_params`, so a typo never commits a write, and appends the op's optional `callShape` (a valid call with placeholder values, set only by `remember`, GST-1493) to the suggestion), `buildUnknownParamWarnBlock` (the model-visible warn notice), `resolveStrictParamsMode(engine, config)` (dual-plane `mcp.strict_params`, DB > file > `'warn'`; a failed DB read applies the LAST successfully read DB mode, held per engine — fail-closed, so a transient config outage on a reject-mode server cannot re-open the warn grace period; test seam `resetStrictParamsModeCache()`). Privacy: raw unknown key names reach the CALLER only, never `mcp_request_log`. Pinned by test/validate-params.test.ts. Every path that hands arguments to an op handler runs normalize → validate first: `dispatchToolCall`, `handleToolCall` (`gbrain call`) and the SkillOpt rollout and write-capture registries, so a model that sends `""` or `null` for every optional argument reads the same as one that omits them (`test/tool-args-empty-optional-sol.test.ts`). On a remote call the audience and attested-actor checks in `dispatchToolCall` read the normalized arguments, so `acting_user: ""` or `null` counts as omitted.
+- `src/mcp/validate-params.ts` — param normalization + validation for dispatch (direct unit surface). `validateParams` (required/type/enum — enum membership is a TYPE error in BOTH strict modes; the caller's raw value is never echoed into the message), `normalizeOptionalParams` (null/`''` optional-param idioms become truly absent, and so do the values a param's schema rules out: `0` below `minimum`/`exclusiveMinimum`, `[]` under `minItems`, `{}` on an object with a required member, `false` on an `actsWhenTrue` flag, then any param whose `appliesWith` param is absent (GST-927); required params untouched, copy-on-write), `findUnknownParams` (unknown top-level keys on the NORMALIZED object; `UNKNOWN_PARAM_ALLOWLIST` = `_meta` + `dry_run`; per-op did-you-mean from the op's OWN declared params only, plus the explicit `PARAM_ALIAS_HINTS` aliases edit distance cannot reach, e.g. `add_timeline_entry` `content` → `detail` and `remember` `facts` → `items`, `text` → `fact`; dispatch rejects unknown keys on every `mutating` op regardless of `mcp.strict_params`, so a typo never commits a write, and appends the op's optional `callShape` (a valid call with placeholder values, set only by `remember`, GST-1493) to the suggestion), `buildUnknownParamWarnBlock` (the model-visible warn notice), `resolveStrictParamsMode(engine, config)` (dual-plane `mcp.strict_params`, DB > file > `'warn'`; a failed DB read applies the LAST successfully read DB mode, held per engine — fail-closed, so a transient config outage on a reject-mode server cannot re-open the warn grace period; test seam `resetStrictParamsModeCache()`). Privacy: raw unknown key names reach the CALLER only, never `mcp_request_log`. Pinned by test/validate-params.test.ts. Every path that hands arguments to an op handler runs normalize → validate first: `dispatchToolCall`, `handleToolCall` (`gbrain call`) and the SkillOpt rollout and write-capture registries, so a model that sends `""` or `null` for every optional argument reads t... (line truncated to 2000 chars)
- `src/core/mcp-request-log-retention.ts` — opt-in request-log retention (`cycle.purge.mcp_request_log_retention_days`: unset/0/off = off, 30-3650; `mcpLogRetentionRefusal` is the `config set` refusal). `pruneMcpRequestLog` runs batches of 2,000 (200 per run, the cutoff fixed once), each ONE statement: oldest rows past the cutoff in `created_at` order `FOR UPDATE SKIP LOCKED`, minus `AUDIT_LOG_OPERATIONS`, deleted and added to `mcp_request_log_rollup` (requests, last_used_at, `pruned_through` = newest pruned row; NULL token under `''`), so a failed tally deletes nothing; a missing tally table skips. `runMcpLogRetention` reads the key and records `{at, deleted, capped}` under `cycle.purge.mcp_request_log_last_prune`; callers: the cycle purge phase and `startMcpLogPruneTicker` (PGLite only, hourly, 3 s budget, yields between batches) in both serve lanes. `lifetimeUsage` = kept rows + tally in one statement (admin Agents totals). Pinned by `test/mcp-request-log-retention.test.ts` (both engines) and `test/serve-http-admin-request-log-retention.test.ts`.
- `src/commands/doctor/checks/mcp-request-log.ts` — doctor `mcp_request_log_retention` (ops): log rows (reltuples on Postgres, a bounded count on PGLite) and size; retention off past 1M rows or 1 GiB warns with an `ask_user` + `destructive` fix (`config set … 90`), never a remediation step; retention on reports `pruned_before` and the last run, and warns when no prune ran for 48 hours (or none ever ran while rows past the window wait). Pinned by `test/doctor-mcp-request-log-retention.test.ts`.
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index fbdbe41763..6393632765 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -6,39 +6,39 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/abort-check.ts` — one canonical place for cooperative-abort checks across gbrain's long loops. `isAborted(signal?)` → boolean (for loops that `break` and return partial progress). `throwIfAborted(signal?, label?)` throws an `AbortError` (`name === 'AbortError'`) at phase boundaries, preferring the signal's `reason` ('wall-clock'/'lock-lost'/'shutdown') so the unwind self-describes. `anySignal(internal, external?)` composes two signals into one that fires when EITHER does (platform `AbortSignal.any` with a manual-relay fallback), returning the internal unchanged when there's no external so non-aborting callers pay nothing. Threading these checks through `runPhaseEmbed → runEmbedCore → embedAll(Stale)/embedPage` lets the embed phase bail and release `gbrain_cycle_locks` immediately (an embed phase that ignored its abort signal would hold the lock and make later autopilot cycles skip with `cycle_already_running`). Coverage spans every long cycle-reachable phase: `extract` (incremental `extractForSlugs` + the full-walk `extractLinksFromDir`/`extractTimelineFromDir`, all via `runSlidingPool`'s signal), `extract_facts` (per-page loop + the per-page `embed` signal + `runPhantomRedirectPass`'s 30s lock-retry), `consolidate`'s bucket loop, and `lint` (which is synchronous, so it `await`s a periodic yield to let the signal land). `runCycle` adds a terminal abort check before stamping `last_full_cycle_at` so a cancelled cycle never reports a completed full run, plus a per-phase `duration_ms` warning that names any phase overrunning the worker's 30s force-evict deadline. Pinned by `test/abort-check.test.ts` + `test/cycle-abort.test.ts`.
- `src/core/abort-signals.ts` — leaf module (no imports): `anyAbortSignal(signals)` fans several signals into one real `AbortSignal`, tolerating duck-typed `{ aborted }` stubs (polled every 50 ms) where `AbortSignal.any` would throw; returns `{signal, dispose}`, and `dispose()` must run when the scope ends so long-lived caller signals do not accumulate listeners. `cycle.ts` re-exports it; the extract_atoms drain imports it directly without loading the cycle. Tests: `test/cycle-any-abort-signal.test.ts`.
-- `src/core/background-work.ts` — process background-work registry: the single owner of "drain every fire-and-forget DB-write sink before the engine goes away," with TWO exit points. `registerBackgroundWorkDrainer({name, order, drain(timeoutMs, mode), abort?})` over a `Map<name, BackgroundWorkDrainer>` (idempotent registration by name; `__registerDrainerForTest` returns an unregister handle); `mode` is `'exit' | 'disconnect'` (`'exit'` = CLI teardown, engine still live, residual buffers may flush; `'disconnect'` = an engine is mid-disconnect, sinks await only IN-FLIGHT work and never start new writes). `drainAllBackgroundWorkForCliExit({timeoutMs})` runs mode `'exit'` with abort allowed; `drainBackgroundWorkBeforeDisconnect({timeoutMs})` is called by BOTH engines' `disconnect()` so an in-flight statement settles before the underlying handle closes — PGLite's `close()` deadlocks PERMANENTLY with a statement in flight — and it NEVER calls `abort()` (permanent process state, wrong for a long-lived `gbrain serve` disconnecting one engine); a partial disconnect-drain warns once per sink to stderr. The module stays a zero-import leaf on purpose (both engines import it statically). Drains in explicit `(order, name)` order — facts FIRST (order 0) so its abort-path DB `logIngest` runs against the freshest live engine — and AWAITS `abort()` only when `drain()` reports `unfinished>0` in `'exit'` mode. Best-effort per drainer: one sink's failure never blocks the others or the disconnect. SIX sinks register at module import: `facts/queue.ts` (order 0; `abort`=`shutdown()` cancels a hung facts:absorb Haiku via internalAbort), `last-retrieved.ts` (order 1), `search/hybrid.ts` (order 2; `awaitPendingSearchCacheWrites` bounded via `Promise.race`), `eval-capture.ts` (order 3; `captureEvalCandidate` self-tracks its promise via `awaitPendingEvalCaptures`), `context/volunteer-events.ts` (order 4 — batched volunteer-event INSERTs, drained like the rest), `search/telemetry.ts` (order 5 — `awaitPendingTelemetryFlush`: awaits the in-flight flush in both modes, flushes residual buckets only in `'exit'` mode so short-lived CLI calls land in `search_telemetry` on clean exit). Every cli.ts teardown site reaches it through `finishCliTeardown` (`src/core/cli-force-exit.ts`), which drains the registry before `engine.disconnect()`, so `db.close()` cannot race an in-flight job and pin the PGLite single-writer lock. Exports `backgroundWorkSinkCount()` so the teardown helper computes its backstop deadline from the registered sink count, plus the shared teardown budgets: `MAX_TIMER_DELAY_MS` (the 2^31−1 setTimeout ceiling; `process-watchdog.ts` aliases it as `MAX_WATCHDOG_TIMER_MS`), `SINK_DRAIN_TIMEOUT_MS` (the per-sink drain bound, used as the `runDrainers` default), and `pgliteCloseTimeoutMs()` (the env-tunable in-loop close bound, defined here so `cli-force-exit`'s computed deadline budgets the SAME bound the engine honors). CLI-EXIT-ONLY: the facts `shutdown()` abort is permanent process state, never call in a long-lived `gbrain serve`. Companion changes: `src/core/ai/gateway.ts` `withDefaultTimeout(caller, ms)` bounds every outbound AI call (chat 300s, embed+multimodal 60s; env `GBRAIN_AI_{CHAT,EMBED,MULTIMODAL}_TIMEOUT_MS`; composed with caller signals via `AbortSignal.any`) and the teardown backstop honors an errored op's exit code so a hung disconnect can't mask failure as success (see `cli-force-exit.ts`); `src/core/postgres-engine.ts` `reconnect()` module-mode branch re-establishes via idempotent `db.connect()` + `connectionManager.setReadPool` refresh instead of `db.disconnect()` (no null window for concurrent ops; fail-loud on real connect failure); `src/core/search/hybrid.ts` `embedQueryBounded` + a shared `QueryEmbedDeadline` (6s, floored 2s per embed via `MIN_QUERY_EMBED_BUDGET_MS`; env `GBRAIN_QUERY_EMBED_TIMEOUT_MS`) bounds the cache-lookup AND inner query embeds so a stalled provider falls back to keyword instead of stalling the whole op. Pinned by `test/core/background-work.test.ts`, `test/search/query-embed-deadline.test.ts`, `test/eval-capture-drain.test.ts`, `test/e2e/postgres-reconnect-singleton.test.ts`, `test/e2e/pglite-cli-exit.serial.test.ts`, `test/fix-wave-structural.test.ts`.
+- `src/core/background-work.ts` — process background-work registry: the single owner of "drain every fire-and-forget DB-write sink before the engine goes away," with TWO exit points. `registerBackgroundWorkDrainer({name, order, drain(timeoutMs, mode), abort?})` over a `Map<name, BackgroundWorkDrainer>` (idempotent registration by name; `__registerDrainerForTest` returns an unregister handle); `mode` is `'exit' | 'disconnect'` (`'exit'` = CLI teardown, engine still live, residual buffers may flush; `'disconnect'` = an engine is mid-disconnect, sinks await only IN-FLIGHT work and never start new writes). `drainAllBackgroundWorkForCliExit({timeoutMs})` runs mode `'exit'` with abort allowed; `drainBackgroundWorkBeforeDisconnect({timeoutMs})` is called by BOTH engines' `disconnect()` so an in-flight statement settles before the underlying handle closes — PGLite's `close()` deadlocks PERMANENTLY with a statement in flight — and it NEVER calls `abort()` (permanent process state, wrong for a long-lived `gbrain serve` disconnecting one engine); a partial disconnect-drain warns once per sink to stderr. The module stays a zero-import leaf on purpose (both engines import it statically). Drains in explicit `(order, name)` order — facts FIRST (order 0) so its abort-path DB `logIngest` runs against the freshest live engine — and AWAITS `abort()` only when `drain()` reports `unfinished>0` in `'exit'` mode. Best-effort per drainer: one sink's failure never blocks the others or the disconnect. SIX sinks register at module import: `facts/queue.ts` (order 0; `abort`=`shutdown()` cancels a hung facts:absorb Haiku via internalAbort), `last-retrieved.ts` (order 1), `search/hybrid.ts` (order 2; `awaitPendingSearchCacheWrites` bounded via `Promise.race`), `eval-capture.ts` (order 3; `captureEvalCandidate` self-tracks its promise via `awaitPendingEvalCaptures`), `context/volunteer-events.ts` (order 4 — batched volunteer-event INSERTs, drained like the rest), `search/telemetry.ts` (order 5 — ... (line truncated to 2000 chars)
- `src/core/backoff.ts` — Adaptive load-aware throttling: CPU/memory checks, exponential backoff, active hours multiplier.
-- `src/core/cli-force-exit.ts` — single owner of one-shot CLI exit + teardown, designed as a PAIR with the exit seam `runCli()` in `src/cli/main.ts` (called by the `src/cli.ts` entry point after its fast paths). `finishCliTeardown({engine, drainTimeoutMs?})` is teardown-ONLY (never exits on the clean path): arms a REF'D backstop (unref'd would let a hung teardown exit naturally, skipping the flush and exiting with whatever PGLite scribbled into `process.exitCode`) whose deadline is COMPUTED from the bounds it guards (`computeTeardownDeadlineMs` = sinks × drainTimeoutMs + sinks × `SINK_DRAIN_TIMEOUT_MS` disconnect-drain bound + the RESOLVED PGLite close bound (`pgliteCloseTimeoutMs()` from background-work.ts — an operator-raised `GBRAIN_PGLITE_CLOSE_TIMEOUT_MS` widens this backstop too, never a hardcoded copy of the default) + facts-abort grace + 2 × pool-end bound + slack, floor 10s — the disconnect-drain and close terms budget `engine.disconnect()`'s own drain pass and bounded close so the backstop can't fire while every component honored its own bound; `GBRAIN_TEARDOWN_DEADLINE_MS` env override is the incident escape hatch), drains every background-work sink, disconnects the engine (a throw is warned + swallowed — the exit code reports the OPERATION, not the cleanup), then returns. The exit VERDICT lives in a gbrain-owned channel (`setCliExitVerdict`/`currentExitCode`; mirror-writes `process.exitCode` but NEVER reads it back) because PGLite's Emscripten runtime scribbles its own status into `process.exitCode` at arbitrary points mid-run — every writer that means to set the CLI exit code (op-dispatch catch, reindex, frontmatter, transcripts, brainstorm, autopilot, doctor's FAIL verdict, extract, and cli.ts's swept inner exits — friction, claw-test, smoke-test, the no-DB eval runners, status/status-thin, whoknows-thin) calls `setCliExitVerdict`; `test/cli-exit-verdict-pin.test.ts` greps src/ so the next raw `process.exitCode =` write fails CI instead of silently reporting success on failure. The deadline arms at TEARDOWN start, never before the op handler (arming before the handler would measure handler + teardown combined, taxing PgBouncer deployments with a flat force-exit deadline on every query and killing any long op mid-run with exit 0). All nine cli.ts disconnect sites route through it; the ONE process exit happens in cli.ts's `main().then/catch` via `flushThenExit(currentExitCode())`, gated by `shouldForceExitAfterMain()` (daemon list: `serve`) — the CLI never waits for Bun's event loop to drain, because `endPoolBounded` deliberately races past stuck PgBouncer sockets that would keep it alive. `flushThenExit(code)` fences stdout+stderr (`write('', cb)` raced with an unref'd guard, EPIPE-safe both sync and async), then exits as soon as no non-TTY stream holds queued bytes — Bun delivers queued pipe writes only while the process is alive (write callbacks fire on accept, not delivery). process.stdout's one-shot writes go through the fd-1 write chain, and `installStdoutPipeDelivery` wraps process.stderr to track Bun's native queue (`write()` returns false exactly when bytes stayed queued; `'drain'` fires when it empties), so with nothing queued the exit is immediate, a queued stream ends the wait at its `'drain'`, and the REF'D grace (250 ms, `GBRAIN_FLUSH_GRACE_MS`) is only the upper bound — or a fixed sleep for a stream nothing tracks (a daemon's fatal path, test doubles). `test/cli-exit-drain.test.ts` pins it on real pipes. Scope claim is deliberately cli.ts-only: command modules' mid-run engine lifecycles stay local (process-exit semantics inside them would be wrong) and are absorbed by the final explicit exit. Pinned by `test/cli-finish-teardown.test.ts`, `test/flush-then-exit-harness.test.ts` (real spawned-Bun pipe semantics), `test/cli-should-force-exit.test.ts`, `test/cli-pipe-truncation.test.ts` (real-CLI piped --tools-json byte-stable), `test/cli-exit-verdict-pin.test.ts`, the teardown describes in `test/fix-wave-structural.test.ts` + `test/e2e/pglite-cli-exit.serial.test.ts`, and `test/e2e/pgbouncer-teardown.test.ts` (CI transaction-mode pooler). Agent contract v1: `jsonRequested(argv)`; `installStdoutPipeDelivery({ json })` guard mode (see `src/cli/json-guard.ts` in [agent contract](agent-contract.md)); `writeNdjsonLine`; `spawnCliChild` (the one `stdio: 'inherit'` site); `noteRenderedErrorCode` feeds the fallback document's `code`. D2 helpers: `writeJsonDocument` (the one document under the guard, the caller's legacy writer otherwise), `writeJsonLine` (its NDJSON analog), `jsonGuardActive()`, `cliChildStdio()` (sync child CLIs: child stdout to fd 2 under the guard); an empty NDJSON stream at exit 0 is valid (no `json_document_missing`).
+- `src/core/cli-force-exit.ts` — single owner of one-shot CLI exit + teardown, designed as a PAIR with the exit seam `runCli()` in `src/cli/main.ts` (called by the `src/cli.ts` entry point after its fast paths). `finishCliTeardown({engine, drainTimeoutMs?})` is teardown-ONLY (never exits on the clean path): arms a REF'D backstop (unref'd would let a hung teardown exit naturally, skipping the flush and exiting with whatever PGLite scribbled into `process.exitCode`) whose deadline is COMPUTED from the bounds it guards (`computeTeardownDeadlineMs` = sinks × drainTimeoutMs + sinks × `SINK_DRAIN_TIMEOUT_MS` disconnect-drain bound + the RESOLVED PGLite close bound (`pgliteCloseTimeoutMs()` from background-work.ts — an operator-raised `GBRAIN_PGLITE_CLOSE_TIMEOUT_MS` widens this backstop too, never a hardcoded copy of the default) + facts-abort grace + 2 × pool-end bound + slack, floor 10s — the disconnect-drain and close terms budget `engine.disconnect()`'s own drain pass and bounded close so the backstop can't fire while every component honored its own bound; `GBRAIN_TEARDOWN_DEADLINE_MS` env override is the incident escape hatch), drains every background-work sink, disconnects the engine (a throw is warned + swallowed — the exit code reports the OPERATION, not the cleanup), then returns. The exit VERDICT lives in a gbrain-owned channel (`setCliExitVerdict`/`currentExitCode`; mirror-writes `process.exitCode` but NEVER reads it back) because PGLite's Emscripten runtime scribbles its own status into `process.exitCode` at arbitrary points mid-run — every writer that means to set the CLI exit code (op-dispatch catch, reindex, frontmatter, transcripts, brainstorm, autopilot, doctor's FAIL verdict, extract, and cli.ts's swept inner exits — friction, claw-test, smoke-test, the no-DB eval runners, status/status-thin, whoknows-thin) calls `setCliExitVerdict`; `test/cli-exit-verdict-pin.test.ts` greps src/ so the next raw `process.exitCode =` write fails CI instead of silently rep... (line truncated to 2000 chars)
- `src/core/exit-codes.ts` — CLI exit statuses with a contract beyond 0/1: `MIGRATIONS_RUNNING_EXIT_CODE` (75, read by `gbrain upgrade` as a lock conflict; re-exported by `migration-orchestration-lock.ts`) and `PENDING_WRITE_EXIT_CODE` (10, an admitted write still pending) and `BUDGET_STOP_EXIT_CODE` (11, `gbrain embed --stale` stopped at its time budget with stale chunks left; stdout names the remaining count and resume command). Agent contract v1 table: 0 ok, 1 failed, 2 usage (`USAGE_EXIT_CODE`), 3 `confirmation_required` only (`CONFIRMATION_REQUIRED_EXIT_CODE`), 10 pending write, 11 budget stop, 75 migration lock, 124 timeout, 130 interrupted; `test/exit-codes.test.ts` enumerates every exit 3 in src/; guide `docs/guides/exit-codes.md`.
-- `src/core/cli-options.ts` — Global CLI flag parser. `parseGlobalFlags(argv)` returns `{cliOpts, rest}` with `--quiet` / `--progress-json` / `--progress-interval=<ms>` / `--brain <id>` stripped. `--brain` is the brain-axis (which database) selector: exact-match only (`--brain-*` per-command flags pass through), value validated against the mount-id regex at parse time, missing/malformed value THROWS — never a silent host fallback. `connectEngine` in `src/cli.ts` feeds it (plus the ambient `GBRAIN_BRAIN_ID` / `.gbrain-mount` / mount-path tiers) through `resolveBrainId` → `BrainRegistry.getBrain`, which throws `UnknownBrainError` for an unregistered id; mounts get no auto-migrations and keep the host-config AI gateway. `getCliOptions()` / `setCliOptions()` expose a module-level singleton so commands reach resolved flags without parameter threading. `cliOptsToProgressOptions()` maps to reporter options. `childGlobalFlags()` returns the flag suffix to append to `execSync('gbrain ...')` calls in migration orchestrators (propagates `--brain=<id>` so children stay on the parent's brain). `OperationContext.cliOpts` extends shared-op dispatch for MCP callers. `CliOptions` carries `explain: boolean`. `parseGlobalFlags` recognizes `--explain` anywhere in argv (stripped before command dispatch). `--wait <seconds>` (#5232 write wait, 0-600 s, no units; a malformed value is `invalid_params`, exit 2) is slotted like `--timeout`: a route in `WAIT_OWNING_ROUTES` (`sources writer movement`, whose own `--wait` takes a duration) gets every `--wait` handed back appended in the space spelling, order kept (#6625). `src/cli.ts` `formatResult` for `search` + `query` cases routes to `formatResultsExplain` from `src/core/search/explain-formatter.ts` when `CliOptions.explain` is set; falls through to the existing JSON / human formatters otherwise. `maybeBackground(opName, fingerprintArgs, runDirect)` helper. Same semantics in TTY and cron (no `--no-tty-detect` flag, no surprise behavior change between contexts): when `--background` is passed, submits the op as a Minion job via `op_checkpoints` for resumability and returns the `job_id`. `--background --follow` execs `gbrain jobs follow <id>` so the user sees the same stderr stream they'd get from a direct call. PGLite degrades to inline execution with a clear stderr note ("PGLite worker pool not yet supported; running inline"). Returns a tagged union the caller dispatches on.
+- `src/core/cli-options.ts` — Global CLI flag parser. `parseGlobalFlags(argv)` returns `{cliOpts, rest}` with `--quiet` / `--progress-json` / `--progress-interval=<ms>` / `--brain <id>` stripped. `--brain` is the brain-axis (which database) selector: exact-match only (`--brain-*` per-command flags pass through), value validated against the mount-id regex at parse time, missing/malformed value THROWS — never a silent host fallback. `connectEngine` in `src/cli.ts` feeds it (plus the ambient `GBRAIN_BRAIN_ID` / `.gbrain-mount` / mount-path tiers) through `resolveBrainId` → `BrainRegistry.getBrain`, which throws `UnknownBrainError` for an unregistered id; mounts get no auto-migrations and keep the host-config AI gateway. `getCliOptions()` / `setCliOptions()` expose a module-level singleton so commands reach resolved flags without parameter threading. `cliOptsToProgressOptions()` maps to reporter options. `childGlobalFlags()` returns the flag suffix to append to `execSync('gbrain ...')` calls in migration orchestrators (propagates `--brain=<id>` so children stay on the parent's brain). `OperationContext.cliOpts` extends shared-op dispatch for MCP callers. `CliOptions` carries `explain: boolean`. `parseGlobalFlags` recognizes `--explain` anywhere in argv (stripped before command dispatch). `--wait <seconds>` (#5232 write wait, 0-600 s, no units; a malformed value is `invalid_params`, exit 2) is slotted like `--timeout`: a route in `WAIT_OWNING_ROUTES` (`sources writer movement`, whose own `--wait` takes a duration) gets every `--wait` handed back appended in the space spelling, order kept (#6625). `src/cli.ts` `formatResult` for `search` + `query` cases routes to `formatResultsExplain` from `src/core/search/explain-formatter.ts` when `CliOptions.explain` is set; falls through to the existing JSON / human formatters otherwise. `maybeBackground(opName, fingerprintArgs, runDirect)` helper. Same semantics in TTY and cron (no `--no-tty-detect` flag, no surprise behavior change... (line truncated to 2000 chars)
-- `src/core/cli-preflight.ts` — `runCliPreflight()`, the first statement of `cli.ts:main()`. (0) Re-run detection: `GBRAIN_CWD_ENV_QUARANTINED` (`CWD_ENV_QUARANTINED_MARKER`) is parsed as JSON `{cwd, neutral, wrapperPid}` and honoured ONLY when the process's startup cwd realpath-equals `neutral` and `neutral` holds none of `CWD_DOTENV_FILES` (`wrapperPid` is informational — accepted only as a positive safe integer, otherwise ignored); on a verified hop it deletes the marker, `chdir(cwd)`s back, skips step 1 (the parent already warned), and arms `installWrapperWatchdog`: an `unref()`ed 1 s interval comparing `process.ppid` (live in Bun) with `wrapperPid` — a mismatch prints one `[env]` line, `rmdirSync`s the empty neutral dir the wrapper's `finally` never reached, and exits 137, so a supervisor that SIGKILLs the wrapper pid (`restartCurrentChild`, job-isolation children, hook pushes) takes the real re-run down within about a second instead of leaving an orphan; an unverified marker is ignored, never chdir'd on. (1) `parseCwdDotenv(cwd)` ONCE, shared by the cwd == config dir check and `quarantineCwdDotenv(process.env, cwd, { assignments })`. (1a) If the drop removed a NON-EMPTY `GBRAIN_GUARDRAILS_MODULE`, print `GUARDRAILS_ASSIGNED_BY_CWD_DOTENV` and exit 1 — fail-closed, never a re-run without the operator's firewall (the `~/.gbrain/.env` home is read after the quarantine and unaffected). (1b) Otherwise, whenever anything was dropped: `Bun.spawn([execPath, ...execArgv (dev runtime only; `resolveRuntimePaths` resolves a `./`/`../`-relative — or bare-and-existing — value of `--preload`/`-r`/`--require`/`--import`, `--config`/`-c`, `--env-file`, `--tsconfig-override`, both spellings, against the ORIGINAL cwd because the re-run starts in the empty neutral dir; everything else passes through verbatim, in order), entry/user args], { cwd: <fresh mkdtemp dir, realpath'd so `neutral` is absolute+canonical>, env: process.env minus undefined + marker, plus the operator's real `HOME` (`USERPROFILE` on win32, from `os.userInfo().homedir`, which Bun derives from the startup environ before the `.env` merge) when a planted one was dropped, stdio: inherit })` — the re-run's Bun never loads the hostile `.env`, so dropped keys are absent (never `''`, which git and the loader presence-check); signal handlers are installed BEFORE the spawn (no orphan window); `reexecSanitized` first removes every pre-existing SIGINT/SIGTERM/SIGHUP listener (cli.ts installs process-cleanup handlers before `main()`; the wrapper relays the child and nothing else), then forwards SIGINT only when `hasControllingTerminal()` is false (`/dev/tty` `O_NOCTTY` probe; isTTY flags on win32 — a terminal delivers Ctrl-C to both processes itself), always forwards SIGTERM/SIGHUP, removes the neutral dir, and exits with the child's code or 128+signal — never earlier. Termination is structural (a re-run's startup cwd has no `.env`); gbrain self-spawns starting in the hostile cwd hop once per subtree. (2) `loadGbrainEnvFile(configDir)`; (3) the #3688 guardrails loader (moved from cli.ts; fail-closed; passes `skipCwdCheck: collision`). cwd == config dir (`cwdIsOperatorConfigDir`, exported for tests): quarantine skipped only when no cwd `.env` assigns any of `GBRAIN_HOME`, `HOME`, `USERPROFILE` and `realpath(cwd) === realpath(configDir())`. Script mode (`isScriptRuntime()`: `process.execPath` is a bun runtime, not a compiled binary): `warnScriptModeBunfig` prints `SCRIPT_MODE_BUNFIG_WARNING` once when the STARTUP cwd's `bunfig.toml` declares a top-level `preload` and the cwd is not the checkout containing the running entry (Bun ran that preload before this code; the compiled binary is built with `--no-compile-autoload-bunfig`); never repeated on the re-run. Zero cost when nothing protected is assigned. Pinned by `test/cli-cwd-dotenv-quarantine.test.ts` (hostile git checkout with planted `core.fsmonitor` via `GIT_CONFIG_*` AND via `XDG_CONFIG_HOME`; `sh` presence probe for `GIT_SSL_NO_VERIFY`; four forged-marker shapes; depth-2 re-spawn; SIGTERM/SIGKILL; native Bun terminal (`Bun.spawn({ terminal })`, skipped on win32) tty-SIGINT ignore vs non-tty SIGINT forward; SIGHUP forward; execArgv preservation across the hop; chdir-back-when-original-cwd-vanished; relative-`TMPDIR` hop; guardrails fail-closed refusal + control; wrapper outlives SIGTERM until the child exits (exit = child's, neutral dir removed); planted-`HOME` drop → real home restored in both the cron and the exported-HOME shapes; forged-home config-dir exemption refused; script-mode bunfig warning (foreign cwd warns once, own checkout silent, `[test]`-section preload silent); cwd + relative-argv restoration; compiled binary from `GBRAIN_COMPILED_BIN ?? bin/gbrain`, including a cwd `bunfig.toml` `preload` staying inert).
+- `src/core/cli-preflight.ts` — `runCliPreflight()`, the first statement of `cli.ts:main()`. (0) Re-run detection: `GBRAIN_CWD_ENV_QUARANTINED` (`CWD_ENV_QUARANTINED_MARKER`) is parsed as JSON `{cwd, neutral, wrapperPid}` and honoured ONLY when the process's startup cwd realpath-equals `neutral` and `neutral` holds none of `CWD_DOTENV_FILES` (`wrapperPid` is informational — accepted only as a positive safe integer, otherwise ignored); on a verified hop it deletes the marker, `chdir(cwd)`s back, skips step 1 (the parent already warned), and arms `installWrapperWatchdog`: an `unref()`ed 1 s interval comparing `process.ppid` (live in Bun) with `wrapperPid` — a mismatch prints one `[env]` line, `rmdirSync`s the empty neutral dir the wrapper's `finally` never reached, and exits 137, so a supervisor that SIGKILLs the wrapper pid (`restartCurrentChild`, job-isolation children, hook pushes) takes the real re-run down within about a second instead of leaving an orphan; an unverified marker is ignored, never chdir'd on. (1) `parseCwdDotenv(cwd)` ONCE, shared by the cwd == config dir check and `quarantineCwdDotenv(process.env, cwd, { assignments })`. (1a) If the drop removed a NON-EMPTY `GBRAIN_GUARDRAILS_MODULE`, print `GUARDRAILS_ASSIGNED_BY_CWD_DOTENV` and exit 1 — fail-closed, never a re-run without the operator's firewall (the `~/.gbrain/.env` home is read after the quarantine and unaffected). (1b) Otherwise, whenever anything was dropped: `Bun.spawn([execPath, ...execArgv (dev runtime only; `resolveRuntimePaths` resolves a `./`/`../`-relative — or bare-and-existing — value of `--preload`/`-r`/`--require`/`--import`, `--config`/`-c`, `--env-file`, `--tsconfig-override`, both spellings, against the ORIGINAL cwd because the re-run starts in the empty neutral dir; everything else passes through verbatim, in order), entry/user args], { cwd: <fresh mkdtemp dir, realpath'd so `neutral` is absolute+canonical>, env: process.env minus undefined + marker, plus the operator's real `... (line truncated to 2000 chars)
-- `src/core/cli-socket/` + `src/cli/cli-socket-client.ts` — the opt-in warm CLI socket for Postgres brains ([guide](../../guides/cli-socket.md)); off unless `gbrain serve --cli-socket` or DB-plane `serve.cli_socket`, which `loadConfigWithEngine` merges from its bulk snapshot only (`mergeServeCliSocket`: `serve_cli_socket` in the config `connectEngine` publishes in `MERGED_CONFIG_BY_ENGINE`, both in `src/core/published-config.ts`), so serve decides without loading this module or reading config; off, it does neither. `server.ts` `startCliSocket` (called from both serve lanes only when on; stdio after the stdout redirect) binds `$GBRAIN_HOME/.gbrain/run/cli.sock` only on a Postgres engine whose resolved brain (`resolveBrainId`, the tier chain `connectEngine` used) is the host (a mount serve logs why and never binds), after `fs-guard.ts` `ensurePrivateDir` (0700, this uid, never a symlink; an open directory this uid owns is tightened, anything else refused; GBRAIN_HOME and `.gbrain` above it must be this uid's with no group/other write bit unless sticky, checked by `ancestorProblem` on both sides and never repaired), a peer-credential self-test on a scratch socket, the native bind lock and a stale-socket probe; `listen()` binds synchronously under `process.umask(0o177)` (restored right after), so the kernel creates the socket 0600, and `verifyBoundSocket` only checks it (lstat: our private socket; nothing is chmod'ed through the path); it is unlinked on exit only while its inode is still ours. At most 8 requests are active, and a request counts until every promise it started settles (`ExecutedRequest.settled`), not until it answered; one still unsettled at the 30 s round-trip cap is logged once. Every accepted connection's uid comes from `peer-cred.ts` (bun:ffi `getsockopt(SO_PEERCRED)` on linux x64/arm64, `getpeereid` on darwin, on the socket's `_handle.fd`) and any other or unreadable uid is dropped before a byte is parsed; with no reader the serve logs why and never binds (fail closed). `protocol.ts`: one newline-JSON request per connection (256 KiB cap), a handshake line (`accepted` or a refusal reason: `identity_mismatch` with the differing part in `mismatch`, `busy`, `malformed_request`) and one result frame (16 MiB cap; `result`, `error` with a plain OperationError's own fields, or `fallback`); the client checks every field it reads per kind (`isHandshakeFrame`, `isResultFrame`) and treats anything else as `malformed_response`. `identity.ts` `cliSocketIdentity`: the resolved brain id, `databaseTarget` (host, port, database, user and the `options` parameter; password and driver-only parameters dropped; the serve's from the engine's `connectedDatabaseUrl`, the URL it actually connected with), config dir and file realpaths, the config file's SHA-256, VERSION and `behaviorEnv` (SHA-256 values of the explicit `READ_BEHAVIOR_ENV` list, which test/cli-socket.test.ts checks against every `GBRAIN_*` name in src, the names, never values, of the recipe registry's provider credentials that are set, and SHA-256 values of its other provider variables: base URLs, endpoints, deployments, API versions, org/project/group ids); `cliSocketIdentityMismatch` compares serve and CLI part by part and returns the first differing part's name (sent as the refusal's `mismatch` and logged once per part by the serve), and a port may differ only on a Supavisor pooler host. `execute.ts` runs only `search`/`query`/`get_page` (read scope, non-mutating) through the op handler with `cliRequestContext` (makeContext's fields, remote false, source resolved from the caller's cwd and GBRAIN_SOURCE via `resolveSourceWithTier`'s `env` option; DB-plane config merged fresh per request) inside one request-scoped config snapshot (`withRequestConfigSnapshot`, `src/core/config-snapshot.ts`, the MCP read-op snapshot: one bulk config read per request, dropped when it settles) and `recall`'s op-backed forms through `recallVerbForCaller` (`src/commands/recall.ts`); the read deadline is the shorter of 30 s and the CLI's `--timeout`, and passing it answers `fallback` (the CLI runs the call itself); a search/query adds the cold path's `recallInteropNotices` (`captureRetrievalNotices`) after the handler; a segmented `get`, a non-OperationError or an OperationError subclass answers `fallback`. `output-capture.ts` records the request's console/stderr output, its `warnOncePerProcess` keys and its first noted source and its first chat-fallback hop notice in an AsyncLocalStorage scope (`setWarnOnceScope`, `setSourceNoteScope`, `setFallbackHopScope`), so MCP work on the same serve is untouched. The client (one gated call before CLI_ONLY dispatch in `src/cli/main.ts`) gives up silently (`GBRAIN_DEBUG=1` prints `[cli-socket] cold path: <reason>`) on a missing or unsafe socket, no peer-credential reader (it never connects), mount brain, `--explain`, stdin or image input, a 150 ms connect or 1 s handshake timeout, a whole exchange over `cliSocketRoundTripMs` (30 s, or a shorter `--timeout`), a refusal, a malformed frame, a frame its renderer throws on (rendered into a buffer first, so nothing prints), a serve uid mismatch, or a connection lost mid-request, and otherwise replays the captured output and renders with the cold path's `formatResult`/`applyCliOpNotices`/`writeCliError` and exit codes; `GBRAIN_CLI_SOCKET=0` skips it. Pinned by `test/cli-socket.test.ts` (identity incl. brain and env, directory/ancestor/socket checks, post-bind chmod, foreign and unreadable peer uids, unsupported platform on both sides, mount refusal, slots held until settled, frame shapes, round-trip cap, per-request hop queue, wedged and dying serves), `test/serve-cli-socket-off.test.ts` (a socket-off serve boot loads no cli-socket module and makes no engine call for it, each boot in its own process), `test/cli-socket-context.test.ts` (context parity with makeContext per source tier, serve-side timeout fallback) and `test/e2e/cli-socket-postgres.test.ts` (byte-identical output, round trips, writes bypass, handshake refusal for config and env, mount serve never answering the host CLI, stale socket, off by default, on from `serve.cli_socket`). GBRA-175: `probe.ts` `probeCliSocket` sends a `probe` frame, which `server.ts` answers with the handshake alone (no op runs), so `gbrain upgrade --restart-only` checks that serve accepts the installed build; it lives outside the client so the upgrade path never loads the CLI.
+- `src/core/cli-socket/` + `src/cli/cli-socket-client.ts` — the opt-in warm CLI socket for Postgres brains ([guide](../../guides/cli-socket.md)); off unless `gbrain serve --cli-socket` or DB-plane `serve.cli_socket`, which `loadConfigWithEngine` merges from its bulk snapshot only (`mergeServeCliSocket`: `serve_cli_socket` in the config `connectEngine` publishes in `MERGED_CONFIG_BY_ENGINE`, both in `src/core/published-config.ts`), so serve decides without loading this module or reading config; off, it does neither. `server.ts` `startCliSocket` (called from both serve lanes only when on; stdio after the stdout redirect) binds `$GBRAIN_HOME/.gbrain/run/cli.sock` only on a Postgres engine whose resolved brain (`resolveBrainId`, the tier chain `connectEngine` used) is the host (a mount serve logs why and never binds), after `fs-guard.ts` `ensurePrivateDir` (0700, this uid, never a symlink; an open directory this uid owns is tightened, anything else refused; GBRAIN_HOME and `.gbrain` above it must be this uid's with no group/other write bit unless sticky, checked by `ancestorProblem` on both sides and never repaired), a peer-credential self-test on a scratch socket, the native bind lock and a stale-socket probe; `listen()` binds synchronously under `process.umask(0o177)` (restored right after), so the kernel creates the socket 0600, and `verifyBoundSocket` only checks it (lstat: our private socket; nothing is chmod'ed through the path); it is unlinked on exit only while its inode is still ours. At most 8 requests are active, and a request counts until every promise it started settles (`ExecutedRequest.settled`), not until it answered; one still unsettled at the 30 s round-trip cap is logged once. Every accepted connection's uid comes from `peer-cred.ts` (bun:ffi `getsockopt(SO_PEERCRED)` on linux x64/arm64, `getpeereid` on darwin, on the socket's `_handle.fd`) and any other or unreadable uid is dropped before a byte is parsed; with no reader the serve logs why and never ... (line truncated to 2000 chars)
- `src/core/vector-prewarm.ts` — opt-in HNSW prewarm for Postgres brains ([ENGINES](../../ENGINES.md#vector-index-prewarm)). `readVectorPrewarmPlan` reads only catalogs and file sizes: every valid `hnsw` index in `current_schema()` with `pg_relation_size`, `pg_size_bytes(current_setting('shared_buffers'))`, `effective_cache_size` (missing_ok, reported only) and the pg_prewarm extension state. `prewarmFits`: shared_buffers alone decides, the total must be at most `PREWARM_SHARED_BUFFERS_SHARE` (0.5) of it, because 'buffer' mode fills Postgres's own cache and a bigger prewarm would evict the heap and keyword-index pages other reads need; effective_cache_size is a planner hint the server never allocates, so it never decides. `runVectorPrewarm` refuses PGLite (`vector_prewarm_unsupported_engine`), a misfit (`vector_prewarm_wont_fit`, host_admin fix naming the shared_buffers needed) and a missing extension (`vector_prewarm_extension_missing`) before any `pg_prewarm` call, and a dry run reads nothing; otherwise one transaction per index, largest first, with `SET LOCAL statement_timeout = 0` and `pg_prewarm(<index>, 'buffer')`. Callers: `gbrain embeddings prewarm` (CLI-only, never an operation, so no MCP caller reaches it) and `prewarmAtServeStart`, which `runServe` starts in the background only when DB-plane `serve.vector_prewarm` is true (`mergeServeVectorPrewarm` in `published-config.ts`, snapshot only); it logs the load or the refusal and never stops the serve. Pinned by `test/vector-prewarm.test.ts`, `test/serve-vector-prewarm-off.test.ts` (off: no module load, no engine call, no log line) and `test/e2e/vector-prewarm-postgres.test.ts` (prewarm, refusal under a simulated 16 kB shared_buffers, missing extension).
- `src/core/console-prefix.ts` — `AsyncLocalStorage<string>`-backed per-source line-prefix helper. Exports `withSourcePrefix(id, fn)` (runs `fn` with `id` as active prefix; nested wraps replace then restore), `getSourcePrefix()` (read-only accessor; test seam), `slog(...)` / `serr(...)` (prefix-aware `console.log`/`console.error`), `withHumanLineSink(sink, fn)` (#6317: every `slog`/`serr` line under `fn`, Bun timers included, goes to `sink` instead of the streams; the serve captures a delegated managed drain's lines per job for `sync_status`), and `withHumanLogsToStderr(fn)` (runs `fn` with every `slog` line, prefixed or not, routed to stderr; `runSync` wraps its body in it under `--json` so stdout carries only the ONE JSON envelope (the cost-gate status object rides inside it as `cost_gate`, #4684) while `serr` and direct `console.log(JSON.stringify(..))` sites are unaffected; scoped via its own `AsyncLocalStorage`, never a process-wide console rebind). Embedded-newline-safe: a multi-line string under prefix `[foo]` emits `[foo] line1\n[foo] line2`. Outside a wrap, `slog`/`serr` fall through to bare `console.log`/`console.error` so single-source callers see identical output (back-compat invariant). Use `src.id` (slug-validated by `sources add`) NOT `src.name` (free-form) to defeat log-injection through newline/control-character names. Coverage: `src/commands/sync.ts` performSync + callees, `src/commands/embed.ts` runEmbedCore + helpers, `src/core/progress.ts` emitHumanLine, `src/commands/import.ts` runImport's human-only lines (`info()` + the end-of-run `Import complete` summary — so the first-sync full import under `sync --json` lands on stderr too).
-- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `RemoteMcpError`, `extractResponseMeta` and `ignoredRemoteParams` live in `src/core/remote-mcp-error.ts` (re-exported here) so local CLI paths can name them without loading the MCP SDK; the CLI imports this module only on a routed call. `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and every request carries `X-Gbrain-Client: gbrain-remote-cli/<version>` so hosts serve it full search/query rows (it never sends `fields`); `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). A /token 429 is `rate_limited` with `RemoteMcpErrorDetail.retry_after_s` parsed from Retry-After (`parseRetryAfterSeconds` in `remote-mcp-probe.ts`); any other non-auth /token failure is `token`, never `discovery`. `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `ignoredRemoteParams(res)` lists params the host reported ignoring (`_meta.warnings` `unknown_param` entries plus the warning text blocks after `content[0]`); the CLI fails when a sent scope param (`source_id`, `all_sources`) is among them and warns for other ignored params the op declares. Access tokens are cached in process and in `src/core/remote-token-cache.ts`: one 0600 file per key under `remote-tokens/` in the gbrain home, shared by every CLI process, keyed by a hash of issuer, MCP URL, client id and secret, holding only the bearer and its expiry (30 s before the host's), written by atomic rename, read through an `O_NOFOLLOW` descriptor whose `fstat` must show this user and no group/other bits (otherwise deleted); an HTTP 401 drops the entry. The host authorizes every request against the client's current grant, so a cached token never outranks it (`test/thin-client-token-cache-7360.test.ts`). `_clearMcpClientTokenCache({keepDisk})` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`. Agent contract v1: a tool_error body is `content[0]` alone; `extractToolErrorDetail` keeps `code` (legacy `error`) plus `canonical_code`, `reason`, `why`, `fix`, `notices`, `contract_version`; `RemoteMcpError.toJSON` adds `code` (derived via `canonicalCodeFor` for old servers) and those fields when present; `extractNotices(res)` reads `_meta.gbrain_notices` or prefixed blocks. Skew pinned by `test/thin-client-contract-skew.test.ts` with a frozen v0.60.37.0 parser. A status-only host's 503 `serve_status_only` envelope from OAuth discovery or `/token` (`status_only` on the `remote-mcp-probe.ts` failure, with `retry_after_s`) becomes `RemoteMcpError` detail (`code`, `reason`, `why`, `fix`), which the CLI renders through the agent envelope and the thin-client doctor reports on its check (`test/remote-mcp-status-only.test.ts`).
+- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `RemoteMcpError`, `extractResponseMeta` and `ignoredRemoteParams` live in `src/core/remote-mcp-error.ts` (re-exported here) so local CLI paths can name them without loading the MCP SDK; the CLI imports this module only on a routed call. `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and every request carries `X-Gbrain-Client: gbrain-remote-cli/<version>` so hosts serve it full search/query rows (it never sends `fields`); `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). A /token 429 is `rate_limited` with `RemoteMcpErrorDetail.retry_after_s` parsed from Retry-After (`parseRetryAfterSeconds` in `remote-mcp-probe.ts`); any other non-auth /token failure is `token`, never `discovery`. `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error ... (line truncated to 2000 chars)
-- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` and `managed-atoms-generation` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten. Git sync holds (`sync-hold`), their per-source summary while it counts any, `sync-hold-retry` requests, `sync-import-provenance` rows, the blocked-cursor conversion log, the #6188 fence census (`fence-candidate`, `fence-scan`) and paid fence-repair attempt claims and memos (`fence-repair-attempt`) of a live source incarnation survive GC (they leave on resolution; a retired incarnation's rows age out), and `connector-hold-retry` requests and `stuck-recovery-resolution` audit entries (`gbrain repair stuck-recovery`) never expire.
+- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_arr... (line truncated to 2000 chars)
- `src/core/persistence/preview-approval.ts` — preview-bound approval shared by `jobs authorize-legacy --select`, `jobs cancel --select`, `repair stale-atoms`, `repair extractor-facts` and the other preview-bound repair kinds such as `repair ontology-facts` (fix wave 5, ENG-O1). `previewHash(parts)` is SHA-256 over key-sorted JSON, byte-identical to `authorityDigest`; `saveApprovedSet` / `loadApprovedSet` / `clearApprovedSet` keep the approved items in `op_checkpoints` (`op='repair-approval'`, fingerprint `<command>:<hash>`); `retireAfterLastItem` applies one item and clears the set only after the last item returns, so an item that throws keeps it and the printed apply resumes with the same `--expect` (`test/repair-timeline-order.test.ts`). A missing, foreign, malformed or older-than-`APPROVAL_MAX_AGE_DAYS` (7, the purge TTL) set refuses whole with `preview_changed`. Tests: `test/preview-approval.test.ts` (PGLite; Postgres via `test/e2e/preview-approval-postgres.test.ts`). #6351: `loadApprovedSet` takes an optional lazy `emptyHash` (the hash a preview of the same selection prints when it finds nothing, from current state including source incarnations); with no saved row and a matching hash it returns an empty set, so the apply command an empty preview prints succeeds while a changed incarnation still refuses `preview_changed`. The eight preview-bound repair kinds without a local `emptyPlanHash` (stale-atoms, captured-facts, conversation-labels, extractor-facts, failed-writes, frontmatter, loop-facts, ontology-facts) pass it. Pinned by `test/repair-empty-preview-apply.test.ts`.
-- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `abortOnCleanupPass(name)` wraps that for child work: it returns `{ signal, release }`, the signal aborts when the cleanup pass runs (sync's `git pull` uses it), and `release` deregisters it. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`). #5079: `serve --http` (detected by `isHttpServeInvocation` in `src/core/serve-invocation.ts`) installs it with `keepServingOnLogEpipe`, so a closed stdout/stderr pipe (SIGPIPE under Bun, or an EPIPE stream error) drops the log write instead of exiting; stdio `serve` and every other command still exit. Pinned by `test/serve-http-log-epipe.test.ts`. #5062: `registerSignalOwner(name, onSignal)` lets a long-lived command (`jobs supervisor`, `jobs work`) claim SIGTERM/SIGHUP/SIGPIPE and a broken stdout/stderr pipe: while an owner is registered the generic handler only forwards the signal (no cleanup pass, no exit), so the owner can drain while still holding its DB lock and then exit through `triggerCleanupAndExit`; crashes keep the generic path. Pinned by `test/process-cleanup.test.ts` and `test/e2e/supervisor-stop-drain-5062.test.ts`. The signal handler calls `noteInterrupted(signal)` (`read-heartbeat.ts`) before the cleanup pass, except on SIGPIPE.
+- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `abortOnCleanupPass(name)` wraps that for child work: it returns `{ signal, release }`, the signal aborts when the cleanup pass runs (sync's `git pull` uses it), and `release` deregisters it. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`). #5079: `serve --http` (detected by `isHttpServeInvocation` in `src/core/serve-invocation.ts`) installs it with `keepServingOnLogEpipe`, so a closed stdout/stderr pipe (SIGPIPE under Bun, or an EPIPE stream error) drops the log write instead of exiting; stdio `serve` and every other command still exit. Pinned by `test/serve-http-log-epipe.test.ts`. #5062: `registerSignalOwner(name, onSignal)` lets a long-lived command (`jobs supervisor`, `jobs work`) claim SIGTERM/SIGHUP/SIGPIPE and a broken stdout/stderr pipe: while an owner is registered the generic handler only forwards the signal (no cleanup pass, no exit), so the owner can drain while still holding its DB lock and then exit through `triggerCleanupAndExit`; crashes keep the generic path. Pinned by `test/pro... (line truncated to 2000 chars)
- `src/core/read-heartbeat.ts` + `src/cli/slow-read.ts` — slow whole-brain reads say what they are doing. A `CliCommandRecord.slowRead(args)` (`src/cli/command-table.ts`) names the read for doctor, sync status, sources status, orphans, anomalies, status and diag; `beginCommandRead` (skipped for `--help` and `--quiet`) wraps the CLI_ONLY dispatch in `src/cli/main.ts` and calls `beginSlowRead`, which prints one stderr start line and an unref'd `still reading` line every `READ_HEARTBEAT_EVERY_MS` (10 s); stdout is untouched. `withReadMeta(doc)` adds `elapsed_ms` and `complete` to a `--json` document and lists `incomplete` (`{field, reason}`) from the markers the documents already carry (`incompleteFields`: a `status: not_read` object, `complete: false` or a `*_complete: false` key, `budget_hit: true`, a doctor check unknown for its budget); an error envelope gets `elapsed_ms` only and an array stays bare. `writeStdoutFinal` (`cli-force-exit.ts`) applies it to a guarded document during a slow read, and orphans, sources status and status call it directly. `noteInterrupted` prints the interrupt line and, under `--json`, writes `{error: 'interrupted', signal, read, elapsed_ms, complete: false}` at once through the writer `cli-force-exit.ts` registers (`setInterruptedDocumentWriter`); a SIGINT handler is installed only when nothing else listens. The fallback document for exits 129, 130 and 143 is `code: 'interrupted'`. Pinned by `test/read-heartbeat-cli.test.ts` (real spawned CLI fixture `test/fixtures/slow-read-cli.ts`: SIGTERM, SIGINT, SIGHUP, SIGKILL after SIGTERM, no `--json`, a kill outside a read) and `test/read-meta-diag.test.ts`.
- `src/commands/diag.ts` (+ `src/cli/commands/diag.ts`, `src/cli/help/diag.ts`) — `gbrain diag [--json] [--budget-ms N] [--query TEXT]`, read-only and refused on a thin client: one bounded bundle an agent pastes whole. `collectDiag` runs six sections in turn, each through `diagSection` under min(its cap in `DIAG_SECTION_CAP_MS`, what is left of the budget, default 30 s): `gbrain` (version, engine, runtime), `skew` (doctor `runtime_build_skew` and `writer_version`), `sources` (per source `last_sync_at`, last commit, `behind_head` from `readGitBehind`, the managed pass row's state from `readLivePassRows`), `holds` (counts per source and code), `pool` (Postgres only: backends by state, lock waits, idle transactions over 60 s, `pg_stat_database` session endings on 14+) and `search` (one search's stage timings and result count, never its results). Each section carries `elapsed_ms` and `status` `ok`, `not_read` (reason `budget`), `not_applicable` or `error` (with its code); the bundle carries `elapsed_ms`, `complete` and `incomplete`, error sections included. It never reads a source's file level (`sync status --detail`). Pinned by `test/read-meta-diag.test.ts`.
-- `src/core/process-watchdog.ts` — out-of-band hard-deadline killer for `gbrain sync`. A spinning sync (synchronous catastrophic-regex / ReDoS in pack link-inference) STARVES the main event loop, so the existing SIGTERM handler (`process-cleanup.ts`), `--timeout` `setTimeout`, and abort-flag checks can't fire — the process becomes unkillable-by-SIGTERM and, under cron, orphans pile up for 24h+. `installProcessWatchdog({deadlineMs, graceMs?, label?, heartbeatMs?, onWarn?}): WatchdogHandle` spawns a Bun `worker_threads` Worker via `new Worker(code, {eval: true, workerData})` — its own OS thread + event loop fires even while main is in an unyielding sync loop. At `deadlineMs` it `process.kill(process.pid, 'SIGTERM')` (clean-shutdown chance if responsive); at `deadlineMs+graceMs` `process.kill(process.pid, 'SIGKILL')` (uncatchable — guaranteed death under starvation). Signaling SELF has NO PID-reuse footgun (current PID never reused while alive — the reason the detached-child-watches-parent design was rejected). `eval: true` bakes the worker body into the `bun build --compile` binary with no separate-file embedding. Empirically validated on Bun 1.3.13 (worker timer + SIGKILL killed a `while(true){}`-starved process). `handle.dispose()` (clean-exit `finally`) `worker.terminate()`s it; `unref()`'d so it never keeps the process alive. Pure `watchdogDecision(elapsedMs, deadlineMs, graceMs) → 'wait'|'sigterm'|'sigkill'` extracted for unit tests, and pure exported `clampWatchdogTimers(deadlineMs, graceMs)` + `MAX_WATCHDOG_TIMER_MS` clamp BOTH worker timers so the deadline AND the `deadline+grace` SUM stay ≤ 2^31−1 — `setTimeout` overflow-fires above that at ~1ms, which for the sum timer would be an instant SIGKILL of a healthy process (unit-tested as pure arithmetic only; never arm a real max-deadline worker in-suite — its firing SIGTERMs the test runner itself). Optional `heartbeatMs` emits periodic `[<label>] parent alive Ns, hard-kill in ~Ms` lines (visible in cron logs even under starvation — the diagnosis surface). Optional `progressWindowMs` makes the deadline progress-aware: the handle forwards `noteForwardProgress()` notes (`src/core/forward-progress.ts`, throttled to at most one `postMessage` per min(1 s, window/4)) to the worker, which past the deadline extends while the last note is younger than the window and sends SIGTERM only after a full window without progress (pure mirror `progressDeadlineDecision(elapsedMs, deadlineMs, sinceProgressMs, windowMs) → 'wait'|'extend'|'stop'`; the window starts at install). A starved loop sends no notes, so starvation is still killed. Optional `stopNotice` is written to stdout (fd 1) when the watchdog stops the run, so the agent sees why and how to resume. GBRA-133 PR 3a: `progressSignal: 'committed'` forwards only `noteCommittedProgress()` notes, and a run that reaches its deadline having committed nothing stops at once (the `progressed` argument of `progressDeadlineDecision` is false) and writes `stallNotice` instead of `stopNotice`; the sync watchdog uses it, so screening and legacy-sweep slices never extend the deadline. Fallback: if `new Worker` throws, degrades to an in-process timer with a loud warning that it can't fire under starvation. Two adopters: `gbrain sync` (below) and the opt-in PGLite disconnect watchdog (`pglite-engine.ts` entry above); autopilot/cycle are follow-up candidates. Pinned by `test/process-watchdog.test.ts` (pure decision matrices + clamp arithmetic + handle contract) + `test/process-watchdog-harness.test.ts` (Bun-pinned spawn integration: a starved harness process IS killed ~deadline+grace, a no-watchdog control does NOT self-exit, clean dispose never kills, a progressing run outlives its deadline, a run that stops progressing is stopped one window later with its stop notice on stdout). Wired into `src/cli.ts` sync dispatch BEFORE `connectEngine` (so a connect-phase hang is bounded too) through `syncWatchdogPlan` in `src/core/sync-reconcile.ts`; deadline resolved by `resolveSyncHardDeadline` (precedence: `--no-hard-deadline` > `--hard-deadline` > `--timeout`(non-`--all`, armed `HARD_DEADLINE_GRACE_SEC` after the timeout so the in-band stop lands first) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none). The env and default deadlines carry `progressWindowMs` = the sync stall window (`GBRAIN_SYNC_STALL_ABORT_SECONDS`, default 900 s; the default when that is disabled), so a large first sync that keeps importing is never stopped; the explicit flags stay strict. The stop notice (`syncDeadlineStopNotice`: `code=sync_deadline_stop`, cause, resume command; one JSON object under `--json`) is pinned by `test/sync-hard-deadline.test.ts`, and the real CLI journey by `test/large-brain-ceilings.test.ts`. The stall notice of a run that committed nothing (`syncDeadlineStallNotice`: `code=sync_deadline_stalled`, why, a read-only `gbrain sync status` fix) is pinned by `test/honest-stalls-gbra133.test.ts`.
+- `src/core/process-watchdog.ts` — out-of-band hard-deadline killer for `gbrain sync`. A spinning sync (synchronous catastrophic-regex / ReDoS in pack link-inference) STARVES the main event loop, so the existing SIGTERM handler (`process-cleanup.ts`), `--timeout` `setTimeout`, and abort-flag checks can't fire — the process becomes unkillable-by-SIGTERM and, under cron, orphans pile up for 24h+. `installProcessWatchdog({deadlineMs, graceMs?, label?, heartbeatMs?, onWarn?}): WatchdogHandle` spawns a Bun `worker_threads` Worker via `new Worker(code, {eval: true, workerData})` — its own OS thread + event loop fires even while main is in an unyielding sync loop. At `deadlineMs` it `process.kill(process.pid, 'SIGTERM')` (clean-shutdown chance if responsive); at `deadlineMs+graceMs` `process.kill(process.pid, 'SIGKILL')` (uncatchable — guaranteed death under starvation). Signaling SELF has NO PID-reuse footgun (current PID never reused while alive — the reason the detached-child-watches-parent design was rejected). `eval: true` bakes the worker body into the `bun build --compile` binary with no separate-file embedding. Empirically validated on Bun 1.3.13 (worker timer + SIGKILL killed a `while(true){}`-starved process). `handle.dispose()` (clean-exit `finally`) `worker.terminate()`s it; `unref()`'d so it never keeps the process alive. Pure `watchdogDecision(elapsedMs, deadlineMs, graceMs) → 'wait'|'sigterm'|'sigkill'` extracted for unit tests, and pure exported `clampWatchdogTimers(deadlineMs, graceMs)` + `MAX_WATCHDOG_TIMER_MS` clamp BOTH worker timers so the deadline AND the `deadline+grace` SUM stay ≤ 2^31−1 — `setTimeout` overflow-fires above that at ~1ms, which for the sum timer would be an instant SIGKILL of a healthy process (unit-tested as pure arithmetic only; never arm a real max-deadline worker in-suite — its firing SIGTERMs the test runner itself). Optional `heartbeatMs` emits periodic `[<label>] parent alive Ns, hard-kill in ~Ms` lines (visible in cron logs ev... (line truncated to 2000 chars)
- `src/core/forward-progress.ts` — process-wide forward-progress signal, zero imports. `noteForwardProgress()` records that a unit of work completed (called by every `progress.ts` tick); `onForwardProgress(listener)` subscribes and returns the unsubscribe; `lastForwardProgressAt()` reads the last note. Consumers are deadlines that must never stop a run that is still progressing: the sync watchdog (`process-watchdog.ts`, `progressWindowMs`) and the `gbrain serve` boot deadline. Heartbeats are not progress. GBRA-133 PR 3a: `noteCommittedProgress()` records committed work (a page written, deleted or renamed, a cursor advanced; the sync import, delete and rename loops, the drain's page commits and checkpoint, and a followed drain holder whose committed count rose) and is also a forward note; `onCommittedProgress` / `lastCommittedProgressAt` read it. The sync watchdog listens to committed notes only.
-- `src/core/spawn.ts` — the one module in `src/` that launches subprocesses with `windowsHide` defaulted (#4992, contributed by @rokas-tarasevicius in PR #6105). A `detached: true` child on Windows has no console, so every console program it launches without `windowsHide` opens a visible console window that takes focus; the Stop-hook push, the backup check, the job supervisor, its worker and every job child run that way. Wraps `spawn`, `spawnSync`, `exec`, `execSync`, `execFile`, `execFileSync` (Node's overloads and `util.promisify.custom` kept) plus `bunSpawn` / `bunSpawnSync`, each defaulting `windowsHide: true` and keeping an explicit `false` (only `openBrowser` in `creds/redirect.ts`). Calls go through `child_process` and `Bun` at call time, so `spyOn` in tests still intercepts them. Trade-off: with every stdio stream piped or ignored, libuv turns the flag into CREATE_NO_WINDOW and the child gets a windowless console of its own, so a program that prompts on the console directly prompts invisibly; gbrain's networked git calls set `GIT_TERMINAL_PROMPT=0` (git-remote.ts also `SSH_ASKPASS_REQUIRE=never`), and inherited-stdio launches still attach to the terminal. `scripts/check-windows-hide.ts` (`bun run check:windows-hide`, in `verify`) is a RATCHET: a new runtime `child_process` import or `Bun.spawn*` in `src/` fails unless the file is in its `NOT_YET_MIGRATED` list (the minions supervisor/worker/child/readiness/isolation/registry/shell handler, `workspace-push.ts`, `cli/main.ts`, `context/hook-heartbeat.ts`, the backup check, `cli-force-exit.ts`, `cli-preflight.ts`, `autopilot-lock.ts`, the autopilot commands and `bounded-child-exec.ts` are migrated; the rest, wave-13-claimed files included, are listed and lose the entry when they move), and a listed file that stops launching directly fails as stale. Pinned by `test/spawn-windows-hide.test.ts` (argument shapes; the detached supervisor, worker and push-git sites), `test/scripts/windows-hide-guard.test.ts` (forms, allowlist, ratchet, stale entries, the repository) and, natively on the test.yml `security-regressions` Windows row, `test/windows-hidden-console.test.ts` (a compiled console probe launched from a console-less detached process: the unhidden CONTROL launch must show a window or the run fails as `windows_console_gate_unsupported`; then the worker, the push's git and every seam launcher show none).
+- `src/core/spawn.ts` — the one module in `src/` that launches subprocesses with `windowsHide` defaulted (#4992, contributed by @rokas-tarasevicius in PR #6105). A `detached: true` child on Windows has no console, so every console program it launches without `windowsHide` opens a visible console window that takes focus; the Stop-hook push, the backup check, the job supervisor, its worker and every job child run that way. Wraps `spawn`, `spawnSync`, `exec`, `execSync`, `execFile`, `execFileSync` (Node's overloads and `util.promisify.custom` kept) plus `bunSpawn` / `bunSpawnSync`, each defaulting `windowsHide: true` and keeping an explicit `false` (only `openBrowser` in `creds/redirect.ts`). Calls go through `child_process` and `Bun` at call time, so `spyOn` in tests still intercepts them. Trade-off: with every stdio stream piped or ignored, libuv turns the flag into CREATE_NO_WINDOW and the child gets a windowless console of its own, so a program that prompts on the console directly prompts invisibly; gbrain's networked git calls set `GIT_TERMINAL_PROMPT=0` (git-remote.ts also `SSH_ASKPASS_REQUIRE=never`), and inherited-stdio launches still attach to the terminal. `scripts/check-windows-hide.ts` (`bun run check:windows-hide`, in `verify`) is a RATCHET: a new runtime `child_process` import or `Bun.spawn*` in `src/` fails unless the file is in its `NOT_YET_MIGRATED` list (the minions supervisor/worker/child/readiness/isolation/registry/shell handler, `workspace-push.ts`, `cli/main.ts`, `context/hook-heartbeat.ts`, the backup check, `cli-force-exit.ts`, `cli-preflight.ts`, `autopilot-lock.ts`, the autopilot commands and `bounded-child-exec.ts` are migrated; the rest, wave-13-claimed files included, are listed and lose the entry when they move), and a listed file that stops launching directly fails as stale. Pinned by `test/spawn-windows-hide.test.ts` (argument shapes; the detached supervisor, worker and push-git sites), `test/scripts/windows-hide-guard.test.ts` (forms, ... (line truncated to 2000 chars)
- `src/core/embed-stale-progress.ts` — `StaleChunkProgress` (#5968, wave 15 P2.6 [R28]): the exact tally behind `embed --stale` progress. Unit: stale chunks. `total` starts at the census and only grows: `listed(rows)` raises it to the rows actually listed (a writer adding stale rows behind the keyset cursor), `reentered(remaining)` to what a paced re-entry will relist, and `pageDone(census, handled)` by the heal delta when one oversized stored chunk became several, in the same step that adds the page's rows to `done` (failed, filtered and quarantined rows included), so `done <= total` at every callback and a finished run reads 100%. Pinned by `test/embed-stale-progress-5968.serial.test.ts`.
- `src/core/progress.ts` — Shared bulk-action progress reporter. Writes to stderr. Modes: `auto` (TTY `\r`-rewriting; non-TTY plain lines), `human`, `json` (JSONL), `quiet`. Rate-gated by `minIntervalMs` and `minItems`. `startHeartbeat(reporter, note)` for single long queries. `child()` composes phase paths. `setTotal(total)` (optional on the interface; #5968) replaces a running phase's total once the exact amount of work is known, so a caller whose work grows mid-phase (a heal split, a re-entry) never reports past 100%. Singleton SIGINT/SIGTERM coordinator emits `abort` events for every live phase. EPIPE defense on both sync throws and stream `'error'` events. Every `tick` calls `noteForwardProgress()`, so bulk work feeds the progress-aware deadlines; its only import is that zero-import leaf. `emitHumanLine` is prefix-aware — inside a `withSourcePrefix(id, ...)` scope from `src/core/console-prefix.ts` it prepends `[id] ` (and TTY-rewrite mode `\r\x1b[2K` carries the prefix inside the clear-to-EOL escape); `emitJson` is intentionally NOT prefixed so NDJSON consumers don't choke on a `[id] {...}` shape. JSON `tick` events carry `cpu_ms`, the main thread's CPU time since the phase started (`process.threadCpuUsage()`); the scale tier's PGLite import-rate gate (`scripts/scale/gates.ts`) judges on it.
-- `src/core/retry.ts` — canonical retry primitive for transient connection errors. Exports `withRetry<T>(fn, opts)` execution wrapper + `BULK_RETRY_OPTS` constant (`{maxRetries:3, delayMs:1000, delayMaxMs:10000, jitter:'decorrelated'}`, tuned for Supabase Supavisor's 5-10s circuit-breaker recovery) + `BATCH_AUDIT_SITES` typed const (closed enum of every audit-emission site) + `resolveBulkRetryOpts(env)` (reads `GBRAIN_BULK_MAX_RETRIES`/`GBRAIN_BULK_RETRY_BASE_MS`/`GBRAIN_BULK_RETRY_MAX_MS` with `>=0` validation, throws on bad input with a paste-ready hint) + `abortableSleep(ms, signal?)` + `RetryAbortError` (tagged error for clean shutdown) + `computeNextDelay()` (pure-fn for 3 jitter modes: `'none'`, `'full'`, `'decorrelated'`). The execution wrapper is consumed by `postgres-engine.ts` + `pglite-engine.ts` batch primitives (`addLinksBatch` / `addTimelineEntriesBatch` / `upsertChunks`) so every caller inherits retry as part of the data-primitive's contract. CI guard `scripts/check-no-double-retry.sh` fails the build on `withRetry(...engine.batch...)` patterns (prevents 3×3=9 retry amplification); `scripts/check-batch-audit-site.sh` validates every string-literal `auditSite: '...'` against the closed `BATCH_AUDIT_SITES` enum. Decorrelated jitter (AWS-style: `uniform(base, prevDelay*3)` capped at `delayMaxMs`) — `'full'` jitter would allow near-zero retries that re-hit the recovering breaker. `WithRetryOpts` has an optional `reconnect?: () => Promise<void>` callback awaited in the catch branch AFTER `isRetryableConnError` classification but BEFORE the inter-attempt sleep — lets engine-level callers rebuild a dead pool/singleton between attempts. `PostgresEngine.batchRetry` injects `() => this.reconnect()` (the race-safe `_reconnecting` guard kicks in). Fail-loud: a reconnect throw PROPAGATES as the new error, replacing the symptomatic "No database connection". `onRetry` callbacks are awaited (sync arrows work identically; async callbacks correctly delay the sleep). Pinned by `test/core/retry.test.ts` (37 cases), `test/core/retry-stress.slow.test.ts` (5 cases, 100 batches × 30% blip rate, asserts zero row loss), `test/core/retry-reconnect.test.ts` (5 cases), `test/e2e/db-singleton-shared-recovery.test.ts` (3 DB-gated cases).
+- `src/core/retry.ts` — canonical retry primitive for transient connection errors. Exports `withRetry<T>(fn, opts)` execution wrapper + `BULK_RETRY_OPTS` constant (`{maxRetries:3, delayMs:1000, delayMaxMs:10000, jitter:'decorrelated'}`, tuned for Supabase Supavisor's 5-10s circuit-breaker recovery) + `BATCH_AUDIT_SITES` typed const (closed enum of every audit-emission site) + `resolveBulkRetryOpts(env)` (reads `GBRAIN_BULK_MAX_RETRIES`/`GBRAIN_BULK_RETRY_BASE_MS`/`GBRAIN_BULK_RETRY_MAX_MS` with `>=0` validation, throws on bad input with a paste-ready hint) + `abortableSleep(ms, signal?)` + `RetryAbortError` (tagged error for clean shutdown) + `computeNextDelay()` (pure-fn for 3 jitter modes: `'none'`, `'full'`, `'decorrelated'`). The execution wrapper is consumed by `postgres-engine.ts` + `pglite-engine.ts` batch primitives (`addLinksBatch` / `addTimelineEntriesBatch` / `upsertChunks`) so every caller inherits retry as part of the data-primitive's contract. CI guard `scripts/check-no-double-retry.sh` fails the build on `withRetry(...engine.batch...)` patterns (prevents 3×3=9 retry amplification); `scripts/check-batch-audit-site.sh` validates every string-literal `auditSite: '...'` against the closed `BATCH_AUDIT_SITES` enum. Decorrelated jitter (AWS-style: `uniform(base, prevDelay*3)` capped at `delayMaxMs`) — `'full'` jitter would allow near-zero retries that re-hit the recovering breaker. `WithRetryOpts` has an optional `reconnect?: () => Promise<void>` callback awaited in the catch branch AFTER `isRetryableConnError` classification but BEFORE the inter-attempt sleep — lets engine-level callers rebuild a dead pool/singleton between attempts. `PostgresEngine.batchRetry` injects `() => this.reconnect()` (the race-safe `_reconnecting` guard kicks in). Fail-loud: a reconnect throw PROPAGATES as the new error, replacing the symptomatic "No database connection". `onRetry` callbacks are awaited (sync arrows work identically; async callbacks correctly delay the sleep). Pi... (line truncated to 2000 chars)
- `src/core/stall-env.ts` — shared env resolver for the stall-watchdog knobs (`resolveStallAbortSecondsFromEnv(envVar, defaultSec)`): one parameterized implementation behind BOTH `GBRAIN_SYNC_STALL_ABORT_SECONDS` and `GBRAIN_EMBED_STALL_ABORT_SECONDS` so the two surfaces' semantics cannot drift — unset/empty/garbage → the caller's default; any finite number returned as-is (`<= 0` disables the watchdog). Deliberately a leaf module (neither the sync nor the embed cluster imports the other's machinery just to parse an env var); env-only incident knobs by design, no config-dashboard surface.
diff --git a/docs/architecture/thin-client.md b/docs/architecture/thin-client.md
index 36cf550085..ffc33aedfb 100644
--- a/docs/architecture/thin-client.md
+++ b/docs/architecture/thin-client.md
@@ -137,6 +137,52 @@ carries the routing-seam picture):
handler in `operations.ts`); thin-client `think` warns loudly when those
flags are set.
+## stdio bridge
+
+On a thin client, bare `gbrain serve` is a stdio MCP server that relays to
+the brain host instead of refusing (#8543). A harness that only speaks stdio
+(OpenClaw, a desktop app, a gateway) can then use a remote brain with the
+same entry it would use for a local one.
+
+- **What it relays.** `tools/list` returns the host's tool list for the
+ stored OAuth client; every `tools/call` goes to the host with that
+ client's token, `_meta` included, and comes back unchanged, refusals
+ included. The bridge opens no local database, writes no page text, and
+ never marks a call as the trusted local CLI. Its client name is
+ `gbrain-stdio-bridge`, so the host serves the lean rows and windowed pages
+ any remote agent gets.
+- **What it accepts.** `--surface`, `--advertise` and `--source-guard` (the
+ argv gbrain's plugins register). `--surface` and `--advertise` narrow the
+ local listing only; `request_tools {surface}` widens this session locally
+ and writes nothing on the host. `serve --http`, `--access` and every other
+ host flag still refuse with `requires_local_engine`: the host enforces
+ what a client may do, so a restriction belongs on a narrower client
+ (`gbrain auth register-client <name> --grant-types client_credentials
+ --scopes read`) used from its own `GBRAIN_HOME`.
+- **Failures.** A transport failure becomes the v1 agent envelope with a
+ bounded `recovery` and a `fix` that never adds a scope. A write that may
+ have reached the host keeps its `request_id` with
+ `submission_status: "unknown"` (`write_outcome_unknown`): read the receipt
+ with `get_write_request` or `gbrain write-request -- <id>`, or resend with
+ the same `request_id`. One HTTP 401 re-mints the token and resends once with
+ the same `request_id`. URLs in every envelope and stderr line lose their
+ userinfo, query and fragment. An unexpected fault writes a 0600 trace under
+ `<GBRAIN_HOME>/.gbrain/bridge-traces/`, answers `internal_error`, and the
+ bridge keeps serving.
+- **Audience.** A call carrying `_meta.on_behalf_of` is relayed only to a host
+ at gbrain 0.60.543.0 or newer, and a read answer must report
+ `_meta.access.audience`; otherwise the bridge answers
+ `host_upgrade_required` instead of the credential's whole view.
+- **Lifecycle.** Same as local stdio serve: signals, the parent watchdog,
+ `MCP_STDIO=1` (stdin EOF is not a disconnect), and a stdin-EOF drain whose
+ bound is the call timeout (`gbrain --timeout=Ns serve`, default 180 s). A
+ write still in flight when the drain expires is logged with its
+ `request_id` and the exit code is 1.
+
+Code: `src/mcp/remote-bridge.ts`, `src/mcp/remote-bridge-errors.ts`,
+`src/mcp/remote-bridge-args.ts`, `src/mcp/stdio-lifecycle.ts`, and
+`forwardRemoteToolCall` in `src/core/mcp-client.ts`.
+
Cross-modal search files (image query, SSRF-guarded image loading, spend
tracking, multimodal reindex) are indexed per-file in
[`KEY_FILES.md`](./KEY_FILES.md) and described behaviorally in
diff --git a/docs/guides/hosted-harness-access.md b/docs/guides/hosted-harness-access.md
index 0bbc1c315c..49716238ab 100644
--- a/docs/guides/hosted-harness-access.md
+++ b/docs/guides/hosted-harness-access.md
@@ -119,7 +119,7 @@ are one principal. See [shared brain skills](shared-brain-skills.md).
A **profile grants authority**. A **surface selects visible tools**. Full surface does not bypass a grant, and `admin` does not imply delegation, the named shared-skill scopes, or owner dashboard/client-management authority. Starter includes authorized skill discovery and membership; the exact seven-tool `verbs` surface is memory-only. `rescope-client <client_id> --surface full` lists every tool. Thin CLI adapters use the full surface while retaining their source, operation, and write restrictions. Direct local CLI access is trusted access to the local computer; OAuth profiles do not confine a local shell.
-Clients granted a memory profile before the full-surface default keep their stored `starter` surface; no migration or repair widens it, and only an explicit `--profile` application regrants it. New grants snapshot operation names and source access. A later server upgrade does not silently give a snapshot-bound client new operations. The connection's own `whoami` reports `grant_diagnosis`: which blocker applies (scope, operation snapshot, client pin or server ceiling) and how many operations it hides, without naming them; `gbrain doctor` on the host reports the same as `grant_new_ops_available` with the commands. The connection is also told once per session, in band, by the `grant_blocked_operations` notice (same blockers and counts, the owner's preview-then-apply command as `fix`, `next: tell_user_to_run`; once per grant revision for stateless HTTP calls), and a read that left out takes a hidden tool serves carries `hidden_tool_content` with the next step that connection can actually take ([connection notices](repair.md#connection-notices)). Neither notice changes what the connection can call. A grant written before snapshots recorded their operation catalog says "original intent unknown" rather than claiming it predates the operations. Explicitly regrant to include them: `gbrain auth rescope --client <client_id> --operations <op,...> --surface full --dry-run` (then without `--dry-run`; `--surface full` only when the stored surface also blocks) for OAuth clients, or `gbrain auth rescope-token <name> --refresh-operations` (preview) then `--add <op,...>` for legacy tokens ([grants that cannot reach new operations](../mcp/ADMIN.md#grants-that-cannot-reach-new-operations)). `gbrain auth rescope --client <client_id> --operations all` (alias: `gbrain auth rescope-client <client_id> --allowed-operations all`) stores no snapshot and clears the profile instead, so the scopes and the surface alone decide, including operations later upgrades add. `gbrain auth clients` marks such a client `operations: "all"` with `includes_future_operations: true` and the command that re-pins it. A `bootstrap harness` re-run carries the replaced token's grants and does not widen its snapshot ([legacy token grants](../mcp/ADMIN.md#legacy-token-grants)). Archived sources are excluded. Legacy clients with a `NULL` operation snapshot retain their prior operation behavior.
+Clients granted a memory profile before the full-surface default keep their stored `starter` surface; no migration or repair widens it, and only an explicit `--profile` application regrants it. New grants snapshot operation names and source access. A later server upgrade does not silently give a snapshot-bound client new operations. The connection's own `whoami` reports `grant_diagnosis`: which blocker applies (scope, operation snapshot, client pin or server ceiling) and how many operations it hides, without naming them; `gbrain doctor` on the host reports the same as `grant_new_ops_available` with the commands. The connection is also told once per session, in band, by the `grant_blocked_operations` notice (same blockers and counts, the owner's preview-then-apply command as `fix`, `next: tell_user_to_run`; once per grant revision for stateless HTTP calls), and a read that left out takes a hidden tool serves carries `hidden_tool_content` with the next step that connection can actually take ([connection notices](repair.md#connection-notices)). Neither notice changes what the connection can call. A grant written before snapshots recorded their operation catalog says "original intent unknown" rather than claiming it predates the operations. Explicitly regrant to include them: `gbrain auth rescope --client <client_id> --operations <op,...> --surface full --dry-run` (then without `--dry-run`; `--surface full` only when the stored surface also blocks) for OAuth clients, or `gbrain auth rescope-token <name> --refresh-operations` (preview) then `--add <op,...>` for legacy tokens ([grants that cannot reach new operations](../mcp/ADMIN.md#grants-that-cannot-reach-new-operations)). `gbrain auth rescope --client <client_id> --operations all` (alias: `gbrain auth rescope-client <client_id> --allowed-operations all`) stores no snapshot and clears the profile instead, so the scopes and the surface alone decide, including operations later upgrades add. `gbrain auth clients` marks su... (line truncated to 2000 chars)
Snapshot-bound clients write through approved MCP operations such as `remember`, `capture`, or `put_page`. They cannot use the legacy `POST /ingest` webhook, whose queued writes do not yet enforce operation snapshots. Existing webhook clients with a `NULL` snapshot keep their legacy behavior.
@@ -153,6 +153,20 @@ It reports desired/installed/acknowledged views and pending cleanup, but keeps
`current_authority: unprobed` and `native_use: unverified`; reconnect and test
the native session separately.
+### Harnesses that only speak stdio
+
+A harness that can launch a command but cannot reach an HTTP MCP server uses
+a thin client's `gbrain serve`: install the CLI there, run `gbrain init
+--mcp-only` with the client from step 1, then register
+`gbrain serve --surface starter --advertise verbs` (absolute path from
+`command -v gbrain`) as the harness's stdio server. It relays to the brain
+host with that client's grant and adds nothing to it
+([stdio bridge](../architecture/thin-client.md#stdio-bridge)). For a narrower
+harness, register its own client (`--scopes read` for read-only) and init it
+under a separate `GBRAIN_HOME`, set in the harness entry's env as well;
+`serve --access read-only` is refused on a thin client because only the
+host can enforce it.
+
## 3. Prove a memory round trip
Save durable facts and preferences, not local harness/configuration state. A
diff --git a/docs/mcp/OPENCLAW.md b/docs/mcp/OPENCLAW.md
index cf6d040263..9afb2c331c 100644
--- a/docs/mcp/OPENCLAW.md
+++ b/docs/mcp/OPENCLAW.md
@@ -106,6 +106,27 @@ client registration, so the brain owner turns that on and approves the consent
the login succeeds, OpenClaw leaves the server out of agent turns. Publish the
endpoint with `gbrain mcp expose` ([remote MCP](../guides/remote-mcp.md)).
+### Or: a thin client's stdio bridge
+
+When OpenClaw should keep a stdio entry, install gbrain on the OpenClaw
+machine as a thin client of the brain host and register its `gbrain serve`,
+which relays every call to the host with that client's grant (it opens no
+local database). On the brain host, `gbrain agent register` with
+`--harness openclaw` prints these lines with your client filled in; run them
+on the OpenClaw machine:
+
+```bash
+gbrain init --mcp-only --issuer-url https://<brain-host> --mcp-url https://<brain-host>/mcp \
+ --oauth-client-id <client_id> --oauth-client-secret <client_secret>
+openclaw mcp add gbrain --command "$(command -v gbrain)" --arg serve --arg --surface --arg starter --arg --advertise --arg verbs
+```
+
+If gbrain's bundle plugin is installed there, it already registers gbrain:
+run only the `init` line. To keep this client apart from another gbrain on
+that machine, put `GBRAIN_HOME=<dir>` before the `init` line and add
+`--env GBRAIN_HOME=<dir>` to the `mcp add` line. What the bridge relays and
+how it reports failures: [stdio bridge](../architecture/thin-client.md#stdio-bridge).
+
## One bot for several people, in DMs
When one OpenClaw bot answers several people, each in their own DM, each DM can
diff --git a/llms-full.txt b/llms-full.txt
index 832556f491..df61d9eba7 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -710,7 +710,7 @@ are one principal. See [shared brain skills](shared-brain-skills.md).
A **profile grants authority**. A **surface selects visible tools**. Full surface does not bypass a grant, and `admin` does not imply delegation, the named shared-skill scopes, or owner dashboard/client-management authority. Starter includes authorized skill discovery and membership; the exact seven-tool `verbs` surface is memory-only. `rescope-client <client_id> --surface full` lists every tool. Thin CLI adapters use the full surface while retaining their source, operation, and write restrictions. Direct local CLI access is trusted access to the local computer; OAuth profiles do not confine a local shell.
-Clients granted a memory profile before the full-surface default keep their stored `starter` surface; no migration or repair widens it, and only an explicit `--profile` application regrants it. New grants snapshot operation names and source access. A later server upgrade does not silently give a snapshot-bound client new operations. The connection's own `whoami` reports `grant_diagnosis`: which blocker applies (scope, operation snapshot, client pin or server ceiling) and how many operations it hides, without naming them; `gbrain doctor` on the host reports the same as `grant_new_ops_available` with the commands. The connection is also told once per session, in band, by the `grant_blocked_operations` notice (same blockers and counts, the owner's preview-then-apply command as `fix`, `next: tell_user_to_run`; once per grant revision for stateless HTTP calls), and a read that left out takes a hidden tool serves carries `hidden_tool_content` with the next step that connection can actually take ([connection notices](repair.md#connection-notices)). Neither notice changes what the connection can call. A grant written before snapshots recorded their operation catalog says "original intent unknown" rather than claiming it predates the operations. Explicitly regrant to include them: `gbrain auth rescope --client <client_id> --operations <op,...> --surface full --dry-run` (then without `--dry-run`; `--surface full` only when the stored surface also blocks) for OAuth clients, or `gbrain auth rescope-token <name> --refresh-operations` (preview) then `--add <op,...>` for legacy tokens ([grants that cannot reach new operations](../mcp/ADMIN.md#grants-that-cannot-reach-new-operations)). `gbrain auth rescope --client <client_id> --operations all` (alias: `gbrain auth rescope-client <client_id> --allowed-operations all`) stores no snapshot and clears the profile instead, so the scopes and the surface alone decide, including operations later upgrades add. `gbrain auth clients` marks such a client `operations: "all"` with `includes_future_operations: true` and the command that re-pins it. A `bootstrap harness` re-run carries the replaced token's grants and does not widen its snapshot ([legacy token grants](../mcp/ADMIN.md#legacy-token-grants)). Archived sources are excluded. Legacy clients with a `NULL` operation snapshot retain their prior operation behavior.
+Clients granted a memory profile before the full-surface default keep their stored `starter` surface; no migration or repair widens it, and only an explicit `--profile` application regrants it. New grants snapshot operation names and source access. A later server upgrade does not silently give a snapshot-bound client new operations. The connection's own `whoami` reports `grant_diagnosis`: which blocker applies (scope, operation snapshot, client pin or server ceiling) and how many operations it hides, without naming them; `gbrain doctor` on the host reports the same as `grant_new_ops_available` with the commands. The connection is also told once per session, in band, by the `grant_blocked_operations` notice (same blockers and counts, the owner's preview-then-apply command as `fix`, `next: tell_user_to_run`; once per grant revision for stateless HTTP calls), and a read that left out takes a hidden tool serves carries `hidden_tool_content` with the next step that connection can actually take ([connection notices](repair.md#connection-notices)). Neither notice changes what the connection can call. A grant written before snapshots recorded their operation catalog says "original intent unknown" rather than claiming it predates the operations. Explicitly regrant to include them: `gbrain auth rescope --client <client_id> --operations <op,...> --surface full --dry-run` (then without `--dry-run`; `--surface full` only when the stored surface also blocks) for OAuth clients, or `gbrain auth rescope-token <name> --refresh-operations` (preview) then `--add <op,...>` for legacy tokens ([grants that cannot reach new operations](../mcp/ADMIN.md#grants-that-cannot-reach-new-operations)). `gbrain auth rescope --client <client_id> --operations all` (alias: `gbrain auth rescope-client <client_id> --allowed-operations all`) stores no snapshot and clears the profile instead, so the scopes and the surface alone decide, including operations later upgrades add. `gbrain auth clients` marks su... (line truncated to 2000 chars)
Snapshot-bound clients write through approved MCP operations such as `remember`, `capture`, or `put_page`. They cannot use the legacy `POST /ingest` webhook, whose queued writes do not yet enforce operation snapshots. Existing webhook clients with a `NULL` snapshot keep their legacy behavior.
@@ -744,6 +744,20 @@ It reports desired/installed/acknowledged views and pending cleanup, but keeps
`current_authority: unprobed` and `native_use: unverified`; reconnect and test
the native session separately.
+### Harnesses that only speak stdio
+
+A harness that can launch a command but cannot reach an HTTP MCP server uses
+a thin client's `gbrain serve`: install the CLI there, run `gbrain init
+--mcp-only` with the client from step 1, then register
+`gbrain serve --surface starter --advertise verbs` (absolute path from
+`command -v gbrain`) as the harness's stdio server. It relays to the brain
+host with that client's grant and adds nothing to it
+([stdio bridge](../architecture/thin-client.md#stdio-bridge)). For a narrower
+harness, register its own client (`--scopes read` for read-only) and init it
+under a separate `GBRAIN_HOME`, set in the harness entry's env as well;
+`serve --access read-only` is refused on a thin client because only the
+host can enforce it.
+
## 3. Prove a memory round trip
Save durable facts and preferences, not local harness/configuration state. A
diff --git a/scripts/check-windows-hide.ts b/scripts/check-windows-hide.ts
index 76bb6a2aed..74dd49d061 100644
--- a/scripts/check-windows-hide.ts
+++ b/scripts/check-windows-hide.ts
@@ -42,7 +42,6 @@ const ALLOWLIST: Record<string, string> = {
*/
const NOT_YET_MIGRATED: Record<string, string> = {
'src/commands/bootstrap.ts': 'not yet migrated: open PR #6283, #6319 edits this file',
- 'src/commands/serve.ts': 'not yet migrated: open PR #6437 edits this file',
'src/commands/setup.ts': 'not yet migrated: open PR #6406 edits this file',
'src/commands/takes.ts': 'not yet migrated: open PR #6505 edits this file',
'src/core/harness/install.ts': 'not yet migrated: open PR #6319, #6406 edits this file',
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 01202716cf..65a0504768 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -21,7 +21,6 @@ src/commands/extract.ts runExtract 398 seed: W5 baseline, refactor wave 1 (decom
src/commands/import.ts runImport 978 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 GBRA-40 F4b: planner-stats refresh every import.analyze_every_pages files (logic in planner-stats.ts); +6 #5988: onFileResult hook so full sync holds content refusals (logic in commands/sync/holds.ts); +3 #5988: heldPaths skip so a full sync never imports a rename destination it held this run (logic in commands/sync/holds.ts); +1 Wave B lane 1d (TODO wave-b PR 1): reads the segmented-storage policy once per run for the streamed import of files over the single-string ceiling; +1 GBRA-218 A2: the import barrier installs the tree's folder rules before any page (logic in access/policy-transfer.ts); +4 GST-2462: the noticeRun option, the privacy_label_ignored notice call and its JSON and result fields (logic in core/search/ignored-privacy-labels.ts)
src/commands/mcp-expose.ts runPublish 443 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/migrate-engine.ts runMigrateEngine 405 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/commands/serve.ts installStdioLifecycle 326 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 GBRA-40 Lane D: facts drain install call and its shutdown stop (logic in installFactsDrain); +1 engine graduation (GBRA-50 G3): onShutdownReady hook for the graduation hand-off (logic in installGraduationHandoff); +3 GBRA-438 PR 2: the idle upkeep slot, its shutdown stop and the upkeep step after the idle sweep (logic in idleUpkeepSlot)
src/commands/sources.ts runAdd 365 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 4 #5673: connector sources print that autopilot keeps them synced after the first sync
src/core/bootstrap/harness.ts applyHarness 1167 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/brainstorm/orchestrator.ts _runBrainstormInner 413 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5890 close-set spreads INTERNAL_BREADTH_SEARCH_OPTS
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index d05de457fa..cbda7221f5 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -354,6 +354,7 @@ test/reindex-trace-transparency.serial.test.ts global-state global-state: R3: co
test/remediation-run-extras.serial.test.ts R2 R2: mock.module(../src/core/minions/queue.ts, ../src/core/minions/wait-for-completion.ts) replaces modules for every file in the process
test/remediation-run-loop.serial.test.ts R2 R2: mock.module(../src/core/minions/queue.ts, ../src/core/minions/wait-for-completion.ts, ../src/core/remediation-checkpoint.ts, ../src/core/ai/gateway.ts) replaces modules for every file in the process
test/remote-privacy-journeys.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; configureGateway changes the process-wide AI gateway; binds local servers/ports
+test/remote-stdio-bridge.serial.test.ts global-state global-state: binds local servers/ports (a real serve --http host it stops and restarts, a proxy, stdio bridge children)
test/repair-contextual-mode-5621.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
test/rerank-degraded-notice.serial.test.ts R2 R2: mock.module (hybridSearchCached)
test/rerank-failure-reason.serial.test.ts global-state global-state: configureGateway changes the process-wide AI gateway; binds local servers/ports; R1: mutates process.env (GBRAIN_HOME, GBRAIN_AUDIT_DIR); R3: constructs PGLiteEngine inside a test (disconnected in finally)
diff --git a/src/cli/help/serve.ts b/src/cli/help/serve.ts
index d381b13847..9b8ad081e7 100644
--- a/src/cli/help/serve.ts
+++ b/src/cli/help/serve.ts
@@ -2,7 +2,7 @@
import type { CliHelpSpec } from '../command-table.ts';
export const help: CliHelpSpec = {
- summary: 'Run the MCP server: stdio by default, or OAuth 2.1 HTTP with --http.',
+ summary: 'Run the MCP server: stdio by default, or OAuth 2.1 HTTP with --http. On a thin client, bare serve is a stdio bridge to the remote brain and takes only --surface, --advertise and --source-guard.',
usage: [
'gbrain serve [--surface verbs|starter|full] [--advertise verbs|starter|full] [--access full|read-only] [--source-guard] [--stdio-idle-timeout <s>] [--stdio-member <id>] [--fail-fast] [--cli-socket]',
'gbrain serve --http [--port <n>] [--bind <host>] [--public-url <url>] [--token-ttl <s>] [--enable-dcr] [--surface …] [--advertise …]',
diff --git a/src/cli/main.ts b/src/cli/main.ts
index e1ccf891d0..82c8f12854 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -1764,7 +1764,7 @@ const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {
'apply-migrations': 'schema migrations run on the host. SSH and run there.',
'repair-jsonb': 'repair-jsonb operates on the local DB only.',
integrity: 'integrity scans local files. Run on the host machine.',
- serve: 'serve starts a server. Run on the host, not the thin client.',
+ serve: '`serve --http` and serve\'s host flags need the brain host; bare `gbrain serve` on a thin client is a stdio bridge to it.',
dream: 'dream runs the autopilot cycle on the host. Run `gbrain dream` on the host machine.',
orphans: "orphans needs the host's brain. Run on the host or use the `find_orphans` MCP tool from your agent.",
transcripts: 'transcripts is server-private (raw chat exports stay on the host). Read transcripts on the host machine.',
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index cb9815b353..25482bc430 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -1,4 +1,3 @@
-import { spawnSync } from 'node:child_process';
import { PoolStallWatch } from '../core/postgres-engine/pool-stall-watch.ts';
import { installRestartRequiredExit, recordServeTransport, resolveRestartRequiredExitSeconds, SERVE_RESTART_REQUIRED_EXIT_ENV } from './serve-health.ts';
import { SERVE_UNHEALTHY_EXIT_CODE } from '../core/exit-codes.ts';
@@ -8,6 +7,9 @@ import type { IdleUpkeep } from '../core/maintenance/idle.ts';
export { serveFailFastRequested, writeServeFailFastEnvelope } from '../core/serve-fail-fast.ts';
import { isEngineDegraded as isEngineDegradedForServe } from '../core/degraded-marker.ts';
import { startMcpServer, stdioRpcsInFlightCount, resolveMcpStdioSourceScope } from '../mcp/server.ts';
+import { installStdioShutdownTriggers, probeWatchdogAvailable, readLiveParentPid, resolveEofDrainMs, type StdioLifecycleDeps } from '../mcp/stdio-lifecycle.ts';
+// The parent-liveness readers moved to the engine-free stdio lifecycle the thin-client bridge shares.
+export { isPidAlive, probeWatchdogAvailable, readLiveParentPid } from '../mcp/stdio-lifecycle.ts';
import { VERB_NAMES } from '../core/verbs.ts';
import { parseStdioMemberFlag } from '../core/stdio-member-flag.ts';
import { RESIDENT_POOL_FLOOR } from '../core/pg-access-classify.ts';
@@ -59,15 +61,6 @@ const CLEANUP_DEADLINE_MS = 5_000;
// one window. Env-tunable via GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS; 0 disables.
const DEFAULT_BOOT_TIMEOUT_SECONDS = 60;
-// How often the parent-process watchdog polls the live kernel parent PID
-// (via `readLiveParentPid`, NOT the cached `process.ppid` — see that
-// helper's comment). We don't receive a signal when our parent dies (the
-// kernel just re-parents us to init / launchd / a subreaper-PID), so
-// polling is the only reliable way to detect "parent went away without
-// closing stdin". 5s matches the cadence in the concurrent #591 PR;
-// faster polling has no benefit, slower would extend the lock-leak window.
-const PARENT_WATCHDOG_INTERVAL_MS = 5_000;
-
// Idle maintenance sweep [ENG-5]: cadence of the stdin-inactivity check.
// Each tick that saw NO stdin data since the previous tick runs a bounded
// sweep (fence reconcile / link+timeline extraction / corpus ingest — see
@@ -559,27 +552,6 @@ async function serveBrain(
// hooks from being able to call process.exit() cleanly.
}
-// #4409: stdin-EOF drain bound. Long enough for a real tool call (a query
-// with embedding + LLM expansion) to finish; short enough that a genuinely
-// wedged handler can't pin the PGLite lock forever after the parent left.
-const DEFAULT_EOF_DRAIN_MS = 30_000;
-
-// Env resolution for the stdin-EOF drain bound. Lenient like
-// resolveBootTimeoutMs: a typo'd env var must not turn the data-loss fix
-// into a shutdown failure. 0 disables the drain (immediate exit).
-function resolveEofDrainMs(): number {
- const raw = process.env.GBRAIN_SERVE_EOF_DRAIN_MS;
- if (raw === undefined || raw.trim() === '') return DEFAULT_EOF_DRAIN_MS;
- const n = Number(raw);
- if (!Number.isFinite(n) || n < 0) {
- console.error(
- `[gbrain serve] ignoring invalid GBRAIN_SERVE_EOF_DRAIN_MS=${JSON.stringify(raw)} — using default ${DEFAULT_EOF_DRAIN_MS}ms`,
- );
- return DEFAULT_EOF_DRAIN_MS;
- }
- return Math.floor(n);
-}
-
/**
* #5205: the boot-deadline line names the boot phase that never finished and
* the engine's pool pressure, so a pool below the resident floor reads as a
@@ -647,17 +619,6 @@ function installGraduationHandoff(engine: BrainEngine, opts: ServeOptions): Serv
};
}
-interface StdioLifecycleDeps {
- stdin: NodeJS.ReadableStream & { isTTY?: boolean };
- signals: Pick<NodeJS.Process, 'on'>;
- exit: (code?: number) => void;
- log: (msg: string) => void;
- getParentPid: () => number;
- setInterval: (fn: () => void, ms: number) => unknown;
- clearInterval: (handle: unknown) => void;
- probeWatchdog: () => boolean;
-}
-
/**
* Automatic facts drain (Foundations 2, Lane D): PGLite has no job worker, so
* the resident serve runs queued facts-absorb jobs on its own unref'd timer,
@@ -726,7 +687,7 @@ function installStdioLifecycle(
};
let shuttingDown = false;
- let parentWatchdog: unknown = null;
+ let stopWatchdog = (): void => {};
let idleSweepTimer: unknown = null;
const idleUpkeep = idleUpkeepSlot(opts.upkeep ?? defaultIdleUpkeep(deps.log)); // GBRA-438
let activateIdleActivityTracking = (): void => {};
@@ -738,10 +699,7 @@ function installStdioLifecycle(
// Stop the parent-watchdog interval as soon as a shutdown begins so
// it cannot fire a redundant 'parent-died' shutdown while the first
// one is still draining the cleanup chain.
- if (parentWatchdog !== null) {
- deps.clearInterval(parentWatchdog);
- parentWatchdog = null;
- }
+ stopWatchdog();
// Stop the idle-sweep interval too [ENG-5] — a sweep must never start
// while the engine is being disconnected underneath it.
@@ -806,127 +764,16 @@ function installStdioLifecycle(
});
};
- // Signal-based termination. SIGTERM: daemon ask. SIGINT: user Ctrl-C.
- // SIGHUP: terminal disconnect / daemon-style "reload" channels — Aragorn
- // observed real-world hosts (Claude Desktop on macOS, hermes-agent
- // restart) send these instead of closing stdin. All three get the same
- // graceful path; the idempotency guard absorbs duplicate signals.
- deps.signals.on('SIGTERM', () => beginShutdown('SIGTERM'));
- deps.signals.on('SIGINT', () => beginShutdown('SIGINT'));
- deps.signals.on('SIGHUP', () => beginShutdown('SIGHUP'));
-
- // Stdin EOF — the parent closes the pipe but the MCP SDK's
- // StdioServerTransport only listens for 'data'/'error', not 'end' or
- // 'close', so without these hooks the process keeps the engine (and its
- // PGLite write lock) live indefinitely after the parent disconnects.
- // 'end' fires on a clean EOF; 'close' fires when the underlying handle
- // is destroyed (e.g. parent SIGKILL'd while pipe still open). Both
- // converge on the same idempotent shutdown.
- // Skip when stdin is a TTY: interactive `gbrain serve` use shouldn't
- // terminate just because the user hasn't typed anything. Signal /
- // watchdog paths still cover that case if needed.
- // v0.34.1 (#870): when MCP_STDIO=1, the wrapping gateway pipes the
- // JSON-RPC handshake then closes its stdin half. Treating that as a
- // permanent disconnect kills the server before the first tool call.
- // Signal handlers (SIGTERM/SIGINT/SIGHUP), transport.onclose, and the
- // parent-process watchdog below still cover legitimate shutdown paths.
- // `mcpStdio` is the injectable form; default reads the env once at
- // install time so tests stay isolated (no process.env mutation).
- const mcpStdioMode = opts.mcpStdio ?? (process.env.MCP_STDIO === '1');
- // #4409: a one-shot MCP client writes its frames and closes stdin
- // immediately. Node delivers 'end' AFTER all 'data' events, and the SDK
- // parses every received frame synchronously during 'data' (handler start
- // is queued as a microtask) — so at EOF time requests can be in flight
- // with no response written yet. Treating EOF as an immediate shutdown
- // silently dropped those responses (the codex-plugin door went red on
- // exactly this shape). Drain in-flight RPCs — bounded — before the
- // graceful exit; idle servers still exit promptly (one timer tick).
- // GBRAIN_SERVE_EOF_DRAIN_MS tunes the bound; 0 restores immediate exit.
- const pendingRpcs = opts.pendingRpcs ?? stdioRpcsInFlightCount;
- const eofDrainMs = opts.eofDrainMs ?? resolveEofDrainMs();
- let eofDrainStarted = false;
- const drainThenShutdown = (reason: string): void => {
- if (shuttingDown || eofDrainStarted) return;
- eofDrainStarted = true;
- void (async () => {
- if (eofDrainMs > 0) {
- // One macrotask so already-parsed requests' handlers (microtasks)
- // start and increment the counter before the first check.
- await new Promise<void>((r) => setTimeout(r, 0));
- if (pendingRpcs() > 0) {
- deps.log(
- `GBrain MCP server: stdin EOF with ${pendingRpcs()} in-flight request(s) — draining before exit (bound ${eofDrainMs}ms; GBRAIN_SERVE_EOF_DRAIN_MS)`,
- );
- const deadlineAt = Date.now() + eofDrainMs;
- while (pendingRpcs() > 0 && Date.now() < deadlineAt && !shuttingDown) {
- await new Promise<void>((r) => setTimeout(r, 25));
- }
- }
- // One extra macrotask: the SDK sends the response in a .then AFTER
- // the handler resolves — let that stdout write get issued before
- // the cleanup chain starts.
- await new Promise<void>((r) => setTimeout(r, 0));
- }
- beginShutdown(reason);
- })();
- };
- opts.onShutdownReady?.(drainThenShutdown);
- if (!deps.stdin.isTTY && !mcpStdioMode) {
- deps.stdin.once('end', () => drainThenShutdown('stdin-end'));
- deps.stdin.once('close', () => drainThenShutdown('stdin-close'));
- }
-
- // Parent-process watchdog. Some hosts (launchd, cron, certain MCP
- // gateways) terminate without closing stdin and without sending a
- // signal — the kernel just re-parents us to whichever ancestor is
- // still alive (PID 1, or any closer subreaper such as launchd, systemd,
- // tmux, or a parent shell with PR_SET_CHILD_SUBREAPER). Polling is the
- // only portable way to notice; see `readLiveParentPid` for why we
- // cannot rely on `process.ppid` (cached at process creation and never
- // refreshed on re-parent in Node or Bun). On Windows the same class of
- // orphan is WORSE in practice: MCP hosts typically launch the server
- // through a `cmd.exe` wrapper (.bat/.cmd), and killing the wrapper
- // does not kill the child — so without a watchdog the orphan holds the
- // PGLite write lock until the machine reboots. `readLiveParentPid`
- // handles the platform split internally (PPID-change on POSIX,
- // parent-liveness on Windows); the comparison below works for both.
- //
- // We capture the initial parent PID once at install time and fire on
- // ANY change, not just reparent-to-PID-1. The PR-#676 author's original
- // `=== 1` check missed reparent-to-subreaper-PID-N, which is the actual
- // observed behavior under launchd / systemd subreapers (codex review
- // finding #3). A process legitimately started under PID 1 (e.g. a
- // systemd service) skips the watchdog: there's no parent-death event
- // to detect, and any reparent FROM 1 doesn't happen. `unref()` keeps
- // the interval from blocking other exit paths.
- //
- // A one-shot startup probe (D2-revisited per codex finding #4) verifies
- // that the underlying mechanism (`spawnSync('ps')`) actually works on
- // this host. Stripped containers / busybox-without-procps environments
- // would silently fall back to the cached `process.ppid` on every tick
- // — the watchdog claims to be installed but never fires. When the probe
- // fails, we skip installing the interval entirely and log loudly so the
- // operator sees the degraded mode instead of a phantom watchdog.
- // `> 1` (was `!== 1`): PID 1 is the documented legitimate-init-child
- // skip; PID 0 is the new "parent already gone at install time" report
- // from the Windows liveness reader — installing an interval that
- // compares 0 to 0 forever would be a phantom watchdog, and stdin
- // 'close' already covers a parent that died before we booted.
- const initialParentPid = deps.getParentPid();
- if (initialParentPid > 1) {
- if (!deps.probeWatchdog()) {
- deps.log(
- '[gbrain serve] watchdog disabled: no parent-liveness mechanism (ps / signal-0 probe failed) — child will rely on stdin EOF / signals only',
- );
- } else {
- parentWatchdog = deps.setInterval(() => {
- if (deps.getParentPid() !== initialParentPid) {
- beginShutdown('parent-died');
- }
- }, PARENT_WATCHDOG_INTERVAL_MS);
- (parentWatchdog as { unref?: () => void } | null)?.unref?.();
- }
- }
+ // Signals, the bounded stdin-EOF drain (#4409; skipped under MCP_STDIO=1, #870, and on a TTY) and the parent-pid
+ // watchdog: the engine-free triggers in src/mcp/stdio-lifecycle.ts, shared with the thin-client bridge.
+ const triggers = installStdioShutdownTriggers(deps, {
+ beginShutdown, isShuttingDown: () => shuttingDown,
+ pendingRpcs: opts.pendingRpcs ?? stdioRpcsInFlightCount,
+ eofDrainMs: opts.eofDrainMs ?? resolveEofDrainMs(),
+ mcpStdio: opts.mcpStdio ?? (process.env.MCP_STDIO === '1'),
+ });
+ stopWatchdog = triggers.stopWatchdog;
+ opts.onShutdownReady?.(triggers.drainThenShutdown);
// Idle maintenance sweep [ENG-5]: every IDLE_SWEEP_INTERVAL_MS tick that
// saw no stdin data since the previous tick runs one bounded sweep (small
@@ -1036,112 +883,6 @@ function installStdioLifecycle(
return activateIdleActivityTracking;
}
-/**
- * Signal-0 process-liveness probe (`process.kill(pid, 0)` — existence
- * check only, no signal delivered; OpenProcess under the hood on
- * Windows). EPERM means the PID exists but we lack rights to signal it
- * — that is still "alive" for watchdog purposes. Exported for direct
- * unit testing of the Windows watchdog path.
- */
-export function isPidAlive(pid: number): boolean {
- if (!Number.isInteger(pid) || pid <= 0) return false;
- try {
- process.kill(pid, 0);
- return true;
- } catch (err) {
- return (err as NodeJS.ErrnoException).code === 'EPERM';
- }
-}
-
-/**
- * Resolve the live parent PID from the kernel (not the cached startup
- * value). Both Node and Bun expose `process.ppid` as a property captured
- * at process creation, so it does NOT update when the kernel re-parents
- * us to a new ancestor after the original parent dies — which is the
- * exact event the watchdog needs to detect. Empirical evidence on
- * macOS / Bun 1.3.12: `process.ppid` stays at the original parent ID
- * indefinitely while `ps -o ppid= -p $$` reports the new parent within
- * one tick.
- *
- * Windows has no `ps` — the original ps-only implementation made the
- * startup probe fail on every Windows host, so the watchdog was always
- * disabled and an orphaned serve (e.g. its cmd.exe .bat wrapper killed
- * by the MCP host without closing stdin) held the PGLite write lock
- * indefinitely. But Windows also never re-parents orphans, so the
- * cached `process.ppid` stays correct for the process's lifetime and
- * the question inverts from "did the live PPID change?" to "is the
- * original parent still alive?" — answered in-process via signal-0,
- * no external binary needed. Parent dead → report 0 (kernel PID 0 is
- * the System Idle Process, never our parent), which differs from
- * `initialParentPid` and fires the watchdog. Known degraded mode:
- * Windows recycles PIDs aggressively, so a reused parent PID can mask
- * a death — stdin EOF / signals remain the primary shutdown channels
- * and the watchdog stays the backstop, same posture as POSIX.
- *
- * Cost: ~10ms per ps spawn on POSIX, effectively free on Windows.
- * Called every 5s (PARENT_WATCHDOG_INTERVAL_MS), so amortized < 0.5%
- * CPU. Falls back to `process.ppid` if `ps` fails (best-effort safety
- * net for stripped-down containers, etc.); the startup probe at
- * watchdog-install time loud-logs and skips the interval entirely when
- * no mechanism is available, so a per-tick fallback is a redundant
- * safety net rather than a primary mechanism.
- *
- * `platform` is a test seam (defaults to the real platform) so CI on
- * any OS can exercise both branches — signal-0 works everywhere.
- */
-export function readLiveParentPid(platform: NodeJS.Platform = process.platform): number {
- if (platform === 'win32') {
- return isPidAlive(process.ppid) ? process.ppid : 0;
- }
- try {
- const r = spawnSync('ps', ['-o', 'ppid=', '-p', String(process.pid)], {
- encoding: 'utf8',
- timeout: 1000,
- });
- if (r.status === 0 && typeof r.stdout === 'string') {
- const n = parseInt(r.stdout.trim(), 10);
- if (Number.isInteger(n) && n >= 0) return n;
- }
- } catch {
- /* fall through */
- }
- return process.ppid;
-}
-
-/**
- * One-shot probe at watchdog-install time to confirm the platform's
- * parent-liveness mechanism actually works on this host. POSIX: true
- * iff `spawnSync('ps','-o','ppid=','-p',PID)` exits 0 with a parseable
- * integer. Windows: true iff signal-0 succeeds against our own PID
- * (always alive — verifies the mechanism, not the parent). When it
- * returns false, the caller skips installing the watchdog and emits a
- * loud stderr line — the operator sees "watchdog disabled" instead of
- * an installed-but-never-fires phantom.
- *
- * Why a separate probe rather than relying on the per-tick fallback in
- * `readLiveParentPid`: the per-tick fallback returns the cached
- * `process.ppid` silently, so the watchdog runs every 5s, compares
- * cached PPID to itself, never detects a change, and never fires —
- * while still claiming to be active. The probe surfaces the gap once
- * at install time and lets the caller short-circuit cleanly.
- */
-export function probeWatchdogAvailable(platform: NodeJS.Platform = process.platform): boolean {
- if (platform === 'win32') {
- return isPidAlive(process.pid);
- }
- try {
- const r = spawnSync('ps', ['-o', 'ppid=', '-p', String(process.pid)], {
- encoding: 'utf8',
- timeout: 1000,
- });
- if (r.status !== 0 || typeof r.stdout !== 'string') return false;
- const n = parseInt(r.stdout.trim(), 10);
- return Number.isInteger(n) && n >= 0;
- } catch {
- return false;
- }
-}
-
function parseStdioIdleTimeout(args: string[]): number {
const idx = args.indexOf('--stdio-idle-timeout');
if (idx < 0) return 0;
diff --git a/src/commands/thin-client-routing.ts b/src/commands/thin-client-routing.ts
index 6576b75809..0990593e7f 100644
--- a/src/commands/thin-client-routing.ts
+++ b/src/commands/thin-client-routing.ts
@@ -64,6 +64,21 @@ export async function routeThinClientCommand(
const sub = args[0];
const rest = args.slice(1);
+ // #8543: bare `serve` (or gbrain's own registration flags) is the stdio bridge to the remote brain; every other serve
+ // form refuses here with a fix that keeps its flags, so the caller's generic refusal never renders `Fix: gbrain serve`.
+ if (command === 'serve' && !args.includes('--help') && !args.includes('-h')) {
+ const { parseBridgeServeArgs, serveThinClientRefusal } = await import('../mcp/remote-bridge-args.ts');
+ const { exitCliError, usageError } = await import('../cli/cli-error.ts');
+ const { getCliOptions } = await import('../core/cli-options.ts');
+ if (getCliOptions().brain) exitCliError(usageError('--brain is not supported on a thin-client install: the remote server is a single brain.', 'Remove --brain, or run from a machine with local mounts (`gbrain mounts list`).'), 'serve');
+ const parsed = (() => { try { return parseBridgeServeArgs(args); } catch (error) { return exitCliError(error, 'serve'); } })();
+ if (!parsed.bridge) return exitCliError(serveThinClientRefusal(parsed.refused, cfg.remote_mcp?.mcp_url ?? ''), 'serve');
+ const { startRemoteStdioBridge } = await import('../mcp/remote-bridge.ts');
+ const timeoutMs = getCliOptions().timeoutMs;
+ await startRemoteStdioBridge(cfg, { surface: parsed.surface, advertise: parsed.advertise, sourceGuard: parsed.sourceGuard, ...(timeoutMs ? { timeoutMs } : {}) });
+ return true;
+ }
+
if (command === 'sources' && sub === 'shared-skills') {
if (rest.includes('--help') || rest.includes('-h')) {
console.log((await import('./sources-shared-skills.ts')).SOURCES_SHARED_SKILLS_HELP);
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 383d3fa8d0..dda84e0bdb 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -27,7 +27,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'beliefs': ['--apply', '--archived-at', '--brain', '--from-url-env', '--help', '--json', '--probe', '--purge-mirror', '--since', '--source'],
'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],
'book-mirror': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--author', '--background', '--body', '--bound-slug-prefixes', '--brain', '--card', '--chapters-dir', '--client', '--context-file', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--expected-revision', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--of', '--only', '--page', '--params', '--patch', '--path', '--phase', '--prefer', '--privacy-url', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--room', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--terms-url', '--timeout', '--timeout-ms', '--timings', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],
- 'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--add', '--adopt', '--advertise', '--all', '--allow-unverified-remote', '--auto', '--autostash', '--batch-check', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--force-with-lease', '--gbrain-bin', '--get', '--get-all', '--git-dir', '--git-path', '--hard', '--harness', '--header', '--heads', '--help', '--home', '--host', '--hostname', '--http', '--id', '--init', '--install', '--is-ancestor', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--keep-checkout', '--local', '--local-env-vars', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-assume-unchanged', '--no-autostash', '--no-capture', '--no-cron', '--no-follow-tags', '--no-hooks', '--no-instructions', '--no-renames', '--no-seat', '--no-skip-worktree', '--no-tags', '--no-verify', '--oauth-client-id', '--oauth-client-secret', '--only', '--operations', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pull', '--pure', '--push-only', '--quiet', '--rebase', '--recurse-submodules', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--require-clean', '--resolve', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skill-loading', '--skills', '--skip', '--source', '--sources', '--status', '--stdin', '--surface', '--to', '--token', '--token-name', '--unset-all', '--untracked-files', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
+ 'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--add', '--adopt', '--advertise', '--all', '--allow-unverified-remote', '--arg', '--auto', '--autostash', '--batch-check', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--command', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--force-with-lease', '--gbrain-bin', '--get', '--get-all', '--git-dir', '--git-path', '--hard', '--harness', '--header', '--heads', '--help', '--home', '--host', '--hostname', '--http', '--id', '--init', '--install', '--is-ancestor', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--keep-checkout', '--local', '--local-env-vars', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-assume-unchanged', '--no-autostash', '--no-capture', '--no-cron', '--no-follow-tags', '--no-hooks', '--no-instructions', '--no-renames', '--no-seat', '--no-skip-worktree', '--no-tags', '--no-verify', '--oauth-client-id', '--oauth-client-secret', '--only', '--operations', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pull', '--pure', '--push-only', '--quiet', '--rebase', '--recurse-submodules', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--require-clean', '--resolve', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skill-loading', '--skills', '--skip', '--source', '--sources', '--status', '--stdin', '--surface', '--to', '--token', '--token-name', '--unset-all', '--untracked-files', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
'brainstorm': ['--admin-intent', '--brain', '--confirm-relocated-root', '--dir', '--expected-epoch', '--expected-state', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--manifest', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--path', '--probe', '--resume', '--save', '--self-transfer', '--source', '--source-id', '--stale', '--strict-budget', '--yes'],
'bundled-skill': ['--asset', '--brain', '--help', '--json', '--source'],
'cache': ['--brain', '--help', '--json', '--source', '--yes'],
@@ -44,7 +44,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'code-refs': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],
'compile-context': ['--brain', '--budget', '--check', '--error-unmatch', '--git-path', '--help', '--include', '--include-core', '--json', '--out', '--remove-core', '--revision', '--show-toplevel', '--source', '--stdout', '--target'],
'config': ['--accept-pending', '--admin-intent', '--all', '--all-from', '--apply', '--as', '--background', '--brain', '--budget-ms', '--call-site', '--channel', '--claims', '--confirm-quiesced', '--coverage-override', '--dataset', '--db-url', '--diff-filter', '--dim', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--exclude', '--expected-state', '--explain', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--gbrain-bin', '--hard-deadline', '--harness', '--help', '--http', '--id', '--include-hidden', '--include-withdrawals', '--input', '--items-out', '--json', '--key-stdin', '--kind', '--limit', '--min', '--name', '--name-only', '--no-accept-pending', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-extract', '--no-hard-deadline', '--no-hooks', '--no-llm', '--no-pull', '--no-renames', '--no-schema-pack', '--only', '--out', '--path', '--pattern', '--phase', '--privacy-url', '--probe', '--progress-interval', '--progress-json', '--provider', '--publish', '--query', '--quiet', '--raw', '--recommended', '--remediate', '--remediation-plan', '--remove', '--repo', '--revision', '--room', '--session', '--shadow', '--since', '--skill-loading', '--slot', '--source', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--suite', '--surface', '--synopsis', '--target', '--terms-url', '--threshold', '--tier', '--timeout', '--timings', '--to', '--url', '--wait', '--what-if-threshold', '--working-tree', '--yes'],
- 'connect': ['--advertise', '--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--fresh-token', '--gbrain-bin', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--no-instructions', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--only', '--public-url', '--pure', '--register', '--remove', '--root', '--runtime', '--scope', '--scopes', '--show-token', '--skill-loading', '--skills-index-only', '--source', '--source-ids', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--workspace', '--yes'],
+ 'connect': ['--advertise', '--agent', '--arg', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--command', '--credentials-file', '--env', '--force', '--fresh-token', '--gbrain-bin', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--no-instructions', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--only', '--public-url', '--pure', '--register', '--remove', '--root', '--runtime', '--scope', '--scopes', '--show-token', '--skill-loading', '--skills-index-only', '--source', '--source-ids', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--workspace', '--yes'],
'connectors': ['--accept-pending', '--all', '--as', '--background', '--brain', '--channels', '--cookie', '--deadline', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--kind', '--limit', '--max-requests', '--no-accept-pending', '--no-browser', '--probe', '--progress-interval', '--progress-json', '--provider', '--quiet', '--room', '--source', '--timeout', '--timings', '--token', '--try-oauth', '--wait', '--window-days', '--workers', '--yes'],
'conversation-parser': ['--brain', '--help', '--json', '--source'],
'core': ['--apply', '--brain', '--fail-fast', '--help', '--include-core', '--json', '--priority', '--revision', '--slug', '--source', '--tools-json'],
@@ -87,7 +87,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
'maintain': ['--absolute-git-dir', '--accept-dns', '--accept-pending', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--alert', '--all', '--allow-outside-source-root', '--apply', '--as', '--assign-corpus', '--attest-read', '--audit', '--background', '--bg', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--cask', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--db-url', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--enable-dcr', '--entity', '--exclude', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--get', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--https', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-extensions', '--no-extract', '--no-hard-deadline', '--no-instructions', '--no-pull', '--no-renames', '--no-schema-pack', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--operator', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefix', '--preview', '--privacy-url', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--public-url', '--pull', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw-only', '--reader-mode', '--readers', '--reads-unscoped', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repo', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--room', '--runner', '--safe', '--scan-secrets', '--schedule', '--scope', '--scopes', '--serves', '--session', '--set-path', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--strict', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--terms-url', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--trust', '--type', '--unattended', '--unindexed', '--unschedule', '--untracked-files', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--wakeshift', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
- 'mcp': ['--admin-token-file', '--advertise', '--agent', '--all', '--arg', '--attest-actor', '--attest-ops', '--attest-read', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--cursor', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--email', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--groups', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--member', '--name', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--qm', '--queue', '--reason', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
+ 'mcp': ['--admin-token-file', '--advertise', '--agent', '--all', '--arg', '--attest-actor', '--attest-ops', '--attest-read', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--command', '--credentials-file', '--credentials-out', '--cursor', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--email', '--enable-dcr', '--env', '--federated-read', '--flow', '--force', '--funnel', '--groups', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--member', '--name', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--qm', '--queue', '--reason', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
'memory-proposals': ['--all', '--brain', '--dry-run', '--help', '--json', '--limit', '--reason', '--replace', '--source'],
'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--as', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--room', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],
'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],
@@ -125,7 +125,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--path', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
'self-upgrade': ['--apply', '--backend', '--brain', '--channel', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--snooze', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],
'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--advertise', '--all-new', '--apply-rewrites', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--labelled-only', '--limit', '--log-full-params', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-open-pages', '--no-pull', '--no-stdio-member', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--private-pages', '--profile', '--provenance', '--public-url', '--read-sources', '--reads-unscoped', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--serves', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--stdio-member', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
- 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--apply', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--catalog', '--credentials-file', '--dry-run', '--env', '--expect', '--force', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--header', '--help', '--http', '--images', '--input-type', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--labelled-only', '--legacy-lock', '--limit', '--link', '--live-fraction', '--max-cost', '--max-usd', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--name', '--no-capture', '--no-embedding', '--no-extensions', '--no-hooks', '--no-instructions', '--no-open-pages', '--no-providers', '--no-stdio-member', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--only', '--owner-sender', '--path', '--pglite', '--pins-route', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--schedule', '--scope', '--serves', '--show-toplevel', '--skill-loading', '--skills-index-only', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--strict-json', '--surface', '--token', '--trust', '--url', '--wakeshift', '--workspace', '--yes'],
+ 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--apply', '--arg', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--catalog', '--command', '--credentials-file', '--dry-run', '--env', '--expect', '--force', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--header', '--help', '--http', '--images', '--input-type', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--labelled-only', '--legacy-lock', '--limit', '--link', '--live-fraction', '--max-cost', '--max-usd', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--name', '--no-capture', '--no-embedding', '--no-extensions', '--no-hooks', '--no-instructions', '--no-open-pages', '--no-providers', '--no-stdio-member', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--only', '--owner-sender', '--path', '--pglite', '--pins-route', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--schedule', '--scope', '--serves', '--show-toplevel', '--skill-loading', '--skills-index-only', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--strict-json', '--surface', '--token', '--trust', '--url', '--wakeshift', '--workspace', '--yes'],
'skill-resolver': ['--accept-capabilities', '--agent', '--brain', '--bundled', '--catalog', '--claude-plugins', '--dir', '--exclude', '--expect-catalog', '--explain-target', '--fail-open', '--force', '--from-json', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--help', '--input-json', '--input-type', '--json', '--line', '--link', '--load-hint', '--min-match', '--names-only', '--no-extensions', '--only', '--out', '--previous', '--reset-session', '--routing', '--runtime', '--scope', '--session', '--shadow', '--shadow-log', '--show-toplevel', '--skill-loading', '--source', '--text', '--top-gate', '--top-k'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--loop', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],
diff --git a/src/core/doctor-remote.ts b/src/core/doctor-remote.ts
index 273b12bdbe..1961dfedca 100644
--- a/src/core/doctor-remote.ts
+++ b/src/core/doctor-remote.ts
@@ -471,8 +471,10 @@ export function buildScopeCheck(grantedScope: string, probe: ScopeProbeResult):
// status doesn't flap on probe noise.
//
// - read.missing_scope → 'fail' (broken setup; nothing works)
- // - admin.missing_scope → 'warn' (the load-bearing case for v0.29.2 thin
- // clients that registered with read+write only; pinpoint hint follows)
+ // - admin.missing_scope → 'ok' when the grant never claimed admin (a
+ // read or read+write client is narrow by design; #8543 — doctor never
+ // recommends adding a scope), 'warn' only when the grant lists admin
+ // and the host still refuses it
// - both succeed → 'ok'
// - other probe errors → 'ok' with inconclusive=true
const readMissing = !probe.read_ok && probe.read_error === 'missing_scope';
@@ -490,6 +492,19 @@ export function buildScopeCheck(grantedScope: string, probe: ScopeProbeResult):
},
};
}
+ if (adminMissing && !grantedScope.split(/[\s,]+/).includes('admin')) {
+ return {
+ name: 'oauth_client_scopes_probe',
+ status: 'ok',
+ message: `read works; this client was granted "${grantedScope || 'unspecified'}" without admin, so admin-only operations are refused by design. Nothing to fix.`,
+ detail: {
+ granted: grantedScope || null,
+ read_ok: true,
+ admin_ok: false,
+ admin_granted: false,
+ },
+ };
+ }
if (adminMissing) {
return {
name: 'oauth_client_scopes_probe',
diff --git a/src/core/mcp-client.ts b/src/core/mcp-client.ts
index 32279a66e0..f2ad929892 100644
--- a/src/core/mcp-client.ts
+++ b/src/core/mcp-client.ts
@@ -21,6 +21,7 @@ import { createHash, randomUUID } from 'node:crypto';
import { isPersistenceIpcMutation } from './persistence/ipc.ts';
import { replayWhilePending } from './persistence/write-wait.ts';
import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import type { CallToolResult, Tool } from '@modelcontextprotocol/sdk/types.js';
import type { StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
import { anySignal } from './abort-check.ts';
@@ -300,7 +301,7 @@ async function getAccessToken(config: GBrainConfig, force = false, signal?: Abor
* The SDK replaces requestInit.signal with its own transport signal. Compose
* them in fetch so cancellation covers HTTP bodies as well as SDK requests.
*/
-async function buildClient(mcpUrl: string, accessToken: string, signal?: AbortSignal): Promise<Client> {
+async function buildClient(mcpUrl: string, accessToken: string, signal?: AbortSignal, clientName: string = GBRAIN_THIN_CLIENT_NAME): Promise<Client> {
const { Client, StreamableHTTPClientTransport } = await loadHttpClientSdk();
const transport = new StreamableHTTPClientTransport(new URL(mcpUrl), {
requestInit: {
@@ -308,7 +309,7 @@ async function buildClient(mcpUrl: string, accessToken: string, signal?: AbortSi
'Authorization': `Bearer ${accessToken}`,
// Hosts serve full search/query rows to gbrain's own CLI (renderers,
// --explain). A row-shape hint only, never an authority claim.
- [GBRAIN_CLIENT_HEADER]: `${GBRAIN_THIN_CLIENT_NAME}/${VERSION}`,
+ [GBRAIN_CLIENT_HEADER]: `${clientName}/${VERSION}`,
},
},
fetch: (input, init) => fetch(input, {
@@ -317,7 +318,7 @@ async function buildClient(mcpUrl: string, accessToken: string, signal?: AbortSi
}),
});
const client = new Client(
- { name: GBRAIN_THIN_CLIENT_NAME, version: '1' },
+ { name: clientName, version: '1' },
{ capabilities: {} },
);
try {
@@ -531,6 +532,18 @@ export async function callRemoteTool(
/** One tool a remote serve lists for this token: its name and the parameter names its input schema declares. */
export interface RemoteToolListing { name: string; params: string[] }
+/** A remote serve's whole tools/list answer for this token, with what its initialize said about itself. */
+export interface RemoteToolDefs {
+ tools: Tool[];
+ /** The host's initialize instructions, when it sent any. */
+ instructions?: string;
+ /** The host's initialize serverInfo. */
+ server?: { name?: string; version?: string };
+}
+
+/** Which client the host sees: the thin client's own name by default (its header asks for full rows). */
+export interface RemoteClientOptions extends CallRemoteToolOptions { clientName?: string }
+
/**
* #6696 B2: the tools a remote serve lists for this client's token (tools/list
* already filters by the token's scope and surface). Lets the thin client send
@@ -538,13 +551,21 @@ export interface RemoteToolListing { name: string; params: string[] }
* `callRemoteTool`: a cached token, one refresh on an HTTP 401.
*/
export async function listRemoteTools(config: GBrainConfig, opts: CallRemoteToolOptions = {}): Promise<RemoteToolListing[]> {
+ const { tools } = await listRemoteToolDefs(config, opts);
+ return tools.map((t) => ({ name: t.name, params: Object.keys((t.inputSchema as { properties?: Record<string, unknown> } | undefined)?.properties ?? {}) }));
+}
+
+/** The full tool definitions behind `listRemoteTools` (the stdio bridge lists them as-is). */
+export async function listRemoteToolDefs(config: GBrainConfig, opts: RemoteClientOptions = {}): Promise<RemoteToolDefs> {
const remote = requireRemoteMcp(config);
const { signal, cleanup } = buildAbortController(opts);
- const list = async (token: string): Promise<RemoteToolListing[]> => {
- const client = await buildClient(remote.mcp_url, token, signal);
+ const list = async (token: string): Promise<RemoteToolDefs> => {
+ const client = await buildClient(remote.mcp_url, token, signal, opts.clientName);
try {
const { tools } = await client.listTools(undefined, buildMcpRequestOptions(opts, signal));
- return tools.map((t) => ({ name: t.name, params: Object.keys((t.inputSchema as { properties?: Record<string, unknown> } | undefined)?.properties ?? {}) }));
+ const instructions = client.getInstructions();
+ const server = client.getServerVersion();
+ return { tools, ...(instructions ? { instructions } : {}), ...(server ? { server: { name: server.name, version: server.version } } : {}) };
} finally {
try { await client.close(); } catch { /* best-effort */ }
}
@@ -565,6 +586,89 @@ export async function listRemoteTools(config: GBrainConfig, opts: CallRemoteTool
}
}
+/** Options for `forwardRemoteToolCall`. */
+export interface ForwardRemoteToolOptions extends RemoteClientOptions {
+ /**
+ * Read after connecting, before anything is sent: a returned result answers
+ * the call instead and nothing reaches the host (the bridge refuses an
+ * audience a host cannot be shown to enforce).
+ */
+ admit?: (server: { name?: string; version?: string } | undefined) => CallToolResult | null;
+}
+
+/**
+ * The stdio bridge's call path: send one tool call to the remote serve and
+ * return its `CallToolResult` exactly as the host answered, `isError`
+ * envelopes and pending write receipts included (`callRemoteTool` turns those
+ * into thrown errors). Same token handling as `callRemoteTool`: a cached
+ * token, and one re-mint and resend only after an explicit HTTP 401, which
+ * refused the request; nothing else is ever replayed. A persistence mutation
+ * gets one `request_id` before the first send, kept across that resend.
+ * Only a transport failure throws: a RemoteMcpError carrying `request_id`
+ * (when one was sent) and `submission_status` (`unknown` once the request
+ * left, `not_sent` before).
+ */
+export async function forwardRemoteToolCall(
+ config: GBrainConfig,
+ toolName: string,
+ args: Record<string, unknown> = {},
+ opts: ForwardRemoteToolOptions = {},
+): Promise<CallToolResult> {
+ const remote = requireRemoteMcp(config);
+ const sent = isPersistenceIpcMutation(toolName) && args.request_id === undefined && args.dry_run !== true ? { ...args, request_id: randomUUID() } : args;
+ const requestId = isPersistenceIpcMutation(toolName) && isWriteRequestId(sent.request_id) ? sent.request_id : undefined;
+ let submitted = false;
+ const { signal, cleanup } = buildAbortController(opts);
+ const send = async (token: string): Promise<CallToolResult> => {
+ const client = await buildClient(remote.mcp_url, token, signal, opts.clientName);
+ try {
+ const refused = opts.admit?.(client.getServerVersion());
+ if (refused) return refused;
+ signal.throwIfAborted();
+ submitted = true;
+ return await client.callTool({ name: toolName, arguments: sent, ...(opts.meta ? { _meta: opts.meta } : {}) }, undefined, buildMcpRequestOptions(opts, signal)) as CallToolResult;
+ } finally {
+ try { await client.close(); } catch { /* best-effort */ }
+ }
+ };
+ try {
+ try {
+ return await send(await getAccessToken(config, false, signal));
+ } catch (e) {
+ signal.throwIfAborted();
+ if (!isStreamableHttpError(e) || e.code !== 401) throw e;
+ submitted = false; // The host refused this attempt; it was not accepted.
+ dropAccessToken(config);
+ let fresh: string;
+ try {
+ fresh = await getAccessToken(config, true, signal);
+ } catch (mintErr) {
+ if (mintErr instanceof RemoteMcpError && mintErr.reason === 'auth') {
+ throw new RemoteMcpError('auth_after_refresh', 'Auth failed after token refresh.', { mcp_url: remote.mcp_url, ...(mintErr.detail?.status ? { status: mintErr.detail.status } : {}) });
+ }
+ throw mintErr;
+ }
+ try {
+ return await send(fresh);
+ } catch (e2) {
+ signal.throwIfAborted();
+ if (!isStreamableHttpError(e2) || e2.code !== 401) throw e2;
+ submitted = false;
+ dropAccessToken(config);
+ throw new RemoteMcpError('auth_after_refresh', 'Auth failed after token refresh.', { mcp_url: remote.mcp_url, status: 401 });
+ }
+ }
+ } catch (e) {
+ const error = toRemoteMcpError(e, remote.mcp_url, signal);
+ throw new RemoteMcpError(error.reason, error.message, {
+ ...error.detail, ...(requestId ? { request_id: requestId } : {}),
+ submission_status: submitted ? 'unknown' : 'not_sent',
+ });
+ } finally {
+ cleanup();
+ }
+}
+
/**
* Extract the structured result from a successful tool-call response. The MCP
* spec says tool results are returned as `content: Array<{type, text|...}>`.
diff --git a/src/core/mcp-registration.ts b/src/core/mcp-registration.ts
index 3eafeca4e4..5d5aedaa7c 100644
--- a/src/core/mcp-registration.ts
+++ b/src/core/mcp-registration.ts
@@ -255,20 +255,24 @@ export const OAUTH_SECRET_NOTE =
'short-lived, scoped access tokens; revoke with `gbrain auth revoke-client`.';
/**
- * Paste-ready OpenClaw wiring block — HONEST v1. The scoped path this client
- * serves is a thin gbrain install on the OpenClaw machine (`gbrain init` in
- * mcp-only mode), which routes brain access through the OAuth client minted
- * for it; OpenClaw's own remote MCP client signs in with its own OAuth login. Deliberately NOT an mcpServers/
- * stdio JSON config: the stdio config in docs/mcp/OPENCLAW.md grants FULL
- * local DB access and does not use this client.
+ * Paste-ready OpenClaw wiring block, run on the OpenClaw machine (never the
+ * host that printed it, so it names no host path): a thin gbrain install for
+ * the OAuth client minted for it, then OpenClaw's own `mcp add` for that
+ * thin client's `gbrain serve`, which is a stdio bridge to the brain host
+ * with this client's grant (#8543). The launcher resolves on the OpenClaw
+ * machine. Deliberately NOT an mcpServers JSON entry: that key belongs to
+ * installed bundle manifests, and the bundle plugin already registers gbrain.
+ * A narrow home (`gbrainHome`) goes on both the init line and the entry.
*/
export function openclawThinClientBlock(opts: {
issuerUrl: string;
mcpUrl: string;
clientId: string;
clientSecret: string;
+ gbrainHome?: string;
}): string {
- const init = cmdString('gbrain', [
+ const home = opts.gbrainHome ? `GBRAIN_HOME=${shellQuote(opts.gbrainHome)}` : '';
+ const init = (home ? `${home} ` : '') + cmdString('gbrain', [
'init',
'--mcp-only',
'--issuer-url', opts.issuerUrl,
@@ -276,14 +280,20 @@ export function openclawThinClientBlock(opts: {
'--oauth-client-id', opts.clientId,
'--oauth-client-secret', opts.clientSecret,
]);
+ const add = 'openclaw mcp add gbrain --command "$(command -v gbrain)" --arg serve --arg --surface --arg starter --arg --advertise --arg verbs'
+ + (home ? ` --env ${home}` : '');
return [
- '# On the OpenClaw machine, install the gbrain CLI, then wire this scoped thin client:',
+ '# On the OpenClaw machine, install the gbrain CLI, then run:',
init,
+ add,
'',
- 'Your OpenClaw reaches the brain through the scoped gbrain CLI (search/query/recall/put);',
+ "On that thin client `gbrain serve` is a stdio bridge: OpenClaw's tool calls reach the brain host with this",
+ "client's grant and nothing more. If gbrain's OpenClaw bundle plugin is installed there, it already registers",
+ 'gbrain: run only the init line.',
+ ...(home ? [] : ['To keep this client apart from another gbrain on that machine, put the same GBRAIN_HOME=<dir> before',
+ 'the init line and add --env GBRAIN_HOME=<dir> to the mcp add line.']),
"OpenClaw's native remote MCP client (streamable HTTP + `openclaw mcp login`) is the other scoped",
- 'route, with its own OAuth login (docs/mcp/OPENCLAW.md); the stdio config in docs/mcp/OPENCLAW.md grants',
- 'FULL local DB access and does not use this client.',
+ 'route, with its own OAuth login (docs/mcp/OPENCLAW.md).',
].join('\n');
}
diff --git a/src/core/url-redact.ts b/src/core/url-redact.ts
index e010dad54a..2891b8e29d 100644
--- a/src/core/url-redact.ts
+++ b/src/core/url-redact.ts
@@ -63,6 +63,27 @@ export function redactUrlsInText(text: string): string {
);
}
+/**
+ * Strip every credential-bearing part (userinfo, query string, fragment) from
+ * URLs of any scheme embedded in free text, keeping scheme, host, port and
+ * path: `demo://user:[email protected]/mcp?token=x#y` becomes
+ * `demo://host.example/mcp`. For bridge-built diagnostics, where any part of
+ * a remote URL past its path can carry a secret; host results never pass here.
+ */
+export function stripUrlSecrets(text: string): string {
+ return text.replace(/(\w[\w+.-]*:\/\/)([^\s/?#]*@)?([^\s/?#@]*)([^\s?#]*)(?:[?#]\S*)?/g, (_m, scheme: string, _user, host: string, path: string) => `${scheme}${host}${path}`);
+}
+
+/** `stripUrlSecrets` over every string inside a value (objects and arrays recursively); other values pass through. */
+export function stripUrlSecretsDeep<T>(value: T): T {
+ if (typeof value === 'string') return stripUrlSecrets(value) as unknown as T;
+ if (Array.isArray(value)) return value.map(stripUrlSecretsDeep) as unknown as T;
+ if (value && typeof value === 'object') {
+ return Object.fromEntries(Object.entries(value as Record<string, unknown>).map(([k, v]) => [k, stripUrlSecretsDeep(v)])) as T;
+ }
+ return value;
+}
+
/**
* Recursively redact any postgresql:// or postgres:// URLs found inside an
* arbitrary value (string, object, array). Useful when the caller is about
diff --git a/src/mcp/remote-bridge-args.ts b/src/mcp/remote-bridge-args.ts
new file mode 100644
index 0000000000..448689f4ac
--- /dev/null
+++ b/src/mcp/remote-bridge-args.ts
@@ -0,0 +1,108 @@
+/**
+ * `gbrain serve` on a thin client: which argument lists start the stdio
+ * bridge (bare, or with gbrain's own registration flags), and the refusal for
+ * every other form. Engine-free and SDK-free, so the CLI routing step can load
+ * it before deciding. A refused invocation's fix keeps its flags (an
+ * allowlisted name, and its value only when it has a safe shape), so
+ * `serve --http --port 3131` is never "fixed" into a bare `serve`, which on
+ * a thin client is the bridge.
+ */
+import { OperationError, opError } from '../core/ops/contract.ts';
+import { isMcpSurface, type McpSurface } from './surface.ts';
+
+export type BridgeServeArgs =
+ | { bridge: true; surface: McpSurface | null; advertise: McpSurface | null; sourceGuard: boolean }
+ | { bridge: false; refused: string[] };
+
+const SURFACE_ORDER: readonly McpSurface[] = ['verbs', 'starter', 'full'];
+/** Serve flags that take a value, with the shape a value must have to be kept in a fix (null: never kept). */
+const VALUE_FLAGS: Record<string, RegExp | null> = {
+ '--surface': /^(verbs|starter|full)$/, '--advertise': /^(verbs|starter|full)$/, '--access': /^(full|read-only)$/,
+ '--port': /^\d{1,5}$/, '--bind': /^[A-Za-z0-9.:[\]-]{1,64}$/, '--token-ttl': /^\d{1,9}$/, '--stdio-idle-timeout': /^\d{1,9}$/,
+ '--stdio-member': /^[a-z0-9][a-z0-9-]{0,63}$/, '--public-url': /^https?:\/\/[A-Za-z0-9.-]+(:\d{1,5})?\/?$/, '--takes-holders': null, '--scopes': null,
+};
+const BOOLEAN_FLAGS = new Set(['--http', '--source-guard', '--fail-fast', '--cli-socket', '--enable-dcr', '--enable-dcr-insecure', '--log-full-params', '--suppress-bootstrap-token', '--print-admin-token']);
+const HTTP_FLAGS = new Set(['--http', '--port', '--bind', '--public-url', '--token-ttl', '--enable-dcr', '--enable-dcr-insecure', '--log-full-params', '--suppress-bootstrap-token', '--print-admin-token', '--scopes']);
+const BRIDGE_NOTE = 'Bare `gbrain serve` on this thin client is the stdio bridge to that brain (it accepts --surface, --advertise and --source-guard).';
+
+const flagName = (a: string): string => (a.startsWith('--') && a.includes('=') ? a.slice(0, a.indexOf('=')) : a);
+
+function badValue(flag: string, raw: string | undefined): OperationError {
+ const got = raw === undefined || raw.startsWith('--') ? 'no value' : `"${raw}"`;
+ return opError('invalid_params', `gbrain serve ${flag} takes verbs, starter or full (got ${got}).`,
+ `Edit the ${flag} value in this harness entry's args to verbs, starter or full, then start a new session.`, {
+ fix: { argv: ['gbrain', 'serve', flag, 'starter'], consent: [], actor: 'user', requires_exclusive: false,
+ why: `On a thin client ${flag} narrows the stdio bridge's tool list; its value is one of verbs, starter or full.` },
+ });
+}
+
+/**
+ * Read a thin-client serve argument list. Bare, or only `--surface <s>`,
+ * `--advertise <s>` (space or `=` form) and `--source-guard`: the bridge.
+ * Any other argument: refused, with the flags it named. A bad surface value
+ * throws `invalid_params` (it is not a host-only form, so "run it on the
+ * brain host" would mislead). A repeated flag takes the narrowest value, as
+ * local serve does.
+ */
+export function parseBridgeServeArgs(args: string[]): BridgeServeArgs {
+ const narrowing: { '--surface': McpSurface | null; '--advertise': McpSurface | null } = { '--surface': null, '--advertise': null };
+ let sourceGuard = false;
+ const refused: string[] = [];
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i];
+ const flag = flagName(a);
+ if (flag === '--surface' || flag === '--advertise') {
+ const raw = a !== flag ? a.slice(flag.length + 1) : args[++i];
+ if (raw === undefined || !isMcpSurface(raw)) throw badValue(flag, raw);
+ const prev = narrowing[flag];
+ narrowing[flag] = prev && SURFACE_ORDER.indexOf(prev) < SURFACE_ORDER.indexOf(raw) ? prev : raw;
+ continue;
+ }
+ if (a === '--source-guard') { sourceGuard = true; continue; }
+ refused.push(a);
+ if (flag in VALUE_FLAGS && a === flag && args[i + 1] !== undefined && !args[i + 1].startsWith('--')) refused.push(args[++i]);
+ }
+ return refused.length ? { bridge: false, refused } : { bridge: true, surface: narrowing['--surface'], advertise: narrowing['--advertise'], sourceGuard };
+}
+
+/** The refused flags as fix argv: known names only, values only when their shape is safe. */
+function keptFlags(refused: string[]): string[] {
+ const out: string[] = [];
+ for (let i = 0; i < refused.length; i++) {
+ const a = refused[i];
+ const flag = flagName(a);
+ if (BOOLEAN_FLAGS.has(flag)) { out.push(flag); continue; }
+ if (!(flag in VALUE_FLAGS)) continue;
+ const value = a !== flag ? a.slice(flag.length + 1) : refused[i + 1] !== undefined && !refused[i + 1].startsWith('--') ? refused[++i] : undefined;
+ out.push(flag, value !== undefined && VALUE_FLAGS[flag]?.test(value) ? value : '<value>');
+ }
+ return out;
+}
+
+/** The refusal for a serve form a thin client cannot run: what it asked for decides the message and the fix. */
+export function serveThinClientRefusal(refused: string[], mcpUrl: string): OperationError {
+ const kept = keptFlags(refused);
+ const names = new Set(kept.filter(a => a.startsWith('--')));
+ const shown = ['gbrain', 'serve', ...kept].join(' ');
+ if ([...names].some(n => HTTP_FLAGS.has(n))) {
+ return opError('requires_local_engine', `\`${shown}\` is not routable (thin-client of ${mcpUrl}): it serves a brain over HTTP, so it runs on the brain host.`,
+ `Run it on the brain host. ${BRIDGE_NOTE}`, {
+ why: 'HTTP serving hosts the brain database, which lives on the brain host; a thin client has none to serve.',
+ fix: { argv: ['gbrain', 'serve', ...kept], consent: [], actor: 'host_admin', requires_exclusive: false, why: 'HTTP serving runs where the brain database lives.' },
+ });
+ }
+ if (names.has('--access')) {
+ return opError('requires_local_engine', `\`${shown}\` is not routable (thin-client of ${mcpUrl}): it asks this bridge to enforce a restriction, and a thin client cannot enforce one locally.`,
+ `Give this harness its own narrow client instead: on the brain host, register an OAuth client with only the scopes it needs (read, for a read-only harness), then run gbrain init --mcp-only with it under a separate GBRAIN_HOME and point the harness entry there (docs/guides/hosted-harness-access.md). ${BRIDGE_NOTE}`, {
+ why: 'The brain host enforces what each client may do; a filter in this process would be advice, not a boundary.',
+ fix: { argv: ['gbrain', 'auth', 'register-client', '<name>', '--grant-types', 'client_credentials', '--scopes', 'read'], consent: [], actor: 'host_admin', requires_exclusive: false,
+ why: 'A read-only client row on the brain host is the restriction; this machine then uses it from its own GBRAIN_HOME.',
+ inputs: [{ name: 'name', how: 'A name for the harness this client is for.' }] },
+ });
+ }
+ return opError('requires_local_engine', `\`${shown}\` is not routable (thin-client of ${mcpUrl}); run it on the brain host.`,
+ `Run it on the brain host. ${BRIDGE_NOTE}`, {
+ why: 'These serve flags act on a local brain database, and a thin client has none.',
+ fix: { argv: ['gbrain', 'serve', ...kept], consent: [], actor: 'host_admin', requires_exclusive: false, why: 'The brain database lives on the brain host; this machine only forwards MCP calls.' },
+ });
+}
diff --git a/src/mcp/remote-bridge-errors.ts b/src/mcp/remote-bridge-errors.ts
new file mode 100644
index 0000000000..d30e20b060
--- /dev/null
+++ b/src/mcp/remote-bridge-errors.ts
@@ -0,0 +1,209 @@
+/**
+ * What the thin-client stdio bridge (remote-bridge.ts) says when it cannot
+ * relay: transport failures on `tools/call` become one v1 `isError`
+ * envelope, and on `tools/list` a JSON-RPC error whose `data` is the same
+ * envelope. Host results never pass through here; they are relayed
+ * byte-identical. Rules every builder keeps:
+ * - a per-reason fix (exhaustive over RemoteMcpErrorReason) that never names
+ * `gbrain remote doctor` (it needs admin scope) and never suggests adding
+ * a scope to this client;
+ * - a mutation keeps its write identity (`request_id`, `submission_status`)
+ * and gets the reconciliation it allows before any replay;
+ * - every string is stripped of URL userinfo, query and fragment.
+ */
+import { randomUUID } from 'node:crypto';
+import { chmodSync, mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
+import { buildEnvelope, toolErrorResult, type Action, type RenderContext, type ToolResultShape } from '../core/agent-output.ts';
+import type { OperationMeta } from '../core/ops/contract.ts';
+import { isPersistenceIpcMutation } from '../core/persistence/ipc.ts';
+import type { RemoteMcpError } from '../core/remote-mcp-error.ts';
+import { stripUrlSecrets, stripUrlSecretsDeep } from '../core/url-redact.ts';
+import { VERSION } from '../version.ts';
+
+export const BRIDGE_LOG_PREFIX = '[gbrain-bridge]';
+const DOCS = 'docs/architecture/thin-client.md#stdio-bridge';
+const DOCTOR: string[] = ['gbrain', 'doctor', '--json'];
+
+/** Bounded retry for a read or an unsent call: at most this many tries, this far apart. */
+export const BRIDGE_RETRY = { tries: 3, delay_s: 2 } as const;
+
+/** An endpoint as a label: origin and path, never userinfo, query or fragment. */
+export function endpointLabel(url: string): string {
+ try {
+ const u = new URL(url);
+ return `${u.protocol}//${u.host}${u.pathname}`;
+ } catch {
+ return stripUrlSecrets(url);
+ }
+}
+
+interface ReasonFix { code: string; why: string; suggestion: string; fix?: Action; retryable: boolean; recovery: string }
+
+const action = (a: Omit<Action, 'consent' | 'requires_exclusive'>): Action => ({ consent: [], requires_exclusive: false, ...a });
+
+/** The per-reason row: what failed, what to do about it, and whether a retry may help. */
+function reasonFix(e: RemoteMcpError, opts: { clientId?: string; timeoutMs: number; read: boolean }): ReasonFix {
+ const doctor = (why: string) => action({ argv: DOCTOR, actor: 'user', why });
+ const retry = `Retry up to ${BRIDGE_RETRY.tries} times, ${BRIDGE_RETRY.delay_s} s apart; if it still fails, run the fix.`;
+ switch (e.reason) {
+ case 'config':
+ return { code: 'config_error', retryable: false, recovery: 'Nothing was sent. Fix the thin-client configuration, then start a new session.',
+ why: 'This thin client has no usable remote credential (no remote_mcp config, or no client secret).',
+ suggestion: 'Run gbrain init --mcp-only on this machine with the OAuth client the brain host issued, or set GBRAIN_REMOTE_CLIENT_SECRET in the env of this harness entry.',
+ fix: action({ argv: ['gbrain', 'init', '--mcp-only'], actor: 'user', why: 'Writes the remote brain address and its OAuth client on this machine.' }) };
+ case 'discovery':
+ case 'token':
+ return { code: 'unavailable', retryable: true, recovery: retry,
+ why: `The brain host's OAuth ${e.reason === 'discovery' ? 'discovery' : '/token'} endpoint did not answer usefully.`,
+ suggestion: 'Check that the brain host is up and its address is right; gbrain doctor --json on this machine probes it without needing admin scope.',
+ fix: doctor('Read-only: probes the remote brain address, OAuth discovery and token mint from this machine.') };
+ case 'rate_limited': {
+ const wait = e.detail?.retry_after_s;
+ return { code: 'rate_limited', retryable: true,
+ recovery: `Wait ${wait !== undefined ? `${wait} s` : 'a few minutes'}, then retry the same call once.`,
+ why: `The brain host's OAuth /token mint budget is spent (HTTP 429); it clears by itself${wait !== undefined ? ` in ${wait} s` : ''}.`,
+ suggestion: 'Wait, then retry the same call. If this repeats, the host operator can raise GBRAIN_OAUTH_TOKEN_RATE_LIMIT_MAX.',
+ fix: action({ argv: DOCTOR, actor: 'provider', why: 'After the wait, doctor confirms the token mint works again.', verify: { argv: DOCTOR } }) };
+ }
+ case 'auth':
+ case 'auth_after_refresh': {
+ const client = opts.clientId ? `OAuth client ${opts.clientId}` : "this thin client's OAuth client";
+ return { code: 'invalid_client', retryable: false, recovery: 'Retrying will not help until the host owner acts.',
+ why: `The brain host rejected ${client}: it was revoked, its secret changed, or it expired.`,
+ suggestion: `Ask the brain host's owner to check ${client} and, if it was revoked, issue a replacement with the same scopes it had; then run gbrain init --mcp-only here with the new credential.`,
+ fix: action({ argv: ['gbrain', 'auth', 'clients'], actor: 'host_admin', why: `Read-only, on the brain host: lists its OAuth clients, so the owner can see whether ${client} is still active.`,
+ user_message: `The gbrain brain host no longer accepts ${client}. Can you ask the host's owner to check it and, if it was revoked, register a replacement with the same scopes, then run gbrain init --mcp-only on this machine with it?` }) };
+ }
+ case 'network': {
+ if (e.detail?.kind === 'aborted') {
+ return { code: 'cancelled', retryable: false, recovery: 'The caller cancelled this call; nothing to repair.', why: 'The call was cancelled before the host answered.', suggestion: 'Nothing to do; send the call again if it is still wanted.' };
+ }
+ if (e.detail?.kind === 'timeout') {
+ const next = Math.ceil((opts.timeoutMs * 2) / 1000);
+ return { code: 'timeout', retryable: opts.read,
+ recovery: opts.read ? 'Retry once; a slow call can finish on a second try.' : 'Do not resend blindly: reconcile the write first (see fix).',
+ why: `The brain host did not answer within the bridge's ${Math.round(opts.timeoutMs / 1000)} s call timeout.`,
+ suggestion: `For slow calls such as think, raise the bridge timeout: add --timeout=${next}s to this harness entry's args (gbrain --timeout=${next}s serve).`,
+ fix: action({ argv: ['gbrain', `--timeout=${next}s`, 'serve'], actor: 'user', why: 'The call timeout is a start flag of this bridge; change it in the harness entry and start a new session.' }) };
+ }
+ return { code: 'unavailable', retryable: true, recovery: retry,
+ why: `The brain host could not be reached${e.detail?.status ? ` (HTTP ${e.detail.status})` : ''}.`,
+ suggestion: 'Check that the brain host is up and reachable from this machine; gbrain doctor --json probes it without needing admin scope.',
+ fix: doctor('Read-only: probes the remote brain address, OAuth discovery and token mint from this machine.') };
+ }
+ case 'parse':
+ case 'tool_error':
+ return { code: 'internal_error', retryable: false, recovery: 'Report it; retrying the same exchange gives the same answer.',
+ why: 'The brain host answered with something this bridge could not read.', suggestion: 'Report it with the gbrain versions of this machine and the brain host.' };
+ default: {
+ const unreachable: never = e.reason;
+ return unreachable;
+ }
+ }
+}
+
+/** What a lost acknowledgment allows before any replay, by what the operation is. */
+function writeIdentity(e: RemoteMcpError, name: string, op: OperationMeta | undefined): Partial<ReasonFix> & { extra: Record<string, unknown> } | null {
+ const status = e.detail?.submission_status;
+ const mutating = op ? op.mutating === true : true;
+ if (!mutating || !status) return null;
+ const requestId = e.detail?.request_id;
+ const extra: Record<string, unknown> = { submission_status: status, ...(requestId ? { request_id: requestId } : {}) };
+ if (status === 'not_sent') return { extra: { ...extra, side_effects: 'none' }, retryable: true, recovery: 'Nothing reached the brain host, so resending the same call is safe.' };
+ if (requestId && isPersistenceIpcMutation(name)) {
+ return { code: 'write_outcome_unknown', retryable: false, extra: { ...extra, detail: 'delivery_unknown' },
+ why: `${name} reached the brain host, but its answer was lost, so whether the write was accepted is unknown.`,
+ recovery: `Retry the same call with the same request_id (${requestId}), or check get_write_request first; do not generate a new ID.`,
+ fix: action({ mcp: { tool: 'get_write_request', arguments: { request_id: requestId } }, argv: ['gbrain', 'write-request', '--', requestId], actor: 'agent',
+ why: 'Read-only: the receipt says whether the write committed; a resend with the same request_id returns that receipt instead of writing twice.' }) };
+ }
+ if (op && op.idempotent !== false) {
+ return { extra, retryable: true, recovery: `${name} is idempotent, so resending the same call once gives one effect.` };
+ }
+ if (name.startsWith('submit_')) {
+ return { code: 'write_outcome_unknown', retryable: false, extra,
+ why: `${name} reached the brain host, but its answer was lost, so whether the job was queued is unknown.`,
+ recovery: 'Check list_jobs for the job before submitting it again; a resend can queue it twice.',
+ fix: action({ mcp: { tool: 'list_jobs', arguments: {} }, argv: ['gbrain', 'jobs', 'list'], actor: 'agent', why: 'Read-only: shows whether the job was queued.' }) };
+ }
+ return { code: 'write_outcome_unknown', retryable: false, extra,
+ why: `${name} reached the brain host, but its answer was lost${op ? '' : ' (this gbrain does not know that tool, so its effects are unknown)'}; whether it took effect is unknown.`,
+ recovery: 'Do not resend: ask the brain host owner whether it took effect first.',
+ fix: action({ argv: DOCTOR, actor: 'host_admin', why: 'The brain host can tell whether the call took effect; this client cannot.',
+ user_message: `A ${name} call to the gbrain brain host lost its answer, so it is unknown whether it took effect. Can you check on the brain host before it is sent again?` }) };
+}
+
+export interface BridgeErrorContext { render: RenderContext; mcpUrl: string; clientId?: string; timeoutMs: number }
+
+function envelope(e: RemoteMcpError, row: ReasonFix, extra: Record<string, unknown>, ctx: BridgeErrorContext, message: string): Record<string, unknown> {
+ const env = buildEnvelope({ error: row.code, code: row.code, reason: e.reason, message, why: row.why, suggestion: row.suggestion, ...(row.fix ? { fix: row.fix } : {}),
+ docs: DOCS, retryable: row.retryable }, ctx.render);
+ return stripUrlSecretsDeep({ ...env, ...extra, recovery: row.recovery, mcp_url: endpointLabel(ctx.mcpUrl),
+ ...(e.detail?.status ? { status: e.detail.status } : {}), ...(e.detail?.retry_after_s !== undefined ? { retry_after_s: e.detail.retry_after_s } : {}) });
+}
+
+/** A `tools/call` transport failure as the v1 `isError` result the agent reads. */
+export function bridgeCallFailure(e: RemoteMcpError, name: string, op: OperationMeta | undefined, ctx: BridgeErrorContext): ToolResultShape {
+ const row = reasonFix(e, { clientId: ctx.clientId, timeoutMs: ctx.timeoutMs, read: op ? op.mutating !== true : false });
+ const identity = writeIdentity(e, name, op);
+ const merged: ReasonFix = identity ? { ...row, ...Object.fromEntries(Object.entries(identity).filter(([k]) => k !== 'extra')) } as ReasonFix : row;
+ const message = `gbrain bridge could not relay ${name} to ${endpointLabel(ctx.mcpUrl)}: ${e.message}`;
+ return toolErrorResult(envelope(e, merged, { stage: 'call', tool: name, ...(identity?.extra ?? {}) }, ctx, message) as never);
+}
+
+/** The stage a `tools/list` failure stopped at. */
+function listStage(e: RemoteMcpError): string {
+ switch (e.reason) {
+ case 'config': return 'config';
+ case 'discovery': return 'discovery';
+ case 'token': case 'rate_limited': case 'auth': case 'auth_after_refresh': return 'token';
+ case 'network': return 'connect';
+ case 'parse': case 'tool_error': return 'list';
+ default: { const unreachable: never = e.reason; return unreachable; }
+ }
+}
+
+/** A `tools/list` failure: a JSON-RPC error whose `data` is the v1 envelope plus its stage and bounded recovery, and the same line for stderr. */
+export function bridgeListFailure(e: RemoteMcpError, ctx: BridgeErrorContext): { error: McpError; line: string } {
+ const row = reasonFix(e, { clientId: ctx.clientId, timeoutMs: ctx.timeoutMs, read: true });
+ const stage = listStage(e);
+ const recovery = row.retryable ? `Retry tools/list up to ${BRIDGE_RETRY.tries} times, ${BRIDGE_RETRY.delay_s} s apart, then run the fix.` : row.recovery;
+ const data = envelope(e, { ...row, recovery }, { stage, side_effects: 'none' }, ctx, e.message);
+ const fix = (data.fix as { command?: string } | undefined)?.command;
+ const message = stripUrlSecrets(`gbrain bridge could not list tools from ${endpointLabel(ctx.mcpUrl)}: ${row.code} (${e.reason}); ${fix ? `fix: ${fix}` : row.suggestion}`);
+ return { error: new McpError(ErrorCode.InternalError, message, data), line: `${BRIDGE_LOG_PREFIX} code=${row.code} reason=${e.reason} stage=${stage} ${message}` };
+}
+
+/** Write a redacted compact trace to a 0600 file under the gbrain home and return its id and path (null when it cannot be written). */
+export function writeBridgeTrace(home: string, error: unknown, context: Record<string, unknown>): { id: string; path: string | null } {
+ const id = randomUUID().slice(0, 8);
+ const stack = error instanceof Error ? (error.stack ?? `${error.name}: ${error.message}`) : String(error);
+ try {
+ const dir = join(home, 'bridge-traces');
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
+ const path = join(dir, `${id}.txt`);
+ writeFileSync(path, stripUrlSecrets(`gbrain ${VERSION} bridge fault ${id}\n${JSON.stringify(context)}\n${stack.split('\n').slice(0, 20).join('\n')}\n`), { mode: 0o600 });
+ chmodSync(path, 0o600);
+ return { id, path };
+ } catch {
+ return { id, path: null };
+ }
+}
+
+/** A throw inside one `tools/call` handler that is not a transport failure: an `internal_error` envelope with a diagnostic id; the bridge keeps serving. */
+export function bridgeInternalFailure(name: string, stage: string, trace: { id: string; path: string | null }, render: RenderContext): ToolResultShape {
+ const env = buildEnvelope({ error: 'internal_error', code: 'internal_error', message: `gbrain bridge failed inside its own ${stage} step for ${name} (diagnostic ${trace.id}).`,
+ why: 'A fault in the bridge on this machine, not in the brain host; nothing was relayed after it.',
+ suggestion: `Report it with diagnostic id ${trace.id} and gbrain ${VERSION}${trace.path ? `; the trace is in ${trace.path}` : ''}.`,
+ docs: DOCS, retryable: false }, render);
+ return toolErrorResult(stripUrlSecretsDeep({ ...env, stage, tool: name, version: VERSION, diagnostic_id: trace.id, ...(trace.path ? { trace_file: trace.path } : {}),
+ recovery: 'Report it. A read can be retried; check a write with get_write_request or the host owner before sending it again.' }) as never);
+}
+
+/** A bridge-built refusal that never reached the host (surface, _meta shape, audience support). */
+export function bridgeRefusal(parts: { code: string; message: string; why: string; suggestion: string; fix?: Action }, render: RenderContext, extra: Record<string, unknown> = {}): ToolResultShape {
+ const env = buildEnvelope({ error: parts.code, code: parts.code, message: parts.message, why: parts.why, suggestion: parts.suggestion, ...(parts.fix ? { fix: parts.fix } : {}), docs: DOCS, retryable: false }, render);
+ return toolErrorResult(stripUrlSecretsDeep({ ...env, ...extra, side_effects: 'none' }) as never);
+}
diff --git a/src/mcp/remote-bridge.ts b/src/mcp/remote-bridge.ts
new file mode 100644
index 0000000000..5ddf39e6e4
--- /dev/null
+++ b/src/mcp/remote-bridge.ts
@@ -0,0 +1,360 @@
+/**
+ * Thin-client `gbrain serve`: a stdio MCP server that relays every request to
+ * the remote brain with this install's stored OAuth credential (#8543).
+ *
+ * Nothing here opens an engine or runs an operation handler, and no page text
+ * is stored on this machine. The host decides every call: `tools/list` is the
+ * host's own list for this client's token (narrowed, never widened, by
+ * `--surface` / `--advertise`), and `tools/call` returns the host's
+ * `CallToolResult` byte-identical, `isError` envelopes and pending write
+ * receipts included. Each relayed call reaches the host as an ordinary remote
+ * OAuth caller (`remote: true`); this process never builds an
+ * OperationContext, so nothing in it can act as the trusted local CLI.
+ *
+ * Bridge-built answers (a transport failure, a refusal that never left this
+ * machine, a bridge fault) are v1 envelopes from remote-bridge-errors.ts.
+ * stdout carries JSON-RPC only; the bridge's own lines go to stderr as
+ * `[gbrain-bridge]`. The lifecycle (signals, bounded EOF drain, MCP_STDIO=1,
+ * parent watchdog) is local serve's, from stdio-lifecycle.ts.
+ */
+import { randomUUID } from 'node:crypto';
+import { Server } from '@modelcontextprotocol/sdk/server/index.js';
+import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
+import { CallToolRequestSchema, ListToolsRequestSchema, type CallToolResult, type Tool } from '@modelcontextprotocol/sdk/types.js';
+import type { RenderContext } from '../core/agent-output.ts';
+import { configDir, type GBrainConfig } from '../core/config.ts';
+import { forwardRemoteToolCall, listRemoteToolDefs, RemoteMcpError, type RemoteToolDefs } from '../core/mcp-client.ts';
+import { OPERATION_MANIFEST } from '../core/operation-manifest.generated.ts';
+import type { Operation, OperationMeta } from '../core/ops/contract.ts';
+import { isPersistenceIpcMutation } from '../core/persistence/ipc.ts';
+import { VERSION } from '../version.ts';
+import { hiddenToolHint } from './hidden-tool-hint.ts';
+import { installInstructionsResolver, MCP_SERVER_DESCRIPTION, resolveMcpInstructions } from './instructions.ts';
+import { BRIDGE_LOG_PREFIX, bridgeCallFailure, bridgeInternalFailure, bridgeListFailure, bridgeRefusal, endpointLabel, writeBridgeTrace, type BridgeErrorContext } from './remote-bridge-errors.ts';
+import { installStdioShutdownTriggers, mcpStdioTransport, probeWatchdogAvailable, readLiveParentPid, resolveEofDrainMs, type StdioLifecycleDeps } from './stdio-lifecycle.ts';
+import { clampSurface, createStdioSurfaceState, isMcpSurface, resolveStdioSurface, sessionWidenAllowed, stdioToolListing, surfaceWiderThan, SURFACE_SOURCE_LABEL, type McpSurface } from './surface.ts';
+import { stripUrlSecrets } from '../core/url-redact.ts';
+
+/** The client name the host sees. Not the thin client's, so the host serves the lean rows and windowed pages any remote agent gets. */
+export const BRIDGE_CLIENT_NAME = 'gbrain-stdio-bridge';
+/** Per-call timeout (the CLI's think default); the SDK's own 60 s would cut think off. `gbrain --timeout=Ns serve` overrides it. */
+export const BRIDGE_DEFAULT_TIMEOUT_MS = 180_000;
+/** The first gbrain whose hosts enforce a request-level `_meta.on_behalf_of` and report it as `_meta.access.audience`. */
+export const AUDIENCE_MIN_HOST_VERSION = '0.60.543.0';
+
+export interface RemoteBridgeOptions {
+ surface?: McpSurface | null;
+ advertise?: McpSurface | null;
+ sourceGuard?: boolean;
+ timeoutMs?: number;
+ /** Test seams; production uses the process's stdio and the real remote calls. */
+ transport?: () => Transport;
+ lifecycle?: Partial<StdioLifecycleDeps>;
+ mcpStdio?: boolean;
+ eofDrainMs?: number;
+ installFatalHandlers?: boolean;
+ list?: typeof listRemoteToolDefs;
+ forward?: typeof forwardRemoteToolCall;
+}
+
+/** Whether a host's initialize `serverInfo` names a gbrain at least `min` (four-part versions). */
+export function hostAtLeast(server: { name?: string; version?: string } | undefined, min: string): boolean {
+ if (server?.name !== 'gbrain' || typeof server.version !== 'string') return false;
+ const have = server.version.split('.').map(Number);
+ const need = min.split('.').map(Number);
+ if (have.some(n => !Number.isInteger(n))) return false;
+ for (let i = 0; i < need.length; i++) {
+ if ((have[i] ?? 0) !== need[i]) return (have[i] ?? 0) > need[i];
+ }
+ return true;
+}
+
+const isPlainObject = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === 'object' && !Array.isArray(v);
+
+/** Start the bridge on this process's stdio. Resolves once the transport is connected; the lifecycle exits the process. */
+export async function startRemoteStdioBridge(cfg: GBrainConfig, opts: RemoteBridgeOptions = {}): Promise<void> {
+ const deps: StdioLifecycleDeps = {
+ stdin: process.stdin, signals: process, exit: (code?: number) => { process.exit(code); }, log: (msg: string) => console.error(msg),
+ getParentPid: readLiveParentPid, setInterval: (fn, ms) => setInterval(fn, ms), clearInterval: (h) => clearInterval(h as ReturnType<typeof setInterval>),
+ probeWatchdog: probeWatchdogAvailable, ...opts.lifecycle,
+ };
+ const log = (line: string) => deps.log(stripUrlSecrets(line));
+ const home = configDir();
+ const fatal = (stage: string, error: unknown) => {
+ const trace = writeBridgeTrace(home, error, { stage });
+ log(`${BRIDGE_LOG_PREFIX} code=internal_error version=${VERSION} stage=${stage} diagnostic=${trace.id}${trace.path ? ` trace=${trace.path}` : ''}`);
+ deps.exit(1);
+ };
+ if (opts.installFatalHandlers !== false) {
+ process.on('uncaughtException', (e) => fatal('uncaught_exception', e));
+ process.on('unhandledRejection', (e) => fatal('unhandled_rejection', e));
+ }
+ try {
+ await runBridge(cfg, opts, deps, log, home);
+ } catch (error) {
+ fatal('startup', error);
+ }
+}
+
+async function runBridge(cfg: GBrainConfig, opts: RemoteBridgeOptions, deps: StdioLifecycleDeps, log: (line: string) => void, home: string): Promise<void> {
+ const remote = cfg.remote_mcp;
+ const mcpUrl = remote?.mcp_url ?? '';
+ const timeoutMs = opts.timeoutMs ?? BRIDGE_DEFAULT_TIMEOUT_MS;
+ const list = opts.list ?? listRemoteToolDefs;
+ const forward = opts.forward ?? forwardRemoteToolCall;
+ const byName = new Map<string, OperationMeta>(OPERATION_MANIFEST.map(op => [op.name, op]));
+
+ const resolved = resolveStdioSurface(opts.surface ?? null, cfg);
+ if (resolved.invalidEnv !== undefined) {
+ log(`${BRIDGE_LOG_PREFIX} surface_env_invalid: ignoring GBRAIN_SURFACE="${resolved.invalidEnv}" (use verbs | starter | full); serving '${resolved.surface}' (source: ${SURFACE_SOURCE_LABEL[resolved.source]})`);
+ }
+ let server: Server | null = null;
+ const notify = () => { Promise.resolve(server?.sendToolListChanged()).catch(() => { /* best-effort */ }); };
+ const session = createStdioSurfaceState(OPERATION_MANIFEST, {
+ surface: clampSurface(resolved.surface), source: resolved.source, readOnly: false,
+ onWiden: ({ from, to, added }) => { log(`${BRIDGE_LOG_PREFIX} surface_widened from=${from} to=${to} op=request_tools added=${added.length}`); notify(); },
+ });
+ session.widenAllowed = await sessionWidenAllowed(null, cfg);
+ const advertise = opts.advertise ?? null;
+ const listing = stdioToolListing(async () => advertise, session, { sendToolListChanged: async () => notify() });
+ const listingNarrowed = () => session.allowedOps !== undefined || (advertise !== null && surfaceWiderThan(session.surface, advertise));
+ const hostNames = new Set<string>();
+ const revealedDefs = new Map<string, Tool>();
+ const warnedUnknown = new Set<string>();
+ const render: RenderContext = {
+ transport: 'stdio', surface: session.surface,
+ isCallable: (n) => hostNames.has(n) && (!session.allowedOps || session.allowedOps.has(n)),
+ preapproved: () => false,
+ };
+ const errCtx: BridgeErrorContext = { render, mcpUrl, clientId: remote?.oauth_client_id, timeoutMs };
+
+ log(`${BRIDGE_LOG_PREFIX} relaying stdio to ${endpointLabel(mcpUrl)} surface=${session.surface} (source: ${SURFACE_SOURCE_LABEL[resolved.source]})${advertise ? ` advertise=${advertise}` : ''}`);
+ if (opts.sourceGuard) {
+ log(`${BRIDGE_LOG_PREFIX} --source-guard: write routing follows this client's source grant on the brain host; the bridge enforces nothing locally`);
+ }
+
+ /** The host's tools for this token that this session may call, before the advertise listing. */
+ const callableTools = (defs: RemoteToolDefs): Tool[] => {
+ const all = [...defs.tools, ...[...revealedDefs.values()].filter(r => !defs.tools.some(t => t.name === r.name))];
+ hostNames.clear();
+ for (const t of all) hostNames.add(t.name);
+ const hostTools = all.filter(t => !byName.get(t.name)?.localOnly && !byName.get(t.name)?.cliOnly);
+ if (!listingNarrowed()) return hostTools;
+ const unknown = hostTools.filter(t => !byName.has(t.name) && !warnedUnknown.has(t.name)).map(t => t.name);
+ if (unknown.length) {
+ for (const n of unknown) warnedUnknown.add(n);
+ log(`${BRIDGE_LOG_PREFIX} not listing ${unknown.length} host tool(s) this gbrain does not know under a narrowed surface: ${unknown.join(', ')}`);
+ }
+ return hostTools.filter(t => byName.has(t.name) && (!session.allowedOps || session.allowedOps.has(t.name)));
+ };
+ const listedTools = async (defs: RemoteToolDefs): Promise<Tool[]> => {
+ const callable = callableTools(defs);
+ if (!listingNarrowed()) return callable;
+ const names = new Set((await listing.listed(callable.map(t => byName.get(t.name)!))).map(op => op.name));
+ return callable.filter(t => names.has(t.name));
+ };
+
+ server = new Server({ name: 'gbrain', version: VERSION, description: MCP_SERVER_DESCRIPTION },
+ { capabilities: { tools: { listChanged: true } }, instructions: resolveMcpInstructions(cfg, process.env) });
+ installInstructionsResolver(server, async () => {
+ const relay = `This MCP server is a gbrain stdio bridge: it relays every call to the remote brain at ${endpointLabel(mcpUrl)}, which decides what each call may read or write.`;
+ try {
+ const defs = await list(cfg, { clientName: BRIDGE_CLIENT_NAME, timeoutMs: Math.min(timeoutMs, 15_000) });
+ return `${defs.instructions ?? resolveMcpInstructions(cfg, process.env)}\n\n${relay}`;
+ } catch {
+ return `${resolveMcpInstructions(cfg, process.env)}\n\n${relay}`;
+ }
+ });
+
+ let inFlight = 0;
+ const writes = new Map<number, { tool: string; requestId?: string }>();
+ let nextCall = 0;
+ const track = async <T>(work: () => Promise<T>): Promise<T> => {
+ inFlight++;
+ try { return await work(); } finally { inFlight--; }
+ };
+
+ server.setRequestHandler(ListToolsRequestSchema, async () => track(async () => {
+ try {
+ return { tools: await listedTools(await list(cfg, { clientName: BRIDGE_CLIENT_NAME, timeoutMs })) };
+ } catch (e) {
+ if (!(e instanceof RemoteMcpError)) throw e;
+ const { error, line } = bridgeListFailure(e, errCtx);
+ log(line);
+ throw error;
+ }
+ }));
+
+ /** `request_tools {surface}` is this session's own widen (never forwarded, so nothing is written on the host). */
+ const widenSession = async (args: Record<string, unknown>): Promise<CallToolResult> => {
+ const requested = args.surface;
+ if (!isMcpSurface(requested)) {
+ return bridgeRefusal({ code: 'invalid_params', message: 'request_tools surface must be one of: verbs, starter, full.', why: 'The bridge widens its own session surface and knows only these three.',
+ suggestion: 'Call request_tools {"surface":"starter"} or {"surface":"full"}.' }, render) as CallToolResult;
+ }
+ const persistent = `For a lasting change, set GBRAIN_SURFACE=${requested} in the env of this harness's MCP server entry for gbrain (or edit its --surface) and start a new session.`;
+ session.widenAllowed = await sessionWidenAllowed(null, cfg);
+ if (!session.widenAllowed) {
+ return bridgeRefusal({ code: 'permission_denied', message: 'Session widening is off for this bridge (mcp.allow_session_widen is false), so request_tools cannot add tools to it.',
+ why: 'The owner of this machine turned stdio session widening off.', suggestion: persistent,
+ fix: { argv: ['gbrain', 'serve', '--surface', requested], consent: [], actor: 'user', requires_exclusive: false, why: `The bridge surface is a start flag of this harness entry. ${persistent}` } }, render) as CallToolResult;
+ }
+ const target = clampSurface(requested);
+ let change: Record<string, unknown>;
+ if (!surfaceWiderThan(target, session.surface)) {
+ change = { persisted: false, scope: 'session', surface: session.surface, widened: false,
+ note: target !== requested ? `GBRAIN_MCP_FORCE_SURFACE caps this bridge at '${target}', so this session stays at '${session.surface}'.` : `This session already serves '${session.surface}', which includes everything in '${requested}'.` };
+ } else {
+ const widened = session.widen(target);
+ render.surface = session.surface;
+ const added = new Set(widened.added);
+ const tools = callableTools(await list(cfg, { clientName: BRIDGE_CLIENT_NAME, timeoutMs })).filter(t => added.has(t.name));
+ change = { persisted: false, scope: 'session', surface: target, previous: widened.from, tools,
+ note: `This session now serves '${target}' (tools/list_changed was sent). Call the new tools by name now; their schemas are above. Only tools the brain host grants this client are added. ${persistent}` };
+ }
+ if (args.tools === undefined) return { content: [{ type: 'text', text: JSON.stringify(change, null, 2) }] };
+ const described = await relay('request_tools', { tools: args.tools }, undefined, undefined);
+ return withBody(described, body => ({ ...body, surface_change: change }));
+ };
+
+ /** Rewrite a relayed request_tools answer for this session: its catalog note, and which described tools this session can call now. */
+ const sessionRequestTools = (result: CallToolResult): CallToolResult => withBody(result, body => {
+ const out = { ...body };
+ if (Array.isArray(body.catalog)) {
+ out.note = 'Call request_tools {tools: ["name", ...]} for full schemas, or {surface: "starter"|"full"} to add those tools to this session (nothing is written).';
+ if (session.allowedOps && !session.widenAllowed) {
+ const allowed = session.allowedOps;
+ out.catalog = (body.catalog as Array<{ area: string; tools: Array<{ name: string }> }>).map(g => ({ ...g, tools: g.tools.filter(t => allowed.has(t.name)) })).filter(g => g.tools.length);
+ out.total_tools = (out.catalog as Array<{ tools: unknown[] }>).reduce((n, g) => n + g.tools.length, 0);
+ }
+ }
+ if (Array.isArray(body.tools)) {
+ const fresh = (body.tools as Tool[]).filter(t => typeof t?.name === 'string' && isPlainObject(t.inputSchema) && !hostNames.has(t.name) && !revealedDefs.has(t.name));
+ for (const t of fresh) revealedDefs.set(t.name, t);
+ if (fresh.length && !listingNarrowed()) notify();
+ }
+ if (Array.isArray(body.tools) && body.tools.length && listingNarrowed()) {
+ const names = (body.tools as Array<{ name?: unknown }>).map(t => t.name).filter((n): n is string => typeof n === 'string');
+ const reachable = names.filter(n => !session.allowedOps || session.allowedOps.has(n));
+ const outside = names.filter(n => !reachable.includes(n));
+ listing.reveal(reachable);
+ out.listed = outside.length === 0;
+ out.note = outside.length === 0
+ ? 'These tools are now in your tool list (tools/list_changed was sent); call them directly.'
+ : `${reachable.length ? `${reachable.map(n => `\`${n}\``).join(', ')} are now in your tool list (tools/list_changed was sent). ` : ''}${outside.map(n => `\`${n}\``).join(', ')} are outside this session's '${session.surface}' surface, so they are not listed and cannot be called yet: call request_tools {"surface":"full"} to add them to this session, then call them by name.`;
+ }
+ return out;
+ });
+
+ /** Forward one call and return the host's answer, or the bridge's envelope for a transport failure. */
+ const relay = async (name: string, args: Record<string, unknown>, meta: Record<string, unknown> | undefined, signal: AbortSignal | undefined): Promise<CallToolResult> => {
+ const op = byName.get(name);
+ const audience = meta?.on_behalf_of !== undefined;
+ const sent = isPersistenceIpcMutation(name) && args.request_id === undefined && args.dry_run !== true ? { ...args, request_id: randomUUID() } : args;
+ const id = nextCall++;
+ if (!op || op.mutating) writes.set(id, { tool: name, ...(typeof sent.request_id === 'string' ? { requestId: sent.request_id } : {}) });
+ let result: CallToolResult;
+ try {
+ result = await forward(cfg, name, sent, {
+ clientName: BRIDGE_CLIENT_NAME, timeoutMs, ...(signal ? { signal } : {}), ...(meta ? { meta } : {}),
+ ...(audience ? { admit: (host) => hostAtLeast(host, AUDIENCE_MIN_HOST_VERSION) ? null : audienceUnsupported(host?.version) } : {}),
+ });
+ } catch (e) {
+ if (!(e instanceof RemoteMcpError)) throw e;
+ return bridgeCallFailure(e, name, op, errCtx) as CallToolResult;
+ } finally {
+ writes.delete(id);
+ }
+ // A received answer is authoritative: a fault while reading it relays it unchanged.
+ try {
+ if (audience && op && !op.mutating && !result.isError && !Array.isArray((result._meta as { access?: { audience?: unknown } } | undefined)?.access?.audience)) {
+ return audienceUnsupported(undefined);
+ }
+ return name === 'request_tools' && !result.isError ? sessionRequestTools(result) : result;
+ } catch (error) {
+ const trace = writeBridgeTrace(home, error, { stage: 'read_result', tool: name });
+ log(`${BRIDGE_LOG_PREFIX} code=internal_error stage=read_result tool=${name} diagnostic=${trace.id}; relayed the host's answer unchanged`);
+ return result;
+ }
+ };
+
+ const audienceUnsupported = (hostVersion: string | undefined): CallToolResult => bridgeRefusal({
+ code: 'host_upgrade_required',
+ message: `This call names an audience (_meta.on_behalf_of), but the brain host${hostVersion ? ` (gbrain ${hostVersion})` : ''} cannot be shown to enforce one, so the bridge did not relay it.`,
+ why: `A host older than gbrain ${AUDIENCE_MIN_HOST_VERSION} ignores a request-level audience and would answer with the credential's whole view; the bridge never relays an audience-narrowed call it cannot verify.`,
+ suggestion: 'Upgrade gbrain on the brain host (gbrain upgrade there), or ask its operator to; until then, call without the audience only if every reader of the answer may see this credential\'s whole view.',
+ fix: { argv: ['gbrain', 'upgrade'], consent: [], actor: 'host_admin', requires_exclusive: false, why: 'The audience is enforced by the brain host; only an upgrade there adds it.' },
+ }, render, { client_version: VERSION, ...(hostVersion ? { host_version: hostVersion } : {}), min_host_version: AUDIENCE_MIN_HOST_VERSION }) as CallToolResult;
+
+ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => track(async () => {
+ const { name, arguments: rawArgs, _meta: meta } = request.params;
+ const args = (rawArgs ?? {}) as Record<string, unknown>;
+ const op = byName.get(name);
+ try {
+ if (op?.localOnly || op?.cliOnly) {
+ return bridgeRefusal({ code: 'unknown_tool', message: `${name} is not a tool this connection can call.`, why: `${name} runs only on the brain host itself, so no remote connection reaches it.`,
+ suggestion: 'Call request_tools for the tools this connection can call.' }, render) as CallToolResult;
+ }
+ if (session.allowedOps && !session.allowedOps.has(name)) {
+ const hint = hiddenToolHint(op as Operation | undefined, { transport: 'stdio', remote: true, surface: session.surface, allowedOps: session.allowedOps, readOnly: false }, session.widenAllowed);
+ return bridgeRefusal({ code: 'unknown_tool', message: `${name} is not in this session's '${session.surface}' tool surface.`,
+ why: hint ? 'The bridge was started with a narrower --surface (or GBRAIN_SURFACE) than the brain host grants.' : `${name} is not a tool this connection can call.`,
+ suggestion: hint?.suggestion ?? 'Call request_tools for the tools this connection can call.', ...(hint ? { fix: hint.fix } : {}) }, render) as CallToolResult;
+ }
+ if (meta !== undefined && !isPlainObject(meta)) {
+ return bridgeRefusal({ code: 'invalid_params', message: 'Request-level _meta must be a JSON object, so the bridge did not relay this call.',
+ why: 'An audience or session id rides in _meta beside arguments; a call is never relayed with its narrowing dropped.',
+ suggestion: 'Send _meta as an object beside arguments, for example {"name": "query", "arguments": {...}, "_meta": {"on_behalf_of": ["alice-example"], "session_id": "s-1"}}; never put on_behalf_of inside arguments.' }, render) as CallToolResult;
+ }
+ if (name === 'request_tools' && args.surface !== undefined) return await widenSession(args);
+ return await relay(name, args, meta as Record<string, unknown> | undefined, extra.signal);
+ } catch (error) {
+ if (error instanceof RemoteMcpError) return bridgeCallFailure(error, name, op, errCtx) as CallToolResult;
+ const trace = writeBridgeTrace(home, error, { stage: 'call', tool: name });
+ log(`${BRIDGE_LOG_PREFIX} code=internal_error stage=call tool=${name} diagnostic=${trace.id}${trace.path ? ` trace=${trace.path}` : ''}`);
+ return bridgeInternalFailure(name, 'call', trace, render) as CallToolResult;
+ }
+ }));
+
+ let shuttingDown = false;
+ let exitCode = 0;
+ const mcpStdio = opts.mcpStdio ?? (process.env.MCP_STDIO === '1');
+ // Under MCP_STDIO=1 stdin EOF is not a disconnect, and with no engine nothing else holds the event loop open.
+ const keepAlive = mcpStdio ? setInterval(() => {}, 1 << 30) : undefined;
+ const triggers = installStdioShutdownTriggers(deps, {
+ beginShutdown: (reason) => {
+ if (shuttingDown) return;
+ shuttingDown = true;
+ triggers.stopWatchdog();
+ if (keepAlive) clearInterval(keepAlive);
+ log(`${BRIDGE_LOG_PREFIX} exit (${reason})`);
+ const deadline = setTimeout(() => deps.exit(exitCode), 2_000);
+ deadline.unref?.();
+ void Promise.resolve(server?.close()).catch(() => { /* best-effort */ }).finally(() => { clearTimeout(deadline); deps.exit(exitCode); });
+ },
+ isShuttingDown: () => shuttingDown,
+ pendingRpcs: () => inFlight,
+ // A forwarded write may take the whole call timeout; the drain waits that long before it gives up on a receipt.
+ eofDrainMs: opts.eofDrainMs ?? resolveEofDrainMs(timeoutMs),
+ mcpStdio,
+ logPrefix: BRIDGE_LOG_PREFIX,
+ onDrainExpired: () => {
+ for (const w of writes.values()) {
+ exitCode = 1;
+ log(`${BRIDGE_LOG_PREFIX} code=write_outcome_unknown tool=${w.tool} submission_status=unknown${w.requestId ? ` request_id=${w.requestId} fix="gbrain write-request -- ${w.requestId}"` : ' fix="ask the brain host owner whether it took effect before resending"'}`);
+ }
+ },
+ });
+ server.onclose = () => triggers.drainThenShutdown('transport-close');
+ await server.connect(opts.transport ? opts.transport() : mcpStdioTransport());
+}
+
+/** Apply `edit` to a result's JSON body (content[0]); any other shape passes through unchanged. */
+function withBody(result: CallToolResult, edit: (body: Record<string, unknown>) => Record<string, unknown>): CallToolResult {
+ const first = result.content?.[0];
+ if (!first || first.type !== 'text') return result;
+ let body: unknown;
+ try { body = JSON.parse(first.text); } catch { return result; }
+ if (!isPlainObject(body)) return result;
+ return { ...result, content: [{ ...first, text: JSON.stringify(edit(body), null, 2) }, ...result.content.slice(1)] };
+}
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index f6f1fa4aad..b32f85b337 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -1,7 +1,5 @@
import { noteForwardProgress } from '../core/forward-progress.ts';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
-import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
-import type { Readable, Writable } from 'node:stream';
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import type { BrainEngine } from '../core/engine.ts';
import { OperationError, opError, type OperationMeta } from '../core/ops/contract.ts';
@@ -33,19 +31,9 @@ import { readOnlyServeSkipsResidentDuties } from '../core/direct-pool-profile.ts
import { hookSessionCwd } from '../core/session-cwd.ts';
import { stdioMemberIdentity } from '../core/access/caller.ts';
-/**
- * Largest JSON-RPC message the stdio server reads (the SDK default is 10 MiB,
- * and an oversized message closes the session). A page at the 24 MiB ceiling
- * travels JSON-escaped, and newlines and quotes double, so 64 MiB carries it
- * with room; the persistence journal caps a principal's outstanding intents at
- * the same 64 MiB.
- */
-export const MCP_STDIO_MAX_MESSAGE_BYTES = 64 * 1024 * 1024;
-
-/** The stdio transport `gbrain serve` connects, sized for ceiling-size page writes. */
-export function mcpStdioTransport(stdin: Readable = process.stdin, stdout: Writable = process.stdout): StdioServerTransport {
- return new StdioServerTransport(stdin, stdout, { maxBufferSize: MCP_STDIO_MAX_MESSAGE_BYTES });
-}
+// The sized stdio transport moved to the engine-free lifecycle module the thin-client bridge shares.
+export { MCP_STDIO_MAX_MESSAGE_BYTES, mcpStdioTransport } from './stdio-lifecycle.ts';
+import { MCP_STDIO_MAX_MESSAGE_BYTES, mcpStdioTransport } from './stdio-lifecycle.ts';
// initialize and tools/list read OPERATION_MANIFEST; the handler graph behind
// dispatch.ts (src/core/operations.ts, ~760 modules) loads with the deferred
diff --git a/src/mcp/stdio-lifecycle.ts b/src/mcp/stdio-lifecycle.ts
new file mode 100644
index 0000000000..67bcc950b7
--- /dev/null
+++ b/src/mcp/stdio-lifecycle.ts
@@ -0,0 +1,328 @@
+/**
+ * The engine-free part of a stdio MCP server's lifecycle, shared by local
+ * `gbrain serve` (src/commands/serve.ts installStdioLifecycle, which adds its
+ * engine hooks: idle sweep, facts drain, tickers, engine close) and the
+ * thin-client bridge (src/mcp/remote-bridge.ts, which has none):
+ * - SIGTERM / SIGINT / SIGHUP converge on one graceful shutdown;
+ * - stdin EOF drains in-flight RPCs, bounded, before it (#4409), and is
+ * ignored under MCP_STDIO=1, where a gateway closes its stdin half after
+ * the handshake (#870), and on a TTY;
+ * - the parent-pid watchdog notices a parent that died without closing
+ * stdin or signalling.
+ * This module imports no engine, dispatch or operation module, so the bridge
+ * can use it without loading a brain.
+ */
+import { spawnSync } from '../core/spawn.ts';
+import type { Readable, Writable } from 'node:stream';
+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
+
+/**
+ * Largest JSON-RPC message the stdio server reads (the SDK default is 10 MiB,
+ * and an oversized message closes the session). A page at the 24 MiB ceiling
+ * travels JSON-escaped, and newlines and quotes double, so 64 MiB carries it
+ * with room; the persistence journal caps a principal's outstanding intents at
+ * the same 64 MiB.
+ */
+export const MCP_STDIO_MAX_MESSAGE_BYTES = 64 * 1024 * 1024;
+
+/** The stdio transport `gbrain serve` connects, sized for ceiling-size page writes. */
+export function mcpStdioTransport(stdin: Readable = process.stdin, stdout: Writable = process.stdout): StdioServerTransport {
+ return new StdioServerTransport(stdin, stdout, { maxBufferSize: MCP_STDIO_MAX_MESSAGE_BYTES });
+}
+
+// How often the parent-process watchdog polls the live kernel parent PID
+// (via `readLiveParentPid`, NOT the cached `process.ppid` — see that
+// helper's comment). We don't receive a signal when our parent dies (the
+// kernel just re-parents us to init / launchd / a subreaper-PID), so
+// polling is the only reliable way to detect "parent went away without
+// closing stdin". 5s matches the cadence in the concurrent #591 PR;
+// faster polling has no benefit, slower would extend the lock-leak window.
+export const PARENT_WATCHDOG_INTERVAL_MS = 5_000;
+
+// #4409: stdin-EOF drain bound. Long enough for a real tool call (a query
+// with embedding + LLM expansion) to finish; short enough that a genuinely
+// wedged handler can't pin the PGLite lock forever after the parent left.
+export const DEFAULT_EOF_DRAIN_MS = 30_000;
+
+// Env resolution for the stdin-EOF drain bound. Lenient like
+// resolveBootTimeoutMs: a typo'd env var must not turn the data-loss fix
+// into a shutdown failure. 0 disables the drain (immediate exit).
+export function resolveEofDrainMs(defaultMs: number = DEFAULT_EOF_DRAIN_MS): number {
+ const raw = process.env.GBRAIN_SERVE_EOF_DRAIN_MS;
+ if (raw === undefined || raw.trim() === '') return defaultMs;
+ const n = Number(raw);
+ if (!Number.isFinite(n) || n < 0) {
+ console.error(
+ `[gbrain serve] ignoring invalid GBRAIN_SERVE_EOF_DRAIN_MS=${JSON.stringify(raw)} — using default ${defaultMs}ms`,
+ );
+ return defaultMs;
+ }
+ return Math.floor(n);
+}
+
+export interface StdioLifecycleDeps {
+ stdin: NodeJS.ReadableStream & { isTTY?: boolean };
+ signals: Pick<NodeJS.Process, 'on'>;
+ exit: (code?: number) => void;
+ log: (msg: string) => void;
+ getParentPid: () => number;
+ setInterval: (fn: () => void, ms: number) => unknown;
+ clearInterval: (handle: unknown) => void;
+ probeWatchdog: () => boolean;
+}
+
+export interface StdioShutdownTriggerOpts {
+ /** The idempotent graceful shutdown every trigger converges on. */
+ beginShutdown: (reason: string) => void;
+ isShuttingDown: () => boolean;
+ /** Live count of JSON-RPC requests whose handlers have not settled. */
+ pendingRpcs: () => number;
+ /** stdin-EOF drain bound in ms; 0 = immediate shutdown. */
+ eofDrainMs: number;
+ /** MCP_STDIO=1: stdin EOF is not a disconnect (#870). */
+ mcpStdio: boolean;
+ /** Called once when the drain bound expires with requests still in flight, before the shutdown. */
+ onDrainExpired?: () => void;
+ /** Prefix of this server's own stderr lines. */
+ logPrefix?: string;
+}
+
+/**
+ * Install the signal, stdin-EOF and parent-watchdog triggers. Returns the
+ * drain-then-shutdown entry point (for callers that start a shutdown on
+ * their own, such as a transport close) and a stop for the watchdog, which
+ * the shutdown calls first so it cannot fire a second one.
+ */
+export function installStdioShutdownTriggers(deps: StdioLifecycleDeps, o: StdioShutdownTriggerOpts): { drainThenShutdown: (reason: string) => void; stopWatchdog: () => void } {
+ let parentWatchdog: unknown = null;
+ const stopWatchdog = (): void => {
+ if (parentWatchdog === null) return;
+ deps.clearInterval(parentWatchdog);
+ parentWatchdog = null;
+ };
+
+ // Signal-based termination. SIGTERM: daemon ask. SIGINT: user Ctrl-C.
+ // SIGHUP: terminal disconnect / daemon-style "reload" channels — Aragorn
+ // observed real-world hosts (Claude Desktop on macOS, hermes-agent
+ // restart) send these instead of closing stdin. All three get the same
+ // graceful path; the idempotency guard absorbs duplicate signals.
+ deps.signals.on('SIGTERM', () => o.beginShutdown('SIGTERM'));
+ deps.signals.on('SIGINT', () => o.beginShutdown('SIGINT'));
+ deps.signals.on('SIGHUP', () => o.beginShutdown('SIGHUP'));
+
+ // Stdin EOF — the parent closes the pipe but the MCP SDK's
+ // StdioServerTransport only listens for 'data'/'error', not 'end' or
+ // 'close', so without these hooks the process keeps the engine (and its
+ // PGLite write lock) live indefinitely after the parent disconnects.
+ // 'end' fires on a clean EOF; 'close' fires when the underlying handle
+ // is destroyed (e.g. parent SIGKILL'd while pipe still open). Both
+ // converge on the same idempotent shutdown.
+ // Skip when stdin is a TTY: interactive `gbrain serve` use shouldn't
+ // terminate just because the user hasn't typed anything. Signal /
+ // watchdog paths still cover that case if needed.
+ // v0.34.1 (#870): when MCP_STDIO=1, the wrapping gateway pipes the
+ // JSON-RPC handshake then closes its stdin half. Treating that as a
+ // permanent disconnect kills the server before the first tool call.
+ // Signal handlers (SIGTERM/SIGINT/SIGHUP), transport.onclose, and the
+ // parent-process watchdog below still cover legitimate shutdown paths.
+ // #4409: a one-shot MCP client writes its frames and closes stdin
+ // immediately. Node delivers 'end' AFTER all 'data' events, and the SDK
+ // parses every received frame synchronously during 'data' (handler start
+ // is queued as a microtask) — so at EOF time requests can be in flight
+ // with no response written yet. Treating EOF as an immediate shutdown
+ // silently dropped those responses (the codex-plugin door went red on
+ // exactly this shape). Drain in-flight RPCs — bounded — before the
+ // graceful exit; idle servers still exit promptly (one timer tick).
+ // GBRAIN_SERVE_EOF_DRAIN_MS tunes the bound; 0 restores immediate exit.
+ let eofDrainStarted = false;
+ const drainThenShutdown = (reason: string): void => {
+ if (o.isShuttingDown() || eofDrainStarted) return;
+ eofDrainStarted = true;
+ void (async () => {
+ if (o.eofDrainMs > 0) {
+ // One macrotask so already-parsed requests' handlers (microtasks)
+ // start and increment the counter before the first check.
+ await new Promise<void>((r) => setTimeout(r, 0));
+ if (o.pendingRpcs() > 0) {
+ deps.log(
+ `GBrain MCP server: stdin EOF with ${o.pendingRpcs()} in-flight request(s) — draining before exit (bound ${o.eofDrainMs}ms; GBRAIN_SERVE_EOF_DRAIN_MS)`,
+ );
+ const deadlineAt = Date.now() + o.eofDrainMs;
+ while (o.pendingRpcs() > 0 && Date.now() < deadlineAt && !o.isShuttingDown()) {
+ await new Promise<void>((r) => setTimeout(r, 25));
+ }
+ if (o.pendingRpcs() > 0 && !o.isShuttingDown()) o.onDrainExpired?.();
+ }
+ // One extra macrotask: the SDK sends the response in a .then AFTER
+ // the handler resolves — let that stdout write get issued before
+ // the cleanup chain starts.
+ await new Promise<void>((r) => setTimeout(r, 0));
+ }
+ o.beginShutdown(reason);
+ })();
+ };
+ if (!deps.stdin.isTTY && !o.mcpStdio) {
+ deps.stdin.once('end', () => drainThenShutdown('stdin-end'));
+ deps.stdin.once('close', () => drainThenShutdown('stdin-close'));
+ }
+
+ // Parent-process watchdog. Some hosts (launchd, cron, certain MCP
+ // gateways) terminate without closing stdin and without sending a
+ // signal — the kernel just re-parents us to whichever ancestor is
+ // still alive (PID 1, or any closer subreaper such as launchd, systemd,
+ // tmux, or a parent shell with PR_SET_CHILD_SUBREAPER). Polling is the
+ // only portable way to notice; see `readLiveParentPid` for why we
+ // cannot rely on `process.ppid` (cached at process creation and never
+ // refreshed on re-parent in Node or Bun). On Windows the same class of
+ // orphan is WORSE in practice: MCP hosts typically launch the server
+ // through a `cmd.exe` wrapper (.bat/.cmd), and killing the wrapper
+ // does not kill the child — so without a watchdog the orphan holds the
+ // PGLite write lock until the machine reboots. `readLiveParentPid`
+ // handles the platform split internally (PPID-change on POSIX,
+ // parent-liveness on Windows); the comparison below works for both.
+ //
+ // We capture the initial parent PID once at install time and fire on
+ // ANY change, not just reparent-to-PID-1. The PR-#676 author's original
+ // `=== 1` check missed reparent-to-subreaper-PID-N, which is the actual
+ // observed behavior under launchd / systemd subreapers (codex review
+ // finding #3). A process legitimately started under PID 1 (e.g. a
+ // systemd service) skips the watchdog: there's no parent-death event
+ // to detect, and any reparent FROM 1 doesn't happen. `unref()` keeps
+ // the interval from blocking other exit paths.
+ //
+ // A one-shot startup probe (D2-revisited per codex finding #4) verifies
+ // that the underlying mechanism (`spawnSync('ps')`) actually works on
+ // this host. Stripped containers / busybox-without-procps environments
+ // would silently fall back to the cached `process.ppid` on every tick
+ // — the watchdog claims to be installed but never fires. When the probe
+ // fails, we skip installing the interval entirely and log loudly so the
+ // operator sees the degraded mode instead of a phantom watchdog.
+ // `> 1` (was `!== 1`): PID 1 is the documented legitimate-init-child
+ // skip; PID 0 is the new "parent already gone at install time" report
+ // from the Windows liveness reader — installing an interval that
+ // compares 0 to 0 forever would be a phantom watchdog, and stdin
+ // 'close' already covers a parent that died before we booted.
+ const initialParentPid = deps.getParentPid();
+ if (initialParentPid > 1) {
+ if (!deps.probeWatchdog()) {
+ deps.log(
+ `${o.logPrefix ?? '[gbrain serve]'} watchdog disabled: no parent-liveness mechanism (ps / signal-0 probe failed) — child will rely on stdin EOF / signals only`,
+ );
+ } else {
+ parentWatchdog = deps.setInterval(() => {
+ if (deps.getParentPid() !== initialParentPid) {
+ o.beginShutdown('parent-died');
+ }
+ }, PARENT_WATCHDOG_INTERVAL_MS);
+ (parentWatchdog as { unref?: () => void } | null)?.unref?.();
+ }
+ }
+
+ return { drainThenShutdown, stopWatchdog };
+}
+
+/**
+ * Signal-0 process-liveness probe (`process.kill(pid, 0)` — existence
+ * check only, no signal delivered; OpenProcess under the hood on
+ * Windows). EPERM means the PID exists but we lack rights to signal it
+ * — that is still "alive" for watchdog purposes. Exported for direct
+ * unit testing of the Windows watchdog path.
+ */
+export function isPidAlive(pid: number): boolean {
+ if (!Number.isInteger(pid) || pid <= 0) return false;
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (err) {
+ return (err as NodeJS.ErrnoException).code === 'EPERM';
+ }
+}
+
+/**
+ * Resolve the live parent PID from the kernel (not the cached startup
+ * value). Both Node and Bun expose `process.ppid` as a property captured
+ * at process creation, so it does NOT update when the kernel re-parents
+ * us to a new ancestor after the original parent dies — which is the
+ * exact event the watchdog needs to detect. Empirical evidence on
+ * macOS / Bun 1.3.12: `process.ppid` stays at the original parent ID
+ * indefinitely while `ps -o ppid= -p $$` reports the new parent within
+ * one tick.
+ *
+ * Windows has no `ps` — the original ps-only implementation made the
+ * startup probe fail on every Windows host, so the watchdog was always
+ * disabled and an orphaned serve (e.g. its cmd.exe .bat wrapper killed
+ * by the MCP host without closing stdin) held the PGLite write lock
+ * indefinitely. But Windows also never re-parents orphans, so the
+ * cached `process.ppid` stays correct for the process's lifetime and
+ * the question inverts from "did the live PPID change?" to "is the
+ * original parent still alive?" — answered in-process via signal-0,
+ * no external binary needed. Parent dead → report 0 (kernel PID 0 is
+ * the System Idle Process, never our parent), which differs from
+ * `initialParentPid` and fires the watchdog. Known degraded mode:
+ * Windows recycles PIDs aggressively, so a reused parent PID can mask
+ * a death — stdin EOF / signals remain the primary shutdown channels
+ * and the watchdog stays the backstop, same posture as POSIX.
+ *
+ * Cost: ~10ms per ps spawn on POSIX, effectively free on Windows.
+ * Called every 5s (PARENT_WATCHDOG_INTERVAL_MS), so amortized < 0.5%
+ * CPU. Falls back to `process.ppid` if `ps` fails (best-effort safety
+ * net for stripped-down containers, etc.); the startup probe at
+ * watchdog-install time loud-logs and skips the interval entirely when
+ * no mechanism is available, so a per-tick fallback is a redundant
+ * safety net rather than a primary mechanism.
+ *
+ * `platform` is a test seam (defaults to the real platform) so CI on
+ * any OS can exercise both branches — signal-0 works everywhere.
+ */
+export function readLiveParentPid(platform: NodeJS.Platform = process.platform): number {
+ if (platform === 'win32') {
+ return isPidAlive(process.ppid) ? process.ppid : 0;
+ }
+ try {
+ const r = spawnSync('ps', ['-o', 'ppid=', '-p', String(process.pid)], {
+ encoding: 'utf8',
+ timeout: 1000,
+ });
+ if (r.status === 0 && typeof r.stdout === 'string') {
+ const n = parseInt(r.stdout.trim(), 10);
+ if (Number.isInteger(n) && n >= 0) return n;
+ }
+ } catch {
+ /* fall through */
+ }
+ return process.ppid;
+}
+
+/**
+ * One-shot probe at watchdog-install time to confirm the platform's
+ * parent-liveness mechanism actually works on this host. POSIX: true
+ * iff `spawnSync('ps','-o','ppid=','-p',PID)` exits 0 with a parseable
+ * integer. Windows: true iff signal-0 succeeds against our own PID
+ * (always alive — verifies the mechanism, not the parent). When it
+ * returns false, the caller skips installing the watchdog and emits a
+ * loud stderr line — the operator sees "watchdog disabled" instead of
+ * an installed-but-never-fires phantom.
+ *
+ * Why a separate probe rather than relying on the per-tick fallback in
+ * `readLiveParentPid`: the per-tick fallback returns the cached
+ * `process.ppid` silently, so the watchdog runs every 5s, compares
+ * cached PPID to itself, never detects a change, and never fires —
+ * while still claiming to be active. The probe surfaces the gap once
+ * at install time and lets the caller short-circuit cleanly.
+ */
+export function probeWatchdogAvailable(platform: NodeJS.Platform = process.platform): boolean {
+ if (platform === 'win32') {
+ return isPidAlive(process.pid);
+ }
+ try {
+ const r = spawnSync('ps', ['-o', 'ppid=', '-p', String(process.pid)], {
+ encoding: 'utf8',
+ timeout: 1000,
+ });
+ if (r.status !== 0 || typeof r.stdout !== 'string') return false;
+ const n = parseInt(r.stdout.trim(), 10);
+ return Number.isInteger(n) && n >= 0;
+ } catch {
+ return false;
+ }
+}
diff --git a/test/cli-dispatch-thin-client.test.ts b/test/cli-dispatch-thin-client.test.ts
index 226c0d5294..acb85f3136 100644
--- a/test/cli-dispatch-thin-client.test.ts
+++ b/test/cli-dispatch-thin-client.test.ts
@@ -97,7 +97,7 @@ describe('thin-client dispatch guard refuses DB-bound commands', () => {
['repair-jsonb', '--dry-run'],
['orphans'],
['integrity', 'check'],
- ['serve'],
+ ['serve', '--http'],
// v0.32 audit REFUSE additions (no MCP route, or localOnly ops) and the
// v0.31.1-era refusals not covered above.
['pages', 'purge-deleted'],
@@ -157,6 +157,14 @@ describe('thin-client dispatch guard does NOT refuse safe commands', () => {
// Commands that are still useful in thin-client mode (init, auth, version,
// help) MUST NOT be refused. We assert the canonical thin-client error
// does NOT appear.
+ test('`gbrain --brain <id> serve` refuses instead of bridging to the configured remote', async () => {
+ seedThinClientConfig(tmp);
+ const r = await run(['--brain', 'other-brain', 'serve']);
+ expect(r.exitCode).toBe(2);
+ expect(r.stderr).toContain('--brain is not supported on a thin-client install');
+ expect(r.stderr).not.toContain('[gbrain-bridge] relaying');
+ });
+
test('`gbrain --version` works on thin-client install', async () => {
seedThinClientConfig(tmp);
const r = await run(['--version']);
diff --git a/test/cli-flag-equals.test.ts b/test/cli-flag-equals.test.ts
index 2c143a670d..4621dfde3d 100644
--- a/test/cli-flag-equals.test.ts
+++ b/test/cli-flag-equals.test.ts
@@ -434,6 +434,7 @@ describe('#7619 split rules', () => {
'src/core/sync-upstream.ts': 'git child argv',
'src/core/tailscale.ts': 'tailscale child argv',
'src/mcp/surface.ts': 'serve --access/--surface parsers read both forms (#7603); the entry splits the = form first',
+ 'src/mcp/remote-bridge-errors.ts': 'prints the global --timeout=Ns form in a bridge fix; reads no flag',
'src/core/stdio-member-flag.ts': 'serve --stdio-member parser reads both forms; the entry splits the = form first, and setup and doctor read it back from a harness entry\'s args as written (GST-363)',
'src/core/direct-pool-profile.ts': 'pool profile reads serve --access in both forms from the raw argv before the gate',
'src/commands/access.ts': 'access has no EQUALS_READERS key, so the entry refuses every = form; flagValue and the --as guard also read it for a direct caller',
diff --git a/test/cli-thin-client-refusal-matrix.test.ts b/test/cli-thin-client-refusal-matrix.test.ts
index 960dd82f4c..55d3adc980 100644
--- a/test/cli-thin-client-refusal-matrix.test.ts
+++ b/test/cli-thin-client-refusal-matrix.test.ts
@@ -63,6 +63,11 @@ const ROUTING_ROWS: string[][] = [
['get', 'alice-example'],
['wakeshift', 'watch', 'job', '1'],
['wakeshift', 'status'],
+ ['serve', '--http'],
+ ['serve', '--http', '--port', '3131'],
+ ['serve', '--access', 'read-only'],
+ ['serve', '--surface', 'Starter'],
+ ['serve', '--advertise=bogus'],
];
const VOLATILE_ROWS: string[][] = [['status'], ['capture', 'hello']];
diff --git a/test/fixtures/goldens/cli/dispatch-phase.json b/test/fixtures/goldens/cli/dispatch-phase.json
index f794862caf..7fb861628e 100644
--- a/test/fixtures/goldens/cli/dispatch-phase.json
+++ b/test/fixtures/goldens/cli/dispatch-phase.json
@@ -2358,6 +2358,7 @@
"stats",
"tune"
],
+ "serve": [],
"sources": [
"shared-skills"
],
diff --git a/test/fixtures/goldens/cli/thin-client-cases.json b/test/fixtures/goldens/cli/thin-client-cases.json
index 86bd36af1d..1541dab549 100644
--- a/test/fixtures/goldens/cli/thin-client-cases.json
+++ b/test/fixtures/goldens/cli/thin-client-cases.json
@@ -101,12 +101,10 @@
},
{
"argv": "serve",
- "exitCode": 1,
+ "exitCode": 0,
"stderr": [
- "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"
+ "[gbrain-bridge] relaying stdio to http://127.0.0.1:1/mcp surface=full (source: default)",
+ "[gbrain-bridge] exit (stdin-end)"
],
"stdout": []
},
diff --git a/test/fixtures/goldens/cli/thin-client-routing.json b/test/fixtures/goldens/cli/thin-client-routing.json
index dee1954c0b..fb2d271a65 100644
--- a/test/fixtures/goldens/cli/thin-client-routing.json
+++ b/test/fixtures/goldens/cli/thin-client-routing.json
@@ -286,6 +286,59 @@
"Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"
],
"stdout": []
+ },
+ {
+ "argv": "serve --http",
+ "exitCode": 1,
+ "stderr": [
+ "Error [requires_local_engine]: `gbrain serve --http` is not routable (thin-client of http://127.0.0.1:1/mcp): it serves a brain over HTTP, so it runs on the brain host.",
+ "Fix: gbrain serve --http",
+ "Why: HTTP serving hosts the brain database, which lives on the brain host; a thin client has none to serve.",
+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"
+ ],
+ "stdout": []
+ },
+ {
+ "argv": "serve --http --port 3131",
+ "exitCode": 1,
+ "stderr": [
+ "Error [requires_local_engine]: `gbrain serve --http --port 3131` is not routable (thin-client of http://127.0.0.1:1/mcp): it serves a brain over HTTP, so it runs on the brain host.",
+ "Fix: gbrain serve --http --port 3131",
+ "Why: HTTP serving hosts the brain database, which lives on the brain host; a thin client has none to serve.",
+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"
+ ],
+ "stdout": []
+ },
+ {
+ "argv": "serve --access read-only",
+ "exitCode": 1,
+ "stderr": [
+ "Error [requires_local_engine]: `gbrain serve --access read-only` is not routable (thin-client of http://127.0.0.1:1/mcp): it asks this bridge to enforce a restriction, and a thin client cannot enforce one locally.",
+ "Fix: gbrain auth register-client '<name>' --grant-types client_credentials --scopes read",
+ "Why: The brain host enforces what each client may do; a filter in this process would be advice, not a boundary.",
+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"
+ ],
+ "stdout": []
+ },
+ {
+ "argv": "serve --surface Starter",
+ "exitCode": 2,
+ "stderr": [
+ "Error [invalid_params]: --surface must be one of verbs|starter|full; got 'Starter'.",
+ "Fix: Pass one of verbs|starter|full, e.g. --surface verbs.",
+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#invalid_params"
+ ],
+ "stdout": []
+ },
+ {
+ "argv": "serve --advertise=bogus",
+ "exitCode": 2,
+ "stderr": [
+ "Error [invalid_params]: --advertise must be one of verbs|starter|full; got 'bogus'.",
+ "Fix: Pass one of verbs|starter|full, e.g. --advertise verbs.",
+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#invalid_params"
+ ],
+ "stdout": []
}
],
"normalizer": "cli-thin-client-v1"
diff --git a/test/mcp-client-forward.test.ts b/test/mcp-client-forward.test.ts
new file mode 100644
index 0000000000..bfbbec160d
--- /dev/null
+++ b/test/mcp-client-forward.test.ts
@@ -0,0 +1,135 @@
+/**
+ * #8543: forwardRemoteToolCall, the stdio bridge's relay. It returns the
+ * host's CallToolResult unchanged (refusals and pending receipts included),
+ * gives a journaled mutation one request_id that survives the single 401
+ * re-mint, never resends after any other failure, and says whether a failed
+ * call may have reached the host.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { forwardRemoteToolCall, RemoteMcpError, _clearMcpClientTokenCache } from '../src/core/mcp-client.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
+import { VERSION } from '../src/version.ts';
+
+let server: ReturnType<typeof Bun.serve>;
+let port = 0;
+let tokenMints = 0;
+let tokenStatus = 200;
+let callAttempts = 0;
+let callStatus: (attempt: number) => number | undefined = () => undefined;
+let answer: (params: any) => unknown = () => ({ content: [{ type: 'text', text: '{"ok":true}' }] });
+let calls: any[] = [];
+let headers: Array<string | null> = [];
+
+beforeAll(() => {
+ server = Bun.serve({ hostname: '127.0.0.1', port: 0, async fetch(req) {
+ const path = new URL(req.url).pathname;
+ if (path === '/.well-known/oauth-authorization-server') return Response.json({ token_endpoint: `http://127.0.0.1:${port}/token`, issuer: `http://127.0.0.1:${port}` });
+ if (path === '/token') {
+ tokenMints++;
+ return tokenStatus === 200 ? Response.json({ access_token: `t-${tokenMints}`, token_type: 'bearer', expires_in: 3600, scope: 'read write' })
+ : Response.json({ error: 'server_error' }, { status: tokenStatus });
+ }
+ if (path === '/mcp' && req.method === 'POST') {
+ const body = await req.json() as { id?: number; method: string; params?: any };
+ headers.push(req.headers.get('x-gbrain-client'));
+ 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: 'gbrain', version: '0.60.600.0' } } });
+ }
+ if (body.method === 'tools/call') {
+ callAttempts++;
+ calls.push(body.params);
+ const status = callStatus(callAttempts);
+ if (status !== undefined) return new Response('fixture', { status });
+ return Response.json({ jsonrpc: '2.0', id: body.id, result: answer(body.params) });
+ }
+ return Response.json({ jsonrpc: '2.0', id: body.id, result: {} });
+ }
+ return new Response(null, { status: path === '/mcp' ? 405 : 404 });
+ } });
+ port = server.port!;
+});
+
+afterAll(async () => { await server.stop(true); });
+
+beforeEach(() => {
+ tokenMints = 0; tokenStatus = 200; callAttempts = 0; calls = []; headers = [];
+ callStatus = () => undefined;
+ answer = () => ({ content: [{ type: 'text', text: '{"ok":true}' }] });
+ _clearMcpClientTokenCache();
+});
+
+const cfg = (): GBrainConfig => ({ engine: 'postgres', remote_mcp: { issuer_url: `http://127.0.0.1:${port}`, mcp_url: `http://127.0.0.1:${port}/mcp`,
+ oauth_client_id: 'cid', oauth_client_secret: 'csecret' } }) as GBrainConfig;
+
+async function failure(p: Promise<unknown>): Promise<RemoteMcpError> {
+ try { await p; } catch (e) { if (e instanceof RemoteMcpError) return e; throw e; }
+ throw new Error('expected a RemoteMcpError');
+}
+
+describe('forwardRemoteToolCall', () => {
+ test('returns the host\'s refusal and pending receipt unchanged instead of throwing', async () => {
+ const refusal: CallToolResult = { isError: true, content: [{ type: 'text', text: '{"code":"insufficient_scope","fix":{"argv":["gbrain"]}}' }] };
+ answer = () => refusal;
+ expect(await forwardRemoteToolCall(cfg(), 'get_page', { slug: 'x' })).toEqual(refusal);
+ const pending: CallToolResult = { isError: true, content: [{ type: 'text', text: JSON.stringify({ code: 'unavailable', write_error: 'write_pending', write_request: { request_id: 'd7599b95-65c2-4d54-aa4e-cb5745af90cf', state: 'queued', retry_after_ms: 1000 } }) }] };
+ answer = () => pending;
+ expect(await forwardRemoteToolCall(cfg(), 'put_page', { slug: 'x', content: 'y' })).toEqual(pending);
+ });
+
+ test('one HTTP 401 re-mints once and resends the same request_id', async () => {
+ callStatus = (n) => n === 1 ? 401 : undefined;
+ const result = await forwardRemoteToolCall(cfg(), 'put_page', { slug: 'x', content: 'y' });
+ expect(result.isError ?? false).toBe(false);
+ expect(tokenMints).toBe(2);
+ expect(calls).toHaveLength(2);
+ expect(calls[0].arguments.request_id).toMatch(/^[0-9a-f-]{36}$/);
+ expect(calls[1].arguments.request_id).toBe(calls[0].arguments.request_id);
+ });
+
+ test('any other failure after the call was sent is never resent and keeps its identity as unknown', async () => {
+ callStatus = () => 502;
+ const e = await failure(forwardRemoteToolCall(cfg(), 'put_page', { slug: 'x', content: 'y' }));
+ expect(calls).toHaveLength(1);
+ expect(e.detail?.submission_status).toBe('unknown');
+ expect(e.detail?.request_id).toBe(calls[0].arguments.request_id);
+ });
+
+ test('a failure before the call is sent says not_sent', async () => {
+ tokenStatus = 500;
+ const e = await failure(forwardRemoteToolCall(cfg(), 'put_page', { slug: 'x', content: 'y', request_id: 'c96cbb61-b862-4f8a-92bb-e79113f8ff19' }));
+ expect(calls).toHaveLength(0);
+ expect(e.detail?.submission_status).toBe('not_sent');
+ expect(e.detail?.request_id).toBe('c96cbb61-b862-4f8a-92bb-e79113f8ff19');
+ });
+
+ test('reads and dry runs carry no injected request_id', async () => {
+ await forwardRemoteToolCall(cfg(), 'get_page', { slug: 'x' });
+ await forwardRemoteToolCall(cfg(), 'put_page', { slug: 'x', content: 'y', dry_run: true });
+ expect(calls.map(c => c.arguments.request_id)).toEqual([undefined, undefined]);
+ });
+
+ test('_meta reaches the host unchanged', async () => {
+ const meta = { on_behalf_of: ['alice-example'], session_id: 's-1', hot_memory: false };
+ await forwardRemoteToolCall(cfg(), 'query', { query: 'x' }, { meta });
+ expect(calls[0]._meta).toEqual(meta);
+ });
+
+ test('the client name is the caller\'s, and the default stays the thin CLI\'s', async () => {
+ await forwardRemoteToolCall(cfg(), 'get_page', { slug: 'x' }, { clientName: 'gbrain-stdio-bridge' });
+ expect(new Set(headers)).toEqual(new Set([`gbrain-stdio-bridge/${VERSION}`]));
+ headers = [];
+ await forwardRemoteToolCall(cfg(), 'get_page', { slug: 'x' });
+ expect(new Set(headers)).toEqual(new Set([`gbrain-remote-cli/${VERSION}`]));
+ });
+
+ test('admit sees the host\'s serverInfo and a refusal is returned without sending the call', async () => {
+ const refused: CallToolResult = { isError: true, content: [{ type: 'text', text: '{"code":"host_upgrade_required"}' }] };
+ let seen: unknown;
+ const result = await forwardRemoteToolCall(cfg(), 'query', { query: 'x' }, { admit: (host) => { seen = host; return refused; } });
+ expect(result).toEqual(refused);
+ expect(seen).toMatchObject({ name: 'gbrain', version: '0.60.600.0' });
+ expect(calls).toHaveLength(0);
+ });
+});
diff --git a/test/mcp-registration-blocks.test.ts b/test/mcp-registration-blocks.test.ts
index 77507e5387..924a6f6f69 100644
--- a/test/mcp-registration-blocks.test.ts
+++ b/test/mcp-registration-blocks.test.ts
@@ -1,9 +1,10 @@
/**
* mcp-registration-blocks.test.ts — cathedral-6 lane B pins:
- * - openclawThinClientBlock is the HONEST v1 OpenClaw path: the scoped
- * `gbrain init` thin-client command with all four connection args, plus the
- * FULL-local-DB-access honesty sentence — and NOT an mcpServers/stdio JSON
- * config.
+ * - openclawThinClientBlock is run on the OpenClaw machine: the scoped
+ * `gbrain init` thin-client command with all four connection args, then
+ * OpenClaw's own `mcp add` for that thin client's stdio bridge (#8543),
+ * with the launcher resolved there, no host path, no mcpServers key, and
+ * one GBRAIN_HOME on both lines when a narrow home is chosen.
* - OAUTH_SECRET_NOTE moved to core with its text unchanged; connect.ts
* re-exports the identical value (surface unchanged).
*/
@@ -29,20 +30,28 @@ describe('openclawThinClientBlock', () => {
expect(block).toContain('--oauth-client-secret sekret_xyz789');
});
- test('states the honesty note: scoped-CLI path, OpenClaw\'s native remote MCP is its own OAuth route, stdio grants FULL local DB access', () => {
+ test('registers the thin client\'s stdio bridge with OpenClaw, launcher resolved on the OpenClaw machine', () => {
const block = openclawThinClientBlock(OPTS);
- expect(block).toContain(
- 'Your OpenClaw reaches the brain through the scoped gbrain CLI (search/query/recall/put);',
- );
- expect(block).not.toContain("isn't supported yet");
+ expect(block).toContain('# On the OpenClaw machine, install the gbrain CLI, then run:');
+ expect(block).toContain('openclaw mcp add gbrain --command "$(command -v gbrain)" --arg serve --arg --surface --arg starter --arg --advertise --arg verbs');
+ expect(block).toContain("If gbrain's OpenClaw bundle plugin is installed there, it already registers");
expect(block).toContain("OpenClaw's native remote MCP client (streamable HTTP + `openclaw mcp login`) is the other scoped");
- expect(block).toContain('the stdio config in docs/mcp/OPENCLAW.md grants');
- expect(block).toContain('FULL local DB access and does not use this client.');
+ expect(block).not.toContain('FULL local DB access');
});
- test('is NOT an mcpServers/stdio JSON config', () => {
+ test('names no path from the machine that printed it and no mcpServers key', () => {
const block = openclawThinClientBlock(OPTS);
expect(block).not.toMatch(/mcpServers|"command"\s*:/);
+ expect(block).not.toContain(process.execPath);
+ expect(block).not.toMatch(/(^|\s)\/(usr|home|Users|opt|root)\//m);
+ });
+
+ test('a narrow home rides on both the init line and the entry', () => {
+ const block = openclawThinClientBlock({ ...OPTS, gbrainHome: '/home/alice-example/.gbrain-openclaw' });
+ const lines = block.split('\n');
+ expect(lines.find(l => l.includes('gbrain init'))).toStartWith('GBRAIN_HOME=/home/alice-example/.gbrain-openclaw gbrain init --mcp-only');
+ expect(lines.find(l => l.startsWith('openclaw mcp add'))).toEndWith(' --env GBRAIN_HOME=/home/alice-example/.gbrain-openclaw');
+ expect(block).not.toContain('GBRAIN_HOME=<dir>');
});
test('shell-quotes unsafe values so a pasted block cannot command-substitute', () => {
diff --git a/test/oauth-scope-probe.test.ts b/test/oauth-scope-probe.test.ts
index 3dafff3cf8..2c91cbd9b9 100644
--- a/test/oauth-scope-probe.test.ts
+++ b/test/oauth-scope-probe.test.ts
@@ -7,8 +7,9 @@
* ScopeProbeResult inputs to pin the status semantics:
*
* read.missing_scope → fail (broken setup)
- * admin.missing_scope → warn (the load-bearing case for v0.29.2/v0.30.0
- * thin clients without admin scope)
+ * admin.missing_scope → warn only when the grant lists admin; a read or
+ * read+write client is narrow by design → ok,
+ * informational, never advice to add a scope (#8543)
* both ok → ok
* inconclusive → ok with detail.inconclusive=true
*/
@@ -46,7 +47,7 @@ describe('buildScopeCheck', () => {
admin_ok: false,
admin_error: 'missing_scope',
};
- const check = buildScopeCheck('read write', probe);
+ const check = buildScopeCheck('read write admin', probe);
expect(check.status).toBe('warn');
expect(check.message).toContain('admin scope MISSING');
// The pinpoint remediation must name the exact CLI invocation.
@@ -57,6 +58,17 @@ describe('buildScopeCheck', () => {
expect(check.detail?.admin_error).toBe('missing_scope');
});
+ for (const granted of ['read', 'read write', 'read,write']) {
+ test(`a "${granted}" client without admin is ok and informational, and nothing suggests adding a scope (#8543)`, () => {
+ const check = buildScopeCheck(granted, { read_ok: true, admin_ok: false, admin_error: 'missing_scope' });
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('by design');
+ expect(check.message).not.toContain('register-client');
+ expect(JSON.stringify(check)).not.toMatch(/--scopes|read,write,admin|re-register/);
+ expect(check.detail).toMatchObject({ granted, read_ok: true, admin_ok: false, admin_granted: false });
+ });
+ }
+
test('admin probe fails for non-scope reason (e.g. parse) → status=ok inconclusive', () => {
const probe: ScopeProbeResult = {
read_ok: true,
diff --git a/test/remote-bridge-args.test.ts b/test/remote-bridge-args.test.ts
new file mode 100644
index 0000000000..00dbfca864
--- /dev/null
+++ b/test/remote-bridge-args.test.ts
@@ -0,0 +1,64 @@
+/**
+ * #8543: which thin-client `gbrain serve` argument lists start the stdio
+ * bridge. The argv gbrain's own plugin manifests register must bridge (T20),
+ * and a refused form's fix keeps its flags, so it is never "fixed" into a
+ * bare serve, which on a thin client is the bridge.
+ */
+import { describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { parseBridgeServeArgs, serveThinClientRefusal } from '../src/mcp/remote-bridge-args.ts';
+
+const ROOT = join(import.meta.dir, '..');
+const MANIFESTS = ['.claude-plugin/plugin.json', '.codex-plugin/mcp.json',
+ 'plugin-variants/gbrain-coding/.claude-plugin/plugin.json', 'plugin-variants/gbrain-coding/.codex-plugin/mcp.json',
+ 'plugin-variants/gbrain-daily/.claude-plugin/plugin.json', 'plugin-variants/gbrain-daily/.codex-plugin/mcp.json'];
+
+function serveArgv(node: unknown): string[] | null {
+ if (Array.isArray(node) && node.every(x => typeof x === 'string') && node.includes('serve')) return node as string[];
+ if (node && typeof node === 'object') for (const v of Object.values(node)) { const hit = serveArgv(v); if (hit) return hit; }
+ return null;
+}
+
+describe('parseBridgeServeArgs', () => {
+ for (const file of MANIFESTS) {
+ test(`the argv registered by ${file} starts the bridge`, () => {
+ const argv = serveArgv(JSON.parse(readFileSync(join(ROOT, file), 'utf8')));
+ expect(argv).not.toBeNull();
+ const parsed = parseBridgeServeArgs(argv!.slice(argv!.indexOf('serve') + 1));
+ expect(parsed.bridge).toBe(true);
+ });
+ }
+
+ test('bare serve, both value forms and --source-guard bridge; a repeat takes the narrowest', () => {
+ expect(parseBridgeServeArgs([])).toEqual({ bridge: true, surface: null, advertise: null, sourceGuard: false });
+ expect(parseBridgeServeArgs(['--surface', 'full', '--surface=starter', '--advertise=verbs', '--source-guard']))
+ .toEqual({ bridge: true, surface: 'starter', advertise: 'verbs', sourceGuard: true });
+ });
+
+ test('a bad surface value is invalid_params, not a host refusal', () => {
+ for (const args of [['--surface', 'Starter'], ['--advertise'], ['--surface=']]) {
+ let caught: unknown;
+ try { parseBridgeServeArgs(args); } catch (e) { caught = e; }
+ expect(caught).toBeInstanceOf(OperationError);
+ expect((caught as OperationError).code).toBe('invalid_params');
+ }
+ });
+
+ test('host-only flags are refused with their flags kept in the fix, unsafe values masked', () => {
+ const parsed = parseBridgeServeArgs(['--http', '--port', '3131', '--bind', 'bad host;rm']);
+ expect(parsed).toEqual({ bridge: false, refused: ['--http', '--port', '3131', '--bind', 'bad host;rm'] });
+ const refusal = serveThinClientRefusal((parsed as { refused: string[] }).refused, 'http://127.0.0.1:1/mcp');
+ expect(refusal.code).toBe('requires_local_engine');
+ const argv = (refusal as unknown as { fix?: { argv?: string[] } }).fix?.argv ?? [];
+ expect(argv).toEqual(['gbrain', 'serve', '--http', '--port', '3131', '--bind', '<value>']);
+ });
+
+ test('--access never suggests widening: its fix registers a narrow read-only client', () => {
+ const refusal = serveThinClientRefusal(['--access', 'read-only'], 'http://127.0.0.1:1/mcp');
+ const argv = (refusal as unknown as { fix: { argv: string[] } }).fix.argv;
+ expect(argv.slice(argv.indexOf('--scopes'))).toEqual(['--scopes', 'read']);
+ expect(refusal.message + refusal.suggestion).not.toMatch(/\bwrite\b|\badmin\b/);
+ });
+});
diff --git a/test/remote-bridge-errors.test.ts b/test/remote-bridge-errors.test.ts
new file mode 100644
index 0000000000..94f106bf17
--- /dev/null
+++ b/test/remote-bridge-errors.test.ts
@@ -0,0 +1,255 @@
+/**
+ * #8543: the stdio bridge's failure envelopes, driven in-process over an
+ * in-memory MCP pair with the remote list/forward calls injected. Every
+ * transport failure becomes the v1 agent envelope with a fix that never
+ * widens the client, every line and envelope is free of URL secrets, and an
+ * unexpected fault leaves the bridge serving.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, rmSync, statSync } from 'node:fs';
+import { EventEmitter } from 'node:events';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import { CallToolResultSchema, McpError, type CallToolResult } from '@modelcontextprotocol/sdk/types.js';
+import { RemoteMcpError, type ForwardRemoteToolOptions, type RemoteToolDefs } from '../src/core/mcp-client.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+import { startRemoteStdioBridge, type RemoteBridgeOptions } from '../src/mcp/remote-bridge.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const USERINFO = ['user', 's3cret'].join(':');
+const SECRET_URL = `https://${USERINFO}@host.example/mcp?token=abc123#frag`;
+const cfg = { engine: 'postgres', remote_mcp: { issuer_url: `https://${USERINFO}@host.example`, mcp_url: SECRET_URL,
+ oauth_client_id: 'gbrain_cl_example', oauth_client_secret: 'client-secret-example' } } as unknown as GBrainConfig;
+const HOST = { name: 'gbrain', version: '9.0.0.0' };
+const TOOLS: RemoteToolDefs = { server: HOST, tools: ['get_page', 'put_page', 'query', 'whoami', 'request_tools', 'submit_job'].map(name => ({ name, inputSchema: { type: 'object' as const } })) };
+const homes: string[] = [];
+
+afterAll(() => { for (const h of homes) rmSync(h, { recursive: true, force: true }); });
+
+type Forward = (c: GBrainConfig, name: string, args: Record<string, unknown>, o: ForwardRemoteToolOptions & { meta?: Record<string, unknown> }) => Promise<CallToolResult>;
+
+async function startBridge(over: { forward?: Forward; list?: () => Promise<RemoteToolDefs>; transport?: RemoteBridgeOptions['transport']; advertise?: RemoteBridgeOptions['advertise'] } = {}) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-bridge-unit-'));
+ homes.push(home);
+ const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
+ const logs: string[] = [];
+ const exits: number[] = [];
+ const stdin = Object.assign(new EventEmitter(), { isTTY: true });
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SURFACE: undefined }, () => startRemoteStdioBridge(cfg, {
+ installFatalHandlers: false, mcpStdio: false, eofDrainMs: 0, ...(over.advertise ? { advertise: over.advertise } : {}),
+ transport: over.transport ?? (() => serverSide),
+ lifecycle: { stdin: stdin as never, signals: new EventEmitter() as never, log: (m: string) => { logs.push(m); }, exit: (c?: number) => { exits.push(c ?? 0); },
+ getParentPid: () => 1, probeWatchdog: () => false },
+ list: (async () => (over.list ? over.list() : TOOLS)) as never,
+ forward: (over.forward ?? (async () => ({ content: [{ type: 'text', text: '{"ok":true}' }] }))) as never,
+ }));
+ const client = new Client({ name: 'bridge-unit', version: '1' }, { capabilities: {} });
+ if (!over.transport) await client.connect(clientSide);
+ return { client, logs, exits, home, close: () => client.close().catch(() => {}) };
+}
+
+const body = (r: unknown) => JSON.parse(((r as CallToolResult).content[0] as { text: string }).text);
+const noSecrets = (s: string) => { expect(s).not.toContain('s3cret'); expect(s).not.toContain('abc123'); expect(s).not.toContain('client-secret-example'); expect(s).not.toContain('#frag'); };
+
+const CASES: Array<[string, RemoteMcpError, string]> = [
+ ['config', new RemoteMcpError('config', `bad config for ${SECRET_URL}`), 'config_error'],
+ ['discovery', new RemoteMcpError('discovery', `no metadata at ${SECRET_URL}`, { mcp_url: SECRET_URL }), 'unavailable'],
+ ['token', new RemoteMcpError('token', 'token endpoint 500', { mcp_url: SECRET_URL }), 'unavailable'],
+ ['rate_limited', new RemoteMcpError('rate_limited', 'slow down', { mcp_url: SECRET_URL }), 'rate_limited'],
+ ['auth', new RemoteMcpError('auth', 'bad creds', { mcp_url: SECRET_URL }), 'invalid_client'],
+ ['auth_after_refresh', new RemoteMcpError('auth_after_refresh', 'still 401', { mcp_url: SECRET_URL }), 'invalid_client'],
+ ['network timeout', new RemoteMcpError('network', `timed out ${SECRET_URL}`, { mcp_url: SECRET_URL, kind: 'timeout' }), 'timeout'],
+ ['network aborted', new RemoteMcpError('network', 'aborted', { mcp_url: SECRET_URL, kind: 'aborted' }), 'cancelled'],
+ ['network unreachable', new RemoteMcpError('network', `ECONNREFUSED ${SECRET_URL}`, { mcp_url: SECRET_URL, kind: 'unreachable' }), 'unavailable'],
+ ['parse', new RemoteMcpError('parse', 'bad json', { mcp_url: SECRET_URL }), 'internal_error'],
+ ['tool_error', new RemoteMcpError('tool_error', 'odd', { mcp_url: SECRET_URL }), 'internal_error'],
+];
+
+describe('bridge call failures', () => {
+ for (const [label, error, code] of CASES) {
+ test(`${label} on a read → ${code}, secret-free, and no fix widens the client`, async () => {
+ const b = await startBridge({ forward: async () => { throw error; } });
+ try {
+ const r = await b.client.callTool({ name: 'get_page', arguments: { slug: 'notes/x' } });
+ expect(r.isError).toBe(true);
+ const env = body(r);
+ expect(env.code).toBe(code);
+ expect(env.stage).toBe('call');
+ noSecrets(JSON.stringify(r));
+ noSecrets(b.logs.join('\n'));
+ expect(JSON.stringify(env)).not.toMatch(/--scopes|rescope|register-client[^"]*admin/);
+ } finally { await b.close(); }
+ });
+ }
+});
+
+describe('bridge list failures', () => {
+ for (const [label, error, code] of CASES) {
+ test(`${label} on tools/list → JSON-RPC error with the ${code} envelope and no side effects`, async () => {
+ let calls = 0;
+ const b = await startBridge({ list: async () => { calls++; throw error; } });
+ try {
+ let caught: unknown;
+ try { await b.client.listTools(); } catch (e) { caught = e; }
+ expect(caught).toBeInstanceOf(McpError);
+ const data = (caught as McpError).data as Record<string, unknown>;
+ expect(data.code).toBe(code);
+ expect(data.side_effects).toBe('none');
+ expect(typeof data.stage).toBe('string');
+ noSecrets(JSON.stringify(data) + (caught as Error).message);
+ expect(b.logs.some(l => l.includes(`code=${code}`) || l.includes(code))).toBe(true);
+ noSecrets(b.logs.join('\n'));
+ expect(calls).toBeGreaterThan(0);
+ } finally { await b.close(); }
+ });
+ }
+});
+
+describe('write identity', () => {
+ test('an accepted mutation whose answer was lost keeps its request_id and says the outcome is unknown', async () => {
+ let sentId: unknown;
+ const b = await startBridge({ forward: async (_c, _n, args) => {
+ sentId = args.request_id;
+ throw new RemoteMcpError('network', 'socket hang up', { mcp_url: SECRET_URL, kind: 'unreachable', request_id: args.request_id as string, submission_status: 'unknown' });
+ } });
+ try {
+ const env = body(await b.client.callTool({ name: 'put_page', arguments: { slug: 'notes/x', content: 'x' } }));
+ expect(env.code).toBe('write_outcome_unknown');
+ expect(env.submission_status).toBe('unknown');
+ expect(env.request_id).toBe(sentId);
+ expect(env.retryable).toBe(false);
+ expect(JSON.stringify(env)).toContain('get_write_request');
+ expect(env.fix.argv).toEqual(['gbrain', 'write-request', '--', sentId]);
+ } finally { await b.close(); }
+ });
+
+ test('a mutation that was never sent is safe to resend', async () => {
+ const b = await startBridge({ forward: async (_c, _n, args) => {
+ throw new RemoteMcpError('network', 'ECONNREFUSED', { mcp_url: SECRET_URL, kind: 'unreachable', request_id: args.request_id as string, submission_status: 'not_sent' });
+ } });
+ try {
+ const env = body(await b.client.callTool({ name: 'put_page', arguments: { slug: 'notes/x', content: 'x' } }));
+ expect(env.code).toBe('unavailable');
+ expect(env.submission_status).toBe('not_sent');
+ } finally { await b.close(); }
+ });
+
+ test('a job submission whose answer was lost points at list_jobs, not a write receipt', async () => {
+ const b = await startBridge({ forward: async () => {
+ throw new RemoteMcpError('network', 'reset', { mcp_url: SECRET_URL, kind: 'unreachable', submission_status: 'unknown' });
+ } });
+ try {
+ const env = body(await b.client.callTool({ name: 'submit_job', arguments: { name: 'sync' } }));
+ expect(env.code).toBe('write_outcome_unknown');
+ expect(JSON.stringify(env)).toContain('list_jobs');
+ expect(JSON.stringify(env)).not.toContain('get_write_request');
+ } finally { await b.close(); }
+ });
+});
+
+describe('unexpected faults', () => {
+ test('a thrown non-remote error becomes internal_error with a 0600 trace, and the next call still works', async () => {
+ let n = 0;
+ const b = await startBridge({ forward: async () => {
+ if (n++ === 0) throw new Error(`kaboom at ${SECRET_URL}`);
+ return { content: [{ type: 'text', text: '{"ok":true}' }] };
+ } });
+ try {
+ const first = await b.client.callTool({ name: 'get_page', arguments: { slug: 'notes/x' } });
+ expect(first.isError).toBe(true);
+ const env = body(first);
+ expect(env.code).toBe('internal_error');
+ const trace = b.logs.map(l => /trace=(\S+)/.exec(l)?.[1]).find(Boolean);
+ expect(trace && existsSync(trace)).toBe(true);
+ expect(statSync(trace!).mode & 0o777).toBe(0o600);
+ noSecrets(await Bun.file(trace!).text());
+ noSecrets(JSON.stringify(first) + b.logs.join('\n'));
+ const second = await b.client.callTool({ name: 'get_page', arguments: { slug: 'notes/x' } });
+ expect(second.isError ?? false).toBe(false);
+ expect(body(second)).toEqual({ ok: true });
+ } finally { await b.close(); }
+ });
+
+ test('a startup failure exits 1 with one secret-free stderr line', async () => {
+ const b = await startBridge({ transport: () => { throw new Error(`cannot open ${SECRET_URL}`); } });
+ expect(b.exits).toEqual([1]);
+ const fatal = b.logs.filter(l => l.includes('code=internal_error'));
+ expect(fatal).toHaveLength(1);
+ expect(fatal[0]).toContain('stage=startup');
+ noSecrets(b.logs.join('\n'));
+ });
+});
+
+describe('audience', () => {
+ test('an audience-bearing call to a host too old to enforce it is refused before it is sent', async () => {
+ let sent = 0;
+ const b = await startBridge({ forward: async (_c, _n, _a, o) => {
+ const refused = o.admit?.({ name: 'gbrain', version: '0.60.500.0' });
+ if (refused) return refused;
+ sent++;
+ return { content: [{ type: 'text', text: '{}' }] };
+ } });
+ try {
+ const env = body(await b.client.callTool({ name: 'query', arguments: { query: 'x' }, _meta: { on_behalf_of: ['alice-example'] } }));
+ expect(env.code).toBe('host_upgrade_required');
+ expect(env.min_host_version).toBe('0.60.543.0');
+ expect(sent).toBe(0);
+ } finally { await b.close(); }
+ });
+
+ test('a read answer that does not report its audience is withheld', async () => {
+ const b = await startBridge({ forward: async (_c, _n, _a, o) => {
+ expect(o.meta).toEqual({ on_behalf_of: ['alice-example'], session_id: 's-1' });
+ return { content: [{ type: 'text', text: '{"rows":["canary-row-8543"]}' }] };
+ } });
+ try {
+ const r = await b.client.callTool({ name: 'query', arguments: { query: 'x' }, _meta: { on_behalf_of: ['alice-example'], session_id: 's-1' } });
+ expect(body(r).code).toBe('host_upgrade_required');
+ expect(JSON.stringify(r)).not.toContain('canary-row-8543');
+ } finally { await b.close(); }
+ });
+
+ test('a read answer that reports its audience is relayed unchanged', async () => {
+ const answer: CallToolResult = { content: [{ type: 'text', text: '{"rows":[]}' }], _meta: { access: { audience: ['alice-example'] } } };
+ const b = await startBridge({ forward: async () => answer });
+ try {
+ const r = await b.client.callTool({ name: 'query', arguments: { query: 'x' }, _meta: { on_behalf_of: ['alice-example'] } });
+ expect(r).toEqual(answer);
+ } finally { await b.close(); }
+ });
+
+ test('a non-object _meta is never relayed (the protocol layer drops the frame before any handler)', async () => {
+ let sent = 0;
+ const b = await startBridge({ forward: async () => { sent++; return { content: [] }; } });
+ try {
+ let failed = false;
+ try { await b.client.request({ method: 'tools/call', params: { name: 'query', arguments: { query: 'x' }, _meta: 'alice-example' as never } }, CallToolResultSchema, { timeout: 1000 }); }
+ catch { failed = true; }
+ expect(failed).toBe(true);
+ expect(sent).toBe(0);
+ expect((await b.client.callTool({ name: 'query', arguments: { query: 'x' } })).isError ?? false).toBe(false);
+ expect(sent).toBe(1);
+ } finally { await b.close(); }
+ });
+});
+
+describe('request_tools schemas the host describes enter the bridge tool list', () => {
+ const hostVerbsOnly: RemoteToolDefs = { server: HOST, tools: ['query', 'request_tools'].map(name => ({ name, inputSchema: { type: 'object' as const } })) };
+ const described = { content: [{ type: 'text' as const, text: JSON.stringify({ tools: [{ name: 'get_page', description: 'Read a page', inputSchema: { type: 'object', properties: { slug: { type: 'string' } } } }] }) }] };
+
+ for (const advertise of [undefined, 'verbs'] as const) {
+ test(`a tool the host lists only after request_tools is listed next time (advertise=${advertise ?? 'none'})`, async () => {
+ const b = await startBridge({ list: async () => hostVerbsOnly, forward: async () => described, ...(advertise ? { advertise } : {}) });
+ try {
+ expect((await b.client.listTools()).tools.map(x => x.name)).not.toContain('get_page');
+ const r = await b.client.callTool({ name: 'request_tools', arguments: { tools: ['get_page'] } });
+ expect(r.isError ?? false).toBe(false);
+ const after = (await b.client.listTools()).tools;
+ expect(after.map(x => x.name)).toContain('get_page');
+ expect(after.find(x => x.name === 'get_page')?.inputSchema).toEqual({ type: 'object', properties: { slug: { type: 'string' } } });
+ } finally { await b.close(); }
+ });
+ }
+});
diff --git a/test/remote-stdio-bridge.serial.test.ts b/test/remote-stdio-bridge.serial.test.ts
new file mode 100644
index 0000000000..9384375e16
--- /dev/null
+++ b/test/remote-stdio-bridge.serial.test.ts
@@ -0,0 +1,398 @@
+/**
+ * #8543 / GST-2104: on a thin client, plain `gbrain serve` is an engine-free
+ * stdio MCP relay to the remote brain. These probes drive the real CLI: a
+ * `gbrain serve --http` host on a keyless, repo-less PGLite home, OAuth
+ * clients registered on it, and thin homes whose bare `gbrain serve` is
+ * spoken to over stdio by the SDK client. The relay adds no privilege: every
+ * answer is the host's answer for the stored credential.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { spawn, type ChildProcess } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { createServer } from 'node:net';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
+import { ToolListChangedNotificationSchema } from '@modelcontextprotocol/sdk/types.js';
+import { STARTER_OPS } from '../src/mcp/surface.ts';
+import { runCli, type CliResult } from './helpers/cli-spawn.ts';
+
+const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');
+const PATH_ENV = `/usr/local/bin:${process.env.PATH ?? '/usr/bin:/bin'}`;
+const baseEnv = { GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_UPDATE_CHECK: '0', GBRAIN_SWEEP: '0', GBRAIN_NON_INTERACTIVE: '1',
+ GBRAIN_NO_BANNER: '1', NO_COLOR: '1', NODE_ENV: 'test', GBRAIN_SOURCE: undefined, GBRAIN_BRAIN_ID: undefined, GBRAIN_SURFACE: undefined };
+
+let hostHome: string;
+let base: string;
+let server: ChildProcess;
+let serverErr = '';
+const tempDirs: string[] = [];
+
+const gbrain = (cwd: string, args: string[]) => runCli(args, { home: cwd, cwd, env: baseEnv, timeoutMs: 90_000 });
+const ok = (result: CliResult) => {
+ expect({ exit: result.exitCode, failure: result.exitCode ? result.stdout + result.stderr : '' }).toEqual({ exit: 0, failure: '' });
+ return result.stdout;
+};
+
+async function freePort(): Promise<number> {
+ return await new Promise((resolve, reject) => {
+ const s = createServer();
+ s.once('error', reject);
+ s.listen(0, '127.0.0.1', () => {
+ const a = s.address();
+ s.close(() => resolve(typeof a === 'object' && a ? a.port : 0));
+ });
+ });
+}
+
+async function registerClient(name: string, scopes: string): Promise<{ id: string; secret: string }> {
+ const reg = await gbrain(hostHome, ['auth', 'register-client', name, '--grant-types', 'client_credentials',
+ '--scopes', scopes, '--token-endpoint-auth-method', 'client_secret_post']);
+ const id = /Client ID:\s+(\S+)/.exec(reg.stdout)?.[1];
+ const secret = /Client Secret:\s+(\S+)/.exec(reg.stdout)?.[1];
+ if (!id || !secret) throw new Error(`register-client yielded no credentials:\n${reg.stdout}\n${reg.stderr}`);
+ return { id, secret };
+}
+
+function thinHome(cred: { id: string; secret: string }, mcpUrl = `${base}/mcp`): string {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-bridge-thin-'));
+ tempDirs.push(dir);
+ mkdirSync(join(dir, '.gbrain'), { recursive: true });
+ writeFileSync(join(dir, '.gbrain', 'config.json'), JSON.stringify({
+ engine: 'postgres', remote_mcp: { issuer_url: base, mcp_url: mcpUrl, oauth_client_id: cred.id, oauth_client_secret: cred.secret },
+ }));
+ return dir;
+}
+
+function childEnv(home: string, extra: Record<string, string> = {}): Record<string, string> {
+ return { PATH: PATH_ENV, HOME: home, GBRAIN_HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_UPDATE_CHECK: '0',
+ GBRAIN_SWEEP: '0', NODE_ENV: 'test', ...extra };
+}
+
+async function bridge(home: string, args: string[] = [], extra: Record<string, string> = {}) {
+ const client = new Client({ name: 'bridge-8543-test', version: '1' }, { capabilities: {} });
+ const transport = new StdioClientTransport({ command: process.execPath, args: ['--no-env-file', CLI, 'serve', ...args],
+ cwd: home, env: childEnv(home, extra), stderr: 'pipe' });
+ let stderr = '';
+ transport.stderr?.on('data', (d: Buffer) => { stderr += d.toString(); });
+ await client.connect(transport, { signal: AbortSignal.timeout(60_000) });
+ return { client, stderr: () => stderr, close: async () => { await client.close().catch(() => {}); await transport.close().catch(() => {}); } };
+}
+
+async function direct(cred: { id: string; secret: string }) {
+ const tok = await fetch(`${base}/token`, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams({ grant_type: 'client_credentials', client_id: cred.id, client_secret: cred.secret }) });
+ const { access_token } = await tok.json() as { access_token: string };
+ const client = new Client({ name: 'direct-8543-test', version: '1' }, { capabilities: {} });
+ const transport = new StreamableHTTPClientTransport(new URL(`${base}/mcp`), { requestInit: { headers: { authorization: `Bearer ${access_token}` } } });
+ await client.connect(transport);
+ return { client, close: async () => { await client.close().catch(() => {}); } };
+}
+
+const text = (r: any) => (r.content ?? []).map((c: any) => c.text ?? '').join('');
+const names = (l: { tools: { name: string }[] }) => l.tools.map(t => t.name).sort();
+
+async function putLocal(slug: string, content: string): Promise<void> {
+ const child = Bun.spawn([process.execPath, '--no-env-file', CLI, 'put', slug], { cwd: hostHome, env: childEnv(hostHome, { GBRAIN_NON_INTERACTIVE: '1' }),
+ stdin: new TextEncoder().encode(content), stdout: 'pipe', stderr: 'pipe' });
+ const [code, out, err] = [await child.exited, await new Response(child.stdout).text(), await new Response(child.stderr).text()];
+ expect({ code, failure: code ? out + err : '' }).toEqual({ code: 0, failure: '' });
+}
+
+let port = 0;
+async function startHost(): Promise<void> {
+ const serverEnv: Record<string, string> = { ...Object.fromEntries(Object.entries(process.env).filter((e): e is [string, string] => e[1] !== undefined)),
+ ...childEnv(hostHome) };
+ for (const key of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_REMOTE_CLIENT_SECRET', 'GBRAIN_SOURCE', 'GBRAIN_BRAIN_ID', 'GBRAIN_SURFACE']) delete serverEnv[key];
+ server = spawn(process.execPath, ['--no-env-file', CLI, 'serve', '--http', '--bind', '127.0.0.1', '--port', String(port), '--public-url', base],
+ { cwd: hostHome, env: serverEnv, stdio: ['ignore', 'pipe', 'pipe'] });
+ server.stderr?.on('data', (d: Buffer) => { serverErr += d.toString(); });
+ let ready = false;
+ for (let i = 0; i < 120 && !ready; i++) {
+ try { ready = (await fetch(`${base}/health`)).ok; } catch { /* not up yet */ }
+ if (!ready) await Bun.sleep(500);
+ }
+ if (!ready) throw new Error(`serve --http did not become ready:\n${serverErr}`);
+}
+
+async function stopHost(): Promise<void> {
+ const s = server;
+ if (!s || s.exitCode !== null) return;
+ s.kill('SIGTERM');
+ await new Promise(resolve => { if (s.exitCode !== null) resolve(null); else s.once('exit', resolve); });
+}
+
+let readCred: { id: string; secret: string };
+let writeCred: { id: string; secret: string };
+let revokeCred: { id: string; secret: string };
+
+beforeAll(async () => {
+ hostHome = mkdtempSync(join(tmpdir(), 'gbrain-bridge-host-'));
+ ok(await gbrain(hostHome, ['init', '--pglite', '--no-embedding', '--non-interactive', '--json']));
+ ok(await gbrain(hostHome, ['access', 'member', 'add', 'alice-example']));
+ readCred = await registerClient('bridge-8543-read', 'read');
+ revokeCred = await registerClient('bridge-8543-revoke', 'read');
+ writeCred = await registerClient('bridge-8543-write', 'read write');
+ await putLocal('notes/alice-example-private-8543', '---\ntitle: Kept page\nreadable_by: [alice-example]\n---\nCanary kept-8543-zq.\n');
+ port = await freePort();
+ base = `http://127.0.0.1:${port}`;
+ await startHost();
+ const w = await direct(writeCred);
+ try {
+ const put = await w.client.callTool({ name: 'put_page', arguments: { slug: 'notes/bridge-seed-8543', content: '---\ntitle: Bridge seed\n---\nSeeded for the stdio bridge test.\n' } });
+ expect(put.isError ?? false).toBe(false);
+ } finally { await w.close(); }
+}, 240_000);
+
+afterAll(async () => {
+ await stopHost();
+ for (const d of [hostHome, ...tempDirs]) if (d) rmSync(d, { recursive: true, force: true });
+});
+
+describe('thin-client gbrain serve relays stdio to the remote brain', () => {
+ test('a read-only client sees exactly the host listing, reads round-trip, refusals are the host\'s own', async () => {
+ const home = thinHome(readCred);
+ const b = await bridge(home);
+ const d = await direct(readCred);
+ try {
+ const [viaBridge, viaHost] = [await b.client.listTools(), await d.client.listTools()];
+ expect(names(viaBridge)).toEqual(names(viaHost));
+ expect(names(viaBridge)).not.toContain('put_page');
+ expect(names(viaBridge)).not.toContain('file_upload');
+
+ const got = await b.client.callTool({ name: 'get_page', arguments: { slug: 'notes/bridge-seed-8543' } });
+ expect(got.isError ?? false).toBe(false);
+ expect(text(got)).toContain('Seeded for the stdio bridge test.');
+
+ const [missB, missH] = [await b.client.callTool({ name: 'get_page', arguments: { slug: 'notes/absent-8543' } }),
+ await d.client.callTool({ name: 'get_page', arguments: { slug: 'notes/absent-8543' } })];
+ expect(missB.isError).toBe(true);
+ expect(text(missB)).toBe(text(missH));
+
+ const [putB, putH] = [await b.client.callTool({ name: 'put_page', arguments: { slug: 'notes/denied-8543', content: 'x' } }),
+ await d.client.callTool({ name: 'put_page', arguments: { slug: 'notes/denied-8543', content: 'x' } })];
+ expect(putB.isError).toBe(true);
+ const withoutSessionNotices = (r: any) => { const { notices: _once, ...rest } = JSON.parse(text(r)); return rest; };
+ expect(withoutSessionNotices(putB)).toEqual(withoutSessionNotices(putH));
+ expect(withoutSessionNotices(putB).code).toBe('insufficient_scope');
+
+ const up = await b.client.callTool({ name: 'file_upload', arguments: { path: '/etc/hostname' } });
+ expect(up.isError).toBe(true);
+ expect(text(up)).toContain('unknown_tool');
+ expect(existsSync(join(home, '.gbrain')) ? readdirSync(join(home, '.gbrain')).filter(f => /pglite/i.test(f)) : []).toEqual([]);
+ } finally { await b.close(); await d.close(); }
+ }, 180_000);
+
+ test('a write client\'s put_page lands on the host and reads back', async () => {
+ const b = await bridge(thinHome(writeCred));
+ try {
+ const put = await b.client.callTool({ name: 'put_page', arguments: { slug: 'notes/bridge-write-8543', content: '---\ntitle: Bridged write\n---\nWritten through the bridge.\n' } });
+ expect({ isError: put.isError ?? false, body: put.isError ? text(put) : '' }).toEqual({ isError: false, body: '' });
+ } finally { await b.close(); }
+ const d = await direct(readCred);
+ try {
+ expect(text(await d.client.callTool({ name: 'get_page', arguments: { slug: 'notes/bridge-write-8543' } }))).toContain('Written through the bridge.');
+ } finally { await d.close(); }
+ }, 180_000);
+
+ test('a narrow surface lists only its tools, refuses the rest locally and widens per session', async () => {
+ const b = await bridge(thinHome(writeCred), ['--surface', 'starter', '--advertise', 'verbs']);
+ try {
+ const listed = names(await b.client.listTools());
+ expect(listed).toContain('request_tools');
+ const d = await direct(writeCred);
+ const hostListed = await (async () => { try { return names(await d.client.listTools()); } finally { await d.close(); } })();
+ expect(listed.length).toBeLessThan(hostListed.length);
+ const hidden = hostListed.find(n => !STARTER_OPS.has(n) && !listed.includes(n));
+ if (!hidden) throw new Error('no full-only tool on the host listing');
+ const refused = await b.client.callTool({ name: hidden, arguments: {} });
+ expect(refused.isError).toBe(true);
+ expect(text(refused)).toContain('unknown_tool');
+ expect(text(refused)).toContain('request_tools');
+ let changed = 0;
+ b.client.setNotificationHandler(ToolListChangedNotificationSchema, () => { changed++; });
+ const outside = await b.client.callTool({ name: 'request_tools', arguments: { tools: [hidden] } });
+ expect(outside.isError ?? false).toBe(false);
+ expect(text(outside)).toContain('request_tools {\\"surface\\":\\"full\\"}');
+ const inSurface = hostListed.find(n => STARTER_OPS.has(n) && !listed.includes(n));
+ if (!inSurface) throw new Error('no starter tool hidden by --advertise verbs');
+ const revealed = await b.client.callTool({ name: 'request_tools', arguments: { tools: [inSurface] } });
+ expect(revealed.isError ?? false).toBe(false);
+ for (let i = 0; i < 20 && changed === 0; i++) await Bun.sleep(100);
+ expect(changed).toBe(1);
+ const afterReveal = names(await b.client.listTools());
+ expect(afterReveal).toContain(inSurface);
+ expect(afterReveal).not.toContain(hidden);
+ const other = hostListed.find(n => !STARTER_OPS.has(n) && n !== hidden && !listed.includes(n));
+ if (!other) throw new Error('no second full-only tool on the host listing');
+ const before = await gbrain(hostHome, ['auth', 'clients', '--json']);
+ const widened = await b.client.callTool({ name: 'request_tools', arguments: { surface: 'full' } });
+ expect(widened.isError ?? false).toBe(false);
+ for (let i = 0; i < 20 && changed === 1; i++) await Bun.sleep(100);
+ expect(changed).toBe(2);
+ expect(names(await b.client.listTools())).toEqual(hostListed);
+ expect((await gbrain(hostHome, ['auth', 'clients', '--json'])).stdout).toBe(before.stdout);
+ } finally { await b.close(); }
+ }, 180_000);
+
+ test('stdout carries only JSON-RPC and stdin EOF exits 0 with no local brain', async () => {
+ const home = thinHome(readCred);
+ const child = Bun.spawn([process.execPath, '--no-env-file', CLI, 'serve'], { cwd: home, env: childEnv(home), stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });
+ const init = { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'raw', version: '1' } } };
+ child.stdin.write(JSON.stringify(init) + '\n');
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/list' }) + '\n');
+ const reader = child.stdout.getReader();
+ let out = '';
+ const deadline = Date.now() + 60_000;
+ while (!out.includes('"id":2') && Date.now() < deadline) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ out += new TextDecoder().decode(value);
+ }
+ child.stdin.end();
+ const code = await child.exited;
+ while (true) { const { value, done } = await reader.read(); if (done) break; out += new TextDecoder().decode(value); }
+ const stderr = await new Response(child.stderr).text();
+ for (const line of out.split('\n').filter(Boolean)) expect(JSON.parse(line).jsonrpc).toBe('2.0');
+ expect({ code, stderr: code ? stderr : '' }).toEqual({ code: 0, stderr: '' });
+ const files = readdirSync(home, { recursive: true }).map(String);
+ expect(files.filter(f => /pglite/i.test(f))).toEqual([]);
+ }, 120_000);
+
+ test('a revoked client is refused on the next call without restarting the bridge', async () => {
+ const cred = revokeCred;
+ const b = await bridge(thinHome(cred));
+ try {
+ expect((await b.client.callTool({ name: 'get_page', arguments: { slug: 'notes/bridge-seed-8543' } })).isError ?? false).toBe(false);
+ await stopHost();
+ const revoked = await gbrain(hostHome, ['auth', 'revoke-client', cred.id]);
+ await startHost();
+ expect({ exit: revoked.exitCode, out: revoked.exitCode ? revoked.stdout + revoked.stderr : '' }).toEqual({ exit: 0, out: '' });
+ const after = await b.client.callTool({ name: 'get_page', arguments: { slug: 'notes/bridge-seed-8543' } });
+ expect(after.isError).toBe(true);
+ expect(text(after)).not.toContain('Seeded for the stdio bridge test.');
+ expect(JSON.parse(text(after)).code).toBe('invalid_client');
+ expect(text(after)).not.toContain(cred.secret);
+ } finally { await b.close(); }
+ }, 180_000);
+
+ test('a page kept to a member stays invisible to an unbound credential through the bridge', async () => {
+ const b = await bridge(thinHome(readCred));
+ const d = await direct(readCred);
+ try {
+ const [viaB, viaH] = [await b.client.callTool({ name: 'get_page', arguments: { slug: 'notes/alice-example-private-8543' } }),
+ await d.client.callTool({ name: 'get_page', arguments: { slug: 'notes/alice-example-private-8543' } })];
+ expect(text(viaH)).not.toContain('kept-8543-zq');
+ expect(text(viaB)).not.toContain('kept-8543-zq');
+ expect(viaB.isError ?? false).toBe(viaH.isError ?? false);
+ const found = await b.client.callTool({ name: 'search', arguments: { query: 'kept-8543-zq' } });
+ expect(text(found)).not.toContain('kept-8543-zq');
+ } finally { await b.close(); await d.close(); }
+ }, 180_000);
+
+ test('a lost acknowledgment keeps the write identity, and a replay commits exactly once', async () => {
+ const seen: string[] = [];
+ let dropNextPut = true;
+ const proxy = Bun.serve({ port: 0, hostname: '127.0.0.1', async fetch(req) {
+ const url = new URL(req.url);
+ const body = req.method === 'POST' ? await req.text() : undefined;
+ const client = req.headers.get('x-gbrain-client');
+ if (client) seen.push(client);
+ const headers = new Headers(req.headers);
+ headers.delete('host');
+ const upstream = await fetch(`${base}${url.pathname}${url.search}`, { method: req.method, headers, body });
+ if (dropNextPut && body?.includes('"tools/call"') && body.includes('"put_page"')) {
+ dropNextPut = false;
+ await upstream.arrayBuffer();
+ return new Response('bad gateway', { status: 502 });
+ }
+ return new Response(upstream.body, { status: upstream.status, headers: upstream.headers });
+ } });
+ const b = await bridge(thinHome(writeCred, `http://127.0.0.1:${proxy.port}/mcp`));
+ try {
+ const args = { slug: 'notes/bridge-lost-ack-8543', content: '---\ntitle: Lost ack\n---\nOnce only.\n' };
+ const lost = await b.client.callTool({ name: 'put_page', arguments: args });
+ expect(lost.isError).toBe(true);
+ const env = JSON.parse(text(lost));
+ expect(env.code).toBe('write_outcome_unknown');
+ expect(env.submission_status).toBe('unknown');
+ expect(env.request_id).toMatch(/^[0-9a-f-]{36}$/);
+ const replay = await b.client.callTool({ name: 'put_page', arguments: { ...args, request_id: env.request_id } });
+ expect({ isError: replay.isError ?? false, body: replay.isError ? text(replay) : '' }).toEqual({ isError: false, body: '' });
+ const receipt = JSON.parse(text(await b.client.callTool({ name: 'get_write_request', arguments: { request_id: env.request_id } })));
+ expect(receipt.state).toBe('committed');
+ expect(JSON.parse(text(replay)).revision).toBe(receipt.revision);
+ const versions = await b.client.callTool({ name: 'get_versions', arguments: { slug: args.slug } });
+ expect(JSON.parse(text(versions))).toHaveLength(0);
+ expect(seen.length).toBeGreaterThan(0);
+ for (const h of seen) expect(h).toMatch(/^gbrain-stdio-bridge\/\S+$/);
+ } finally { await b.close(); proxy.stop(true); }
+ }, 180_000);
+
+ test('with MCP_STDIO=1 the bridge outlives stdin end and SIGTERM ends it like any gbrain process (143)', async () => {
+ const home = thinHome(readCred);
+ const child = Bun.spawn([process.execPath, '--no-env-file', CLI, 'serve'], { cwd: home, env: childEnv(home, { MCP_STDIO: '1' }), stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'raw', version: '1' } } }) + '\n');
+ const reader = child.stdout.getReader();
+ let out = '';
+ while (!out.includes('"id":1')) { const { value, done } = await reader.read(); if (done) break; out += new TextDecoder().decode(value); }
+ child.stdin.end();
+ await Bun.sleep(1500);
+ expect(child.exitCode).toBeNull();
+ child.kill('SIGTERM');
+ expect(await child.exited).toBe(143);
+ }, 120_000);
+
+ test('stdin EOF with a put_page still in flight delivers its receipt before exit', async () => {
+ const home = thinHome(writeCred);
+ const child = Bun.spawn([process.execPath, '--no-env-file', CLI, 'serve'], { cwd: home, env: childEnv(home), stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'raw', version: '1' } } }) + '\n');
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'put_page',
+ arguments: { slug: 'notes/bridge-eof-8543', content: '---\ntitle: EOF write\n---\nWritten at EOF.\n' } } }) + '\n');
+ child.stdin.end();
+ const [code, out] = [await child.exited, await new Response(child.stdout).text()];
+ const reply = out.split('\n').filter(Boolean).map(l => JSON.parse(l)).find(m => m.id === 2);
+ expect(code).toBe(0);
+ expect(reply?.result?.isError ?? false).toBe(false);
+ expect(JSON.parse(reply.result.content[0].text).slug).toBe('notes/bridge-eof-8543');
+ }, 120_000);
+
+ test('_meta reaches the host unchanged: identity is the credential\'s and a forbidden on_behalf_of is the host\'s refusal', async () => {
+ const b = await bridge(thinHome(readCred));
+ const d = await direct(readCred);
+ try {
+ const [whoB, whoH] = [await b.client.callTool({ name: 'whoami', arguments: {} }), await d.client.callTool({ name: 'whoami', arguments: {} })];
+ expect(text(whoH)).toContain(readCred.id);
+ expect(text(whoB)).toContain(readCred.id);
+ expect(JSON.parse(text(whoB)).scopes ?? null).toEqual(JSON.parse(text(whoH)).scopes ?? null);
+ const meta = { on_behalf_of: ['alice-example'] };
+ const [obB, obH] = [await b.client.callTool({ name: 'get_page', arguments: { slug: 'notes/bridge-seed-8543' }, _meta: meta }),
+ await d.client.callTool({ name: 'get_page', arguments: { slug: 'notes/bridge-seed-8543' }, _meta: meta })];
+ expect(obH.isError).toBe(true);
+ expect(obB.isError).toBe(true);
+ expect(JSON.parse(text(obB)).code).toBe(JSON.parse(text(obH)).code);
+ expect(text(obB)).not.toContain('Seeded for the stdio bridge test.');
+ } finally { await b.close(); await d.close(); }
+ }, 180_000);
+
+ test('doctor on a read-only thin client never recommends adding a scope', async () => {
+ const r = await gbrain(thinHome(readCred), ['doctor', '--json']);
+ const out = r.stdout + r.stderr;
+ expect(out).not.toMatch(/--scopes[ =]?[^\n"]*admin|read,write,admin|re-register/);
+ const scope = JSON.parse(r.stdout).checks?.find((x: any) => x.name === 'oauth_client_scopes_probe');
+ expect(scope?.status).toBe('ok');
+ }, 180_000);
+
+ test('host-only serve forms still refuse on a thin client', async () => {
+ const home = thinHome(readCred);
+ for (const args of [['serve', '--http'], ['serve', '--http', '--port', '3131'], ['serve', '--access', 'read-only']]) {
+ const r = await gbrain(home, args);
+ expect(r.exitCode).not.toBe(0);
+ expect(r.stderr + r.stdout).toContain('requires_local_engine');
+ }
+ }, 120_000);
+});
diff --git a/test/url-redact.test.ts b/test/url-redact.test.ts
index b74de533da..f8d82d94e4 100644
--- a/test/url-redact.test.ts
+++ b/test/url-redact.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'bun:test';
-import { redactPgUrl, redactDeep, redactUrlsInText } from '../src/core/url-redact.ts';
+import { redactPgUrl, redactDeep, redactUrlsInText, stripUrlSecrets } from '../src/core/url-redact.ts';
describe('redactPgUrl', () => {
test('strips userinfo from postgresql:// URL', () => {
@@ -121,3 +121,20 @@ describe('redactUrlsInText — libpq keyword/value form', () => {
.toBe('PASSWORD=*** sslpassword=*** host=h');
});
});
+
+describe('stripUrlSecrets — userinfo stops at the authority', () => {
+ const url = (...parts: string[]) => parts.join('');
+
+ test('an @ inside a query value never lets the token after it survive', () => {
+ expect(stripUrlSecrets(`see ${url('https://host.example/[email protected]&tok', 'en=qtok123')} now`))
+ .toBe('see https://host.example/mcp now');
+ });
+
+ test('an @ inside the path keeps the real host', () => {
+ expect(stripUrlSecrets(url('https://host.example/a/@b?tok', 'en=qtok123'))).toBe('https://host.example/a/@b');
+ });
+
+ test('userinfo holding an @ is still removed whole', () => {
+ expect(stripUrlSecrets(url('https://', 'u:p@ss', '@host.example/mcp'))).toBe('https://host.example/mcp');
+ });
+});