Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(cli): load only the running op's module and defer SDK graphs off cold start

time-attack4d75a5798994
diff --git a/bun.lock b/bun.lock
index 5b8ed05786..0c6580e018 100644
--- a/bun.lock
+++ b/bun.lock
@@ -9,6 +9,7 @@
"@ai-sdk/google": "^3.0.64",
"@ai-sdk/openai": "^3.0.53",
"@ai-sdk/openai-compatible": "^2.0.41",
+ "@ai-sdk/provider-utils": "4.0.56",
"@anthropic-ai/sdk": "^0.30.0",
"@aws-sdk/client-s3": "^3.1028.0",
"@dqbd/tiktoken": "^1.0.22",
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index 22c19e8cd4..2cdd466a90 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/errors.ts` — error normalization and classification. One private generator, `wrappedErrorLayers`, opens a thrown error's wrappers outermost first (`cause`, else RetryError's `lastError`; objects only, at most five layers, a repeated layer ends the walk). `isStructuredOutputRejection` and `readProviderFailureSignals` use it; the latter returns the first finite `status`/`statusCode`/`apiErrorStatus` plus every string `name` and `code` and never throws (a throwing getter ends the walk). `page-summary.ts` `classifyChatError` reads those signals, so a wrapped claude-cli 429, an AI SDK RetryError's 429/5xx or a `TimeoutError`/network code on `cause` classifies as rate_limit/provider_5xx/timeout/network instead of `malformed` (which drops the page to the title tier). `classifyGlobalLlmError` keeps its own depth-3 loop over `cause ?? lastError`, so a 404 there halts as `model_not_found`; the `--- raw ---` phrase barrier and billing-over-429 precedence hold (`test/synopsis-chat-failure-class.test.ts`, `test/ai/classify-global-llm-error.test.ts`).
-- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `voyageCompatFetch` adapts Voyage embedding requests and responses; `openAICompatAsymmetricFetch` threads explicit query/document input types for other compatible recipes through the SDK boundary. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/rerank`; supported recipes declare their path explicitly) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `no_key` preflight: after `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` writes ONE `no_key` audit row per process per model without a stderr line, avoiding per-query noise. `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. `src/core/ai/multimodal-model.ts:multimodalEmbeddingModel()` answers the model `embedMultimodal()` would use when it passes those same recipe and allow-list checks (null otherwise, or when the gateway is unconfigured); hybrid search routes an inferred image intent and the LLM modality tie-break to the image arm only when it is set (`test/cross-modal-hybrid-integration.serial.test.ts`). Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (`test/ai/gateway.test.ts` drives both layers through `embed()`). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.timeoutMs` replaces the default chat backstop (`GBRAIN_AI_CHAT_TIMEOUT_MS`, 300 s) for one call and `ToolLoopOpts.turnTimeoutMs` forwards it to every turn (the subagent handler's per-turn cap, #4921); `ChatOpts.thinking: 'off'` maps per route through `thinking-off.ts` (#5331). `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts` Tracker recording goes through `src/core/ai/budget-record.ts:recordOnTracker` (fail-open: a cap breach on `record()` surfaces on the next `reserve()`); every chat/toolLoop/expand/embed/rerank/OCR record site passes the requested model, `purpose` (optional on `ChatOpts` + toolLoop opts; skillopt sets `skillopt.optimizer|target|judge`, engine-internal calls leave it null), `failed` on failure paths, `countsAsCall: false` for expand's structured-output fallback attempt and `estimated` when tokens are char-estimated. `reconfigureGatewayWithEngine` records the expansion/chat `ResolveSource` (`file_config` for the servable config.json pin) in `src/core/ai/gateway-model-sources.ts`; its getters answer only while the gateway still routes to the recorded model, so a later reconfigure reads as unknown instead of stale provenance.
+- `src/core/ai/gateway.ts` — unified seam for every AI call. The `ai` SDK loads at the first provider call (lazy default transports), not on configure. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `voyageCompatFetch` adapts Voyage embedding requests and responses; `openAICompatAsymmetricFetch` threads explicit query/document input types for other compatible recipes through the SDK boundary. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/rerank`; supported recipes declare their path explicitly) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `no_key` preflight: after `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` writes ONE `no_key` audit row per process per model without a stderr line, avoiding per-query noise. `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. `src/core/ai/multimodal-model.ts:multimodalEmbeddingModel()` answers the model `embedMultimodal()` would use when it passes those same recipe and allow-list checks (null otherwise, or when the gateway is unconfigured); hybrid search routes an inferred image intent and the LLM modality tie-break to the image arm only when it is set (`test/cross-modal-hybrid-integration.serial.test.ts`). Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (`test/ai/gateway.test.ts` drives both layers through `embed()`). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.timeoutMs` replaces the default chat backstop (`GBRAIN_AI_CHAT_TIMEOUT_MS`, 300 s) for one call and `ToolLoopOpts.turnTimeoutMs` forwards it to every turn (the subagent handler's per-turn cap, #4921); `ChatOpts.thinking: 'off'` maps per route through `thinking-off.ts` (#5331). `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts` Tracker recording goes through `src/core/ai/budget-record.ts:recordOnTracker` (fail-open: a cap breach on `record()` surfaces on the next `reserve()`); every chat/toolLoop/expand/embed/rerank/OCR record site passes the requested model, `purpose` (optional on `ChatOpts` + toolLoop opts; skillopt sets `skillopt.optimizer|target|judge`, engine-internal calls leave it null), `failed` on failure paths, `countsAsCall: false` for expand's structured-output fallback attempt and `estimated` when tokens are char-estimated. `reconfigureGatewayWithEngine` records the expansion/chat `ResolveSource` (`file_config` for the servable config.json pin) in `src/core/ai/gateway-model-sources.ts`; its getters answer only while the gateway still routes to the recorded model, so a later reconfigure reads as unknown instead of stale provenance.
- `src/core/ai/chat-fallback.ts`: the `chat_fallback_chain` consumer. `gateway.chat()` hands a call to `chatWithFallback` when a chain is configured and the caller did not pass `allowFallback: false`; `configureGateway` normalizes the chain with `normalizeChatFallbackChain` (a comma-separated string, the env and DB form, is split). Attempts run the call's own model, then each chain entry not already tried (`chatFallbackAttempts`), each as a complete single-model `chat()`, so budget, usage ledger, guardrails and `ChatResult.model` follow the model that ran; an answer from a chain entry also carries `ChatResult.fallbackFrom` (the call's own model). A provider error (a claude-cli subscription limit arrives as `apiErrorStatus` 429) or a structural refusal (`stopReason` `refusal`/`content_filter`) moves to the next model with one `[ai.gateway]` stderr line, and the first hop of a process queues one `chat_fallback_hop` safety notice in `fallback-hop-queue.ts`; with `chat_fallback_on_refusal: false` (`ChatFallbackOptions.onRefusal`, passed by `chat()` from the gateway config) a structural refusal is returned and a provider content block (`providerContentBlockReason`: a Gemini prompt block, or an HTTP 400 content-policy body such as OpenAI `invalid_prompt`, Azure `content_filter` or DeepSeek "Content Exists Risk") is thrown instead of being sent on, while provider errors still fall back; a policy refusal (`isAIInvocationPolicyError` or a BudgetTracker `BudgetExhausted`, including an unpriced chain entry under an explicit cap) or the caller's own abort stops the chain, and a cancel that lands while an attempt refuses returns that refusal instead of forwarding it; an earlier refusal is returned in preference to a later error, otherwise the call's own model's error is thrown (the last failure logged), so retry and halt classification follow the configured model. `toolLoop` forwards `allowFallback` to every turn. Judge, critic and eval call sites pin their model: brainstorm judges, grade_takes, drift, the edge_contradictions judge (apply mode defaults from a per-model certification), voice-gate, eval-contradictions, notability-eval, takes-quality-eval, cross-modal eval, skillopt (judge, optimizer, rollouts), the LongMemEval reader and judge, the functional-area-resolver harness, the `models doctor` / `providers test` probes, `decide()` (its egress gate cleared one provider), `auto_think` (its BudgetMeter priced one model), and `think` with an explicit `--model`; the synthesize triage and concept synthesis fall back. Pinned by `test/ai/gateway-chat-fallback.test.ts` and `test/ai/chat-fallback-on-refusal.test.ts` (refusal switch through the real loader on every plane, the once-per-process hop notice).
- `src/core/ai/fallback-hop-queue.ts`: the process-level queue for the first hop's `chat_fallback_hop` notice (at most one per process; type-only imports so every drain site loads it cheaply). Drained by stdio MCP dispatch, the CLI op notice channel (`src/cli/op-notices.ts`) and `finishCliTeardown`; never by HTTP, because the notice names models.
- `src/core/ai/chat-fallback-planes.ts`: where the effective `chat_fallback_chain` comes from, read without network, subprocess or inference. `readChatFallbackPlanes(db)` reads env `GBRAIN_CHAT_FALLBACK_CHAIN` > the config.json key > the DB row (`parseDbChatFallbackChain` in `config-db-merge.ts`) with the loader's rule that the first plane that speaks wins even when its value yields no chain, and returns the winner, shadowed values, unreadable planes and the `chat_fallback_on_refusal` value with its plane. `diagnoseChatFallbackEntry` checks one entry by presence: `provider:model` parse, known provider with chat, the provider's own credential (recipe env keys or `authPresent`; for `claude-cli` the binary on PATH or `GBRAIN_CLAUDE_CLI_BIN`), and a price when a key in `USER_CHAT_CAP_KEYS` sets a user cap. `chatFallbackRemovalFix` is the per-plane removal guidance (DB `gbrain config unset chat_fallback_chain` with `destructive` consent → `ask_user`; env/file are the user's, with the restart note). Consumers: the `chat_fallback_chain` doctor check and the `behavior_changes` notice.
diff --git a/docs/architecture/key-files/entrypoints-and-docs.md b/docs/architecture/key-files/entrypoints-and-docs.md
index cff0031673..1fe11080e9 100644
--- a/docs/architecture/key-files/entrypoints-and-docs.md
+++ b/docs/architecture/key-files/entrypoints-and-docs.md
@@ -127,7 +127,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/lib/cli-pipeline.ts` — flattens `handleCliOnly` (inlining `@cliPipelineStage` functions) and reads the command table by AST, for the W0 dispatch-shape extractor (`test/helpers/cli-dispatch-extract.ts`) and `scripts/generate-flag-registry.ts`.
-- `src/core/operation-manifest.generated.ts` + `scripts/build-operation-manifest.ts` (`bun run build:operation-manifest`, in `regen:all`) — every operation in `src/core/operations.ts` minus its handler, in registry order (`OperationMeta` in `src/core/ops/contract.ts`). `gbrain serve` (stdio initialize/tools/list, surface and publish-gate filtering, skill-resource permission checks) and the CLI dispatcher (`src/cli/op-manifest.ts`: command, alias, flag and help lookup plus the A1 fix-routing registration) read it, so neither loads the handler graph until an op runs. Freshness, equality with the live registry, and the absence of `operations.ts`/`dispatch.ts` from the serve and dispatcher import graphs are pinned by `test/operation-manifest.test.ts`.
+- `src/core/operation-manifest.generated.ts` + `scripts/build-operation-manifest.ts` (`bun run build:operation-manifest`, in `regen:all`) — every operation in `src/core/operations.ts` minus its handler, in registry order (`OperationMeta` in `src/core/ops/contract.ts`). `gbrain serve` (stdio initialize/tools/list, surface and publish-gate filtering, skill-resource permission checks) and the CLI dispatcher (`src/cli/op-manifest.ts`: command, alias, flag and help lookup plus the A1 fix-routing registration) read it, so neither loads the handler graph until an op runs. Freshness, equality with the live registry, and the absence of `operations.ts`/`dispatch.ts` from the serve and dispatcher import graphs are pinned by `test/operation-manifest.test.ts`. The same script writes `src/core/operation-loaders.generated.ts`: each op's defining module (`verbs.ts` or `ops/*.ts`) and export, as string-literal `import()`s. `src/core/operation-load.ts` holds the one finalize step (central `OP_AREAS` + the output-redaction wrapper, idempotent per op object) that `operations.ts` applies to the registry, and `loadOperation(name)`, which `runSharedOperation` uses to load and finalize only the op it runs; `test/cli-cold-start-graph.test.ts` pins that a lone load is the registry's object in the registry's state.
- `src/core/cli-flag-registry.generated.ts` (strict flag validation in `src/cli/main.ts`) + `scripts/generate-flag-registry.ts` — pre-dispatch, pre-engine unknown-flag rejection for every command: a flag no handler consults fails loud (`unknown flag --x for 'gbrain <cmd>'`, exit 1; `--json` invocations also get a structured `{status:'error', reason:'invalid_flag'}` on stdout) instead of being silently ignored while the un-asked-for real operation runs. `validateCommandFlags(command, subArgs)` runs after the `--help` short-circuit and before any dispatch or engine connect, in two lanes mirroring dispatch order (CLI_ONLY first — `think`/`salience`/`anomalies` are both ops AND CLI_ONLY members whose handlers parse flags the op contract doesn't declare): CLI_ONLY commands validate against the generated `CLI_FLAG_REGISTRY` (per-command legal sets derived from each command's source — its `src/cli/commands/` module and pipeline branches + imported modules + one level of relative imports + `EXTRA_FLAGS` + `DELEGATED_MODULES`, the modules a command hands its argv to through a nested handler (auth → `persistence-admin.ts` and `grants/cli.ts`), scanned at module depth without their imports so their safety-flag reads count as consumption; deliberately over-inclusive, help-text mentions count, but `//` and `/* */` comments are stripped at every depth before the scan — a helper's doc comment naming `--fresh` must not legalise it for a command that only imports one function from that helper; regenerate via `bun run build:flag-registry`); op commands validate via `findUnknownOpFlag`, which mirrors `parseOpArgs`'s traversal (non-boolean flags consume their value token; `--key=value` inline form recognized) plus the CLI-local flags consumed outside the op contract (`json`, `explain`, `help`, `source`, `dry-run`); the CLI_ONLY token scan is the exported `findUnknownFlag(args, legal)`. `parseOpArgs` also refuses to let a non-boolean flag swallow a token that is itself a known flag of the same command (op-contract param, a CLI-local, or the `--no-<boolean>` form): `gbrain put x --content --source default` fails with `--content requires a value, but '--source' is a flag; omit --content (or put it last) to read stdin` (exit 1, pre-write) instead of storing the literal `--source` as the page body. A value that merely starts with `--` but names no flag of this command stays a value; the shared `isKnownOpFlag` predicate (`src/core/op-flag-tokens.ts`) sits next to `isBooleanLiteral` so parser and validator cannot disagree. In `parseOpArgs`, `json`/`dry_run` are CLI-local booleans that never consume a value token, so a trailing `--dry-run` is a real rehearsal switch feeding `makeContext`'s `ctx.dryRun`. Uppercase flag spellings are treated as unknown (every handler is case-sensitive-lowercase, so they'd be silently ignored downstream — the exact class the validator kills). Exempt by contract: `call` (arbitrary `--param` interface), `config` (arbitrary set values), `jobs submit` (handler-defined payload params); everything after a literal `--` is passthrough and never validated. A command missing from the registry fails OPEN at runtime (never bricks a command); `test/cli-flag-validation.test.ts` pins registry freshness, per-command drift, and consumption evidence — a safety flag (`--dry-run`, `--yes`, `--force`) may only be advertised if the command's source actually reads it. The generator segments `handleCliOnly` into per-command text blocks with `segmentDispatchBlocks`: both `case 'X':` labels and every `if (command === 'X' …)` head — plain, compound (`&& args[0] === 'sub'`: the no-DB `eval <sub>` bypasses such as `eval longmemeval`, the `<cmd> --help` pre-engine branches, `agent register`) and multi-line — are markers, and ownership follows the `command === 'X'` head, never the condition's tail, so a compound block's flags land on its own command's row (the `eval` row is a union across eval subcommands, the registry's shape for every multi-subcommand command); a bare `command === 'X'` inside a non-`if` expression is deliberately not a marker. Only `import('./commands/*.ts')` inside a block counts as a command module (core helpers a block reaches for directly are not scanned — a flag the block consumes through one is already a literal in the block's own text), and `isValueOnlyImport` skips a destructured import whose bindings are all SCREAMING_CASE constants (a borrowed message string, not a handler). Pinned by `test/generate-flag-registry.test.ts` (acceptance AND rejection: `--frobnicate` is still refused) and `test/eval-longmemeval-cli-smoke.test.ts` (the documented `gbrain eval longmemeval … --retrieval-only --by-type --no-trajectory --keyword-only` invocation exits 0 as a subprocess).
- `src/schema.sql` — Full Postgres + pgvector DDL: canonical for every table except the TS fragment tables, whose `BEGIN/END GENERATED` regions are rewritten from the fragment modules; `bun run build:schema` derives schema-embedded.generated.ts and the PGLite template from it (`docs/ENGINES.md#canonical-schema-sources`)
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index ae97eb973f..309061cf1c 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`), `withHumanLineSink(sink, fn)` (#6317: every `slog`/`serr` line under `fn`, Bun timers included, goes to `sink` instead of the streams; the serve captures a delegated managed drain's lines per job for `sync_status`), and `withHumanLogsToStderr(fn)` (runs `fn` with every `slog` line, prefixed or not, routed to stderr; `runSync` wraps its body in it under `--json` so stdout carries only the ONE JSON envelope (the cost-gate status object rides inside it as `cost_gate`, #4684) while `serr` and direct `console.log(JSON.stringify(..))` sites are unaffected; scoped via its own `AsyncLocalStorage`, never a process-wide console rebind). Embedded-newline-safe: a multi-line string under prefix `[foo]` emits `[foo] line1\n[foo] line2`. Outside a wrap, `slog`/`serr` fall through to bare `console.log`/`console.error` so single-source callers see identical output (back-compat invariant). Use `src.id` (slug-validated by `sources add`) NOT `src.name` (free-form) to defeat log-injection through newline/control-character names. Coverage: `src/commands/sync.ts` performSync + callees, `src/commands/embed.ts` runEmbedCore + helpers, `src/core/progress.ts` emitHumanLine, `src/commands/import.ts` runImport's human-only lines (`info()` + the end-of-run `Import complete` summary — so the first-sync full import under `sync --json` lands on stderr too).
-- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and every request carries `X-Gbrain-Client: gbrain-remote-cli/<version>` so hosts serve it full search/query rows (it never sends `fields`); `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). A /token 429 is `rate_limited` with `RemoteMcpErrorDetail.retry_after_s` parsed from Retry-After (`parseRetryAfterSeconds` in `remote-mcp-probe.ts`); any other non-auth /token failure is `token`, never `discovery`. `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `ignoredRemoteParams(res)` lists params the host reported ignoring (`_meta.warnings` `unknown_param` entries plus the warning text blocks after `content[0]`); the CLI fails when a sent scope param (`source_id`, `all_sources`) is among them and warns for other ignored params the op declares. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`. Agent contract v1: a tool_error body is `content[0]` alone; `extractToolErrorDetail` keeps `code` (legacy `error`) plus `canonical_code`, `reason`, `why`, `fix`, `notices`, `contract_version`; `RemoteMcpError.toJSON` adds `code` (derived via `canonicalCodeFor` for old servers) and those fields when present; `extractNotices(res)` reads `_meta.gbrain_notices` or prefixed blocks. Skew pinned by `test/thin-client-contract-skew.test.ts` with a frozen v0.60.37.0 parser. A status-only host's 503 `serve_status_only` envelope from OAuth discovery or `/token` (`status_only` on the `remote-mcp-probe.ts` failure, with `retry_after_s`) becomes `RemoteMcpError` detail (`code`, `reason`, `why`, `fix`), which the CLI renders through the agent envelope and the thin-client doctor reports on its check (`test/remote-mcp-status-only.test.ts`).
+- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `RemoteMcpError`, `extractResponseMeta` and `ignoredRemoteParams` live in `src/core/remote-mcp-error.ts` (re-exported here) so local CLI paths can name them without loading the MCP SDK; the CLI imports this module only on a routed call. `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and every request carries `X-Gbrain-Client: gbrain-remote-cli/<version>` so hosts serve it full search/query rows (it never sends `fields`); `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). A /token 429 is `rate_limited` with `RemoteMcpErrorDetail.retry_after_s` parsed from Retry-After (`parseRetryAfterSeconds` in `remote-mcp-probe.ts`); any other non-auth /token failure is `token`, never `discovery`. `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error 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`. Agent contract v1: a tool_error body is `content[0]` alone; `extractToolErrorDetail` keeps `code` (legacy `error`) plus `canonical_code`, `reason`, `why`, `fix`, `notices`, `contract_version`; `RemoteMcpError.toJSON` adds `code` (derived via `canonicalCodeFor` for old servers) and those fields when present; `extractNotices(res)` reads `_meta.gbrain_notices` or prefixed blocks. Skew pinned by `test/thin-client-contract-skew.test.ts` with a frozen v0.60.37.0 parser. A status-only host's 503 `serve_status_only` envelope from OAuth discovery or `/token` (`status_only` on the `remote-mcp-probe.ts` failure, with `retry_after_s`) becomes `RemoteMcpError` detail (`code`, `reason`, `why`, `fix`), which the CLI renders through the agent envelope and the thin-client doctor reports on its check (`test/remote-mcp-status-only.test.ts`).
- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` and `managed-atoms-generation` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten. Git sync holds (`sync-hold`), their per-source summary while it counts any, `sync-hold-retry` requests, `sync-import-provenance` rows, the blocked-cursor conversion log, the #6188 fence census (`fence-candidate`, `fence-scan`) and paid fence-repair attempt claims and memos (`fence-repair-attempt`) of a live source incarnation survive GC (they leave on resolution; a retired incarnation's rows age out), and `connector-hold-retry` requests never expire.
- `src/core/persistence/preview-approval.ts` — preview-bound approval shared by `jobs authorize-legacy --select`, `jobs cancel --select`, `repair stale-atoms`, `repair extractor-facts` and the other preview-bound repair kinds such as `repair ontology-facts` (fix wave 5, ENG-O1). `previewHash(parts)` is SHA-256 over key-sorted JSON, byte-identical to `authorityDigest`; `saveApprovedSet` / `loadApprovedSet` / `clearApprovedSet` keep the approved items in `op_checkpoints` (`op='repair-approval'`, fingerprint `<command>:<hash>`). 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/package.json b/package.json
index 7ab6b3ceef..166334eb62 100644
--- a/package.json
+++ b/package.json
@@ -186,6 +186,7 @@
"@ai-sdk/google": "^3.0.64",
"@ai-sdk/openai": "^3.0.53",
"@ai-sdk/openai-compatible": "^2.0.41",
+ "@ai-sdk/provider-utils": "4.0.56",
"@anthropic-ai/sdk": "^0.30.0",
"@aws-sdk/client-s3": "^3.1028.0",
"@dqbd/tiktoken": "^1.0.22",
diff --git a/scripts/build-operation-manifest.ts b/scripts/build-operation-manifest.ts
index 54cc7c6b5a..0f9e727f3e 100644
--- a/scripts/build-operation-manifest.ts
+++ b/scripts/build-operation-manifest.ts
@@ -10,14 +10,72 @@
* test/operation-manifest.test.ts; tools/list byte-identity against the eager
* registry by test/mcp-tool-list-snapshot.test.ts.
*
+ * Second output: src/core/operation-loaders.generated.ts, each operation's
+ * defining module and export, so the CLI loads only the module behind the one
+ * op it runs (src/core/operation-load.ts) instead of the whole registry.
+ *
* Regenerate: bun run build:operation-manifest
*/
-import { writeFileSync } from 'fs';
+import { readdirSync, writeFileSync } from 'fs';
import { join } from 'path';
import { operations } from '../src/core/operations.ts';
+import type { Operation } from '../src/core/ops/contract.ts';
export const OPERATION_MANIFEST_PATH = join(import.meta.dir, '..', 'src', 'core', 'operation-manifest.generated.ts');
+export const OPERATION_LOADERS_PATH = join(import.meta.dir, '..', 'src', 'core', 'operation-loaders.generated.ts');
+
+const isOperation = (v: unknown): v is Operation =>
+ !!v && typeof v === 'object' && typeof (v as Operation).name === 'string' && typeof (v as Operation).handler === 'function';
+
+/** Every module that defines operations, relative to src/core, in a stable order. */
+function operationModules(): string[] {
+ const opsDir = join(import.meta.dir, '..', 'src', 'core', 'ops');
+ return ['verbs.ts', ...readdirSync(opsDir).filter(f => f.endsWith('.ts')).sort().map(f => `ops/${f}`)];
+}
+
+export async function renderOperationLoaders(): Promise<string> {
+ const definedIn = new Map<Operation, [string, string][]>();
+ for (const file of operationModules()) {
+ const mod: Record<string, unknown> = await import(join(import.meta.dir, '..', 'src', 'core', file));
+ for (const [exportName, value] of Object.entries(mod)) {
+ const ops = Array.isArray(value) && value.length > 0 && value.every(isOperation) ? value : isOperation(value) ? [value] : [];
+ for (const op of ops) definedIn.set(op, [...(definedIn.get(op) ?? []), [file, exportName]]);
+ }
+ }
+ const used = new Set<string>();
+ const entries = operations.map(op => {
+ const sites = definedIn.get(op) ?? [];
+ if (sites.length !== 1) {
+ throw new Error(`operation ${op.name} must be exported by exactly one module under src/core (found ${sites.length}: ${sites.map(s => s.join(':')).join(', ') || 'none'})`);
+ }
+ const [file, exportName] = sites[0]!;
+ used.add(file);
+ return ` ${JSON.stringify(op.name)}: [${loaderName(file)}, ${JSON.stringify(exportName)}],`;
+ });
+ return [
+ '// AUTO-GENERATED by scripts/build-operation-manifest.ts — do not edit by hand.',
+ '// Regenerate: bun run build:operation-manifest',
+ '// Freshness pinned by test/operation-manifest.test.ts.',
+ '//',
+ '// Merge conflict here? Take either side wholesale, then re-run the command above.',
+ '//',
+ '// Operation name -> [loader of its defining module, export holding it].',
+ '// String-literal import()s so bun --compile embeds every module.',
+ '',
+ ...[...used].sort().map(file => `const ${loaderName(file)} = () => import('./${file}') as Promise<Record<string, unknown>>;`),
+ '',
+ 'export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<string, unknown>>, string]> = {',
+ ...entries,
+ '};',
+ '',
+ ].join('\n');
+}
+
+function loaderName(file: string): string {
+ return `load_${file.replace(/^ops\//, '').replace(/\.ts$/, '').replace(/[^a-zA-Z0-9]/g, '_')}`;
+}
+
export function renderOperationManifest(): string {
const meta = operations.map(({ handler: _handler, ...rest }) => rest);
return [
@@ -41,4 +99,7 @@ if (import.meta.main) {
const out = renderOperationManifest();
writeFileSync(OPERATION_MANIFEST_PATH, out, 'utf-8');
console.log(`Wrote ${OPERATION_MANIFEST_PATH} (${operations.length} operations, ${out.length} bytes).`);
+ const loaders = await renderOperationLoaders();
+ writeFileSync(OPERATION_LOADERS_PATH, loaders, 'utf-8');
+ console.log(`Wrote ${OPERATION_LOADERS_PATH} (${loaders.length} bytes).`);
}
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 78f7022f48..a4470aa1f9 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -6,7 +6,6 @@
* helpers below from here.
*/
import { affectsRecall } from '../core/types.ts';
-import { deliveryVersionSkewWarning } from '../core/search/evidence-delivery.ts';
import { installSigchldHandler } from '../core/zombie-reap.ts';
installSigchldHandler();
@@ -35,6 +34,7 @@ import type { AIGatewayConfig } from '../core/ai/types.ts';
import type { BrainEngine } from '../core/engine.ts';
import { OperationError, type OperationMeta } from '../core/ops/contract.ts';
import { OPERATION_MANIFEST, cliOps } from './op-manifest.ts';
+import { loadOperation } from '../core/operation-load.ts';
import { resolveSourceIdEngineFree } from '../core/source-resolver.ts';
import { installCliRoutingFor } from './fix-routing-provider.ts';
import { formatVolunteeredPage } from '../core/context/volunteer.ts';
@@ -56,7 +56,7 @@ import { isBooleanLiteral, isKnownOpFlag } from '../core/op-flag-tokens.ts';
import { conceptNudge } from '../core/search/query-intent.ts';
import { redactRetrievalOutput } from '../core/search/output-redaction.ts';
import type { CliOptions } from '../core/cli-options.ts';
-import { callRemoteTool, RemoteMcpError, unpackToolResult, extractResponseMeta } from '../core/mcp-client.ts';
+import { RemoteMcpError, extractResponseMeta } from '../core/remote-mcp-error.ts';
import { assertSingleSourceScopeFlag, checkHostHonoredParams, hintAmbientNarrowing, type AmbientSourceBinding } from './source-scope.ts';
import { maybePromptForUpgrade } from '../core/thin-client-upgrade-prompt.ts';
import { CLI_FLAG_REGISTRY } from '../core/cli-flag-registry.generated.ts';
@@ -521,7 +521,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
// Shared operations (fall through to aliases, e.g. link-add -> add_link)
const meta = cliOps.get(command) ?? cliAliases.get(command);
if (!meta) exitCliError(usageError(`Unknown command: ${command}`, 'Run `gbrain --help` for available commands.', { code: 'unknown_command' }), command);
- const op = (await import('../core/operations.ts')).operations.find(o => o.name === meta.name)!;
+ const op = (await loadOperation(meta.name))!;
// v0.31.1 (Issue #734, CDX-1): parse CLI args BEFORE engine connect so
// the routing seam below can decide local-vs-remote without paying a
@@ -786,6 +786,7 @@ async function runThinClientRouted(
await printIdentityBannerBestEffort(cfg, cliOpts, sigintController.signal);
try {
+ const { callRemoteTool, unpackToolResult } = await import('../core/mcp-client.ts');
const raw = await callRemoteTool(cfg, op.name, params, {
timeoutMs,
signal: sigintController.signal,
@@ -798,6 +799,7 @@ async function runThinClientRouted(
checkHostHonoredParams(op, params, raw);
const result = unpackToolResult(raw);
hintAmbientNarrowing(op, params, result, ambientScope);
+ const { deliveryVersionSkewWarning } = await import('../core/search/evidence-delivery.ts');
const skew = deliveryVersionSkewWarning(op.name, params, envelopeMeta?.retrieval as Record<string, unknown> | undefined, result);
if (skew) process.stderr.write(skew + '\n');
const output = formatResult(op.name, result, params);
@@ -941,6 +943,7 @@ async function fetchIdentity(
signal: AbortSignal,
): Promise<BrainIdentity> {
// 2s timeout for the banner fetch — must not delay the underlying command.
+ const { callRemoteTool, unpackToolResult } = await import('../core/mcp-client.ts');
const raw = await callRemoteTool(cfg, 'get_brain_identity', {}, {
timeoutMs: 2000,
signal,
diff --git a/src/cli/source-scope.ts b/src/cli/source-scope.ts
index b0c2e31a8e..7f00a0465a 100644
--- a/src/cli/source-scope.ts
+++ b/src/cli/source-scope.ts
@@ -6,7 +6,7 @@
*/
import type { Operation } from '../core/operations.ts';
import { opOwnsSource } from '../core/ops/contract.ts';
-import { ignoredRemoteParams } from '../core/mcp-client.ts';
+import { ignoredRemoteParams } from '../core/remote-mcp-error.ts';
/** Where an ambient (not flag-supplied) thin-client source scope came from. */
export type AmbientSourceBinding = { sourceId: string; via: 'GBRAIN_SOURCE' | '.gbrain-source' };
diff --git a/src/commands/persistence-delegate.ts b/src/commands/persistence-delegate.ts
index 9b5f79af02..88e96f3f6e 100644
--- a/src/commands/persistence-delegate.ts
+++ b/src/commands/persistence-delegate.ts
@@ -5,7 +5,7 @@ import { OperationError } from '../core/ops/contract.ts';
import { finishCliTeardown, noteRenderedErrorCode, setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';
import { maybeDelegateLocalOperation } from '../core/persistence/local-client.ts';
import { PersistenceIpcTransportError } from '../core/persistence/ipc.ts';
-import { RemoteMcpError } from '../core/mcp-client.ts';
+import { RemoteMcpError } from '../core/remote-mcp-error.ts';
import { getCliOptions } from '../core/cli-options.ts';
import { PENDING_WRITE_EXIT_CODE } from '../core/exit-codes.ts';
import { acceptPendingRequested, pendingReceiptOf, pollCommand, WRITE_EXIT_DOCS, writeErrorExitCode } from '../core/persistence/write-wait.ts';
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 42a99ed115..136dbdcfc7 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -21,7 +21,8 @@
* rotation (via configureGateway()) invalidates stale entries.
*/
-import { embed as aiEmbed, embedMany, generateObject, generateText, jsonSchema, type JSONSchema7, type Output } from 'ai';
+import type { embedMany, generateObject, generateText, JSONSchema7, Output } from 'ai';
+import { jsonSchema } from '@ai-sdk/provider-utils';
import { installAiSdkWarningWriter } from './sdk-warnings.ts';
import { AsyncLocalStorage } from 'node:async_hooks';
import { createHash, randomUUID } from 'node:crypto';
@@ -163,19 +164,27 @@ export function configureGatewayIfUninitialized(): void {
/**
* The function the gateway calls to actually run a batch through the AI SDK.
- * Defaults to the imported `embedMany`. Tests inject a stub via
+ * Defaults to the AI SDK's `embedMany`, loaded on the first call. Tests inject a stub via
* `__setEmbedTransportForTests` to drive recursion + fast-path scenarios
* without hitting a real provider. Production never reads the override.
*/
type EmbedManyFn = typeof embedMany;
-let _embedTransport: EmbedManyFn = embedMany;
type GenerateTextFn = typeof generateText;
-let _generateTextTransport: GenerateTextFn = generateText;
+type GenerateObjectFn = typeof generateObject;
+// The AI SDK (and the OpenTelemetry API it pulls in) loads at the first
+// provider call, not when the gateway is configured, so a command that never
+// calls a model never pays for its module graph.
+let aiSdk: Promise<typeof import('ai')> | undefined;
+const loadAiSdk = () => (aiSdk ??= import('ai'));
+const sdkEmbedMany = (async (opts: Parameters<EmbedManyFn>[0]) => (await loadAiSdk()).embedMany(opts)) as EmbedManyFn;
+const sdkGenerateText = (async (opts: Parameters<GenerateTextFn>[0]) => (await loadAiSdk()).generateText(opts)) as GenerateTextFn;
+const sdkGenerateObject = (async (opts: Parameters<GenerateObjectFn>[0]) => (await loadAiSdk()).generateObject(opts as never)) as GenerateObjectFn;
+let _embedTransport: EmbedManyFn = sdkEmbedMany;
+let _generateTextTransport: GenerateTextFn = sdkGenerateText;
// Test-only seam for expand()'s structured-output SDK call. Mirrors
// _generateTextTransport (see __setGenerateObjectTransportForTests). Never
// swapped in production — expand() always calls the real generateObject.
-type GenerateObjectFn = typeof generateObject;
-let _generateObjectTransport: GenerateObjectFn = generateObject;
+let _generateObjectTransport: GenerateObjectFn = sdkGenerateObject;
// Adversarial F5 (#4121): recipes that DECLARE structured-output support but
// reject json_schema at call time would otherwise pay the rejected attempt —
// and a pessimistic '.failed' budget record — on EVERY expand() call
@@ -676,9 +685,9 @@ function clearGatewayState(): void {
stashGatewayAnthropicKeyFromEnv(undefined); // gateway-owned snapshot dies with the config
_modelCache.clear();
_shrinkState.clear();
- _embedTransport = embedMany;
- _generateTextTransport = generateText;
- _generateObjectTransport = generateObject;
+ _embedTransport = sdkEmbedMany;
+ _generateTextTransport = sdkGenerateText;
+ _generateObjectTransport = sdkGenerateObject;
_structuredOutputRejectedRecipes.clear();
_embedTransportInstalled = false;
_chatTransport = null;
@@ -731,7 +740,7 @@ export function __unconfigureGatewayForTests(): void {
* @internal exported for tests; not part of the public gateway API.
*/
export function __setEmbedTransportForTests(fn: EmbedManyFn | null): void {
- _embedTransport = fn ?? embedMany;
+ _embedTransport = fn ?? sdkEmbedMany;
_embedTransportInstalled = fn !== null;
}
@@ -743,7 +752,7 @@ export function __setEmbedTransportForTests(fn: EmbedManyFn | null): void {
* @internal exported for tests; not part of the public gateway API.
*/
export function __setGenerateTextTransportForTests(fn: GenerateTextFn | null): void {
- _generateTextTransport = fn ?? generateText;
+ _generateTextTransport = fn ?? sdkGenerateText;
}
/**
@@ -754,7 +763,7 @@ export function __setGenerateTextTransportForTests(fn: GenerateTextFn | null): v
* @internal exported for tests; not part of the public gateway API.
*/
export function __setGenerateObjectTransportForTests(fn: GenerateObjectFn | null): void {
- _generateObjectTransport = fn ?? generateObject;
+ _generateObjectTransport = fn ?? sdkGenerateObject;
}
/**
diff --git a/src/core/embedding-disabled.ts b/src/core/embedding-disabled.ts
index fe3ef6cbcd..7de2cc5992 100644
--- a/src/core/embedding-disabled.ts
+++ b/src/core/embedding-disabled.ts
@@ -7,6 +7,17 @@
import { loadConfig, type GBrainConfig } from './config.ts';
import type { BrainEngine } from './engine.ts';
+let readConsumerConfig: ((engine: BrainEngine) => GBrainConfig | undefined) | null = null;
+
+/**
+ * persistence/service.ts registers its consumer-config reader as it loads. A
+ * process that never loaded it runs no persistence consumer, so a read-only
+ * command (search, query) never pays for that module graph here.
+ */
+export function registerPersistenceConsumerConfig(read: (engine: BrainEngine) => GBrainConfig | undefined): void {
+ readConsumerConfig = read;
+}
+
export async function embeddingsDisabled(engine?: { getConfig(key: string): Promise<string | null> } | null): Promise<boolean> {
try {
if (loadConfig()?.embedding_disabled === true) return true;
@@ -28,10 +39,7 @@ export async function embeddingsDisabled(engine?: { getConfig(key: string): Prom
*/
export async function factEmbeddingDisabled(engine: BrainEngine | null | undefined, config?: GBrainConfig | null): Promise<boolean> {
let effective = config ?? null;
- if (!effective && engine) {
- const { persistenceConsumerConfig } = await import('./persistence/service.ts');
- effective = persistenceConsumerConfig(engine) ?? null;
- }
+ if (!effective && engine && readConsumerConfig) effective = readConsumerConfig(engine) ?? null;
if (effective?.embedding_disabled === true) return true;
return embeddingsDisabled(engine);
}
diff --git a/src/core/mcp-client.ts b/src/core/mcp-client.ts
index e5d7e63c88..a14ef3e153 100644
--- a/src/core/mcp-client.ts
+++ b/src/core/mcp-client.ts
@@ -24,12 +24,17 @@ import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
import type { StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
import { anySignal } from './abort-check.ts';
-import { canonicalCodeFor } from './error-catalogue.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 { isWriteErrorCode, isWriteReceipt, isWriteRequestId, publicWriteReceipt } from './persistence/types.ts';
import { GBRAIN_CLIENT_HEADER, GBRAIN_THIN_CLIENT_NAME } from '../mcp/result-rows.ts';
import { VERSION } from '../version.ts';
+import { RemoteMcpError, extractResponseMeta, type RemoteMcpErrorDetail } from './remote-mcp-error.ts';
+
+// The error class and the envelope-meta readers live in remote-mcp-error.ts so
+// a local CLI command can name them without loading this module's MCP SDK graph.
+export { RemoteMcpError, extractResponseMeta, ignoredRemoteParams } from './remote-mcp-error.ts';
+export type { RemoteMcpErrorReason, RemoteMcpErrorDetail } from './remote-mcp-error.ts';
interface CachedToken {
access_token: string;
@@ -49,100 +54,6 @@ export function _clearMcpClientTokenCache(): void {
tokenCache.clear();
}
-/**
- * Stable union of failure reasons. The CLI dispatcher (cli.ts thin-client
- * routing branch, v0.31.1) uses an exhaustive TS switch over this union to
- * produce canned, actionable user messages — adding a new variant fails
- * compilation until every dispatcher knows what to render.
- *
- * v0.31.1 additions:
- * - `kind` sub-tag on `network` errors distinguishes 'unreachable' /
- * 'timeout' / 'aborted' so callers can render the right hint.
- * - `code` field on `tool_error` carries the MCP server's `error.code` (when
- * present) so the dispatcher can map missing-scope etc. to pinpoint hints.
- */
-export type RemoteMcpErrorReason =
- | 'config'
- | 'discovery'
- | 'auth'
- | 'auth_after_refresh'
- /** OAuth /token answered 429; `detail.retry_after_s` carries its Retry-After. */
- | 'rate_limited'
- /** OAuth /token failed after discovery succeeded (non-auth HTTP status or bad body). */
- | 'token'
- | 'network'
- | 'tool_error'
- | 'parse';
-
-export interface RemoteMcpErrorDetail {
- status?: number;
- mcp_url?: string;
- /** v0.31.1: sub-tag for network errors (timeout vs aborted vs generic). */
- kind?: 'timeout' | 'aborted' | 'unreachable';
- /** v0.31.1: server-supplied error code on tool_error (e.g. 'missing_scope'). */
- code?: string;
- /** Seconds the server asked us to wait before minting again (rate_limited). */
- retry_after_s?: number;
- /** An accepted mutation's receipt survives the transport's tool-error wrapper. */
- write_request?: WriteReceipt;
- write_error?: WriteErrorCode;
- /** Retained even when no acknowledgment proves whether the write was accepted. */
- request_id?: string;
- submission_status?: 'unknown' | 'not_sent';
- message?: string;
- suggestion?: string;
- protocol_version?: 1;
- server_detail?: string;
- docs?: string;
- /** Agent contract v1: canonical registry code (`code`) when it differs from or adds to the wire `error` (kept in `code` above). */
- canonical_code?: string;
- reason?: string;
- why?: string;
- /** Rendered fix as the server sent it (`next` included). */
- fix?: Record<string, unknown>;
- /** Notices from the envelope's `notices` key (error results carry exactly one block). */
- notices?: Array<Record<string, unknown>>;
- contract_version?: 1;
-}
-
-export class RemoteMcpError extends Error {
- constructor(
- public readonly reason: RemoteMcpErrorReason,
- message: string,
- public readonly detail?: RemoteMcpErrorDetail,
- ) {
- super(message);
- this.name = 'RemoteMcpError';
- }
-
- /** Mutation error output shares the CLI/IPC envelope without inventing a receipt. */
- toJSON() {
- const detail = this.detail;
- const unknown = detail?.submission_status === 'unknown';
- const wire = detail?.code ?? 'unavailable';
- return {
- error: wire,
- code: detail?.canonical_code ?? canonicalCodeFor(wire),
- message: detail?.message ?? this.message,
- ...(detail?.request_id ? { request_id: detail.request_id } : {}),
- ...(detail?.submission_status ? { submission_status: detail.submission_status } : {}),
- ...(unknown ? { detail: 'delivery_unknown' } : detail?.server_detail ? { detail: detail.server_detail } : {}),
- suggestion: detail?.suggestion ?? (detail?.request_id
- ? `${unknown ? 'Submission state is unknown. ' : ''}Retry the same operation and arguments with request_id ${detail.request_id}; do not generate a replacement ID.`
- : 'Inspect the remote connection before retrying.'),
- ...(detail?.protocol_version === 1 ? { protocol_version: 1 } : {}),
- ...(detail?.docs ? { docs: detail.docs } : {}),
- ...(detail?.write_request ? { write_request: publicWriteReceipt(detail.write_request) } : {}),
- ...(detail?.write_error ? { write_error: detail.write_error } : {}),
- ...(detail?.reason ? { reason: detail.reason } : {}),
- ...(detail?.why ? { why: detail.why } : {}),
- ...(detail?.fix ? { fix: detail.fix } : {}),
- ...(detail?.notices?.length ? { notices: detail.notices } : {}),
- ...(detail?.contract_version === 1 ? { contract_version: 1 } : {}),
- };
- }
-}
-
/**
* B5 (#5949): a 429 on the /token mint is the host's mint budget, not a
* connectivity fault: code `rate_limited`, a provider-side wait, and the
@@ -638,38 +549,3 @@ export function extractNotices(res: unknown): Array<Record<string, unknown>> {
return out;
}
-/**
- * T15/FOV-1: read the response-level `_meta` from a tool-call envelope
- * (see docs/protocol/MCP_META_CHANNELS.md). Old servers simply lack the
- * field — callers must treat undefined as "no meta", never as an error.
- */
-export function extractResponseMeta(res: unknown): Record<string, unknown> | undefined {
- const meta = (res as { _meta?: unknown } | undefined)?._meta;
- if (meta && typeof meta === 'object' && !Array.isArray(meta)) {
- return meta as Record<string, unknown>;
- }
- return undefined;
-}
-
-/**
- * Params the server reported it ignored (WP3 warn mode): `_meta.warnings`
- * entries with code `unknown_param`, plus the model-visible warning blocks
- * after content[0] for transports that drop `_meta`. Empty for hosts that
- * predate unknown-parameter warnings, which cannot be detected.
- */
-export function ignoredRemoteParams(res: unknown): string[] {
- const names = new Set<string>();
- const warnings = extractResponseMeta(res)?.warnings;
- if (Array.isArray(warnings)) {
- for (const w of warnings as Array<{ code?: unknown; param?: unknown }>) {
- if (w?.code === 'unknown_param' && typeof w.param === 'string') names.add(w.param);
- }
- }
- const content = (res as { content?: unknown[] } | undefined)?.content;
- for (const block of Array.isArray(content) ? content.slice(1) : []) {
- const text = (block as { text?: unknown })?.text;
- if (typeof text !== 'string') continue;
- for (const m of text.matchAll(/^(?:why: )?warning: unknown parameter "([^"]+)" ignored/gm)) names.add(m[1]);
- }
- return [...names];
-}
diff --git a/src/core/operation-load.ts b/src/core/operation-load.ts
new file mode 100644
index 0000000000..ff9e580da8
--- /dev/null
+++ b/src/core/operation-load.ts
@@ -0,0 +1,137 @@
+/**
+ * The one finalize step every operation gets before it runs (central area
+ * taxonomy + output redaction wrapper), and the CLI's per-op loader.
+ *
+ * src/core/operations.ts finalizes the whole registry as it loads. The CLI
+ * runs exactly one op per process, so loadOperation() imports only the module
+ * that defines it (src/core/operation-loaders.generated.ts) and finalizes that
+ * one op the same way, keeping the rest of the handler graph off the
+ * cold-start path. Finalizing is idempotent per op object, so a process
+ * that later loads operations.ts sees the same objects in the same state.
+ */
+import type { Operation } from './ops/contract.ts';
+import { withOutputRedaction } from './search/output-redaction.ts';
+import { OPERATION_LOADERS } from './operation-loaders.generated.ts';
+
+// ---------------------------------------------------------------------------
+// WP4 (amendment 22) — area taxonomy.
+//
+// One central map (single reviewable block) rather than 100+ scattered inline
+// fields. Area NAMES ARE NON-CONTRACTUAL: they group the request_tools
+// catalog and the generated tool-catalog doc; renaming or regrouping is never
+// a breaking change. Every non-localOnly op MUST have an area — enforced by
+// the CI walker in test/mcp-tool-defs.test.ts, so a future op missing from
+// this map fails at PR time. localOnly ops are covered too (harmless; the
+// walker only requires non-localOnly). Ops that declare `area` inline
+// (request_tools) win over this map.
+// ---------------------------------------------------------------------------
+const OP_AREAS: Record<string, string> = {
+ // memory verbs (the frozen protocol facade)
+ recall: 'memory-verbs', remember: 'memory-verbs', entity: 'memory-verbs',
+ synthesize: 'memory-verbs', forget: 'memory-verbs',
+ context_pack: 'memory-verbs', delta: 'memory-verbs',
+ // pages (CRUD, versions, raw payloads, resolution)
+ get_page: 'pages', put_page: 'pages', delete_page: 'pages', list_pages: 'pages',
+ restore_page: 'pages', purge_deleted_pages: 'pages',
+ get_versions: 'pages', revert_version: 'pages',
+ resolve_slugs: 'pages', get_chunks: 'pages',
+ put_raw_data: 'pages', get_raw_data: 'pages',
+ fetch: 'pages', // #4039 deep-research read adapter (search/fetch pair)
+ // search
+ search: 'search', query: 'search', search_by_image: 'search', assemble_evidence: 'search',
+ // tags
+ add_tag: 'tags', remove_tag: 'tags', get_tags: 'tags',
+ // links + graph
+ add_link: 'links', remove_link: 'links', get_links: 'links',
+ get_backlinks: 'links', list_link_sources: 'links', traverse_graph: 'links',
+ find_orphans: 'links',
+ wanted_pages: 'links',
+ // timeline
+ add_timeline_entry: 'timeline', get_timeline: 'timeline',
+ // life chronicle
+ chronicle_day: 'chronicle', chronicle_on_this_day: 'chronicle',
+ chronicle_since: 'chronicle', chronicle_last_seen: 'chronicle',
+ volunteer_chronicle: 'chronicle', chronicle_backfill: 'chronicle',
+ // ontology
+ ontology_get: 'ontology', ontology_propose: 'ontology',
+ ontology_dimensions: 'ontology', ontology_conflicts: 'ontology',
+ // admin + operations
+ get_stats: 'admin', get_health: 'admin', run_doctor: 'admin', mute_notice: 'admin',
+ get_status_snapshot: 'admin', run_onboard: 'admin', run_skillopt: 'admin',
+ migrate_embeddings: 'admin', code_traversal_cache_clear: 'admin', get_write_attribution: 'admin',
+ // identity
+ whoami: 'identity', get_brain_identity: 'identity',
+ // skills
+ list_skills: 'skills', get_skill: 'skills', list_brain_skillpack: 'skills',
+ get_skill_asset: 'skills', put_skill: 'skills', delete_skill: 'skills',
+ get_skill_policy: 'skills', set_skill_policy: 'skills', import_skill_proposal: 'skills',
+ get_skill_retention: 'skills', prune_skill_revisions: 'skills', retain_skill_revision: 'skills',
+ join_brain: 'skills', sync_brain_skills: 'skills', leave_brain: 'skills',
+ // advisor
+ advisor: 'advisor',
+ // sources
+ sources_add: 'sources', sources_list: 'sources', sources_remove: 'sources',
+ sources_status: 'sources',
+ // sync (localOnly)
+ sync_brain: 'sync',
+ // ingest log
+ log_ingest: 'ingest', get_ingest_log: 'ingest',
+ get_usage: 'admin',
+ // files (localOnly)
+ file_list: 'files', file_upload: 'files', file_url: 'files',
+ // jobs (Minions + agent lane)
+ submit_job: 'jobs', get_job: 'jobs', list_jobs: 'jobs', cancel_job: 'jobs',
+ retry_job: 'jobs', get_job_progress: 'jobs', pause_job: 'jobs',
+ resume_job: 'jobs', replay_job: 'jobs', send_job_message: 'jobs',
+ submit_agent: 'jobs', get_agent_job: 'jobs',
+ // takes + think
+ takes_list: 'takes', takes_search: 'takes', think: 'takes',
+ takes_scorecard: 'takes', takes_calibration: 'takes',
+ // hot memory (facts)
+ extract_facts: 'memory', forget_fact: 'memory', confirm_memory: 'memory',
+ // entity extraction lane
+ extract_entities: 'entities', extraction_pending: 'entities',
+ extraction_review: 'entities',
+ // #4224 cross-source entity identity (v1 manual-only)
+ entity_identity_link: 'entities', entity_identity_unlink: 'entities',
+ entity_identity_list: 'entities',
+ // v0.47 open-loop engine (google source kind)
+ open_loops: 'loops', loops_close: 'loops', loops_mute: 'loops', loops_unmute: 'loops',
+ // insight / signal reads
+ get_recent_salience: 'insights', find_anomalies: 'insights',
+ find_contradictions: 'insights', find_experts: 'insights',
+ find_trajectory: 'insights', get_calibration_profile: 'insights',
+ volunteer_context: 'insights', get_recent_transcripts: 'insights',
+ // code intelligence
+ code_callers: 'code', code_callees: 'code', code_def: 'code',
+ code_refs: 'code', code_blast: 'code', code_flow: 'code',
+ // schema packs
+ get_active_schema_pack: 'schema', list_schema_packs: 'schema',
+ schema_stats: 'schema', schema_lint: 'schema', schema_graph: 'schema',
+ schema_explain_type: 'schema', schema_review_orphans: 'schema',
+ schema_apply_mutations: 'schema', reload_schema_pack: 'schema',
+ // discovery
+ request_tools: 'discovery',
+};
+
+const finalized = new WeakSet<Operation>();
+
+export function finalizeOperation(op: Operation): void {
+ if (finalized.has(op)) return;
+ finalized.add(op);
+ if (op.area === undefined && OP_AREAS[op.name] !== undefined) {
+ op.area = OP_AREAS[op.name];
+ }
+ op.handler = withOutputRedaction(op);
+}
+
+/** The finalized operation named `name`, loading only the module that defines it. */
+export async function loadOperation(name: string): Promise<Operation | undefined> {
+ const entry = OPERATION_LOADERS[name];
+ if (!entry) return undefined;
+ const [load, exportName] = entry;
+ const exported = (await load())[exportName] as Operation | Operation[];
+ const op = Array.isArray(exported) ? exported.find(o => o.name === name) : exported;
+ if (op) finalizeOperation(op);
+ return op;
+}
diff --git a/src/core/operation-loaders.generated.ts b/src/core/operation-loaders.generated.ts
new file mode 100644
index 0000000000..2233653747
--- /dev/null
+++ b/src/core/operation-loaders.generated.ts
@@ -0,0 +1,220 @@
+// AUTO-GENERATED by scripts/build-operation-manifest.ts — do not edit by hand.
+// Regenerate: bun run build:operation-manifest
+// Freshness pinned by test/operation-manifest.test.ts.
+//
+// Merge conflict here? Take either side wholesale, then re-run the command above.
+//
+// Operation name -> [loader of its defining module, export holding it].
+// String-literal import()s so bun --compile embeds every module.
+
+const load_admin = () => import('./ops/admin.ts') as Promise<Record<string, unknown>>;
+const load_attribution = () => import('./ops/attribution.ts') as Promise<Record<string, unknown>>;
+const load_brain_membership = () => import('./ops/brain-membership.ts') as Promise<Record<string, unknown>>;
+const load_calibration = () => import('./ops/calibration.ts') as Promise<Record<string, unknown>>;
+const load_chronicle = () => import('./ops/chronicle.ts') as Promise<Record<string, unknown>>;
+const load_chunks = () => import('./ops/chunks.ts') as Promise<Record<string, unknown>>;
+const load_code_intel = () => import('./ops/code-intel.ts') as Promise<Record<string, unknown>>;
+const load_connectors = () => import('./ops/connectors.ts') as Promise<Record<string, unknown>>;
+const load_embedding_migration = () => import('./ops/embedding-migration.ts') as Promise<Record<string, unknown>>;
+const load_entity_identity = () => import('./ops/entity-identity.ts') as Promise<Record<string, unknown>>;
+const load_extraction = () => import('./ops/extraction.ts') as Promise<Record<string, unknown>>;
+const load_facts = () => import('./ops/facts.ts') as Promise<Record<string, unknown>>;
+const load_feedback = () => import('./ops/feedback.ts') as Promise<Record<string, unknown>>;
+const load_files = () => import('./ops/files.ts') as Promise<Record<string, unknown>>;
+const load_image = () => import('./ops/image.ts') as Promise<Record<string, unknown>>;
+const load_ingest_log = () => import('./ops/ingest-log.ts') as Promise<Record<string, unknown>>;
+const load_insights = () => import('./ops/insights.ts') as Promise<Record<string, unknown>>;
+const load_jobs = () => import('./ops/jobs.ts') as Promise<Record<string, unknown>>;
+const load_links = () => import('./ops/links.ts') as Promise<Record<string, unknown>>;
+const load_loops = () => import('./ops/loops.ts') as Promise<Record<string, unknown>>;
+const load_notices = () => import('./ops/notices.ts') as Promise<Record<string, unknown>>;
+const load_orphans = () => import('./ops/orphans.ts') as Promise<Record<string, unknown>>;
+const load_page_batch = () => import('./ops/page-batch.ts') as Promise<Record<string, unknown>>;
+const load_page_edit = () => import('./ops/page-edit.ts') as Promise<Record<string, unknown>>;
+const load_pages = () => import('./ops/pages.ts') as Promise<Record<string, unknown>>;
+const load_persistence = () => import('./ops/persistence.ts') as Promise<Record<string, unknown>>;
+const load_purge = () => import('./ops/purge.ts') as Promise<Record<string, unknown>>;
+const load_raw_data = () => import('./ops/raw-data.ts') as Promise<Record<string, unknown>>;
+const load_request_tools = () => import('./ops/request-tools.ts') as Promise<Record<string, unknown>>;
+const load_salience = () => import('./ops/salience.ts') as Promise<Record<string, unknown>>;
+const load_schema_packs = () => import('./ops/schema-packs.ts') as Promise<Record<string, unknown>>;
+const load_search = () => import('./ops/search.ts') as Promise<Record<string, unknown>>;
+const load_skillopt = () => import('./ops/skillopt.ts') as Promise<Record<string, unknown>>;
+const load_skills_catalog = () => import('./ops/skills-catalog.ts') as Promise<Record<string, unknown>>;
+const load_sources = () => import('./ops/sources.ts') as Promise<Record<string, unknown>>;
+const load_sync_status = () => import('./ops/sync-status.ts') as Promise<Record<string, unknown>>;
+const load_tags = () => import('./ops/tags.ts') as Promise<Record<string, unknown>>;
+const load_takes = () => import('./ops/takes.ts') as Promise<Record<string, unknown>>;
+const load_timeline = () => import('./ops/timeline.ts') as Promise<Record<string, unknown>>;
+const load_transcripts = () => import('./ops/transcripts.ts') as Promise<Record<string, unknown>>;
+const load_trust = () => import('./ops/trust.ts') as Promise<Record<string, unknown>>;
+const load_usage = () => import('./ops/usage.ts') as Promise<Record<string, unknown>>;
+const load_verbs = () => import('./verbs.ts') as Promise<Record<string, unknown>>;
+
+export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<string, unknown>>, string]> = {
+ "remember": [load_verbs, "verbOperations"],
+ "entity": [load_verbs, "verbOperations"],
+ "synthesize": [load_verbs, "verbOperations"],
+ "forget": [load_verbs, "verbOperations"],
+ "get_page": [load_pages, "pagesOperations"],
+ "put_page": [load_pages, "pagesOperations"],
+ "delete_page": [load_pages, "pagesOperations"],
+ "list_pages": [load_pages, "pagesOperations"],
+ "restore_page": [load_pages, "pagesOperations"],
+ "purge_deleted_pages": [load_pages, "pagesOperations"],
+ "capture": [load_pages, "pagesOperations"],
+ "fetch": [load_pages, "pagesOperations"],
+ "edit_page": [load_page_edit, "pageEditOperations"],
+ "put_pages": [load_page_batch, "pageBatchOperations"],
+ "get_write_request": [load_persistence, "persistenceOperations"],
+ "list_write_requests": [load_persistence, "persistenceOperations"],
+ "cancel_write_request": [load_persistence, "persistenceOperations"],
+ "search": [load_search, "searchOperations"],
+ "query": [load_search, "searchOperations"],
+ "assemble_evidence": [load_search, "searchOperations"],
+ "search_stats": [load_search, "searchOperations"],
+ "search_modes": [load_search, "searchOperations"],
+ "search_tune": [load_search, "searchOperations"],
+ "cache_stats": [load_search, "searchOperations"],
+ "rate_answer": [load_feedback, "feedbackOperations"],
+ "search_by_image": [load_image, "imageOperations"],
+ "add_tag": [load_tags, "tagsOperations"],
+ "remove_tag": [load_tags, "tagsOperations"],
+ "get_tags": [load_tags, "tagsOperations"],
+ "add_link": [load_links, "linksOperations"],
+ "remove_link": [load_links, "linksOperations"],
+ "get_links": [load_links, "linksOperations"],
+ "get_backlinks": [load_links, "linksOperations"],
+ "list_link_sources": [load_links, "linksOperations"],
+ "traverse_graph": [load_links, "linksOperations"],
+ "wanted_pages": [load_links, "linksOperations"],
+ "add_timeline_entry": [load_timeline, "timelineOperations"],
+ "get_timeline": [load_timeline, "timelineOperations"],
+ "get_stats": [load_admin, "adminOperations"],
+ "get_health": [load_admin, "adminOperations"],
+ "run_doctor": [load_admin, "adminOperations"],
+ "get_versions": [load_admin, "adminOperations"],
+ "revert_version": [load_admin, "adminOperations"],
+ "get_brain_identity": [load_admin, "adminOperations"],
+ "quarantine_list": [load_admin, "adminOperations"],
+ "get_write_attribution": [load_attribution, "attributionOperations"],
+ "confirm_memory": [load_trust, "trustOperations"],
+ "list_skills": [load_skills_catalog, "skillsCatalogOperations"],
+ "get_skill": [load_skills_catalog, "skillsCatalogOperations"],
+ "list_brain_skillpack": [load_skills_catalog, "skillsCatalogOperations"],
+ "advisor": [load_skills_catalog, "skillsCatalogOperations"],
+ "get_status_snapshot": [load_skills_catalog, "skillsCatalogOperations"],
+ "get_skill_asset": [load_skills_catalog, "skillsCatalogOperations"],
+ "put_skill": [load_skills_catalog, "skillsCatalogOperations"],
+ "delete_skill": [load_skills_catalog, "skillsCatalogOperations"],
+ "set_skill_policy": [load_skills_catalog, "skillsCatalogOperations"],
+ "get_skill_policy": [load_skills_catalog, "skillsCatalogOperations"],
+ "get_skill_retention": [load_skills_catalog, "skillsCatalogOperations"],
+ "prune_skill_revisions": [load_skills_catalog, "skillsCatalogOperations"],
+ "retain_skill_revision": [load_skills_catalog, "skillsCatalogOperations"],
+ "import_skill_proposal": [load_skills_catalog, "skillsCatalogOperations"],
+ "join_brain": [load_brain_membership, "brainMembershipOperations"],
+ "sync_brain_skills": [load_brain_membership, "brainMembershipOperations"],
+ "leave_brain": [load_brain_membership, "brainMembershipOperations"],
+ "sync_brain": [load_sync_status, "syncStatusOperations"],
+ "put_raw_data": [load_raw_data, "rawDataOperations"],
+ "get_raw_data": [load_raw_data, "rawDataOperations"],
+ "resolve_slugs": [load_chunks, "chunksOperations"],
+ "get_chunks": [load_chunks, "chunksOperations"],
+ "log_ingest": [load_ingest_log, "ingestLogOperations"],
+ "get_ingest_log": [load_ingest_log, "ingestLogOperations"],
+ "get_usage": [load_usage, "usageOperations"],
+ "file_list": [load_files, "filesOperations"],
+ "file_upload": [load_files, "filesOperations"],
+ "file_url": [load_files, "filesOperations"],
+ "submit_job": [load_jobs, "jobsOperations"],
+ "get_job": [load_jobs, "jobsOperations"],
+ "list_jobs": [load_jobs, "jobsOperations"],
+ "cancel_job": [load_jobs, "jobsOperations"],
+ "retry_job": [load_jobs, "jobsOperations"],
+ "get_job_progress": [load_jobs, "jobsOperations"],
+ "pause_job": [load_jobs, "jobsOperations"],
+ "resume_job": [load_jobs, "jobsOperations"],
+ "replay_job": [load_jobs, "jobsOperations"],
+ "send_job_message": [load_jobs, "jobsOperations"],
+ "submit_agent": [load_jobs, "jobsOperations"],
+ "get_agent_job": [load_jobs, "jobsOperations"],
+ "get_job_stats": [load_jobs, "jobsOperations"],
+ "find_orphans": [load_orphans, "orphansOperations"],
+ "get_calibration_profile": [load_calibration, "calibrationOperations"],
+ "takes_list": [load_takes, "takesOperations"],
+ "takes_search": [load_takes, "takesOperations"],
+ "think": [load_takes, "takesOperations"],
+ "takes_scorecard": [load_takes, "takesOperations"],
+ "takes_calibration": [load_takes, "takesOperations"],
+ "takes_add": [load_takes, "takesOperations"],
+ "takes_update": [load_takes, "takesOperations"],
+ "takes_resolve": [load_takes, "takesOperations"],
+ "takes_supersede": [load_takes, "takesOperations"],
+ "takes_remove": [load_takes, "takesOperations"],
+ "takes_rebuild": [load_takes, "takesOperations"],
+ "whoami": [load_sources, "sourcesOperations"],
+ "sources_add": [load_sources, "sourcesOperations"],
+ "sources_list": [load_sources, "sourcesOperations"],
+ "sources_remove": [load_sources, "sourcesOperations"],
+ "sources_status": [load_sources, "sourcesOperations"],
+ "sources_inspect": [load_sources, "sourcesOperations"],
+ "request_tools": [load_request_tools, "requestToolsOperations"],
+ "get_recent_salience": [load_salience, "salienceOperations"],
+ "find_anomalies": [load_salience, "salienceOperations"],
+ "get_recent_transcripts": [load_transcripts, "transcriptsOperations"],
+ "connectors_status": [load_connectors, "connectorsOperations"],
+ "connector_sync": [load_connectors, "connectorsOperations"],
+ "chronicle_day": [load_chronicle, "chronicleOperations"],
+ "chronicle_on_this_day": [load_chronicle, "chronicleOperations"],
+ "chronicle_since": [load_chronicle, "chronicleOperations"],
+ "chronicle_last_seen": [load_chronicle, "chronicleOperations"],
+ "ontology_get": [load_chronicle, "chronicleOperations"],
+ "ontology_propose": [load_chronicle, "chronicleOperations"],
+ "ontology_dimensions": [load_chronicle, "chronicleOperations"],
+ "ontology_conflicts": [load_chronicle, "chronicleOperations"],
+ "volunteer_chronicle": [load_chronicle, "chronicleOperations"],
+ "chronicle_backfill": [load_chronicle, "chronicleOperations"],
+ "volunteer_context": [load_insights, "volunteer_context"],
+ "extract_entities": [load_extraction, "extractionOperations"],
+ "extraction_pending": [load_extraction, "extractionOperations"],
+ "extraction_review": [load_extraction, "extractionOperations"],
+ "entity_identity_link": [load_entity_identity, "entityIdentityOperations"],
+ "entity_identity_unlink": [load_entity_identity, "entityIdentityOperations"],
+ "entity_identity_list": [load_entity_identity, "entityIdentityOperations"],
+ "extract_facts": [load_facts, "factsOperations"],
+ "recall": [load_facts, "factsOperations"],
+ "context_pack": [load_facts, "factsOperations"],
+ "delta": [load_facts, "factsOperations"],
+ "forget_fact": [load_facts, "factsOperations"],
+ "purge_fact": [load_purge, "purgeOperations"],
+ "list_page_purges": [load_purge, "purgeOperations"],
+ "unpurge_page": [load_purge, "purgeOperations"],
+ "find_contradictions": [load_insights, "find_contradictions"],
+ "find_experts": [load_insights, "find_experts"],
+ "find_trajectory": [load_insights, "find_trajectory"],
+ "code_callers": [load_code_intel, "codeIntelOperations"],
+ "code_callees": [load_code_intel, "codeIntelOperations"],
+ "code_def": [load_code_intel, "codeIntelOperations"],
+ "code_refs": [load_code_intel, "codeIntelOperations"],
+ "code_blast": [load_code_intel, "codeIntelOperations"],
+ "code_flow": [load_code_intel, "codeIntelOperations"],
+ "code_traversal_cache_clear": [load_code_intel, "codeIntelOperations"],
+ "migrate_embeddings": [load_embedding_migration, "embeddingMigrationOperations"],
+ "get_active_schema_pack": [load_schema_packs, "schemaPacksOperations"],
+ "list_schema_packs": [load_schema_packs, "schemaPacksOperations"],
+ "schema_stats": [load_schema_packs, "schemaPacksOperations"],
+ "schema_lint": [load_schema_packs, "schemaPacksOperations"],
+ "schema_graph": [load_schema_packs, "schemaPacksOperations"],
+ "schema_explain_type": [load_schema_packs, "schemaPacksOperations"],
+ "schema_review_orphans": [load_schema_packs, "schemaPacksOperations"],
+ "schema_apply_mutations": [load_schema_packs, "schemaPacksOperations"],
+ "reload_schema_pack": [load_schema_packs, "schemaPacksOperations"],
+ "run_onboard": [load_skillopt, "skilloptOperations"],
+ "run_skillopt": [load_skillopt, "skilloptOperations"],
+ "open_loops": [load_loops, "loopsOperations"],
+ "loops_close": [load_loops, "loopsOperations"],
+ "loops_mute": [load_loops, "loopsOperations"],
+ "loops_unmute": [load_loops, "loopsOperations"],
+ "mute_notice": [load_notices, "noticesOperations"],
+};
diff --git a/src/core/operations.ts b/src/core/operations.ts
index 36f85dd512..c9121414ca 100644
--- a/src/core/operations.ts
+++ b/src/core/operations.ts
@@ -12,7 +12,7 @@ export { MEMORY_VERBS_VERSION };
// operations.ts is unchanged.
import type { Operation } from './ops/contract.ts';
-import { withOutputRedaction } from './search/output-redaction.ts';
+import { finalizeOperation } from './operation-load.ts';
import { registerOpRoutes } from './fix-routing.ts';
// Re-exports: the full previously-exported foundation surface of this module.
@@ -229,112 +229,9 @@ export const operations: Operation[] = [
...loopsOperations, ...noticesOperations, // + agent contract v1 A6 mute_notice — ops/notices.ts
];
-// ---------------------------------------------------------------------------
-// WP4 (amendment 22) — area taxonomy.
-//
-// One central map (single reviewable block) rather than 100+ scattered inline
-// fields. Area NAMES ARE NON-CONTRACTUAL: they group the request_tools
-// catalog and the generated tool-catalog doc; renaming or regrouping is never
-// a breaking change. Every non-localOnly op MUST have an area — enforced by
-// the CI walker in test/mcp-tool-defs.test.ts, so a future op missing from
-// this map fails at PR time. localOnly ops are covered too (harmless; the
-// walker only requires non-localOnly). Ops that declare `area` inline
-// (request_tools) win over this map.
-// ---------------------------------------------------------------------------
-const OP_AREAS: Record<string, string> = {
- // memory verbs (the frozen protocol facade)
- recall: 'memory-verbs', remember: 'memory-verbs', entity: 'memory-verbs',
- synthesize: 'memory-verbs', forget: 'memory-verbs',
- context_pack: 'memory-verbs', delta: 'memory-verbs',
- // pages (CRUD, versions, raw payloads, resolution)
- get_page: 'pages', put_page: 'pages', delete_page: 'pages', list_pages: 'pages',
- restore_page: 'pages', purge_deleted_pages: 'pages',
- get_versions: 'pages', revert_version: 'pages',
- resolve_slugs: 'pages', get_chunks: 'pages',
- put_raw_data: 'pages', get_raw_data: 'pages',
- fetch: 'pages', // #4039 deep-research read adapter (search/fetch pair)
- // search
- search: 'search', query: 'search', search_by_image: 'search', assemble_evidence: 'search',
- // tags
- add_tag: 'tags', remove_tag: 'tags', get_tags: 'tags',
- // links + graph
- add_link: 'links', remove_link: 'links', get_links: 'links',
- get_backlinks: 'links', list_link_sources: 'links', traverse_graph: 'links',
- find_orphans: 'links',
- wanted_pages: 'links',
- // timeline
- add_timeline_entry: 'timeline', get_timeline: 'timeline',
- // life chronicle
- chronicle_day: 'chronicle', chronicle_on_this_day: 'chronicle',
- chronicle_since: 'chronicle', chronicle_last_seen: 'chronicle',
- volunteer_chronicle: 'chronicle', chronicle_backfill: 'chronicle',
- // ontology
- ontology_get: 'ontology', ontology_propose: 'ontology',
- ontology_dimensions: 'ontology', ontology_conflicts: 'ontology',
- // admin + operations
- get_stats: 'admin', get_health: 'admin', run_doctor: 'admin', mute_notice: 'admin',
- get_status_snapshot: 'admin', run_onboard: 'admin', run_skillopt: 'admin',
- migrate_embeddings: 'admin', code_traversal_cache_clear: 'admin', get_write_attribution: 'admin',
- // identity
- whoami: 'identity', get_brain_identity: 'identity',
- // skills
- list_skills: 'skills', get_skill: 'skills', list_brain_skillpack: 'skills',
- get_skill_asset: 'skills', put_skill: 'skills', delete_skill: 'skills',
- get_skill_policy: 'skills', set_skill_policy: 'skills', import_skill_proposal: 'skills',
- get_skill_retention: 'skills', prune_skill_revisions: 'skills', retain_skill_revision: 'skills',
- join_brain: 'skills', sync_brain_skills: 'skills', leave_brain: 'skills',
- // advisor
- advisor: 'advisor',
- // sources
- sources_add: 'sources', sources_list: 'sources', sources_remove: 'sources',
- sources_status: 'sources',
- // sync (localOnly)
- sync_brain: 'sync',
- // ingest log
- log_ingest: 'ingest', get_ingest_log: 'ingest',
- get_usage: 'admin',
- // files (localOnly)
- file_list: 'files', file_upload: 'files', file_url: 'files',
- // jobs (Minions + agent lane)
- submit_job: 'jobs', get_job: 'jobs', list_jobs: 'jobs', cancel_job: 'jobs',
- retry_job: 'jobs', get_job_progress: 'jobs', pause_job: 'jobs',
- resume_job: 'jobs', replay_job: 'jobs', send_job_message: 'jobs',
- submit_agent: 'jobs', get_agent_job: 'jobs',
- // takes + think
- takes_list: 'takes', takes_search: 'takes', think: 'takes',
- takes_scorecard: 'takes', takes_calibration: 'takes',
- // hot memory (facts)
- extract_facts: 'memory', forget_fact: 'memory', confirm_memory: 'memory',
- // entity extraction lane
- extract_entities: 'entities', extraction_pending: 'entities',
- extraction_review: 'entities',
- // #4224 cross-source entity identity (v1 manual-only)
- entity_identity_link: 'entities', entity_identity_unlink: 'entities',
- entity_identity_list: 'entities',
- // v0.47 open-loop engine (google source kind)
- open_loops: 'loops', loops_close: 'loops', loops_mute: 'loops', loops_unmute: 'loops',
- // insight / signal reads
- get_recent_salience: 'insights', find_anomalies: 'insights',
- find_contradictions: 'insights', find_experts: 'insights',
- find_trajectory: 'insights', get_calibration_profile: 'insights',
- volunteer_context: 'insights', get_recent_transcripts: 'insights',
- // code intelligence
- code_callers: 'code', code_callees: 'code', code_def: 'code',
- code_refs: 'code', code_blast: 'code', code_flow: 'code',
- // schema packs
- get_active_schema_pack: 'schema', list_schema_packs: 'schema',
- schema_stats: 'schema', schema_lint: 'schema', schema_graph: 'schema',
- schema_explain_type: 'schema', schema_review_orphans: 'schema',
- schema_apply_mutations: 'schema', reload_schema_pack: 'schema',
- // discovery
- request_tools: 'discovery',
-};
-for (const op of operations) {
- if (op.area === undefined && OP_AREAS[op.name] !== undefined) {
- op.area = OP_AREAS[op.name];
- }
- op.handler = withOutputRedaction(op);
-}
+// Area taxonomy + output redaction: one finalize step shared with the CLI's
+// per-op loader (src/core/operation-load.ts).
+for (const op of operations) finalizeOperation(op);
export const operationsByName = Object.fromEntries(
operations.map(op => [op.name, op]),
diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.ts
index 43791346bc..e4edbaa08b 100644
--- a/src/core/ops/admin.ts
+++ b/src/core/ops/admin.ts
@@ -1,4 +1,3 @@
-import { pageMutationSource, submitPageMutation } from '../persistence/page-mutations.ts';
import { PAGE_MUTATION_PARAMS } from '../persistence/params.ts';
import { readPolicyOpts } from './context.ts';
import { attributeVersions, canReadWriteAttribution } from './attribution.ts';
@@ -234,6 +233,7 @@ const revert_version: Operation = {
mutating: true,
scope: 'write',
handler: async (ctx, p) => {
+ const { pageMutationSource, submitPageMutation } = await import('../persistence/page-mutations.ts');
pageMutationSource(ctx, p, 'revert_version');
enforceClientSlugFence(ctx, p.slug as string, 'revert_version');
if (ctx.dryRun) return { dry_run: true, action: 'revert_version', slug: p.slug, version_id: p.version_id };
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 9cf7cdc687..83c5464844 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -755,8 +755,8 @@ export interface Operation {
* ARE NON-CONTRACTUAL: they exist so an agent can scan ~20 groups instead
* of ~100 flat names; renaming/regrouping is never a breaking change.
* Required (by the CI walker in test/mcp-tool-defs.test.ts) on every
- * non-localOnly op; populated centrally via OP_AREAS at the bottom of
- * this file.
+ * non-localOnly op; populated centrally via OP_AREAS in
+ * src/core/operation-load.ts.
*/
area?: string;
/**
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index 2ddc8f1220..df554ddb9c 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -23,6 +23,7 @@ import { contentRefusalFromReceipt } from '../import-screen.ts';
import { fenceIssuesFromDetail, fenceLocationFromDetail } from '../fence-repair/refusal.ts';
import { heldFileDiagnostic } from './verb-errors.ts';
import { isMissingPageMessage } from './page-identity.ts';
+import { registerPersistenceConsumerConfig } from '../embedding-disabled.ts';
interface Service { consumer: PersistenceConsumerLike; heartbeat?: ConsumerHeartbeat; stopping: boolean; unregisterStop?: () => void; unregisterReopen?: () => void; }
const services = new WeakMap<BrainEngine, Service>();
@@ -184,6 +185,7 @@ export function persistenceConsumerConfig(engine: BrainEngine): GBrainConfig | u
const service = services.get(engine);
return service && !service.stopping ? service.consumer.config : undefined;
}
+registerPersistenceConsumerConfig(persistenceConsumerConfig);
export function persistenceConsumerStatus(engine: BrainEngine) {
const service = services.get(engine);
return service ? { state: service.stopping ? 'closing' : 'open', ...service.consumer.status() }
diff --git a/src/core/remote-mcp-error.ts b/src/core/remote-mcp-error.ts
new file mode 100644
index 0000000000..d491e31011
--- /dev/null
+++ b/src/core/remote-mcp-error.ts
@@ -0,0 +1,138 @@
+/**
+ * The thin-client error class and the tool-result envelope readers that a
+ * local CLI command also names (instanceof checks, ignored-param warnings),
+ * split out of mcp-client.ts so naming them never loads the MCP SDK types and
+ * zod schema graph behind a remote call. mcp-client.ts re-exports all of it.
+ */
+import { canonicalCodeFor } from './error-catalogue.ts';
+import { publicWriteReceipt, type WriteErrorCode, type WriteReceipt } from './persistence/types.ts';
+
+/**
+ * Stable union of failure reasons. The CLI dispatcher (cli.ts thin-client
+ * routing branch, v0.31.1) uses an exhaustive TS switch over this union to
+ * produce canned, actionable user messages — adding a new variant fails
+ * compilation until every dispatcher knows what to render.
+ *
+ * v0.31.1 additions:
+ * - `kind` sub-tag on `network` errors distinguishes 'unreachable' /
+ * 'timeout' / 'aborted' so callers can render the right hint.
+ * - `code` field on `tool_error` carries the MCP server's `error.code` (when
+ * present) so the dispatcher can map missing-scope etc. to pinpoint hints.
+ */
+export type RemoteMcpErrorReason =
+ | 'config'
+ | 'discovery'
+ | 'auth'
+ | 'auth_after_refresh'
+ /** OAuth /token answered 429; `detail.retry_after_s` carries its Retry-After. */
+ | 'rate_limited'
+ /** OAuth /token failed after discovery succeeded (non-auth HTTP status or bad body). */
+ | 'token'
+ | 'network'
+ | 'tool_error'
+ | 'parse';
+
+export interface RemoteMcpErrorDetail {
+ status?: number;
+ mcp_url?: string;
+ /** v0.31.1: sub-tag for network errors (timeout vs aborted vs generic). */
+ kind?: 'timeout' | 'aborted' | 'unreachable';
+ /** v0.31.1: server-supplied error code on tool_error (e.g. 'missing_scope'). */
+ code?: string;
+ /** Seconds the server asked us to wait before minting again (rate_limited). */
+ retry_after_s?: number;
+ /** An accepted mutation's receipt survives the transport's tool-error wrapper. */
+ write_request?: WriteReceipt;
+ write_error?: WriteErrorCode;
+ /** Retained even when no acknowledgment proves whether the write was accepted. */
+ request_id?: string;
+ submission_status?: 'unknown' | 'not_sent';
+ message?: string;
+ suggestion?: string;
+ protocol_version?: 1;
+ server_detail?: string;
+ docs?: string;
+ /** Agent contract v1: canonical registry code (`code`) when it differs from or adds to the wire `error` (kept in `code` above). */
+ canonical_code?: string;
+ reason?: string;
+ why?: string;
+ /** Rendered fix as the server sent it (`next` included). */
+ fix?: Record<string, unknown>;
+ /** Notices from the envelope's `notices` key (error results carry exactly one block). */
+ notices?: Array<Record<string, unknown>>;
+ contract_version?: 1;
+}
+
+export class RemoteMcpError extends Error {
+ constructor(
+ public readonly reason: RemoteMcpErrorReason,
+ message: string,
+ public readonly detail?: RemoteMcpErrorDetail,
+ ) {
+ super(message);
+ this.name = 'RemoteMcpError';
+ }
+
+ /** Mutation error output shares the CLI/IPC envelope without inventing a receipt. */
+ toJSON() {
+ const detail = this.detail;
+ const unknown = detail?.submission_status === 'unknown';
+ const wire = detail?.code ?? 'unavailable';
+ return {
+ error: wire,
+ code: detail?.canonical_code ?? canonicalCodeFor(wire),
+ message: detail?.message ?? this.message,
+ ...(detail?.request_id ? { request_id: detail.request_id } : {}),
+ ...(detail?.submission_status ? { submission_status: detail.submission_status } : {}),
+ ...(unknown ? { detail: 'delivery_unknown' } : detail?.server_detail ? { detail: detail.server_detail } : {}),
+ suggestion: detail?.suggestion ?? (detail?.request_id
+ ? `${unknown ? 'Submission state is unknown. ' : ''}Retry the same operation and arguments with request_id ${detail.request_id}; do not generate a replacement ID.`
+ : 'Inspect the remote connection before retrying.'),
+ ...(detail?.protocol_version === 1 ? { protocol_version: 1 } : {}),
+ ...(detail?.docs ? { docs: detail.docs } : {}),
+ ...(detail?.write_request ? { write_request: publicWriteReceipt(detail.write_request) } : {}),
+ ...(detail?.write_error ? { write_error: detail.write_error } : {}),
+ ...(detail?.reason ? { reason: detail.reason } : {}),
+ ...(detail?.why ? { why: detail.why } : {}),
+ ...(detail?.fix ? { fix: detail.fix } : {}),
+ ...(detail?.notices?.length ? { notices: detail.notices } : {}),
+ ...(detail?.contract_version === 1 ? { contract_version: 1 } : {}),
+ };
+ }
+}
+
+/**
+ * T15/FOV-1: read the response-level `_meta` from a tool-call envelope
+ * (see docs/protocol/MCP_META_CHANNELS.md). Old servers simply lack the
+ * field — callers must treat undefined as "no meta", never as an error.
+ */
+export function extractResponseMeta(res: unknown): Record<string, unknown> | undefined {
+ const meta = (res as { _meta?: unknown } | undefined)?._meta;
+ if (meta && typeof meta === 'object' && !Array.isArray(meta)) {
+ return meta as Record<string, unknown>;
+ }
+ return undefined;
+}
+
+/**
+ * Params the server reported it ignored (WP3 warn mode): `_meta.warnings`
+ * entries with code `unknown_param`, plus the model-visible warning blocks
+ * after content[0] for transports that drop `_meta`. Empty for hosts that
+ * predate unknown-parameter warnings, which cannot be detected.
+ */
+export function ignoredRemoteParams(res: unknown): string[] {
+ const names = new Set<string>();
+ const warnings = extractResponseMeta(res)?.warnings;
+ if (Array.isArray(warnings)) {
+ for (const w of warnings as Array<{ code?: unknown; param?: unknown }>) {
+ if (w?.code === 'unknown_param' && typeof w.param === 'string') names.add(w.param);
+ }
+ }
+ const content = (res as { content?: unknown[] } | undefined)?.content;
+ for (const block of Array.isArray(content) ? content.slice(1) : []) {
+ const text = (block as { text?: unknown })?.text;
+ if (typeof text !== 'string') continue;
+ for (const m of text.matchAll(/^(?:why: )?warning: unknown parameter "([^"]+)" ignored/gm)) names.add(m[1]);
+ }
+ return [...names];
+}
diff --git a/test/cli-cold-start-graph.test.ts b/test/cli-cold-start-graph.test.ts
new file mode 100644
index 0000000000..c0dc98d6a8
--- /dev/null
+++ b/test/cli-cold-start-graph.test.ts
@@ -0,0 +1,89 @@
+/**
+ * CLI cold start (GBRA-75 wave 11): pins the module-graph cuts that keep a
+ * local command off code it never runs, and that each cut leaves behavior
+ * unchanged.
+ *
+ * - runSharedOperation loads only the module that defines the op
+ * (src/core/operation-load.ts) and finalizes it exactly as
+ * src/core/operations.ts does: same object, same area, same redaction
+ * wrapper, never wrapped twice when the registry loads later.
+ * - factEmbeddingDisabled reads the persistence consumer's config through a
+ * reader persistence/service.ts registers as it loads, so a read-only
+ * command never imports that graph.
+ * - Importing the CLI dispatcher loads neither the MCP SDK (remote calls only)
+ * nor the search evidence-delivery graph; configuring the AI gateway loads
+ * no AI SDK until a provider call runs.
+ */
+import { describe, expect, test } from 'bun:test';
+import { resolve } from 'path';
+import { loadOperation } from '../src/core/operation-load.ts';
+import { operations, operationsByName } from '../src/core/operations.ts';
+
+const REPO_ROOT = resolve(import.meta.dir, '..');
+
+function probe(lines: string[]): unknown {
+ const out = Bun.spawnSync([process.execPath, '-e', lines.join('\n')], {
+ cwd: REPO_ROOT,
+ env: { ...process.env, GBRAIN_HOME: '/nonexistent-gbrain-home' },
+ });
+ if (out.exitCode !== 0) throw new Error(out.stderr.toString());
+ return JSON.parse(out.stdout.toString().trim().split('\n').pop()!);
+}
+
+describe('per-op loading', () => {
+ test('every registry op loads as the same finalized object', async () => {
+ for (const op of operations) {
+ expect(await loadOperation(op.name)).toBe(operationsByName[op.name]!);
+ }
+ expect(await loadOperation('no_such_op')).toBeUndefined();
+ });
+
+ test('a lone load finalizes like the registry, and the registry never re-wraps it', () => {
+ const result = probe([
+ "const { loadOperation } = await import('./src/core/operation-load.ts');",
+ "const names = ['search', 'query', 'get_stats', 'get_page', 'remember', 'volunteer_context', 'list_pages'];",
+ 'const loaded = {};',
+ 'for (const n of names) { const op = await loadOperation(n); loaded[n] = { op, handler: op.handler, area: op.area }; }',
+ "const registryLoaded = Object.keys(require.cache).some(k => k.endsWith('/src/core/operations.ts'));",
+ "const { operationsByName } = await import('./src/core/operations.ts');",
+ 'console.log(JSON.stringify({ registryLoaded, rows: names.map(n => ({ n, same: operationsByName[n] === loaded[n].op, handler: operationsByName[n].handler === loaded[n].handler, area: loaded[n].area ?? null })) }));',
+ ]) as { registryLoaded: boolean; rows: Array<{ n: string; same: boolean; handler: boolean; area: string | null }> };
+ expect(result.registryLoaded).toBe(false);
+ for (const row of result.rows) {
+ expect(row).toEqual({ n: row.n, same: true, handler: true, area: operationsByName[row.n]!.area ?? null });
+ }
+ });
+
+ test('retrieval ops carry the output-redaction wrapper on the lone-load path', () => {
+ const result = probe([
+ "const { loadOperation } = await import('./src/core/operation-load.ts');",
+ "const { searchOperations } = await import('./src/core/ops/search.ts');",
+ "const raw = searchOperations.find(o => o.name === 'search').handler;",
+ "const op = await loadOperation('search');",
+ "console.log(JSON.stringify({ policy: op.outputRedaction, wrapped: op.handler !== raw }));",
+ ]) as { policy: unknown; wrapped: boolean };
+ expect(result.policy).toBe(operationsByName.search!.outputRedaction);
+ expect(result.wrapped).toBe(true);
+ });
+});
+
+describe('cold-start module graph', () => {
+ test('factEmbeddingDisabled without a running consumer does not load persistence/service.ts', () => {
+ const loaded = probe([
+ "const { factEmbeddingDisabled } = await import('./src/core/embedding-disabled.ts');",
+ "const disabled = await factEmbeddingDisabled({ getConfig: async () => null });",
+ "console.log(JSON.stringify({ disabled, service: Object.keys(require.cache).some(k => k.endsWith('/src/core/persistence/service.ts')) }));",
+ ]);
+ expect(loaded).toEqual({ disabled: false, service: false });
+ });
+
+ test('the CLI dispatcher and a configured gateway load no MCP SDK, AI SDK or evidence-delivery graph', () => {
+ const loaded = probe([
+ "await import('./src/cli/main.ts');",
+ "const { configureGateway } = await import('./src/core/ai/gateway.ts');",
+ "configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });",
+ "console.log(JSON.stringify(Object.keys(require.cache).filter(k => /node_modules\\/(@modelcontextprotocol|ai|@opentelemetry)\\//.test(k) || k.endsWith('/src/core/search/evidence-delivery.ts') || k.endsWith('/src/core/mcp-client.ts')).map(k => k.replace(/.*node_modules\\//, '').split('/').slice(0, 2).join('/')).filter((v, i, a) => a.indexOf(v) === i)));",
+ ]);
+ expect(loaded).toEqual([]);
+ });
+});
diff --git a/test/mcp-tool-defs.test.ts b/test/mcp-tool-defs.test.ts
index 4bec570e18..e9863ae8de 100644
--- a/test/mcp-tool-defs.test.ts
+++ b/test/mcp-tool-defs.test.ts
@@ -332,7 +332,7 @@ describe('param description completeness (WP3)', () => {
// WP4 (amendment 22): every non-localOnly op must carry an `area` — the
// request_tools catalog groups by it, and an op missing from the central
- // OP_AREAS map in operations.ts would silently land in the 'other' bucket.
+ // OP_AREAS map in operation-load.ts would silently land in the 'other' bucket.
// Area NAMES are non-contractual; presence is not.
test('every non-localOnly op carries a non-empty area (WP4)', () => {
const violations: string[] = [];
diff --git a/test/operation-manifest.test.ts b/test/operation-manifest.test.ts
index e48ec50e96..6381175538 100644
--- a/test/operation-manifest.test.ts
+++ b/test/operation-manifest.test.ts
@@ -8,7 +8,7 @@
import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'fs';
import { resolve } from 'path';
-import { OPERATION_MANIFEST_PATH, renderOperationManifest } from '../scripts/build-operation-manifest.ts';
+import { OPERATION_LOADERS_PATH, OPERATION_MANIFEST_PATH, renderOperationLoaders, renderOperationManifest } from '../scripts/build-operation-manifest.ts';
import { OPERATION_MANIFEST } from '../src/core/operation-manifest.generated.ts';
import { operations } from '../src/core/operations.ts';
@@ -19,6 +19,10 @@ describe('operation manifest', () => {
expect(readFileSync(OPERATION_MANIFEST_PATH, 'utf-8')).toBe(renderOperationManifest());
});
+ test('committed loader table matches a fresh render (run `bun run build:operation-manifest`)', async () => {
+ expect(readFileSync(OPERATION_LOADERS_PATH, 'utf-8')).toBe(await renderOperationLoaders());
+ });
+
test('every operation minus its handler, same order, same key order', () => {
const live = operations.map(({ handler: _handler, ...meta }) => meta);
expect(JSON.stringify(OPERATION_MANIFEST)).toBe(JSON.stringify(live));