Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(mcp): lean search/query rows for remote callers and compact JSON results (cat40 cost wave C1+C2)

garrytanabc3182e206b
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index e784a2e7a0..ea2dd21404 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -41,7 +41,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ops/raw-data.ts` — `put_raw_data` / `get_raw_data`. `get_raw_data` follows the page soft-delete (a tombstoned page reads as `[]`, `restore_page` brings the rows back; there is no remote `include_deleted` param — `get_page include_deleted: true` verifies the tombstone) and, per #4352, a `visibility: private` page's raw data reads exactly like a missing page's for untrusted callers. Scope comes from `readPolicyOpts(ctx)`, never from MCP parameters.
-- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's scope holds pages of any kind below the safe-chunk index version (`hasUnsealedPagesInScope`: sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by the unsealed-only partial `pages_safe_chunk_pending_idx` — NOT the COALESCE `safeChunksFilter` form; pinned by `test/search-safe-index-probe.test.ts`; fail-open; retains source, private, quarantine and live-page policy), it appends the `safe_index_pending` degraded stage to empty and partial results alike, so neither reads as a clean or complete answer; the drain is `gbrain repair safe-chunks`. The withholding itself is unchanged. Empty and nonempty replies also carry projection_readiness, with projection_pending/projection_status_unknown degradation when appropriate. Vector candidate incompleteness and scoped pool details survive the public CLI/MCP serialization boundary; public type filters constrain the current-projection probe. Retrieval output copies and sanitizes result/metadata after grading and capture using the canonical scanner, before snippet truncation; internal pipeline/capture remains unredacted. The CLI formatter repeats this on JSON, explain and human output. System One: the `query` op asks S4 answerability (`decide.answerability`, diagnostic only) and surfaces `meta.answerability`; the crag escalation re-run keeps S2-S5 off (`rerankOnly`).
+- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's scope holds pages of any kind below the safe-chunk index version (`hasUnsealedPagesInScope`: sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by the unsealed-only partial `pages_safe_chunk_pending_idx` — NOT the COALESCE `safeChunksFilter` form; pinned by `test/search-safe-index-probe.test.ts`; fail-open; retains source, private, quarantine and live-page policy), it appends the `safe_index_pending` degraded stage to empty and partial results alike, so neither reads as a clean or complete answer; the drain is `gbrain repair safe-chunks`. The withholding itself is unchanged. Empty and nonempty replies also carry projection_readiness, with projection_pending/projection_status_unknown degradation when appropriate. Vector candidate incompleteness and scoped pool details survive the public CLI/MCP serialization boundary; public type filters constrain the current-projection probe. Retrieval output copies and sanitizes result/metadata after grading and capture using the canonical scanner, before snippet truncation; internal pipeline/capture remains unredacted. `searchOutput` then projects the returned rows to the caller's row shape (`src/core/search/lean-rows.ts`: lean for remote callers unless `fields: "full"`, the transport chose full rows, or the caller is trusted-local) and reports it as `retrieval.rows` for remote callers and whenever `fields` is passed. The CLI formatter repeats this on JSON, explain and human output. System One: the `query` op asks S4 answerability (`decide.answerability`, diagnostic only) and surfaces `meta.answerability`; the crag escalation re-run keeps S2-S5 off (`rerankOnly`).
- `src/core/ops/sources.ts` — `sources_remove` is confined to the caller's WRITE authority via `assertSourceInCallerWriteScope(ctx, id)` (context.ts): an untrusted caller may hard-remove only its own write source; a federated read grant naming a source does not make it removable; any other id answers `OperationError('not_found', 'Unknown source: <id>')`, byte-identical to a nonexistent source so the error is not an existence oracle. `sources_status` keeps the read-scope helper (`assertSourceInCallerScope`), so a federated grant can still diagnose a source it cannot remove. Trusted local CLI keeps the full operator view. Over HTTP every client carries a write source (registration default `default`) and its own `oauth_clients.source_id` row FK-RESTRICTs removing that source, so hard removal is effectively an operator action (`gbrain sources remove`); a source a remote `sources_admin` caller just created via `sources_add` stays outside its authority until the operator rescopes the client. There is no `sources_archive` op — archive lives in the CLI (`gbrain sources archive`). Pinned by `test/sources-mcp.test.ts` (federated-read-only id → not_found while status still answers; write-source id → removed; unbound → any; local → any; `remote: undefined` fail-closed) and `test/e2e/sources-remote-mcp.test.ts` (real server: not_found before AND after a read-grant widen; operator CLI completes; rescoping `--source` moves the authority).
diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.md
index 8551d87f55..3a131848c4 100644
--- a/docs/architecture/key-files/mcp.md
+++ b/docs/architecture/key-files/mcp.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `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` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, 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, and each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served), each producer isolated so one failure never drops another's key; empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. 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)`.
+- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `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` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, 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, and each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served), 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`. 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)`.
- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract. It is compile-time source text (no runtime filesystem dependency; static imports of pure core leaves are fine — the rule bans filesystem/dynamic loading) and is imported by the stdio SDK server, OAuth HTTP SDK server, and legacy raw HTTP initialize path so all transports return the same instructions without drift. The contract covers skill routing, untrusted-content posture, source scope, and the `put_page` whole-page replacement/read-before-write rule. Two append-only extensions compose on top of it, in a fixed order: `buildMcpInstructions({writeback?})` adds the opt-in ambient-writeback section (from `src/core/facts/writeback-instructions.ts`) when `memory.auto_writeback` is enabled — absent/off is BYTE-IDENTICAL to `GBRAIN_MCP_INSTRUCTIONS`, and three exact-equality transport pins depend on that; `resolveMcpInstructions(config, env?, { writeback? })` takes that composed base and appends the operator-set deployment identity LAST under a `Deployment identity:` banner (no transport can weaken the contract): `GBRAIN_MCP_INSTRUCTIONS` env wins when non-blank, else `mcp.instructions` from the FILE plane (`~/.gbrain/config.json`; `gbrain config set|unset mcp.instructions` route there via `FILE_PLANE_DOTTED_KEYS` in `src/commands/config.ts`); an empty or whitespace-only env value is UNSET, not an override, and blank identity + writeback off returns the byte-identical canonical contract. Every transport calls `resolveMcpInstructions` with its own writeback opts: stdio once at boot via the fail-closed resolver (restart-to-flip, the strict-params posture; read failure = OFF bundle, never a wrong visibility posture; a running `gbrain serve` also needs a restart to pick up a new identity); OAuth per request (write-scope-gated, and the section renders only when THIS token's actual visible set — surface filter + bound-client fence — can call `remember`; `extract_facts` advertised under the same predicates); legacy bearer per initialize (surface-clamped: a surface without `remember` gets no section). All three route availability through `ambientOptsFrom(wb, {remember, extractFacts})`. Pinned over a real SDK `StdioClientTransport` by `test/serve-stdio-roundtrip.test.ts`, over raw HTTP by `test/http-transport.test.ts`, the identity plane (incl. the three-way composition order) by `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`, and the enabled-state builder/parity matrix by `test/mcp-instructions-writeback.test.ts`.
@@ -11,6 +11,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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/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 listener (another serve) returns the null binding (that serve is the IPC provider). Reflex-channel event logging fires at DELIVERY (`onDelivered`/`onTurnContextDelivered`), never inside the resolver. Pinned by `test/resolve-ipc-binding.test.ts`.
- `src/mcp/server.ts` — MCP stdio server (generated from operations). `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`.
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index b1b0a64b85..d3fca5194c 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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`), 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). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and `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`). `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. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`.
+- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `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`). `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. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`.
- `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.
- `src/core/persistence/preview-approval.ts` — preview-bound approval shared by `jobs authorize-legacy --select`, `jobs cancel --select`, `repair stale-atoms` and `repair extractor-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>`). 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`).
diff --git a/docs/architecture/thin-client.md b/docs/architecture/thin-client.md
index 55b7e1f4ac..5d54e18b11 100644
--- a/docs/architecture/thin-client.md
+++ b/docs/architecture/thin-client.md
@@ -35,6 +35,14 @@ connectors) request exactly the hinted scope and never step up after an
Discovery excludes `agent`, which DCR cannot grant, while explicit DCR requests
for delegation remain rejected.
+**Result rows:** the thin client sends `X-Gbrain-Client: gbrain-remote-cli/<version>`
+on every request, so hosts serve it full `search`/`query` rows (renderers and
+`--explain` read the ranking diagnostics) while other remote callers get lean
+rows. It never sends `fields`, so `mcp.strict_params=reject` hosts of any
+version accept its calls. The header is unverified and selects a row shape
+only; CLIs that predate it get lean rows unless the host sets
+`mcp.result_rows: full`.
+
Keep general-purpose thin-client OAuth rows at `full` (or NULL). Native MCP
configurations can deliberately use starter/verbs to expose fewer tools. Stdio
serves the server-resolved surface directly, without a client row; per-client
diff --git a/docs/mcp/README.md b/docs/mcp/README.md
index bd5590fd00..e7c9b38282 100644
--- a/docs/mcp/README.md
+++ b/docs/mcp/README.md
@@ -35,3 +35,53 @@ Client-specific details: [ChatGPT](CHATGPT.md), [Claude Code](CLAUDE_CODE.md),
[Claude Desktop](CLAUDE_DESKTOP.md), [Codex](CODEX.md),
[opencode](OPENCODE.md), [Perplexity](PERPLEXITY.md),
[OpenClaw](OPENCLAW.md), and the [adapter reference](../guides/harness-adapters.md).
+
+## Search and query result rows
+
+`search` and `query` return their rows as compact JSON in the first content
+block. Remote callers get **lean rows** by default: the fields an agent acts
+on, without the ranking diagnostics that made each row several times longer
+than its evidence text.
+
+A lean row keeps `id` (the `fetch` key), `slug`, `title`, `type`,
+`chunk_text`, `score`, `effective_date`, `source_id`, `chunk_id` (with
+`slug` and `source_id`, the `assemble_evidence` hit), `evidence` and
+`create_safety` (the duplicate-page guard). It also keeps every safety or
+provenance marker that is present: `injection_suspected`, `injection_p`,
+`unverified`, `content_flag`, `status`, `superseded`, `superseded_by`,
+`message_id`, `thread_id`, `source_subject`, `modality` when not `text`,
+`stale` when true, and `delivered: {"truncated": true}` when evidence
+delivery cut the text.
+
+```json
+{"query": "acme-example renewal terms"}
+```
+
+```json
+[{"slug":"contracts/acme-example-msa","title":"MSA: Acme Example","type":"contract","chunk_text":"Payment terms: Net 45. Renewal is annual.","chunk_id":812,"score":0.91,"source_id":"default","effective_date":"2026-04-02","id":"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FjbWUtZXhhbXBsZS1tc2EiXQ","evidence":"keyword_exact","create_safety":"probable"}]
+```
+
+Pass `fields: "full"` to get every field (`page_id`, `chunk_index`,
+`chunk_source`, `keyword_hit`, `cosine`, `base_score`, boosts, rerank and
+graph signals, the full `delivered` object):
+
+```json
+{"query": "acme-example renewal terms", "fields": "full"}
+```
+
+`_meta.retrieval.rows` reports `"lean"` or `"full"` for every remote call.
+
+| Client | Rows by default | How to get full rows |
+| --- | --- | --- |
+| Any MCP client (stdio or HTTP) | lean | `fields: "full"` per call, or the host sets `gbrain config set mcp.result_rows full` |
+| gbrain thin CLI, this release or later | full (it sends `X-Gbrain-Client`) | nothing to do |
+| gbrain thin CLI, older release | lean | upgrade the CLI, or the host sets `mcp.result_rows full` |
+| Trusted local CLI (`gbrain search`, `gbrain call`) | full | nothing to do |
+
+The host setting is read per request over OAuth HTTP and at start-up for
+`gbrain serve` (stdio), so restart a stdio server after changing it. The
+`X-Gbrain-Client` header selects a row shape only; it is not an identity
+claim and never grants access.
+
+Say to your agent: *"Search my brain for the acme-example renewal terms and
+show me every ranking field for the top result."*
diff --git a/docs/protocol/MCP_META_CHANNELS.md b/docs/protocol/MCP_META_CHANNELS.md
index 0f9ff300a0..5c5de8619c 100644
--- a/docs/protocol/MCP_META_CHANNELS.md
+++ b/docs/protocol/MCP_META_CHANNELS.md
@@ -31,7 +31,7 @@ shape for it.
| Key | Producer | Contents |
|-----|----------|----------|
| `brain_hot_memory` | serve-http `metaHook` (`getBrainHotMemoryMeta`) | Hot-memory facts relevant to the call |
-| `retrieval` | `search`/`query` op handlers | `returned_count`, `retrieved_count`, `vector_enabled`, `expansion_applied`, `cache`, `token_budget`, `degraded[]` (closed stage vocabulary), `hint` (non-contractual prose) |
+| `retrieval` | `search`/`query` op handlers | `returned_count`, `retrieved_count`, `vector_enabled`, `expansion_applied`, `cache`, `token_budget`, `degraded[]` (closed stage vocabulary), `hint` (non-contractual prose), `rows` (`"lean"` or `"full"`: the row shape of content[0]; reported for remote callers and whenever `fields` is passed) |
| `warnings` | dispatch strict-params warn mode | `[{code: 'unknown_param', param, suggestion?}]` |
Inbound `_meta` (e.g. `_meta.session_id` inside tool ARGUMENTS) is a
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 65e75800a5..d32c4b76d4 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -64,4 +64,4 @@ src/core/think/index.ts runThink 450 seed: W5 baseline, refactor wave 1 (decompo
src/core/transcripts/ingest.ts runTranscriptsIngest 317 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/workspace-push.ts workspacePush 312 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/mcp/dispatch.ts dispatchToolCall 325 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 eval wave N5-1: hot-memory invalidation after mutating ops (success and failure paths)
-src/mcp/http-transport.ts startHttpTransport 408 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
+src/mcp/http-transport.ts startHttpTransport 409 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): dispatch resultRows from X-Gbrain-Client / mcp.result_rows (logic in mcp/result-rows.ts)
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index d0c6f75034..e5f50b98a7 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
-src/core/config.ts 1821 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys
+src/core/config.ts 1824 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts)
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 644 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso
diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.ts
index 94261106f0..344dfd7b99 100644
--- a/src/commands/serve-http-mcp.ts
+++ b/src/commands/serve-http-mcp.ts
@@ -22,6 +22,7 @@ import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback
import { hasScope, operationScopesAllowed } from '../core/scope.ts';
import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult, acceptedPendingReceipt, type ToolResult } from '../mcp/dispatch.ts';
import { resolveStrictParamsMode } from '../mcp/validate-params.ts';
+import { GBRAIN_CLIENT_HEADER, resolveResultRowsMode, resultRowsForRequest, type ResultRowsMode } from '../mcp/result-rows.ts';
import { buildToolDefs } from '../mcp/tool-defs.ts';
import {
filterOpsForSurface,
@@ -47,6 +48,8 @@ interface McpRequestState {
surface: McpSurface;
surfaceCeiling: McpSurface;
surfaceAllowedOps: ReadonlySet<string> | undefined;
+ /** C1: search/query row shape for this request (thin-client header, else host `mcp.result_rows`). */
+ resultRows: ResultRowsMode;
}
export function mountMcp(app: Express, ctx: ServeHttpContext): void {
@@ -138,16 +141,20 @@ export function mountMcp(app: Express, ctx: ServeHttpContext): void {
// can call it (surface + scope + bound-client fence — the same
// predicates tools/list applies).
const canWrite = hasScope(authInfo.scopes, 'write');
- const [{ ceiling: surfaceCeiling, effective: surface }, writeback] = await Promise.all([
+ const [{ ceiling: surfaceCeiling, effective: surface }, writeback, hostResultRows] = await Promise.all([
resolveEffectiveSurface(authInfo),
canWrite ? resolveWritebackConfig(engine, config) : Promise.resolve(null),
+ resolveResultRowsMode(engine, config),
]);
+ // C1: gbrain's thin client keeps full rows. The header is unverified and
+ // selects a row shape only; it never gates anything security-relevant.
+ const resultRows = resultRowsForRequest(req.get(GBRAIN_CLIENT_HEADER), hostResultRows);
const mcpOperations = filterOpsForSurface(mcpOperationsBase, surface)
.filter(op => authInfo.allowedOperations == null || authInfo.allowedOperations.includes(op.name));
authInfo.effectiveSurface = surface;
const surfaceAllowedOps: ReadonlySet<string> | undefined =
surface === 'full' && authInfo.allowedOperations == null ? undefined : new Set(mcpOperations.map(o => o.name));
- const state: McpRequestState = { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps };
+ const state: McpRequestState = { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps, resultRows };
const server = createMcpRequestServer(ctx, state, writeback);
await serveMcpRequest(server, req, res);
});
@@ -264,7 +271,7 @@ async function listMcpTools(ctx: ServeHttpContext, state: McpRequestState) {
async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, request: CallToolRequest): Promise<ToolResult> {
const { engine, broadcastEvent, logFullParams } = ctx;
- const { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps } = state;
+ const { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps, resultRows } = state;
const { name, arguments: params } = request.params;
const op = mcpOperations.find(o => o.name === name);
if (!op) {
@@ -364,6 +371,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, reques
surface,
// WP4 (D2): request_tools bounds its catalog + persist by this.
surfaceCeiling,
+ resultRows,
// v0.31 follow-up fix: thread auth so the whoami op (and any
// future scope-aware handlers) can introspect the caller. The
// original D12/eE1 refactor moved dispatch into dispatchToolCall
diff --git a/src/core/config.ts b/src/core/config.ts
index 12ef0346a2..97281774bd 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -549,6 +549,8 @@ export interface GBrainConfig {
* over this file slot. Always bounded by the server ceiling (D2).
*/
default_surface_dcr?: 'verbs' | 'starter' | 'full';
+ /** Search/query row shape for remote MCP callers: 'lean' (default) | 'full'. Dual-plane, DB > file. */
+ result_rows?: 'lean' | 'full';
};
}
@@ -1530,6 +1532,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// WP3 — unknown tool-call argument posture ('warn' default | 'reject').
// Read dual-plane by src/mcp/validate-params.ts (DB > file > 'warn').
'mcp.strict_params',
+ 'mcp.result_rows', // C1 row shape, read dual-plane by src/mcp/result-rows.ts
// Skill-nag suppression (#2180): brain-resident pack install nag off-switch.
'skillpack.nag_disabled',
// Self-upgrade (v0.42; file plane, read on the hot path)
diff --git a/src/core/mcp-client.ts b/src/core/mcp-client.ts
index 82d9545177..c9528fc9ec 100644
--- a/src/core/mcp-client.ts
+++ b/src/core/mcp-client.ts
@@ -27,6 +27,8 @@ import { anySignal } from './abort-check.ts';
import type { GBrainConfig } from './config.ts';
import { discoverOAuth, mintClientCredentialsToken } from './remote-mcp-probe.ts';
import { isWriteErrorCode, isWriteReceipt, isWriteRequestId, publicWriteReceipt, type WriteErrorCode, type WriteReceipt } from './persistence/types.ts';
+import { GBRAIN_CLIENT_HEADER, GBRAIN_THIN_CLIENT_NAME } from '../mcp/result-rows.ts';
+import { VERSION } from '../version.ts';
interface CachedToken {
access_token: string;
@@ -293,6 +295,9 @@ async function buildClient(mcpUrl: string, accessToken: string, signal?: AbortSi
requestInit: {
headers: {
'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}`,
},
},
fetch: (input, init) => fetch(input, {
@@ -301,7 +306,7 @@ async function buildClient(mcpUrl: string, accessToken: string, signal?: AbortSi
}),
});
const client = new Client(
- { name: 'gbrain-remote-cli', version: '1' },
+ { name: GBRAIN_THIN_CLIENT_NAME, version: '1' },
{ capabilities: {} },
);
try {
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 88378f01c6..63da1a69b2 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -390,6 +390,15 @@ export interface OperationContext {
* (persistence/write-wait.ts).
*/
writeWaitMs?: number;
+ /**
+ * Row shape for `search`/`query` results in content[0]. Set by the MCP
+ * transports: 'full' for gbrain's own thin client (X-Gbrain-Client header)
+ * and for hosts with `mcp.result_rows: full`, otherwise 'lean'. Unset means
+ * 'lean' for remote callers; trusted local callers (`remote === false`)
+ * always get full rows. A per-call `fields: "full"` overrides 'lean'.
+ * Shape only, never authority: nothing security-relevant reads it.
+ */
+ resultRows?: 'lean' | 'full';
/**
* Resolved global CLI options (--quiet / --progress-json / --progress-interval).
* CLI callers populate this from `getCliOptions()`. MCP / library callers
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index cc5dde0e9c..5e2bdf7603 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -25,6 +25,7 @@ import type { HybridSearchMeta, SearchResult } from '../types.ts';
import { bumpLastRetrievedAt } from '../last-retrieved.ts';
import { applySnippetCap, DEFAULT_AGENT_SNIPPET_CHARS } from '../search/snippet-cap.ts';
import { redactRetrievalOutput } from '../search/output-redaction.ts';
+import { projectRows, resultRowsFor } from '../search/lean-rows.ts';
import { assembleEvidenceForHits, capDeliveredSnippets, deliverEvidence, effectivePlan, resolveEvidencePlan, unsupportedDelivery, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';
import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';
@@ -67,22 +68,38 @@ async function resolveEffectiveLimit(ctx: OperationContext, p: Record<string, un
type SourceScope = { sourceId?: string; sourceIds?: string[] };
-function searchOutput(ctx: OperationContext, results: SearchResult[], meta: Record<string, unknown>, snippetCap: number,
+/**
+ * The returned rows: redacted, snippet-capped, then projected to the caller's
+ * row shape (C1: lean for remote callers unless `fields: "full"`, the host's
+ * `mcp.result_rows: full` or gbrain's thin client). Every internal consumer
+ * (capture, response meta, last-retrieved bump) has already read full rows.
+ */
+function searchOutput(ctx: OperationContext, p: Record<string, unknown>, results: SearchResult[], meta: Record<string, unknown>, snippetCap: number,
evidence?: { delivery: DeliveryMeta; explicitSnippet: boolean }): SearchResult[] {
+ const rows = resultRowsFor(ctx, p.fields);
+ // The shape is reported where it can vary: remote callers, or an explicit `fields`.
+ const shown = ctx.remote !== false || p.fields !== undefined ? { rows } : {};
if (!evidence) {
- const output = redactRetrievalOutput(results, meta);
+ const output = redactRetrievalOutput(results, { ...meta, ...shown });
ctx.emitResponseMeta?.('retrieval', output.meta);
- return applySnippetCap(output.results, snippetCap);
+ return projectRows(applySnippetCap(output.results, snippetCap), rows);
}
// Evidence delivery: explicit snippet_chars wins over the delivered blocks;
// otherwise the blocks are returned whole (their budget already bounds
// them). The cap runs before the meta is emitted so it can report itself.
- const output = redactRetrievalOutput(results, { ...meta, delivery: evidence.delivery });
+ const output = redactRetrievalOutput(results, { ...meta, delivery: evidence.delivery, ...shown });
const capped = evidence.explicitSnippet ? capDeliveredSnippets(output.results, snippetCap, output.meta.delivery) : output.results;
ctx.emitResponseMeta?.('retrieval', output.meta);
- return capped;
+ return projectRows(capped, rows);
}
+/** C1: the per-call row-shape escape hatch shared by `search` and `query` (`detail` is query's low/medium/high). */
+const FIELDS_PARAM = {
+ type: 'string' as const,
+ enum: ['lean', 'full'],
+ description: "Row fields. Remote callers get 'lean' rows by default; 'full' adds every ranking diagnostic.",
+};
+
/** Evidence delivery params shared by `search` and `query`. */
const RETURN_UNIT_PARAM = {
type: 'string' as const,
@@ -137,7 +154,7 @@ async function withEvidence(ctx: OperationContext, p: Record<string, unknown>, r
async function evidenceOutput(ctx: OperationContext, p: Record<string, unknown>, results: SearchResult[], plan: EvidencePlan | null, scope: DeliveryScope,
meta: HybridSearchMeta | null, snippetCap: number, buildMeta: (rows: SearchResult[]) => Promise<Record<string, unknown>>): Promise<SearchResult[]> {
const ev = await withEvidence(ctx, p, results, plan, scope, meta);
- return searchOutput(ctx, ev.rows, await buildMeta(ev.rows), snippetCap, ev.evidence);
+ return searchOutput(ctx, p, ev.rows, await buildMeta(ev.rows), snippetCap, ev.evidence);
}
/**
@@ -516,6 +533,7 @@ const search: Operation = {
"Recency boost (per-prefix age decay, no mattering signal): 'off' | 'on' | 'strong'. " +
'Omit and gbrain auto-detects. Independent of `salience`. Ignored on the keyword-only opt-out path.',
},
+ fields: FIELDS_PARAM,
},
handler: async (ctx, p) => {
const startedAt = Date.now();
@@ -656,6 +674,7 @@ const query: Operation = {
token_budget: { type: 'number', description: "Token budget. Chunk mode, and whenever return_unit is omitted: caps the cumulative chunk payload (results that would overflow are skipped). Explicit non-chunk return_unit: the budget for delivered evidence (default search.return_budget_default = 6000, auto 24000; remote max search.return_budget_max_remote = 32000)." },
expand: { type: 'boolean', description: 'Request multi-query expansion (default: true in every search mode, regardless of search.expansion). Set false to opt out. Requires configured embedding and expansion providers; a cloud expander receives the query and may charge for the call. Response metadata expansion_applied reports whether variants were actually used.' },
detail: { type: 'string', description: 'Result detail level: low (compiled truth only), medium (default, all with dedup), high (all chunks)' },
+ fields: FIELDS_PARAM,
mode: { type: 'string', description: 'Search mode (conservative|balanced|tokenmax). Local callers only; remote uses configured mode.' },
// v0.20.0 Cathedral II Layer 10 C1/C2: language + symbol-kind filters.
lang: { type: 'string', description: 'Filter to chunks where content_chunks.language matches (e.g., typescript, python, ruby)' },
@@ -816,7 +835,7 @@ const query: Operation = {
})).map(r => ({ ...r }));
stampDeepResearchIds(results);
imageMeta.retrieved_count = results.length;
- return searchOutput(ctx, results, { ...await buildRetrievalResponseMeta(ctx, querySourceScope, queryText ?? '', results, imageMeta, { types }), ...(plan && (plan.unit !== 'auto' || plan.explicitUnit) ? { delivery: unsupportedDelivery(plan, 'image_query_unsupported') } : {}) }, snippetCap);
+ return searchOutput(ctx, p, results, { ...await buildRetrievalResponseMeta(ctx, querySourceScope, queryText ?? '', results, imageMeta, { types }), ...(plan && (plan.unit !== 'auto' || plan.explicitUnit) ? { delivery: unsupportedDelivery(plan, 'image_query_unsupported') } : {}) }, snippetCap);
}
if (!queryText) {
diff --git a/src/core/search/lean-rows.ts b/src/core/search/lean-rows.ts
new file mode 100644
index 0000000000..bd5316feb7
--- /dev/null
+++ b/src/core/search/lean-rows.ts
@@ -0,0 +1,54 @@
+/**
+ * Lean `search`/`query` rows for remote callers.
+ *
+ * A full row averages about 1.2k characters, of which the evidence text is
+ * 200-460; the rest is ranking diagnostics (page_id, chunk_index,
+ * chunk_source, keyword_hit, cosine, base_score, boosts, rerank and graph
+ * signals) that agents do not read but pay for on every later turn. A lean
+ * row keeps what an agent acts on:
+ * - identity and text: id (the deep-research fetch key), slug, title, type,
+ * chunk_text, score, effective_date, source_id, chunk_id (assemble_evidence
+ * takes {source_id, slug, chunk_id});
+ * - the duplicate-page guard: evidence and create_safety;
+ * - safety and provenance markers whenever present: injection_suspected,
+ * injection_p, unverified, content_flag, status, superseded, superseded_by,
+ * message_id, thread_id, source_subject; modality when not text; stale
+ * only when true;
+ * - `delivered: { truncated: true }` whenever evidence delivery truncated.
+ * `fields: "full"`, the `mcp.result_rows: full` host config and gbrain's own
+ * thin client get every field; trusted local callers always do.
+ */
+
+import type { OperationContext } from '../ops/contract.ts';
+
+export type ResultRows = 'lean' | 'full';
+
+const KEPT_FIELDS: ReadonlySet<string> = new Set([
+ 'id', 'slug', 'title', 'type', 'chunk_text', 'score', 'effective_date', 'source_id', 'chunk_id',
+ 'evidence', 'create_safety',
+ 'injection_suspected', 'injection_p', 'unverified', 'content_flag', 'status', 'superseded', 'superseded_by',
+ 'message_id', 'thread_id', 'source_subject',
+]);
+
+/** Explicit `fields` wins; then trusted local callers get full rows; then the transport's choice (default lean). */
+export function resultRowsFor(ctx: Pick<OperationContext, 'remote' | 'resultRows'>, fields: unknown): ResultRows {
+ if (fields === 'lean' || fields === 'full') return fields;
+ if (ctx.remote === false) return 'full';
+ return ctx.resultRows ?? 'lean';
+}
+
+export function leanRow(row: Record<string, unknown>): Record<string, unknown> {
+ const out: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(row)) {
+ if (value === undefined || (value === null && key !== 'effective_date')) continue;
+ if (KEPT_FIELDS.has(key)) out[key] = value;
+ else if (key === 'stale' && value === true) out[key] = true;
+ else if (key === 'modality' && value !== 'text') out[key] = value;
+ else if (key === 'delivered' && (value as { truncated?: unknown }).truncated === true) out[key] = { truncated: true };
+ }
+ return out;
+}
+
+export function projectRows<T>(rows: T[], shape: ResultRows): T[] {
+ return shape === 'full' ? rows : rows.map(r => leanRow(r as Record<string, unknown>) as T);
+}
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 1b60119fa2..b67a33f0cf 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -238,6 +238,8 @@ export interface DispatchOpts {
surfaceCeiling?: 'verbs' | 'starter' | 'full';
/** #5232: commit wait for coordinated writes (OperationContext.writeWaitMs); unset = agent default. */
writeWaitMs?: number;
+ /** C1: search/query row shape chosen by the transport (OperationContext.resultRows); unset = lean for remote callers. */
+ resultRows?: OperationContext['resultRows'];
}
/**
@@ -535,6 +537,7 @@ export function buildOperationContext(
...(opts.explicitReadBinding ? { explicitReadBinding: opts.explicitReadBinding } : {}),
...(opts.surfaceCeiling ? { surfaceCeiling: opts.surfaceCeiling } : {}),
...(opts.writeWaitMs !== undefined ? { writeWaitMs: opts.writeWaitMs } : {}),
+ ...(opts.resultRows ? { resultRows: opts.resultRows } : {}),
auth: opts.auth,
};
}
@@ -762,7 +765,10 @@ export async function dispatchToolCall(
...(name === 'remember' && typeof r?.status === 'string' ? { remember_status: r.status } : {}),
});
}
- const out: ToolResult = { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
+ // C2: compact JSON. Every result stays in the agent's context and is
+ // re-sent on each later turn; indentation was about a fifth of a search
+ // result. Error envelopes below stay indented (small and rare).
+ const out: ToolResult = { content: [{ type: 'text', text: JSON.stringify(result) }] };
// D8: model-visible loudness for empty retrievals. The body stays a bare
// array (D3 — deployed thin-clients parse content[0] only), and a SECOND
// text block carries the diagnosis the model actually sees. Structured
diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.ts
index 986fa13158..4a3270f385 100644
--- a/src/mcp/http-transport.ts
+++ b/src/mcp/http-transport.ts
@@ -38,6 +38,7 @@ import { operations, operationsByName, opAllowedForBoundClient } from '../core/o
import type { AuthInfo } from '../core/operations.ts';
import { VERSION } from '../version.ts';
import { dispatchToolCall, requestLogStatusForResult } from './dispatch.ts';
+import { GBRAIN_CLIENT_HEADER, resolveResultRowsMode, resultRowsForRequest } from './result-rows.ts';
import { parseStrictParamsMode } from './validate-params.ts';
import { filterOpsForSurface, clampSurface, type McpSurface } from './surface.ts';
import { disabledOpsForPublishGates } from './publish-gates.ts';
@@ -538,6 +539,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
// WP4 (D2): this transport has no per-client rows, so its surface
// IS the ceiling request_tools bounds catalog + persist by.
surfaceCeiling: surface,
+ resultRows: resultRowsForRequest(req.headers.get(GBRAIN_CLIENT_HEADER), await resolveResultRowsMode(engine, fileConfig)), // C1; row shape only, never authority
});
// Same status taxonomy as the OAuth transport (denied_after_list /
// success_with_warnings feed the amendment-33 metric + E4 usage).
diff --git a/src/mcp/result-rows.ts b/src/mcp/result-rows.ts
new file mode 100644
index 0000000000..2bc8f88e42
--- /dev/null
+++ b/src/mcp/result-rows.ts
@@ -0,0 +1,56 @@
+/**
+ * Row shape for `search`/`query` results served to remote MCP callers.
+ *
+ * Remote callers get lean rows by default (the projection lives in
+ * src/core/search/lean-rows.ts). Two host-side escape hatches restore full
+ * rows without any change on the client: the `mcp.result_rows: full` host
+ * config (every remote caller), and the `X-Gbrain-Client` header gbrain's own
+ * thin client sends (src/core/mcp-client.ts), so the CLI's renderers and
+ * `--explain` keep every field. A caller can also pass `fields: "full"`.
+ *
+ * The header is unverified: any HTTP client can send it. It selects a row
+ * shape and nothing else; it must never gate authority, scope, visibility or
+ * any other security-relevant decision.
+ */
+
+import type { BrainEngine } from '../core/engine.ts';
+import type { GBrainConfig } from '../core/config.ts';
+
+export type ResultRowsMode = 'lean' | 'full';
+
+/** HTTP header gbrain's thin client sends on every request: `gbrain-remote-cli/<version>`. */
+export const GBRAIN_CLIENT_HEADER = 'X-Gbrain-Client';
+export const GBRAIN_THIN_CLIENT_NAME = 'gbrain-remote-cli';
+
+export function parseResultRowsMode(v: unknown): ResultRowsMode | null {
+ return v === 'lean' || v === 'full' ? v : null;
+}
+
+/** True when an `X-Gbrain-Client` header value names gbrain's thin client. */
+export function isGbrainThinClient(header: string | null | undefined): boolean {
+ return typeof header === 'string'
+ && (header === GBRAIN_THIN_CLIENT_NAME || header.startsWith(`${GBRAIN_THIN_CLIENT_NAME}/`));
+}
+
+/**
+ * Dual-plane `mcp.result_rows`: the DB plane wins, the file plane is the
+ * fallback, absent or unparseable on both = 'lean'. A failed DB read falls to
+ * the file plane; resolving a row shape never takes a request down.
+ */
+export async function resolveResultRowsMode(
+ engine: BrainEngine,
+ config: GBrainConfig | null | undefined,
+): Promise<ResultRowsMode> {
+ try {
+ const dbMode = parseResultRowsMode(await engine.getConfig('mcp.result_rows'));
+ if (dbMode) return dbMode;
+ } catch {
+ // Engine without a config table / transient error: the file plane decides.
+ }
+ return parseResultRowsMode(config?.mcp?.result_rows) ?? 'lean';
+}
+
+/** The row shape for one HTTP request: the thin-client header wins, then the host mode. */
+export function resultRowsForRequest(clientHeader: string | null | undefined, hostMode: ResultRowsMode): ResultRowsMode {
+ return isGbrainThinClient(clientHeader) ? 'full' : hostMode;
+}
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 31560138cc..4ee1e220d6 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -10,6 +10,7 @@ import { dispatchToolCall, buildOperationContext } from './dispatch.ts';
import { validateParams, parseStrictParamsMode } from './validate-params.ts';
import { filterOpsForSurface, allowedOpNames, clampSurface, isReadOnlyOperation, type McpAccess, type McpSurface } from './surface.ts';
import { disabledOpsForPublishGates } from './publish-gates.ts';
+import { parseResultRowsMode, resolveResultRowsMode } from './result-rows.ts';
import type { Operation } from '../core/operations.ts';
import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';
import { loadConfig } from '../core/config.ts';
@@ -281,6 +282,13 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// `mcp.strict_params` flip needs a serve restart here (deliberate; the
// OAuth HTTP path re-reads dual-plane per request).
const strictParams = parseStrictParamsMode(config?.mcp?.strict_params) === 'reject';
+ // C1: search/query row shape for this pipe, resolved once at boot like
+ // strict_params (restart to flip). Stdio has no thin-client identity: the
+ // thin client only speaks HTTP.
+ // A degraded engine is not touched: the file plane decides.
+ const resultRows = isEngineDegraded(engine)
+ ? parseResultRowsMode(config?.mcp?.result_rows) ?? 'lean'
+ : await resolveResultRowsMode(engine, config);
// Generate tool definitions from operations. Extracted to buildToolDefs so
// the subagent tool registry (v0.15+) can call the same mapper against a
@@ -362,6 +370,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// WP4 (D2): stdio has no per-client rows; its surface is the ceiling
// request_tools bounds its catalog by (persist no-ops without auth).
surfaceCeiling: surface,
+ resultRows,
});
}));
diff --git a/test/bootstrap-harness-lifecycle.serial.test.ts b/test/bootstrap-harness-lifecycle.serial.test.ts
index 3f2cd79454..83a82d9835 100644
--- a/test/bootstrap-harness-lifecycle.serial.test.ts
+++ b/test/bootstrap-harness-lifecycle.serial.test.ts
@@ -210,7 +210,7 @@ describe('bootstrap harness lifecycle E2E (PGLite + real serve --http)', () => {
expect(result).toBe(0);
// real smoke against the live serve — identity round-tripped over bearer
expect(out).toMatch(/smoke test:/);
- expect(out).toMatch(/"engine": "pglite"/);
+ expect(out).toMatch(/"engine":"pglite"/); // C2: tool results are compact JSON
// the sandbox held: nothing touched the operator's real user scope
expect(out).not.toContain(`${process.env.HOME}/.claude/settings.json`);
diff --git a/test/e2e/evidence-delivery-leak.test.ts b/test/e2e/evidence-delivery-leak.test.ts
index dbff06fba5..2290ed8fdf 100644
--- a/test/e2e/evidence-delivery-leak.test.ts
+++ b/test/e2e/evidence-delivery-leak.test.ts
@@ -408,7 +408,7 @@ for (const backend of backends) describe(`evidence delivery leak canaries (${bac
assertNoLeak('mid-flight edit', after.results, ['EDITSECRETCANARY']);
expect(JSON.stringify(after.results)).toContain('EDITEDPUBLICLINE');
// Private flip between ranking and expansion.
- const hits = await operations.find(o => o.name === 'search')!.handler(ctxOf(true), { query: 'heron editable EDITEDPUBLICLINE', source_id: BOUND, limit: 50 }) as SearchResult[];
+ const hits = await operations.find(o => o.name === 'search')!.handler(ctxOf(true), { query: 'heron editable EDITEDPUBLICLINE', source_id: BOUND, limit: 50, fields: 'full' }) as SearchResult[];
const editHit = hits.filter(h => h.slug === 'notes/heron-edit');
expect(editHit.length).toBeGreaterThan(0);
await importPage('notes/heron-edit', BOUND, `---\ntitle: heron edit\ntype: note\nvisibility: private\n---\n\nheron editable page. EDITEDPUBLICLINE replaced.\n\n${filler(6)}\n`);
diff --git a/test/e2e/evidence-delivery-parity.test.ts b/test/e2e/evidence-delivery-parity.test.ts
index 34ab19ef2a..dbeaf574c1 100644
--- a/test/e2e/evidence-delivery-parity.test.ts
+++ b/test/e2e/evidence-delivery-parity.test.ts
@@ -22,7 +22,7 @@ import type { SearchResult } from '../../src/core/types.ts';
import { operations, type OperationContext } from '../../src/core/operations.ts';
import { evidenceFingerprint, pageEvidenceText } from '../../src/core/search/evidence-delivery.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
-import { captureOffPath, seedOffPath } from '../helpers/evidence-delivery-fixture.ts';
+import { captureOffPath, seedOffPath, withCostWave } from '../helpers/evidence-delivery-fixture.ts';
const FIXTURE = join(import.meta.dir, '../fixtures/goldens/evidence-delivery/off-path.json');
const backends = process.env.DATABASE_URL ? ['pglite', 'postgres'] as const : ['pglite'] as const;
@@ -67,7 +67,7 @@ describe('evidence delivery parity', () => {
await engine.setConfig('think.return_unit', 'chunk');
try {
const got = await captureOffPath(engine);
- for (const key of Object.keys(want)) expect(`${key}: ${got[key]}`).toBe(`${key}: ${want[key]}`);
+ for (const key of Object.keys(want)) expect(`${key}: ${got[key]}`).toBe(`${key}: ${withCostWave(key, want[key])}`);
} finally {
await engine.executeRaw(`DELETE FROM config WHERE key IN ('search.return_unit', 'think.return_unit')`);
}
@@ -78,8 +78,9 @@ describe('evidence delivery parity', () => {
let expanded = 0;
for (const remote of [false, true]) {
for (const query of ['ocelot', 'ocelot renewal roadmap']) {
- const hits = await op('search').handler(ctxOf(engine, remote), { query, return_unit: 'chunk' }) as SearchResult[];
- const viaDefault = await op('search').handler(ctxOf(engine, remote), { query }) as SearchResult[];
+ // fields: 'full': these checks compare complete rows (page_id, delivered) with assemble_evidence.
+ const hits = await op('search').handler(ctxOf(engine, remote), { fields: 'full', query, return_unit: 'chunk' }) as SearchResult[];
+ const viaDefault = await op('search').handler(ctxOf(engine, remote), { fields: 'full', query }) as SearchResult[];
const viaAssemble = await op('assemble_evidence').handler(ctxOf(engine, remote), {
hits: hits.map(h => ({ source_id: h.source_id, slug: h.slug, chunk_id: h.chunk_id })), return_unit: 'auto',
}) as { results: SearchResult[] };
@@ -99,7 +100,7 @@ describe('evidence delivery parity', () => {
test(`page evidence is byte-identical to the stored body minus frontmatter and protected content (${backend})`, async () => {
const engine = engines[backend]!;
for (const remote of [false, true]) {
- const rows = await op('search').handler(ctxOf(engine, remote), { query: 'ocelot', return_unit: 'page', token_budget: 32000 }) as SearchResult[];
+ const rows = await op('search').handler(ctxOf(engine, remote), { fields: 'full', query: 'ocelot', return_unit: 'page', token_budget: 32000 }) as SearchResult[];
expect(rows.length).toBeGreaterThan(0);
for (const r of rows) {
const [page] = await engine.executeRaw<{ compiled_truth: string; timeline: string }>('SELECT compiled_truth, timeline FROM pages WHERE id = $1', [r.page_id]);
@@ -111,17 +112,17 @@ describe('evidence delivery parity', () => {
test(`search/query and assemble_evidence deliver identical evidence for the same hits (${backend})`, async () => {
const engine = engines[backend]!;
for (const remote of [false, true]) {
- const hits = await op('search').handler(ctxOf(engine, remote), { query: 'ocelot' }) as SearchResult[];
+ const hits = await op('search').handler(ctxOf(engine, remote), { fields: 'full', query: 'ocelot' }) as SearchResult[];
expect(hits.length).toBeGreaterThan(0);
for (const unit of UNITS) {
- const viaSearch = await op('search').handler(ctxOf(engine, remote), { query: 'ocelot', return_unit: unit, token_budget: 2500 }) as SearchResult[];
+ const viaSearch = await op('search').handler(ctxOf(engine, remote), { fields: 'full', query: 'ocelot', return_unit: unit, token_budget: 2500 }) as SearchResult[];
const viaAssemble = await op('assemble_evidence').handler(ctxOf(engine, remote), {
hits: hits.map(h => ({ source_id: h.source_id, slug: h.slug, chunk_id: h.chunk_id })), return_unit: unit, token_budget: 2500,
}) as { results: SearchResult[] };
expect(evidenceFingerprint(viaAssemble.results)).toBe(evidenceFingerprint(viaSearch));
}
- const qHits = await op('query').handler(ctxOf(engine, remote), { query: 'ocelot pricing', expand: false }) as SearchResult[];
- const viaQuery = await op('query').handler(ctxOf(engine, remote), { query: 'ocelot pricing', expand: false, return_unit: 'page', token_budget: 2500 }) as SearchResult[];
+ const qHits = await op('query').handler(ctxOf(engine, remote), { fields: 'full', query: 'ocelot pricing', expand: false }) as SearchResult[];
+ const viaQuery = await op('query').handler(ctxOf(engine, remote), { fields: 'full', query: 'ocelot pricing', expand: false, return_unit: 'page', token_budget: 2500 }) as SearchResult[];
const viaAssemble = await op('assemble_evidence').handler(ctxOf(engine, remote), {
hits: qHits.map(h => ({ source_id: h.source_id, slug: h.slug, chunk_id: h.chunk_id })), return_unit: 'page', token_budget: 2500,
}) as { results: SearchResult[] };
@@ -135,8 +136,8 @@ describe('evidence delivery parity', () => {
const [a, b] = [engines.pglite!, engines.postgres!];
const textOf = (rows: SearchResult[]) => rows.map(r => [r.slug, r.chunk_text, r.delivered?.unit, r.delivered?.tokens, r.delivered?.truncated]);
for (const unit of [...UNITS, undefined]) {
- const ra = await op('search').handler(ctxOf(a), { query: 'ocelot', return_unit: unit, token_budget: 2500 }) as SearchResult[];
- const rb = await op('search').handler(ctxOf(b), { query: 'ocelot', return_unit: unit, token_budget: 2500 }) as SearchResult[];
+ const ra = await op('search').handler(ctxOf(a), { fields: 'full', query: 'ocelot', return_unit: unit, token_budget: 2500 }) as SearchResult[];
+ const rb = await op('search').handler(ctxOf(b), { fields: 'full', query: 'ocelot', return_unit: unit, token_budget: 2500 }) as SearchResult[];
expect(textOf(rb)).toEqual(textOf(ra));
}
const windows = async (engine: BrainEngine) => {
diff --git a/test/e2e/legacy-chunk-privacy.test.ts b/test/e2e/legacy-chunk-privacy.test.ts
index 2c4b714058..11b48db575 100644
--- a/test/e2e/legacy-chunk-privacy.test.ts
+++ b/test/e2e/legacy-chunk-privacy.test.ts
@@ -89,7 +89,9 @@ for (const kind of ['pglite', 'postgres'] as const) {
};
}
- const call = (ctx: OperationContext, name: string, args: Record<string, unknown>) => operationsByName[name].handler(ctx, args);
+ // search/query rows are read for page_id, a diagnostic remote callers get only with fields: 'full'.
+ const call = (ctx: OperationContext, name: string, args: Record<string, unknown>) =>
+ operationsByName[name].handler(ctx, name === 'search' || name === 'query' ? { ...args, fields: 'full' } : args);
async function legacy(slug: string, sourceId: string, body: string, text: string, timeline = ''): Promise<number> {
const page = await engine.putPage(slug, {
diff --git a/test/e2e/mcp-search-transport-matrix.test.ts b/test/e2e/mcp-search-transport-matrix.test.ts
index acf479b4eb..2226eb531b 100644
--- a/test/e2e/mcp-search-transport-matrix.test.ts
+++ b/test/e2e/mcp-search-transport-matrix.test.ts
@@ -45,7 +45,8 @@ async function stop(child: ChildProcess): Promise<void> {
}
async function search(client: Client, query: string, source_id?: string) {
- const result = await client.callTool({ name: 'search', arguments: { query, ...(source_id ? { source_id } : {}) } });
+ // fields: 'full' — this matrix reads ranking diagnostics (cosine), which remote rows omit by default.
+ const result = await client.callTool({ name: 'search', arguments: { query, fields: 'full', ...(source_id ? { source_id } : {}) } });
expect(result.isError, toolDiagnostic('search', result)).not.toBe(true);
const content = result.content as Array<{ type: string; text: string }>;
const rows = JSON.parse(content[0]!.text) as Array<{ slug: string; source_id: string; cosine?: number }>;
diff --git a/test/evidence-delivery-golden.test.ts b/test/evidence-delivery-golden.test.ts
index 5e4e995097..b9a474584f 100644
--- a/test/evidence-delivery-golden.test.ts
+++ b/test/evidence-delivery-golden.test.ts
@@ -10,7 +10,9 @@
* count, recall field order, think excerpting), or auto touching a
* non-conversation hit. The fixture was generated by this same file on the
* release before evidence delivery (refactor wave 1, 9a0e01b4) and must not
- * be regenerated on a branch that changes the off path.
+ * be regenerated on a branch that changes the off path. The cost wave's two
+ * declared remote-output changes (lean rows, compact MCP JSON) are applied to
+ * the frozen bytes by `withCostWave`, not regenerated into them.
*
* The Postgres arm lives in test/e2e/evidence-delivery-parity.test.ts.
*/
@@ -19,7 +21,7 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import type { SearchResult } from '../src/core/types.ts';
-import { captureOffPath, OFF_PATH_PAGES, seedOffPath } from './helpers/evidence-delivery-fixture.ts';
+import { captureOffPath, OFF_PATH_PAGES, seedOffPath, withCostWave } from './helpers/evidence-delivery-fixture.ts';
const FIXTURE = join(import.meta.dir, 'fixtures/goldens/evidence-delivery/off-path.json');
const CONVERSATION = 'chat/session-a';
@@ -59,7 +61,7 @@ describe('evidence delivery off path', () => {
}
const want = JSON.parse(readFileSync(FIXTURE, 'utf8')) as Record<string, string>;
expect(Object.keys(got).sort()).toEqual(Object.keys(want).sort());
- for (const key of Object.keys(want)) expect(`${key}: ${got[key]}`).toBe(`${key}: ${want[key]}`);
+ for (const key of Object.keys(want)) expect(`${key}: ${got[key]}`).toBe(`${key}: ${withCostWave(key, want[key])}`);
});
test('an explicit return_unit chunk is byte-identical to the pre-feature release', async () => {
@@ -67,7 +69,7 @@ describe('evidence delivery off path', () => {
const got = await captureOffPath(engine);
const keys = Object.keys(want).filter(k => k.endsWith(':chunk'));
expect(keys.length).toBeGreaterThan(5);
- for (const key of keys) expect(`${key}: ${got[key]}`).toBe(`${key}: ${want[key]}`);
+ for (const key of keys) expect(`${key}: ${got[key]}`).toBe(`${key}: ${withCostWave(key, want[key])}`);
});
test('the implied auto default is byte-identical to chunk on a corpus without conversations', async () => {
@@ -83,10 +85,10 @@ describe('evidence delivery off path', () => {
const got = await captureOffPath(engine);
let expanded = 0;
for (const key of ['search', 'search-remote', 'query', 'query-low']) {
- const frozen = (JSON.parse(want[key]) as { result: SearchResult[] }).result;
+ const frozen = (JSON.parse(withCostWave(key, want[key])) as { result: SearchResult[] }).result;
const auto = JSON.parse(got[key]) as { result: SearchResult[] };
if (!auto.result.some(r => r.slug === CONVERSATION)) {
- expect(`${key}: ${got[key]}`).toBe(`${key}: ${want[key]}`);
+ expect(`${key}: ${got[key]}`).toBe(`${key}: ${withCostWave(key, want[key])}`);
continue;
}
const others = auto.result.filter(r => r.slug !== CONVERSATION).map(({ delivered, ...r }) => {
diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.json
index 8eedf7dff5..86c02f3c3b 100644
--- a/test/fixtures/goldens/cli/help-and-errors.json
+++ b/test/fixtures/goldens/cli/help-and-errors.json
@@ -689,6 +689,7 @@
" --token-budget Token budget. Chunk mode, and whenever return_unit is omitted: caps the cumulative chunk payload (results that would overflow are skipped). Explicit non-chunk return_unit: the budget for delivered evidence (default search.return_budget_default = 6000, auto 24000; remote max search.return_budget_max_remote = 32000).",
" --expand Request multi-query expansion (default: true in every search mode, regardless of search.expansion). Set false to opt out. Requires configured embedding and expansion providers; a cloud expander receives the query and may charge for the call. Response metadata expansion_applied reports whether variants were actually used.",
" --detail Result detail level: low (compiled truth only), medium (default, all with dedup), high (all chunks)",
+ " --fields Row fields. Remote callers get 'lean' rows by default; 'full' adds every ranking diagnostic.",
" --mode Search mode (conservative|balanced|tokenmax). Local callers only; remote uses configured mode.",
" --lang Filter to chunks where content_chunks.language matches (e.g., typescript, python, ruby)",
" --symbol-kind Filter to chunks where content_chunks.symbol_type matches (e.g., function, class, method, type, interface)",
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index f4ec1add0a..ac6dc76c01 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 209860,
- "stdoutSha256": "1ec5b407e08b2b2333a2f5fe2c24561fa47447bb9303de69902a0bfe562610df",
+ "stdoutBytes": 210416,
+ "stdoutSha256": "04c1305a174bd8b1967a39df87e39dd3818325c5197d6bbe48c8f2833dcb808d",
"toolNames": [
"remember",
"entity",
@@ -819,6 +819,7 @@
"description": "Cheap hybrid search (vector + keyword + RRF) with no LLM expansion. Best for exact known tokens, names, and structured-field lookups. A populated result set is NOT proof of coverage — for concept / synonym / landscape questions use `query` (adds multi-query expansion); for exhaustive enumeration use list_pages pagination. Pass `return_unit` ('window' / 'section' / 'page') for whole evidence instead of chunks; conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). For personal/emotional questions, prefer get_recent_salience or find_anomalies — they surface activity bursts without needing a search term. For code-symbol questions (callers, callees, definitions, blast radius), use code_callers / code_callees / code_def / code_refs instead — those return structural graph data, not text chunks. For agent memory reads (saved facts + budget-packed retrieval), prefer the `recall` verb.",
"name": "search",
"parameters": {
+ "fields": "string?",
"limit": "number?",
"mode": "string?",
"offset": "number?",
@@ -834,6 +835,14 @@
},
"schema": {
"properties": {
+ "fields": {
+ "description": "Row fields. Remote callers get 'lean' rows by default; 'full' adds every ranking diagnostic.",
+ "enum": [
+ "lean",
+ "full"
+ ],
+ "type": "string"
+ },
"limit": {
"description": "Max results (default 20)",
"type": "number"
@@ -919,6 +928,7 @@
"detail": "string?",
"embedding_column": "string?",
"expand": "boolean?",
+ "fields": "string?",
"image": "string?",
"image_mime": "string?",
"lang": "string?",
@@ -973,6 +983,14 @@
"description": "Request multi-query expansion (default: true in every search mode, regardless of search.expansion). Set false to opt out. Requires configured embedding and expansion providers; a cloud expander receives the query and may charge for the call. Response metadata expansion_applied reports whether variants were actually used.",
"type": "boolean"
},
+ "fields": {
+ "description": "Row fields. Remote callers get 'lean' rows by default; 'full' adds every ranking diagnostic.",
+ "enum": [
+ "lean",
+ "full"
+ ],
+ "type": "string"
+ },
"image": {
"description": "Base64-encoded image bytes for image-similarity search (CLI: --image <path>).",
"type": "string"
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 99970b8152..56416c2457 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -2468,7 +2468,7 @@
"hooks?: { stop_push_debounce_min?: number | string; } | undefined",
"integrations?: { memorable?: { enabled?: boolean; }; } | undefined",
"litellm_api_key?: string | undefined",
- "mcp?: { instructions?: string; publish_skills?: boolean; publish_advisor?: boolean; skills_dir?: string; strict_params?: \"warn\" | \"reject\"; default_surface_dcr?: \"verbs\" | \"starter\" | \"full\"; } | undefined",
+ "mcp?: { instructions?: string; publish_skills?: boolean; publish_advisor?: boolean; skills_dir?: string; strict_params?: \"warn\" | \"reject\"; default_surface_dcr?: \"verbs\" | \"starter\" | \"full\"; result_rows?: \"lean\" | \"full\"; } | undefined",
"mcp_surface?: \"verbs\" | \"starter\" | \"full\" | undefined",
"memory?: { auto_writeback?: string; auto_writeback_transient_ttl?: string; visibility_posture?: string; } | undefined",
"openai_api_key?: string | undefined",
@@ -5437,6 +5437,7 @@
"localSourceImplicit?: boolean | undefined",
"logger: Logger",
"remote: boolean",
+ "resultRows?: \"full\" | \"lean\" | undefined",
"sessionId?: string | undefined",
"sourceId: string",
"subagentId?: number | undefined",
diff --git a/test/helpers/evidence-delivery-fixture.ts b/test/helpers/evidence-delivery-fixture.ts
index 84356cfeef..f93b6c9ebd 100644
--- a/test/helpers/evidence-delivery-fixture.ts
+++ b/test/helpers/evidence-delivery-fixture.ts
@@ -12,6 +12,7 @@ import { runThink } from '../../src/core/think/index.ts';
import { prepareMarkdownChunks } from '../../src/core/markdown-chunks.ts';
import { installFixtureChunks } from './page-projection.ts';
import { withEnv } from './with-env.ts';
+import { leanRow } from '../../src/core/search/lean-rows.ts';
export const OFF_PATH_PAGES: Array<{ slug: string; body: string; timeline?: string; frontmatter?: Record<string, unknown> }> = [
{
@@ -76,6 +77,33 @@ export async function captureOffPath(engine: BrainEngine): Promise<Record<string
return out;
}
+const leanRetrieval = (meta: Record<string, unknown>) => ({ ...meta, rows: 'lean' });
+
+/**
+ * The cost wave changes remote output on purpose: C1 projects remote
+ * search/query rows to lean rows (and reports `rows: "lean"` in the retrieval
+ * meta), and C2 serializes MCP content[0] as compact JSON. The frozen
+ * pre-feature bytes stay as captured; this applies exactly those two declared
+ * transforms to them, so every other byte of the capture is still compared.
+ */
+export function withCostWave(key: string, frozen: string): string {
+ const base = key.replace(/:chunk$/, '');
+ if (base === 'search-remote') {
+ const v = JSON.parse(frozen) as { result: Record<string, unknown>[]; meta: Array<{ key: string; value: Record<string, unknown> }> };
+ return JSON.stringify({
+ result: v.result.map(leanRow),
+ meta: v.meta.map(m => m.key === 'retrieval' ? { key: m.key, value: leanRetrieval(m.value) } : m),
+ });
+ }
+ if (!base.startsWith('mcp-')) return frozen;
+ const res = JSON.parse(frozen) as { content: Array<{ type: string; text: string }>; _meta?: Record<string, Record<string, unknown>> };
+ const body = JSON.parse(res.content[0].text);
+ const lean = base === 'mcp-search' || base === 'mcp-query';
+ res.content[0].text = JSON.stringify(lean ? (body as Record<string, unknown>[]).map(leanRow) : body);
+ if (lean && res._meta?.retrieval) res._meta.retrieval = leanRetrieval(res._meta.retrieval);
+ return JSON.stringify(res);
+}
+
export async function seedOffPath(engine: BrainEngine, pages = OFF_PATH_PAGES): Promise<void> {
for (const p of pages) {
await engine.putPage(p.slug, { type: 'note', title: p.slug, compiled_truth: p.body, timeline: p.timeline ?? '', frontmatter: p.frontmatter ?? {} });
diff --git a/test/mcp-backup-nag.serial.test.ts b/test/mcp-backup-nag.serial.test.ts
index c8ef6e643f..bcc8881d66 100644
--- a/test/mcp-backup-nag.serial.test.ts
+++ b/test/mcp-backup-nag.serial.test.ts
@@ -111,6 +111,11 @@ type CallOpts = { remote?: boolean; transport?: 'stdio' | 'http' };
// Default transport is 'stdio' — the ONLY transport the notice fires on.
// Trust-pin tests pass 'http' / undefined explicitly.
+/** Remote callers get lean rows (C1): the fixture row minus its page_id diagnostic. */
+function leanResults(): unknown[] {
+ return nextResults.map(r => { const { page_id: _p, ...lean } = r as Record<string, unknown>; return lean; });
+}
+
function callSearch(opts: CallOpts = {}) {
return dispatchToolCall(engineStub, 'search', { query: 'anything at all' }, {
remote: true,
@@ -171,7 +176,7 @@ describe('maybeAttachBackupNotice (stdio aggregate block)', () => {
const first = await callSearch({ remote: true, transport: 'stdio' });
expect(first.isError).toBeUndefined();
// content[0] is UNCHANGED — still the bare op result.
- expect(JSON.parse(first.content[0].text)).toEqual(nextResults);
+ expect(JSON.parse(first.content[0].text)).toEqual(leanResults());
// The backup block rides as an EXTRA block.
expect(first.content.length).toBe(2);
const block = first.content[1].text;
@@ -182,7 +187,7 @@ describe('maybeAttachBackupNotice (stdio aggregate block)', () => {
// Once per process: the second call carries NO backup block.
const second = await callSearch({ remote: true, transport: 'stdio' });
expect(second.content.length).toBe(1);
- expect(JSON.parse(second.content[0].text)).toEqual(nextResults);
+ expect(JSON.parse(second.content[0].text)).toEqual(leanResults());
});
test("transport 'http' + warn cache → NO block (stdio-only notice); a later stdio call still gets it", async () => {
@@ -190,7 +195,7 @@ describe('maybeAttachBackupNotice (stdio aggregate block)', () => {
const http = await callSearch({ remote: true, transport: 'http' });
expect(http.content.length).toBe(1);
- expect(JSON.parse(http.content[0].text)).toEqual(nextResults);
+ expect(JSON.parse(http.content[0].text)).toEqual(leanResults());
// The http call must not burn the once-per-process flag or arm the
// hourly latch — the first stdio call still attaches the block.
@@ -203,7 +208,7 @@ describe('maybeAttachBackupNotice (stdio aggregate block)', () => {
saveBackupStatus(warnStatus());
const out = await callSearch({ remote: true, transport: undefined });
expect(out.content.length).toBe(1);
- expect(JSON.parse(out.content[0].text)).toEqual(nextResults);
+ expect(JSON.parse(out.content[0].text)).toEqual(leanResults());
});
test('aggregate block never leaks local paths or source ids', async () => {
diff --git a/test/mcp-client.test.ts b/test/mcp-client.test.ts
index a284a5df5c..096a50b34a 100644
--- a/test/mcp-client.test.ts
+++ b/test/mcp-client.test.ts
@@ -25,6 +25,7 @@ import {
import type { GBrainConfig } from '../src/core/config.ts';
import { discoverOAuth, mintClientCredentialsToken } from '../src/core/remote-mcp-probe.ts';
import { withEnv } from './helpers/with-env.ts';
+import { VERSION } from '../src/version.ts';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
let server: ReturnType<typeof Bun.serve>;
@@ -45,6 +46,7 @@ let onHangClosed: (() => void) | undefined;
let toolExecutions = 0;
let initializeTokens: string[] = [];
let toolArguments: Record<string, unknown>[] = [];
+let clientHeaders: Array<string | null> = [];
function intercept(stage: Stage, req: Request): Response | Promise<Response> | undefined {
requests[stage] = (requests[stage] ?? 0) + 1;
@@ -91,6 +93,7 @@ beforeAll(() => {
if (path === '/mcp' && req.method === 'POST') {
const body = await req.json() as { id?: number; method: string; params?: { protocolVersion?: string } };
if (body.method === 'initialize') initializeTokens.push(req.headers.get('authorization') ?? '');
+ clientHeaders.push(req.headers.get('x-gbrain-client'));
if (body.method === 'tools/call') toolArguments.push((body.params as any)?.arguments ?? {});
const intercepted = intercept(body.method as Stage, req);
if (intercepted) return intercepted;
@@ -135,6 +138,7 @@ beforeEach(() => {
mcpResponseFor = () => ({ content: [{ type: 'text', text: JSON.stringify({ ok: true }) }] });
_clearMcpClientTokenCache();
toolArguments = [];
+ clientHeaders = [];
});
function makeConfig(): GBrainConfig {
@@ -230,6 +234,20 @@ describe('callRemoteTool — happy path', () => {
});
});
+describe('callRemoteTool — thin-client identity (C1)', () => {
+ test('every MCP request names gbrain\'s thin client so hosts keep full search rows', async () => {
+ await callRemoteTool(makeConfig(), 'search', { query: 'x' });
+ expect(clientHeaders.length).toBeGreaterThanOrEqual(2);
+ for (const h of clientHeaders) expect(h).toBe(`gbrain-remote-cli/${VERSION}`);
+ });
+
+ test('the thin client never sends `fields`, so strict-params hosts of any version accept its calls', async () => {
+ await callRemoteTool(makeConfig(), 'search', { query: 'x' });
+ await callRemoteTool(makeConfig(), 'query', { query: 'x' });
+ for (const args of toolArguments) expect(args).not.toHaveProperty('fields');
+ });
+});
+
describe('callRemoteTool — HTTP authentication boundaries', () => {
for (const stage of ['initialize', 'tools/call'] as const) {
test(`${stage}: one HTTP 401 refreshes once and executes the tool once`, async () => {
diff --git a/test/mcp-result-rows-skew.test.ts b/test/mcp-result-rows-skew.test.ts
new file mode 100644
index 0000000000..7a8a1f76da
--- /dev/null
+++ b/test/mcp-result-rows-skew.test.ts
@@ -0,0 +1,240 @@
+/**
+ * C1 version skew (DX-1, DX-2, DX-16): who gets lean and who gets full
+ * `search`/`query` rows, across client and host versions and transports.
+ *
+ * client host transport rows
+ * new thin CLI (X-Gbrain-Client) new OAuth HTTP full
+ * new thin CLI new, strict_params=reject OAuth HTTP full, accepted
+ * new thin CLI old (no `fields`, header any HTTP unchanged: it sends no
+ * unknown) `fields` (test/mcp-client.test.ts)
+ * old thin CLI (no header) new OAuth HTTP lean; `mcp.result_rows: full` -> full
+ * new / old thin CLI new legacy bearer HTTP full with header, lean without
+ * third-party MCP client new stdio lean; `fields: "full"` or host
+ * `mcp.result_rows: full` -> full;
+ * reject mode accepts `fields`
+ * Old CLI renderers read slug/score/chunk_text/stale only, which lean rows keep.
+ *
+ * Fails when: the thin client loses full rows (renderers, --explain), the
+ * host-wide escape hatch stops working on a transport, or strict hosts
+ * refuse a call the thin client makes.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { Server } from 'node:http';
+import { spawnSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import express from 'express';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { buildServeHttpApp } from '../src/commands/serve-http.ts';
+import { startHttpTransport } from '../src/mcp/http-transport.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { serializeMarkdown } from '../src/core/markdown.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { callRemoteTool, unpackToolResult, _clearMcpClientTokenCache } from '../src/core/mcp-client.ts';
+import { resetStrictParamsModeCache } from '../src/mcp/validate-params.ts';
+import { formatResult } from '../src/cli.ts';
+import { keylessBrainEnv } from './helpers/provider-env.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+type Row = Record<string, unknown>;
+const isFull = (rows: Row[]) => rows.length > 0 && rows.every(r => 'page_id' in r && 'chunk_source' in r);
+const isLean = (rows: Row[]) => rows.length > 0 && rows.every(r => !('page_id' in r) && !('chunk_source' in r) && 'chunk_id' in r && 'id' in r);
+
+let engine: PGLiteEngine;
+let server: Server;
+let base: string;
+let clientId: string;
+let clientSecret: string;
+let token: string;
+
+async function json<T>(res: Response): Promise<T> {
+ expect(res.status).toBe(200);
+ const text = await res.text();
+ const data = text.split('\n').find(l => l.startsWith('data:'));
+ return JSON.parse(data ? data.slice('data:'.length) : text) as T;
+}
+
+/** A raw MCP POST: what an old thin CLI or any third-party HTTP client sends (no X-Gbrain-Client). */
+async function rawCall(name: string, args: Row, headers: Record<string, string> = {}): Promise<{ isError?: boolean; content: Array<{ text: string }> }> {
+ const rpc = await json<{ result: { isError?: boolean; content: Array<{ text: string }> } }>(await fetch(`${base}/mcp`, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', ...headers },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }),
+ }));
+ return rpc.result;
+}
+
+const thinConfig = () => ({
+ engine: 'postgres' as const,
+ remote_mcp: { issuer_url: base, mcp_url: `${base}/mcp`, oauth_client_id: clientId, oauth_client_secret: clientSecret },
+});
+
+async function thinCall(name: string, args: Row): Promise<Row[]> {
+ return unpackToolResult<Row[]>(await callRemoteTool(thinConfig() as never, name, args));
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (const [slug, body] of [['notes/ocelot-pricing', 'Ocelot pricing is tiered by seat.'], ['notes/ocelot-roadmap', 'The ocelot roadmap ships pricing changes next quarter.']]) {
+ await importFromContent(engine, slug, serializeMarkdown({}, body, '', { type: 'note', title: slug, tags: [] }), { noEmbed: true, forceRechunk: true });
+ }
+ const app = express();
+ server = await new Promise(resolve => { const s = app.listen(0, '127.0.0.1', () => resolve(s)); });
+ const port = (server.address() as { port: number }).port;
+ base = `http://127.0.0.1:${port}`;
+ const built = await buildServeHttpApp(app, engine, { port, tokenTtl: 3600, enableDcr: false, publicUrl: base });
+ const login = await fetch(`${base}/admin/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: built.bootstrapToken }) });
+ const cookie = login.headers.get('set-cookie')!.split(';')[0];
+ const reg = await json<{ clientId: string; clientSecret: string }>(await fetch(`${base}/admin/api/register-client`, {
+ method: 'POST', headers: { Cookie: cookie, 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'skew-client', scopes: 'read write', grantTypes: ['client_credentials'] }),
+ }));
+ ({ clientId, clientSecret } = reg);
+ token = (await json<{ access_token: string }>(await fetch(`${base}/token`, {
+ method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret, scope: 'read write' }),
+ }))).access_token;
+}, 120_000);
+
+afterAll(async () => {
+ _clearMcpClientTokenCache();
+ await new Promise<void>(resolve => { server?.closeAllConnections?.(); server?.close(() => resolve()); });
+ await engine?.disconnect();
+});
+
+describe('OAuth HTTP host', () => {
+ test('new thin CLI: full rows for search and query without sending fields', async () => {
+ expect(isFull(await thinCall('search', { query: 'ocelot pricing' }))).toBe(true);
+ expect(isFull(await thinCall('query', { query: 'ocelot pricing', expand: false }))).toBe(true);
+ });
+
+ test('old thin CLI or third-party client (no header): lean rows; fields "full" restores them', async () => {
+ expect(isLean(JSON.parse((await rawCall('search', { query: 'ocelot pricing' })).content[0].text))).toBe(true);
+ expect(isFull(JSON.parse((await rawCall('search', { query: 'ocelot pricing', fields: 'full' })).content[0].text))).toBe(true);
+ });
+
+ test('a header naming another client is not the thin client', async () => {
+ const res = await rawCall('search', { query: 'ocelot pricing' }, { 'X-Gbrain-Client': 'someone-else/1.0' });
+ expect(isLean(JSON.parse(res.content[0].text))).toBe(true);
+ });
+
+ test('host mcp.result_rows: full serves full rows to every remote caller, restart-free', async () => {
+ await engine.setConfig('mcp.result_rows', 'full');
+ try {
+ expect(isFull(JSON.parse((await rawCall('search', { query: 'ocelot pricing' })).content[0].text))).toBe(true);
+ } finally {
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'mcp.result_rows'`);
+ }
+ expect(isLean(JSON.parse((await rawCall('search', { query: 'ocelot pricing' })).content[0].text))).toBe(true);
+ });
+
+ test('strict_params=reject: the thin client still works, fields is accepted, an unknown key is refused', async () => {
+ await engine.setConfig('mcp.strict_params', 'reject');
+ resetStrictParamsModeCache();
+ try {
+ expect(isFull(await thinCall('search', { query: 'ocelot pricing' }))).toBe(true);
+ expect((await rawCall('search', { query: 'ocelot pricing', fields: 'full' })).isError).not.toBe(true);
+ expect((await rawCall('search', { query: 'ocelot pricing', row_fields: 'full' })).isError).toBe(true);
+ } finally {
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'mcp.strict_params'`);
+ resetStrictParamsModeCache();
+ }
+ });
+
+ test('the CLI renderer an old thin client uses reads only fields lean rows keep', async () => {
+ const rows = JSON.parse((await rawCall('search', { query: 'ocelot pricing' })).content[0].text) as Row[];
+ const out = formatResult('search', rows, {});
+ for (const r of rows) expect(out).toContain(`] ${r.slug} -- `);
+ });
+});
+
+describe('legacy bearer HTTP transport', () => {
+ test('header -> full rows, no header -> lean rows, host config -> full rows', async () => {
+ const legacy = await withEnv({ GBRAIN_HOME: mkdtempSync(join(tmpdir(), 'gbrain-skew-legacy-')) }, () => startHttpTransport({ port: 0, engine }));
+ const { token: bearer } = await mintLegacyToken(engine, { name: 'skew-legacy', takesHolders: ['world'], scopes: ['read'] });
+ const call = async (headers: Record<string, string> = {}) => {
+ const res = await fetch(`http://127.0.0.1:${(legacy as { port: number }).port}/mcp`, {
+ method: 'POST', headers: { Authorization: `Bearer ${bearer}`, 'Content-Type': 'application/json', ...headers },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'search', arguments: { query: 'ocelot pricing' } } }),
+ });
+ const body = await res.json() as { result: { content: Array<{ text: string }> } };
+ return JSON.parse(body.result.content[0].text) as Row[];
+ };
+ try {
+ expect(isFull(await call({ 'X-Gbrain-Client': 'gbrain-remote-cli/0.0.0' }))).toBe(true);
+ expect(isLean(await call())).toBe(true);
+ await engine.setConfig('mcp.result_rows', 'full');
+ expect(isFull(await call())).toBe(true);
+ } finally {
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'mcp.result_rows'`);
+ (legacy as { stop: (force?: boolean) => void }).stop(true);
+ }
+ });
+});
+
+describe('stdio host (third-party MCP client)', () => {
+ let home: string;
+
+ const run = (env: Record<string, string>, ...args: string[]) => {
+ const r = spawnSync('bun', ['--no-env-file', 'run', 'src/cli.ts', ...args], { cwd: process.cwd(), env, encoding: 'utf8' });
+ if (r.status !== 0) throw new Error(`${args.join(' ')} failed: ${r.stderr}`);
+ };
+
+ /** One `gbrain serve` session; closed before the next CLI write (PGLite has one holder). */
+ async function session<T>(env: Record<string, string>, fn: (client: Client) => Promise<T>): Promise<T> {
+ const transport = new StdioClientTransport({ command: 'bun', args: ['--no-env-file', 'run', 'src/cli.ts', 'serve'], cwd: process.cwd(), env });
+ const client = new Client({ name: 'third-party-agent', version: '1' }, { capabilities: {} });
+ await client.connect(transport);
+ try { return await fn(client); } finally { await client.close(); }
+ }
+
+ const rows = async (client: Client, args: Row) => {
+ const res = await client.callTool({ name: 'search', arguments: { query: 'ocelot pricing', ...args } });
+ expect(res.isError).not.toBe(true);
+ return JSON.parse((res.content as Array<{ text: string }>)[0].text) as Row[];
+ };
+
+ let env: Record<string, string>;
+ beforeAll(() => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-skew-stdio-'));
+ env = keylessBrainEnv(process.env, home, { DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_REMOTE_CLIENT_SECRET: undefined }) as Record<string, string>;
+ delete env.GBRAIN_SOURCE;
+ run(env, 'init', '--pglite', '--no-embedding', '--non-interactive');
+ const notes = join(home, 'notes');
+ mkdirSync(notes, { recursive: true });
+ writeFileSync(join(notes, 'ocelot.md'), '---\ntitle: Ocelot pricing\n---\n\nOcelot pricing is tiered by seat.\n');
+ run(env, 'import', notes, '--no-embed');
+ }, 120_000);
+
+ afterAll(() => { if (home) rmSync(home, { recursive: true, force: true }); });
+
+ test('lean by default; fields "full" restores full rows', async () => {
+ await session(env, async client => {
+ expect(isLean(await rows(client, {}))).toBe(true);
+ expect(isFull(await rows(client, { fields: 'full' }))).toBe(true);
+ });
+ }, 60_000);
+
+ test('host mcp.result_rows: full (read at serve start) serves full rows', async () => {
+ run(env, 'config', 'set', 'mcp.result_rows', 'full');
+ try {
+ expect(await session(env, async client => isFull(await rows(client, {})))).toBe(true);
+ } finally {
+ run(env, 'config', 'unset', 'mcp.result_rows');
+ }
+ }, 60_000);
+
+ test('strict_params=reject accepts fields', async () => {
+ run(env, 'config', 'set', 'mcp.strict_params', 'reject');
+ try {
+ expect(await session(env, async client => isFull(await rows(client, { fields: 'full' })))).toBe(true);
+ } finally {
+ run(env, 'config', 'unset', 'mcp.strict_params');
+ }
+ }, 60_000);
+});
diff --git a/test/mcp-result-size-ceiling.test.ts b/test/mcp-result-size-ceiling.test.ts
new file mode 100644
index 0000000000..b8b5a70ffb
--- /dev/null
+++ b/test/mcp-result-size-ceiling.test.ts
@@ -0,0 +1,93 @@
+/**
+ * E3 + C2 (cost wave): the model-visible size of a canonical remote `search`
+ * and `query` result on a deterministic fixture brain, pinned beside the C3
+ * schema ceiling (test/mcp-schema-budget.test.ts). Every result stays in an
+ * agent's context and is re-sent on every later turn, so a change that grows
+ * it (pretty-printing content[0] grew a search result by about a quarter)
+ * must fail here rather than show up as a cost regression in an eval.
+ *
+ * The fixture has no embedding key; the first test proves the keyword
+ * fallback ran, so the bytes are deterministic. The measured text is every
+ * content block an agent sees: content[0] plus the notice blocks (saved
+ * facts, other names).
+ *
+ * Re-pin procedure (when a change grows the result on purpose): run
+ * `PRINT_RESULT_SIZES=1 bun test test/mcp-result-size-ceiling.test.ts`,
+ * set the ceiling to ceil(measured x 1.05), and say why in the commit
+ * message. Never raise a ceiling to absorb pretty-printing or a dropped lean
+ * projection: those are the regressions this file exists to catch.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { serializeMarkdown } from '../src/core/markdown.ts';
+import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+/** ceil(measured x 1.05) on the fixture below. */
+const CEILINGS = { search: 2540, query: 2540 };
+
+const PAGES: Array<[string, string, string]> = [
+ ['crm/numbat-labs', 'CRM record: Numbat Labs', 'Account record. Account code: NULA. Segment: mid-market. Renewal owner: the platform team. Billing contact: Old Person.'],
+ ['contracts/numbat-labs-msa', 'MSA: Numbat Labs', 'Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45. Renewal is annual with a 60 day notice window.'],
+ ['contracts/amendment-one', 'Amendment No. 1: NULA', 'Executed amendment for NULA: payment terms change to Net 30 from the next invoice.'],
+ ['notes/renewal-playbook', 'Renewal playbook', 'The renewal playbook: confirm the billing contact, check payment terms, and send the renewal quote 60 days before the term ends.'],
+ ['notes/billing-faq', 'Billing FAQ', 'Billing contacts change often. Confirm the current billing contact before sending an invoice or a renewal quote.'],
+];
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (const [slug, title, body] of PAGES) {
+ await importFromContent(engine, slug, serializeMarkdown({}, body, '', { type: 'note', title, tags: [] }), { noEmbed: true, forceRechunk: true });
+ }
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, valid_from) VALUES
+ ('default', 'numbat-labs', 'The billing contact for Numbat Labs is New Person.', 'fact', 'world', 'user update', '2026-09-01'),
+ ('default', 'numbat-labs', 'Numbat Labs renewal quote goes to the billing contact.', 'fact', 'world', 'user update', '2026-09-02')`);
+}, 120_000);
+
+afterAll(async () => { await engine?.disconnect(); });
+
+async function visible(name: 'search' | 'query'): Promise<{ res: ToolResult; text: string }> {
+ const args = name === 'query' ? { query: 'Numbat Labs billing contact renewal', expand: false } : { query: 'Numbat Labs billing contact renewal' };
+ const res = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, name, args, { remote: true, transport: 'http', sourceId: 'default' }));
+ expect(res.isError).not.toBe(true);
+ return { res, text: res.content.map(c => c.text).join('\n') };
+}
+
+describe('canonical remote result size', () => {
+ for (const name of ['search', 'query'] as const) {
+ test(`${name}: keyword fallback (deterministic), notices present`, async () => {
+ const { res } = await visible(name);
+ expect((res._meta?.retrieval as { vector_enabled?: boolean }).vector_enabled).toBe(false);
+ expect(res.content.length).toBeGreaterThan(1);
+ });
+
+ test(`${name}: content[0] is compact JSON (C2)`, async () => {
+ const { res } = await visible(name);
+ const text = res.content[0].text;
+ expect(text).toBe(JSON.stringify(JSON.parse(text)));
+ expect(text).not.toContain('\n ');
+ });
+
+ test(`${name}: model-visible text stays under its ceiling`, async () => {
+ const { text } = await visible(name);
+ if (process.env.PRINT_RESULT_SIZES === '1') process.stderr.write(`[result-size] ${name}: ${text.length} chars (ceiling ${Math.ceil(text.length * 1.05)})\n`);
+ expect(text.length).toBeLessThanOrEqual(CEILINGS[name]);
+ });
+
+ test(`${name}: the ceiling catches pretty-printing or full rows coming back`, async () => {
+ const { res, text } = await visible(name);
+ const rest = text.length - res.content[0].text.length;
+ const body = JSON.parse(res.content[0].text);
+ expect(JSON.stringify(body, null, 2).length + rest).toBeGreaterThan(CEILINGS[name]);
+ const full = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, name,
+ { query: 'Numbat Labs billing contact renewal', ...(name === 'query' ? { expand: false } : {}), fields: 'full' },
+ { remote: true, transport: 'http', sourceId: 'default' }));
+ expect(full.content.map(c => c.text).join('\n').length).toBeGreaterThan(CEILINGS[name]);
+ });
+ }
+});
diff --git a/test/memory-safety-wave.serial.test.ts b/test/memory-safety-wave.serial.test.ts
index 358ef482d4..a311083866 100644
--- a/test/memory-safety-wave.serial.test.ts
+++ b/test/memory-safety-wave.serial.test.ts
@@ -239,7 +239,7 @@ test('sync, remember, withdraw, metadata repair, migration, export and HTTP MCP
await client.connect(transport);
for (const query of [vectorQuery, privateText, foreignText, retired]) {
const callsBefore = embeddingCalls;
- const result = await client.callTool({ name: 'search', arguments: { query, expand: false } });
+ const result = await client.callTool({ name: 'search', arguments: { query, expand: false, fields: 'full' } });
expect(result.isError, stderr).not.toBe(true);
const rows = JSON.parse((result.content as Array<{ text: string }>)[0].text) as Array<{ slug: string; source_id: string; cosine?: number }>;
const meta = result._meta?.retrieval as { vector_enabled?: boolean; degraded?: unknown[]; projection_readiness: { status: string } };
diff --git a/test/search-lean-rows.test.ts b/test/search-lean-rows.test.ts
new file mode 100644
index 0000000000..f2d600e0d9
--- /dev/null
+++ b/test/search-lean-rows.test.ts
@@ -0,0 +1,226 @@
+/**
+ * C1 (cost wave): remote `search`/`query` callers get lean rows by default.
+ *
+ * Protects: the lean field set (identity, text, the duplicate-page guard,
+ * safety and provenance markers, truncation), every escape hatch (`fields:
+ * "full"`, the transport's `resultRows`, trusted local callers), the
+ * `_meta.retrieval.rows` report, and the two follow-up calls a lean row must
+ * still feed: `assemble_evidence` ({source_id, slug, chunk_id}) and `fetch`
+ * (`id`).
+ * Fails when: a kept field is dropped, a diagnostic leaks back into lean rows,
+ * an escape hatch stops restoring full rows, or a lean row can no longer be
+ * widened or fetched.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall, type DispatchOpts } from '../src/mcp/dispatch.ts';
+import { operations } from '../src/core/operations.ts';
+import { leanRow, resultRowsFor } from '../src/core/search/lean-rows.ts';
+import { stampEvidence } from '../src/core/search/evidence.ts';
+import { seedOffPath } from './helpers/evidence-delivery-fixture.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const REMOTE: DispatchOpts = { remote: true, transport: 'http', sourceId: 'default' };
+const LEAN_ALWAYS = ['id', 'slug', 'title', 'type', 'chunk_text', 'score', 'source_id', 'chunk_id', 'evidence', 'create_safety'];
+const DIAGNOSTICS = ['page_id', 'chunk_index', 'chunk_source', 'keyword_hit', 'effective_date_source', 'stale'];
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await seedOffPath(engine);
+}, 120_000);
+
+afterAll(async () => { await engine?.disconnect(); });
+
+async function call(name: string, params: Record<string, unknown>, opts: DispatchOpts = REMOTE) {
+ const res = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, name, params, opts));
+ expect(res.isError, res.content[0]?.text).not.toBe(true);
+ return { rows: JSON.parse(res.content[0].text) as Array<Record<string, unknown>>, meta: res._meta?.retrieval as Record<string, unknown> | undefined };
+}
+
+describe('lean rows for remote callers', () => {
+ for (const name of ['search', 'query'] as const) {
+ test(`${name}: a remote caller gets lean rows and _meta.retrieval.rows = "lean"`, async () => {
+ const { rows, meta } = await call(name, { query: 'ocelot pricing', ...(name === 'query' ? { expand: false } : {}), return_unit: 'chunk' });
+ expect(rows.length).toBeGreaterThan(0);
+ for (const row of rows) {
+ for (const key of LEAN_ALWAYS) expect(row, key).toHaveProperty(key);
+ for (const key of DIAGNOSTICS) expect(row, key).not.toHaveProperty(key);
+ expect(row).toHaveProperty('effective_date');
+ }
+ expect(meta?.rows).toBe('lean');
+ });
+
+ test(`${name}: fields "full" restores every field the local caller sees`, async () => {
+ const params = { query: 'ocelot pricing', ...(name === 'query' ? { expand: false } : {}), return_unit: 'chunk' };
+ const full = await call(name, { ...params, fields: 'full' });
+ const local = await call(name, params, { remote: false, sourceId: 'default' });
+ expect(full.meta?.rows).toBe('full');
+ expect(full.rows.map(r => Object.keys(r).sort())).toEqual(local.rows.map(r => Object.keys(r).sort()));
+ for (const key of ['page_id', 'chunk_index', 'chunk_source']) expect(full.rows[0], key).toHaveProperty(key);
+ });
+ }
+
+ test('trusted local callers keep full rows and get no rows marker', async () => {
+ const { rows, meta } = await call('search', { query: 'ocelot', return_unit: 'chunk' }, { remote: false, sourceId: 'default' });
+ expect(rows[0]).toHaveProperty('page_id');
+ expect(meta?.rows).toBeUndefined();
+ });
+
+ test('a transport that chose full rows (thin client, mcp.result_rows: full) gets them; fields "lean" still wins', async () => {
+ const full = await call('search', { query: 'ocelot', return_unit: 'chunk' }, { ...REMOTE, resultRows: 'full' });
+ expect(full.rows[0]).toHaveProperty('page_id');
+ expect(full.meta?.rows).toBe('full');
+ const lean = await call('search', { query: 'ocelot', return_unit: 'chunk', fields: 'lean' }, { ...REMOTE, resultRows: 'full' });
+ expect(lean.rows[0]).not.toHaveProperty('page_id');
+ });
+
+ test('resultRowsFor: explicit fields > local caller > transport choice > lean', () => {
+ expect(resultRowsFor({ remote: true }, undefined)).toBe('lean');
+ expect(resultRowsFor({ remote: true, resultRows: 'full' }, undefined)).toBe('full');
+ expect(resultRowsFor({ remote: false }, undefined)).toBe('full');
+ expect(resultRowsFor({ remote: false }, 'lean')).toBe('lean');
+ expect(resultRowsFor({ remote: true }, 'full')).toBe('full');
+ expect(resultRowsFor({ remote: true, resultRows: 'full' }, 'lean')).toBe('lean');
+ });
+});
+
+describe('lean rows still feed the follow-up calls', () => {
+ test('a lean search row passed to assemble_evidence resolves', async () => {
+ const { rows } = await call('search', { query: 'ocelot pricing', return_unit: 'chunk' });
+ const hits = rows.slice(0, 2).map(r => ({ source_id: r.source_id, slug: r.slug, chunk_id: r.chunk_id }));
+ const res = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, 'assemble_evidence', { hits, return_unit: 'chunk' }, REMOTE));
+ const out = JSON.parse(res.content[0].text) as { results: unknown[]; unresolved: unknown[] };
+ expect(out.unresolved).toEqual([]);
+ expect(out.results.length).toBe(hits.length);
+ });
+
+ test("a lean search row's id resolves through fetch", async () => {
+ const { rows } = await call('search', { query: 'ocelot pricing', return_unit: 'chunk' });
+ const res = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, 'fetch', { id: rows[0].id }, REMOTE));
+ expect(res.isError).not.toBe(true);
+ const page = JSON.parse(res.content[0].text) as { id: string; text: string };
+ expect(page.id).toBe(rows[0].id as string);
+ expect(page.text.length).toBeGreaterThan(0);
+ });
+});
+
+describe('delivered.truncated survives in lean rows whenever delivery truncated (DX-13)', () => {
+ const truncatedConversation = (rows: Array<Record<string, unknown>>) => {
+ const row = rows.find(r => r.slug === 'chat/session-a');
+ expect(row).toBeDefined();
+ return row!.delivered;
+ };
+
+ test('omitted return_unit (auto)', async () => {
+ const { rows } = await call('search', { query: 'ocelot renewal', snippet_chars: 200 });
+ expect(truncatedConversation(rows)).toEqual({ truncated: true });
+ for (const r of rows.filter(r => r.slug !== 'chat/session-a')) expect(r).not.toHaveProperty('delivered');
+ });
+
+ test('configured return_unit', async () => {
+ await engine.setConfig('search.return_unit', 'page');
+ try {
+ const { rows } = await call('search', { query: 'ocelot renewal', snippet_chars: 200 });
+ expect(truncatedConversation(rows)).toEqual({ truncated: true });
+ } finally {
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'search.return_unit'`);
+ }
+ });
+
+ test('explicit return_unit', async () => {
+ const { rows } = await call('search', { query: 'ocelot renewal', return_unit: 'page', snippet_chars: 200 });
+ expect(truncatedConversation(rows)).toEqual({ truncated: true });
+ });
+
+ test('an untruncated delivery carries no delivered object', async () => {
+ const { rows } = await call('search', { query: 'ocelot renewal', return_unit: 'page' });
+ expect(rows.find(r => r.slug === 'chat/session-a')).not.toHaveProperty('delivered');
+ });
+});
+
+describe('leanRow field contract', () => {
+ const full = {
+ id: 'gbrain-page:v1:x', slug: 's', page_id: 7, title: 't', type: 'note', chunk_text: 'body', chunk_source: 'compiled_truth',
+ chunk_id: 3, chunk_index: 0, score: 0.5, stale: false, source_id: 'default', effective_date: null, effective_date_source: null,
+ keyword_hit: true, cosine: 0.4, base_score: 0.3, rerank_score: 0.2, alias_hit: true, exact_lookup: true, graph_adjacency_hits: 2,
+ evidence: 'keyword_exact', create_safety: 'probable',
+ injection_suspected: true, injection_p: 0.9, unverified: true, content_flag: { reason: 'junk', detail: 'x' }, status: 'superseded',
+ superseded: true, superseded_by: 'canon', modality: 'text', message_id: 'm1', thread_id: 'th1', source_subject: 'subj',
+ delivered: { unit: 'page', chunk_ids: [3], match_spans: [], tokens: 9, truncated: false },
+ };
+
+ test('keeps identity, text, the duplicate guard and every present safety/provenance marker; drops diagnostics', () => {
+ expect(leanRow(full)).toEqual({
+ id: 'gbrain-page:v1:x', slug: 's', title: 't', type: 'note', chunk_text: 'body', chunk_id: 3, score: 0.5, source_id: 'default',
+ effective_date: null, evidence: 'keyword_exact', create_safety: 'probable',
+ injection_suspected: true, injection_p: 0.9, unverified: true, content_flag: { reason: 'junk', detail: 'x' }, status: 'superseded',
+ superseded: true, superseded_by: 'canon', message_id: 'm1', thread_id: 'th1', source_subject: 'subj',
+ });
+ });
+
+ test('stale only when true, modality only when not text, delivered only as {truncated: true}', () => {
+ const marked = leanRow({ ...full, stale: true, modality: 'image', delivered: { ...full.delivered, truncated: true } });
+ expect(marked.stale).toBe(true);
+ expect(marked.modality).toBe('image');
+ expect(marked.delivered).toEqual({ truncated: true });
+ });
+
+ test('absent sparse fields stay absent', () => {
+ expect(Object.keys(leanRow({ slug: 's', title: 't', type: 'note', chunk_text: 'x', score: 1, chunk_id: 1, page_id: 1 })).sort())
+ .toEqual(['chunk_id', 'chunk_text', 'score', 'slug', 'title', 'type']);
+ });
+});
+
+describe('the duplicate-page guard survives projection (E-7)', () => {
+ // The duplicate-prevention cases of test/search/evidence.ts, run through the
+ // remote projection: an agent reading a lean row must get the same
+ // don't-duplicate signal the full row carried.
+ const cases: Array<[string, Record<string, unknown>, string, string]> = [
+ ['the incident: a 0.64 keyword-hit body chunk', { base_score: 0.64, score: 0.64, keyword_hit: true }, 'keyword_exact', 'probable'],
+ ['the same 0.64 without a keyword hit', { base_score: 0.64, score: 0.64 }, 'weak_semantic', 'unknown'],
+ ['the same page via alias', { base_score: 0.64, alias_hit: true }, 'alias_hit', 'exists'],
+ ['a relaxed keyword hit', { keyword_hit: true, keyword_relaxed: true, base_score: 0.9 }, 'weak_semantic', 'unknown'],
+ ];
+ for (const [label, signals, evidence, safety] of cases) {
+ test(label, () => {
+ const row = { slug: 's', title: 't', chunk_text: '', type: 'note', source_id: 'default', chunk_index: 0, chunk_id: 1, page_id: 1, score: 0.5, ...signals } as never;
+ stampEvidence([row]);
+ const lean = leanRow(row);
+ expect(lean.evidence).toBe(evidence);
+ expect(lean.create_safety).toBe(safety);
+ for (const raw of Object.keys(signals)) if (raw !== 'score') expect(lean).not.toHaveProperty(raw);
+ });
+ }
+});
+
+describe('schema', () => {
+ const param = (op: string, key: string) => operations.find(o => o.name === op)!.params[key];
+
+ test('search and query declare fields: lean | full', () => {
+ for (const op of ['search', 'query']) expect(param(op, 'fields')).toMatchObject({ type: 'string', enum: ['lean', 'full'] });
+ });
+
+ test('query.detail still means low/medium/high', () => {
+ const d = param('query', 'detail').description ?? '';
+ for (const level of ['low', 'medium', 'high']) expect(d).toContain(level);
+ expect(param('query', 'detail').enum ?? ['low', 'medium', 'high']).toEqual(['low', 'medium', 'high']);
+ });
+
+ test('strict reject mode accepts fields (declared) and rejects an undeclared row-shape key', async () => {
+ await engine.setConfig('mcp.strict_params', 'reject');
+ try {
+ const ok = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, 'search', { query: 'ocelot', fields: 'full' }, REMOTE));
+ expect(ok.isError).not.toBe(true);
+ const bad = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, 'search', { query: 'ocelot', detail_rows: 'full' }, REMOTE));
+ expect(bad.isError).toBe(true);
+ } finally {
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'mcp.strict_params'`);
+ const { resetStrictParamsModeCache } = await import('../src/mcp/validate-params.ts');
+ resetStrictParamsModeCache();
+ }
+ });
+});
diff --git a/test/serve-http-mcp-dispatch-context.serial.test.ts b/test/serve-http-mcp-dispatch-context.serial.test.ts
index 4ccc1d3ee8..91616d67d3 100644
--- a/test/serve-http-mcp-dispatch-context.serial.test.ts
+++ b/test/serve-http-mcp-dispatch-context.serial.test.ts
@@ -87,7 +87,7 @@ async function rpc(base: string, token: string, method: string, params?: unknown
return JSON.parse(dataLine ? dataLine.slice('data:'.length) : text).result;
}
-const FULL_SURFACE_KEYS = ['auth', 'logger', 'metaHook', 'remote', 'sourceId', 'surface', 'surfaceCeiling', 'takesHoldersAllowList', 'transport'];
+const FULL_SURFACE_KEYS = ['auth', 'logger', 'metaHook', 'remote', 'resultRows', 'sourceId', 'surface', 'surfaceCeiling', 'takesHoldersAllowList', 'transport'];
describe('POST /mcp dispatch context', () => {
test('full surface: remote http dispatch with the verified auth and token source scope', async () => {
@@ -98,6 +98,8 @@ describe('POST /mcp dispatch context', () => {
const { opts } = calls[0];
expect(Object.keys(opts).sort()).toEqual(FULL_SURFACE_KEYS);
expect(opts.remote).toBe(true);
+ // C1: a client without the thin-client header gets the host default, lean rows.
+ expect(opts.resultRows).toBe('lean');
expect(opts.transport).toBe('http');
expect(opts.takesHoldersAllowList).toEqual(['world']);
expect(opts.sourceId).toBe('default');