Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript

feat: stable error codes on the MCP wire, typed rerank degradation and a rerank doctor check (v1.66.0) (#225)

Serg Eroshe3ec2334a8f77
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 6756b0d0..de5414ff 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.65.0",
+ "version": "1.66.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 08113c9a..5c2e3cd8 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.65.0",
+ "version": "1.66.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 22dbee99..61c1a053 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,34 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.66.0] - 2026-10-01
+
+A failed MCP call now says what failed in a token a client can branch on, and the optional cross-encoder rerank says why it stepped aside: every JSON-RPC error answer carries `error.data.code` and every `isError` tool result carries `_meta["open-second-brain/error"].code`, both drawn from one closed registry with the error prose left byte for byte as it was; a failed rerank endpoint is recorded on the retrieval trail as `rerank-provider-unavailable` with a typed category and is never cached, a model past its announced decommission date is skipped without a request (`rerank-model-sunset`), and `o2b brain doctor` checks the rerank configuration before a search has to fail on it.
+
+### Added
+
+- **Every failed MCP call carries a stable code.** A failure reaches the client on one of two channels, and each now names its code. On the JSON-RPC channel every error response carries `error.data.code`: a code the refusing site chose (`vault_frozen`, `budget_exceeded`, `unknown_argument`, a search error code) wins, and otherwise the server fills in the default for the numeric code (`parse_error`, `invalid_request`, `method_not_found`, `invalid_params`, `internal_error`), after any `data` members the answer already had. On the tool-result channel an `isError: true` result carries `_meta["open-second-brain/error"] = { schema: "o2b.error.v1", code }`, beside a progress refusal when the call has one, and never in `structuredContent`, which a strict client validates against the tool's `outputSchema` even on an error. Every error message and text block reads as before, and a successful result never gains the envelope. The stdio and HTTP transport errors pass through the same single builder, so the rule holds by construction.
+- **One closed registry of wire codes.** `TOOL_ERROR_CODES` in `src/mcp/tool-error-codes.ts` is the union of the vocabularies the core already defines, passed through with their existing spelling (search errors stay UPPER_SNAKE, the write-binding, reach and owner-scope refusals stay kebab-case, the `brain_expire` refusals keep their class names), and 21 lower snake_case tokens of its own, nearly all for failures that had no code before: the five JSON-RPC defaults, `safeguard_timeout`, `safeguard_aborted`, `output_contract_failed`, `config_unreadable`, `skill_not_found`, `skill_invalid_path`, `unknown_skill`, `unknown_operation`, `invalid_status`, `trigger_transition_refused`, `write_session_unknown`, `write_session_terminal`, `session_id_required`, `unknown_argument`, `brain_artifact_unparseable` and `argument_forbidden`. Nothing already on the wire was renamed. A failure is classified by its error class over a closed table, never by reading an arbitrary `.code` property, so an operating-system code such as `ENOENT` never reaches the wire; a class the table does not know is answered as `internal_error` and named on stderr by class name only (`warning: unclassified tool error mapped to internal_error: <name>`). A code a refusing site supplies outside the registry is still sent and is named on stderr, JSON-quoted and capped at 120 characters.
+- **Search, skill, workspace, write-session and argument refusals name their code.** `SearchError` codes reach `error.data.code` on `brain_search` and the recall tools, where they used to be dropped or appended to the text only; skill tools answer `unknown_skill`, `skill_not_found` or `skill_invalid_path`; `brain_trigger` answers `invalid_status` and `trigger_transition_refused`, with an absent trigger and one the caller may not see sharing one code and one message; the write-session tools answer `session_id_required`, `write_session_unknown` and `write_session_terminal`; the argument guard answers `unknown_argument`, and the reach and owner-scope refusals carry `caller-supplied-reach`, `foreign-owner` and `unresolved-identity`. Every tool that dispatches on an `operation`, `op` or `action` argument, a `brain_write_batch` operation's `op` included, answers an unknown one with `unknown_operation`; a `brain_memory_bridge` host write keeps its existing `invalid_action`. A Brain artifact that cannot be parsed answers `brain_artifact_unparseable` instead of `internal_error`.
+- **The Hermes bridge exposes the code.** `BridgeError` gains a `code` attribute holding `error.data.code` of a JSON-RPC error response, so Hermes can branch on the token without parsing the rendered message; it is `None` for a transport failure and for a response whose code is missing or not a string. `str(err)` is unchanged.
+- **A failed rerank endpoint is named on the retrieval trail.** When the cross-encoder rerank endpoint cannot answer, the answer keeps the heuristic order as before, and the trail in `--json` and on `brain_search` now carries `rerank-provider-unavailable` with `detail.category` computed from the typed failure, never from the provider's message: `auth` (401, 403), `quota` (402), `gone` (404, 410), `rejected` (any other 4xx), `transient` (408, 429, 5xx), `timeout`, `network` (refused connection, DNS, TLS, a redirect, or a body that broke while it was read), `malformed` (not JSON, the wrong number of scores, an out-of-range or duplicate index) or `unclassified`. The `rerank_degraded:` warning stays the human signal.
+- **A rerank model past its announced decommission date is not called.** A shipped rerank sunset survey, built on the embedding survey's shape and classifier, records the Cohere `rerank-english-v2.0` and `rerank-multilingual-v2.0` shutdown of 2025-04-30 with its cited source; once a configured `openai-compat` model's date has passed, the stage sends no request and the trail carries `rerank-model-sunset`. The ZeroEntropy `zerank` checkpoints are recorded as open-weight negatives: their hosted API ended after 2026-09-04, but a self-hosted checkpoint keeps answering, so a dead hosted endpoint is reported as `rerank-provider-unavailable` instead of being skipped.
+- **`o2b brain doctor` checks the rerank configuration.** With `search_rerank_enabled` on and the `openai-compat` kind, a config-only check that sends no request reports `rerank-endpoint-unconfigured` (error) for a missing or blank base URL, model or key, a base URL the provider would refuse, or a `search_rerank_provider` that names no registered profile and so left one of them empty; `rerank-model-sunset-announced` (warning) for a model whose announced decommission date is 90 days away or fewer, or past; and `rerank-model-sunset-unsurveyed` or `rerank-model-sunset-undetermined` (uncertain) when the survey makes no statement or reaches no verdict. A base URL that carries `user:password@` credentials gets one fixed finding, and the doctor refuses it without repeating it: the configured value never appears in the finding, which shows `<search_rerank_base_url>` in its place.
+
+### Changed
+
+- **Every JSON-RPC error answer carries `error.data`.** It is always an object with a string `code`, never absent and never an array; a `code` member that is not a string is replaced by the default. A client that asserted `"data" not in error` sees the change; existing `data` members such as `tool`, `unknown_arguments` or `errors` are kept as they were.
+- **A failed rerank answer is served but never cached.** The next identical query asks the endpoint again instead of replaying the failure. A `rerank-model-sunset` answer depends only on the build and the date and is cached as usual; for an enabled `openai-compat` rerank the query cache key now carries the survey's review date, so a corrected survey does not replay the old answer, and such an install sees one cache miss per query after the upgrade.
+- **`argument_forbidden` and the three `brain_expire` refusals are registry members.** `brain_scaffold_stub`'s `argument_forbidden` and `ExpirationValueError`, `ExpirationTargetNotFoundError` and `InvalidExpirationTargetError` keep the spelling they already had on the wire.
+- **Docs:** `docs/mcp.md` gains a "Tool errors" section with both channels, the generic code table and the casing rules; `docs/cli-reference.md` documents the two rerank trail codes, the category table, the missing `hybrid-deadline-exceeded` row and the rerank doctor check; `docs/how-it-works.md` describes the rerank trail and the sunset skip; `docs/updating.md` names what a client sees after the upgrade; the README names this release.
+
+### Fixed
+
+- **A JSON-RPC refusal keeps the progress-token refusal.** A `tools/call` with a progress token over a single-response transport that failed on the JSON-RPC channel gave no sign that its token was refused; the refusal now rides in `error.data["open-second-brain/progress"]` beside `code`, with the message and the numeric code unchanged.
+- **A throw that escapes the HTTP dispatch is answered like any internal error.** The HTTP catch-all answered with the raw error message; it now answers `internal error: <message>` with the message passed through the redactor for the bind's reach and a classified `data.code`, the same builder the dispatcher's own internal-error answer uses.
+- **The rerank timeout covers the response body.** An endpoint that sent its headers and then stalled the body held the search past the rerank timeout, and a caller's cancellation during the stall was not honoured; the timeout and the cancellation now cover the body read, answering `timeout` or the caller's own reason, with the messages unchanged.
+- **`o2b brain doctor` no longer prints the plain-http rerank warning.** With `search_rerank_allow_insecure_http` set, the rerank check printed the runtime's once-per-process plain-http warning, so a later search in the same process sent vault text without it; the check now answers that case from the configuration alone.
+
## [1.65.0] - 2026-10-01
The maintenance lane becomes something an unattended host can schedule and extend, and the MCP server survives the background faults that used to end it: `o2b brain maintenance run --cron-template` prints the recipe that schedules the lane, every recipe can be printed as a systemd user timer, an install can put its own upkeep commands under the lane's gates as `custom:<name>` tasks, and a served `o2b mcp` names and counts a stray promise rejection instead of dying on it, while an uncaught exception still exits, through the hooks that checkpoint the index and release the locks.
@@ -7924,6 +7952,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.66.0]: https://github.com/itechmeat/open-second-brain/compare/v1.65.0...v1.66.0
[1.65.0]: https://github.com/itechmeat/open-second-brain/compare/v1.64.0...v1.65.0
[1.64.0]: https://github.com/itechmeat/open-second-brain/compare/v1.63.0...v1.64.0
[1.63.0]: https://github.com/itechmeat/open-second-brain/compare/v1.62.0...v1.63.0
diff --git a/README.md b/README.md
index 02153f4d..04442a9d 100644
--- a/README.md
+++ b/README.md
@@ -113,7 +113,7 @@ The full router with readiness criteria is [`install.md`](install.md); native Wi
## What is new
-1.65.0 makes the maintenance lane something an unattended host can schedule and extend (a cron recipe of its own, a systemd user timer for every recipe, install-owned `custom:<name>` upkeep tasks under the lane's gates) and keeps a served `o2b mcp` alive through a stray promise rejection, naming and counting it on stderr and in `/health`, while an uncaught exception still exits through the hooks that checkpoint the index and release the locks. Every release is described in the [CHANGELOG](CHANGELOG.md).
+1.66.0 puts a stable error code on every failed MCP call, `error.data.code` on a JSON-RPC error and `_meta["open-second-brain/error"].code` on an `isError` result, drawn from one closed registry with the error prose unchanged, so a client branches on a token instead of matching English text. The optional cross-encoder rerank names why it stepped aside on the retrieval trail (`rerank-provider-unavailable` with a typed category, never cached, and `rerank-model-sunset` for a model past its announced decommission date), and `o2b brain doctor` checks the rerank configuration without sending a request. Every release is described in the [CHANGELOG](CHANGELOG.md).
## Documentation
diff --git a/docs/brainstorm/mcp-error-codes/cli-output/claude.md b/docs/brainstorm/mcp-error-codes/cli-output/claude.md
new file mode 100644
index 00000000..7bb33c07
--- /dev/null
+++ b/docs/brainstorm/mcp-error-codes/cli-output/claude.md
@@ -0,0 +1,40 @@
+### Variant 1: Boundary interceptor with a namespaced `_meta` error envelope
+- **Approach**: Add one registry module (frozen `MCP_ERROR_CODES` object, members list, guard, census test) and teach the two existing choke points to read a structural `readonly code: string` off any thrown error: `toolError` in server.ts attaches `_meta["open-second-brain/error"] = {code, surface}` next to the unchanged text body, and the MCPError builder copies the code into `data.code` where a wrapping site (skill-tools rewrap, `searchErrorToMcp`) currently drops it. Throws without a code get the single registered `unclassified` code, and `withProgressRefusal` is changed to merge `_meta` instead of replacing it. Rerank liveness joins the same release as a new `RETRIEVAL_DEGRADATION` member `rerank_skipped` whose detail is an identifier reason (`provider_sunset`, `provider_unreachable`, `provider_error`), fed by a rerank sunset survey that reuses the generic classifier from `embeddings/sunset.ts`, a `doctor/rerank-sunset-check.ts` registered in the exit census, and a cache-write bypass when that degradation is present.
+- **Trade-offs**:
+ - Pro: two change points cover all ~28 coded classes and every surface at once; no per-tool rewiring.
+ - Pro: text bodies and existing `data.code` spellings stay byte-identical; `_meta` passes strict SDK result validation, mirroring the existing progress key.
+ - Pro: the census test forces each listed code to a live producer and surfaces casing drift as data, without rewriting it.
+ - Pro: rerank skip stays inside the closed-vocabulary convention and flows into `search --explain` for free.
+ - Con: mixed snake/kebab/UPPER casing is inherited onto the wire as-is; a normalization pass would be a second release.
+ - Con: structural duck-typing can pick up unrelated `code` fields (Node `ENOENT` strings); needs the guard to whitelist registry members and route the rest to `unclassified`.
+ - Con: the `_meta` merge in progress.ts is a behavior change that needs its own test.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Shared `CodedError` base class, codes normalized at the source
+- **Approach**: Introduce an abstract `BrainError` base in core carrying `code`, `surface`, and `retryable`, migrate the ~28 existing coded classes to extend it, and add new `WorkspaceError` and `WriteSessionError` classes with their own enumerated vocabularies for the currently prose-only paths. The server detects errors by `instanceof` and emits both `data.code` (channel A) and the `_meta` envelope (channel B); a `wire` alias table keeps already-emitted spellings while new codes use one canonical casing. Rerank becomes a typed `RerankOutcome` returned by post-rank, consumed by the trail as a degradation member, by doctor, and by the cache layer to skip caching degraded results.
+- **Trade-offs**:
+ - Pro: strongest typing and one place to answer "what codes exist"; `retryable` lets clients branch on retry versus fallback without a second table.
+ - Pro: workspace and write-session refusals gain real codes instead of `unclassified`.
+ - Pro: the typed `RerankOutcome` cleanly separates "did not run" from "ran and failed" for the explain and doctor surfaces.
+ - Con: touches 28 classes across core; large diff with real chances of altering a message string or a pinned `toBe` text.
+ - Con: `instanceof` is brittle across module duplication and the Hermes plugin boundary; structural detection would still be needed as a fallback.
+ - Con: two vocabularies (canonical plus wire aliases) is a second convention the constraints warn against.
+ - Con: converting write-session prose refusals to typed errors risks moving them between channels and changing wire shape for clients.
+- **Complexity**: large
+- **Risk**: medium
+
+### Variant 3: Per-surface mapping tables extending the search precedent
+- **Approach**: Keep the server untouched and replicate the `searchErrorToMcp` pattern per tool module: `skillErrorToMcp`, `workspaceErrorToMcp`, `writeSessionErrorToMcp`, each with a sibling `*_ERROR_CODES` frozen vocabulary and each producing an `MCPError` with `data.code`. Unmapped throws stay on the prose-only channel B path. Rerank liveness is reported as its own `rerank: {ran, skipped_reason}` block in the retrieval trail rather than a degradation member, with a doctor section that reads the provider registry and a static rerank sunset table.
+- **Trade-offs**:
+ - Pro: smallest server-side change; each mapping is explicit and locally reviewable, exactly like the existing search module.
+ - Pro: no duck-typing, no `_meta` merge change in progress.ts.
+ - Con: N mapping sites drift independently; a new tool module ships uncoded unless someone remembers the mapper, which is the gap that produced today's state.
+ - Con: moving skill and workspace errors from a `isError` tool result to a JSON-RPC error changes the wire shape clients already see, even though message text is unchanged.
+ - Con: a separate `rerank` trail block diverges from the closed `RETRIEVAL_DEGRADATION` convention and does not surface in existing degradation-driven output paths.
+ - Con: still leaves the cached-degraded-rerank problem unless handled separately.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Recommended: Variant 1
+**Rationale**: It satisfies every hard constraint directly: text bodies stay byte-identical, no error payload touches `structuredContent`, existing `data.code` spellings are preserved, and the registry census enforces a live producer per code. Two interception points plus the existing namespaced `_meta` precedent deliver cross-surface coverage without the 28-class migration of Variant 2 or the drift-prone per-module mappers and wire-shape change of Variant 3, and the rerank work lands inside the closed-vocabulary and sunset-survey conventions the repository already uses.
diff --git a/docs/brainstorm/mcp-error-codes/cli-output/prompt.md b/docs/brainstorm/mcp-error-codes/cli-output/prompt.md
new file mode 100644
index 00000000..aaabe883
--- /dev/null
+++ b/docs/brainstorm/mcp-error-codes/cli-output/prompt.md
@@ -0,0 +1,111 @@
+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.
+
+# Task
+
+Two tracker cards ship together as one release ("stable error codes at the MCP boundary").
+
+## Card A: stable machine-readable error codes on every MCP tool error
+**Source**: https://github.com/garrytan/gbrain/releases/tag/v0.47.4.0
+**Repo**: garrytan/gbrain (18439β˜…)
+**Released**: v0.47.4.0 (2026-08-28T17:16:15Z)
+
+## What
+Give every MCP tool error a stable, machine-readable code, the way OSB already does for the search surface via SEARCH_ERROR_CODES. Today skill- and workspace-execution failures return free-form text with no enumerated code vocabulary, so remote agent clients cannot branch on an error class without parsing prose. This extends the existing code discipline to the skill/workspace tool surfaces and, optionally, standardizes an HTTP 429 JSON envelope on repeated-failure paths.
+
+## Why useful for OSB
+OSB is consumed over MCP by remote agent clients (Hermes, Claude Code, Codex). Stable codes on tool errors let those clients retry, fall back, or surface a specific class programmatically instead of string-matching English prose that can change at any time. It also makes the surface consistent: search already speaks codes; skill/workspace execution should too.
+
+## Status in OSB
+- **Verdict**: present_weaker
+- **Codegraph hints**: Partial coverage exists - SEARCH_ERROR_CODES at src/core/search/search-error.ts:13 with the code accessor at src/core/search/search-error.ts:62; MCP protocol layer carries a code field at src/mcp/protocol.ts:23; response shaping has code at src/core/brain/response-shape.ts:212; policy errors expose source at src/core/brain/policy/errors.ts:24. Gap: no run_skillopt-equivalent or skill/workspace error-code vocabulary - not found for skill execution; the affected surfaces are src/core/brain/skill-accept-journal.ts and WORKSPACE_TOOLS at src/mcp/brain/workspace-tools.ts:148, neither of which defines an enumerated error-code set.
+
+## Notes
+Upstream's run_skillopt and admin-auth 429 specifics are gbrain-internal; the transferable idea is a single enumerated error-code vocabulary spanning all MCP tool surfaces, mirroring the existing search-error pattern rather than copying gbrain's endpoint names. Scope should reuse the existing code-bearing error class shape (search-error.ts, protocol.ts) to avoid a second, divergent convention. The 429 JSON-envelope piece applies only if OSB exposes rate-limited auth endpoints; verify before folding it into the same task.
+
+
+**Also observed**:
+- Gentleman-Programming/engram (4586β˜…) β€” PR #906 β€” structured `invalid_session_id` / `retry_without_session_id` error fields on unregistered-session writes: a concrete first member for this task's cross-surface error-code vocabulary.
+
+## Card B: reranker liveness as a typed degradation code, a doctor check and a rerank sunset table
+**Source**: https://github.com/garrytan/gbrain/releases/tag/v0.48.2.0
+**Repo**: garrytan/gbrain (18439β˜…)
+**Released**: v0.48.2.0 (2026-09-02T21:47:13Z)
+
+## What
+Every reranker-facing surface reports whether the cross-encoder rerank stage actually ran on a query and, if it was skipped, why (missing key, dead/sunset provider, disabled) and the exact remediation. A reranker whose provider is gone degrades quietly to fusion order instead of erroring or paying dead HTTP calls, and the skip is surfaced as a first-class degradation code in explain output and doctor.
+
+## Why useful for OSB
+OSB has hybrid search with an optional cross-encoder rerank stage but no way to tell whether that stage actually fired on a given query β€” `o2b search rerank-fit` answers "does the configured reranker re-order results" (fit), not "was it skipped this query and why" (liveness). Without a liveness signal, a missing key or a decommissioned rerank provider silently returns fusion-order results that look unranked, with no surface pointing at the cause or the fix.
+
+## Status in OSB
+- **Verdict**: not_in_osb_useful
+- **Codegraph hints**:
+ - `src/cli/search/verbs/rerank-fit.ts` β€” `o2b search rerank-fit` checks FIT (does the cross-encoder re-order), not LIVENESS (was it skipped this query and why); the liveness gap is adjacent but uncovered.
+ - `src/cli/brain/verbs/doctor.ts` β€” no reranker health section (grep "rerank" = 0 hits across its 306 lines); doctor cannot report reranker skip/reason.
+ - `src/core/search/retrieval-trail.ts:68` β€” `RETRIEVAL_DEGRADATION` is a closed code union with no reranker-skip member; a `reranker-skipped` code (with reason: `no_key` / `provider_sunset` / `disabled`) needs adding here to flow into `search --explain`.
+ - `src/core/search/rerank/provider.ts` (`makeRerankProvider`), `registry.ts` (fail-soft load of `Brain/search/rerank-providers.json`), `cross-encoder.ts` (OpenAI-compatible `/rerank`) β€” the rerank path already fail-soft-loads but does not emit a structured skip event the surfaces can read.
+ - `src/core/search/embeddings/sunset.ts` β€” static decommission SURVEY table (t_e7a226ce) exists for EMBEDDING models but has no rerank-provider equivalent; a sunset-driven skip reason for rerankers would mirror this.
+ - `src/core/search/embeddings/zeroentropy.ts` β€” a native ZeroEntropy EMBEDDING provider exists, but the rerank side has no ZeroEntropy provider; the upstream ZeroEntropy hosted-rerank sunset (2026-09-04) maps to OSB's rerank-provider registry, not this embedding module.
+
+## Notes
+Scope is observability plus safe degradation, not a provider migration: OSB does not ship a ZeroEntropy rerank default to move off of, so the upstream "switch default to Voyage rerank-2.5" step does not directly apply β€” the transferable capability is the skip-reason surfacing (`degraded: reranker_skipped (no_key)`-style codes) and the "degrade to fusion order without dead HTTP" guarantee. Suggested surfaces to wire: `retrieval-trail.ts` degradation code β†’ `search --explain`, a reranker section in `doctor.ts`, and the search-modes listing.
+
+## Verified premise (live source, tree a1ecfe7b)
+- Two error channels exist. Channel A: a handler throws MCPError (src/mcp/protocol.ts:38) and handleRequest returns a JSON-RPC error {code:<numeric>, message, data?} (src/mcp/server.ts:358-361, builder errorResponse :585). 373 throw sites; only about 12 put a string `code` in `data` (write batch, create note, pinned, memory bridge, lifecycle, vault_frozen). Channel B: any other throw inside tools/call is caught (server.ts:463-478) and wrapped by toolError (:570) as {content:[{type:"text",text}], isError:true} with no code; withProgressRefusal (src/mcp/progress.ts:173-179) REPLACES `_meta` with the progress refusal.
+- About 28 core error classes carry a readonly `code` (SearchError with SEARCH_ERROR_CODES, SkillError NOT_FOUND|INVALID_PATH, WriteBatchError, CreateNoteError, NoteLifecycleError, PinnedBatchError, ...). Casing on the wire is mixed (snake, kebab, UPPER) and is a public contract where already emitted; tests pin budget_exceeded, invalid_action, invalid_target.
+- searchErrorToMcp (src/mcp/search-tools.ts:863-887) drops SearchError.code; skill-tools.ts:90 rewraps SkillError as MCPError(INVALID_PARAMS, message) and drops the code; workspace tools and the write-session refusals are prose only.
+- The MCP SDK (1.30) validates structuredContent against outputSchema even when isError is true, so an error object in structuredContent breaks strict clients on 16 tools; `_meta` passes the loose result schema. Repo already uses a namespaced `_meta` key "open-second-brain/progress". Tests pin the text body with toBe in two places.
+- No HTTP 429 exists in the MCP server (out of scope). The engram pair has no direct counterpart; the closest is write-session unknown/terminal plus a missing session_id.
+- Rerank: RETRIEVAL_DEGRADATION (src/core/search/retrieval-trail.ts:68) is a closed vocabulary with no rerank member; rerank failure is only a warning string `rerank_degraded: <raw provider message>` (pipeline/post-rank.ts:178); trail detail must be identifiers/integers only, never provider prose. `disabled` and missing-key cannot be degradations (disabled is the default; enabled + missing key fails closed). Embedding sunset survey precedent: src/core/search/embeddings/sunset.ts, model-string keyed, injectable survey and clock, classifier generic over the survey; doctor check precedent doctor/embedding-sunset-check.ts with a doctor exit census. A degraded rerank outcome is currently written to the query cache, so a transient failure is served from cache.
+
+# Project context
+
+Open Second Brain: TypeScript on Bun, a hand-rolled MCP server (stdio and HTTP), a CLI `o2b`, a Hermes Python plugin. No @modelcontextprotocol/sdk dependency.
+Recent commits:
+a1ecfe7b feat: unattended maintenance recipes, install-owned lane tasks and an MCP fault guard (v1.65.0) (#224)
+4499698c feat: search that honours pins and event time, diagnostics that prove action, writes that name their residue (v1.64.0) (#223)
+a0b3c2e0 feat: exactly-one binding for mentions and imports, once-only write receipts, selectable search breadth and per-device ledgers (v1.63.0) (#222)
+f4f9e3e6 feat: silent failures surface by name in redaction, receipts, ingest, search store, doctor (v1.62.0) (#220)
+eb3c4c85 docs: concise README, ZCode client page, CLI reference and safety notes moved to child pages (#219)
+f22df2c5 chore(apb): zg search, code-ranker and OpenCodeReview before push, scope-scan hardening (#218)
+83979b9d fix: MCP startup off the upgrade path, fair ingest locks, inline plugin MCP manifest, inbox archive (v1.61.0) (#217)
+3e59f319 feat: decision-model uses, adapters and setup skill (v1.60.0) (#215)
+eacad953 feat: optional decision-model core and decision-model rerank kind (v1.59.0) (#214)
+0afa0c5a chore(deps): bump the bun-minor-and-patch group with 5 updates (#201)
+f6212cd2 fix: quiet one-line Stop reminder via Claude Code feedback channel (v1.58.2) (#202)
+534befdb chore(deps): bump the github-actions group with 3 updates (#200)
+5c550263 fix: session capture off the hook path, registry scanner hygiene (v1.58.1) (#199)
+6f33c424 feat: payload registry and knowledge packs, boundary hardening, CJK chunking (v1.58.0) (#197)
+a4d3ecf8 fix(codex): real plugin files and a truthful install check (v1.57.1) (#193)
+d7e6094a feat: a second platform (v1.57.0) (#191)
+54bb28d9 feat: what this install knows (v1.56.0) (#185)
+5f415267 feat: who wrote what, and how to take it back (v1.55.0) (#184)
+dc552590 feat: private is not a suggestion (v1.54.0) (#183)
+23e6b81e fix(brain): merged pages leave the dedup pool, and the write seam refuses cycles (v1.53.1) (#182)
+Related files: src/mcp/server.ts, src/mcp/protocol.ts, src/mcp/progress.ts, src/mcp/search-tools.ts, src/mcp/skill-tools.ts, src/mcp/brain/workspace-tools.ts, src/mcp/brain/context-tools.ts, src/core/search/search-error.ts, src/core/search/retrieval-trail.ts, src/core/search/rerank/index.ts, src/core/search/rerank/cross-encoder.ts, src/core/search/pipeline/post-rank.ts, src/core/search/search.ts, src/core/search/embeddings/sunset.ts, src/core/brain/doctor.ts, src/core/brain/diagnostics.ts, src/core/brain/doctor-exits.ts
+Conventions:
+- Closed vocabularies as frozen object + members list + guard, registered in a census test.
+- Named failures, never silent fallbacks; "absent, not empty" envelopes keep healthy payloads byte-identical.
+- No network calls for third-party facts; sourced static tables with review dates.
+- All strings English; no per-language phrase lists.
+Constraints:
+- Text bodies of existing errors stay byte-identical; existing wire codes keep their spelling.
+- No error payload in structuredContent.
+- No new external dependencies. Every enumerated code must have a live producer.
+
+# Required output format
+
+Produce exactly 3 distinct architectural variants. For each variant:
+
+### Variant N: <short name>
+- **Approach**: 2-3 sentences describing the variant.
+- **Trade-offs**: bullet list of pros and cons.
+- **Complexity**: small | medium | large
+- **Risk**: low | medium | high
+
+After the three variants, add exactly one recommendation:
+
+### Recommended: Variant N
+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.
+
+Output nothing outside of these sections.
diff --git a/docs/brainstorm/mcp-error-codes/design.md b/docs/brainstorm/mcp-error-codes/design.md
new file mode 100644
index 00000000..bd3d4bdb
--- /dev/null
+++ b/docs/brainstorm/mcp-error-codes/design.md
@@ -0,0 +1,119 @@
+# Stable error codes at the MCP boundary - every tool failure and every rerank skip carries a closed, enumerated code
+
+**Status:** draft (phase 1 spec review applied)
+**Author:** release orchestrator (via feature-release-playbook)
+**Audience:** implementation
+**Cards:** t_40f13576 (stable machine-readable error codes on every MCP tool error), t_c4b85802 (reranker liveness as a typed degradation code, a doctor check, a rerank sunset table)
+**Base:** origin/main a1ecfe7b (v1.65.0), branch `feat/mcp-error-codes`
+
+## Problem statement
+
+Open Second Brain is consumed over MCP by Hermes, Claude Code and Codex, and none of them can branch on a tool failure without matching English prose. The server has two error channels and neither carries a stable code consistently: a thrown `MCPError` becomes a JSON-RPC error whose `data` holds a string `code` at about 12 of 373 throw sites, and every other throw inside `tools/call` becomes an `isError: true` result with one text block and nothing else. About 28 core error classes already carry a `readonly code`, and the boundary throws that code away (search, skills) or never had one (workspace, write session). On the retrieval side, a failed cross-encoder rerank is reported only as the warning string `rerank_degraded: <raw provider message>`, there is no rerank member in the closed `RETRIEVAL_DEGRADATION` vocabulary, no rerank doctor check, no rerank decommission survey, and a degraded rerank outcome is written to the query cache so a transient endpoint failure is served again from cache.
+
+## Premise verification (live source, a1ecfe7b)
+
+Full evidence: the two recon reports of this wave (`premise-t_40f13576.md`, `premise-t_c4b85802.md`). The orchestrator re-checked the anchors it relies on (`server.ts:357-371, 463-478, 570-597`, `progress.ts:173-179`, `post-rank.ts:170-179`, `search.ts:280-292, 510-517`, `rerank/index.ts:140-245`, `rerank/cross-encoder.ts:110-175`, `embeddings/sunset.ts:12-545`, `retrieval-trail.ts:60-180`, `protocol.ts:15-48`).
+
+### t_40f13576 - partly false, and the true part is wider than the card
+
+1. Confirmed: `toolError` (`src/mcp/server.ts:570-575`) returns `{content, isError: true}` with no code; the catch at `:463-478` routes every non-`MCPError` there.
+2. Confirmed: skill and workspace errors carry no code on the wire. `SkillError` has `NOT_FOUND | INVALID_PATH` but `skill-tools.ts:90` rewraps it as `MCPError(INVALID_PARAMS, message)`; `unknown skill` (`:84`) and the workspace refusals (`workspace-tools.ts:82, 190, 228, 231`) are prose only.
+3. Refuted: "search already does this". `SEARCH_ERROR_CODES` exists only in the core; `searchErrorToMcp` (`search-tools.ts:863-887`) builds an `MCPError` with no `data`, except the fallback arm which appends `[<CODE>]` to the prose. `recall-tools.ts:959` drops it too.
+4. Missed by the card: there are two channels (JSON-RPC error and `isError` result), and the `error.data.code` convention already exists on the first.
+5. Refuted for this tree: the HTTP 429 leg. The MCP server has no rate-limited endpoint; its non-200 replies are 401/403/405 and a draining 503 (`http.ts:251-308`).
+6. Refuted as named: the engram `invalid_session_id` / `retry_without_session_id` pair. The real counterparts are an unknown write session (`write-session/engine.ts:273`), a terminal one (`:284`) and a missing `session_id` (`context-tools.ts:73`). No retry-without-session semantic exists, so none is invented.
+
+### t_c4b85802 - partly false (validator narrowing holds, with four corrections)
+
+1. Confirmed: `RETRIEVAL_DEGRADATION` (`retrieval-trail.ts:68-150`) has no rerank member; the failure travels only as `rerank_degraded:` (`post-rank.ts:178`); no rerank hit in doctor; no rerank sunset table.
+2. Refuted: `no_key` as a degradation. Enabled with a missing key fails closed by contract (`rerank/index.ts:15-19`, `provider-resolve.ts:85-91`, pinned by `rerank.search.test.ts:80-84`). It belongs to doctor; the orchestrator also put missing-key-as-degradation out of scope.
+3. Refuted: `disabled` as a degradation. Disabled is the default and must keep a healthy answer trail-free (`retrieval-trail.test.ts:85`, the "absent, not empty" contract).
+4. Corrected: the trail is not an `--explain` feature. `retrieval_trail` appears in `--json` and MCP `brain_search` whenever anything degraded (`outcome-render.ts:152`, `search-tools.ts:1167`); `--explain` adds receipts only. The human transcript names a trail code only on an empty window, which rerank cannot produce, so the existing `rerank_degraded:` warning stays the human signal.
+5. Corrected: the upstream claim behind the survey. ZeroEntropy announced (2026-07-24) that its HOSTED `/models/rerank` and `/models/embed` endpoints shut down on 2026-09-04, and that its models are open-weight under Apache 2.0 (source: https://zeroentropy.dev/articles/zeroentropy-is-joining-notion/). That is an endpoint going away, not a model being decommissioned. The survey is keyed on the model string and its header rule (`embeddings/sunset.ts:66-75`) says a negative or positive is a claim about the MODEL: a self-hosted `zerank-*` checkpoint keeps answering. Shipping a ZeroEntropy positive would make the sunset skip refuse a live self-hosted endpoint. So ZeroEntropy rows, if any, are open-checkpoint negatives, and the dead hosted endpoint is reported by the liveness code (`rerank-provider-unavailable` with category `gone` or `network`). The one sourced positive found for a model reachable through the Cohere-compatible `/rerank` shape (`cross-encoder.ts:5`) is the Cohere `rerank-*-v2.0` family, retired 2025-04-30 (source: https://docs.cohere.com/docs/deprecations); the implementer re-reads that page and records only what it states.
+
+## Scope
+
+1. A closed MCP-boundary error registry, `src/mcp/tool-error-codes.ts`, that imports the existing core vocabularies unchanged and adds snake_case tokens for the uncoded remainder.
+2. Channel B (`isError` results): `result._meta["open-second-brain/error"] = { schema: "o2b.error.v1", code }`, text body byte-identical, `structuredContent` never set.
+3. Channel A (JSON-RPC errors): `error.data.code` on every error response, the default derived in the single builder `errorResponse` (server.ts) from the numeric JSON-RPC code, a thrower-supplied code always winning.
+4. `withProgressRefusal` merges into an existing `_meta` instead of replacing it.
+5. Per-surface precise codes where the generic default would hide a known class: search (`SearchError.code`), skills, workspace intention and trigger refusals, write session, argument guard, reach refusal, owner-scope refusal.
+6. Rerank: two `RETRIEVAL_DEGRADATION` members, `rerank-provider-unavailable` (`detail.category` from a closed `RERANK_FAILURE_CATEGORY`) and `rerank-model-sunset` (no HTTP call once the announced date has passed); a rerank sunset survey that reuses the generic embedding classifier; a degraded `rerank-provider-unavailable` outcome is not written to the query cache.
+7. A config-only `rerankHealthCheck` in doctor, its codes registered in `DIAGNOSTIC_SIGNALS` or `DOCTOR_EXIT_EXCLUSIONS` as the census test demands.
+8. Docs: a "Tool errors" section in `docs/mcp.md`; the trail table in `docs/cli-reference.md` gains the two rerank rows and the missing `hybrid-deadline-exceeded` row; the doctor codes are documented.
+
+## Out of scope
+
+1. HTTP 429 and any rate-limit envelope (no rate-limited endpoint exists; a rerank endpoint's own 429 is classified `transient`, with no retry policy added).
+2. The OpenClaw tool envelope (`src/openclaw/index.ts` does not use `MCPServer`; the host owns its error shape).
+3. Missing rerank key, base URL or model as a trail degradation (fail-closed by contract; doctor reports it instead).
+4. Moving any error between channels. The MCP spec prefers `isError` results for tool errors, but changing channel is a wire-shape change for every client and is not what the cards ask for.
+5. Renaming or re-casing any code already on the wire (kebab, snake and UPPER stay as they are).
+6. Retry hints (`retryable`, `retry_after_ms`) on the boundary envelope.
+7. A rerank operator declaration key (`search_rerank.sunset_at`); the survey alone satisfies the card, and the classifier keeps its `declaration` parameter for a later release.
+8. The CLI bridge (`server.callTool` has no envelope; its stderr line stays unchanged).
+9. `decision-model` and `local` rerank kinds for the sunset skip (no model string to key on, and the decision-model kind has its own fallback record).
+
+## Chosen approach
+
+Variant 1 of the consultant ("boundary interceptor with a namespaced `_meta` error envelope"), with five orchestrator overrides recorded below. The mapping runs at the two boundary seams in `server.ts`, so coverage of every tool does not depend on editing 373 throw sites; a small number of surface mappers add the precise code where the seam would otherwise only see a generic class. The rerank work stays inside the existing closed-vocabulary and survey conventions.
+
+## Design decisions
+
+1. **Where the code lives on channel B: `_meta`, key `open-second-brain/error`.** (Orchestrator decision 1.) The MCP SDK 1.30 client validates `structuredContent` against `outputSchema` even on `isError` results, and 16 tools declare one, so an error object there breaks strict clients; `_meta` passes the loose result schema. The repository already chose a namespaced `_meta` key for progress for the same reason (`progress.ts:53`, `docs/mcp.md:114-119`). Hermes `_structured()` would misread an error placed in `structuredContent`. Payload: `{ schema: "o2b.error.v1", code }`, mirroring `PROGRESS_SCHEMA = "o2b.progress.v1"`. The text body stays byte-identical because two tests pin it with `toBe` and Hermes and agents parse it.
+2. **Where the code lives on channel A: `error.data.code`, defaulted inside `errorResponse`.** (Orchestrator decision 1.) It is the convention 12 sites and `vault_frozen` already use, and `error.data` is `unknown` in every client. The default is derived in `errorResponse` (server.ts:585), the one builder every JSON-RPC error passes through, including the `stdio.ts` and `http.ts` transport errors (parse error, invalid request), so "every error response carries a code" holds by construction. The numeric code parameter is narrowed to a closed `JsonRpcErrorCode` union of the five constants in `protocol.ts:15-19`, and the default map is a total `Record` over it, so no unknown numeric code can reach the builder and no runtime fallback is needed.
+3. **`MCPError.data` is narrowed to `Readonly<Record<string, unknown>> | undefined`.** The seam has to merge a code into `data`; a non-record `data` would force either a shape change or a silent skip. A scan of the 373 sites found only record literals or record-typed variables, so the type narrowing is checked by `tsc` instead of a runtime branch. Merge rule: `data` absent gives `{ code }`; a record without a string `code` gets `code` added after its own members; a record with a string `code` is left untouched.
+4. **One closed registry that imports the core vocabularies unchanged.** (Orchestrator decision 2.) `TOOL_ERROR_CODE` is a frozen object of the new generic tokens; `TOOL_ERROR_CODES` is the membership list built by spreading the new tokens and every imported vocabulary (`SEARCH_ERROR_CODES`, `SHAPE_VIOLATION_CODES`, `SEMANTIC_VIOLATION_CODES`, `VAULT_FROZEN_REFUSAL`, `WRITE_BINDING_REFUSED_CODE`, `REACH_REFUSAL`, `OWNER_SCOPE_REFUSALS`, and the type-only vocabularies of write batch, create note, note lifecycle, note revert, scaffold stub, note title resolution, note template, pinned, exact state, host memory write, count guard). For a vocabulary that exists only as a TypeScript union, the registry declares its member array with `satisfies ReadonlyArray<X>` plus a compile-time exhaustiveness assertion, so the core file stays unchanged and a new core member fails `tsc` until the registry lists it. Duplicate tokens across vocabularies (for example `invalid_path`) are de-duplicated; the list is unique. Tests already pin `budget_exceeded`, `invalid_action`, `invalid_target`; nothing is renamed.
+5. **New tokens are lower snake_case.** That is the majority casing on the wire. The generic set is exactly the members that have a producer in this release: `parse_error`, `invalid_request`, `method_not_found`, `invalid_params`, `internal_error` (the five JSON-RPC defaults), `safeguard_timeout`, `safeguard_aborted`, `output_contract_failed`, `config_unreadable`, `skill_not_found`, `skill_invalid_path`, `unknown_skill`, `unknown_operation`, `invalid_status`, `trigger_transition_refused`, `write_session_unknown`, `write_session_terminal`, `session_id_required`, `unknown_argument`. `config_invalid` and `preference_not_found` are already members of imported vocabularies and are reused, not duplicated; the reach refusal keeps its existing kebab token `caller-supplied-reach` and the owner-scope refusal its `foreign-owner` / `unresolved-identity` tokens, which are already named in their messages.
+6. **No generic blank code and no silent fallback.** (Orchestrator decision 2.) `codeForError(exc)` classifies by `instanceof` over a closed table of known classes, walking `Error.cause` to a fixed depth (the feedback rethrow at `feedback-tools.ts:790-795` keeps the original as `cause`). A class that carries its own `code` contributes it only when the guard `isToolErrorCode` accepts it. Anything else maps to the explicit member `internal_error` and is logged once per occurrence to stderr as `warning: unclassified tool error mapped to internal_error: <error name>` (name only, never the message, so no path leaks into logs at remote reach). Structural duck-typing on any `.code` was rejected: Node fs errors carry `ENOENT` and would leak an unregistered token.
+7. **Skill wire tokens are `skill_not_found` and `skill_invalid_path`, not `NOT_FOUND` / `INVALID_PATH`.** The `SkillError` codes never reached the wire, so no public contract binds their spelling, and a bare `NOT_FOUND` in a cross-tool registry is ambiguous. The core `SkillError` vocabulary stays unchanged; `skill-tools.ts` maps it through a total `Record<SkillErrorCode, ToolErrorCode>`.
+8. **Search keeps its UPPER codes.** `SearchError.code` is already partly public through the fallback `[CODE]` suffix, so `searchErrorToMcp` puts the same token in `data.code` and the suffix stays as legacy text. `search-error-mapping.test.ts:16` pins `message` with `toBe`; the message does not change.
+9. **Privacy: one code for "absent" and "not visible".** `brain_trigger` makes both byte-identical (`workspace-tools.ts:213-222`); the whole transition catch carries `trigger_transition_refused`, so the code does not split them either.
+10. **`withProgressRefusal` merges `_meta`.** (Orchestrator decision 1.) `{ ...result, _meta: { ...result._meta, [PROGRESS_META_KEY]: refusal } }`; with no refusal the result stays untouched (byte-identical to v1.65.0). Success results never gain `_meta`.
+11. **Two rerank degradation members, not one.** (Orchestrator decision 3.) The vocabulary names cause in the code (`semantic-provider-unavailable` + `detail.category`), the lane prefix rule groups both under `rerank-*`, and each needs its own sentence in `describeRetrievalDegradation`. Casing is kebab, like every member of that vocabulary.
+12. **`RERANK_FAILURE_CATEGORY` is a closed vocabulary computed from typed errors, never from message text.** Members: `auth` (401, 403), `quota` (402), `gone` (404, 410: the decommissioned-endpoint signal), `rejected` (any other 4xx), `transient` (408, 429, 5xx), `timeout`, `network`, `malformed` (non-JSON body, wrong score count, out-of-range or duplicate index), `unclassified` (a throw the cross-encoder did not type, for example from a provider implementation outside `cross-encoder.ts`; named, not hidden, and its sentence says so). The cross-encoder throws `RerankEndpointError extends SearchError` with code `RERANK_PROVIDER_HTTP` unchanged, `status` where it has one, and a `category`; the telemetry event gains a required `category` on `status: "error"`. Messages stay byte-identical, so the `rerank_degraded:` warning and `rerank.search.test.ts:94` keep their text. The plain `Error("expected N scores ...")` at `rerank/index.ts:226` becomes a `RerankEndpointError` with category `malformed` and the same message.
+13. **How rerank codes reach the trail.** `PostRankOutcome` gains `degraded` parallel to `warnings`, merged into the sink at `search.ts:485` like every lane's `{warnings, degraded}`. `PostRankInput` gains `nowMs`, taken from the clock already in `search.ts` scope, so the sunset decision is injectable in tests.
+14. **Rerank sunset survey reuses the embedding classifier.** `src/core/search/rerank/sunset.ts` exports `RERANK_SUNSET_SURVEY` (typed `EmbeddingSunsetSurvey`) and `classifyRerankSunset(model, nowMs, survey = RERANK_SUNSET_SURVEY)`, a thin delegate to `classifyEmbeddingSunset`. The states, sources, undetermined reasons, horizon and staleness asymmetry are one mechanism, so no second four-piece vocabulary is created (DRY, and no new census entries for the sunset). Entries only where a source was read, each with its `source` string; the module header records why ZeroEntropy is an open-checkpoint negative rather than a positive (premise correction 5). `embeddings/sunset.ts` is not edited.
+15. **Sunset skip semantics.** Only the `announced` state with `days_remaining < 0` skips the HTTP call and returns the heuristic order with code `rerank-model-sunset` (`detail` empty: the model name is configuration, not an identifier the results carry; the doctor check names it). Every other state calls the endpoint exactly as today. Kinds `local` and `decision-model` never consult the survey.
+16. **Cache rule.** (Orchestrator decision 3.) An outcome whose trail carries `rerank-provider-unavailable` is served but never cached, mirroring the `decisionFallback` bypass at `search.ts:517`, so a transient failure is retried on the next identical query. A `rerank-model-sunset` outcome is deterministic for the build and the date, and is cached as today.
+17. **Doctor check is config-only and registered where the census demands.** (Orchestrator decision 3.) `src/core/brain/doctor/rerank-health-check.ts`, `failSoft: true`, no network, appended after `embeddingsHealthCheck` in `DOCTOR_CHECKS` (`doctor.ts:185`). It runs only when rerank is enabled with kind `openai-compat`. Codes: `rerank-endpoint-unconfigured` (error: missing base URL, model or key, or an unregistered `search_rerank_provider` name, because every search would throw), `rerank-model-sunset-announced` (warning, inside a 90-day window and past dates included, mirroring the embedding window constant by import), `rerank-model-sunset-unsurveyed` and `rerank-model-sunset-undetermined` (uncertain stream). The two actionable codes go to `DIAGNOSTIC_SIGNALS` with next commands (`o2b search rerank-provider list` for unconfigured, `o2b search rerank-provider add` for an announced sunset, since the act is choosing another endpoint or model); the two uncertain codes go to `DOCTOR_EXIT_EXCLUSIONS` with a reason, as the embedding precedent does (`doctor-exits.ts:219-235`).
+18. **Codes are fixed tokens.** `visibility-matrix.test.ts` sweeps the serialized response including `_meta`; no code is ever interpolated with a path or a name.
+19. **Docs over descriptions.** Codes are documented in `docs/mcp.md` and `docs/cli-reference.md`, not in tool descriptions, because `registry-guard.ts:51-52` caps descriptions; no inputSchema or description changes, so `plugins/hermes/_schemas.py` needs no regeneration.
+
+### Orchestrator overrides of the consultant's Variant 1
+
+1. Unclassified errors map to `internal_error` and are logged, not to a new `unclassified` member: the five JSON-RPC defaults already give `internal_error` the exact meaning, and a second member would be a blank code by another name.
+2. Classification is by `instanceof` over a closed table, not by reading any `.code` structurally (fs `ENOENT` would leak).
+3. Two rerank codes in kebab case instead of one snake `rerank_skipped`, matching the vocabulary's casing and cause-in-name precedent.
+4. No `surface` member in the `_meta` payload: the tool name is already the request's own, and a second field could drift.
+5. The rerank code is not claimed to appear in `search --explain`; it appears in `--json` and MCP `brain_search` (premise correction 4).
+
+## File changes
+
+Lane split and per-file ownership are in `plan.md` ("File ownership").
+
+
+New:
+- `src/mcp/tool-error-codes.ts` (registry, guard, `codeForError`, `defaultCodeForRpc`, `TOOL_ERROR_META_KEY`, `TOOL_ERROR_SCHEMA`, `toolErrorMeta`)
+- `src/core/search/rerank/failure.ts` (`RERANK_FAILURE_CATEGORY`, list, guard, `RerankEndpointError`, `rerankCategoryForStatus`)
+- `src/core/search/rerank/sunset.ts` (`RERANK_SUNSET_SURVEY`, `classifyRerankSunset`)
+- `src/core/brain/doctor/rerank-health-check.ts`
+- tests: `tests/mcp/tool-error-codes.test.ts`, `tests/mcp/tool-error-envelope.test.ts`, `tests/mcp/surface-error-codes.test.ts`, `tests/core/search/rerank-failure.test.ts`, `tests/core/search/rerank-sunset.test.ts`, `tests/core/brain/doctor/rerank-health-check.test.ts`, helper `tests/helpers/tool-error-envelope.ts`
+
+Modified:
+- `src/mcp/protocol.ts`, `src/mcp/server.ts`, `src/mcp/progress.ts`, `src/mcp/output-contract.ts`
+- `src/mcp/search-tools.ts`, `src/mcp/brain/recall-tools.ts`, `src/mcp/skill-tools.ts`, `src/mcp/brain/workspace-tools.ts`, `src/mcp/brain/context-tools.ts`, `src/core/brain/write-session/engine.ts`, `src/mcp/argument-guard.ts`, `src/mcp/reach-refusal.ts`, `src/mcp/coerce.ts` (owner-scope refusal site only)
+- `src/core/search/retrieval-trail.ts`, `src/core/search/rerank/index.ts`, `src/core/search/rerank/cross-encoder.ts`, `src/core/search/pipeline/post-rank.ts`, `src/core/search/search.ts`
+- `src/core/brain/doctor.ts`, `src/core/brain/diagnostics.ts`, `src/core/brain/doctor-exits.ts`
+- tests: `tests/mcp/mcp.test.ts`, `tests/mcp/progress-token.test.ts`, `tests/mcp/search-error-mapping.test.ts`, `tests/core/search/retrieval-trail.test.ts`, `tests/core/search/rerank.search.test.ts`, `tests/core/search/rerank.test.ts`, `tests/core/architecture/verdict-vocabulary-census.test.ts`
+- docs: `docs/mcp.md`, `docs/cli-reference.md`, `docs/how-it-works.md`
+- release (phase 5, in osb-pr-prepare, not in this plan): `CHANGELOG.md`, `package.json` minor bump to 1.66.0 plus `scripts/sync-version.ts`
+
+## Risks and open questions
+
+1. `tsc` may flag an `MCPError` site whose `data` is typed wider than a record once `data` is narrowed. Mitigation: lane A runs `tsc` right after narrowing; a flagged site in a lane-B file is fixed by lane B, a flagged site in a file no lane owns is fixed by lane A and added to its ownership in its report (the only edit is the type at the throw). The 373-site scan found no such site.
+2. The `_meta` merge changes a v1.65.0 behaviour (replace becomes merge). Only an error result with a progress token over HTTP is affected; a test pins both keys present.
+3. The census scan under `src/core/brain/doctor/` may require the four doctor codes as `code: "..."` literals or `const *_CODE` constants; the check follows the embedding check's spelling so the scan finds them.
+4. The Cohere deprecation page may have changed since 2025; the implementer records only what the page states on the day it is read, and bumps `reviewedAt` to that day. If the page cannot be read, the survey ships with the ZeroEntropy negatives only (sourced) and `rerank-model-sunset` is exercised by injected surveys in tests; the producer still exists on the path.
+5. Hermes reads channel B `_meta` through its whole-result serialization; no Python change is expected. The Python suite runs in phase 4 to confirm.
+6. A new tool added later with a new error class is classified `internal_error` until it is registered. That is visible (logged by name) rather than silent, which is the intent.
diff --git a/docs/brainstorm/mcp-error-codes/plan.md b/docs/brainstorm/mcp-error-codes/plan.md
new file mode 100644
index 00000000..ce882d7b
--- /dev/null
+++ b/docs/brainstorm/mcp-error-codes/plan.md
@@ -0,0 +1,152 @@
+# Stable error codes at the MCP boundary - implementation plan
+
+Design: `docs/brainstorm/mcp-error-codes/design.md` (decision numbers below refer to its "Design decisions" list).
+
+## How to run this plan
+
+Four lanes with DISJOINT file ownership, so the implement node can run them concurrently in the one worktree. A lane edits only the files listed under its own tasks. Every task is TDD: write the named test first, run it and see it fail for the stated reason, implement, see it pass, then `oxfmt` and `oxlint` on the lane's own files only, then `git add <own paths>` and a conventional commit (`feat(mcp): ...`, `feat(search): ...`, `feat(doctor): ...`, `docs: ...`). Retry on `index.lock`. Gates per task: `bun test <the task's test files>` and `bun run typecheck`.
+
+### Cross-lane contract (fixed now, so lanes do not wait on each other's code)
+
+Lane A exports from `src/mcp/tool-error-codes.ts`:
+- `TOOL_ERROR_META_KEY = "open-second-brain/error"`, `TOOL_ERROR_SCHEMA = "o2b.error.v1"`
+- `TOOL_ERROR_CODE` (frozen object of the new tokens, decision 5), `TOOL_ERROR_CODES` (closed list incl. imported vocabularies), `type ToolErrorCode`, `isToolErrorCode(value)`
+- `codeForError(exc: unknown): ToolErrorCode`, `defaultCodeForRpc(code: JsonRpcErrorCode): ToolErrorCode`, `toolErrorMeta(code): { schema, code }`
+
+The complete new-token list is the one in decision 5: `parse_error`, `invalid_request`, `method_not_found`, `invalid_params`, `internal_error`, `safeguard_timeout`, `safeguard_aborted`, `output_contract_failed`, `config_unreadable`, `skill_not_found`, `skill_invalid_path`, `unknown_skill`, `unknown_operation`, `invalid_status`, `trigger_transition_refused`, `write_session_unknown`, `write_session_terminal`, `session_id_required`, `unknown_argument`. Lane B uses only these plus the imported vocabularies. A token lane B finds missing is reported to the orchestrator, never added by lane B.
+
+Lane C exports:
+- from `src/core/search/rerank/failure.ts`: `RERANK_FAILURE_CATEGORY` (`auth`, `quota`, `gone`, `rejected`, `transient`, `timeout`, `network`, `malformed`, `unclassified`), `RERANK_FAILURE_CATEGORIES`, `type RerankFailureCategory`, `isRerankFailureCategory`, `RerankEndpointError`, `rerankCategoryForStatus(status: number)`
+- from `src/core/search/rerank/sunset.ts`: `RERANK_SUNSET_SURVEY`, `classifyRerankSunset(model, nowMs, survey?)`
+- from `src/core/search/retrieval-trail.ts`: `RETRIEVAL_DEGRADATION.rerankProviderUnavailable = "rerank-provider-unavailable"`, `RETRIEVAL_DEGRADATION.rerankModelSunset = "rerank-model-sunset"`
+
+### File ownership (every file this plan touches, exactly one owner)
+
+| Lane | Owns |
+| ---- | ---- |
+| A boundary | `src/mcp/tool-error-codes.ts` (new), `src/mcp/protocol.ts`, `src/mcp/server.ts`, `src/mcp/progress.ts`, `src/mcp/output-contract.ts`, `tests/mcp/tool-error-codes.test.ts` (new), `tests/mcp/tool-error-envelope.test.ts` (new), `tests/mcp/mcp.test.ts`, `tests/mcp/progress-token.test.ts` |
+| B surfaces | `src/mcp/search-tools.ts`, `src/mcp/brain/recall-tools.ts`, `src/mcp/skill-tools.ts`, `src/mcp/brain/workspace-tools.ts`, `src/mcp/brain/context-tools.ts`, `src/core/brain/write-session/engine.ts`, `src/mcp/argument-guard.ts`, `src/mcp/reach-refusal.ts`, `src/mcp/coerce.ts`, `tests/mcp/search-error-mapping.test.ts`, `tests/mcp/surface-error-codes.test.ts` (new) |
+| C rerank | `src/core/search/rerank/failure.ts` (new), `src/core/search/rerank/sunset.ts` (new), `src/core/search/rerank/index.ts`, `src/core/search/rerank/cross-encoder.ts`, `src/core/search/retrieval-trail.ts`, `src/core/search/pipeline/post-rank.ts`, `src/core/search/search.ts`, `tests/core/search/rerank-failure.test.ts` (new), `tests/core/search/rerank-sunset.test.ts` (new), `tests/core/search/rerank.test.ts`, `tests/core/search/rerank.search.test.ts`, `tests/core/search/retrieval-trail.test.ts` |
+| D doctor, docs, shared tests | `src/core/brain/doctor/rerank-health-check.ts` (new), `src/core/brain/doctor.ts`, `src/core/brain/diagnostics.ts`, `src/core/brain/doctor-exits.ts`, `tests/core/brain/doctor/rerank-health-check.test.ts` (new), `tests/helpers/tool-error-envelope.ts` (new), `tests/core/architecture/verdict-vocabulary-census.test.ts`, `docs/mcp.md`, `docs/cli-reference.md`, `docs/how-it-works.md` |
+
+Shared files and how they are handled:
+- `src/mcp/search-tools.ts` is touched by B only. C's two new degradation codes reach its `brain_search` outputSchema automatically (the enum is spread from `RETRIEVAL_DEGRADATION_CODES`, `search-tools.ts:520-545`), so C does not edit it.
+- `src/mcp/tool-error-codes.ts` is A's. B depends on its exports (contract above) and never edits it.
+- `tests/core/architecture/verdict-vocabulary-census.test.ts` registers both A's and C's new four-piece vocabularies; D owns it. Until D1 lands, the census test fails on the integrated tree; it is expected to be red only between A1/C1 and D1.
+- `tests/helpers/tool-error-envelope.ts` is D's (task D0, which needs only A1's constants). A's and B's tests import it once it exists; a lane that starts before D0 reads the envelope inline in its own test file and switches to the helper in its own file later. D never edits A's or B's tests.
+- `CHANGELOG.md`, `package.json` and the mirrored manifests are NOT in this plan: the version bump (minor, 1.66.0) and the CHANGELOG entry ride in phase 5 of osb-pr-prepare.
+- If `bun run typecheck` after A2 flags an `MCPError` site in a lane-B file (risk 1), lane B fixes that throw's type in its own file; lane A does not edit it.
+
+Dependency summary: A1 -> A2 -> A3; A1 -> B1..B5; C1 -> C2 -> C3; A1 + C1 -> D1; C3 -> D2; A1 -> D0; all -> D3 (D3 can be drafted from the design and finalized last).
+
+## Tasks
+
+### Lane A - boundary registry, server seam, progress merge
+
+### Task A1: closed boundary registry and classifier
+- **Files**: `src/mcp/tool-error-codes.ts` (new), `tests/mcp/tool-error-codes.test.ts` (new)
+- **Test first**: (a) `TOOL_ERROR_CODES` is frozen, unique, and contains every member of each imported vocabulary (`SEARCH_ERROR_CODES`, `SHAPE_VIOLATION_CODES`, `SEMANTIC_VIOLATION_CODES`, `VAULT_FROZEN_REFUSAL`, `WRITE_BINDING_REFUSED_CODE`, `REACH_REFUSAL`, `OWNER_SCOPE_REFUSALS`, and the type-only vocabularies of write batch, create note, note lifecycle, note revert, scaffold stub, note title resolution, note template, pinned, exact state, host memory write, count guard) plus exactly the 19 new tokens; (b) the pinned wire tokens `budget_exceeded`, `invalid_action`, `invalid_target`, `vault_frozen` are members verbatim; (c) every new token matches `^[a-z][a-z0-9_]*$`; (d) `defaultCodeForRpc` maps each of the five JSON-RPC constants to its snake token; (e) `codeForError` returns the carried code for a `WriteBatchError`, `SearchError`, `PinnedBatchError`; `safeguard_timeout` / `safeguard_aborted` for the safeguard errors; `config_unreadable` for `ConfigReadError`; `config_invalid` for `BrainConfigError`; `preference_not_found` for a plain `Error` whose `cause` is `BrainPreferenceNotFoundError`; (f) a plain `Error`, a Node fs error carrying `code: "ENOENT"`, and a non-Error throw all return `internal_error`, and each writes exactly one stderr line `warning: unclassified tool error mapped to internal_error: <name>` (spy on `process.stderr.write`; the line never contains the message).
+- **Implementation notes**: type-only vocabularies get a member array declared with `satisfies ReadonlyArray<X>` and a compile-time exhaustiveness check (decision 4); the `instanceof` table is a closed `ReadonlyArray<[ctor, code | (e) => code]>`; the cause walk has a named depth constant; core files are not edited.
+- **Acceptance**: the new test passes; `bun run typecheck` is clean.
+- **Depends on**: none
+
+### Task A2: channel A default code at the single builder
+- **Files**: `src/mcp/protocol.ts`, `src/mcp/server.ts`, `tests/mcp/tool-error-envelope.test.ts` (new, channel A part)
+- **Test first**: through `MCPServer.handleRequest`: (a) an unknown method answers `error.data.code === "method_not_found"`; (b) a tool throwing `MCPError(INVALID_PARAMS, msg)` with no data answers `data: { code: "invalid_params" }` and `message` unchanged; (c) a thrower-supplied `data.code` (pinned `budget_exceeded`) is untouched; (d) a record `data` without a code (argument guard shape) keeps every member and gains `code` last; (e) a non-`MCPError` throw outside `tools/call` answers `INTERNAL_ERROR`, message `internal error: <redacted>` unchanged, `data.code === "internal_error"`, and logs the stderr line.
+- **Implementation notes**: narrow `MCPError.data` to `Readonly<Record<string, unknown>> | undefined` and add `type JsonRpcErrorCode` over the five constants (decision 3); `errorResponse(requestId, code: JsonRpcErrorCode, message, data?)` merges the default code (decision 2); `stdio.ts` and `http.ts` transport errors inherit it with no edit there; add one stdio parse-error case to the test.
+- **Acceptance**: new test passes; existing `tests/mcp/frozen-refusal.test.ts`, `argument-guard.test.ts`, `brain-memory-bridge.test.ts`, `brain-pinned-context.test.ts`, `brain-create-note.test.ts`, `search-error-mapping.test.ts` still pass unchanged; `bun run typecheck` clean.
+- **Depends on**: A1
+
+### Task A3: channel B `_meta` code and progress merge
+- **Files**: `src/mcp/server.ts`, `src/mcp/progress.ts`, `src/mcp/output-contract.ts`, `tests/mcp/tool-error-envelope.test.ts` (channel B part), `tests/mcp/mcp.test.ts`, `tests/mcp/progress-token.test.ts`
+- **Test first**: (a) a handler throwing a safeguard timeout yields `isError: true`, `content[0].text` byte-identical to v1.65.0, `structuredContent` absent, `_meta["open-second-brain/error"]` equal to `{ schema: "o2b.error.v1", code: "safeguard_timeout" }`; (b) the output-contract failure in `mcp.test.ts:640-643` additionally carries `output_contract_failed`; (c) a call with a progress token over a single-response transport that then fails carries BOTH `_meta` keys; (d) a successful call with no progress token has no `_meta` key at all (byte-identical); (e) an unclassified throw carries `internal_error` and logs once.
+- **Implementation notes**: `toolError(message, code)` gets its code from `codeForError` at the catch (`server.ts:463-478`); `output-contract.ts` throws a named `OutputContractError` with the same message and A1's table maps it; `withProgressRefusal` merges (decision 10).
+- **Acceptance**: tests pass; `tests/mcp/schema-tools.test.ts:273-277`, `long-running-tools.test.ts`, `brain.test.ts:508, 718`, `visibility-matrix.test.ts` pass unchanged.
+- **Depends on**: A2
+
+### Lane B - per-surface mappers
+
+### Task B1: search codes reach the wire
+- **Files**: `src/mcp/search-tools.ts`, `src/mcp/brain/recall-tools.ts`, `tests/mcp/search-error-mapping.test.ts`
+- **Test first**: every `SearchError` code mapped by `searchErrorToMcp` yields `data.code === <the SearchError code>`, with `message` and numeric code unchanged (the `EMBEDDING_QUOTA_MESSAGE` `toBe` pin stays); the fallback arm keeps its `[CODE]` suffix; the recall path (`recall-tools.ts:959`) carries the code too.
+- **Acceptance**: test passes; `tests/mcp/search-*.test.ts` pass.
+- **Depends on**: A1
+
+### Task B2: skill errors
+- **Files**: `src/mcp/skill-tools.ts`, `tests/mcp/surface-error-codes.test.ts` (new, skills part)
+- **Test first**: an unknown skill answers `data.code === "unknown_skill"`; a `SkillError` `NOT_FOUND` answers `skill_not_found`, `INVALID_PATH` answers `skill_invalid_path`; messages unchanged.
+- **Implementation notes**: a total `Record<SkillErrorCode, ToolErrorCode>` (decision 7); `src/core/surface/skills.ts` is not edited.
+- **Acceptance**: test passes; existing skill tool tests pass.
+- **Depends on**: A1
+
+### Task B3: workspace refusals
+- **Files**: `src/mcp/brain/workspace-tools.ts`, `tests/mcp/surface-error-codes.test.ts` (workspace part)
+- **Test first**: an unknown `brain_intention` or `brain_trigger` operation answers `unknown_operation`; an unknown trigger status answers `invalid_status`; a transition on an absent id and on an id the caller may not see answer the SAME `trigger_transition_refused` and byte-identical messages (decision 9).
+- **Acceptance**: test passes; existing workspace tests pass.
+- **Depends on**: A1
+
+### Task B4: write-session codes
+- **Files**: `src/core/brain/write-session/engine.ts`, `src/mcp/brain/context-tools.ts`, `tests/mcp/surface-error-codes.test.ts` (write-session part)
+- **Test first**: an op needing a session without `session_id` answers `session_id_required`; an unknown id answers `write_session_unknown`; a terminal session answers `write_session_terminal`; an error carrying `errors[]` keeps `data.errors` byte-identical and gains the seam default `invalid_params`; messages unchanged.
+- **Implementation notes**: `WriteSessionRequestError` gains an optional `code` (constructor option, so every other site stays valid and keeps the seam default, which matches its JSON-RPC code); `context-tools.ts:164-173` forwards it into `data`.
+- **Acceptance**: test passes; `tests/core/brain/write-session*` and `tests/mcp/*write-session*` pass.
+- **Depends on**: A1
+
+### Task B5: argument guard, reach refusal, owner-scope refusal
+- **Files**: `src/mcp/argument-guard.ts`, `src/mcp/reach-refusal.ts`, `src/mcp/coerce.ts`, `tests/mcp/surface-error-codes.test.ts` (refusal part)
+- **Test first**: an undeclared argument answers `data.code === "unknown_argument"` with `tool`, `unknown_arguments`, `declared_arguments` unchanged; a caller-supplied reach answers `caller-supplied-reach`; an owner-scope refusal answers `foreign-owner` or `unresolved-identity` as its outcome names.
+- **Acceptance**: test passes; `argument-guard.test.ts`, `reach-refusal.test.ts`, `owner-scope-refusal.test.ts` pass unchanged.
+- **Depends on**: A1
+
+### Lane C - rerank codes, sunset, cache
+
+### Task C1: typed rerank failure category
+- **Files**: `src/core/search/rerank/failure.ts` (new), `src/core/search/rerank/cross-encoder.ts`, `src/core/search/rerank/index.ts`, `tests/core/search/rerank-failure.test.ts` (new), `tests/core/search/rerank.test.ts`
+- **Test first**: `rerankCategoryForStatus` maps 401/403 auth, 402 quota, 404/410 gone, 408/429/5xx transient, other 4xx rejected; with `tests/helpers/fake-http.ts`, an endpoint timeout, a network failure, a non-JSON body, a wrong score count and a duplicate index each surface a telemetry event `{ status: "error", category: <expected> }`, and every thrown error keeps `code === "RERANK_PROVIDER_HTTP"` and its v1.65.0 message; a provider throwing a plain `Error` yields `unclassified`.
+- **Implementation notes**: decision 12; the vocabulary is a four-piece one (frozen object, list, guard, type), registered in the census by D1.
+- **Acceptance**: tests pass; `rerank.decision-model.test.ts` passes unchanged.
+- **Depends on**: none
+
+### Task C2: `rerank-provider-unavailable` in the trail, not cached
+- **Files**: `src/core/search/retrieval-trail.ts`, `src/core/search/pipeline/post-rank.ts`, `src/core/search/search.ts`, `tests/core/search/retrieval-trail.test.ts`, `tests/core/search/rerank.search.test.ts`
+- **Test first**: (a) HTTP 503 from the rerank endpoint yields the heuristic order, the `rerank_degraded:` warning unchanged, and `retrieval_trail.degraded` containing `{ code: "rerank-provider-unavailable", detail: { category: "transient" } }`; (b) the same query run twice calls the endpoint twice (the degraded outcome was not cached); (c) a healthy rerank and a disabled rerank produce no trail; (d) every code still has a unique non-empty sentence, and the new sentence names no provider.
+- **Implementation notes**: decisions 11, 13, 16; `PostRankOutcome.degraded` merged at `search.ts:485`; the cache bypass sits beside the `decisionFallback` rule at `search.ts:517`.
+- **Acceptance**: tests pass; `tests/mcp/search-retrieval-trail.test.ts` and `tests/cli/search-retrieval-trail.test.ts` pass unchanged.
+- **Depends on**: C1
+
+### Task C3: rerank sunset survey and skip
+- **Files**: `src/core/search/rerank/sunset.ts` (new), `src/core/search/rerank/index.ts`, `src/core/search/pipeline/post-rank.ts`, `src/core/search/retrieval-trail.ts`, `tests/core/search/rerank-sunset.test.ts` (new), `tests/core/search/rerank.search.test.ts`
+- **Test first**: (a) every survey entry has a non-empty `source`, and `reviewedAt` parses; (b) with an injected survey holding a past date for the configured model, the search makes NO HTTP call (fake-http records zero requests), returns the heuristic order and carries `rerank-model-sunset`; (c) a future announced date, an off-survey model and a surveyed negative all call the endpoint as today; (d) kinds `local` and `decision-model` never consult the survey; (e) a sunset outcome is cached (second identical query makes no request and returns the same trail).
+- **Implementation notes**: decisions 14, 15 and premise correction 5. Survey rows: read https://docs.cohere.com/docs/deprecations and record the `rerank-*-v2.0` models with the date and announcement the page states; read https://zeroentropy.dev/articles/zeroentropy-is-joining-notion/ and the model cards for the `zerank-*` checkpoints and record them as open-checkpoint negatives with that source. Set `reviewedAt` to the day the pages are read. No row without a read source. The header records why the ZeroEntropy hosted shutdown is liveness, not a sunset.
+- **Acceptance**: tests pass; `nowMs` reaches post-rank from the existing clock in `search.ts`, never `Date.now()` inside rerank.
+- **Depends on**: C2
+
+### Lane D - doctor check, docs, shared test helpers
+
+### Task D0: envelope test helper
+- **Files**: `tests/helpers/tool-error-envelope.ts` (new)
+- **Test first**: none of its own (a pure reader); it is exercised by A3's and B's tests that adopt it.
+- **Implementation notes**: `readToolErrorCode(result)` reads `result._meta[TOOL_ERROR_META_KEY].code`; `readRpcErrorCode(response)` reads `response.error.data.code`; both import A1's constants and throw a named assertion error when the member is missing, never return `undefined` silently.
+- **Acceptance**: `bun run typecheck` clean.
+- **Depends on**: A1
+
+### Task D1: census registration
+- **Files**: `tests/core/architecture/verdict-vocabulary-census.test.ts`
+- **Test first**: on the integrated tree with A1 and C1, the census scan fails naming `TOOL_ERROR_CODE` and `RERANK_FAILURE_CATEGORY` as unregistered.
+- **Implementation notes**: register both beside the `EMBEDDING_SUNSET*` and `RETRIEVAL_DEGRADATION` entries; the rerank sunset adds no vocabulary (decision 14).
+- **Acceptance**: the census test passes.
+- **Depends on**: A1, C1
+
+### Task D2: config-only rerank doctor check
+- **Files**: `src/core/brain/doctor/rerank-health-check.ts` (new), `src/core/brain/doctor.ts`, `src/core/brain/diagnostics.ts`, `src/core/brain/doctor-exits.ts`, `tests/core/brain/doctor/rerank-health-check.test.ts` (new)
+- **Test first**: (a) rerank disabled: no finding; (b) enabled `openai-compat` with no base URL, no model, no key, or an unregistered `search_rerank_provider` name: one `rerank-endpoint-unconfigured` error; (c) an injected survey with an announced date inside 90 days or in the past: `rerank-model-sunset-announced` warning naming the model and the date; (d) off-survey model: `rerank-model-sunset-unsurveyed` uncertain; stale survey: `rerank-model-sunset-undetermined` uncertain; (e) the check makes no network call; (f) `tests/core/brain/doctor-exit-census.test.ts` passes with the four codes registered.
+- **Implementation notes**: decision 17; the factory takes the survey as a parameter (as `makeEmbeddingSunsetCheck` does); the window is `EMBEDDING_SUNSET_WARNING_WINDOW_DAYS` imported, not a second literal; registered after `embeddingsHealthCheck` in `DOCTOR_CHECKS`.
+- **Acceptance**: tests pass, doctor census green.
+- **Depends on**: C3
+
+### Task D3: docs
+- **Files**: `docs/mcp.md`, `docs/cli-reference.md`, `docs/how-it-works.md`
+- **Test first**: none (prose); verified by reading the rendered tables and by `bun run link-ratchet:check` and `check:paths`.
+- **Content**: `docs/mcp.md` gains "### Tool errors (since v1.66.0)" under "Protocol": the two channels, `error.data.code` and `_meta["open-second-brain/error"]`, the payload shape, the closed code list (generic tokens plus a pointer to each imported vocabulary), the casing note, the `internal_error` rule, and that text bodies are unchanged. `docs/cli-reference.md`: trail table gains `hybrid-deadline-exceeded` (orchestrator decision 4), `rerank-provider-unavailable` (with the `detail.category` members) and `rerank-model-sunset`; the doctor section lists the four rerank codes. `docs/how-it-works.md:1096` names the trail code beside the `rerank_degraded:` warning and the no-cache rule. English, "Open Second Brain" in full, no exclamation marks, no card ids.
+- **Acceptance**: tables match the source vocabularies member for member.
+- **Depends on**: A3, B1-B5, C3, D2 (drafted early, finalized last)
diff --git a/docs/brainstorm/mcp-error-codes/variants.md b/docs/brainstorm/mcp-error-codes/variants.md
new file mode 100644
index 00000000..41961951
--- /dev/null
+++ b/docs/brainstorm/mcp-error-codes/variants.md
@@ -0,0 +1,60 @@
+# Stable error codes at the MCP boundary - variants (audit trail)
+
+Consultant: Claude Code (`claude -p`, primary), prompt in `cli-output/prompt.md`, raw output in `cli-output/claude.md`. It returned three parseable variants and exited 0, so the Codex fallback was not run.
+
+## Variants, verbatim
+
+### Variant 1: Boundary interceptor with a namespaced `_meta` error envelope
+- **Approach**: Add one registry module (frozen `MCP_ERROR_CODES` object, members list, guard, census test) and teach the two existing choke points to read a structural `readonly code: string` off any thrown error: `toolError` in server.ts attaches `_meta["open-second-brain/error"] = {code, surface}` next to the unchanged text body, and the MCPError builder copies the code into `data.code` where a wrapping site (skill-tools rewrap, `searchErrorToMcp`) currently drops it. Throws without a code get the single registered `unclassified` code, and `withProgressRefusal` is changed to merge `_meta` instead of replacing it. Rerank liveness joins the same release as a new `RETRIEVAL_DEGRADATION` member `rerank_skipped` whose detail is an identifier reason (`provider_sunset`, `provider_unreachable`, `provider_error`), fed by a rerank sunset survey that reuses the generic classifier from `embeddings/sunset.ts`, a `doctor/rerank-sunset-check.ts` registered in the exit census, and a cache-write bypass when that degradation is present.
+- **Trade-offs**:
+ - Pro: two change points cover all ~28 coded classes and every surface at once; no per-tool rewiring.
+ - Pro: text bodies and existing `data.code` spellings stay byte-identical; `_meta` passes strict SDK result validation, mirroring the existing progress key.
+ - Pro: the census test forces each listed code to a live producer and surfaces casing drift as data, without rewriting it.
+ - Pro: rerank skip stays inside the closed-vocabulary convention and flows into `search --explain` for free.
+ - Con: mixed snake/kebab/UPPER casing is inherited onto the wire as-is; a normalization pass would be a second release.
+ - Con: structural duck-typing can pick up unrelated `code` fields (Node `ENOENT` strings); needs the guard to whitelist registry members and route the rest to `unclassified`.
+ - Con: the `_meta` merge in progress.ts is a behavior change that needs its own test.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Shared `CodedError` base class, codes normalized at the source
+- **Approach**: Introduce an abstract `BrainError` base in core carrying `code`, `surface`, and `retryable`, migrate the ~28 existing coded classes to extend it, and add new `WorkspaceError` and `WriteSessionError` classes with their own enumerated vocabularies for the currently prose-only paths. The server detects errors by `instanceof` and emits both `data.code` (channel A) and the `_meta` envelope (channel B); a `wire` alias table keeps already-emitted spellings while new codes use one canonical casing. Rerank becomes a typed `RerankOutcome` returned by post-rank, consumed by the trail as a degradation member, by doctor, and by the cache layer to skip caching degraded results.
+- **Trade-offs**:
+ - Pro: strongest typing and one place to answer "what codes exist"; `retryable` lets clients branch on retry versus fallback without a second table.
+ - Pro: workspace and write-session refusals gain real codes instead of `unclassified`.
+ - Pro: the typed `RerankOutcome` cleanly separates "did not run" from "ran and failed" for the explain and doctor surfaces.
+ - Con: touches 28 classes across core; large diff with real chances of altering a message string or a pinned `toBe` text.
+ - Con: `instanceof` is brittle across module duplication and the Hermes plugin boundary; structural detection would still be needed as a fallback.
+ - Con: two vocabularies (canonical plus wire aliases) is a second convention the constraints warn against.
+ - Con: converting write-session prose refusals to typed errors risks moving them between channels and changing wire shape for clients.
+- **Complexity**: large
+- **Risk**: medium
+
+### Variant 3: Per-surface mapping tables extending the search precedent
+- **Approach**: Keep the server untouched and replicate the `searchErrorToMcp` pattern per tool module: `skillErrorToMcp`, `workspaceErrorToMcp`, `writeSessionErrorToMcp`, each with a sibling `*_ERROR_CODES` frozen vocabulary and each producing an `MCPError` with `data.code`. Unmapped throws stay on the prose-only channel B path. Rerank liveness is reported as its own `rerank: {ran, skipped_reason}` block in the retrieval trail rather than a degradation member, with a doctor section that reads the provider registry and a static rerank sunset table.
+- **Trade-offs**:
+ - Pro: smallest server-side change; each mapping is explicit and locally reviewable, exactly like the existing search module.
+ - Pro: no duck-typing, no `_meta` merge change in progress.ts.
+ - Con: N mapping sites drift independently; a new tool module ships uncoded unless someone remembers the mapper, which is the gap that produced today's state.
+ - Con: moving skill and workspace errors from a `isError` tool result to a JSON-RPC error changes the wire shape clients already see, even though message text is unchanged.
+ - Con: a separate `rerank` trail block diverges from the closed `RETRIEVAL_DEGRADATION` convention and does not surface in existing degradation-driven output paths.
+ - Con: still leaves the cached-degraded-rerank problem unless handled separately.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Recommended: Variant 1
+**Rationale**: It satisfies every hard constraint directly: text bodies stay byte-identical, no error payload touches `structuredContent`, existing `data.code` spellings are preserved, and the registry census enforces a live producer per code. Two interception points plus the existing namespaced `_meta` precedent deliver cross-surface coverage without the 28-class migration of Variant 2 or the drift-prone per-module mappers and wire-shape change of Variant 3, and the rerank work lands inside the closed-vocabulary and sunset-survey conventions the repository already uses.
+
+## Orchestrator decision
+
+Variant 1 is taken, as the consultant recommended. It is the only variant that keeps text bodies byte-identical, keeps every error payload out of `structuredContent`, and covers every tool through the two seams in `server.ts` instead of relying on each module remembering a mapper (the failure mode that produced today's state, which Variant 3 repeats). Variant 2 was rejected because migrating about 28 core classes to a new base risks altering pinned message strings and adds a canonical-plus-alias second convention; Variant 3 was rejected because it leaves every unmapped throw prose-only, moves skill and workspace errors between channels, and puts rerank liveness outside the closed `RETRIEVAL_DEGRADATION` vocabulary.
+
+Five parts of Variant 1 are overridden, with reasons recorded in `design.md` ("Orchestrator overrides of the consultant's Variant 1"):
+
+1. An unclassified error maps to the existing explicit member `internal_error` and is logged by error name; no `unclassified` boundary code is added, because that would be a blank code by another name.
+2. Classification is by `instanceof` over a closed table (with a bounded `cause` walk), not by structurally reading any `.code`, which would leak Node `ENOENT` and similar unregistered tokens.
+3. Rerank gets two kebab-case members, `rerank-provider-unavailable` (with `detail.category` from a closed `RERANK_FAILURE_CATEGORY`) and `rerank-model-sunset`, instead of one snake-case `rerank_skipped`: the vocabulary is kebab throughout and names the cause in the code.
+4. The `_meta` payload is `{ schema, code }` with no `surface` member.
+5. The rerank code is documented as appearing in `--json` and MCP `brain_search`, not in `search --explain` (premise correction in `design.md`).
+
+Orchestrator decisions taken before the consultant ran, and honoured by the chosen variant: channel B code in `_meta["open-second-brain/error"]` with the text unchanged; channel A `error.data.code` with the default derived at the single builder; `withProgressRefusal` merges `_meta`; one closed registry importing the core vocabularies unchanged; a sunset survey with entries only where a source was read; a config-only doctor check registered where the census tests demand; a rerank endpoint failure not written to the query cache; the missing `hybrid-deadline-exceeded` row added to `docs/cli-reference.md`; HTTP 429, the OpenClaw envelope and missing-key-as-degradation out of scope.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index b1b8ef89..f7c8acba 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -1678,6 +1678,22 @@ o2b search rerank-eval Rerank eval gate over a labelled dataset: runs the
decision model and its `decision_model_*` config; see
[`docs/decision-models.md`](decision-models.md).
+`o2b brain doctor` checks the rerank configuration (since v1.66.0)
+whenever `search_rerank_enabled` is on with the `openai-compat` kind. The
+check reads configuration only and sends no request:
+
+| Code | Stream | When | Next command |
+| ---- | ------ | ---- | ------------ |
+| `rerank-endpoint-unconfigured` | error | the base URL is missing, carries `user:password@` credentials or is not an accepted endpoint (the configured value is never repeated in the finding; `<search_rerank_base_url>` stands in for it), the model or the key is missing or blank, or `search_rerank_provider` names no registered profile and so left one of them empty, so every rerank-enabled search would fail | `o2b search rerank-provider list` |
+| `rerank-model-sunset-announced` | warning | the configured model has an announced decommission date that is 90 days away or fewer, or already past | `o2b search rerank-provider add` |
+| `rerank-model-sunset-unsurveyed` | uncertain | the configured model is outside the shipped rerank decommission survey, so no statement was made about it | none, with the reason printed |
+| `rerank-model-sunset-undetermined` | uncertain | the check ran and reached no verdict, for example because the survey is older than its horizon | none, with the reason printed |
+
+The survey records model strings and the published notice each entry
+rests on, never an endpoint: a hosted service shutting down while its
+open checkpoints keep running elsewhere is not a model sunset, and is
+reported at query time as `rerank-provider-unavailable` instead.
+
### The retrieval trail (since v1.46.0)
A search that came back with nothing used to say only `(no results)`,
@@ -1718,7 +1734,10 @@ so there is no separate lane field that could drift from it:
| `semantic-structured-lanes-skipped` | a structured semantic lane was requested while semantic search is off |
| `semantic-embedding-abi-drift` | the index carries embeddings written by another build; `detail.fields` counts the contradicted ABI fields |
| `hybrid-degraded` | hybrid recall was asked for and the semantic lane did not run, so this answer is keyword-only |
+| `hybrid-deadline-exceeded` | the composite hybrid path (embed, semantic top-k, rerank, second pass) outlived `search_hybrid_deadline_ms`, so the phases past the budget were cut; `detail.budgetMs` is the deadline, `detail.elapsedMs` the moment it fired |
| `rank-cap-truncated-pool` | the rank cap truncated the candidate pool; `detail.cap` is the cap that bit |
+| `rerank-provider-unavailable` | the configured cross-encoder reranker (remote endpoint or local model) could not answer, so the answer keeps the heuristic order; `detail.category` is one of `auth`, `quota`, `gone`, `rejected`, `transient`, `timeout`, `network`, `malformed`, `unclassified` |
+| `rerank-model-sunset` | the configured rerank model's announced decommission date has passed, so no rerank request was sent and the answer keeps the heuristic order |
| `relevance-floor-dropped-rows` | the relevance floor dropped ranked rows; `detail.dropped` counts them |
| `scope-filters-dropped-rows` | visibility, ownership, or session / project scope dropped ranked rows; `detail.dropped` against `detail.before` |
| `cross-vault-origin-failed` | a cross-vault origin could not be searched; `detail.origin` is the origin label |
@@ -1729,6 +1748,34 @@ above has a producer on the search path today. `hybrid-degraded` is the
umbrella over the five `semantic-*` codes: they say why the lane did not
run, it says what the caller received.
+The two `rerank-*` codes report the optional cross-encoder rerank (since
+v1.66.0). Neither turns a search into an error: the answer keeps the
+heuristic order, and the existing `rerank_degraded:` warning stays the
+human signal for a failed endpoint. `detail.category` on
+`rerank-provider-unavailable` is computed from the typed failure, never
+from the provider's message:
+
+| Category | The failure it names |
+| -------- | -------------------- |
+| `auth` | the endpoint answered 401 or 403 |
+| `quota` | the endpoint answered 402 |
+| `gone` | the endpoint answered 404 or 410, the usual sign of a retired endpoint |
+| `rejected` | the endpoint answered any other 4xx |
+| `transient` | the endpoint answered 408, 429 or a 5xx. Some vendors also answer 429 for exhausted quota; the category is computed from the status alone |
+| `timeout` | the request outlived its timeout, including a 2xx body that stalled after the headers arrived |
+| `network` | the request never reached a complete answer: refused connection, DNS, TLS, a redirect, or a body that broke while it was read |
+| `malformed` | the endpoint answered, but the body was not JSON, carried the wrong number of scores, or an out-of-range or duplicate index |
+| `unclassified` | the rerank provider threw an error the cross-encoder did not type; it is named rather than folded into another category |
+
+An answer carrying `rerank-provider-unavailable` is served but never
+written to the query cache, so the next identical query asks the
+endpoint again instead of replaying the failure. An answer carrying
+`rerank-model-sunset` depends only on the build and the date, and is
+cached as usual; the cache key carries the survey's review date, so a
+build with a corrected survey does not replay the old answer. The sunset skip applies to the `openai-compat` kind
+only: the `local` and `decision-model` kinds carry no model string to
+look up.
+
The human transcript names the cause instead of printing a bare
no-results line. The first degradation wins, because the lanes push in
pipeline order and the earliest narrowing produced the ones after it:
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index e854998a..94a884c3 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -1093,8 +1093,13 @@ semantic_weightΒ·cosine + link_boost + recency_boost + entity_boost)`
candidates by the returned relevance, promoting a genuinely-relevant hit
the heuristic ranker placed deep. Zero HTTP cost and byte-identical
ordering when disabled; a request-time endpoint error degrades to the
- heuristic ordering (a `rerank_degraded:` warning, never a throw). Most
- valuable on the `thorough` profile.
+ heuristic ordering (a `rerank_degraded:` warning, never a throw). Since
+ v1.66.0 the same failure is also recorded in the retrieval trail as
+ `rerank-provider-unavailable` with a typed `detail.category`, and such
+ an answer is never written to the query cache, so a transient endpoint
+ failure is retried on the next identical query. A configured model
+ whose announced decommission date has passed is not called at all
+ (`rerank-model-sunset`). Most valuable on the `thorough` profile.
- **Query plan + recall economy (v0.20.0).** A pure structural pass
classifies each query's intent (neutral / exact / entity / broad) from
its shape - quoted phrases, FTS wildcards, wikilinks, entity-token
diff --git a/docs/mcp.md b/docs/mcp.md
index 86f9ed8d..23f49aa1 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -182,6 +182,155 @@ stating rather than rounding to "both sides":
Either way a call that has already entered one of them runs it to the end.
`src/core/brain/heal-run.ts` names the same two and the same asymmetry.
+### Tool errors (since v1.66.0)
+
+Every failed call now carries a stable, machine-readable code, so a
+client can branch on the failure without matching English prose. The
+prose itself is unchanged: every error message and every error text
+block reads byte for byte as it did before, and a successful result
+never gains the envelope. The one message that changed is the HTTP
+transport's answer to a throw that escapes its dispatch: it used to be
+the raw error message, and it is now `internal error: <message>` with the
+message redacted for the bind's reach, the same answer the dispatcher
+gives an internal error.
+
+A failure reaches the client on one of two channels, and the code rides
+in a different place on each:
+
+| Channel | When | Where the code is |
+| --- | --- | --- |
+| JSON-RPC error | the request was refused before or around the tool: an unknown method, invalid params, an undeclared argument, a refusal the tool raises as a protocol error, a transport parse error | `error.data.code` |
+| tool error result | the tool ran and failed: `isError: true` with one text block | `result._meta["open-second-brain/error"].code` |
+
+On the JSON-RPC channel every error response carries `error.data.code`.
+A code the refusing site chose (`vault_frozen`, `budget_exceeded`,
+`unknown_argument`, a search error code) wins. Otherwise the server fills
+in the default for the numeric JSON-RPC code: `parse_error` (-32700),
+`invalid_request` (-32600), `method_not_found` (-32601), `invalid_params`
+(-32602), `internal_error` (-32603). Existing `data` members such as
+`tool`, `unknown_arguments` or `errors` are kept as they were, with
+`code` added after them. A refusing site's code is itself a registry
+member; the server checks it, still sends an unregistered one as it is,
+and names it on stderr, JSON-quoted and capped at 120 characters
+(`warning: unregistered error code on the wire: "<code>"`).
+A `code` member that is not a string is replaced by the default, and
+`data` is always an object, never an array.
+
+```json
+{
+ "jsonrpc": "2.0",
+ "id": 7,
+ "error": {
+ "code": -32602,
+ "message": "brain_search: unknown argument 'quiery' (did you mean 'query'?). ...",
+ "data": {
+ "tool": "brain_search",
+ "unknown_arguments": [{ "name": "quiery", "suggestion": "query" }],
+ "declared_arguments": ["query", "..."],
+ "code": "unknown_argument"
+ }
+ }
+}
+```
+
+On the tool-result channel the code rides on `_meta` under a namespaced
+key, with a schema tag like the progress envelope's:
+
+```json
+{
+ "result": {
+ "content": [{ "type": "text", "text": "<the error message, unchanged>" }],
+ "isError": true,
+ "_meta": {
+ "open-second-brain/error": {
+ "schema": "o2b.error.v1",
+ "code": "safeguard_timeout"
+ }
+ }
+ }
+}
+```
+
+It is not placed in `structuredContent`: a strict client validates
+`structuredContent` against the tool's `outputSchema` even on an error
+result, and an error object there would fail that check. When the same
+call also carries a progress refusal, both keys sit side by side on the
+one `_meta` object. A call refused on the JSON-RPC channel carries its
+progress refusal in `error.data`, under the same
+`open-second-brain/progress` key, beside `code`.
+
+**The code list is closed.** Every code the server can send is a member
+of one registry, so a client can treat an unknown value as a newer
+server rather than as a malformed reply. It is the union of these
+generic tokens:
+
+| Code | Meaning |
+| --- | --- |
+| `parse_error`, `invalid_request`, `method_not_found`, `invalid_params`, `internal_error` | the default for each JSON-RPC error code, used when nothing more precise applies |
+| `safeguard_timeout` | the operation outlived its cooperative deadline (see "Which tools are bounded" above) |
+| `safeguard_aborted` | the operation's abort signal fired and it stopped at a checkpoint |
+| `output_contract_failed` | the tool produced a payload that does not satisfy its own `outputSchema` |
+| `config_unreadable` | the configuration file could not be read |
+| `skill_not_found`, `skill_invalid_path`, `unknown_skill` | a skill tool could not resolve the named skill, refused its path, or does not know it |
+| `unknown_operation` | a tool that dispatches on an `operation`, `op` or `action` argument (or a `brain_write_batch` operation's `op`) was asked for one it does not have; every operation-dispatching tool shares this code, except that a `brain_memory_bridge` host write keeps its pinned `invalid_action` |
+| `invalid_status` | `brain_trigger` was given a status outside its vocabulary |
+| `trigger_transition_refused` | a trigger transition was refused; an absent trigger and one the caller may not see answer with the same code and the same message |
+| `write_session_unknown`, `write_session_terminal`, `session_id_required` | a write-session call named no session, an unknown one, or one that has already ended |
+| `unknown_argument` | the call carried an argument the tool does not declare (see "Argument contract" above) |
+| `brain_artifact_unparseable` | a Brain artifact file (a preference or a retired rule, for example) could not be parsed |
+| `argument_forbidden` | `brain_scaffold_stub` was given an argument that belongs to its other action |
+
+plus every member of the vocabularies the core already defines, passed
+through unchanged:
+
+- search errors (`SEARCH_ERROR_CODES`, for example `INDEX_MISSING`,
+ `EMBEDDING_QUOTA_EXHAUSTED`); the bracketed `[CODE]` suffix some search
+ messages already carried stays in the text;
+- response-shape and semantic response violations
+ (`SHAPE_VIOLATION_CODES`, `SEMANTIC_VIOLATION_CODES`);
+- the frozen-vault refusal `vault_frozen`, the write-binding refusal
+ `write-binding-refused`, the reach refusal `caller-supplied-reach`, and
+ the owner-scope refusals `foreign-owner` and `unresolved-identity`;
+- the codes of write batches (`budget_exceeded`, `invalid_action`,
+ `invalid_target`, ...), note creation, note lifecycle, note revert,
+ stub scaffolding, note title resolution, note templates, pinned
+ context, exact state, host memory writes, the count guard
+ (`count_guard`), and the shared `config_invalid` and
+ `preference_not_found`;
+- the `brain_expire` refusals, sent under their error class names:
+ `ExpirationValueError` (the date is not one the server can compare),
+ `ExpirationTargetNotFoundError` (no signal or preference has that id)
+ and `InvalidExpirationTargetError` (the id has no addressable shape).
+
+The canonical list is `TOOL_ERROR_CODES` in `src/mcp/tool-error-codes.ts`.
+
+**Casing follows the vocabulary.** New tokens are lower snake_case. A
+code that was already on the wire keeps its spelling: search codes stay
+UPPER_SNAKE, the write-binding, reach and owner-scope refusals stay
+kebab-case, and the `brain_expire` refusals keep their class names. Nothing was
+renamed, so a client that already matched `vault_frozen` or
+`budget_exceeded` keeps working.
+
+**No blank code and no guess.** The server classifies a failure by its
+error class, never by reading an arbitrary `.code` property, so an
+operating-system code such as `ENOENT` never leaks onto the wire. A
+failure the registry does not recognise is reported as `internal_error`
+and the server writes one stderr line naming the error class (never its
+message):
+
+```text
+warning: unclassified tool error mapped to internal_error: <error name>
+```
+
+Codes are fixed tokens; none is ever built from a path, a note name or
+a query.
+
+The Hermes bridge surfaces the JSON-RPC channel's code as `BridgeError.code`
+(the string `error.data.code`, or `None` for a transport failure and for a
+response whose code is missing or not a string), so a Hermes caller
+branches on the token without parsing the rendered message; `str(err)` is
+unchanged.
+
## Tool Highlights
The full server currently advertises 115 tools; the 18 deprecated predecessor
diff --git a/docs/updating.md b/docs/updating.md
index 99f4f7ef..c73047cc 100644
--- a/docs/updating.md
+++ b/docs/updating.md
@@ -47,6 +47,36 @@ instruction files such as `CLAUDE.md`/`AGENTS.md`, installed
`.claude/skills/`) and warns with the exact replacement for any stale
reference it finds (`removed-tool-reference`).
+## Upgrading to 1.66.0
+
+No step below is required. Three changes are visible to a client or an
+operator.
+
+**Every JSON-RPC error answer now carries `error.data`.** It is always an
+object with a string `code` (for example `unknown_argument`,
+`vault_frozen` or the default `invalid_params`), and an `isError` tool
+result carries its code on `_meta["open-second-brain/error"].code`. The
+error messages and text blocks are unchanged, so a client that matched
+prose keeps working; a client that asserted `"data" not in error` sees the
+new member. The Hermes bridge exposes the code as `BridgeError.code`. See
+"Tool errors" in [`mcp.md`](mcp.md).
+
+**An install with an enabled `openai-compat` rerank sees one query-cache
+miss per query.** The cache key now carries the rerank sunset survey's
+review date, and an answer whose rerank endpoint failed is no longer
+cached, so the next identical query asks the endpoint again. Every other
+install keeps its cache keys.
+
+**`o2b brain doctor` checks the rerank configuration.** With
+`search_rerank_enabled` on and the `openai-compat` kind, a missing or blank
+base URL, model or key now fails the doctor as
+`rerank-endpoint-unconfigured`, and a model with an announced
+decommission date warns. A model outside the shipped survey is reported
+as uncertain (`rerank-model-sunset-unsurveyed`), which says only that no
+statement was made about it. The check reads configuration only and sends
+no request. See the rerank doctor table in
+[`cli-reference.md`](cli-reference.md).
+
## Upgrading to 1.65.0
No step below is required, and an existing install sees no change in what
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 211dfcad..11605f39 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "1.65.0",
+ "version": "1.66.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 3dc8edac..ed3349ad 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.65.0",
+ "version": "1.66.0",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
diff --git a/plugin.yaml b/plugin.yaml
index 874327ae..270880e1 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.65.0"
+version: "1.66.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index 4fd16b26..a63a4aa9 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.65.0",
+ "version": "1.66.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/codex/README.md b/plugins/codex/README.md
index 2ad22c0d..197b2fe8 100644
--- a/plugins/codex/README.md
+++ b/plugins/codex/README.md
@@ -113,7 +113,7 @@ The full router with readiness criteria is [`install.md`](https://github.com/ite
## What is new
-1.65.0 makes the maintenance lane something an unattended host can schedule and extend (a cron recipe of its own, a systemd user timer for every recipe, install-owned `custom:<name>` upkeep tasks under the lane's gates) and keeps a served `o2b mcp` alive through a stray promise rejection, naming and counting it on stderr and in `/health`, while an uncaught exception still exits through the hooks that checkpoint the index and release the locks. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
+1.66.0 puts a stable error code on every failed MCP call, `error.data.code` on a JSON-RPC error and `_meta["open-second-brain/error"].code` on an `isError` result, drawn from one closed registry with the error prose unchanged, so a client branches on a token instead of matching English text. The optional cross-encoder rerank names why it stepped aside on the retrieval trail (`rerank-provider-unavailable` with a typed category, never cached, and `rerank-model-sunset` for a model past its announced decommission date), and `o2b brain doctor` checks the rerank configuration without sending a request. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
## Documentation
diff --git a/plugins/hermes/bridge.py b/plugins/hermes/bridge.py
index 22612b47..ca000609 100644
--- a/plugins/hermes/bridge.py
+++ b/plugins/hermes/bridge.py
@@ -80,7 +80,24 @@ def resolve_request_timeout() -> float | None:
class BridgeError(RuntimeError):
- """Base error: a JSON-RPC error response or a transport failure."""
+ """Base error: a JSON-RPC error response or a transport failure.
+
+ ``code`` is the stable string code of a JSON-RPC error response
+ (``error.data.code``, for example ``unknown_argument``), so a caller
+ branches on a token instead of parsing the rendered message. It is
+ ``None`` for a transport failure and for a response that names none.
+ """
+
+ def __init__(self, message: str, code: str | None = None) -> None:
+ super().__init__(message)
+ self.code = code
+
+
+def _error_code(error: Any) -> str | None:
+ """The string ``error.data.code`` of a JSON-RPC error, or ``None``."""
+ data = error.get("data") if isinstance(error, dict) else None
+ code = data.get("code") if isinstance(data, dict) else None
+ return code if isinstance(code, str) else None
class BridgeTransportError(BridgeError):
@@ -218,7 +235,8 @@ class JsonRpcStdioClient:
if not isinstance(message, dict) or message.get("id") != rid:
continue
if "error" in message:
- raise BridgeError(str(message["error"]))
+ error = message["error"]
+ raise BridgeError(str(error), code=_error_code(error))
return message.get("result")
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 874327ae..270880e1 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.65.0"
+version: "1.66.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/pyproject.toml b/pyproject.toml
index 7cfcd217..dcb39841 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "1.65.0"
+version = "1.66.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/core/brain/diagnostics.ts b/src/core/brain/diagnostics.ts
index a12abc8f..6c8d6802 100644
--- a/src/core/brain/diagnostics.ts
+++ b/src/core/brain/diagnostics.ts
@@ -566,6 +566,27 @@ export const DIAGNOSTIC_SIGNALS: ReadonlyMap<string, DiagnosticSignal> = new Map
nextCommand: "o2b search provider presets",
autoRepairable: false,
},
+ {
+ // An enabled openai-compat rerank whose endpoint cannot resolve:
+ // every search fails closed until it does. The exit lists the
+ // registered rerank profiles, because the usual repair is naming
+ // one of them (or registering one) rather than typing three keys.
+ code: "rerank-endpoint-unconfigured",
+ issueClass: "rerank enabled with an endpoint that cannot resolve",
+ nextCommand: "o2b search rerank-provider list",
+ autoRepairable: false,
+ },
+ {
+ // An announced decommission of the configured rerank model. The
+ // act is choosing another model or endpoint, and registering it
+ // as a profile is the verb this tool has for that; unlike the
+ // embedding case no re-embed follows, because rerank stores
+ // nothing derived from the model.
+ code: "rerank-model-sunset-announced",
+ issueClass: "configured rerank model has an announced decommission date",
+ nextCommand: "o2b search rerank-provider add",
+ autoRepairable: false,
+ },
{
// The index behind its embedding configuration: chunks with no
// vector, or stored vectors under a retired model/dimension. The
diff --git a/src/core/brain/doctor-exits.ts b/src/core/brain/doctor-exits.ts
index a6cafdd3..0eeea471 100644
--- a/src/core/brain/doctor-exits.ts
+++ b/src/core/brain/doctor-exits.ts
@@ -234,6 +234,24 @@ const EXCLUSIONS: ReadonlyArray<DoctorExitExclusion> = [
"The first is an edit to a config file whose intended value only the operator knows, and " +
"the other two are defects in this build rather than in the vault being examined",
},
+ {
+ code: "rerank-model-sunset-unsurveyed",
+ reason:
+ "the configured rerank model is outside the shipped rerank decommission survey, and the " +
+ "repair is for somebody to look up whether its provider has announced anything - a " +
+ "question about the world, answered by reading a vendor's notice rather than by any edit " +
+ "to this vault. The finding says only that no statement was made, which is deliberately " +
+ "not the same as saying no decommission exists",
+ },
+ {
+ code: "rerank-model-sunset-undetermined",
+ reason:
+ "the check reached no sunset verdict for the rerank model, for a reason it names in the " +
+ "finding: the search configuration could not be resolved, the survey is older than its " +
+ "horizon so its record of no announcement has expired, or a shipped survey entry carries " +
+ "an unparseable date. The first is a config file whose intended content only the operator " +
+ "knows, and the other two are defects in this build rather than in the vault examined",
+ },
{
code: "embeddings-census-unrecorded",
reason:
diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.ts
index b1241e04..0d35a53f 100644
--- a/src/core/brain/doctor.ts
+++ b/src/core/brain/doctor.ts
@@ -75,6 +75,7 @@ import {
} from "./doctor/records.ts";
import { embeddingSunsetCheck } from "./doctor/embedding-sunset-check.ts";
import { embeddingsHealthCheck } from "./doctor/embeddings-health-check.ts";
+import { rerankHealthCheck } from "./doctor/rerank-health-check.ts";
import { payloadRegistryCheck } from "./doctor/payload-checks.ts";
import { recallChannelCoverageCheck } from "./doctor/recall-channel-coverage.ts";
import { recoveryPointLivenessCheck } from "./doctor/recovery-point-liveness.ts";
@@ -183,6 +184,7 @@ const DOCTOR_CHECKS: ReadonlyArray<DoctorCheck> = Object.freeze([
recoveryPointLivenessCheck,
embeddingSunsetCheck,
embeddingsHealthCheck,
+ rerankHealthCheck,
payloadRegistryCheck,
]);
diff --git a/src/core/brain/doctor/rerank-health-check.ts b/src/core/brain/doctor/rerank-health-check.ts
new file mode 100644
index 00000000..448d4cfc
--- /dev/null
+++ b/src/core/brain/doctor/rerank-health-check.ts
@@ -0,0 +1,324 @@
+/**
+ * Config-only health of the optional cross-encoder rerank.
+ *
+ * Rerank fails closed by contract when it is enabled and its endpoint
+ * does not resolve (`rerank/index.ts`, invariant 2): every search throws
+ * a typed `SearchError`. That is the right behaviour at query time and a
+ * late way to learn about a missing key, so this check says it first,
+ * from the configuration alone. It also reads the rerank decommission
+ * survey, the same way `embedding-sunset-check.ts` reads the embedding
+ * one, so a model whose retirement is announced is named before search
+ * starts skipping it (`rerank-model-sunset` in the retrieval trail).
+ *
+ * ## No network, by design
+ *
+ * Endpoint liveness is a query-time fact and is already reported there,
+ * per answer, as `rerank-provider-unavailable` with a typed category. A
+ * doctor probe would spend provider budget on every run, send a request
+ * an operator did not ask for, and report a state that is stale the
+ * moment the pass ends. So the check proves configuration only: the
+ * three endpoint fields resolve to non-blank values, the base URL carries
+ * no `user:password@` part and passes the endpoint rule the provider
+ * applies (shape only), the key variable is set and not blank, a provider
+ * name that left a field empty is named, and the survey's answer for the
+ * model.
+ *
+ * ## Scope
+ *
+ * Only an enabled rerank of kind `openai-compat`. Disabled is the default
+ * and healthy. `local` needs no endpoint. `decision-model` resolves
+ * through the decision-model config, which has its own check
+ * (`o2b decision-model check`), and neither kind carries a model string
+ * the survey could be keyed on.
+ */
+
+import { discoverConfig } from "../../config.ts";
+import { assertHttpEgressEndpoint } from "../../search/embeddings/http-util.ts";
+import { resolveSearchConfig } from "../../search/index.ts";
+import {
+ EMBEDDING_SUNSET,
+ EMBEDDING_SUNSET_SURVEY_HORIZON_DAYS,
+ EMBEDDING_SUNSET_UNDETERMINED_REASON,
+ type EmbeddingSunsetSurvey,
+ type EmbeddingSunsetVerdict,
+} from "../../search/embeddings/sunset.ts";
+import { loadRerankRegistry } from "../../search/rerank/registry.ts";
+import { classifyRerankSunset, RERANK_SUNSET_SURVEY } from "../../search/rerank/sunset.ts";
+import type { ResolvedRerankConfig } from "../../search/types.ts";
+import { envOrConfig } from "../../validate.ts";
+import type { DoctorIssue } from "../types.ts";
+import type { DoctorCheck, DoctorCheckContext, DoctorFindings } from "./check.ts";
+import { EMBEDDING_SUNSET_WARNING_WINDOW_DAYS } from "./embedding-sunset-check.ts";
+import { pushUncertain } from "./uncertain-stream.ts";
+
+/** An enabled remote rerank whose endpoint cannot resolve. */
+export const RERANK_ENDPOINT_UNCONFIGURED_CODE = "rerank-endpoint-unconfigured";
+
+/** The configured rerank model has an announced decommission date inside the window. */
+export const RERANK_MODEL_SUNSET_ANNOUNCED_CODE = "rerank-model-sunset-announced";
+
+/** The configured rerank model is outside the survey; no statement was made. */
+export const RERANK_MODEL_SUNSET_UNSURVEYED_CODE = "rerank-model-sunset-unsurveyed";
+
+/** The check ran and reached no sunset verdict; the message says why. */
+export const RERANK_MODEL_SUNSET_UNDETERMINED_CODE = "rerank-model-sunset-undetermined";
+
+/** The only rerank kind that resolves a remote endpoint keyed on a model string. */
+const REMOTE_RERANK_KIND: ResolvedRerankConfig["kind"] = "openai-compat";
+
+/** The config keys an operator edits, named in the findings verbatim. */
+const BASE_URL_KEY = "search_rerank_base_url";
+const MODEL_KEY = "search_rerank_model";
+const ENV_KEY_KEY = "search_rerank_env_key";
+const PROVIDER_KEY = "search_rerank_provider";
+const ALLOW_INSECURE_HTTP_KEY = "search_rerank_allow_insecure_http";
+/** The environment override of {@link PROVIDER_KEY}, read the way the resolver reads it. */
+const PROVIDER_ENV = "OPEN_SECOND_BRAIN_SEARCH_RERANK_PROVIDER";
+
+/** Why every rerank-enabled search fails while the endpoint is unresolved. */
+const FAIL_CLOSED =
+ "rerank is enabled with the openai-compat kind, so every search resolves this endpoint and " +
+ "fails while it cannot";
+
+/**
+ * The provider name the configuration carries, or null.
+ *
+ * Read with the resolver's own precedence (environment over config file)
+ * and the resolver's own config source: no file when the pass names no
+ * config path, exactly as `resolveSearchConfig` does, so the two can never
+ * disagree about which name is in force.
+ */
+function configuredProviderName(configPath: string | undefined): string | null {
+ const config = configPath ? discoverConfig(configPath).data : {};
+ return envOrConfig(process.env, config, PROVIDER_ENV, PROVIDER_KEY);
+}
+
+/**
+ * Whether `value` is absent for the runtime: null, empty or whitespace.
+ * The endpoint resolver rejects a blank string the same way it rejects a
+ * missing one, so a variable exported as `RERANK_KEY=` is a gap here too.
+ */
+function blank(value: string | null): boolean {
+ return (value ?? "").trim() === "";
+}
+
+/**
+ * The fixed finding for a base URL that carries `user:password@`. The key
+ * travels in a header from {@link ENV_KEY_KEY}, and the endpoint rule's
+ * own refusal repeats the raw URL, so the URL is never echoed here.
+ */
+const CREDENTIALED_BASE_URL =
+ `${BASE_URL_KEY} must not carry user:password@ credentials; the key is sent in a header ` +
+ `from ${ENV_KEY_KEY}`;
+
+/** Whether `baseUrl` parses and names a username or a password. */
+function carriesCredentials(baseUrl: string): boolean {
+ let parsed: URL;
+ try {
+ parsed = new URL(baseUrl);
+ } catch {
+ // Not a URL at all: the endpoint rule names that itself, and a string
+ // it cannot parse has no userinfo part to strip.
+ return false;
+ }
+ return parsed.username !== "" || parsed.password !== "";
+}
+
+/** Stands in for the configured base URL wherever a refusal would repeat it. */
+const BASE_URL_PLACEHOLDER = `<${BASE_URL_KEY}>`;
+
+/**
+ * Why `baseUrl` would be refused by the endpoint rule the rerank provider
+ * applies at construction (`assertHttpEgressEndpoint`), or null when it is
+ * accepted. No request is sent; the rule reads the URL's shape only. The
+ * rule's message repeats the raw value, and a string the URL parser rejects
+ * (or one without a scheme) can still carry `user:password@` that
+ * {@link carriesCredentials} cannot see, so every occurrence of the value is
+ * replaced with {@link BASE_URL_PLACEHOLDER} and the rest of the message kept.
+ */
+function baseUrlRefusal(rerank: ResolvedRerankConfig, baseUrl: string): string | null {
+ // The opt-out admits any parseable http URL; answer that here so the
+ // runtime's once-per-process plain-http warning is not spent by doctor.
+ if (rerank.allowInsecureHttp === true) {
+ try {
+ if (new URL(baseUrl).protocol === "http:") return null;
+ } catch {
+ // Not a URL: fall through, the rule names it.
+ }
+ }
+ try {
+ assertHttpEgressEndpoint(baseUrl, BASE_URL_KEY, {
+ allowInsecureHttp: rerank.allowInsecureHttp === true,
+ key: ALLOW_INSECURE_HTTP_KEY,
+ });
+ return null;
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ return message.split(baseUrl).join(BASE_URL_PLACEHOLDER);
+ }
+}
+
+/** Every reason the endpoint cannot resolve, in the order an operator fixes them. */
+function endpointGaps(rerank: ResolvedRerankConfig, ctx: DoctorCheckContext): string[] {
+ const gaps: string[] = [];
+ if (rerank.baseUrl === null || blank(rerank.baseUrl)) {
+ gaps.push(`${BASE_URL_KEY} is not set`);
+ } else if (carriesCredentials(rerank.baseUrl)) {
+ gaps.push(CREDENTIALED_BASE_URL);
+ } else {
+ const refusal = baseUrlRefusal(rerank, rerank.baseUrl);
+ if (refusal !== null) gaps.push(refusal);
+ }
+ if (blank(rerank.model)) gaps.push(`${MODEL_KEY} is not set`);
+ if (blank(rerank.envKey)) {
+ gaps.push(`${ENV_KEY_KEY} is not set, so no API key can be read`);
+ } else if (blank(rerank.apiKey)) {
+ gaps.push(`the environment variable ${rerank.envKey} named by ${ENV_KEY_KEY} is not set`);
+ }
+ // An unregistered provider name matters only when it is why a field is
+ // empty: the explicit search_rerank_* values win over a profile, so with
+ // all of them set search works and the name is no endpoint gap. A
+ // profile carries the base URL, the model and the key variable, never
+ // the key itself, so an unset key value is not the name's doing.
+ if (!blank(rerank.baseUrl) && !blank(rerank.model) && !blank(rerank.envKey)) return gaps;
+ const provider = configuredProviderName(ctx.configPath);
+ if (provider !== null && !loadRerankRegistry(ctx.vault).some((p) => p.name === provider)) {
+ gaps.unshift(
+ `${PROVIDER_KEY} names ${provider}, which no registered rerank profile carries, so its ` +
+ "base URL, model and key variable were not applied",
+ );
+ }
+ return gaps;
+}
+
+/** The provenance clause every sunset message carries. */
+function provenance(verdict: EmbeddingSunsetVerdict): string {
+ return `this rests on the rerank decommission survey last reviewed ${verdict.surveyed_at}, which records model strings and identifies nobody's endpoint`;
+}
+
+function announcedMessage(verdict: EmbeddingSunsetVerdict): string {
+ const days = verdict.days_remaining ?? 0;
+ const when =
+ days < 0
+ ? `passed ${Math.abs(days)} days ago, so search no longer sends it rerank requests and keeps the heuristic order`
+ : `${days} days away, inside the ${EMBEDDING_SUNSET_WARNING_WINDOW_DAYS}-day window`;
+ return (
+ `the configured rerank model ${verdict.model} has an announced decommission date of ` +
+ `${verdict.sunset_at}, ${when}. Choose another rerank model or endpoint. Note ${provenance(verdict)}`
+ );
+}
+
+function unsurveyedMessage(verdict: EmbeddingSunsetVerdict): string {
+ return (
+ `the configured rerank model ${verdict.model} is outside this build's rerank decommission ` +
+ `survey (reviewed ${verdict.surveyed_at}), so NO sunset statement was made about it. That is ` +
+ "not the same as no decommission having been announced - nobody here looked this model up"
+ );
+}
+
+function undeterminedMessage(verdict: EmbeddingSunsetVerdict): string {
+ switch (verdict.reason) {
+ case EMBEDDING_SUNSET_UNDETERMINED_REASON.surveyStale:
+ return (
+ `the rerank decommission survey covers ${verdict.model} and records no announcement, but ` +
+ `it was reviewed ${verdict.surveyed_at}, more than ${EMBEDDING_SUNSET_SURVEY_HORIZON_DAYS} ` +
+ "days ago. A negative is a claim about the world and it expires, so this build will not " +
+ "report it as a clean bill of health"
+ );
+ case EMBEDDING_SUNSET_UNDETERMINED_REASON.surveyEntryMalformed:
+ return (
+ `the rerank decommission survey entry for ${verdict.model} carries a date this build ` +
+ "cannot parse, so no verdict was reached. That is a defect in the shipped table rather " +
+ "than in this vault"
+ );
+ case EMBEDDING_SUNSET_UNDETERMINED_REASON.modelUnresolved:
+ // Unreachable from `run`: a missing model is the endpoint finding
+ // and the survey is never consulted for it. Kept as its own arm so
+ // the switch stays total over the closed reason vocabulary.
+ return `the configuration resolved no rerank model, so there was nothing to check. ${provenance(verdict)}`;
+ case null:
+ return `no verdict was reached for ${verdict.model}, and this build recorded no reason`;
+ }
+}
+
+/**
+ * Build the check against `survey`.
+ *
+ * A factory, following `makeEmbeddingSunsetCheck`: the survey is data the
+ * check reads, so injecting it makes every verdict reachable from a test
+ * without editing the shipped table.
+ */
+export function makeRerankHealthCheck(
+ survey: EmbeddingSunsetSurvey = RERANK_SUNSET_SURVEY,
+): DoctorCheck {
+ return {
+ failSoft: true,
+ run(ctx: DoctorCheckContext, out: DoctorFindings): void {
+ const path = ctx.configPath ?? ctx.vault;
+ let rerank: ResolvedRerankConfig;
+ try {
+ rerank = resolveSearchConfig({ vault: ctx.vault, configPath: ctx.configPath }).rerank;
+ } catch (err) {
+ pushUncertain(out.uncertain, {
+ code: RERANK_MODEL_SUNSET_UNDETERMINED_CODE,
+ path,
+ message:
+ "the search configuration could not be resolved, so neither the rerank endpoint nor " +
+ `the rerank model's decommission state could be checked: ${
+ err instanceof Error ? err.message : String(err)
+ }`,
+ });
+ return;
+ }
+ if (!rerank.enabled || rerank.kind !== REMOTE_RERANK_KIND) return;
+
+ const gaps = endpointGaps(rerank, ctx);
+ if (gaps.length > 0) {
+ out.issues.push({
+ severity: "error",
+ code: RERANK_ENDPOINT_UNCONFIGURED_CODE,
+ path,
+ target: rerank.model ?? "",
+ message: `${FAIL_CLOSED}: ${gaps.join("; ")}`,
+ } satisfies DoctorIssue);
+ }
+ // A missing model is already the finding above; consulting the
+ // survey for it would meet the operator with two findings for one
+ // condition.
+ if (rerank.model === null || blank(rerank.model)) return;
+
+ const verdict = classifyRerankSunset(rerank.model, ctx.now.getTime(), survey);
+ switch (verdict.state) {
+ case EMBEDDING_SUNSET.noneAnnounced:
+ return;
+ case EMBEDDING_SUNSET.announced:
+ if ((verdict.days_remaining ?? 0) > EMBEDDING_SUNSET_WARNING_WINDOW_DAYS) return;
+ out.issues.push({
+ severity: "warning",
+ code: RERANK_MODEL_SUNSET_ANNOUNCED_CODE,
+ path,
+ target: verdict.model ?? "",
+ message: announcedMessage(verdict),
+ } satisfies DoctorIssue);
+ return;
+ case EMBEDDING_SUNSET.unsurveyed:
+ pushUncertain(out.uncertain, {
+ code: RERANK_MODEL_SUNSET_UNSURVEYED_CODE,
+ path,
+ message: unsurveyedMessage(verdict),
+ });
+ return;
+ case EMBEDDING_SUNSET.undetermined:
+ pushUncertain(out.uncertain, {
+ code: RERANK_MODEL_SUNSET_UNDETERMINED_CODE,
+ path,
+ message: undeterminedMessage(verdict),
+ });
+ return;
+ }
+ },
+ };
+}
+
+/** The registered instance, reading the shipped survey. */
+export const rerankHealthCheck: DoctorCheck = makeRerankHealthCheck();
diff --git a/src/core/brain/expiration-set.ts b/src/core/brain/expiration-set.ts
index 55266db5..989d0750 100644
--- a/src/core/brain/expiration-set.ts
+++ b/src/core/brain/expiration-set.ts
@@ -68,6 +68,21 @@ export const EXPIRATION_TARGET_KIND = Object.freeze({
export type ExpirationTargetKind =
(typeof EXPIRATION_TARGET_KIND)[keyof typeof EXPIRATION_TARGET_KIND];
+/**
+ * The codes the three refusals below are reported under on the MCP wire:
+ * each class's own name, which `brain_expire` has always sent as
+ * `error.data.code`. One definition, so the class names and the boundary
+ * registry cannot drift apart.
+ */
+export const EXPIRATION_REFUSAL_CODE = Object.freeze({
+ invalidTarget: "InvalidExpirationTargetError",
+ targetNotFound: "ExpirationTargetNotFoundError",
+ invalidValue: "ExpirationValueError",
+} as const);
+
+/** Membership list over {@link EXPIRATION_REFUSAL_CODE}. */
+export const EXPIRATION_REFUSAL_CODES = Object.freeze(Object.values(EXPIRATION_REFUSAL_CODE));
+
/**
* An id shape that could never name an artifact, so no filesystem path is
* formed from it. The regexes also close path traversal: no separator
@@ -84,7 +99,7 @@ export class InvalidExpirationTargetError extends Error {
`invalid expiration target ${JSON.stringify(id)} - expected sig-<date>-<slug>, ` +
"pref-<slug> or ret-<slug>",
);
- this.name = "InvalidExpirationTargetError";
+ this.name = EXPIRATION_REFUSAL_CODE.invalidTarget;
this.id = id;
}
}
@@ -95,7 +110,7 @@ export class ExpirationTargetNotFoundError extends Error {
readonly searched: ReadonlyArray<string>;
constructor(id: string, searched: ReadonlyArray<string>) {
super(`no signal or preference with id ${JSON.stringify(id)}; searched ${searched.join(", ")}`);
- this.name = "ExpirationTargetNotFoundError";
+ this.name = EXPIRATION_REFUSAL_CODE.targetNotFound;
this.id = id;
this.searched = Object.freeze([...searched]);
}
@@ -112,7 +127,7 @@ export class ExpirationValueError extends Error {
readonly value: string;
constructor(value: string, reason: string) {
super(reason);
- this.name = "ExpirationValueError";
+ this.name = EXPIRATION_REFUSAL_CODE.invalidValue;
this.value = value;
}
}
diff --git a/src/core/brain/write-session/engine.ts b/src/core/brain/write-session/engine.ts
index 0a57d800..66fd6c88 100644
--- a/src/core/brain/write-session/engine.ts
+++ b/src/core/brain/write-session/engine.ts
@@ -53,14 +53,31 @@ import { assertVaultIdentityForWrite } from "../vault-identity.ts";
export const DEFAULT_RETRY_CAP = 3;
export const DEFAULT_TTL_MS = 24 * 3600 * 1000;
+/**
+ * Why a request named a session that cannot take it, for the two refusals
+ * a caller can act on without reading prose: the id names no session, or
+ * the session already ended. Every other request failure carries none.
+ */
+export type WriteSessionRequestReason = "unknown-session" | "terminal-session";
+
+export interface WriteSessionRequestErrorOptions {
+ readonly reason?: WriteSessionRequestReason;
+}
+
/** Structured request failure - carries the machine-readable errors. */
export class WriteSessionRequestError extends Error {
readonly errors: ReadonlyArray<WriteSessionError>;
+ readonly reason?: WriteSessionRequestReason;
- constructor(message: string, errors: ReadonlyArray<WriteSessionError> = []) {
+ constructor(
+ message: string,
+ errors: ReadonlyArray<WriteSessionError> = [],
+ options: WriteSessionRequestErrorOptions = {},
+ ) {
super(message);
this.name = "WriteSessionRequestError";
this.errors = errors;
+ if (options.reason !== undefined) this.reason = options.reason;
}
}
@@ -270,7 +287,9 @@ export function loadLiveSession(vault: string, id: string, now: string): WriteSe
throw new WriteSessionRequestError(probe.error);
}
if (probe.session === null) {
- throw new WriteSessionRequestError(`unknown write-session: ${id}`);
+ throw new WriteSessionRequestError(`unknown write-session: ${id}`, [], {
+ reason: "unknown-session",
+ });
}
const session = probe.session;
if (isTerminalWriteSessionStatus(session.status)) {
@@ -285,6 +304,8 @@ export function loadLiveSession(vault: string, id: string, now: string): WriteSe
`write-session ${id} is terminal (${session.status}${
session.failReason ? `/${session.failReason}` : ""
})`,
+ [],
+ { reason: "terminal-session" },
);
}
return session;
diff --git a/src/core/search/pipeline/cache-slot.ts b/src/core/search/pipeline/cache-slot.ts
index f170a6ab..be55e9a7 100644
--- a/src/core/search/pipeline/cache-slot.ts
+++ b/src/core/search/pipeline/cache-slot.ts
@@ -12,6 +12,7 @@ import { activationStateFingerprint } from "../activation/store.ts";
import { learnedWeightsFingerprint } from "../feedback.ts";
import { buildCacheKey, getCachedOutcome, putCachedOutcome } from "../query-cache.ts";
import { reinforceFingerprint } from "../reinforce.ts";
+import { RERANK_SUNSET_SURVEY } from "../rerank/sunset.ts";
import type { Store } from "../store.ts";
import type { SemanticPolicy } from "../semantic-phase.ts";
import type { TemporalIntent } from "../temporal-intent.ts";
@@ -71,6 +72,14 @@ function configFingerprint(config: ResolvedSearchConfig): string {
rrkModel: config.rerank.model,
rrkTopK: config.rerank.topK,
rrkMin: config.rerank.minScore,
+ // An enabled openai-compat rerank skips a model once its surveyed
+ // shutdown date has passed, and that skip answer is cached. The
+ // survey's review date re-keys it, so a build that corrects a survey
+ // row stops replaying the old verdict. Present only for that kind, so
+ // every other key is unchanged.
+ ...(config.rerank.enabled && config.rerank.kind === "openai-compat"
+ ? { rrkSunset: RERANK_SUNSET_SURVEY.reviewedAt }
+ : {}),
// The decision-model kind: its mode decides whether the order changes.
// Present only for that kind, so every other key is unchanged.
...(config.rerank.kind === "decision-model"
diff --git a/src/core/search/pipeline/post-rank.ts b/src/core/search/pipeline/post-rank.ts
index 3a2ba7e0..745204f7 100644
--- a/src/core/search/pipeline/post-rank.ts
+++ b/src/core/search/pipeline/post-rank.ts
@@ -38,6 +38,11 @@ import {
type FrontmatterCache,
} from "../result-filters.ts";
import { applyStructuredExclusions } from "../structured-lanes.ts";
+import {
+ RETRIEVAL_DEGRADATION,
+ noteDegradation,
+ type RetrievalDegradationSink,
+} from "../retrieval-trail.ts";
import type { Store } from "../store.ts";
import type {
BrainSearchResult,
@@ -64,6 +69,8 @@ export interface PostRankInput {
readonly raceRerank?: RerankRace;
/** The deadline's cancellation, handed to the rerank provider request. */
readonly signal?: AbortSignal;
+ /** The request's clock, for the rerank sunset decision. */
+ readonly nowMs: number;
}
/** Start `work` under a budget; serve `fallback()` when the budget wins. */
@@ -82,6 +89,13 @@ export interface PostRankOutcome {
/** Null on the default path, where the outcome shape stays unchanged. */
readonly trustReceipts: TrustReceipts | null;
readonly warnings: string[];
+ /**
+ * The typed codes beside {@link warnings}, merged into the search's own
+ * sink like every lane's. A failed cross-encoder request records
+ * `rerank-provider-unavailable` with its failure category here, and a
+ * request skipped for a retired model records `rerank-model-sunset`.
+ */
+ readonly degraded: RetrievalDegradationSink;
/**
* Extra decision-model answers carried by the rerank request (issue
* #213, Part 2). Present only when rerank kind `decision-model` ran,
@@ -115,6 +129,7 @@ function decisionMetaFields(meta: FrontmatterMap): Readonly<Record<string, strin
export async function applyPostRankPhases(input: PostRankInput): Promise<PostRankOutcome> {
const { store, config, opts, frontmatterCache } = input;
const warnings: string[] = [];
+ const degraded: RetrievalDegradationSink = [];
const excluded = applyStructuredExclusions(input.pool, input.structured);
// Relation polarity (recall-trust-suite): typed relation edges adjust
@@ -173,10 +188,21 @@ export async function applyPostRankPhases(input: PostRankInput): Promise<PostRan
const runRerank = (): Promise<ReadonlyArray<BrainSearchResult>> =>
applyCrossEncoderRerank(reinforced, input.query, config.rerank, {
...(input.signal !== undefined ? { signal: input.signal } : {}),
- onTelemetry: (event) =>
- emitGatedTelemetry(event.status === "error", () => {
- warnings.push(`rerank_degraded: ${event.reason ?? "endpoint error"}`);
- }),
+ sunset: {
+ nowMs: input.nowMs,
+ onSkip: () => noteDegradation(degraded, RETRIEVAL_DEGRADATION.rerankModelSunset),
+ },
+ onTelemetry: (event) => {
+ if (event.status !== "error") return;
+ // The code is the answer's own record, not telemetry: it is
+ // written outside the fail-open gate so it cannot be swallowed.
+ noteDegradation(degraded, RETRIEVAL_DEGRADATION.rerankProviderUnavailable, {
+ category: event.category,
+ });
+ emitGatedTelemetry(event, (failure) => {
+ warnings.push(`rerank_degraded: ${failure.reason}`);
+ });
+ },
// Decision-model kind only: a candidate leaves the machine only when
// its page's visibility resolves and does not carry `private`.
resolveVisibility: (path) => {
@@ -269,6 +295,7 @@ export async function applyPostRankPhases(input: PostRankInput): Promise<PostRan
results: adjusted.results,
trustReceipts,
warnings,
+ degraded,
...(decisionExtras !== undefined ? { decisionModel: decisionExtras } : {}),
...(decisionFallback ? { decisionFallback: true } : {}),
};
diff --git a/src/core/search/rerank/cross-encoder.ts b/src/core/search/rerank/cross-encoder.ts
index 99e0212f..6ba73885 100644
--- a/src/core/search/rerank/cross-encoder.ts
+++ b/src/core/search/rerank/cross-encoder.ts
@@ -11,17 +11,28 @@
*
* Network rules mirror `embeddings/openai-compat.ts` at a smaller scale:
* one request (the top-K candidate set is small, no batching), a
- * per-request timeout, and provider-shaped `SearchError`s. Retries are
+ * per-request timeout, and provider-shaped `RerankEndpointError`s (a
+ * `SearchError` with code `RERANK_PROVIDER_HTTP` plus a closed failure
+ * category, see `failure.ts`). Retries are
* intentionally omitted: this is an opt-in final reader step that
* degrades gracefully to the heuristic ordering on ANY failure (see
* `applyCrossEncoderRerank`), so a slow retry loop would only add latency
* to the hot path for a result the caller already has a good answer for.
*/
-import { SearchError } from "../types.ts";
import { assertHttpEgressEndpoint, linkAbortSignal } from "../embeddings/http-util.ts";
import type { OpenAiCompatEndpoint } from "../embeddings/provider-resolve.ts";
import type { RerankCallOptions, RerankProvider } from "./contract.ts";
+import {
+ RERANK_FAILURE_CATEGORY,
+ RerankEndpointError,
+ rerankCategoryForStatus,
+} from "./failure.ts";
+
+/** A 2xx body this build cannot read as one score per document. */
+function malformed(message: string): RerankEndpointError {
+ return new RerankEndpointError(message, { category: RERANK_FAILURE_CATEGORY.malformed });
+}
/** Default per-request timeout when the caller does not override it. */
export const DEFAULT_RERANK_TIMEOUT_MS = 5000;
@@ -45,19 +56,13 @@ function extractItems(json: unknown): ReadonlyArray<RerankResultItem> {
) {
return (json as WrappedRerankResponse).results;
}
- throw new SearchError(
- "RERANK_PROVIDER_HTTP",
- "rerank response shape: expected an array or a { results: [...] } object",
- );
+ throw malformed("rerank response shape: expected an array or a { results: [...] } object");
}
function scoreOf(item: RerankResultItem): number {
const raw = item.relevance_score ?? item.score;
if (typeof raw !== "number" || !Number.isFinite(raw)) {
- throw new SearchError(
- "RERANK_PROVIDER_HTTP",
- `rerank response: item at index ${item.index} has no finite relevance score`,
- );
+ throw malformed(`rerank response: item at index ${item.index} has no finite relevance score`);
}
return raw;
}
@@ -92,62 +97,88 @@ export class CrossEncoderRerankProvider implements RerankProvider {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
const unlink = linkAbortSignal(opts?.signal, controller);
- let response: Response;
+ // The timeout and the caller's signal cover the body read as well as
+ // the fetch, so the timer is cleared only once the body is in.
+ let text: string;
try {
- response = await fetch(this.url, {
- method: "POST",
- headers: {
- "content-type": "application/json",
- authorization: `Bearer ${this.endpoint.apiKey}`,
- },
- body: JSON.stringify({
- model: this.model,
- query,
- documents: [...documents],
- }),
- // No cross-host redirect may take the bearer key - or the query -
- // somewhere the operator did not configure.
- redirect: "error",
- signal: controller.signal,
- });
- } catch (e) {
- const cause = e instanceof Error ? e : new Error(String(e));
- // The caller cancelled: its own abort reason travels up unchanged,
- // so the caller recognises its cancellation by name.
- if (opts?.signal?.aborted === true) throw opts.signal.reason;
- if (cause.name === "AbortError") {
- throw new SearchError(
- "RERANK_PROVIDER_HTTP",
- `rerank request timed out after ${this.timeoutMs}ms`,
+ let response: Response;
+ try {
+ response = await fetch(this.url, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ authorization: `Bearer ${this.endpoint.apiKey}`,
+ },
+ body: JSON.stringify({
+ model: this.model,
+ query,
+ documents: [...documents],
+ }),
+ // No cross-host redirect may take the bearer key - or the query -
+ // somewhere the operator did not configure.
+ redirect: "error",
+ signal: controller.signal,
+ });
+ } catch (e) {
+ const cause = e instanceof Error ? e : new Error(String(e));
+ // The caller cancelled: its own abort reason travels up unchanged,
+ // so the caller recognises its cancellation by name.
+ if (opts?.signal?.aborted === true) throw opts.signal.reason;
+ if (controller.signal.aborted) {
+ throw new RerankEndpointError(`rerank request timed out after ${this.timeoutMs}ms`, {
+ category: RERANK_FAILURE_CATEGORY.timeout,
+ });
+ }
+ throw new RerankEndpointError(`network error: ${cause.message}`, {
+ category: RERANK_FAILURE_CATEGORY.network,
+ });
+ }
+
+ if (!response.ok) {
+ const body = await response.text().catch(() => "");
+ const head = body.slice(0, 300);
+ throw new RerankEndpointError(
+ `rerank HTTP ${response.status}: ${head || response.statusText}`,
+ { category: rerankCategoryForStatus(response.status), status: response.status },
);
}
- throw new SearchError("RERANK_PROVIDER_HTTP", `network error: ${cause.message}`);
+
+ // Read and parse apart: a stream that breaks while the 2xx body is
+ // read is the path failing (`network`), while a body that arrived
+ // whole and is not JSON is the endpoint's answer (`malformed`).
+ try {
+ text = await response.text();
+ } catch (e) {
+ // The timer and the caller's signal abort a stalled body too, and
+ // read the same way they do for the fetch.
+ if (opts?.signal?.aborted === true) throw opts.signal.reason;
+ if (controller.signal.aborted) {
+ throw new RerankEndpointError(`rerank request timed out after ${this.timeoutMs}ms`, {
+ category: RERANK_FAILURE_CATEGORY.timeout,
+ });
+ }
+ const msg = e instanceof Error ? e.message : String(e);
+ throw new RerankEndpointError(`network error: ${msg}`, {
+ category: RERANK_FAILURE_CATEGORY.network,
+ });
+ }
} finally {
clearTimeout(timer);
unlink();
}
-
- if (!response.ok) {
- const body = await response.text().catch(() => "");
- const head = body.slice(0, 300);
- throw new SearchError(
- "RERANK_PROVIDER_HTTP",
- `rerank HTTP ${response.status}: ${head || response.statusText}`,
- );
- }
-
let json: unknown;
try {
- json = await response.json();
+ // Parsed through a Response rather than JSON.parse, so the parse
+ // error, and with it the message, is the one `response.json()` gave.
+ json = await new Response(text).json();
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
- throw new SearchError("RERANK_PROVIDER_HTTP", `rerank response not JSON: ${msg}`);
+ throw malformed(`rerank response not JSON: ${msg}`);
}
const items = extractItems(json);
if (items.length !== documents.length) {
- throw new SearchError(
- "RERANK_PROVIDER_HTTP",
+ throw malformed(
`rerank response shape: expected ${documents.length} scores, got ${items.length}`,
);
}
@@ -163,16 +194,10 @@ export class CrossEncoderRerankProvider implements RerankProvider {
item.index >= documents.length ||
!Number.isInteger(item.index)
) {
- throw new SearchError(
- "RERANK_PROVIDER_HTTP",
- `rerank response: out-of-range index ${item.index}`,
- );
+ throw malformed(`rerank response: out-of-range index ${item.index}`);
}
if (seen[item.index]) {
- throw new SearchError(
- "RERANK_PROVIDER_HTTP",
- `rerank response: duplicate index ${item.index}`,
- );
+ throw malformed(`rerank response: duplicate index ${item.index}`);
}
seen[item.index] = true;
scores[item.index] = scoreOf(item);
diff --git a/src/core/search/rerank/failure.ts b/src/core/search/rerank/failure.ts
new file mode 100644
index 00000000..1d335306
--- /dev/null
+++ b/src/core/search/rerank/failure.ts
@@ -0,0 +1,129 @@
+/**
+ * Why a cross-encoder rerank request failed, as a closed vocabulary.
+ *
+ * The rerank stage degrades to the heuristic order on any request-time
+ * failure, and until this module the only record of why was the provider's
+ * own message inside a `rerank_degraded:` warning. A caller that wanted to
+ * tell a revoked key from a dead endpoint from a flaky one had to
+ * pattern-match English. The category below is computed where the failure
+ * is typed - the HTTP status, the abort, the parse - and never from message
+ * text, so it survives a provider rewording its errors.
+ *
+ * The thrown carrier, {@link RerankEndpointError}, stays a `SearchError`
+ * with the unchanged `RERANK_PROVIDER_HTTP` code and the unchanged message:
+ * every existing consumer of either keeps working byte for byte.
+ */
+
+import { SearchError } from "../search-error.ts";
+
+/** The closed failure categories of a rerank request. */
+export const RERANK_FAILURE_CATEGORY = Object.freeze({
+ /** HTTP 401 or 403: the key is missing, wrong or not allowed this model. */
+ auth: "auth",
+ /** HTTP 402: the account's quota or billing is exhausted. */
+ quota: "quota",
+ /** HTTP 404 or 410: the endpoint or the model is gone (the decommission signal). */
+ gone: "gone",
+ /** Any other HTTP 4xx: the endpoint refused this request as sent. */
+ rejected: "rejected",
+ /**
+ * HTTP 408, 429 or 5xx: the endpoint may answer later. Some vendors also
+ * answer 429 for exhausted quota; the category is computed from the
+ * status alone.
+ */
+ transient: "transient",
+ /** The request outlived this build's own per-request timeout. */
+ timeout: "timeout",
+ /** The request never reached an answer: refused connection, DNS, TLS, redirect. */
+ network: "network",
+ /** The endpoint answered 2xx with a body this build cannot read as scores. */
+ malformed: "malformed",
+ /**
+ * A failure no rerank provider typed - a provider implementation outside
+ * the cross-encoder threw a plain error. Named, so it is never hidden
+ * inside another category.
+ */
+ unclassified: "unclassified",
+} as const);
+
+/** Closed union over {@link RERANK_FAILURE_CATEGORY}. */
+export type RerankFailureCategory =
+ (typeof RERANK_FAILURE_CATEGORY)[keyof typeof RERANK_FAILURE_CATEGORY];
+
+/** Membership list, from the most to the least specific operator action. */
+export const RERANK_FAILURE_CATEGORIES: ReadonlyArray<RerankFailureCategory> = Object.freeze([
+ RERANK_FAILURE_CATEGORY.auth,
+ RERANK_FAILURE_CATEGORY.quota,
+ RERANK_FAILURE_CATEGORY.gone,
+ RERANK_FAILURE_CATEGORY.rejected,
+ RERANK_FAILURE_CATEGORY.transient,
+ RERANK_FAILURE_CATEGORY.timeout,
+ RERANK_FAILURE_CATEGORY.network,
+ RERANK_FAILURE_CATEGORY.malformed,
+ RERANK_FAILURE_CATEGORY.unclassified,
+]);
+
+/** Narrow a string read back across a tool boundary. */
+export function isRerankFailureCategory(value: unknown): value is RerankFailureCategory {
+ return (
+ typeof value === "string" &&
+ (RERANK_FAILURE_CATEGORIES as ReadonlyArray<string>).includes(value)
+ );
+}
+
+const AUTH_STATUSES: ReadonlySet<number> = new Set([401, 403]);
+const QUOTA_STATUSES: ReadonlySet<number> = new Set([402]);
+const GONE_STATUSES: ReadonlySet<number> = new Set([404, 410]);
+const TRANSIENT_CLIENT_STATUSES: ReadonlySet<number> = new Set([408, 429]);
+const SERVER_ERROR_MIN = 500;
+
+/**
+ * The category of a non-2xx rerank response. Total over every status the
+ * cross-encoder can see: a status that is not an auth, quota, gone or
+ * retryable client status is a server error (5xx, transient) or a refusal
+ * of this request (every other non-2xx, rejected).
+ */
+export function rerankCategoryForStatus(status: number): RerankFailureCategory {
+ if (AUTH_STATUSES.has(status)) return RERANK_FAILURE_CATEGORY.auth;
+ if (QUOTA_STATUSES.has(status)) return RERANK_FAILURE_CATEGORY.quota;
+ if (GONE_STATUSES.has(status)) return RERANK_FAILURE_CATEGORY.gone;
+ if (TRANSIENT_CLIENT_STATUSES.has(status) || status >= SERVER_ERROR_MIN) {
+ return RERANK_FAILURE_CATEGORY.transient;
+ }
+ return RERANK_FAILURE_CATEGORY.rejected;
+}
+
+/** What a {@link RerankEndpointError} knows beyond its message. */
+export interface RerankEndpointErrorOptions {
+ readonly category: RerankFailureCategory;
+ /** Upstream HTTP status, present only when the endpoint answered. */
+ readonly status?: number;
+}
+
+/**
+ * A rerank request failure with its category attached. Code and message
+ * are exactly those of the untyped `SearchError` it replaces.
+ */
+export class RerankEndpointError extends SearchError {
+ readonly category: RerankFailureCategory;
+ constructor(message: string, opts: RerankEndpointErrorOptions) {
+ super(
+ "RERANK_PROVIDER_HTTP",
+ message,
+ opts.status !== undefined ? { status: opts.status } : {},
+ );
+ this.name = "RerankEndpointError";
+ this.category = opts.category;
+ }
+}
+
+/**
+ * The category of any value a rerank provider threw. A typed
+ * {@link RerankEndpointError} names its own; anything else was not typed
+ * by a provider and says so.
+ */
+export function rerankCategoryForError(error: unknown): RerankFailureCategory {
+ return error instanceof RerankEndpointError
+ ? error.category
+ : RERANK_FAILURE_CATEGORY.unclassified;
+}
diff --git a/src/core/search/rerank/index.ts b/src/core/search/rerank/index.ts
index 08833677..6fd9fad4 100644
--- a/src/core/search/rerank/index.ts
+++ b/src/core/search/rerank/index.ts
@@ -28,20 +28,41 @@ import { makeRerankProvider } from "./provider.ts";
import type { RerankProvider } from "./contract.ts";
import type { DecisionProvider } from "../../decision-model/contract.ts";
import type { DecisionRerankExtras } from "./decision-model.ts";
+import {
+ RERANK_FAILURE_CATEGORY,
+ RerankEndpointError,
+ rerankCategoryForError,
+ type RerankFailureCategory,
+} from "./failure.ts";
+import { classifyRerankSunset, rerankSunsetHasPassed } from "./sunset.ts";
+import type { EmbeddingSunsetSurvey } from "../embeddings/sunset.ts";
/** Fixed-precision so the reason string is stable for a given score. */
function fmtScore(x: number): string {
return x.toFixed(4);
}
-export interface RerankTelemetryEvent {
- readonly status: "applied" | "error";
- /** Present on `error`: the provider-shaped failure message. */
- readonly reason?: string;
+interface RerankTelemetryBase {
/** Number of top candidates handed to the cross-encoder. */
readonly candidateCount: number;
}
+/** The rerank re-ordered the top-K block. */
+export interface RerankAppliedEvent extends RerankTelemetryBase {
+ readonly status: "applied";
+}
+
+/** The rerank request failed and the heuristic order was served. */
+export interface RerankErrorEvent extends RerankTelemetryBase {
+ readonly status: "error";
+ /** Why, as a closed category computed from the typed failure. */
+ readonly category: RerankFailureCategory;
+ /** The provider-shaped failure message, for the operator-facing warning. */
+ readonly reason: string;
+}
+
+export type RerankTelemetryEvent = RerankAppliedEvent | RerankErrorEvent;
+
export interface ApplyCrossEncoderRerankOptions {
/** Inject a provider (tests / alternate backends). Defaults to the HTTP one. */
readonly provider?: RerankProvider;
@@ -96,6 +117,24 @@ export interface ApplyCrossEncoderRerankOptions {
* instead of degrading, because nobody is waiting for the order.
*/
readonly signal?: AbortSignal;
+ /**
+ * `openai-compat` kind only: consult the rerank sunset survey for the
+ * configured model, and skip the request once its announced shutdown
+ * date has passed. Absent: the survey is not consulted (direct callers
+ * and tests that measure the endpoint they are pointed at).
+ */
+ readonly sunset?: RerankSunsetOptions;
+}
+
+/**
+ * The sunset skip's inputs. The clock is the caller's own, so this stage
+ * reads no wall clock; the survey defaults to the shipped one.
+ */
+export interface RerankSunsetOptions {
+ readonly nowMs: number;
+ readonly survey?: EmbeddingSunsetSurvey;
+ /** Called once when the configured model is past its announced date. */
+ readonly onSkip: () => void;
}
interface Scored {
@@ -210,6 +249,17 @@ export async function applyCrossEncoderRerank(
if (results.length === 0) return results;
+ // A model past its announced shutdown can only refuse the request, so
+ // none is made. Only the remote kind keys on a model string a vendor
+ // can retire; `local` is this build's own reranker.
+ if (config.kind === "openai-compat" && opts.sunset !== undefined) {
+ const verdict = classifyRerankSunset(config.model, opts.sunset.nowMs, opts.sunset.survey);
+ if (rerankSunsetHasPassed(verdict)) {
+ opts.sunset.onSkip();
+ return results;
+ }
+ }
+
const topK = Math.min(Math.max(1, config.topK), results.length);
const head = results.slice(0, topK);
const tail = results.slice(topK);
@@ -223,7 +273,9 @@ export async function applyCrossEncoderRerank(
opts.signal !== undefined ? { signal: opts.signal } : undefined,
);
if (scores.length !== documents.length) {
- throw new Error(`expected ${documents.length} scores, got ${scores.length}`);
+ throw new RerankEndpointError(`expected ${documents.length} scores, got ${scores.length}`, {
+ category: RERANK_FAILURE_CATEGORY.malformed,
+ });
}
} catch (e) {
// A cancelled call is not an endpoint failure: no telemetry, and the
@@ -233,6 +285,7 @@ export async function applyCrossEncoderRerank(
// untouched and emit one fail-open telemetry event.
opts.onTelemetry?.({
status: "error",
+ category: rerankCategoryForError(e),
reason: e instanceof Error ? e.message : String(e),
candidateCount: topK,
});
diff --git a/src/core/search/rerank/sunset.ts b/src/core/search/rerank/sunset.ts
new file mode 100644
index 00000000..a82144ad
--- /dev/null
+++ b/src/core/search/rerank/sunset.ts
@@ -0,0 +1,135 @@
+/**
+ * Announced decommissions of cross-encoder rerank models.
+ *
+ * The rerank stage keys on the configured `search_rerank_model` string, and
+ * a model its vendor has retired stops answering on a known date. Once that
+ * date has passed, every search would pay a request the endpoint can only
+ * refuse; the stage skips the call instead and names the skip on the
+ * retrieval trail (`rerank-model-sunset`).
+ *
+ * ## One mechanism, not two
+ *
+ * This is the embedding survey's problem with a different population, so
+ * it reuses that module's survey shape, states, sources, staleness horizon
+ * and classifier unchanged (`embeddings/sunset.ts`). Its header holds the
+ * reasoning this table inherits: why a static survey rather than a network
+ * registry, why a negative expires while a positive survives a stale
+ * survey, and why absence is `unsurveyed` rather than `none_announced`.
+ * Only the rows below are rerank-specific.
+ *
+ * ## Why the ZeroEntropy rows are negatives
+ *
+ * ZeroEntropy announced on 2026-07-24 that its hosted products are sunset
+ * after 2026-09-04, and that its models are open source under Apache 2.0.
+ * That is an ENDPOINT going away, not a model being decommissioned: an
+ * entry here is a claim about the model string, and a self-hosted
+ * `zerank` checkpoint keeps answering after the hosted API is gone. A
+ * positive row would make the skip refuse a live self-hosted endpoint. So
+ * the checkpoints are recorded as open-checkpoint negatives, and a dead
+ * hosted endpoint is reported by the liveness code instead
+ * (`rerank-provider-unavailable`, category `gone` or `network`).
+ *
+ * Pure and injectable like the embedding classifier: the clock and the
+ * survey are parameters, so no wall clock is read here.
+ */
+
+import {
+ EMBEDDING_SUNSET,
+ classifyEmbeddingSunset,
+ type EmbeddingSunsetEntry,
+ type EmbeddingSunsetSurvey,
+ type EmbeddingSunsetVerdict,
+} from "../embeddings/sunset.ts";
+
+/** Where the Cohere rows were read from. Cited, not remembered. */
+const COHERE_DEPRECATIONS_URL = "https://docs.cohere.com/docs/deprecations";
+
+/** The shutdown date that page states for both second-generation rerank models. */
+const COHERE_RERANK_V2_SHUTDOWN = "2025-04-30";
+
+const COHERE_RERANK_V2_SOURCE =
+ `Cohere deprecations, announced 2024-12-02, shutdown ${COHERE_RERANK_V2_SHUTDOWN}, ` +
+ `recommended replacement rerank-v3.5: ${COHERE_DEPRECATIONS_URL}`;
+
+/** Every model that entry names, verbatim. */
+const COHERE_RERANK_V2_MODELS: ReadonlyArray<string> = Object.freeze([
+ "rerank-english-v2.0",
+ "rerank-multilingual-v2.0",
+]);
+
+/** Where the ZeroEntropy announcement was read. */
+const ZEROENTROPY_ANNOUNCEMENT_URL =
+ "https://zeroentropy.dev/articles/zeroentropy-is-joining-notion/";
+
+const ZEROENTROPY_SOURCE =
+ "open-weight checkpoint under Apache 2.0 per the ZeroEntropy announcement of 2026-07-24 " +
+ `(${ZEROENTROPY_ANNOUNCEMENT_URL}) and the model card on huggingface.co: there is no operator ` +
+ "with the authority to decommission the model itself";
+
+const ZEROENTROPY_NOTE =
+ "the hosted ZeroEntropy API is sunset after 2026-09-04; that is liveness of one endpoint, " +
+ "not a sunset of the model";
+
+/**
+ * The checkpoint names read on the day of review: `zerank-2`, `zerank-1`
+ * and `zerank-1-small` as the announcement page names them (the hosted
+ * API ids an operator typed for the endpoint now gone), and the three
+ * repository ids the model cards carry. Listed rather than matched by
+ * prefix, as every survey row is.
+ *
+ * `zerank-2-small` and `zerank-2-nano` are deliberately left unsurveyed:
+ * the page lists them as products, but no open checkpoint for either was
+ * found on review day, so no claim is made about them and the doctor
+ * reports them as `rerank-model-sunset-unsurveyed`.
+ */
+const ZEROENTROPY_CHECKPOINTS: ReadonlyArray<string> = Object.freeze([
+ "zerank-2",
+ "zerank-1",
+ "zerank-1-small",
+ "zeroentropy/zerank-2-reranker",
+ "zeroentropy/zerank-1-reranker",
+ "zeroentropy/zerank-1-small-reranker",
+]);
+
+function zeroEntropyCheckpoint(model: string): EmbeddingSunsetEntry {
+ return { model, sunsetAt: null, source: ZEROENTROPY_SOURCE, note: ZEROENTROPY_NOTE };
+}
+
+/**
+ * The shipped rerank survey. Adding an entry is a one-line edit plus a bump
+ * of `reviewedAt`; every row owes a `source` and a test enforces it.
+ */
+export const RERANK_SUNSET_SURVEY: EmbeddingSunsetSurvey = Object.freeze({
+ reviewedAt: "2026-10-01",
+ entries: Object.freeze([
+ ...COHERE_RERANK_V2_MODELS.map((model) => ({
+ model,
+ sunsetAt: COHERE_RERANK_V2_SHUTDOWN,
+ source: COHERE_RERANK_V2_SOURCE,
+ note: "fine-tuned models created from these base models are not affected, per the same page",
+ })),
+ ...ZEROENTROPY_CHECKPOINTS.map(zeroEntropyCheckpoint),
+ ]),
+});
+
+/** What the rerank survey says about `model` at `nowMs`. */
+export function classifyRerankSunset(
+ model: string | null,
+ nowMs: number,
+ survey: EmbeddingSunsetSurvey = RERANK_SUNSET_SURVEY,
+): EmbeddingSunsetVerdict {
+ return classifyEmbeddingSunset(model, nowMs, survey);
+}
+
+/**
+ * Whether the rerank request is skipped: only an announced date that has
+ * already passed. A future date, a negative, an off-survey model and an
+ * undetermined verdict all keep calling the endpoint.
+ */
+export function rerankSunsetHasPassed(verdict: EmbeddingSunsetVerdict): boolean {
+ return (
+ verdict.state === EMBEDDING_SUNSET.announced &&
+ verdict.days_remaining !== null &&
+ verdict.days_remaining < 0
+ );
+}
diff --git a/src/core/search/retrieval-trail.ts b/src/core/search/retrieval-trail.ts
index 69605eeb..0ed80dc5 100644
--- a/src/core/search/retrieval-trail.ts
+++ b/src/core/search/retrieval-trail.ts
@@ -124,6 +124,24 @@ export const RETRIEVAL_DEGRADATION = Object.freeze({
* cut and were never ranked. `detail.cap` is the cap that bit.
*/
rankCapTruncatedPool: "rank-cap-truncated-pool",
+ /**
+ * The configured cross-encoder rerank (remote endpoint or local model)
+ * could not answer, so the heuristic order was served. `detail.category`
+ * carries the closed `RERANK_FAILURE_CATEGORY` the failure was typed
+ * with (`auth`, `gone`, `transient`, ...; a local model's failure is
+ * `unclassified`); the provider's own message stays in the
+ * `rerank_degraded:` warning. Never cached: the next identical query
+ * asks the reranker again.
+ */
+ rerankProviderUnavailable: "rerank-provider-unavailable",
+ /**
+ * The configured rerank model is past the shutdown date the rerank
+ * sunset survey records for it, so no request was made and the
+ * heuristic order was served. No `detail`: the model name is
+ * configuration, not an identifier the results carry, and the doctor
+ * check names it. Deterministic for the build and the date, so cached.
+ */
+ rerankModelSunset: "rerank-model-sunset",
/**
* The caller's relevance floor dropped ranked rows. `detail.dropped`
* counts them - which is how a floor that removed every hit stops
@@ -167,6 +185,8 @@ export const RETRIEVAL_DEGRADATION_CODES: ReadonlyArray<RetrievalDegradationCode
RETRIEVAL_DEGRADATION.hybridDegraded,
RETRIEVAL_DEGRADATION.hybridDeadlineExceeded,
RETRIEVAL_DEGRADATION.rankCapTruncatedPool,
+ RETRIEVAL_DEGRADATION.rerankProviderUnavailable,
+ RETRIEVAL_DEGRADATION.rerankModelSunset,
RETRIEVAL_DEGRADATION.relevanceFloorDroppedRows,
RETRIEVAL_DEGRADATION.scopeFiltersDroppedRows,
RETRIEVAL_DEGRADATION.crossVaultOriginFailed,
@@ -298,6 +318,10 @@ export function describeRetrievalDegradation(code: RetrievalDegradationCode): st
return "the composite search outlived its wall-clock deadline, so the phases past the budget were cut and this answer is keyword-only";
case RETRIEVAL_DEGRADATION.rankCapTruncatedPool:
return "the rank cap truncated the candidate pool, so lower-ranked matches were never considered";
+ case RETRIEVAL_DEGRADATION.rerankProviderUnavailable:
+ return "the configured reranker could not answer, so this answer keeps the heuristic order";
+ case RETRIEVAL_DEGRADATION.rerankModelSunset:
+ return "the configured rerank model is past its announced shutdown date, so no rerank request was made and this answer keeps the heuristic order";
case RETRIEVAL_DEGRADATION.relevanceFloorDroppedRows:
return "the requested relevance floor dropped every ranked row it judged, so matches below it are not in this answer";
case RETRIEVAL_DEGRADATION.scopeFiltersDroppedRows:
diff --git a/src/core/search/search.ts b/src/core/search/search.ts
index e0d4ede9..5c65665e 100644
--- a/src/core/search/search.ts
+++ b/src/core/search/search.ts
@@ -475,6 +475,7 @@ export async function search(
pool,
structured: shape.structured,
frontmatterCache,
+ nowMs,
...(deadline !== null
? {
signal: deadline.signal,
@@ -483,6 +484,7 @@ export async function search(
: {}),
});
for (const w of postRank.warnings) warnings.push(w);
+ for (const d of postRank.degraded) degraded.push(d);
// The pool the window is cut from (task F). `postRank.results` is the
// last stage that can still add, drop or re-order a candidate, so its
@@ -511,10 +513,16 @@ export async function search(
degraded,
);
- // A decision-model fallback (degraded, inactive or skipped) is the
- // heuristic order under a key that promises the configured one: serve
- // it, but never cache it (the deadline case is `finalize`'s own rule).
- const emit = postRank.decisionFallback === true ? (o: SearchOutcome) => o : finalize;
+ // A decision-model fallback (degraded, inactive or skipped) and a
+ // failed cross-encoder request are both the heuristic order under a
+ // key that promises the reranked one: serve them, but never cache
+ // them, so a transient endpoint failure is retried by the next
+ // identical query (the deadline case is `finalize`'s own rule).
+ const rerankUnavailable = postRank.degraded.some(
+ (d) => d.code === RETRIEVAL_DEGRADATION.rerankProviderUnavailable,
+ );
+ const emit =
+ postRank.decisionFallback === true || rerankUnavailable ? (o: SearchOutcome) => o : finalize;
return emit(
buildSearchOutcome({
store,
diff --git a/src/mcp/argument-guard.ts b/src/mcp/argument-guard.ts
index 3ac35b26..b7a2f116 100644
--- a/src/mcp/argument-guard.ts
+++ b/src/mcp/argument-guard.ts
@@ -34,6 +34,7 @@
import { nearestName } from "../core/text/nearest-name.ts";
import { INVALID_PARAMS, MCPError } from "./protocol.ts";
import type { ToolDefinition } from "./tool-contract.ts";
+import { TOOL_ERROR_CODE } from "./tool-error-codes.ts";
/** One argument the caller sent that the tool never declared. */
export interface UnknownArgument {
@@ -48,6 +49,8 @@ export interface UnknownArgumentData {
readonly unknown_arguments: ReadonlyArray<UnknownArgument>;
/** Every argument the tool does declare, sorted, so the fix is in hand. */
readonly declared_arguments: ReadonlyArray<string>;
+ /** The boundary error code, last, after the members it summarises. */
+ readonly code: typeof TOOL_ERROR_CODE.unknownArgument;
}
/** What the caller is told when no declared name is near enough to name. */
@@ -123,6 +126,7 @@ export function assertKnownArguments(tool: ToolDefinition, args: Record<string,
tool: tool.name,
unknown_arguments: unknown,
declared_arguments: Object.freeze(declared.toSorted()),
+ code: TOOL_ERROR_CODE.unknownArgument,
});
throw new MCPError(INVALID_PARAMS, message, data);
}
diff --git a/src/mcp/brain/admin-tools.ts b/src/mcp/brain/admin-tools.ts
index 407d0117..d994568a 100644
--- a/src/mcp/brain/admin-tools.ts
+++ b/src/mcp/brain/admin-tools.ts
@@ -53,7 +53,7 @@ import { resolveNotePath } from "../../core/brain/note-path.ts";
import type { FrontmatterMap } from "../../core/types.ts";
import { parseFrontmatter } from "../../core/vault.ts";
import { normalizeAgentArgument } from "../../core/agent-identity.ts";
-import { coerceInt, coerceStrList } from "../coerce.ts";
+import { coerceInt, coerceStrList, unknownOperationError } from "../coerce.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { contextReach } from "../tool-contract.ts";
@@ -98,10 +98,7 @@ function toolBrainLabels(
): Record<string, unknown> | Promise<Record<string, unknown>> {
const op = args["operation"];
if (op !== "assign" && op !== "remove" && op !== "show" && op !== "suggest") {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_labels: operation must be assign|remove|show|suggest",
- );
+ throw unknownOperationError("brain_labels: operation must be assign|remove|show|suggest");
}
// a-label-is-not-a-boundary, U12: the ARGUMENT is right and the
// VALIDATOR's message was wrong. `path` is the only name this tool
@@ -176,7 +173,7 @@ async function toolBrainTiers(
): Promise<Record<string, unknown>> {
const op = args["operation"];
if (op !== "check" && op !== "restore" && op !== "accept") {
- throw new MCPError(INVALID_PARAMS, "brain_tiers: operation must be check|restore|accept");
+ throw unknownOperationError("brain_tiers: operation must be check|restore|accept");
}
const searchConfig = resolveSearchConfig({
vault: ctx.vault,
@@ -287,7 +284,7 @@ async function toolBrainSecrets(
): Promise<Record<string, unknown>> {
const op = args["operation"];
if (op !== "list" && op !== "run") {
- throw new MCPError(INVALID_PARAMS, "brain_secrets: operation must be list|run");
+ throw unknownOperationError("brain_secrets: operation must be list|run");
}
if (op === "list") {
return { secrets: listSecrets(ctx.vault) };
@@ -348,7 +345,7 @@ async function toolBrainMaintenance(
): Promise<Record<string, unknown>> {
const op = args["operation"];
if (op !== "run" && op !== "status") {
- throw new MCPError(INVALID_PARAMS, "brain_maintenance: operation must be run|status");
+ throw unknownOperationError("brain_maintenance: operation must be run|status");
}
const now = new Date();
if (op === "status") {
diff --git a/src/mcp/brain/analytics-tools.ts b/src/mcp/brain/analytics-tools.ts
index 6f2af4a3..f5e05afc 100644
--- a/src/mcp/brain/analytics-tools.ts
+++ b/src/mcp/brain/analytics-tools.ts
@@ -34,6 +34,7 @@ import {
localizeEnvelope,
requiredStringArg,
} from "./shared.ts";
+import { unknownOperationError } from "../coerce.ts";
function coerceEventKind(tool: string, raw: unknown): BrainLogEventKind | undefined {
if (raw === undefined || raw === null) return undefined;
@@ -213,8 +214,7 @@ async function toolBrainAttentionFlows(
text: renderAttentionFlow(ctx.vault, flowId),
};
}
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
"brain_analytics view=attention_flows: operation must be one of list|evaluate|render",
);
}
diff --git a/src/mcp/brain/calendar-tools.ts b/src/mcp/brain/calendar-tools.ts
index 196da756..39c5f572 100644
--- a/src/mcp/brain/calendar-tools.ts
+++ b/src/mcp/brain/calendar-tools.ts
@@ -24,7 +24,7 @@ import {
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
-import { coerceStr, coerceStrList } from "../coerce.ts";
+import { coerceStr, coerceStrList, unknownOperationError } from "../coerce.ts";
function pageJson(page: ObligationPage): Record<string, unknown> {
return {
@@ -98,8 +98,7 @@ function toolBrainObligation(
if (err instanceof MCPError) throw err;
throw new MCPError(INVALID_PARAMS, `brain_obligation: ${(err as Error).message}`);
}
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
"brain_obligation operation must be one of: add, done, list, show, remove",
);
}
diff --git a/src/mcp/brain/context-tools.ts b/src/mcp/brain/context-tools.ts
index 5aef4904..7baeb64b 100644
--- a/src/mcp/brain/context-tools.ts
+++ b/src/mcp/brain/context-tools.ts
@@ -29,6 +29,7 @@ import { readVaultInstructionFile } from "../../core/brain/vault-instruction-fil
import { normalizeAgentArgument } from "../../core/agent-identity.ts";
import {
WriteSessionRequestError,
+ type WriteSessionRequestReason,
abandonSession,
approveSession,
openArtifactSession,
@@ -49,9 +50,10 @@ import {
type PinnedOperation,
} from "../../core/brain/pinned.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import { TOOL_ERROR_CODE, type ToolErrorCode } from "../tool-error-codes.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { VAULT_PATH_OUTPUT_SCHEMA, vaultPathField } from "../vault-path-field.ts";
-import { coerceStr, coerceInt } from "../coerce.ts";
+import { coerceStr, coerceInt, unknownOperationError } from "../coerce.ts";
import { vaultRelativeSafe } from "./shared.ts";
/**
@@ -70,7 +72,9 @@ async function toolBrainWriteSession(
const sessionId = coerceStr(args, "session_id", false);
const requireSessionId = (): string => {
if (!sessionId) {
- throw new MCPError(INVALID_PARAMS, `brain_write_session: op '${op}' requires session_id`);
+ throw new MCPError(INVALID_PARAMS, `brain_write_session: op '${op}' requires session_id`, {
+ code: TOOL_ERROR_CODE.sessionIdRequired,
+ });
}
return sessionId;
};
@@ -142,7 +146,9 @@ async function toolBrainWriteSession(
const probe = readWriteSession(ctx.vault, id, new Date().toISOString());
if (probe.error !== null) throw new MCPError(INVALID_PARAMS, probe.error);
if (probe.session === null) {
- throw new MCPError(INVALID_PARAMS, `unknown write-session: ${id}`);
+ throw new MCPError(INVALID_PARAMS, `unknown write-session: ${id}`, {
+ code: WRITE_SESSION_REASON_CODE["unknown-session"],
+ });
}
return asRecord(sessionEnvelope(probe.session));
}
@@ -155,8 +161,7 @@ async function toolBrainWriteSession(
};
}
default:
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
`brain_write_session: op must be open|submit|approve|abandon|status|list, got '${op}'`,
);
}
@@ -165,16 +170,37 @@ async function toolBrainWriteSession(
// Preserve the {code, path, message} boundary contract: the
// structured list rides MCPError's data slot, the message stays
// human-readable prose.
- throw new MCPError(
- INVALID_PARAMS,
- err.message,
- err.errors.length > 0 ? { errors: err.errors } : undefined,
- );
+ throw new MCPError(INVALID_PARAMS, err.message, writeSessionErrorData(err));
}
throw err;
}
}
+/**
+ * The wire code for each session refusal the engine names. Total over the
+ * core union, so a new reason fails the type check until it is mapped.
+ */
+const WRITE_SESSION_REASON_CODE: Readonly<Record<WriteSessionRequestReason, ToolErrorCode>> =
+ Object.freeze({
+ "unknown-session": TOOL_ERROR_CODE.writeSessionUnknown,
+ "terminal-session": TOOL_ERROR_CODE.writeSessionTerminal,
+ });
+
+/**
+ * `data` for a request failure: the structured error list when there is
+ * one, the precise code when the engine named a reason, nothing otherwise
+ * - an absent code is filled by the boundary's `invalid_params` default.
+ */
+function writeSessionErrorData(
+ err: WriteSessionRequestError,
+): Readonly<Record<string, unknown>> | undefined {
+ const data = {
+ ...(err.errors.length > 0 ? { errors: err.errors } : {}),
+ ...(err.reason !== undefined ? { code: WRITE_SESSION_REASON_CODE[err.reason] } : {}),
+ };
+ return Object.keys(data).length > 0 ? data : undefined;
+}
+
function asRecord(envelope: WriteSessionEnvelope): Record<string, unknown> {
return { ...envelope };
}
@@ -191,8 +217,7 @@ function coercePinnedContextOperation(args: Record<string, unknown>): PinnedCont
operation !== "append" &&
operation !== "clear"
) {
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
"brain_pinned_context operation must be one of: read, write, append, clear",
);
}
diff --git a/src/mcp/brain/decisions-tools.ts b/src/mcp/brain/decisions-tools.ts
index 5baefb2e..f2749ee4 100644
--- a/src/mcp/brain/decisions-tools.ts
+++ b/src/mcp/brain/decisions-tools.ts
@@ -24,10 +24,15 @@ import {
updateRating,
DecisionError,
} from "../../core/brain/decisions/record.ts";
-import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
-import { coerceBool, coerceInt, coerceStr, coerceStrList } from "../coerce.ts";
+import {
+ coerceBool,
+ coerceInt,
+ coerceStr,
+ coerceStrList,
+ unknownOperationError,
+} from "../coerce.ts";
import { wrapToolErrors } from "./shared.ts";
import { DECISION_RATING_MAX, DECISION_RATING_MIN } from "../../core/brain/decisions/record.ts";
import { BRAIN_COMMITMENT_TIER, type BrainCommitmentTier } from "../../core/brain/types.ts";
@@ -249,8 +254,7 @@ async function toolBrainDecision(
};
}
default:
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
`${TOOL}: 'action' must be one of record, outcome, rate, show, list, compare, similar, history, recall`,
);
}
diff --git a/src/mcp/brain/feedback-tools.ts b/src/mcp/brain/feedback-tools.ts
index da8b6349..445b3240 100644
--- a/src/mcp/brain/feedback-tools.ts
+++ b/src/mcp/brain/feedback-tools.ts
@@ -77,12 +77,13 @@ import {
import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
+import { codeForError } from "../tool-error-codes.ts";
import {
emitObservedUse,
isObservedUseVerdict,
type ObservedUseEntry,
} from "../../core/brain/observed-use.ts";
-import { coerceStr, coerceBool, coerceIsoDate } from "../coerce.ts";
+import { coerceStr, coerceBool, coerceIsoDate, unknownOperationError } from "../coerce.ts";
import {
enforceCountGuard,
readCountGuardArgs,
@@ -447,8 +448,7 @@ async function toolBrainDream(
action !== "discard" &&
action !== "list"
) {
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
"brain_dream: action must be run|stage|validate|apply|retriage|discard|list",
);
}
@@ -925,13 +925,16 @@ async function toolBrainExpire(
} catch (err) {
// Each of the three is the caller's fault and each has a different
// next move: fix the date, fix the id, or use a surface that takes a
- // path. They keep their own class name as the reported code.
+ // path. They keep their own class name as the reported code, read
+ // from the boundary registry's classification rather than `err.name`.
if (
err instanceof ExpirationValueError ||
err instanceof ExpirationTargetNotFoundError ||
err instanceof InvalidExpirationTargetError
) {
- throw new MCPError(INVALID_PARAMS, `${EXPIRE_TOOL}: ${err.message}`, { code: err.name });
+ throw new MCPError(INVALID_PARAMS, `${EXPIRE_TOOL}: ${err.message}`, {
+ code: codeForError(err),
+ });
}
if (err instanceof MCPError) throw err;
throw new MCPError(
diff --git a/src/mcp/brain/generation-tools.ts b/src/mcp/brain/generation-tools.ts
index b5862e04..0c318e18 100644
--- a/src/mcp/brain/generation-tools.ts
+++ b/src/mcp/brain/generation-tools.ts
@@ -33,6 +33,7 @@ import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { vaultPathField } from "../vault-path-field.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
import { coercePositiveInteger, optionalStringArg, requiredStringArg } from "./shared.ts";
+import { unknownOperationError } from "../coerce.ts";
const TOOL = "brain_generation_reports";
@@ -49,7 +50,7 @@ async function toolBrainGenerationReports(
if (action === "summary") {
return { ...summarizeGenerationReports(ctx.vault, readFilter(args)) };
}
- throw new MCPError(INVALID_PARAMS, `${TOOL}: action must be record, list, or summary`);
+ throw unknownOperationError(`${TOOL}: action must be record, list, or summary`);
}
function recordAction(ctx: ServerContext, args: Record<string, unknown>): Record<string, unknown> {
diff --git a/src/mcp/brain/knowledge-tools.ts b/src/mcp/brain/knowledge-tools.ts
index c725dd89..4cd2dd9b 100644
--- a/src/mcp/brain/knowledge-tools.ts
+++ b/src/mcp/brain/knowledge-tools.ts
@@ -68,7 +68,13 @@ import { contextReach } from "../tool-contract.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { vaultPathField } from "../vault-path-field.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
-import { AGENT_SCOPE_SCHEMA, coerceAgentScope, coerceStr, coerceBool } from "../coerce.ts";
+import {
+ AGENT_SCOPE_SCHEMA,
+ coerceAgentScope,
+ coerceStr,
+ coerceBool,
+ unknownOperationError,
+} from "../coerce.ts";
import { coercePositiveInteger, toolSafeguard } from "./shared.ts";
/**
@@ -115,10 +121,7 @@ async function toolBrainBridges(
): Promise<Record<string, unknown>> {
const op = args["operation"];
if (op !== "discover" && op !== "list" && op !== "accept" && op !== "dismiss") {
- throw new MCPError(
- INVALID_PARAMS,
- "brain_bridges: operation must be discover|list|accept|dismiss",
- );
+ throw unknownOperationError("brain_bridges: operation must be discover|list|accept|dismiss");
}
if (op === "accept" || op === "dismiss") {
const source = args["source"];
@@ -250,7 +253,7 @@ async function toolBrainClusters(
): Promise<Record<string, unknown>> {
const op = args["operation"];
if (op !== "run" && op !== "list") {
- throw new MCPError(INVALID_PARAMS, "brain_clusters: operation must be run|list");
+ throw unknownOperationError("brain_clusters: operation must be run|list");
}
if (op === "list") {
const dir = join(ctx.vault, BRAIN_CLUSTERS_REL);
@@ -580,8 +583,7 @@ function toolBrainTruth(
op !== "aggregate" &&
op !== "collisions"
) {
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
"brain_truth: operation must be ingest|slots|conflicts|aggregate|collisions",
);
}
@@ -675,7 +677,7 @@ function toolBrainDeadEnds(
): Record<string, unknown> {
const op = args["operation"];
if (op !== "record" && op !== "list") {
- throw new MCPError(INVALID_PARAMS, "brain_dead_ends: operation must be record|list");
+ throw unknownOperationError("brain_dead_ends: operation must be record|list");
}
if (op === "list") {
const { entries, warnings } = listDeadEnds(ctx.vault);
@@ -803,8 +805,7 @@ function toolBrainClaims(
return { operation, count: rows.length, claims: rows.map(renderClaimNode) };
}
default:
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
"brain_claims: 'operation' must be one of current, at, history, replaced, contests, rebuild",
);
}
diff --git a/src/mcp/brain/lifecycle-file-tools.ts b/src/mcp/brain/lifecycle-file-tools.ts
index 1b07b0b4..6820b1fe 100644
--- a/src/mcp/brain/lifecycle-file-tools.ts
+++ b/src/mcp/brain/lifecycle-file-tools.ts
@@ -43,15 +43,13 @@ import {
} from "../../core/brain/notes/create-note.ts";
import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+import { COUNT_GUARD_WIRE_CODE, TOOL_ERROR_CODE } from "../tool-error-codes.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
-import { coerceBoolOptional, coerceStr } from "../coerce.ts";
+import { coerceBoolOptional, coerceStr, unknownOperationError } from "../coerce.ts";
import { coerceNonNegativeInteger, readCountGuardArgs } from "./shared.ts";
const TOOL = "brain_note_lifecycle";
-/** The `data.code` a count-guard refusal reports itself under. */
-const COUNT_GUARD_CODE = "count_guard";
-
/** Project the frozen core result into the tool's snake_cased response. */
function renderResult(res: NoteLifecycleResult): Record<string, unknown> {
return {
@@ -113,8 +111,7 @@ async function toolBrainNoteLifecycle(
// Refused rather than defaulted: a caller that asked for a
// disposition this tool does not have must never be told its request
// succeeded under a different one.
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
`${TOOL}: 'action' must be one of ${NOTE_LIFECYCLE_ACTIONS.join(", ")}`,
);
}
@@ -150,7 +147,7 @@ async function toolBrainNoteLifecycle(
}
if (err instanceof CountGuardError) {
throw new MCPError(INVALID_PARAMS, `${TOOL}: ${err.message}`, {
- code: COUNT_GUARD_CODE,
+ code: COUNT_GUARD_WIRE_CODE,
matched: err.matched,
expected: err.expected,
});
@@ -222,9 +219,6 @@ const STUB_ACTION_ARGUMENTS: Readonly<Record<StubScaffoldAction, ReadonlyArray<s
]),
});
-/** The `data.code` an action-incompatible argument is refused under. */
-const ARGUMENT_FORBIDDEN_CODE = "argument_forbidden";
-
/**
* Refuse every argument that belongs to the OTHER action. `action`
* itself is the dispatch key and belongs to both; anything the schema
@@ -247,7 +241,7 @@ function assertArgumentsMatchAction(
INVALID_PARAMS,
`${STUB_TOOL}: action=${action} takes none of ${foreign.join(", ")}; ` +
`it reads ${mine.join(", ")}`,
- { code: ARGUMENT_FORBIDDEN_CODE, action, forbidden: foreign, accepted: [...mine] },
+ { code: TOOL_ERROR_CODE.argumentForbidden, action, forbidden: foreign, accepted: [...mine] },
);
}
@@ -267,8 +261,7 @@ async function toolBrainScaffoldStub(
): Promise<Record<string, unknown>> {
const action = coerceStr(args, "action", true)!;
if (!isStubScaffoldAction(action)) {
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
`${STUB_TOOL}: 'action' must be one of ${STUB_SCAFFOLD_ACTIONS.join(", ")}`,
);
}
diff --git a/src/mcp/brain/lifecycle-tools.ts b/src/mcp/brain/lifecycle-tools.ts
index e88682c2..bf1a8cd5 100644
--- a/src/mcp/brain/lifecycle-tools.ts
+++ b/src/mcp/brain/lifecycle-tools.ts
@@ -24,10 +24,9 @@ import {
tombstone,
TombstoneError,
} from "../../core/brain/lifecycle/tombstone.ts";
-import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
-import { coerceStr } from "../coerce.ts";
+import { coerceStr, unknownOperationError } from "../coerce.ts";
import { coerceNonNegativeInteger, wrapToolErrors } from "./shared.ts";
const TOOL = "brain_lifecycle";
@@ -134,8 +133,7 @@ async function toolBrainLifecycle(
};
}
default:
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
`${TOOL}: 'action' must be one of tombstone, supersede, temporal-replace, tip, curator`,
);
}
diff --git a/src/mcp/brain/notes-tools.ts b/src/mcp/brain/notes-tools.ts
index 8dd6cca8..c77e5052 100644
--- a/src/mcp/brain/notes-tools.ts
+++ b/src/mcp/brain/notes-tools.ts
@@ -49,7 +49,7 @@ import {
import { WRITE_BINDING_REFUSED_CODE } from "../../core/write-binding/index.ts";
import { isFrontmatterKey } from "../../core/vault.ts";
import { rethrowVaultFrozen } from "../frozen-refusal.ts";
-import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";
+import { INTERNAL_ERROR, INVALID_PARAMS, type JsonRpcErrorCode, MCPError } from "../protocol.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { coerceBoolOptional, coerceStr, coerceStringOptional } from "../coerce.ts";
@@ -111,7 +111,7 @@ const OPERATOR_FAULT_CODES: ReadonlySet<string> = new Set([
]);
/** JSON-RPC code for a refusal, split on whose fault the refusal is. */
-function rpcCodeFor(surfaceCode: string): number {
+function rpcCodeFor(surfaceCode: string): JsonRpcErrorCode {
return OPERATOR_FAULT_CODES.has(surfaceCode) ? INTERNAL_ERROR : INVALID_PARAMS;
}
diff --git a/src/mcp/brain/pack-tools.ts b/src/mcp/brain/pack-tools.ts
index cc7b2844..103bb720 100644
--- a/src/mcp/brain/pack-tools.ts
+++ b/src/mcp/brain/pack-tools.ts
@@ -76,6 +76,7 @@ import {
coerceStrList,
coerceBool,
recallAdequacyPairing,
+ unknownOperationError,
} from "../coerce.ts";
import { decisionAnswerableFor } from "../decision-answerable.ts";
import {
@@ -381,10 +382,7 @@ async function toolBrainContextReceipts(
if (operation === "summary") return summarizeReceipts(ctx, args);
- throw new MCPError(
- INVALID_PARAMS,
- "brain_context_receipts: operation must be list, show, or summary",
- );
+ throw unknownOperationError("brain_context_receipts: operation must be list, show, or summary");
}
/**
@@ -608,10 +606,7 @@ async function toolBrainContextPresets(
...diffContextPreset(presetId, contextPresetCurrentConfig(args["current"])),
};
}
- throw new MCPError(
- INVALID_PARAMS,
- "brain_context_presets: operation must be show, suggest, or diff",
- );
+ throw unknownOperationError("brain_context_presets: operation must be show, suggest, or diff");
}
function contextPresetCurrentConfig(raw: unknown): ContextPresetCurrentConfig {
diff --git a/src/mcp/brain/procedure-tools.ts b/src/mcp/brain/procedure-tools.ts
index 51d674cc..db3656be 100644
--- a/src/mcp/brain/procedure-tools.ts
+++ b/src/mcp/brain/procedure-tools.ts
@@ -39,7 +39,7 @@ import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import { contextReach } from "../tool-contract.ts";
import { reachView } from "../../core/brain/reach-view.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
-import { coerceStrList } from "../coerce.ts";
+import { coerceStrList, unknownOperationError } from "../coerce.ts";
import { coercePositiveInteger, optionalStringArg, requiredStringArg } from "./shared.ts";
async function toolBrainSkillProposals(
@@ -159,8 +159,7 @@ async function toolBrainSkillProposals(
const usage = deriveSkillUsage(ctx.vault);
return { total: usage.length, usage };
}
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
"brain_skill_proposals: operation must be one of " +
"learn|list|accept|reject|recover|usage|evidence|page_candidates|page_draft",
);
@@ -235,8 +234,7 @@ async function toolBrainProceduralMemory(
}
return { ...updated };
}
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
"brain_procedural_memory: operation must be one of reconcile|list|mark_used|mark_outcome",
);
}
@@ -275,8 +273,7 @@ async function toolBrainRecurrence(
purgeRecurrenceSource(ctx.vault, sourceId);
return { ok: true, source_id: sourceId };
}
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
"brain_recurrence: operation must be one of list|show|learn|forget|purge_source",
);
}
@@ -316,8 +313,7 @@ async function toolBrainProceduralGraph(
}
return { ...hints };
}
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
"brain_procedural_graph: operation must be one of rebuild|show|hints",
);
}
diff --git a/src/mcp/brain/query-tools.ts b/src/mcp/brain/query-tools.ts
index c6068eca..5cea603b 100644
--- a/src/mcp/brain/query-tools.ts
+++ b/src/mcp/brain/query-tools.ts
@@ -57,6 +57,7 @@ import {
coerceFormat,
coerceInt,
coerceStringOptional,
+ unknownOperationError,
} from "../coerce.ts";
import { emitGatedTelemetry } from "../../core/brain/continuity/emit.ts";
import {
@@ -330,8 +331,7 @@ async function toolBrainWrites(
return planRevert(ctx, args);
}
if (action !== BRAIN_WRITES_ACTION.list) {
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
`brain_writes: 'action' must be one of ${BRAIN_WRITES_ACTIONS.join(", ")}`,
);
}
diff --git a/src/mcp/brain/recall-tools.ts b/src/mcp/brain/recall-tools.ts
index 89ba9a3c..9d04300d 100644
--- a/src/mcp/brain/recall-tools.ts
+++ b/src/mcp/brain/recall-tools.ts
@@ -82,12 +82,13 @@ import {
} from "../../core/brain/payload-registry.ts";
import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import { searchErrorData } from "../search-tools.ts";
import { contextReach } from "../tool-contract.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { vaultPathField } from "../vault-path-field.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
import { coercePositiveInteger, optionalStringArg, requiredStringArg } from "./shared.ts";
-import { AGENT_SCOPE_SCHEMA, coerceAgentScope } from "../coerce.ts";
+import { AGENT_SCOPE_SCHEMA, coerceAgentScope, unknownOperationError } from "../coerce.ts";
/** Recall-quality benchmark over an inline dataset. */
async function toolBrainBenchmark(
@@ -96,7 +97,7 @@ async function toolBrainBenchmark(
): Promise<Record<string, unknown>> {
const op = args["operation"];
if (op !== "run") {
- throw new MCPError(INVALID_PARAMS, "brain_benchmark: operation must be run");
+ throw unknownOperationError("brain_benchmark: operation must be run");
}
const k = args["k"];
if (k !== undefined && (!Number.isInteger(k) || (k as number) < 1)) {
@@ -156,7 +157,7 @@ async function toolBrainTune(
): Promise<Record<string, unknown>> {
const op = args["operation"];
if (op !== "run" && op !== "status" && op !== "reset") {
- throw new MCPError(INVALID_PARAMS, "brain_tune: operation must be run|status|reset");
+ throw unknownOperationError("brain_tune: operation must be run|status|reset");
}
const searchConfig = resolveSearchConfig({
vault: ctx.vault,
@@ -287,8 +288,7 @@ async function toolBrainRecallTelemetry(
});
return { vault_path: vaultPathField(ctx), ...meter };
}
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
"brain_recall_telemetry: operation must be list, summary, gate_list, gate_summary, observed_reuse, or cost",
);
}
@@ -379,7 +379,7 @@ async function toolBrainRouteMetrics(
const summary = summarizeMcpRouteLatency(ctx.vault, filter);
return { vault_path: vaultPathField(ctx), ...summary };
}
- throw new MCPError(INVALID_PARAMS, "brain_route_metrics: operation must be list or summary");
+ throw unknownOperationError("brain_route_metrics: operation must be list or summary");
}
// ----- brain_retrieval_plan (shadow-only retrieval advisor, t_3ffb021c) -----
@@ -535,8 +535,7 @@ async function toolBrainTokenImpact(
if (operation === "summary") {
return { vault_path: vaultPathField(ctx), ...summarizeTokenImpact(ctx.vault, filter) };
}
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
"brain_token_impact: operation must be record, outcome, list, or summary",
);
}
@@ -747,8 +746,7 @@ async function toolBrainContextPackOutcome(
if (operation === "summary") {
return { vault_path: vaultPathField(ctx), ...summarizeContextPackOutcomes(ctx.vault, filter) };
}
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
"brain_context_pack_outcome: operation must be post, list, or summary",
);
}
@@ -956,7 +954,9 @@ function resolveSessionGrepBounds(
Date.now(),
);
} catch (exc) {
- if (exc instanceof SearchError) throw new MCPError(INVALID_PARAMS, exc.message);
+ if (exc instanceof SearchError) {
+ throw new MCPError(INVALID_PARAMS, exc.message, searchErrorData(exc));
+ }
throw exc;
}
}
diff --git a/src/mcp/brain/synthesis-tools.ts b/src/mcp/brain/synthesis-tools.ts
index c9fcf66e..730bdaa3 100644
--- a/src/mcp/brain/synthesis-tools.ts
+++ b/src/mcp/brain/synthesis-tools.ts
@@ -29,7 +29,7 @@ import {
type IdeaLineageResult,
} from "../../core/brain/idea-lineage.ts";
import { decomposeNoteHistory } from "../../core/brain/note-history.ts";
-import { coerceStringOptional } from "../coerce.ts";
+import { coerceStringOptional, unknownOperationError } from "../coerce.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";
import { contextReach, type ServerContext, type ToolDefinition } from "../tool-contract.ts";
@@ -89,7 +89,7 @@ async function toolBrainSessionSummary(
): Promise<Record<string, unknown>> {
const operation = args["operation"];
if (operation !== "write" && operation !== "get" && operation !== "list") {
- throw new MCPError(INVALID_PARAMS, `${SUMMARY_TOOL}: operation must be write|get|list`);
+ throw unknownOperationError(`${SUMMARY_TOOL}: operation must be write|get|list`);
}
if (operation === "write") {
diff --git a/src/mcp/brain/tension-tools.ts b/src/mcp/brain/tension-tools.ts
index 87d45b89..a19763cb 100644
--- a/src/mcp/brain/tension-tools.ts
+++ b/src/mcp/brain/tension-tools.ts
@@ -33,7 +33,7 @@ import { verdictFields } from "../../core/decision-model/pair-verdict.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
-import { coerceBool, coerceStr } from "../coerce.ts";
+import { coerceBool, coerceStr, unknownOperationError } from "../coerce.ts";
import { wrapToolErrors } from "./shared.ts";
const TOOL = "brain_tension";
@@ -145,8 +145,7 @@ async function toolBrainTension(
};
}
default:
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
`${TOOL}: 'action' must be one of detect, list, show, confirm, dismiss, resolve, verify`,
);
}
diff --git a/src/mcp/brain/workspace-tools.ts b/src/mcp/brain/workspace-tools.ts
index be86f0d0..74021c6f 100644
--- a/src/mcp/brain/workspace-tools.ts
+++ b/src/mcp/brain/workspace-tools.ts
@@ -32,9 +32,10 @@ import {
showIntention,
} from "../../core/brain/intentions.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import { TOOL_ERROR_CODE } from "../tool-error-codes.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
-import { coerceStr } from "../coerce.ts";
+import { coerceStr, unknownOperationError } from "../coerce.ts";
function toolBrainIntention(
ctx: ServerContext,
@@ -79,10 +80,7 @@ function toolBrainIntention(
const moved = moveIntentionToHistory(ctx.vault, { scope });
return { operation, scope: moved.scope, archive_path: moved.archivePath };
}
- throw new MCPError(
- INVALID_PARAMS,
- "brain_intention operation must be one of: set, show, list, move",
- );
+ throw unknownOperationError("brain_intention operation must be one of: set, show, list, move");
}
// ----- brain_trigger (Workspace Insight Suite) ------------------------------
@@ -187,7 +185,9 @@ function toolBrainTrigger(
if (operation === "list" || operation === "history") {
const statusRaw = coerceStr(args, "status", false);
if (statusRaw !== null && statusRaw !== undefined && !isTriggerStatus(statusRaw)) {
- throw new MCPError(INVALID_PARAMS, `brain_trigger: unknown status '${statusRaw}'`);
+ throw new MCPError(INVALID_PARAMS, `brain_trigger: unknown status '${statusRaw}'`, {
+ code: TOOL_ERROR_CODE.invalidStatus,
+ });
}
const scan = readTriggers(ctx.vault, {
now,
@@ -225,11 +225,14 @@ function toolBrainTrigger(
trigger: triggerToJson(transitionTrigger(ctx.vault, id, operation, { now })),
};
} catch (err) {
- throw new MCPError(INVALID_PARAMS, `brain_trigger: ${(err as Error).message}`);
+ // One code for the whole transition refusal: a separate code for
+ // "absent" would split exactly what the shared message keeps together.
+ throw new MCPError(INVALID_PARAMS, `brain_trigger: ${(err as Error).message}`, {
+ code: TOOL_ERROR_CODE.triggerTransitionRefused,
+ });
}
}
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
`brain_trigger operation must be one of: ${TRIGGER_OPERATIONS.join(", ")}`,
);
}
diff --git a/src/mcp/brain/write-batch-tools.ts b/src/mcp/brain/write-batch-tools.ts
index 6e68afd0..2a083564 100644
--- a/src/mcp/brain/write-batch-tools.ts
+++ b/src/mcp/brain/write-batch-tools.ts
@@ -35,6 +35,7 @@ import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { noteWriteResult, parseFrontmatterArg, writeBatchErrorToMcp } from "./notes-tools.ts";
import { vaultRelativeSafe } from "./shared.ts";
+import { unknownOperationError } from "../coerce.ts";
/** Recognised batch operation discriminators. */
const OP_KINDS = [
@@ -147,8 +148,7 @@ function mapOperation(
},
};
default:
- throw new MCPError(
- INVALID_PARAMS,
+ throw unknownOperationError(
`brain_write_batch: operations[${index}].op must be one of ${OP_KINDS.join(", ")}`,
);
}
diff --git a/src/mcp/coerce.ts b/src/mcp/coerce.ts
index 7e7420fd..1a19848f 100644
--- a/src/mcp/coerce.ts
+++ b/src/mcp/coerce.ts
@@ -8,6 +8,7 @@
import { refuseOwnerScopeRequest } from "./owner-scope-refusal.ts";
import { INVALID_PARAMS, MCPError } from "./protocol.ts";
+import { TOOL_ERROR_CODE } from "./tool-error-codes.ts";
export function coerceStr(
args: Record<string, unknown>,
@@ -136,7 +137,11 @@ export function coerceAgentScope(
requested: explicit,
identity: ctx.agentName,
});
- if (refused !== null) throw new MCPError(INVALID_PARAMS, refused.message);
+ // The refusal token is the boundary code: already a registered member,
+ // already named in the message, so the wire carries one spelling.
+ if (refused !== null) {
+ throw new MCPError(INVALID_PARAMS, refused.message, { code: refused.refusal });
+ }
return explicit;
}
@@ -354,3 +359,14 @@ export function coerceFormat(args: Record<string, unknown>, key = "format"): "ma
}
return raw;
}
+
+/**
+ * The refusal every operation-dispatching tool answers when the argument
+ * that selects its operation (`operation`, `op` or `action`) names none
+ * of the tool's closed set. One builder, so the `unknown_operation` code
+ * is a contract of every such tool rather than of the few that set it;
+ * the message stays the tool's own.
+ */
+export function unknownOperationError(message: string): MCPError {
+ return new MCPError(INVALID_PARAMS, message, { code: TOOL_ERROR_CODE.unknownOperation });
+}
diff --git a/src/mcp/http.ts b/src/mcp/http.ts
index 13b70a32..815c5890 100644
--- a/src/mcp/http.ts
+++ b/src/mcp/http.ts
@@ -25,8 +25,8 @@ import type { Socket } from "node:net";
import type { Writable } from "node:stream";
import { MCPServer, type MCPServerOptions, type MCPServerRuntimeOptions } from "./server.ts";
-import { errorResponse, type JsonRpcResponse } from "./server.ts";
-import { INTERNAL_ERROR, INVALID_REQUEST, PARSE_ERROR } from "./protocol.ts";
+import { errorResponse, internalErrorResponse, type JsonRpcResponse } from "./server.ts";
+import { INVALID_REQUEST, PARSE_ERROR } from "./protocol.ts";
import { DRAIN_STATE, RequestDrain, resolveDrainDeadlineMs, type DrainOutcome } from "./drain.ts";
import { ORIGIN_CHANNEL, setOriginChannel } from "../core/origin-channel.ts";
import { TRANSPORT_REACH, type TransportReach } from "../core/graph/transport-reach.ts";
@@ -141,8 +141,12 @@ export async function startHttp(
// the socket open with no response on it and no record anywhere;
// the client waited until its own timeout for a request the server
// had already given up on.
+ // The dispatcher's own INTERNAL_ERROR builder, so the same handling:
+ // the prose goes through the redactor for this bind's reach, and
+ // the code comes from the classifier, which names the class on
+ // stderr when it does not know it.
if (!res.headersSent) {
- writeJson(res, errorResponse(null, INTERNAL_ERROR, (exc as Error).message));
+ writeJson(res, internalErrorResponse(null, exc, mcp.vault, mcp.reach));
} else {
res.end();
}
diff --git a/src/mcp/output-contract.ts b/src/mcp/output-contract.ts
index ed029a52..833bcd05 100644
--- a/src/mcp/output-contract.ts
+++ b/src/mcp/output-contract.ts
@@ -29,6 +29,26 @@ export function validateOutputContract(
return checkResponseShape(schema, value, path).map(formatShapeViolation);
}
+/**
+ * A tool's result did not match the output schema it declares. Named so
+ * the boundary classifies it as `output_contract_failed` by class rather
+ * than by its message; the message is the one the contract has always
+ * reported.
+ */
+export class OutputContractError extends Error {
+ /** The tool whose result broke its contract. */
+ readonly toolName: string;
+ /** The `<path>: <detail>` violation lines. */
+ readonly violations: ReadonlyArray<string>;
+
+ constructor(toolName: string, violations: ReadonlyArray<string>) {
+ super(`${toolName} output contract failed: ${violations.join("; ")}`);
+ this.name = "OutputContractError";
+ this.toolName = toolName;
+ this.violations = Object.freeze([...violations]);
+ }
+}
+
export function assertOutputContract(
toolName: string,
schema: OutputSchema | undefined,
@@ -37,6 +57,6 @@ export function assertOutputContract(
if (!schema) return;
const errors = validateOutputContract(schema, value);
if (errors.length > 0) {
- throw new Error(`${toolName} output contract failed: ${errors.join("; ")}`);
+ throw new OutputContractError(toolName, errors);
}
}
diff --git a/src/mcp/progress.ts b/src/mcp/progress.ts
index 46da79a5..2c407df5 100644
--- a/src/mcp/progress.ts
+++ b/src/mcp/progress.ts
@@ -52,6 +52,12 @@ export const PROGRESS_NOTIFICATION_METHOD = "notifications/progress";
*/
export const PROGRESS_META_KEY = "open-second-brain/progress";
+/**
+ * The member of a `tools/call` request's params and of its result that
+ * namespaced extensions ride on.
+ */
+export const META_MEMBER = "_meta";
+
/**
* What the MCP specification allows a progress token to be: a string or
* an integer. Deliberately not `number` - a fractional token is a client
@@ -95,7 +101,7 @@ function describeValue(value: unknown): string {
* not errors.
*/
export function readProgressToken(params: Record<string, unknown>): ProgressToken | undefined {
- const meta = params["_meta"];
+ const meta = params[META_MEMBER];
if (meta === undefined) return undefined;
if (typeof meta !== "object" || meta === null || Array.isArray(meta)) {
throw new MCPError(
@@ -165,7 +171,8 @@ export function progressRefusal(token: ProgressToken, reason: ProgressReason): P
}
/**
- * Attach a refusal to a `tools/call` result. With no refusal the result
+ * Attach a refusal to a `tools/call` result, merged into any `_meta` the
+ * result already carries (an error result's code, for one). With no refusal the result
* is returned untouched - not cloned with an empty `_meta` - so a call
* that asked for no progress is byte-identical to the one the previous
* release answered.
@@ -175,5 +182,6 @@ export function withProgressRefusal(
refusal: ProgressRefusal | undefined,
): Record<string, unknown> {
if (refusal === undefined) return result;
- return { ...result, _meta: { [PROGRESS_META_KEY]: refusal } };
+ const existing = result[META_MEMBER] as Readonly<Record<string, unknown>> | undefined;
+ return { ...result, [META_MEMBER]: { ...existing, [PROGRESS_META_KEY]: refusal } };
}
diff --git a/src/mcp/protocol.ts b/src/mcp/protocol.ts
index 7cb12e33..7024424f 100644
--- a/src/mcp/protocol.ts
+++ b/src/mcp/protocol.ts
@@ -19,6 +19,18 @@ export const METHOD_NOT_FOUND = -32601;
export const INVALID_PARAMS = -32602;
export const INTERNAL_ERROR = -32603;
+/**
+ * The closed set of JSON-RPC error codes this server answers with. Every
+ * error response is built from one of these, so the boundary registry can
+ * map each to a stable string code with a total table and no fallback.
+ */
+export type JsonRpcErrorCode =
+ | typeof PARSE_ERROR
+ | typeof INVALID_REQUEST
+ | typeof METHOD_NOT_FOUND
+ | typeof INVALID_PARAMS
+ | typeof INTERNAL_ERROR;
+
/**
* A frame the server writes without having been asked for it, addressed
* to no request id.
@@ -35,11 +47,35 @@ export interface JsonRpcNotification {
readonly params?: unknown;
}
+/**
+ * What an {@link MCPError} may carry as `data`: an object or nothing. The
+ * single builder `errorResponse` merges the stable string code into it,
+ * and a primitive payload would leave it no member to merge into. It is
+ * `object` rather than a `Record` so the named payload interfaces the
+ * refusal modules declare (argument guard, reach refusal, frozen vault)
+ * are accepted without an index signature; every site passes a record.
+ *
+ * `object` also admits an array, which the merge would turn into numbered
+ * keys, so the {@link MCPError} constructor refuses one by name. A `code`
+ * member that is not a string is replaced by the JSON-RPC default.
+ */
+export type MCPErrorData = object;
+
+/** An {@link MCPError} was built with an array as its `data`. */
+export class MCPErrorDataArrayError extends TypeError {
+ constructor() {
+ super("MCPError data must be a record, not an array: wrap the list in a named member");
+ this.name = "MCPErrorDataArrayError";
+ }
+}
+
+/** A JSON-RPC error a handler throws, answered through `errorResponse`. */
export class MCPError extends Error {
- readonly code: number;
- readonly data: unknown;
+ readonly code: JsonRpcErrorCode;
+ readonly data: MCPErrorData | undefined;
- constructor(code: number, message: string, data?: unknown) {
+ constructor(code: JsonRpcErrorCode, message: string, data?: MCPErrorData) {
+ if (Array.isArray(data)) throw new MCPErrorDataArrayError();
super(message);
this.name = "MCPError";
this.code = code;
diff --git a/src/mcp/reach-refusal.ts b/src/mcp/reach-refusal.ts
index 3fb91bf7..c37e6ad9 100644
--- a/src/mcp/reach-refusal.ts
+++ b/src/mcp/reach-refusal.ts
@@ -60,6 +60,11 @@ export interface CallerSuppliedReachData {
/** The caller's own spellings, in the caller's own key order. */
readonly refused_arguments: ReadonlyArray<string>;
readonly reserved_argument_names: ReadonlyArray<string>;
+ /**
+ * The boundary error code: the refusal token itself, already named in
+ * the message, so the wire carries one spelling rather than two.
+ */
+ readonly code: typeof REACH_REFUSAL;
}
/**
@@ -101,6 +106,7 @@ export function assertNoCallerSuppliedReach(
tool: tool.name,
refused_arguments: refused,
reserved_argument_names: RESERVED_REACH_ARGUMENTS,
+ code: REACH_REFUSAL,
});
throw new MCPError(INVALID_PARAMS, message, data);
}
diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.ts
index 8e8a345d..619fc61d 100644
--- a/src/mcp/search-tools.ts
+++ b/src/mcp/search-tools.ts
@@ -50,6 +50,7 @@ import {
} from "../core/search/retrieval-trail.ts";
import { probeRetrievalCorpus } from "../core/search/pipeline/outcome.ts";
import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";
+import type { ToolErrorCode } from "./tool-error-codes.ts";
import { contextReach } from "./tool-contract.ts";
import type { ServerContext, ToolDefinition } from "./tool-contract.ts";
import {
@@ -860,30 +861,48 @@ function windowContent(c: string, query: string, max: number): string {
return markWindow(body, start, hasMore, ELLIPSIS);
}
+/**
+ * The structured `data` every mapped {@link SearchError} carries: its own
+ * code, verbatim. `SEARCH_ERROR_CODES` is imported into the boundary
+ * registry unchanged, so the UPPER token is already a registered wire code
+ * and no second spelling is minted for it.
+ */
+export function searchErrorData(e: SearchError): { readonly code: ToolErrorCode } {
+ return { code: e.code };
+}
+
export function searchErrorToMcp(e: SearchError): MCPError {
- if (e.code === "INVALID_INPUT") return new MCPError(INVALID_PARAMS, e.message);
+ const data = searchErrorData(e);
+ if (e.code === "INVALID_INPUT") return new MCPError(INVALID_PARAMS, e.message, data);
if (e.code === "EMBEDDING_QUOTA_EXHAUSTED") {
- return new MCPError(INTERNAL_ERROR, EMBEDDING_QUOTA_MESSAGE);
+ return new MCPError(INTERNAL_ERROR, EMBEDDING_QUOTA_MESSAGE, data);
}
if (e.code === "INDEX_MISSING") {
- return new MCPError(INTERNAL_ERROR, "search index not initialised. Run: o2b search index");
+ return new MCPError(
+ INTERNAL_ERROR,
+ "search index not initialised. Run: o2b search index",
+ data,
+ );
}
if (e.code === "INDEX_UNREADABLE") {
- return new MCPError(INTERNAL_ERROR, `search index unreadable: ${e.message}`);
+ return new MCPError(INTERNAL_ERROR, `search index unreadable: ${e.message}`, data);
}
if (e.code === "VEC_EXTENSION_UNAVAILABLE") {
return new MCPError(
INTERNAL_ERROR,
"semantic search unavailable: sqlite-vec extension not loaded",
+ data,
);
}
if (e.code === "EMBEDDING_KEY_MISSING") {
- return new MCPError(INTERNAL_ERROR, "embedding key not configured");
+ return new MCPError(INTERNAL_ERROR, "embedding key not configured", data);
}
if (e.code === "EMBEDDING_PROVIDER_HTTP" || e.code === "EMBEDDING_PROVIDER_TIMEOUT") {
- return new MCPError(INTERNAL_ERROR, `embedding provider unavailable: ${e.message}`);
+ return new MCPError(INTERNAL_ERROR, `embedding provider unavailable: ${e.message}`, data);
}
- return new MCPError(INTERNAL_ERROR, `${e.message} [${e.code}]`);
+ // The `[CODE]` suffix predates `data.code` and stays as legacy text:
+ // callers that parsed it before this release keep working.
+ return new MCPError(INTERNAL_ERROR, `${e.message} [${e.code}]`, data);
}
async function toolBrainSearch(
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 8fb0bd6d..44e79e33 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -27,8 +27,18 @@ import {
SERVER_NAME,
SERVER_VERSION,
} from "./protocol.ts";
-import type { JsonRpcNotification } from "./protocol.ts";
+import type { JsonRpcErrorCode, JsonRpcNotification, MCPErrorData } from "./protocol.ts";
import {
+ codeForError,
+ isToolErrorCode,
+ defaultCodeForRpc,
+ TOOL_ERROR_META_KEY,
+ toolErrorMeta,
+ type ToolErrorCode,
+} from "./tool-error-codes.ts";
+import {
+ META_MEMBER,
+ PROGRESS_META_KEY,
progressRefusal,
progressSink,
readProgressToken,
@@ -121,9 +131,23 @@ export interface JsonRpcResponse {
readonly jsonrpc: string;
readonly id: unknown;
readonly result?: unknown;
- readonly error?: { code: number; message: string; data?: unknown };
+ readonly error?: JsonRpcErrorBody;
+}
+
+/**
+ * The `error` member of a JSON-RPC answer. `data` is always present and
+ * always carries the string code, because {@link errorResponse} is the
+ * one builder and adds it when the thrower did not.
+ */
+export interface JsonRpcErrorBody {
+ readonly code: JsonRpcErrorCode;
+ readonly message: string;
+ readonly data: JsonRpcErrorData;
}
+/** `error.data`: the thrower's record plus the stable string code. */
+export type JsonRpcErrorData = MCPErrorData & { readonly code: string };
+
export class MCPServer {
readonly vault: string;
readonly configPath: string | null;
@@ -365,9 +389,7 @@ export class MCPServer {
// through the redactor - at remote reach with the vault, home and
// temp roots replaced too: a caller probing with traversal paths
// learns that a file is missing, not the host layout behind it.
- const raw = (exc as Error).message ?? String(exc);
- const message = redactErrorForCaller(raw, this.vault, this.reach);
- return errorResponse(requestId, INTERNAL_ERROR, `internal error: ${message}`);
+ return internalErrorResponse(requestId, exc, this.vault, this.reach);
}
}
@@ -452,8 +474,8 @@ export class MCPServer {
const token = readProgressToken(params);
const onProgress = progressSink(token, this.sendNotification);
// A token this transport cannot honour is refused by name on the way
- // out - on the error envelope too, because a call that asked for
- // progress and then failed still never got any.
+ // out - on an isError result and on a JSON-RPC error too, because a
+ // call that asked for progress and then failed still never got any.
const refusal: ProgressRefusal | undefined =
token !== undefined && onProgress === undefined
? progressRefusal(token, PROGRESS_REASON.transportSingleResponse)
@@ -462,7 +484,10 @@ export class MCPServer {
const structured = await this.invokeToolHandler(tool, args, onProgress);
return withProgressRefusal(buildMcpToolResult(tool, structured, this.artifactStore), refusal);
} catch (exc) {
- if (exc instanceof MCPError) throw exc;
+ if (exc instanceof MCPError) {
+ if (refusal === undefined) throw exc;
+ throw new MCPError(exc.code, exc.message, { ...exc.data, [PROGRESS_META_KEY]: refusal });
+ }
// The tool-level twin of the INTERNAL_ERROR channel: the same raw
// exception prose, so the same host-path redaction at remote reach.
// A local caller already holds the filesystem, and these messages
@@ -475,7 +500,7 @@ export class MCPServer {
// ValueError/TypeError semantics in Python β†’ tool-level error envelope.
// OSError in Python β†’ "filesystem error" prefix. We collapse both to a
// single tool-level error since JS doesn't distinguish.
- return withProgressRefusal(toolError(message), refusal);
+ return withProgressRefusal(toolError(message, codeForError(exc)), refusal);
}
}
}
@@ -567,10 +592,16 @@ export function buildMcpToolResult(
};
}
-function toolError(message: string): Record<string, unknown> {
+/**
+ * An `isError` tool result. The text is the message alone, as it always
+ * was; the stable code rides on `_meta` because strict clients validate
+ * `structuredContent` against the tool's output schema even on an error.
+ */
+function toolError(message: string, code: ToolErrorCode): Record<string, unknown> {
return {
content: [{ type: "text", text: message }],
isError: true,
+ [META_MEMBER]: { [TOOL_ERROR_META_KEY]: toolErrorMeta(code) },
};
}
@@ -582,18 +613,84 @@ function sortedReplacer(_key: string, value: unknown): unknown {
return value;
}
+/** The member of `error.data` every JSON-RPC error answer carries. */
+const ERROR_DATA_CODE_KEY = "code";
+
+/** The stderr line a thrower-supplied code outside the registry is named on. */
+const UNREGISTERED_CODE_WARNING = "warning: unregistered error code on the wire: ";
+
+/** The longest quoted code that warning line repeats. */
+const UNREGISTERED_CODE_LOG_MAX = 120;
+
+/**
+ * `data` with its stable string code. A thrower-supplied string code
+ * always wins; otherwise the default derived from the numeric JSON-RPC
+ * code is added after the thrower's own members, so a record such as the
+ * argument guard's keeps its shape and gains one key.
+ *
+ * A supplied code outside {@link isToolErrorCode} is still sent as it
+ * is - replacing it would hide which producer chose it - and is named on
+ * stderr. Every producer passes a constant token, never prose, but the
+ * line exists to catch one that breaks that rule, so the code is written
+ * JSON-quoted and capped: a newline in it cannot forge a second line.
+ */
+function withDefaultCode(code: JsonRpcErrorCode, data: MCPErrorData | undefined): JsonRpcErrorData {
+ const supplied: unknown = (data as { readonly [ERROR_DATA_CODE_KEY]?: unknown } | undefined)?.[
+ ERROR_DATA_CODE_KEY
+ ];
+ if (data !== undefined && typeof supplied === "string") {
+ if (!isToolErrorCode(supplied)) {
+ const quoted = JSON.stringify(supplied).slice(0, UNREGISTERED_CODE_LOG_MAX);
+ process.stderr.write(`${UNREGISTERED_CODE_WARNING}${quoted}\n`);
+ }
+ return data as JsonRpcErrorData;
+ }
+ return { ...data, [ERROR_DATA_CODE_KEY]: defaultCodeForRpc(code) };
+}
+
+/**
+ * The one builder every JSON-RPC error answer passes through, including
+ * the transport errors of `stdio.ts` and `http.ts`, so "every error
+ * response carries `error.data.code`" holds by construction.
+ */
export function errorResponse(
requestId: unknown,
- code: number,
+ code: JsonRpcErrorCode,
message: string,
- data?: unknown,
+ data?: MCPErrorData,
): JsonRpcResponse {
- const error: { code: number; message: string; data?: unknown } = {
- code,
- message,
+ return {
+ jsonrpc: JSONRPC_VERSION,
+ id: requestId ?? null,
+ error: { code, message, data: withDefaultCode(code, data) },
};
- if (data !== undefined) error.data = data;
- return { jsonrpc: JSONRPC_VERSION, id: requestId ?? null, error };
+}
+
+/**
+ * The prefix of the INTERNAL_ERROR answer {@link internalErrorResponse}
+ * builds for an unmapped throw. Handlers that throw their own
+ * INTERNAL_ERROR keep their own message; `error.data.code` is the stable
+ * signal, not this prefix.
+ */
+const INTERNAL_ERROR_PREFIX = "internal error: ";
+
+/**
+ * The INTERNAL_ERROR answer for a throw no handler mapped: the raw prose
+ * through the redactor for the bind's reach, the code from the
+ * classifier, which names an unknown class on stderr. One builder for the
+ * dispatcher and the HTTP catch-all, so the two channels cannot drift.
+ */
+export function internalErrorResponse(
+ requestId: unknown,
+ exc: unknown,
+ vault: string,
+ reach: TransportReach,
+): JsonRpcResponse {
+ const raw = (exc as Error).message ?? String(exc);
+ const message = redactErrorForCaller(raw, vault, reach);
+ return errorResponse(requestId, INTERNAL_ERROR, `${INTERNAL_ERROR_PREFIX}${message}`, {
+ code: codeForError(exc),
+ });
}
// Re-exports so callers that previously imported these names from
diff --git a/src/mcp/skill-tools.ts b/src/mcp/skill-tools.ts
index 1e64e251..5d102776 100644
--- a/src/mcp/skill-tools.ts
+++ b/src/mcp/skill-tools.ts
@@ -28,11 +28,29 @@ import {
type SkillDecisionInfo,
} from "../core/surface/skill-attach-decision.ts";
import { isSkillOfferId, SKILL_OFFER_ID_KEY } from "../core/surface/skill-offer.ts";
-import { discoverSkills, readSkillFile, skillRoots, SkillError } from "../core/surface/skills.ts";
+import {
+ discoverSkills,
+ readSkillFile,
+ skillRoots,
+ SkillError,
+ type SkillErrorCode,
+} from "../core/surface/skills.ts";
import { coerceInt, coerceStr } from "./coerce.ts";
import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";
import { INVALID_PARAMS, MCPError } from "./protocol.ts";
import type { ServerContext, ToolDefinition } from "./tool-contract.ts";
+import { TOOL_ERROR_CODE, type ToolErrorCode } from "./tool-error-codes.ts";
+
+/**
+ * The wire code for each `SkillError` kind. Total over the core union, so
+ * a new kind fails the type check until it is mapped here. The core's
+ * bare `NOT_FOUND` / `INVALID_PATH` never reached the wire and would be
+ * ambiguous in a cross-tool registry, so they are spelled per surface.
+ */
+const SKILL_ERROR_WIRE_CODE: Readonly<Record<SkillErrorCode, ToolErrorCode>> = Object.freeze({
+ NOT_FOUND: TOOL_ERROR_CODE.skillNotFound,
+ INVALID_PATH: TOOL_ERROR_CODE.skillInvalidPath,
+});
function rootsFor(ctx: ServerContext): string[] {
const skillsDir = resolveSkillsDir(ctx.configPath ?? undefined);
@@ -81,13 +99,17 @@ function toolGetSkill(ctx: ServerContext, args: Record<string, unknown>): Record
const skill = skills.find((s) => s.name === name);
if (skill === undefined) {
const known = skills.map((s) => s.name).join(", ") || "(none)";
- throw new MCPError(INVALID_PARAMS, `unknown skill: ${name}. Known skills: ${known}`);
+ throw new MCPError(INVALID_PARAMS, `unknown skill: ${name}. Known skills: ${known}`, {
+ code: TOOL_ERROR_CODE.unknownSkill,
+ });
}
let content: string;
try {
content = readSkillFile(skill, filePath);
} catch (err) {
- if (err instanceof SkillError) throw new MCPError(INVALID_PARAMS, err.message);
+ if (err instanceof SkillError) {
+ throw new MCPError(INVALID_PARAMS, err.message, { code: SKILL_ERROR_WIRE_CODE[err.code] });
+ }
throw err;
}
return {
diff --git a/src/mcp/tool-error-codes.ts b/src/mcp/tool-error-codes.ts
new file mode 100644
index 00000000..d048f996
--- /dev/null
+++ b/src/mcp/tool-error-codes.ts
@@ -0,0 +1,413 @@
+/**
+ * The closed registry of error codes the MCP boundary answers with.
+ *
+ * Open Second Brain answers a failed tool call on one of two channels: a
+ * JSON-RPC error (`error.data.code`) or an `isError` result
+ * (`_meta["open-second-brain/error"].code`). Both carry one member of
+ * {@link TOOL_ERROR_CODES}, so a client branches on a token instead of
+ * matching English prose.
+ *
+ * The registry does not rename anything already on the wire. It imports
+ * the core vocabularies verbatim - kebab, snake and UPPER spellings stay
+ * as their owners chose them - and adds lower snake_case tokens
+ * ({@link TOOL_ERROR_CODE}) only for the failures that had no code at all.
+ *
+ * Core vocabularies that exist only as a TypeScript union are listed here
+ * through {@link exhaustiveMembers}, which fails `tsc` both when an entry
+ * is not a member of the union and when a union member is missing, so a
+ * code added in the core cannot reach the wire unregistered.
+ *
+ * {@link codeForError} classifies a thrown value by `instanceof` over a
+ * closed table and never reads a `.code` structurally: a Node fs error
+ * carries `ENOENT`, which is no member of this registry. Anything the
+ * table does not know is the explicit {@link TOOL_ERROR_CODE.internalError}
+ * and is named on stderr by its class name only, never by its message, so
+ * no vault path reaches a log at remote reach.
+ */
+
+import { BrainPreferenceNotFoundError } from "../core/brain/apply-evidence.ts";
+import { CountGuardError } from "../core/brain/count-guard.ts";
+import type { ExactStateErrorCode } from "../core/brain/exact-state.ts";
+import { ExactStateError } from "../core/brain/exact-state.ts";
+import {
+ EXPIRATION_REFUSAL_CODE,
+ EXPIRATION_REFUSAL_CODES,
+ ExpirationTargetNotFoundError,
+ ExpirationValueError,
+ InvalidExpirationTargetError,
+} from "../core/brain/expiration-set.ts";
+import { VaultFrozenError } from "../core/brain/freeze-marker.ts";
+import type { HostMemoryWriteErrorCode } from "../core/brain/host-memory-write.ts";
+import { HostMemoryWriteError } from "../core/brain/host-memory-write.ts";
+import type { CreateNoteErrorCode } from "../core/brain/notes/create-note.ts";
+import { CreateNoteError } from "../core/brain/notes/create-note.ts";
+import type { NoteLifecycleErrorCode } from "../core/brain/notes/lifecycle.ts";
+import { NoteLifecycleError } from "../core/brain/notes/lifecycle.ts";
+import type { NoteTemplateErrorCode } from "../core/brain/notes/note-template.ts";
+import { NoteTemplateError } from "../core/brain/notes/note-template.ts";
+import type { NoteTitleResolutionErrorCode } from "../core/brain/notes/note-title-resolver.ts";
+import { NoteTitleResolutionError } from "../core/brain/notes/note-title-resolver.ts";
+import { NOTE_REVERT_ERROR, NoteRevertError } from "../core/brain/notes/revert.ts";
+import type { ScaffoldStubErrorCode } from "../core/brain/notes/scaffold-stub.ts";
+import { ScaffoldStubError } from "../core/brain/notes/scaffold-stub.ts";
+import { BrainParseError } from "../core/brain/parse-error.ts";
+import type { PinnedBatchErrorCode } from "../core/brain/pinned.ts";
+import { PinnedBatchError } from "../core/brain/pinned.ts";
+import { BrainConfigError } from "../core/brain/policy/errors.ts";
+import { ResponseCheckError, SEMANTIC_VIOLATION_CODES } from "../core/brain/response-checks.ts";
+import { ResponseShapeError, SHAPE_VIOLATION_CODES } from "../core/brain/response-shape.ts";
+import { SafeguardAbortError, SafeguardTimeoutError } from "../core/brain/safeguard.ts";
+import type { WriteBatchErrorCode } from "../core/brain/write-batch.ts";
+import { WriteBatchError } from "../core/brain/write-batch.ts";
+import { ConfigReadError } from "../core/config.ts";
+import { SEARCH_ERROR_CODES, SearchError } from "../core/search/search-error.ts";
+import { WRITE_BINDING_REFUSED_CODE } from "../core/write-binding/index.ts";
+import { VAULT_FROZEN_REFUSAL } from "./frozen-refusal.ts";
+import { OWNER_SCOPE_REFUSALS } from "./owner-scope-refusal.ts";
+import {
+ INTERNAL_ERROR,
+ INVALID_PARAMS,
+ INVALID_REQUEST,
+ type JsonRpcErrorCode,
+ METHOD_NOT_FOUND,
+ PARSE_ERROR,
+} from "./protocol.ts";
+import { OutputContractError } from "./output-contract.ts";
+import { REACH_REFUSAL } from "./reach-refusal.ts";
+
+/** The `_meta` key an `isError` result carries its code under. */
+export const TOOL_ERROR_META_KEY = "open-second-brain/error";
+
+/** Payload schema tag, versioned like `o2b.progress.v1`. */
+export const TOOL_ERROR_SCHEMA = "o2b.error.v1";
+
+/**
+ * The generic tokens this registry adds: one per failure that reaches the
+ * boundary with no code of its own. Each has a producer in this release.
+ */
+export const TOOL_ERROR_CODE = Object.freeze({
+ /** The five JSON-RPC defaults, one per {@link JsonRpcErrorCode}. */
+ parseError: "parse_error",
+ invalidRequest: "invalid_request",
+ methodNotFound: "method_not_found",
+ invalidParams: "invalid_params",
+ /** A throw the classifier does not know; logged by name on stderr. */
+ internalError: "internal_error",
+ /** A safeguard deadline aborted the operation at a checkpoint. */
+ safeguardTimeout: "safeguard_timeout",
+ /** The operation's abort signal fired on demand. */
+ safeguardAborted: "safeguard_aborted",
+ /** A tool's result did not match its declared output schema. */
+ outputContractFailed: "output_contract_failed",
+ /** The plugin config file exists and could not be read. */
+ configUnreadable: "config_unreadable",
+ /** A `SkillError` of kind `NOT_FOUND`. */
+ skillNotFound: "skill_not_found",
+ /** A `SkillError` of kind `INVALID_PATH`. */
+ skillInvalidPath: "skill_invalid_path",
+ /** A skill name the registry does not hold. */
+ unknownSkill: "unknown_skill",
+ /** An `operation` argument outside the tool's closed set. */
+ unknownOperation: "unknown_operation",
+ /** A `status` argument outside the tool's closed set. */
+ invalidStatus: "invalid_status",
+ /** A trigger transition refused; absent and not-visible share it. */
+ triggerTransitionRefused: "trigger_transition_refused",
+ /** A `session_id` that names no write session. */
+ writeSessionUnknown: "write_session_unknown",
+ /** A write session that is already committed or aborted. */
+ writeSessionTerminal: "write_session_terminal",
+ /** An operation that needs a write session was sent without one. */
+ sessionIdRequired: "session_id_required",
+ /** An argument the tool's input schema does not declare. */
+ unknownArgument: "unknown_argument",
+ /** A Brain artifact file could not be parsed (`BrainParseError`). */
+ brainArtifactUnparseable: "brain_artifact_unparseable",
+ /** An argument that belongs to another action of the same tool. */
+ argumentForbidden: "argument_forbidden",
+} as const);
+
+/** Closed union over {@link TOOL_ERROR_CODE}. */
+export type GenericToolErrorCode = (typeof TOOL_ERROR_CODE)[keyof typeof TOOL_ERROR_CODE];
+
+/** Membership list of the generic tokens alone. */
+export const GENERIC_TOOL_ERROR_CODES: ReadonlyArray<GenericToolErrorCode> = Object.freeze(
+ Object.values(TOOL_ERROR_CODE),
+);
+
+const GENERIC_TOOL_ERROR_CODE_SET: ReadonlySet<string> = new Set(GENERIC_TOOL_ERROR_CODES);
+
+/** Narrow a value to one of the generic tokens this registry adds. */
+export function isGenericToolErrorCode(value: unknown): value is GenericToolErrorCode {
+ return typeof value === "string" && GENERIC_TOOL_ERROR_CODE_SET.has(value);
+}
+
+/**
+ * The members `Union` lacks from `List`, or `never` when `List` names them
+ * all. A non-`never` result is what makes {@link exhaustiveMembers} fail.
+ */
+type MissingMembers<Union, List extends ReadonlyArray<Union>> = Exclude<Union, List[number]>;
+
+/**
+ * Freeze the member list of a type-only core vocabulary, checked by `tsc`
+ * in both directions: an entry outside `Union` is rejected by the element
+ * type, and a member of `Union` absent from the list turns the argument
+ * type into an object naming it, which no array literal satisfies.
+ */
+function exhaustiveMembers<Union extends string>() {
+ return <const List extends ReadonlyArray<Union>>(
+ list: List &
+ ([MissingMembers<Union, List>] extends [never]
+ ? unknown
+ : { readonly missingMembers: MissingMembers<Union, List> }),
+ ): List => Object.freeze([...list]) as unknown as List;
+}
+
+const WRITE_BATCH_CODES = exhaustiveMembers<WriteBatchErrorCode>()([
+ "invalid_operation",
+ "invalid_path",
+ "excluded",
+ "outside_vault",
+ "exists",
+ "target_missing",
+ "target_unreadable",
+ "target_frontmatter_lossy",
+ "blank_overwrite_refused",
+ "reserved_frontmatter_key",
+ "duplicate_target",
+ "too_many_operations",
+ "preference_not_found",
+ "write_binding",
+ "invalid_document",
+ "invalid_template",
+ "config_invalid",
+]);
+
+const CREATE_NOTE_CODES = exhaustiveMembers<CreateNoteErrorCode>()([
+ "invalid_path",
+ "excluded",
+ "exists",
+ "outside_vault",
+ "invalid_document",
+ "invalid_template",
+ "write_binding",
+ "config_invalid",
+]);
+
+const NOTE_LIFECYCLE_CODES = exhaustiveMembers<NoteLifecycleErrorCode>()([
+ "source_missing",
+ "destination_required",
+ "destination_forbidden",
+ "destination_occupied",
+ "destination_unchanged",
+ "wrong_action",
+ "not_confirmed",
+ "already_archived",
+ "cascade_forbidden",
+]);
+
+const SCAFFOLD_STUB_CODES = exhaustiveMembers<ScaffoldStubErrorCode>()([
+ "empty_target",
+ "target_resolves",
+ "target_ambiguous",
+ "unknown_source",
+]);
+
+const NOTE_TITLE_RESOLUTION_CODES = exhaustiveMembers<NoteTitleResolutionErrorCode>()([
+ "empty_target",
+ "path_not_found",
+ "not_found",
+ "ambiguous",
+]);
+
+const NOTE_TEMPLATE_CODES = exhaustiveMembers<NoteTemplateErrorCode>()([
+ "unbalanced_section",
+ "section_too_deep",
+ "invalid_variable",
+]);
+
+const PINNED_BATCH_CODES = exhaustiveMembers<PinnedBatchErrorCode>()([
+ "invalid_operation",
+ "replace_target_missing",
+ "budget_exceeded",
+]);
+
+const EXACT_STATE_CODES = exhaustiveMembers<ExactStateErrorCode>()([
+ "budget_exceeded",
+ "invalid_aspect",
+]);
+
+const HOST_MEMORY_WRITE_CODES = exhaustiveMembers<HostMemoryWriteErrorCode>()([
+ "invalid_action",
+ "invalid_target",
+ "empty_content",
+]);
+
+/**
+ * The token a count-guard refusal is reported under on the wire. The core
+ * `CountGuardError` carries `COUNT_GUARD`; `brain_note_lifecycle` has
+ * always answered it as this lower-case token, and this registry keeps the
+ * wire spelling rather than the class field. `brain_note_lifecycle` imports
+ * it, so the spelling has one definition.
+ */
+export const COUNT_GUARD_WIRE_CODE = "count_guard";
+
+/**
+ * Every code the MCP boundary may answer with: the generic tokens plus
+ * each imported vocabulary, de-duplicated (several core vocabularies share
+ * a token such as `invalid_path`, and it means the same thing in each).
+ */
+export const TOOL_ERROR_CODES = Object.freeze([
+ ...new Set([
+ ...GENERIC_TOOL_ERROR_CODES,
+ ...SEARCH_ERROR_CODES,
+ ...Object.values(SHAPE_VIOLATION_CODES),
+ ...Object.values(SEMANTIC_VIOLATION_CODES),
+ VAULT_FROZEN_REFUSAL,
+ WRITE_BINDING_REFUSED_CODE,
+ REACH_REFUSAL,
+ ...OWNER_SCOPE_REFUSALS,
+ ...WRITE_BATCH_CODES,
+ ...CREATE_NOTE_CODES,
+ ...NOTE_LIFECYCLE_CODES,
+ ...Object.values(NOTE_REVERT_ERROR),
+ ...SCAFFOLD_STUB_CODES,
+ ...NOTE_TITLE_RESOLUTION_CODES,
+ ...NOTE_TEMPLATE_CODES,
+ ...PINNED_BATCH_CODES,
+ ...EXACT_STATE_CODES,
+ ...HOST_MEMORY_WRITE_CODES,
+ COUNT_GUARD_WIRE_CODE,
+ ...EXPIRATION_REFUSAL_CODES,
+ ] as const),
+]);
+
+/** Closed union over {@link TOOL_ERROR_CODES}. */
+export type ToolErrorCode = (typeof TOOL_ERROR_CODES)[number];
+
+const TOOL_ERROR_CODE_SET: ReadonlySet<string> = new Set(TOOL_ERROR_CODES);
+
+/** Narrow a value read back off the wire to a registered code. */
+export function isToolErrorCode(value: unknown): value is ToolErrorCode {
+ return typeof value === "string" && TOOL_ERROR_CODE_SET.has(value);
+}
+
+/** The `_meta` payload an `isError` result carries. */
+export interface ToolErrorMeta {
+ readonly schema: typeof TOOL_ERROR_SCHEMA;
+ readonly code: ToolErrorCode;
+}
+
+/** Build the `_meta["open-second-brain/error"]` payload for `code`. */
+export function toolErrorMeta(code: ToolErrorCode): ToolErrorMeta {
+ return { schema: TOOL_ERROR_SCHEMA, code };
+}
+
+/** Total map from each JSON-RPC error code to its string default. */
+const RPC_DEFAULT_CODE: Readonly<Record<JsonRpcErrorCode, GenericToolErrorCode>> = Object.freeze({
+ [PARSE_ERROR]: TOOL_ERROR_CODE.parseError,
+ [INVALID_REQUEST]: TOOL_ERROR_CODE.invalidRequest,
+ [METHOD_NOT_FOUND]: TOOL_ERROR_CODE.methodNotFound,
+ [INVALID_PARAMS]: TOOL_ERROR_CODE.invalidParams,
+ [INTERNAL_ERROR]: TOOL_ERROR_CODE.internalError,
+});
+
+/** The code a JSON-RPC error carries when its thrower named none. */
+export function defaultCodeForRpc(code: JsonRpcErrorCode): ToolErrorCode {
+ return RPC_DEFAULT_CODE[code];
+}
+
+/** A class constructor, matched by `instanceof`. */
+type ErrorClass<E extends Error> = abstract new (...args: never[]) => E;
+
+/** How one known class is classified: a fixed code, or the code it carries. */
+interface ClassificationRule {
+ readonly matches: (exc: unknown) => boolean;
+ readonly code: (exc: Error) => string;
+}
+
+function fixed<E extends Error>(ctor: ErrorClass<E>, code: ToolErrorCode): ClassificationRule {
+ return { matches: (exc) => exc instanceof ctor, code: () => code };
+}
+
+function carried<E extends Error & { readonly code: string }>(
+ ctor: ErrorClass<E>,
+): ClassificationRule {
+ return { matches: (exc) => exc instanceof ctor, code: (exc) => (exc as E).code };
+}
+
+/**
+ * The closed classification table. A carried code still has to pass
+ * {@link isToolErrorCode} before it reaches the wire.
+ */
+const CLASSIFICATION: ReadonlyArray<ClassificationRule> = Object.freeze([
+ carried(WriteBatchError),
+ carried(CreateNoteError),
+ carried(NoteLifecycleError),
+ carried(NoteRevertError),
+ carried(ScaffoldStubError),
+ carried(NoteTitleResolutionError),
+ carried(NoteTemplateError),
+ carried(PinnedBatchError),
+ carried(ExactStateError),
+ carried(HostMemoryWriteError),
+ carried(SearchError),
+ carried(ResponseShapeError),
+ carried(ResponseCheckError),
+ fixed(CountGuardError, COUNT_GUARD_WIRE_CODE),
+ fixed(VaultFrozenError, VAULT_FROZEN_REFUSAL),
+ fixed(SafeguardTimeoutError, TOOL_ERROR_CODE.safeguardTimeout),
+ fixed(SafeguardAbortError, TOOL_ERROR_CODE.safeguardAborted),
+ fixed(ConfigReadError, TOOL_ERROR_CODE.configUnreadable),
+ fixed(OutputContractError, TOOL_ERROR_CODE.outputContractFailed),
+ fixed(BrainConfigError, "config_invalid"),
+ fixed(BrainPreferenceNotFoundError, "preference_not_found"),
+ fixed(BrainParseError, TOOL_ERROR_CODE.brainArtifactUnparseable),
+ fixed(ExpirationValueError, EXPIRATION_REFUSAL_CODE.invalidValue),
+ fixed(ExpirationTargetNotFoundError, EXPIRATION_REFUSAL_CODE.targetNotFound),
+ fixed(InvalidExpirationTargetError, EXPIRATION_REFUSAL_CODE.invalidTarget),
+]);
+
+/**
+ * How many `cause` links the classifier follows. A tool that rethrows a
+ * typed error as a plain one keeps the original as `cause` (the feedback
+ * rethrow does); a bounded walk also stops a cyclic chain.
+ */
+const MAX_CAUSE_DEPTH = 4;
+
+const UNCLASSIFIED_WARNING = "warning: unclassified tool error mapped to internal_error: ";
+
+function classifyOne(exc: unknown): ToolErrorCode | undefined {
+ if (!(exc instanceof Error)) return undefined;
+ for (const rule of CLASSIFICATION) {
+ if (!rule.matches(exc)) continue;
+ const code = rule.code(exc);
+ return isToolErrorCode(code) ? code : undefined;
+ }
+ return undefined;
+}
+
+/**
+ * The name an unclassified throw is logged under; never its message. The
+ * constructor's name comes first because several core error classes never
+ * set `this.name`, and would all be logged as `Error`.
+ */
+function unclassifiedName(exc: unknown): string {
+ return exc instanceof Error ? exc.constructor?.name || exc.name : typeof exc;
+}
+
+/**
+ * The registered code for a thrown value. Walks `cause` up to
+ * {@link MAX_CAUSE_DEPTH} links; a throw no rule classifies is
+ * `internal_error`, and one stderr line names its class.
+ */
+export function codeForError(exc: unknown): ToolErrorCode {
+ let current: unknown = exc;
+ for (let depth = 0; depth <= MAX_CAUSE_DEPTH && current !== undefined; depth += 1) {
+ const code = classifyOne(current);
+ if (code !== undefined) return code;
+ current = current instanceof Error ? current.cause : undefined;
+ }
+ process.stderr.write(`${UNCLASSIFIED_WARNING}${unclassifiedName(exc)}\n`);
+ return TOOL_ERROR_CODE.internalError;
+}
diff --git a/tests/core/architecture/verdict-vocabulary-census.test.ts b/tests/core/architecture/verdict-vocabulary-census.test.ts
index 2ede43de..a35c698f 100644
--- a/tests/core/architecture/verdict-vocabulary-census.test.ts
+++ b/tests/core/architecture/verdict-vocabulary-census.test.ts
@@ -205,6 +205,16 @@ import {
RETRIEVAL_DEGRADATION,
RETRIEVAL_DEGRADATION_CODES,
} from "../../../src/core/search/retrieval-trail.ts";
+import {
+ isRerankFailureCategory,
+ RERANK_FAILURE_CATEGORIES,
+ RERANK_FAILURE_CATEGORY,
+} from "../../../src/core/search/rerank/failure.ts";
+import {
+ GENERIC_TOOL_ERROR_CODES,
+ isGenericToolErrorCode,
+ TOOL_ERROR_CODE,
+} from "../../../src/mcp/tool-error-codes.ts";
import {
isPageLintSkipReason,
PAGE_LINT_SKIP_REASON,
@@ -685,6 +695,30 @@ const CENSUS: ReadonlyArray<VocabularyUnderCensus> = Object.freeze([
members: RETRIEVAL_DEGRADATION_CODES,
guard: isRetrievalDegradationCode,
},
+ {
+ // Why a cross-encoder rerank request failed. Registered because the
+ // value leaves TypeScript: it rides `detail.category` of the
+ // `rerank-provider-unavailable` trail entry in `--json` and MCP
+ // `brain_search`, and it is computed from typed errors, so a member
+ // added to the object and forgotten in the list would be a category
+ // the producer emits and no reader can narrow back.
+ name: "RERANK_FAILURE_CATEGORY",
+ values: RERANK_FAILURE_CATEGORY,
+ members: RERANK_FAILURE_CATEGORIES,
+ guard: isRerankFailureCategory,
+ },
+ {
+ // The generic tokens the MCP boundary adds for failures that reach it
+ // with no code of their own. Registered because every value is a wire
+ // contract: it rides `error.data.code` or
+ // `_meta["open-second-brain/error"].code`, and clients branch on it.
+ // Only the generic object is four-piece; the imported core
+ // vocabularies keep their own registration where they live.
+ name: "TOOL_ERROR_CODE",
+ values: TOOL_ERROR_CODE,
+ members: GENERIC_TOOL_ERROR_CODES,
+ guard: isGenericToolErrorCode,
+ },
{
// C3. The two vocabularies the schema-completeness audit is built on:
// what kind of schema node the walk is standing on, and what a node
@@ -1591,7 +1625,7 @@ const SCANNED = scanVocabularies(SOURCE_TREE);
* How many four-piece vocabularies `src/` currently holds. Measured, and
* kept as an equality rather than a floor - see the population test.
*/
-const VOCABULARY_POPULATION = 79;
+const VOCABULARY_POPULATION = 81;
const REGISTERED = new Map(CENSUS.map((entry) => [entry.name, entry] as const));
describe("verdict vocabulary census", () => {
diff --git a/tests/core/brain/doctor-exit-census.test.ts b/tests/core/brain/doctor-exit-census.test.ts
index 246fc0b7..242c5ff1 100644
--- a/tests/core/brain/doctor-exit-census.test.ts
+++ b/tests/core/brain/doctor-exit-census.test.ts
@@ -197,6 +197,8 @@ const DOCTOR_REGISTERED_CODES: ReadonlyArray<string> = [
"principle-corrupted",
"recall-channel-silent",
"recovery-point-stale",
+ "rerank-endpoint-unconfigured",
+ "rerank-model-sunset-announced",
"schema-version-unknown",
"stale-claim",
"stale-dependency",
diff --git a/tests/core/brain/doctor/rerank-health-check.test.ts b/tests/core/brain/doctor/rerank-health-check.test.ts
new file mode 100644
index 00000000..d46d67ea
--- /dev/null
+++ b/tests/core/brain/doctor/rerank-health-check.test.ts
@@ -0,0 +1,370 @@
+/**
+ * The config-only rerank doctor check.
+ *
+ * Pins the four judgements the check owns: a rerank that is off or not
+ * the remote kind is silence; an enabled remote rerank that cannot
+ * resolve its endpoint is one error naming every missing piece; an
+ * announced decommission inside the warning window (or past) is a
+ * warning naming the model and the date; an off-survey model or a stale
+ * survey reaches the uncertain stream. The check reads configuration only,
+ * so a run with `fetch` replaced by a thrower must still complete.
+ */
+
+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { DIAGNOSTIC_SIGNALS } from "../../../../src/core/brain/diagnostics.ts";
+import type { DoctorCheckContext } from "../../../../src/core/brain/doctor/check.ts";
+import { EMBEDDING_SUNSET_WARNING_WINDOW_DAYS } from "../../../../src/core/brain/doctor/embedding-sunset-check.ts";
+import {
+ makeRerankHealthCheck,
+ RERANK_ENDPOINT_UNCONFIGURED_CODE,
+ RERANK_MODEL_SUNSET_ANNOUNCED_CODE,
+ RERANK_MODEL_SUNSET_UNDETERMINED_CODE,
+ RERANK_MODEL_SUNSET_UNSURVEYED_CODE,
+} from "../../../../src/core/brain/doctor/rerank-health-check.ts";
+import type { DoctorUncertainEntry } from "../../../../src/core/brain/doctor/report.ts";
+import { DOCTOR_EXIT_EXCLUSIONS } from "../../../../src/core/brain/doctor-exits.ts";
+import { runDoctor } from "../../../../src/core/brain/doctor.ts";
+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
+import type { DoctorIssue } from "../../../../src/core/brain/types.ts";
+import {
+ EMBEDDING_SUNSET_SURVEY_HORIZON_DAYS,
+ type EmbeddingSunsetSurvey,
+} from "../../../../src/core/search/embeddings/sunset.ts";
+
+const MS_PER_DAY = 24 * 60 * 60 * 1000;
+const NOW = new Date("2026-06-01T00:00:00.000Z");
+const MODEL = "vendor-x/rerank-v1";
+const BASE_URL = "https://example.invalid/v1";
+/** An env var name unique to this file, so no other test can set it. */
+const KEY_VAR = "O2B_TEST_RERANK_HEALTH_CHECK_KEY";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+interface RerankConfig {
+ readonly enabled?: boolean;
+ readonly kind?: string;
+ readonly baseUrl?: string | null;
+ readonly model?: string | null;
+ readonly envKey?: string | null;
+ readonly provider?: string;
+ readonly allowInsecureHttp?: boolean;
+}
+
+/** Write the `o2b` config; every field defaults to a complete remote rerank. */
+function configure(c: RerankConfig = {}): void {
+ const lines = [`vault: ${vault}`, `search_rerank_enabled: "${c.enabled ?? true}"`];
+ if (c.kind !== undefined) lines.push(`search_rerank_kind: "${c.kind}"`);
+ const baseUrl = c.baseUrl === undefined ? BASE_URL : c.baseUrl;
+ const model = c.model === undefined ? MODEL : c.model;
+ const envKey = c.envKey === undefined ? KEY_VAR : c.envKey;
+ if (baseUrl !== null) lines.push(`search_rerank_base_url: "${baseUrl}"`);
+ if (model !== null) lines.push(`search_rerank_model: "${model}"`);
+ if (envKey !== null) lines.push(`search_rerank_env_key: "${envKey}"`);
+ if (c.provider !== undefined) lines.push(`search_rerank_provider: "${c.provider}"`);
+ if (c.allowInsecureHttp !== undefined) {
+ lines.push(`search_rerank_allow_insecure_http: "${c.allowInsecureHttp}"`);
+ }
+ writeFileSync(configPath, lines.join("\n") + "\n");
+}
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-rerank-check-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-rerank-check-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ bootstrapBrain(vault);
+ process.env[KEY_VAR] = "test-key";
+ configure();
+});
+
+afterEach(() => {
+ delete process.env[KEY_VAR];
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+function surveyWith(
+ sunsetAt: string | null,
+ reviewedAt = "2026-05-31",
+ model = MODEL,
+): EmbeddingSunsetSurvey {
+ return { reviewedAt, entries: [{ model, sunsetAt, source: "unit fixture", note: "" }] };
+}
+
+/** A survey that covers the model with a negative, so sunset says nothing. */
+const QUIET_SURVEY = surveyWith(null);
+
+interface RunResult {
+ readonly issues: ReadonlyArray<DoctorIssue>;
+ readonly uncertain: ReadonlyArray<DoctorUncertainEntry>;
+}
+
+function run(survey: EmbeddingSunsetSurvey = QUIET_SURVEY, now: Date = NOW): RunResult {
+ const issues: DoctorIssue[] = [];
+ const uncertain: DoctorUncertainEntry[] = [];
+ makeRerankHealthCheck(survey).run({ vault, now, configPath } as unknown as DoctorCheckContext, {
+ issues,
+ uncertain,
+ });
+ return { issues, uncertain };
+}
+
+function codes(result: RunResult): ReadonlyArray<string> {
+ return [...result.issues, ...result.uncertain].map((e) => e.code);
+}
+
+function inDays(days: number): string {
+ return new Date(NOW.getTime() + days * MS_PER_DAY).toISOString().slice(0, 10);
+}
+
+describe("silence where rerank is not a remote endpoint", () => {
+ test("rerank disabled reports nothing, even with every key missing", () => {
+ configure({ enabled: false, baseUrl: null, model: null, envKey: null });
+ expect(codes(run())).toEqual([]);
+ });
+
+ test("the local and decision-model kinds report nothing", () => {
+ for (const kind of ["local", "decision-model"]) {
+ configure({ kind, baseUrl: null, model: null, envKey: null });
+ expect(codes(run(surveyWith(inDays(-5))))).toEqual([]);
+ }
+ });
+
+ test("a complete remote rerank on a surveyed negative reports nothing", () => {
+ expect(codes(run())).toEqual([]);
+ });
+});
+
+describe("an enabled remote rerank that cannot resolve its endpoint is one error", () => {
+ const cases: ReadonlyArray<readonly [string, RerankConfig, string]> = [
+ ["no base URL", { baseUrl: null }, "search_rerank_base_url"],
+ ["no model", { model: null }, "search_rerank_model"],
+ ["no key variable", { envKey: null }, "search_rerank_env_key"],
+ ];
+ for (const [name, config, named] of cases) {
+ test(name, () => {
+ configure(config);
+ const { issues, uncertain } = run();
+ expect(issues.map((i) => [i.code, i.severity])).toEqual([
+ [RERANK_ENDPOINT_UNCONFIGURED_CODE, "error"],
+ ]);
+ expect(issues[0]!.message).toContain(named);
+ expect(uncertain).toEqual([]);
+ });
+ }
+
+ test("a key variable that is set nowhere names the variable, never a value", () => {
+ delete process.env[KEY_VAR];
+ const { issues } = run();
+ expect(issues.map((i) => i.code)).toEqual([RERANK_ENDPOINT_UNCONFIGURED_CODE]);
+ expect(issues[0]!.message).toContain(KEY_VAR);
+ });
+
+ test("an unregistered provider name that leaves a field empty is named in the error", () => {
+ configure({ provider: "nobody-registered-this", baseUrl: null });
+ const { issues } = run();
+ expect(issues.map((i) => i.code)).toEqual([RERANK_ENDPOINT_UNCONFIGURED_CODE]);
+ expect(issues[0]!.message).toContain("nobody-registered-this");
+ });
+
+ test("an unregistered provider name beside a complete explicit endpoint is no finding", () => {
+ // The explicit search_rerank_* values win over a profile, so search
+ // works and a fail-closed error would be false.
+ configure({ provider: "nobody-registered-this" });
+ expect(codes(run())).toEqual([]);
+ });
+
+ test("an unregistered provider name is not blamed for an unset key value", () => {
+ // A profile supplies the key variable's name, never its value.
+ configure({ provider: "nobody-registered-this" });
+ delete process.env[KEY_VAR];
+ const { issues } = run();
+ expect(issues.map((i) => i.code)).toEqual([RERANK_ENDPOINT_UNCONFIGURED_CODE]);
+ expect(issues[0]!.message).toContain(KEY_VAR);
+ expect(issues[0]!.message).not.toContain("nobody-registered-this");
+ });
+
+ test("an unregistered provider name is not blamed for a refused base URL", () => {
+ // A profile could have supplied a base URL, but not repaired this one.
+ configure({ provider: "nobody-registered-this", baseUrl: "http://example.invalid/v1" });
+ const { issues } = run();
+ expect(issues.map((i) => i.code)).toEqual([RERANK_ENDPOINT_UNCONFIGURED_CODE]);
+ expect(issues[0]!.message).toContain("search_rerank_base_url must be an https endpoint");
+ expect(issues[0]!.message).not.toContain("nobody-registered-this");
+ });
+
+ test("a key variable set to blank is the error the runtime would raise", () => {
+ process.env[KEY_VAR] = " ";
+ const { issues } = run();
+ expect(issues.map((i) => i.code)).toEqual([RERANK_ENDPOINT_UNCONFIGURED_CODE]);
+ expect(issues[0]!.message).toContain(KEY_VAR);
+ });
+
+ test("a blank model is the same error as a missing one", () => {
+ configure({ model: " " });
+ const { issues } = run();
+ expect(issues.map((i) => i.code)).toEqual([RERANK_ENDPOINT_UNCONFIGURED_CODE]);
+ expect(issues[0]!.message).toContain("search_rerank_model");
+ });
+
+ test("a base URL the endpoint rule refuses is the same error, naming the rule", () => {
+ configure({ baseUrl: "http://example.invalid/v1" });
+ const { issues } = run();
+ expect(issues.map((i) => i.code)).toEqual([RERANK_ENDPOINT_UNCONFIGURED_CODE]);
+ expect(issues[0]!.message).toContain("search_rerank_base_url must be an https endpoint");
+ });
+
+ test("a plain-http base URL under the opt-out is accepted without the runtime warning", () => {
+ // The once-per-process plain-http warning belongs to the search that
+ // sends vault text; doctor must not print it or spend it.
+ configure({ baseUrl: "http://rerank-doctor-optout.lan:8080/v1", allowInsecureHttp: true });
+ const stderr = spyOn(process.stderr, "write");
+ try {
+ const { issues } = run();
+ expect(issues.map((i) => i.code)).not.toContain(RERANK_ENDPOINT_UNCONFIGURED_CODE);
+ const written = stderr.mock.calls.map((call) => String(call[0]));
+ expect(written.filter((line) => line.includes("plain http"))).toEqual([]);
+ } finally {
+ stderr.mockRestore();
+ }
+ });
+
+ test("a base URL carrying credentials is refused without repeating them", () => {
+ // The key travels in a header; a user:password@ part never belongs in
+ // the URL, and doctor output is pasted into issues, so it is not echoed.
+ configure({ baseUrl: "http://user:[email protected]:8080/v1" });
+ const { issues } = run();
+ expect(issues.map((i) => i.code)).toEqual([RERANK_ENDPOINT_UNCONFIGURED_CODE]);
+ expect(issues[0]!.message).toContain(
+ "search_rerank_base_url must not carry user:password@ credentials",
+ );
+ expect(issues[0]!.message).not.toContain("s3cret");
+ });
+
+ test("an unparseable base URL that carries credentials is refused without repeating it", () => {
+ // The URL parser rejects the port, so no userinfo is detected; the
+ // endpoint rule's own message must not echo the configured value.
+ configure({ baseUrl: "http://u:secretpw@h:abc/v1" });
+ const { issues } = run();
+ expect(issues.map((i) => i.code)).toEqual([RERANK_ENDPOINT_UNCONFIGURED_CODE]);
+ expect(issues[0]!.message).toContain("<search_rerank_base_url>");
+ expect(issues[0]!.message).not.toContain("secretpw");
+ });
+
+ test("a scheme-less base URL that carries credentials is refused without repeating it", () => {
+ configure({ baseUrl: "u:secretpw@h/v1" });
+ const { issues } = run();
+ expect(issues.map((i) => i.code)).toEqual([RERANK_ENDPOINT_UNCONFIGURED_CODE]);
+ expect(issues[0]!.message).toContain("<search_rerank_base_url>");
+ expect(issues[0]!.message).not.toContain("secretpw");
+ });
+
+ test("a base URL that is not a URL is the same error", () => {
+ configure({ baseUrl: "not a url" });
+ const { issues } = run();
+ expect(issues.map((i) => i.code)).toEqual([RERANK_ENDPOINT_UNCONFIGURED_CODE]);
+ expect(issues[0]!.message).toContain("search_rerank_base_url is not a URL");
+ });
+
+ test("a registered provider name supplies the missing endpoint fields", () => {
+ mkdirSync(join(vault, "Brain", "search"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "search", "rerank-providers.json"),
+ JSON.stringify([
+ { name: "fixture", baseUrl: BASE_URL, defaultModel: MODEL, envKey: KEY_VAR },
+ ]),
+ );
+ configure({ provider: "fixture", baseUrl: null, model: null, envKey: null });
+ expect(codes(run())).toEqual([]);
+ });
+
+ test("several missing pieces are still one finding naming each", () => {
+ configure({ baseUrl: null, model: null });
+ const { issues } = run();
+ expect(issues.length).toBe(1);
+ expect(issues[0]!.message).toContain("search_rerank_base_url");
+ expect(issues[0]!.message).toContain("search_rerank_model");
+ });
+});
+
+describe("an announced decommission is a warning naming model and date", () => {
+ test("inside the window", () => {
+ const date = inDays(EMBEDDING_SUNSET_WARNING_WINDOW_DAYS - 10);
+ const { issues } = run(surveyWith(date));
+ expect(issues.map((i) => [i.code, i.severity])).toEqual([
+ [RERANK_MODEL_SUNSET_ANNOUNCED_CODE, "warning"],
+ ]);
+ expect(issues[0]!.message).toContain(MODEL);
+ expect(issues[0]!.message).toContain(date);
+ });
+
+ test("already past", () => {
+ const date = inDays(-5);
+ const { issues } = run(surveyWith(date));
+ expect(issues.map((i) => i.code)).toEqual([RERANK_MODEL_SUNSET_ANNOUNCED_CODE]);
+ expect(issues[0]!.message).toContain(date);
+ });
+
+ test("beyond the window is not yet a finding", () => {
+ expect(codes(run(surveyWith(inDays(EMBEDDING_SUNSET_WARNING_WINDOW_DAYS + 30))))).toEqual([]);
+ });
+});
+
+describe("what the survey cannot say reaches the uncertain stream", () => {
+ test("an off-survey model is unsurveyed", () => {
+ const { issues, uncertain } = run(surveyWith(null, "2026-05-31", "some-other-model"));
+ expect(issues).toEqual([]);
+ expect(uncertain.map((u) => u.code)).toEqual([RERANK_MODEL_SUNSET_UNSURVEYED_CODE]);
+ expect(uncertain[0]!.message).toContain(MODEL);
+ });
+
+ test("a stale survey is undetermined", () => {
+ const stale = new Date(
+ new Date("2026-05-31T00:00:00.000Z").getTime() +
+ (EMBEDDING_SUNSET_SURVEY_HORIZON_DAYS + 10) * MS_PER_DAY,
+ );
+ const { issues, uncertain } = run(QUIET_SURVEY, stale);
+ expect(issues).toEqual([]);
+ expect(uncertain.map((u) => u.code)).toEqual([RERANK_MODEL_SUNSET_UNDETERMINED_CODE]);
+ });
+});
+
+describe("the check is config-only and registered", () => {
+ test("it makes no network call", () => {
+ const original = globalThis.fetch;
+ let calls = 0;
+ globalThis.fetch = (() => {
+ calls += 1;
+ throw new Error("the rerank doctor check must not reach the network");
+ }) as unknown as typeof fetch;
+ try {
+ run(surveyWith(inDays(-5)));
+ run(surveyWith(null, "2026-05-31", "some-other-model"));
+ } finally {
+ globalThis.fetch = original;
+ }
+ expect(calls).toBe(0);
+ });
+
+ test("the doctor pass runs it", () => {
+ configure({ baseUrl: null });
+ const result = runDoctor(vault, { now: NOW, configPath });
+ expect(result.errors.map((e) => e.code)).toContain(RERANK_ENDPOINT_UNCONFIGURED_CODE);
+ });
+
+ test("actionable codes carry a command, uncertain codes a reason", () => {
+ expect(DIAGNOSTIC_SIGNALS.get(RERANK_ENDPOINT_UNCONFIGURED_CODE)?.nextCommand).toBe(
+ "o2b search rerank-provider list",
+ );
+ expect(DIAGNOSTIC_SIGNALS.get(RERANK_MODEL_SUNSET_ANNOUNCED_CODE)?.nextCommand).toBe(
+ "o2b search rerank-provider add",
+ );
+ expect(DOCTOR_EXIT_EXCLUSIONS.has(RERANK_MODEL_SUNSET_UNSURVEYED_CODE)).toBe(true);
+ expect(DOCTOR_EXIT_EXCLUSIONS.has(RERANK_MODEL_SUNSET_UNDETERMINED_CODE)).toBe(true);
+ });
+});
diff --git a/tests/core/search/rerank-failure.test.ts b/tests/core/search/rerank-failure.test.ts
new file mode 100644
index 00000000..c5ec63ea
--- /dev/null
+++ b/tests/core/search/rerank-failure.test.ts
@@ -0,0 +1,431 @@
+/**
+ * The typed rerank failure category: why a cross-encoder request failed,
+ * as a closed vocabulary computed from typed errors and HTTP statuses,
+ * never from the provider's message text.
+ *
+ * The provider's thrown errors keep their `RERANK_PROVIDER_HTTP` code and
+ * their exact messages, so the `rerank_degraded:` warning stays the same
+ * text; the category travels beside it on the telemetry event.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+
+import {
+ RERANK_FAILURE_CATEGORIES,
+ RERANK_FAILURE_CATEGORY,
+ RerankEndpointError,
+ rerankCategoryForStatus,
+} from "../../../src/core/search/rerank/failure.ts";
+import { CrossEncoderRerankProvider } from "../../../src/core/search/rerank/cross-encoder.ts";
+import {
+ applyCrossEncoderRerank,
+ type RerankTelemetryEvent,
+} from "../../../src/core/search/rerank/index.ts";
+import type { RerankProvider } from "../../../src/core/search/rerank/contract.ts";
+import { SearchError } from "../../../src/core/search/types.ts";
+import type { BrainSearchResult, ResolvedRerankConfig } from "../../../src/core/search/types.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
+import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
+
+const SHORT_TIMEOUT_MS = 50;
+const SLOW_ANSWER_MS = 400;
+const API_KEY = FAKE_PROVIDER_KEY;
+
+function result(id: number): BrainSearchResult {
+ return Object.freeze({
+ documentId: id,
+ chunkId: id,
+ path: `note-${id}.md`,
+ title: `Note ${id}`,
+ content: `content ${id}`,
+ startLine: 1,
+ endLine: 2,
+ score: 1 - id * 0.1,
+ keywordScore: 0.5,
+ semanticScore: 0.5,
+ linkBoost: 0,
+ recencyBoost: 0,
+ searchType: "hybrid" as const,
+ reasons: Object.freeze(["fts5_bm25: 0.500"]),
+ });
+}
+
+const RESULTS = Object.freeze([result(1), result(2)]);
+
+function enabledConfig(baseUrl: string): ResolvedRerankConfig {
+ return Object.freeze({
+ enabled: true,
+ kind: "openai-compat",
+ baseUrl,
+ model: "rerank-test",
+ envKey: null,
+ apiKey: API_KEY,
+ topK: 20,
+ minScore: 0,
+ });
+}
+
+async function runAgainst(
+ baseUrl: string,
+ timeoutMs?: number,
+): Promise<ReadonlyArray<RerankTelemetryEvent>> {
+ const events: RerankTelemetryEvent[] = [];
+ const out = await applyCrossEncoderRerank(RESULTS, "q", enabledConfig(baseUrl), {
+ onTelemetry: (e) => events.push(e),
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
+ });
+ // Every failure degrades to the heuristic order.
+ expect(out).toBe(RESULTS);
+ return events;
+}
+
+async function thrownBy(baseUrl: string, timeoutMs?: number): Promise<unknown> {
+ const provider = new CrossEncoderRerankProvider(
+ { baseUrl, model: "rerank-test", apiKey: API_KEY },
+ timeoutMs !== undefined ? { timeoutMs } : undefined,
+ );
+ try {
+ await provider.rerank("q", ["a", "b"]);
+ } catch (e) {
+ return e;
+ }
+ throw new Error("expected the provider to throw");
+}
+
+function expectEndpointError(err: unknown, category: string, message: RegExp | string): void {
+ expect(err).toBeInstanceOf(RerankEndpointError);
+ const typed = err as RerankEndpointError;
+ expect(typed.code).toBe("RERANK_PROVIDER_HTTP");
+ expect(typed.category).toBe(category as RerankEndpointError["category"]);
+ if (typeof message === "string") expect(typed.message).toBe(message);
+ else expect(typed.message).toMatch(message);
+}
+
+describe("RERANK_FAILURE_CATEGORY vocabulary", () => {
+ // Frozen object, membership list and guard are the census's to check;
+ // this pins the members, which ride `detail.category` on the wire.
+ test("names exactly the nine wire categories", () => {
+ expect(RERANK_FAILURE_CATEGORIES.toSorted()).toEqual([
+ "auth",
+ "gone",
+ "malformed",
+ "network",
+ "quota",
+ "rejected",
+ "timeout",
+ "transient",
+ "unclassified",
+ ]);
+ });
+});
+
+describe("rerankCategoryForStatus", () => {
+ test.each([
+ [401, "auth"],
+ [403, "auth"],
+ [402, "quota"],
+ [404, "gone"],
+ [410, "gone"],
+ [408, "transient"],
+ [429, "transient"],
+ [500, "transient"],
+ [502, "transient"],
+ [503, "transient"],
+ [599, "transient"],
+ [400, "rejected"],
+ [413, "rejected"],
+ [422, "rejected"],
+ ] as const)("HTTP %d is %s", (status, category) => {
+ expect(rerankCategoryForStatus(status)).toBe(category);
+ });
+});
+
+describe("RerankEndpointError", () => {
+ test("is a SearchError with the unchanged RERANK_PROVIDER_HTTP code", () => {
+ const err = new RerankEndpointError("rerank HTTP 503: down", {
+ category: RERANK_FAILURE_CATEGORY.transient,
+ status: 503,
+ });
+ expect(err).toBeInstanceOf(SearchError);
+ expect(err.code).toBe("RERANK_PROVIDER_HTTP");
+ expect(err.message).toBe("rerank HTTP 503: down");
+ expect(err.category).toBe("transient");
+ expect(err.status).toBe(503);
+ });
+});
+
+/** A loopback endpoint that sends 200 headers, then never finishes the body. */
+function stalledBodyServer(): { url: string; stop: () => Promise<void> } {
+ const server = Bun.serve({
+ port: 0,
+ hostname: "127.0.0.1",
+ fetch: () =>
+ new Response(
+ new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode('{"results":['));
+ },
+ }),
+ { status: 200, headers: { "content-type": "application/json" } },
+ ),
+ });
+ return { url: `http://127.0.0.1:${server.port}/v1`, stop: () => server.stop(true) };
+}
+
+/** Settles with `p`, or with "unbounded" when `p` outlives a bounded wait. */
+function bounded<T>(p: Promise<T>): Promise<T | "unbounded"> {
+ return Promise.race([p, Bun.sleep(2_000).then(() => "unbounded" as const)]);
+}
+
+describe("the category reaches the telemetry event", () => {
+ let fake: FakeHttp;
+ beforeEach(async () => {
+ fake = await startFakeHttp();
+ });
+ afterEach(async () => {
+ await fake.close();
+ });
+
+ test("HTTP 503 is transient and keeps its v1.65.0 message", async () => {
+ fake.setHandler(() => ({ status: 503, body: { error: "down" } }));
+ const events = await runAgainst(fake.url);
+ expect(events).toEqual([
+ {
+ status: "error",
+ category: "transient",
+ reason: 'rerank HTTP 503: {"error":"down"}',
+ candidateCount: 2,
+ },
+ ]);
+ const err = await thrownBy(fake.url);
+ expectEndpointError(err, "transient", 'rerank HTTP 503: {"error":"down"}');
+ expect((err as RerankEndpointError).status).toBe(503);
+ });
+
+ test("HTTP 401 is auth and HTTP 410 is gone", async () => {
+ fake.setHandler(() => ({ status: 401, body: { error: "no" } }));
+ expect((await runAgainst(fake.url))[0]).toMatchObject({ status: "error", category: "auth" });
+ fake.setHandler(() => ({ status: 410, body: { error: "retired" } }));
+ expect((await runAgainst(fake.url))[0]).toMatchObject({ status: "error", category: "gone" });
+ });
+
+ test("an endpoint that outlives the timeout is timeout", async () => {
+ fake.setHandler(() => ({ status: 200, body: [], delayMs: SLOW_ANSWER_MS }));
+ const events = await runAgainst(fake.url, SHORT_TIMEOUT_MS);
+ expect(events[0]).toMatchObject({ status: "error", category: "timeout" });
+ expectEndpointError(
+ await thrownBy(fake.url, SHORT_TIMEOUT_MS),
+ "timeout",
+ `rerank request timed out after ${SHORT_TIMEOUT_MS}ms`,
+ );
+ });
+
+ test("a timed-out fetch rejected under another error name is still timeout", async () => {
+ // Runtimes differ in the name of the error an aborted fetch rejects
+ // with; the category follows the request's own abort state, not it.
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = ((_url: string, init: RequestInit) =>
+ new Promise<Response>((_resolve, reject) => {
+ init.signal?.addEventListener("abort", () =>
+ reject(new DOMException("the operation timed out", "TimeoutError")),
+ );
+ })) as unknown as typeof fetch;
+ try {
+ expectEndpointError(
+ await thrownBy(fake.url, SHORT_TIMEOUT_MS),
+ "timeout",
+ `rerank request timed out after ${SHORT_TIMEOUT_MS}ms`,
+ );
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+ });
+
+ test("a refused connection is network", async () => {
+ const dead = await startFakeHttp();
+ const deadUrl = dead.url;
+ await dead.close();
+ const events = await runAgainst(deadUrl);
+ expect(events[0]).toMatchObject({ status: "error", category: "network" });
+ expectEndpointError(await thrownBy(deadUrl), "network", /^network error: /);
+ });
+
+ test("a non-JSON body is malformed", async () => {
+ // The fake server JSON-encodes every body, so this one answer is
+ // stubbed at the fetch seam instead.
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = (async () =>
+ new Response("<html>not json</html>", { status: 200 })) as unknown as typeof fetch;
+ try {
+ expect((await runAgainst(fake.url))[0]).toMatchObject({
+ status: "error",
+ category: "malformed",
+ });
+ expectEndpointError(
+ await thrownBy(fake.url),
+ "malformed",
+ "rerank response not JSON: Failed to parse JSON",
+ );
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+ });
+
+ test("a 2xx body that breaks while it is read is network, not malformed", async () => {
+ // The connection dropped mid-body: nothing is wrong with the body's
+ // shape, so the category points at the path, not at the endpoint.
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = (async () => {
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode('{"results":['));
+ controller.error(new Error("connection reset"));
+ },
+ });
+ return new Response(body, { status: 200 });
+ }) as unknown as typeof fetch;
+ try {
+ expectEndpointError(await thrownBy(fake.url), "network", /^network error: /);
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+ });
+
+ test("a 2xx body that stalls is timeout, within the per-request timeout", async () => {
+ const stalled = stalledBodyServer();
+ try {
+ expectEndpointError(
+ await bounded(thrownBy(stalled.url, SHORT_TIMEOUT_MS)),
+ "timeout",
+ `rerank request timed out after ${SHORT_TIMEOUT_MS}ms`,
+ );
+ } finally {
+ await stalled.stop();
+ }
+ });
+
+ test("a caller abort during a stalled body throws the caller's reason", async () => {
+ const stalled = stalledBodyServer();
+ const caller = new AbortController();
+ const reason = new Error("caller cancelled");
+ const provider = new CrossEncoderRerankProvider(
+ { baseUrl: stalled.url, model: "rerank-test", apiKey: API_KEY },
+ { timeoutMs: 60_000 },
+ );
+ try {
+ setTimeout(() => caller.abort(reason), SHORT_TIMEOUT_MS);
+ const outcome = await bounded(
+ provider.rerank("q", ["a", "b"], { signal: caller.signal }).then(
+ () => "resolved",
+ (e: unknown) => e,
+ ),
+ );
+ expect(outcome).toBe(reason);
+ } finally {
+ await stalled.stop();
+ }
+ });
+
+ test("a wrong score count is malformed", async () => {
+ fake.setHandler(() => ({ status: 200, body: { results: [{ index: 0, relevance_score: 1 }] } }));
+ expect((await runAgainst(fake.url))[0]).toMatchObject({
+ status: "error",
+ category: "malformed",
+ });
+ expectEndpointError(
+ await thrownBy(fake.url),
+ "malformed",
+ "rerank response shape: expected 2 scores, got 1",
+ );
+ });
+
+ test("a duplicate index is malformed", async () => {
+ fake.setHandler(() => ({
+ status: 200,
+ body: {
+ results: [
+ { index: 0, relevance_score: 1 },
+ { index: 0, relevance_score: 0.5 },
+ ],
+ },
+ }));
+ expect((await runAgainst(fake.url))[0]).toMatchObject({
+ status: "error",
+ category: "malformed",
+ });
+ expectEndpointError(
+ await thrownBy(fake.url),
+ "malformed",
+ "rerank response: duplicate index 0",
+ );
+ });
+
+ test("an unwrapped object body and a missing score are malformed", async () => {
+ fake.setHandler(() => ({ status: 200, body: { nope: true } }));
+ expectEndpointError(
+ await thrownBy(fake.url),
+ "malformed",
+ "rerank response shape: expected an array or a { results: [...] } object",
+ );
+ fake.setHandler(() => ({ status: 200, body: [{ index: 0 }, { index: 1, score: 1 }] }));
+ expectEndpointError(
+ await thrownBy(fake.url),
+ "malformed",
+ "rerank response: item at index 0 has no finite relevance score",
+ );
+ });
+});
+
+describe("failures outside the cross-encoder", () => {
+ const cfg = enabledConfig("https://rerank.example.test/v1");
+
+ async function eventsFor(provider: RerankProvider): Promise<RerankTelemetryEvent[]> {
+ const events: RerankTelemetryEvent[] = [];
+ const out = await applyCrossEncoderRerank(RESULTS, "q", cfg, {
+ provider,
+ onTelemetry: (e) => events.push(e),
+ });
+ expect(out).toBe(RESULTS);
+ return events;
+ }
+
+ test("a provider throwing a plain Error is unclassified, named rather than hidden", async () => {
+ const events = await eventsFor({
+ name: "plain",
+ model: "plain-1",
+ async rerank() {
+ throw new Error("something odd");
+ },
+ });
+ expect(events).toEqual([
+ { status: "error", category: "unclassified", reason: "something odd", candidateCount: 2 },
+ ]);
+ });
+
+ test("a provider returning the wrong number of scores is malformed", async () => {
+ const events = await eventsFor({
+ name: "short",
+ model: "short-1",
+ async rerank() {
+ return [1];
+ },
+ });
+ expect(events).toEqual([
+ {
+ status: "error",
+ category: "malformed",
+ reason: "expected 2 scores, got 1",
+ candidateCount: 2,
+ },
+ ]);
+ });
+
+ test("a success event carries no category", async () => {
+ const events: RerankTelemetryEvent[] = [];
+ await applyCrossEncoderRerank(RESULTS, "q", cfg, {
+ provider: { name: "ok", model: "ok-1", rerank: async (_q, docs) => docs.map(() => 1) },
+ onTelemetry: (e) => events.push(e),
+ });
+ expect(events).toEqual([{ status: "applied", candidateCount: 2 }]);
+ });
+});
diff --git a/tests/core/search/rerank-sunset.test.ts b/tests/core/search/rerank-sunset.test.ts
new file mode 100644
index 00000000..568605a2
--- /dev/null
+++ b/tests/core/search/rerank-sunset.test.ts
@@ -0,0 +1,259 @@
+/**
+ * The rerank sunset survey and the skip it drives: once a surveyed model's
+ * announced shutdown date has passed, the cross-encoder stage makes no
+ * request and the answer names `rerank-model-sunset` on its trail. Every
+ * other verdict calls the endpoint exactly as before.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { Database } from "bun:sqlite";
+
+import type { EmbeddingSunsetSurvey } from "../../../src/core/search/embeddings/sunset.ts";
+import { parseIsoUtc } from "../../../src/core/brain/health/iso-time.ts";
+import { applyCrossEncoderRerank } from "../../../src/core/search/rerank/index.ts";
+import {
+ RERANK_SUNSET_SURVEY,
+ classifyRerankSunset,
+ rerankSunsetHasPassed,
+} from "../../../src/core/search/rerank/sunset.ts";
+import { RETRIEVAL_DEGRADATION } from "../../../src/core/search/retrieval-trail.ts";
+import { indexVault } from "../../../src/core/search/indexer.ts";
+import { search } from "../../../src/core/search/search.ts";
+import type { BrainSearchResult, ResolvedRerankConfig } from "../../../src/core/search/types.ts";
+import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
+
+const MODEL = "rerank-test";
+const NOW_MS = parseIsoUtc("2026-10-01");
+const PAST = "2026-01-01";
+const FUTURE = "2027-06-01";
+/** A model the shipped survey records as already shut down. */
+const RETIRED_SHIPPED_MODEL = "rerank-english-v2.0";
+/** A model the shipped survey records as an open-checkpoint negative. */
+const NEGATIVE_SHIPPED_MODEL = "zeroentropy/zerank-2-reranker";
+
+function result(id: number): BrainSearchResult {
+ return Object.freeze({
+ documentId: id,
+ chunkId: id,
+ path: `note-${id}.md`,
+ title: `Note ${id}`,
+ content: `content ${id}`,
+ startLine: 1,
+ endLine: 2,
+ score: 1 - id * 0.1,
+ keywordScore: 0.5,
+ semanticScore: 0.5,
+ linkBoost: 0,
+ recencyBoost: 0,
+ searchType: "hybrid" as const,
+ reasons: Object.freeze(["fts5_bm25: 0.500"]),
+ });
+}
+
+const RESULTS = Object.freeze([result(1), result(2)]);
+
+/** Rows in the persistent query cache of the index at `dbPath`. */
+function queryCacheRows(dbPath: string): number {
+ const db = new Database(dbPath, { readonly: true });
+ try {
+ return db.query<{ c: number }, []>("SELECT count(*) AS c FROM query_cache").get()?.c ?? 0;
+ } finally {
+ db.close();
+ }
+}
+
+function surveyWith(sunsetAt: string | null): EmbeddingSunsetSurvey {
+ return {
+ reviewedAt: "2026-09-30",
+ entries: [{ model: MODEL, sunsetAt, source: "test survey", note: "" }],
+ };
+}
+
+function rerankConfig(
+ baseUrl: string,
+ overrides: Partial<ResolvedRerankConfig> = {},
+): ResolvedRerankConfig {
+ return Object.freeze({
+ enabled: true,
+ kind: "openai-compat",
+ baseUrl,
+ model: MODEL,
+ envKey: null,
+ apiKey: "k",
+ topK: 20,
+ minScore: 0,
+ ...overrides,
+ });
+}
+
+describe("the shipped survey", () => {
+ test("every entry owes a source, models are unique and the review date parses", () => {
+ expect(Number.isFinite(parseIsoUtc(RERANK_SUNSET_SURVEY.reviewedAt))).toBe(true);
+ const models = RERANK_SUNSET_SURVEY.entries.map((e) => e.model);
+ expect(new Set(models).size).toBe(models.length);
+ for (const entry of RERANK_SUNSET_SURVEY.entries) {
+ expect(entry.source.trim().length).toBeGreaterThan(0);
+ if (entry.sunsetAt !== null) expect(Number.isFinite(parseIsoUtc(entry.sunsetAt))).toBe(true);
+ }
+ });
+
+ test("the retired second-generation Cohere rerank models are past their date", () => {
+ for (const model of [RETIRED_SHIPPED_MODEL, "rerank-multilingual-v2.0"]) {
+ const verdict = classifyRerankSunset(model, NOW_MS);
+ expect(verdict.state).toBe("announced");
+ expect(verdict.sunset_at).toBe("2025-04-30");
+ expect(rerankSunsetHasPassed(verdict)).toBe(true);
+ }
+ });
+
+ test("ZeroEntropy checkpoints are open-checkpoint negatives, never positives", () => {
+ const zerank = RERANK_SUNSET_SURVEY.entries.filter((e) => e.model.includes("zerank"));
+ expect(zerank.length).toBeGreaterThan(0);
+ for (const entry of zerank) expect(entry.sunsetAt).toBeNull();
+ expect(classifyRerankSunset(NEGATIVE_SHIPPED_MODEL, NOW_MS).state).toBe("none_announced");
+ });
+
+ test("the hosted ZeroEntropy ids are negatives; the two without a checkpoint stay unsurveyed", () => {
+ for (const model of ["zerank-1", "zerank-1-small"]) {
+ expect(classifyRerankSunset(model, NOW_MS).state).toBe("none_announced");
+ }
+ for (const model of ["zerank-2-small", "zerank-2-nano"]) {
+ expect(classifyRerankSunset(model, NOW_MS).state).toBe("unsurveyed");
+ }
+ });
+
+ test("only a passed announced date skips", () => {
+ expect(rerankSunsetHasPassed(classifyRerankSunset(MODEL, NOW_MS, surveyWith(PAST)))).toBe(true);
+ expect(rerankSunsetHasPassed(classifyRerankSunset(MODEL, NOW_MS, surveyWith(FUTURE)))).toBe(
+ false,
+ );
+ expect(rerankSunsetHasPassed(classifyRerankSunset(MODEL, NOW_MS, surveyWith(null)))).toBe(
+ false,
+ );
+ expect(rerankSunsetHasPassed(classifyRerankSunset("other", NOW_MS, surveyWith(PAST)))).toBe(
+ false,
+ );
+ expect(rerankSunsetHasPassed(classifyRerankSunset(null, NOW_MS))).toBe(false);
+ });
+});
+
+describe("the stage under an injected survey", () => {
+ let fake: FakeHttp;
+ beforeEach(async () => {
+ fake = await startFakeHttp();
+ fake.setHandler((req) => {
+ const docs = (req.body as { documents: string[] }).documents;
+ return { status: 200, body: docs.map((_d, index) => ({ index, score: index })) };
+ });
+ });
+ afterEach(async () => {
+ await fake.close();
+ });
+
+ async function run(
+ survey: EmbeddingSunsetSurvey,
+ overrides: Partial<ResolvedRerankConfig> = {},
+ ): Promise<{ out: ReadonlyArray<BrainSearchResult>; skipped: number }> {
+ let skipped = 0;
+ const out = await applyCrossEncoderRerank(RESULTS, "q", rerankConfig(fake.url, overrides), {
+ skipDecisionModel: true,
+ sunset: {
+ nowMs: NOW_MS,
+ survey,
+ onSkip: () => {
+ skipped += 1;
+ },
+ },
+ });
+ return { out, skipped };
+ }
+
+ test("a passed date makes no request and returns the heuristic order", async () => {
+ const { out, skipped } = await run(surveyWith(PAST));
+ expect(fake.callCount()).toBe(0);
+ expect(out).toBe(RESULTS);
+ expect(skipped).toBe(1);
+ });
+
+ test("a future date, an off-survey model and a negative call the endpoint", async () => {
+ const runs = await Promise.all(
+ [surveyWith(FUTURE), surveyWith(null), { reviewedAt: "2026-09-30", entries: [] }].map(
+ (survey) => run(survey),
+ ),
+ );
+ for (const { out, skipped } of runs) {
+ expect(skipped).toBe(0);
+ expect(out.map((r) => r.documentId)).toEqual([2, 1]);
+ }
+ expect(fake.callCount()).toBe(3);
+ });
+
+ test("the local kind never consults the survey", async () => {
+ // A passed date would skip an openai-compat request; the local
+ // reranker is this build's own and has no vendor date to pass.
+ const { skipped } = await run(surveyWith(PAST), { kind: "local" });
+ expect(skipped).toBe(0);
+ expect(fake.callCount()).toBe(0);
+ });
+});
+
+describe("through search()", () => {
+ let vault: string;
+ let dbPath: string;
+ let cleanup: () => void;
+ const realFetch = globalThis.fetch;
+ let calls = 0;
+
+ beforeEach(() => {
+ ({ vault, dbPath, cleanup } = createTempVault("rerank-sunset"));
+ writeMd(vault, "strong.md", "# Strong\n\nfox fox fox fox the quick brown fox jumps high.");
+ writeMd(vault, "weak.md", "# Weak\n\nA note mostly about cats, with one fox mention here.");
+ calls = 0;
+ globalThis.fetch = (async (_url: string, init: RequestInit) => {
+ calls += 1;
+ const body = JSON.parse(String(init.body)) as { documents: string[] };
+ const results = body.documents.map((_d, index) => ({ index, relevance_score: index }));
+ return new Response(JSON.stringify({ results }), { status: 200 });
+ }) as unknown as typeof fetch;
+ });
+ afterEach(() => {
+ globalThis.fetch = realFetch;
+ cleanup();
+ });
+
+ function cfg(model: string) {
+ return makeConfig({
+ vault,
+ dbPath,
+ cacheEnabled: true,
+ rerank: { enabled: true, baseUrl: "https://api.example.com/v1", model, apiKey: "k" },
+ });
+ }
+
+ test("a retired model is skipped, named on the trail, and the outcome is cached", async () => {
+ const config = cfg(RETIRED_SHIPPED_MODEL);
+ await indexVault(config);
+ const base = await search(makeConfig({ vault, dbPath }), { query: "fox", limit: 10 });
+ const first = await search(config, { query: "fox", limit: 10 });
+ expect(calls).toBe(0);
+ expect(first.results.map((r) => r.path)).toEqual(base.results.map((r) => r.path));
+ expect(first.retrievalTrail?.degraded).toContainEqual({
+ code: RETRIEVAL_DEGRADATION.rerankModelSunset,
+ });
+ // Unlike an endpoint failure, a passed date is a stable verdict, so
+ // the answer is written to the query cache.
+ expect(queryCacheRows(dbPath)).toBe(1);
+ const second = await search(config, { query: "fox", limit: 10 });
+ expect(calls).toBe(0);
+ expect(second.retrievalTrail).toEqual(first.retrievalTrail);
+ });
+
+ test("a surveyed negative calls the endpoint as before", async () => {
+ const config = cfg(NEGATIVE_SHIPPED_MODEL);
+ await indexVault(config);
+ const out = await search(config, { query: "fox", limit: 10 });
+ expect(calls).toBe(1);
+ expect(out.retrievalTrail).toBeUndefined();
+ });
+});
diff --git a/tests/core/search/rerank.search.test.ts b/tests/core/search/rerank.search.test.ts
index fb158f5c..5ea9a920 100644
--- a/tests/core/search/rerank.search.test.ts
+++ b/tests/core/search/rerank.search.test.ts
@@ -8,9 +8,14 @@
* fails closed; an endpoint error degrades gracefully with a warning.
*/
-import { test, expect, beforeEach, afterEach } from "bun:test";
+import { test, expect, beforeEach, afterEach, spyOn } from "bun:test";
import { indexVault } from "../../../src/core/search/indexer.ts";
+import { LocalRerankProvider } from "../../../src/core/search/rerank/local.ts";
+import {
+ describeRetrievalDegradation,
+ RETRIEVAL_DEGRADATION,
+} from "../../../src/core/search/retrieval-trail.ts";
import { search } from "../../../src/core/search/search.ts";
import { SearchError } from "../../../src/core/search/types.ts";
import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
@@ -93,3 +98,94 @@ test("enabled + endpoint error degrades to heuristic order with a warning", asyn
expect(out.results.map((r) => r.path)).toEqual(base.results.map((r) => r.path));
expect(out.warnings.some((w) => w.startsWith("rerank_degraded:"))).toBe(true);
});
+
+// ─── the rerank liveness code on the retrieval trail ─────────────────────────
+
+/** A 503 endpoint that counts the requests it answered. */
+function failingRerankFetch(): { calls: () => number } {
+ let calls = 0;
+ globalThis.fetch = (async () => {
+ calls += 1;
+ return new Response("upstream boom", { status: 503 });
+ }) as unknown as typeof fetch;
+ return { calls: () => calls };
+}
+
+test("a failed rerank names rerank-provider-unavailable with its category", async () => {
+ const cfg = makeConfig({ vault, dbPath, rerank: ENABLED });
+ await indexVault(cfg);
+ const base = await search(makeConfig({ vault, dbPath }), { query: "fox", limit: 10 });
+ failingRerankFetch();
+ const out = await search(cfg, { query: "fox", limit: 10 });
+ expect(out.results.map((r) => r.path)).toEqual(base.results.map((r) => r.path));
+ // The human signal is byte-identical to v1.65.0.
+ expect(out.warnings).toContain("rerank_degraded: rerank HTTP 503: upstream boom");
+ expect(out.retrievalTrail?.degraded).toContainEqual({
+ code: RETRIEVAL_DEGRADATION.rerankProviderUnavailable,
+ detail: { category: "transient" },
+ });
+});
+
+test("a failed rerank is served but never cached, so the next query retries", async () => {
+ const cfg = makeConfig({ vault, dbPath, rerank: ENABLED, cacheEnabled: true });
+ await indexVault(cfg);
+ const endpoint = failingRerankFetch();
+ await search(cfg, { query: "fox", limit: 10 });
+ const second = await search(cfg, { query: "fox", limit: 10 });
+ expect(endpoint.calls()).toBe(2);
+ expect(second.retrievalTrail?.degraded.map((d) => d.code)).toContain(
+ RETRIEVAL_DEGRADATION.rerankProviderUnavailable,
+ );
+});
+
+test("a healthy rerank is cached as before", async () => {
+ const cfg = makeConfig({ vault, dbPath, rerank: ENABLED, cacheEnabled: true });
+ await indexVault(cfg);
+ let calls = 0;
+ stubRerankFetch("cats");
+ const scoring = globalThis.fetch;
+ globalThis.fetch = (async (...args: Parameters<typeof fetch>) => {
+ calls += 1;
+ return scoring(...args);
+ }) as unknown as typeof fetch;
+ await search(cfg, { query: "fox", limit: 10 });
+ await search(cfg, { query: "fox", limit: 10 });
+ expect(calls).toBe(1);
+});
+
+test("a healthy rerank and a disabled rerank carry no trail", async () => {
+ const enabled = makeConfig({ vault, dbPath, rerank: ENABLED });
+ await indexVault(enabled);
+ stubRerankFetch("cats");
+ expect((await search(enabled, { query: "fox", limit: 10 })).retrievalTrail).toBeUndefined();
+ const disabled = makeConfig({ vault, dbPath });
+ expect((await search(disabled, { query: "fox", limit: 10 })).retrievalTrail).toBeUndefined();
+});
+
+test("a failed local reranker records the same code, unclassified and uncached", async () => {
+ const cfg = makeConfig({
+ vault,
+ dbPath,
+ rerank: { enabled: true, kind: "local", topK: 10 },
+ cacheEnabled: true,
+ });
+ await indexVault(cfg);
+ const failing = spyOn(LocalRerankProvider.prototype, "rerank").mockImplementation(() =>
+ Promise.reject(new Error("model failed to load")),
+ );
+ try {
+ await search(cfg, { query: "fox", limit: 10 });
+ const second = await search(cfg, { query: "fox", limit: 10 });
+ expect(failing).toHaveBeenCalledTimes(2);
+ expect(second.retrievalTrail?.degraded).toContainEqual({
+ code: RETRIEVAL_DEGRADATION.rerankProviderUnavailable,
+ detail: { category: "unclassified" },
+ });
+ } finally {
+ failing.mockRestore();
+ }
+ // The local reranker has no endpoint, so the sentence must not name one.
+ expect(describeRetrievalDegradation(RETRIEVAL_DEGRADATION.rerankProviderUnavailable)).not.toMatch(
+ /endpoint/u,
+ );
+});
diff --git a/tests/core/search/rerank.test.ts b/tests/core/search/rerank.test.ts
index e3ed2e06..a3626fee 100644
--- a/tests/core/search/rerank.test.ts
+++ b/tests/core/search/rerank.test.ts
@@ -18,6 +18,10 @@ import {
type RerankTelemetryEvent,
} from "../../../src/core/search/rerank/index.ts";
import type { RerankProvider } from "../../../src/core/search/rerank/contract.ts";
+import {
+ RERANK_FAILURE_CATEGORY,
+ RerankEndpointError,
+} from "../../../src/core/search/rerank/failure.ts";
import { SearchError } from "../../../src/core/search/types.ts";
import type { BrainSearchResult, ResolvedRerankConfig } from "../../../src/core/search/types.ts";
@@ -115,7 +119,10 @@ describe("applyCrossEncoderRerank", () => {
name: "boom",
model: "boom-1",
async rerank() {
- throw new SearchError("RERANK_PROVIDER_HTTP", "rerank HTTP 503: unavailable");
+ throw new RerankEndpointError("rerank HTTP 503: unavailable", {
+ category: RERANK_FAILURE_CATEGORY.transient,
+ status: 503,
+ });
},
};
const events: RerankTelemetryEvent[] = [];
@@ -125,8 +132,12 @@ describe("applyCrossEncoderRerank", () => {
});
expect(out.map((r) => r.documentId)).toEqual([1, 2]); // unchanged order
expect(events).toHaveLength(1);
- expect(events[0]!.status).toBe("error");
- expect(events[0]!.reason).toMatch(/503/);
+ expect(events[0]).toEqual({
+ status: "error",
+ category: "transient",
+ reason: "rerank HTTP 503: unavailable",
+ candidateCount: 2,
+ });
});
test("minScore floor: a below-floor doc sinks below qualifying ones but is kept", async () => {
diff --git a/tests/core/search/retrieval-trail.test.ts b/tests/core/search/retrieval-trail.test.ts
index c961a6a6..c8687d2f 100644
--- a/tests/core/search/retrieval-trail.test.ts
+++ b/tests/core/search/retrieval-trail.test.ts
@@ -70,6 +70,16 @@ test("every degradation code renders its own sentence", () => {
expect(new Set(sentences).size).toBe(RETRIEVAL_DEGRADATION_CODES.length);
});
+/** Names no rerank vendor may appear under in a trail sentence. */
+const RERANK_VENDOR_NAMES = /cohere|jina|voyage|zeroentropy|zerank|mixedbread|openai/iu;
+
+test("the rerank liveness code is kebab-case and its sentence names no provider", () => {
+ expect(RETRIEVAL_DEGRADATION.rerankProviderUnavailable).toBe("rerank-provider-unavailable");
+ expect(isRetrievalDegradationCode("rerank-provider-unavailable")).toBe(true);
+ const sentence = describeRetrievalDegradation(RETRIEVAL_DEGRADATION.rerankProviderUnavailable);
+ expect(sentence).not.toMatch(RERANK_VENDOR_NAMES);
+});
+
test("the guard rejects a near miss", () => {
expect(isRetrievalDegradationCode(RETRIEVAL_DEGRADATION.hybridDegraded)).toBe(true);
expect(isRetrievalDegradationCode("hybrid_degraded")).toBe(false);
diff --git a/tests/docs/retrieval-trail-doc.test.ts b/tests/docs/retrieval-trail-doc.test.ts
new file mode 100644
index 00000000..0b628413
--- /dev/null
+++ b/tests/docs/retrieval-trail-doc.test.ts
@@ -0,0 +1,42 @@
+/**
+ * Every retrieval-trail code a `--json` or `brain_search` answer can carry
+ * has its own row in the trail table of `docs/cli-reference.md`, and so
+ * does every rerank failure category `detail.category` can name, so a
+ * code or category shipped without its documentation fails here, not in
+ * a reader's client.
+ */
+
+import { expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { RERANK_FAILURE_CATEGORIES } from "../../src/core/search/rerank/failure.ts";
+import { RETRIEVAL_DEGRADATION_CODES } from "../../src/core/search/retrieval-trail.ts";
+
+const CLI_REFERENCE = readFileSync(
+ join(import.meta.dir, "..", "..", "docs", "cli-reference.md"),
+ "utf8",
+);
+
+/** The table whose header row is `header`, up to the blank line after it. */
+function tableUnder(header: string): string {
+ const start = CLI_REFERENCE.indexOf(header);
+ expect(start).toBeGreaterThanOrEqual(0);
+ const end = CLI_REFERENCE.indexOf("\n\n", start);
+ return CLI_REFERENCE.slice(start, end === -1 ? undefined : end);
+}
+
+/** The tokens of `tokens` that head no row of `table`. */
+function withoutRow(table: string, tokens: ReadonlyArray<string>): ReadonlyArray<string> {
+ return tokens.filter((token) => !table.includes(`\n| \`${token}\` |`));
+}
+
+test("every retrieval degradation code has a row in the trail table", () => {
+ const table = tableUnder("| Code | The narrowing it reports |");
+ expect(withoutRow(table, RETRIEVAL_DEGRADATION_CODES)).toEqual([]);
+});
+
+test("every rerank failure category has a row in the category table", () => {
+ const table = tableUnder("| Category | The failure it names |");
+ expect(withoutRow(table, RERANK_FAILURE_CATEGORIES)).toEqual([]);
+});
diff --git a/tests/helpers/tool-error-envelope.ts b/tests/helpers/tool-error-envelope.ts
new file mode 100644
index 00000000..4486a73c
--- /dev/null
+++ b/tests/helpers/tool-error-envelope.ts
@@ -0,0 +1,70 @@
+/**
+ * Readers for the two places an MCP failure carries its stable code.
+ *
+ * Channel A, a JSON-RPC error response: `error.data.code`.
+ * Channel B, an `isError: true` tool result:
+ * `result._meta["open-second-brain/error"].code`, beside the schema tag.
+ *
+ * Both readers THROW a named {@link ToolErrorEnvelopeMissing} when the
+ * member is absent or malformed instead of returning `undefined`, so a
+ * test asserting a code cannot pass by comparing `undefined` with a
+ * missing expectation, and a failure names exactly which piece of the
+ * envelope was not there. The code itself is returned as the raw string
+ * the wire carried, so an unexpected value shows up in the assertion
+ * diff rather than as a second, less specific error.
+ */
+
+import { TOOL_ERROR_META_KEY, TOOL_ERROR_SCHEMA } from "../../src/mcp/tool-error-codes.ts";
+
+/** A required member of the error envelope was absent or of the wrong type. */
+export class ToolErrorEnvelopeMissing extends Error {
+ constructor(what: string, received: unknown) {
+ super(`${what} is missing from the error envelope; received ${JSON.stringify(received)}`);
+ this.name = "ToolErrorEnvelopeMissing";
+ }
+}
+
+function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
+ return value !== null && typeof value === "object" && !Array.isArray(value);
+}
+
+/** `value[key]` as a record, or a named throw naming `what`. */
+function recordAt(value: unknown, key: string, what: string): Readonly<Record<string, unknown>> {
+ const member = isRecord(value) ? value[key] : undefined;
+ if (!isRecord(member)) throw new ToolErrorEnvelopeMissing(what, value);
+ return member;
+}
+
+/** `value[key]` as a string, or a named throw naming `what`. */
+function stringAt(value: Readonly<Record<string, unknown>>, key: string, what: string): string {
+ const member = value[key];
+ if (typeof member !== "string") throw new ToolErrorEnvelopeMissing(what, value);
+ return member;
+}
+
+/**
+ * The code an `isError` tool result carries on `_meta`.
+ *
+ * Accepts the tool result itself (`response.result`), and also checks the
+ * payload's schema tag, because a payload under the right key with the
+ * wrong schema is a different envelope.
+ */
+export function readToolErrorCode(result: unknown): string {
+ const meta = recordAt(result, "_meta", "result._meta");
+ const payload = recordAt(meta, TOOL_ERROR_META_KEY, `result._meta["${TOOL_ERROR_META_KEY}"]`);
+ const schema = stringAt(payload, "schema", `result._meta["${TOOL_ERROR_META_KEY}"].schema`);
+ if (schema !== TOOL_ERROR_SCHEMA) {
+ throw new ToolErrorEnvelopeMissing(
+ `result._meta["${TOOL_ERROR_META_KEY}"].schema ${TOOL_ERROR_SCHEMA}`,
+ payload,
+ );
+ }
+ return stringAt(payload, "code", `result._meta["${TOOL_ERROR_META_KEY}"].code`);
+}
+
+/** The code a JSON-RPC error response carries on `error.data`. */
+export function readRpcErrorCode(response: unknown): string {
+ const error = recordAt(response, "error", "response.error");
+ const data = recordAt(error, "data", "response.error.data");
+ return stringAt(data, "code", "response.error.data.code");
+}
diff --git a/tests/mcp/http-transport.test.ts b/tests/mcp/http-transport.test.ts
index 56943be7..e7df41e0 100644
--- a/tests/mcp/http-transport.test.ts
+++ b/tests/mcp/http-transport.test.ts
@@ -1,10 +1,11 @@
-import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { request } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { JSONRPC_VERSION, PROTOCOL_VERSION, startHttp } from "../../src/mcp/index.ts";
+import { MCPServer } from "../../src/mcp/server.ts";
interface RawResponse {
readonly status: number;
@@ -268,4 +269,31 @@ describe("Streamable HTTP MCP transport", () => {
await handle.close();
}
});
+
+ test("a throw that escapes the dispatch is classified, redacted and named", async () => {
+ // The catch-all behind `handleHttpRequest`: the one path where raw
+ // exception prose could leave without the redactor or a code.
+ const dispatch = spyOn(MCPServer.prototype, "handleRequest").mockImplementation(() => {
+ throw new Error(`boom at ${join(vault, "private.md")}`);
+ });
+ const lines: string[] = [];
+ const stderr = spyOn(process.stderr, "write").mockImplementation((chunk) => {
+ lines.push(String(chunk));
+ return true;
+ });
+ const handle = await startHttp({ vault }, { apiKey: "secret", host: "127.0.0.1", port: 0 });
+ try {
+ const res = await post(handle.url, rpc("ping", 4), { key: "secret" });
+ const body = await responseJson(res);
+ expect(body.error.code).toBe(-32603);
+ expect(body.error.data).toEqual({ code: "internal_error" });
+ expect(body.error.message).toStartWith("internal error: boom at ");
+ expect(body.error.message).not.toContain(vault);
+ expect(lines).toEqual(["warning: unclassified tool error mapped to internal_error: Error\n"]);
+ } finally {
+ stderr.mockRestore();
+ dispatch.mockRestore();
+ await handle.close();
+ }
+ });
});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 5a075f47..61d815b5 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -13,6 +13,7 @@ import {
slugify,
} from "../../src/mcp/index.ts";
import { createPluginRepo, createSandboxVault } from "../helpers/fixtures.ts";
+import { readToolErrorCode } from "../helpers/tool-error-envelope.ts";
import { REDACTION_PLACEHOLDER } from "../../src/core/redactor.ts";
import { PARTNER_CODEGRAPH_DISABLED_ENV } from "../../src/core/config.ts";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
@@ -641,6 +642,9 @@ describe("tool calls", () => {
expect(r.result.isError).toBe(true);
expect(r.result.structuredContent).toBeUndefined();
expect(r.result.content[0].text).toContain("bad_contract output contract failed");
+ // The code rides on `_meta`, never on `structuredContent`, which a
+ // strict client would validate against the very schema that failed.
+ expect(readToolErrorCode(r.result)).toBe("output_contract_failed");
});
});
diff --git a/tests/mcp/progress-token.test.ts b/tests/mcp/progress-token.test.ts
index 9421dd77..c7b09567 100644
--- a/tests/mcp/progress-token.test.ts
+++ b/tests/mcp/progress-token.test.ts
@@ -31,7 +31,11 @@ import {
serveStdioFromString,
startHttp,
} from "../../src/mcp/index.ts";
-import { PROGRESS_META_KEY, PROGRESS_NOTIFICATION_METHOD } from "../../src/mcp/progress.ts";
+import {
+ PROGRESS_META_KEY,
+ PROGRESS_NOTIFICATION_METHOD,
+ withProgressRefusal,
+} from "../../src/mcp/progress.ts";
import {
isProgressKind,
PROGRESS_KIND,
@@ -354,3 +358,13 @@ describe("HTTP refuses a progress token by name", () => {
}
});
});
+
+describe("withProgressRefusal", () => {
+ // The merge beside an error code is covered end to end by
+ // tool-error-envelope.test.ts; this pins the no-refusal identity, which
+ // keeps a call that asked for no progress byte-identical.
+ test("no refusal returns the very same result object", () => {
+ const ok = { content: [], isError: false };
+ expect(withProgressRefusal(ok, undefined)).toBe(ok);
+ });
+});
diff --git a/tests/mcp/search-error-mapping.test.ts b/tests/mcp/search-error-mapping.test.ts
index f40138ee..284abf2a 100644
--- a/tests/mcp/search-error-mapping.test.ts
+++ b/tests/mcp/search-error-mapping.test.ts
@@ -5,10 +5,19 @@
*/
import { test, expect } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { searchErrorToMcp } from "../../src/mcp/search-tools.ts";
-import { EMBEDDING_QUOTA_MESSAGE, SearchError } from "../../src/core/search/types.ts";
-import { INTERNAL_ERROR } from "../../src/mcp/protocol.ts";
+import {
+ EMBEDDING_QUOTA_MESSAGE,
+ SEARCH_ERROR_CODES,
+ SearchError,
+} from "../../src/core/search/types.ts";
+import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../../src/mcp/protocol.ts";
+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";
+import type { ServerContext } from "../../src/mcp/tool-contract.ts";
test("EMBEDDING_QUOTA_EXHAUSTED maps to the actionable billing message", () => {
const mcp = searchErrorToMcp(new SearchError("EMBEDDING_QUOTA_EXHAUSTED", "internal detail"));
@@ -20,3 +29,51 @@ test("a generic provider HTTP error keeps its own message", () => {
const mcp = searchErrorToMcp(new SearchError("EMBEDDING_PROVIDER_HTTP", "embedding HTTP 500"));
expect(mcp.message).toContain("embedding HTTP 500");
});
+
+// ----- the SearchError code reaches the wire ---------------------------------
+
+test("every SearchError code rides in data.code, verbatim", () => {
+ for (const code of SEARCH_ERROR_CODES) {
+ const mcp = searchErrorToMcp(new SearchError(code, "detail"));
+ expect(mcp.data).toEqual({ code });
+ }
+});
+
+test("the carried code leaves the numeric code and the message unchanged", () => {
+ const invalid = searchErrorToMcp(new SearchError("INVALID_INPUT", "bad input"));
+ expect(invalid.code).toBe(INVALID_PARAMS);
+ expect(invalid.message).toBe("bad input");
+ const quota = searchErrorToMcp(new SearchError("EMBEDDING_QUOTA_EXHAUSTED", "internal detail"));
+ expect(quota.code).toBe(INTERNAL_ERROR);
+ expect(quota.message).toBe(EMBEDDING_QUOTA_MESSAGE);
+});
+
+test("the fallback arm keeps its legacy [CODE] suffix beside the carried code", () => {
+ const mcp = searchErrorToMcp(new SearchError("SCHEMA_MISMATCH", "index schema is stale"));
+ expect(mcp.code).toBe(INTERNAL_ERROR);
+ expect(mcp.message).toBe("index schema is stale [SCHEMA_MISMATCH]");
+ expect(mcp.data).toEqual({ code: "SCHEMA_MISMATCH" });
+});
+
+test("the session-grep time bounds carry the SearchError code too", async () => {
+ const scratch = mkdtempSync(join(tmpdir(), "o2b-search-error-"));
+ try {
+ const vault = join(scratch, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ const ctx: ServerContext = { vault, configPath: null, repoRoot: null };
+ const grep = findTool(buildToolTable("full"), "brain_session_grep");
+ let thrown: unknown;
+ try {
+ await grep.handler(ctx, { query: "needle", since: "2026-05-02", before: "2026-05-01" });
+ } catch (exc) {
+ thrown = exc;
+ }
+ expect(thrown).toBeInstanceOf(MCPError);
+ const err = thrown as MCPError;
+ expect(err.code).toBe(INVALID_PARAMS);
+ expect(err.message).toBe("'since' must not be after 'until'");
+ expect(err.data).toEqual({ code: "INVALID_INPUT" });
+ } finally {
+ rmSync(scratch, { recursive: true, force: true });
+ }
+});
diff --git a/tests/mcp/surface-error-codes.test.ts b/tests/mcp/surface-error-codes.test.ts
new file mode 100644
index 00000000..ff82c36c
--- /dev/null
+++ b/tests/mcp/surface-error-codes.test.ts
@@ -0,0 +1,555 @@
+/**
+ * Per-surface error codes at the MCP boundary.
+ *
+ * The boundary seam can only see a class; the surfaces below know a more
+ * precise reason and name it in `error.data.code` from the closed registry
+ * in `src/mcp/tool-error-codes.ts`. Every message stays byte-identical to
+ * the one it replaced, because agents and the Hermes bridge parse it.
+ *
+ * Handlers are called directly: the precise code is set at the throw, and
+ * the seam keeps a thrower-supplied code untouched.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { brainConfigPath } from "../../src/core/brain/paths.ts";
+import { writePreference } from "../../src/core/brain/preference.ts";
+import { createTriggers } from "../../src/core/brain/triggers/store.ts";
+import type { InsightCandidate } from "../../src/core/brain/triggers/types.ts";
+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.ts";
+import { GATE_MODE } from "../../src/core/integrity/stamp.ts";
+import { assertKnownArguments } from "../../src/mcp/argument-guard.ts";
+import { FEEDBACK_TOOLS } from "../../src/mcp/brain/feedback-tools.ts";
+import { LIFECYCLE_FILE_TOOLS } from "../../src/mcp/brain/lifecycle-file-tools.ts";
+import { AGENT_SCOPE_ARG_NAME, coerceAgentScope } from "../../src/mcp/coerce.ts";
+import { OWNER_SCOPE_REFUSAL } from "../../src/mcp/owner-scope-refusal.ts";
+import { INVALID_PARAMS, MCPError } from "../../src/mcp/protocol.ts";
+import { assertNoCallerSuppliedReach, REACH_REFUSAL } from "../../src/mcp/reach-refusal.ts";
+import { MCPServer } from "../../src/mcp/server.ts";
+import { SKILL_TOOLS } from "../../src/mcp/skill-tools.ts";
+import type { ServerContext, ToolDefinition } from "../../src/mcp/tool-contract.ts";
+import { isToolErrorCode } from "../../src/mcp/tool-error-codes.ts";
+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";
+import { readRpcErrorCode } from "../helpers/tool-error-envelope.ts";
+
+const TOOLS = buildToolTable("full");
+
+/** The `MCPError` a call raised; fails the test when it answered instead. */
+async function raised(run: () => unknown): Promise<MCPError> {
+ let thrown: unknown;
+ try {
+ await run();
+ } catch (exc) {
+ thrown = exc;
+ }
+ expect(thrown).toBeInstanceOf(MCPError);
+ return thrown as MCPError;
+}
+
+/** The code a raised error carries, checked against the closed registry. */
+function codeOf(err: MCPError): string {
+ const code = (err.data as { readonly code?: unknown } | undefined)?.code;
+ expect(typeof code).toBe("string");
+ expect(isToolErrorCode(code)).toBe(true);
+ return code as string;
+}
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-surface-codes-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: "${vault}"\n`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+// ----- skills -----------------------------------------------------------------
+
+function skillCtx(): ServerContext {
+ const skillDir = join(tmp, "skills", "demo-skill");
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(
+ join(skillDir, "SKILL.md"),
+ "---\nname: demo-skill\ndescription: Demonstration skill.\n---\n\n# Demo\n",
+ );
+ return { vault, configPath: null, repoRoot: tmp };
+}
+
+const getSkill = (): ToolDefinition => SKILL_TOOLS.find((t) => t.name === "get_skill")!;
+
+describe("skill errors", () => {
+ test("an unknown skill answers unknown_skill", async () => {
+ const err = await raised(() => getSkill().handler(skillCtx(), { name: "no-such-skill" }));
+ expect(err.code).toBe(INVALID_PARAMS);
+ expect(err.message).toBe("unknown skill: no-such-skill. Known skills: demo-skill");
+ expect(codeOf(err)).toBe("unknown_skill");
+ });
+
+ test("a missing skill file answers skill_not_found", async () => {
+ const err = await raised(() =>
+ getSkill().handler(skillCtx(), { name: "demo-skill", file_path: "missing.md" }),
+ );
+ expect(err.message).toBe("skill file not found: missing.md");
+ expect(codeOf(err)).toBe("skill_not_found");
+ });
+
+ test("an escaping skill file path answers skill_invalid_path", async () => {
+ const err = await raised(() =>
+ getSkill().handler(skillCtx(), { name: "demo-skill", file_path: "../outside.md" }),
+ );
+ expect(err.message).toBe("skill file path must stay inside the skill directory");
+ expect(codeOf(err)).toBe("skill_invalid_path");
+ });
+});
+
+// ----- workspace refusals ------------------------------------------------------
+
+const OWNER_A = "agent-a";
+const OWNER_B = "agent-b";
+const TRIGGER_NOW = new Date("2099-06-03T10:00:00Z");
+
+function candidate(source: string): InsightCandidate {
+ return {
+ kind: "contradiction",
+ urgency: "high",
+ reason: `${source} contradicts pref-other`,
+ suggestedAction: "Review the pair",
+ sourceArtifacts: [`[[${source}]]`],
+ contextSnippets: [],
+ cooldownKey: `contradiction:${source}:pref-other`,
+ };
+}
+
+function workspaceCtx(agentName?: string): ServerContext {
+ return { vault, configPath, repoRoot: null, ...(agentName ? { agentName } : {}) };
+}
+
+describe("workspace refusals", () => {
+ test("an unknown brain_intention operation answers unknown_operation", async () => {
+ const err = await raised(() =>
+ findTool(TOOLS, "brain_intention").handler(workspaceCtx(), {
+ operation: "rename",
+ scope: "w",
+ }),
+ );
+ expect(err.message).toBe("brain_intention operation must be one of: set, show, list, move");
+ expect(codeOf(err)).toBe("unknown_operation");
+ });
+
+ test("an unknown brain_trigger operation answers unknown_operation", async () => {
+ const err = await raised(() =>
+ findTool(TOOLS, "brain_trigger").handler(workspaceCtx(), { operation: "rename" }),
+ );
+ expect(err.message).toStartWith("brain_trigger operation must be one of: ");
+ expect(codeOf(err)).toBe("unknown_operation");
+ });
+
+ test("an unknown trigger status answers invalid_status", async () => {
+ const err = await raised(() =>
+ findTool(TOOLS, "brain_trigger").handler(workspaceCtx(), {
+ operation: "list",
+ status: "bogus",
+ }),
+ );
+ expect(err.message).toBe("brain_trigger: unknown status 'bogus'");
+ expect(codeOf(err)).toBe("invalid_status");
+ });
+
+ test("an absent id and an id the caller may not see answer the same code and message", async () => {
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ writePreference(vault, {
+ slug: "owned-by-a",
+ topic: "owned-by-a",
+ principle: "principle for owned-by-a",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: ["[[sig-2026-05-01-owned-by-a]]"],
+ confirmed_at: "2026-05-02T00:00:00Z",
+ applied_count: 1,
+ violated_count: 0,
+ last_evidence_at: "2026-05-02T00:00:00Z",
+ confidence: BRAIN_CONFIDENCE.high,
+ confidence_value: 0.8,
+ owner: OWNER_A,
+ });
+ const { created } = createTriggers(vault, [candidate("pref-owned-by-a")], { now: TRIGGER_NOW });
+ const hiddenId = created[0]!.id;
+ writeFileSync(
+ brainConfigPath(vault),
+ `schema_version: 1\nintegrity:\n owner_scope_delivery: ${GATE_MODE.fail}\n`,
+ );
+ const absentId = `${hiddenId.slice(0, -4)}zzzz`;
+ const trigger = findTool(TOOLS, "brain_trigger");
+
+ const hidden = await raised(() =>
+ trigger.handler(workspaceCtx(OWNER_B), { operation: "acknowledge", id: hiddenId }),
+ );
+ const absent = await raised(() =>
+ trigger.handler(workspaceCtx(OWNER_B), { operation: "acknowledge", id: absentId }),
+ );
+
+ expect(codeOf(hidden)).toBe("trigger_transition_refused");
+ expect(codeOf(absent)).toBe("trigger_transition_refused");
+ expect(hidden.message.replace(hiddenId, "<id>")).toBe(absent.message.replace(absentId, "<id>"));
+ expect(hidden.data).toEqual(absent.data);
+ });
+});
+
+// ----- write session ----------------------------------------------------------
+
+const writeSession = (): ToolDefinition => findTool(TOOLS, "brain_write_session");
+const sessionCtx = (): ServerContext => ({ vault, configPath, repoRoot: null });
+
+describe("write-session codes", () => {
+ test("an op that needs a session but names none answers session_id_required", async () => {
+ const err = await raised(() => writeSession().handler(sessionCtx(), { op: "approve" }));
+ expect(err.message).toBe("brain_write_session: op 'approve' requires session_id");
+ expect(codeOf(err)).toBe("session_id_required");
+ });
+
+ test("an unknown session id answers write_session_unknown on every op", async () => {
+ const errors = await Promise.all(
+ ["approve", "abandon", "status"].map((op) =>
+ raised(() => writeSession().handler(sessionCtx(), { op, session_id: "ws-does-not-exist" })),
+ ),
+ );
+ for (const err of errors) {
+ expect(err.message).toBe("unknown write-session: ws-does-not-exist");
+ expect(codeOf(err)).toBe("write_session_unknown");
+ }
+ });
+
+ test("a terminal session answers write_session_terminal", async () => {
+ const opened = (await writeSession().handler(sessionCtx(), {
+ op: "open",
+ kind: "artifact",
+ target: "Brain/notes/terminal.md",
+ agent: "mcp-agent",
+ })) as Record<string, unknown>;
+ const id = opened["session_id"] as string;
+ await writeSession().handler(sessionCtx(), { op: "abandon", session_id: id });
+
+ const err = await raised(() =>
+ writeSession().handler(sessionCtx(), { op: "approve", session_id: id }),
+ );
+ expect(err.message).toStartWith(`write-session ${id} is terminal (`);
+ expect(codeOf(err)).toBe("write_session_terminal");
+ });
+});
+
+describe("write-session codes at the boundary", () => {
+ test("a structured request failure gains the invalid_params default after its errors", async () => {
+ const server = new MCPServer({ vault });
+ const response = await server.handleRequest({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/call",
+ params: {
+ name: "brain_write_session",
+ arguments: { op: "open", kind: "artifact", target: "../outside.md", agent: "mcp-agent" },
+ },
+ });
+ expect(response?.error?.code).toBe(INVALID_PARAMS);
+ expect(response?.error?.message).toStartWith("target rejected: ");
+ // Byte-identical to v1.65.0 up to the default: the handler hands over
+ // the list alone, and the boundary seam adds `invalid_params` after it.
+ const data = response?.error?.data as {
+ readonly errors: ReadonlyArray<unknown>;
+ readonly code: string;
+ };
+ expect(Object.keys(data)).toEqual(["errors", "code"]);
+ expect(data.errors.length).toBeGreaterThan(0);
+ expect(readRpcErrorCode(response)).toBe("invalid_params");
+ });
+});
+
+// ----- argument guard, reach refusal, owner-scope refusal -----------------------
+
+describe("refusal codes", () => {
+ const CLOSED_TOOL: ToolDefinition = {
+ name: "demo_tool",
+ description: "A demo tool.",
+ inputSchema: {
+ type: "object",
+ properties: { query: { type: "string", description: "The search text." } },
+ additionalProperties: false,
+ },
+ handler: () => ({}),
+ };
+
+ test("an undeclared argument answers unknown_argument with its data unchanged", async () => {
+ const err = await raised(() => assertKnownArguments(CLOSED_TOOL, { quiery: "x" }));
+ expect(codeOf(err)).toBe("unknown_argument");
+ expect(err.data).toEqual({
+ tool: "demo_tool",
+ unknown_arguments: [{ name: "quiery", suggestion: "query" }],
+ declared_arguments: ["query"],
+ code: "unknown_argument",
+ });
+ });
+
+ test("a caller-supplied reach answers its own refusal token", async () => {
+ const err = await raised(() => assertNoCallerSuppliedReach(CLOSED_TOOL, { reach: "local" }));
+ expect(codeOf(err)).toBe(REACH_REFUSAL);
+ const data = err.data as Record<string, unknown>;
+ expect(data["refused_arguments"]).toEqual(["reach"]);
+ expect(data["tool"]).toBe("demo_tool");
+ });
+
+ test("an owner-scope refusal answers the outcome it names", async () => {
+ writeFileSync(
+ brainConfigPath(vault),
+ `schema_version: 1\nintegrity:\n owner_scope_delivery: ${GATE_MODE.fail}\n`,
+ );
+ const foreign = await raised(() =>
+ coerceAgentScope(
+ { vault, agentName: "agent-b" },
+ { [AGENT_SCOPE_ARG_NAME]: "agent-a" },
+ false,
+ ),
+ );
+ expect(foreign.message).toContain(OWNER_SCOPE_REFUSAL.foreignOwner);
+ expect(codeOf(foreign)).toBe(OWNER_SCOPE_REFUSAL.foreignOwner);
+
+ const unresolved = await raised(() =>
+ coerceAgentScope({ vault, agentName: "agent" }, { [AGENT_SCOPE_ARG_NAME]: "agent-a" }, false),
+ );
+ expect(unresolved.message).toContain(OWNER_SCOPE_REFUSAL.unresolvedIdentity);
+ expect(codeOf(unresolved)).toBe(OWNER_SCOPE_REFUSAL.unresolvedIdentity);
+ });
+});
+
+// ----- codes a refusing site supplies itself ------------------------------------
+
+const expireTool = (): ToolDefinition => FEEDBACK_TOOLS.find((t) => t.name === "brain_expire")!;
+const stubTool = (): ToolDefinition =>
+ LIFECYCLE_FILE_TOOLS.find((t) => t.name === "brain_scaffold_stub")!;
+
+describe("thrower-supplied codes are registry members", () => {
+ // The boundary keeps a code the refusing site chose, so each of these
+ // producers has to name a registered token itself: a client narrowing
+ // `error.data.code` with `isToolErrorCode` would reject anything else.
+ test("each brain_expire refusal answers a registered code", async () => {
+ bootstrapBrain(vault, { configPath });
+ const ctx: ServerContext = { vault, configPath, repoRoot: null };
+ const refusal = (args: Record<string, unknown>) =>
+ raised(() => expireTool().handler(ctx, args));
+ const [badDate, missing, unaddressable] = await Promise.all([
+ refusal({ id: "sig-2026-01-01-demo", expires: "soon" }),
+ refusal({ id: "sig-2026-01-01-demo", expires: "2026-12-31" }),
+ refusal({ id: "not-an-id", expires: "2026-12-31" }),
+ ]);
+ expect(codeOf(badDate)).toBe("ExpirationValueError");
+ expect(codeOf(missing)).toBe("ExpirationTargetNotFoundError");
+ expect(codeOf(unaddressable)).toBe("InvalidExpirationTargetError");
+ });
+
+ test("an argument of the other brain_scaffold_stub action answers a registered code", async () => {
+ const ctx: ServerContext = { vault, configPath, repoRoot: null };
+ const err = await raised(() =>
+ stubTool().handler(ctx, { action: "list", target: "Foo", apply: true }),
+ );
+ expect(codeOf(err)).toBe("argument_forbidden");
+ });
+});
+
+// ----- unknown operations ------------------------------------------------------
+
+describe("every operation-dispatching tool answers unknown_operation", () => {
+ // One case per dispatch: the argument that selects the operation, set to
+ // a value outside the tool's closed set, and the message the refusal has
+ // always carried, which stays byte-identical.
+ const BOGUS = "no_such_operation";
+ const CASES: ReadonlyArray<readonly [string, Record<string, unknown>, string]> = [
+ [
+ "brain_skill_proposals",
+ { operation: BOGUS },
+ "brain_skill_proposals: operation must be one of " +
+ "learn|list|accept|reject|recover|usage|evidence|page_candidates|page_draft",
+ ],
+ [
+ "brain_procedural_memory",
+ { operation: BOGUS },
+ "brain_procedural_memory: operation must be one of reconcile|list|mark_used|mark_outcome",
+ ],
+ [
+ "brain_recurrence",
+ { operation: BOGUS },
+ "brain_recurrence: operation must be one of list|show|learn|forget|purge_source",
+ ],
+ [
+ "brain_procedural_graph",
+ { operation: BOGUS },
+ "brain_procedural_graph: operation must be one of rebuild|show|hints",
+ ],
+ [
+ "brain_obligation",
+ // `slug` is read before the last branch, so the refusal needs one.
+ { operation: BOGUS, slug: "demo" },
+ "brain_obligation operation must be one of: add, done, list, show, remove",
+ ],
+ [
+ "brain_context_receipts",
+ { operation: BOGUS },
+ "brain_context_receipts: operation must be list, show, or summary",
+ ],
+ [
+ "brain_context_presets",
+ { operation: BOGUS },
+ "brain_context_presets: operation must be show, suggest, or diff",
+ ],
+ [
+ "brain_write_session",
+ { op: BOGUS },
+ `brain_write_session: op must be open|submit|approve|abandon|status|list, got '${BOGUS}'`,
+ ],
+ [
+ "brain_pinned_context",
+ { operation: BOGUS },
+ "brain_pinned_context operation must be one of: read, write, append, clear",
+ ],
+ [
+ "brain_session_summary",
+ { operation: BOGUS },
+ "brain_session_summary: operation must be write|get|list",
+ ],
+ ["brain_benchmark", { operation: BOGUS }, "brain_benchmark: operation must be run"],
+ ["brain_tune", { operation: BOGUS }, "brain_tune: operation must be run|status|reset"],
+ [
+ "brain_recall_telemetry",
+ { operation: BOGUS },
+ "brain_recall_telemetry: operation must be list, summary, gate_list, gate_summary, observed_reuse, or cost",
+ ],
+ [
+ "brain_route_metrics",
+ { operation: BOGUS },
+ "brain_route_metrics: operation must be list or summary",
+ ],
+ [
+ "brain_token_impact",
+ { operation: BOGUS },
+ "brain_token_impact: operation must be record, outcome, list, or summary",
+ ],
+ [
+ "brain_context_pack_outcome",
+ { operation: BOGUS },
+ "brain_context_pack_outcome: operation must be post, list, or summary",
+ ],
+ [
+ "brain_analytics",
+ { view: "attention_flows", operation: BOGUS },
+ "brain_analytics view=attention_flows: operation must be one of list|evaluate|render",
+ ],
+ [
+ "brain_bridges",
+ { operation: BOGUS },
+ "brain_bridges: operation must be discover|list|accept|dismiss",
+ ],
+ ["brain_clusters", { operation: BOGUS }, "brain_clusters: operation must be run|list"],
+ [
+ "brain_truth",
+ { operation: BOGUS },
+ "brain_truth: operation must be ingest|slots|conflicts|aggregate|collisions",
+ ],
+ ["brain_dead_ends", { operation: BOGUS }, "brain_dead_ends: operation must be record|list"],
+ [
+ "brain_claims",
+ { operation: BOGUS },
+ "brain_claims: 'operation' must be one of current, at, history, replaced, contests, rebuild",
+ ],
+ [
+ "brain_generation_reports",
+ { action: BOGUS },
+ "brain_generation_reports: action must be record, list, or summary",
+ ],
+ [
+ "brain_labels",
+ { operation: BOGUS },
+ "brain_labels: operation must be assign|remove|show|suggest",
+ ],
+ ["brain_tiers", { operation: BOGUS }, "brain_tiers: operation must be check|restore|accept"],
+ ["brain_secrets", { operation: BOGUS }, "brain_secrets: operation must be list|run"],
+ ["brain_maintenance", { operation: BOGUS }, "brain_maintenance: operation must be run|status"],
+ [
+ "brain_dream",
+ { action: BOGUS },
+ "brain_dream: action must be run|stage|validate|apply|retriage|discard|list",
+ ],
+ [
+ "brain_tension",
+ { action: BOGUS },
+ "brain_tension: 'action' must be one of detect, list, show, confirm, dismiss, resolve, verify",
+ ],
+ [
+ "brain_decision",
+ { action: BOGUS },
+ "brain_decision: 'action' must be one of record, outcome, rate, show, list, compare, similar, history, recall",
+ ],
+ [
+ "brain_lifecycle",
+ { action: BOGUS },
+ "brain_lifecycle: 'action' must be one of tombstone, supersede, temporal-replace, tip, curator",
+ ],
+ ["brain_writes", { action: BOGUS }, "brain_writes: 'action' must be one of list, plan_revert"],
+ [
+ "brain_note_lifecycle",
+ { action: BOGUS },
+ "brain_note_lifecycle: 'action' must be one of rename, move, archive, delete",
+ ],
+ [
+ "brain_scaffold_stub",
+ { action: BOGUS },
+ "brain_scaffold_stub: 'action' must be one of list, write",
+ ],
+ ];
+
+ for (const [tool, args, message] of CASES) {
+ test(`${tool} answers unknown_operation with its message unchanged`, async () => {
+ const err = await raised(() => findTool(TOOLS, tool).handler(workspaceCtx(), args));
+ expect(err.message).toBe(message);
+ expect(codeOf(err)).toBe("unknown_operation");
+ });
+ }
+
+ test("the table covers every tool whose schema declares a dispatch enum", () => {
+ // Derived from the catalog, so a new dispatcher that forgets the shared
+ // code fails here instead of shipping (brain_claims was found by hand).
+ const covered = new Set<string>([
+ ...CASES.map(([tool]) => tool),
+ // pinned by the workspace refusal tests above
+ "brain_intention",
+ "brain_trigger",
+ ]);
+ // A host write whose `action` refusal keeps the pinned `invalid_action`.
+ const exempt = new Set<string>(["brain_memory_bridge"]);
+ const declared = TOOLS.filter((tool) => {
+ const props =
+ (tool.inputSchema as { readonly properties?: Record<string, { readonly enum?: unknown }> })
+ .properties ?? {};
+ return ["operation", "op", "action"].some((arg) => Array.isArray(props[arg]?.enum));
+ }).map((tool) => tool.name);
+ expect(declared.filter((name) => !covered.has(name) && !exempt.has(name))).toEqual([]);
+ });
+
+ test("a write batch operation of an unknown kind answers unknown_operation", async () => {
+ const err = await raised(() =>
+ findTool(TOOLS, "brain_write_batch").handler(workspaceCtx(), {
+ operations: [{ op: BOGUS, path: "notes/x.md" }],
+ }),
+ );
+ expect(err.message).toStartWith("brain_write_batch: operations[0].op must be one of ");
+ expect(codeOf(err)).toBe("unknown_operation");
+ });
+});
diff --git a/tests/mcp/tool-error-codes.test.ts b/tests/mcp/tool-error-codes.test.ts
new file mode 100644
index 00000000..4f59c4a4
--- /dev/null
+++ b/tests/mcp/tool-error-codes.test.ts
@@ -0,0 +1,312 @@
+/**
+ * The closed MCP-boundary error registry.
+ *
+ * Every tool failure the server answers carries one code from
+ * `TOOL_ERROR_CODES`. The registry imports the core vocabularies verbatim
+ * and adds lower snake_case tokens for the uncoded remainder, so these
+ * tests pin three things: the list is closed and complete, the tokens the
+ * wire already carries are members unchanged, and the classifier never
+ * invents a code - an error it does not know is `internal_error`, named on
+ * stderr by its class name only.
+ */
+
+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
+import type { Mock } from "bun:test";
+
+import { BrainPreferenceNotFoundError } from "../../src/core/brain/apply-evidence.ts";
+import { CountGuardError } from "../../src/core/brain/count-guard.ts";
+import {
+ ExpirationTargetNotFoundError,
+ ExpirationValueError,
+ InvalidExpirationTargetError,
+} from "../../src/core/brain/expiration-set.ts";
+import { BrainParseError } from "../../src/core/brain/parse-error.ts";
+import { BrainStatusFolderMismatchError } from "../../src/core/brain/preference.ts";
+import { PinnedBatchError } from "../../src/core/brain/pinned.ts";
+import { BrainConfigError } from "../../src/core/brain/policy/errors.ts";
+import { SHAPE_VIOLATION_CODES } from "../../src/core/brain/response-shape.ts";
+import { SEMANTIC_VIOLATION_CODES } from "../../src/core/brain/response-checks.ts";
+import { SafeguardAbortError, SafeguardTimeoutError } from "../../src/core/brain/safeguard.ts";
+import { WriteBatchError } from "../../src/core/brain/write-batch.ts";
+import { ConfigReadError } from "../../src/core/config.ts";
+import { SEARCH_ERROR_CODES, SearchError } from "../../src/core/search/search-error.ts";
+import { WRITE_BINDING_REFUSED_CODE } from "../../src/core/write-binding/index.ts";
+import { VAULT_FROZEN_REFUSAL } from "../../src/mcp/frozen-refusal.ts";
+import { OutputContractError } from "../../src/mcp/output-contract.ts";
+import { OWNER_SCOPE_REFUSALS } from "../../src/mcp/owner-scope-refusal.ts";
+import {
+ INTERNAL_ERROR,
+ INVALID_PARAMS,
+ INVALID_REQUEST,
+ METHOD_NOT_FOUND,
+ PARSE_ERROR,
+} from "../../src/mcp/protocol.ts";
+import { REACH_REFUSAL } from "../../src/mcp/reach-refusal.ts";
+import {
+ GENERIC_TOOL_ERROR_CODES,
+ TOOL_ERROR_CODE,
+ TOOL_ERROR_CODES,
+ TOOL_ERROR_META_KEY,
+ TOOL_ERROR_SCHEMA,
+ codeForError,
+ defaultCodeForRpc,
+ isGenericToolErrorCode,
+ isToolErrorCode,
+ toolErrorMeta,
+} from "../../src/mcp/tool-error-codes.ts";
+
+/**
+ * Decision 5 of the design plus `brain_artifact_unparseable` and
+ * `argument_forbidden` (on the wire before the registry existed): the generic
+ * tokens this release adds.
+ */
+const NEW_TOKENS = [
+ "parse_error",
+ "invalid_request",
+ "method_not_found",
+ "invalid_params",
+ "internal_error",
+ "safeguard_timeout",
+ "safeguard_aborted",
+ "output_contract_failed",
+ "config_unreadable",
+ "skill_not_found",
+ "skill_invalid_path",
+ "unknown_skill",
+ "unknown_operation",
+ "invalid_status",
+ "trigger_transition_refused",
+ "write_session_unknown",
+ "write_session_terminal",
+ "session_id_required",
+ "unknown_argument",
+ "brain_artifact_unparseable",
+ "argument_forbidden",
+] as const;
+
+/**
+ * Members of the type-only core vocabularies, spelled out here as the
+ * independent oracle: the registry's own arrays are checked against the
+ * core unions by `tsc`, and against this list by the test.
+ */
+const TYPE_ONLY_MEMBERS = [
+ // write batch
+ "invalid_operation",
+ "invalid_path",
+ "excluded",
+ "outside_vault",
+ "exists",
+ "target_missing",
+ "target_unreadable",
+ "target_frontmatter_lossy",
+ "blank_overwrite_refused",
+ "reserved_frontmatter_key",
+ "duplicate_target",
+ "too_many_operations",
+ "preference_not_found",
+ "write_binding",
+ "invalid_document",
+ "invalid_template",
+ "config_invalid",
+ // note lifecycle
+ "source_missing",
+ "destination_required",
+ "destination_forbidden",
+ "destination_occupied",
+ "destination_unchanged",
+ "wrong_action",
+ "not_confirmed",
+ "already_archived",
+ "cascade_forbidden",
+ // note revert
+ "unbounded_selector",
+ "digest_mismatch",
+ "nothing_to_apply",
+ // scaffold stub
+ "empty_target",
+ "target_resolves",
+ "target_ambiguous",
+ "unknown_source",
+ // note title resolution
+ "path_not_found",
+ "not_found",
+ "ambiguous",
+ // note template
+ "unbalanced_section",
+ "section_too_deep",
+ "invalid_variable",
+ // pinned
+ "replace_target_missing",
+ "budget_exceeded",
+ // exact state
+ "invalid_aspect",
+ // host memory write
+ "invalid_action",
+ "invalid_target",
+ "empty_content",
+ // count guard, as the lifecycle tool reports it
+ "count_guard",
+ // the brain_expire refusals, reported under their class names
+ "ExpirationValueError",
+ "ExpirationTargetNotFoundError",
+ "InvalidExpirationTargetError",
+] as const;
+
+/** A core-style error class that, like several real ones, never sets `this.name`. */
+class Nameless extends Error {}
+
+const UNCLASSIFIED_PREFIX = "warning: unclassified tool error mapped to internal_error: ";
+
+describe("TOOL_ERROR_CODES", () => {
+ test("is frozen and unique", () => {
+ expect(Object.isFrozen(TOOL_ERROR_CODES)).toBe(true);
+ expect(new Set(TOOL_ERROR_CODES).size).toBe(TOOL_ERROR_CODES.length);
+ });
+
+ test("is exactly the imported vocabularies plus the 21 new tokens", () => {
+ const expected = new Set<string>([
+ ...NEW_TOKENS,
+ ...SEARCH_ERROR_CODES,
+ ...Object.values(SHAPE_VIOLATION_CODES),
+ ...Object.values(SEMANTIC_VIOLATION_CODES),
+ VAULT_FROZEN_REFUSAL,
+ WRITE_BINDING_REFUSED_CODE,
+ REACH_REFUSAL,
+ ...OWNER_SCOPE_REFUSALS,
+ ...TYPE_ONLY_MEMBERS,
+ ]);
+ expect([...TOOL_ERROR_CODES].toSorted() as string[]).toEqual([...expected].toSorted());
+ expect([...GENERIC_TOOL_ERROR_CODES].toSorted()).toEqual([...NEW_TOKENS].toSorted());
+ expect(Object.values(TOOL_ERROR_CODE).toSorted()).toEqual([...NEW_TOKENS].toSorted());
+ expect(Object.isFrozen(TOOL_ERROR_CODE)).toBe(true);
+ });
+
+ test("keeps the pinned wire tokens verbatim", () => {
+ for (const token of ["budget_exceeded", "invalid_action", "invalid_target", "vault_frozen"]) {
+ expect(isToolErrorCode(token)).toBe(true);
+ }
+ });
+
+ test("the guards accept members only", () => {
+ for (const outsider of ["", "ENOENT", "INTERNAL_ERROR", "unclassified", 42, null, undefined]) {
+ expect(isToolErrorCode(outsider)).toBe(false);
+ expect(isGenericToolErrorCode(outsider)).toBe(false);
+ }
+ expect(isGenericToolErrorCode("INDEX_MISSING")).toBe(false);
+ expect(isToolErrorCode("INDEX_MISSING")).toBe(true);
+ });
+});
+
+describe("toolErrorMeta", () => {
+ test("names the schema and the code", () => {
+ expect(TOOL_ERROR_META_KEY).toBe("open-second-brain/error");
+ expect(TOOL_ERROR_SCHEMA).toBe("o2b.error.v1");
+ expect(toolErrorMeta("safeguard_timeout")).toEqual({
+ schema: "o2b.error.v1",
+ code: "safeguard_timeout",
+ });
+ });
+});
+
+describe("defaultCodeForRpc", () => {
+ test("maps each JSON-RPC constant to its snake token", () => {
+ expect(defaultCodeForRpc(PARSE_ERROR)).toBe("parse_error");
+ expect(defaultCodeForRpc(INVALID_REQUEST)).toBe("invalid_request");
+ expect(defaultCodeForRpc(METHOD_NOT_FOUND)).toBe("method_not_found");
+ expect(defaultCodeForRpc(INVALID_PARAMS)).toBe("invalid_params");
+ expect(defaultCodeForRpc(INTERNAL_ERROR)).toBe("internal_error");
+ });
+});
+
+describe("codeForError", () => {
+ let stderr: Mock<typeof process.stderr.write>;
+ let lines: string[];
+
+ beforeEach(() => {
+ lines = [];
+ stderr = spyOn(process.stderr, "write").mockImplementation((chunk) => {
+ lines.push(String(chunk));
+ return true;
+ });
+ });
+
+ afterEach(() => {
+ stderr.mockRestore();
+ });
+
+ test("returns the code a typed core error carries", () => {
+ expect(codeForError(new WriteBatchError("invalid_path", 0, "bad path"))).toBe("invalid_path");
+ expect(codeForError(new SearchError("INDEX_MISSING", "no index"))).toBe("INDEX_MISSING");
+ expect(codeForError(new PinnedBatchError("budget_exceeded", -1, "too big"))).toBe(
+ "budget_exceeded",
+ );
+ expect(lines).toEqual([]);
+ });
+
+ test("names the safeguard, config and count-guard errors", () => {
+ expect(codeForError(new SafeguardTimeoutError("dream", 10))).toBe("safeguard_timeout");
+ expect(codeForError(new SafeguardAbortError("dream"))).toBe("safeguard_aborted");
+ expect(codeForError(new ConfigReadError("config.yaml", "EACCES"))).toBe("config_unreadable");
+ expect(codeForError(new BrainConfigError("bad", "dream.x", "_brain.yaml"))).toBe(
+ "config_invalid",
+ );
+ expect(codeForError(new CountGuardError("mismatch", 2, 1, ["a", "b"]))).toBe("count_guard");
+ expect(codeForError(new OutputContractError("probe", ["$.ok: expected boolean"]))).toBe(
+ "output_contract_failed",
+ );
+ expect(lines).toEqual([]);
+ });
+
+ test("an expiration refusal keeps its class name as its code", () => {
+ expect(codeForError(new ExpirationValueError("soon", "bad date"))).toBe("ExpirationValueError");
+ expect(codeForError(new ExpirationTargetNotFoundError("sig-x", ["Brain/inbox"]))).toBe(
+ "ExpirationTargetNotFoundError",
+ );
+ expect(codeForError(new InvalidExpirationTargetError("x"))).toBe(
+ "InvalidExpirationTargetError",
+ );
+ expect(lines).toEqual([]);
+ });
+
+ test("a Brain artifact parse failure is brain_artifact_unparseable, subclasses included", () => {
+ const path = "/vault/Brain/retired/ret-broken.md";
+ expect(codeForError(new BrainParseError("missing retired_at", path))).toBe(
+ "brain_artifact_unparseable",
+ );
+ expect(
+ codeForError(
+ new BrainStatusFolderMismatchError(
+ "status disagrees with folder",
+ path,
+ "retired",
+ "preferences",
+ ),
+ ),
+ ).toBe("brain_artifact_unparseable");
+ expect(lines).toEqual([]);
+ });
+
+ test("walks the cause chain of a rethrown error", () => {
+ const original = new BrainPreferenceNotFoundError("pref-x", "Brain/preferences/pref-x.md");
+ const rethrown = new Error(original.message, { cause: original });
+ expect(codeForError(rethrown)).toBe("preference_not_found");
+ expect(lines).toEqual([]);
+ });
+
+ test("an unknown error is internal_error, logged once by name only", () => {
+ const privatePath = "/home/someone/vault/private.md";
+ const cases: ReadonlyArray<readonly [unknown, string]> = [
+ [new Error(`boom at ${privatePath}`), "Error"],
+ [Object.assign(new Error(`ENOENT: ${privatePath}`), { code: "ENOENT" }), "Error"],
+ [`thrown string ${privatePath}`, "string"],
+ // A class that never sets `this.name` is still named by its class.
+ [new Nameless(`boom at ${privatePath}`), "Nameless"],
+ ];
+ for (const [thrown, name] of cases) {
+ lines = [];
+ expect(codeForError(thrown)).toBe("internal_error");
+ expect(lines).toEqual([`${UNCLASSIFIED_PREFIX}${name}\n`]);
+ expect(lines[0]).not.toContain(privatePath);
+ }
+ });
+});
diff --git a/tests/mcp/tool-error-envelope.test.ts b/tests/mcp/tool-error-envelope.test.ts
new file mode 100644
index 00000000..a3622c24
--- /dev/null
+++ b/tests/mcp/tool-error-envelope.test.ts
@@ -0,0 +1,277 @@
+/**
+ * Every MCP error answer carries a stable code, on both channels.
+ *
+ * Channel A is the JSON-RPC error: `error.data.code`, defaulted inside the
+ * single builder `errorResponse` from the numeric JSON-RPC code, a
+ * thrower-supplied code always winning. Channel B is the `isError` tool
+ * result: `_meta["open-second-brain/error"] = { schema, code }`, with the
+ * text body byte-identical to the previous release and no
+ * `structuredContent`, because strict clients validate that against the
+ * tool's output schema even on an error.
+ */
+
+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
+import type { Mock } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { SafeguardTimeoutError } from "../../src/core/brain/safeguard.ts";
+import { PROGRESS_META_KEY } from "../../src/mcp/progress.ts";
+import {
+ INVALID_PARAMS,
+ JSONRPC_VERSION,
+ MCPError,
+ MCPErrorDataArrayError,
+} from "../../src/mcp/protocol.ts";
+import { MCPServer } from "../../src/mcp/server.ts";
+import { serveStdioFromString } from "../../src/mcp/stdio.ts";
+import { TOOL_ERROR_META_KEY, TOOL_ERROR_SCHEMA } from "../../src/mcp/tool-error-codes.ts";
+import { readRpcErrorCode, readToolErrorCode } from "../helpers/tool-error-envelope.ts";
+
+type JsonObject = Record<string, any>;
+
+const UNCLASSIFIED_LINE = "warning: unclassified tool error mapped to internal_error: Error\n";
+const TOOL = "envelope_probe";
+/** The prefix, a code capped at 120 characters, and the newline. */
+const UNREGISTERED_LINE_MAX = "warning: unregistered error code on the wire: ".length + 120 + 1;
+
+let tmp: string;
+let stderr: Mock<typeof process.stderr.write>;
+let lines: string[];
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-envelope-"));
+ lines = [];
+ stderr = spyOn(process.stderr, "write").mockImplementation((chunk) => {
+ lines.push(String(chunk));
+ return true;
+ });
+});
+
+afterEach(() => {
+ stderr.mockRestore();
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+/** A server whose whole tool table is one probe running `handler`. */
+function serverWith(handler: () => unknown): MCPServer {
+ const server = new MCPServer({ vault: tmp });
+ (server as any).tools = [
+ {
+ name: TOOL,
+ description: "test tool",
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
+ handler,
+ },
+ ];
+ return server;
+}
+
+async function call(server: MCPServer, meta?: JsonObject): Promise<JsonObject> {
+ const res = await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 7,
+ method: "tools/call",
+ params: { name: TOOL, arguments: {}, ...(meta === undefined ? {} : { _meta: meta }) },
+ });
+ return res as JsonObject;
+}
+
+describe("channel A: error.data.code on every JSON-RPC error", () => {
+ test("an unknown method answers method_not_found", async () => {
+ const res = (await new MCPServer({ vault: tmp }).handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "no/such/method",
+ })) as JsonObject;
+ expect(res["error"]["code"]).toBe(-32601);
+ expect(res["error"]["message"]).toBe("unknown method: no/such/method");
+ expect(res["error"]["data"]).toEqual({ code: "method_not_found" });
+ });
+
+ test("an MCPError with no data gains the default code, message unchanged", async () => {
+ const res = await call(
+ serverWith(() => {
+ throw new MCPError(INVALID_PARAMS, "limit must be positive");
+ }),
+ );
+ expect(res["error"]["code"]).toBe(INVALID_PARAMS);
+ expect(readRpcErrorCode(res)).toBe("invalid_params");
+ expect(res["error"]["message"]).toBe("limit must be positive");
+ expect(res["error"]["data"]).toEqual({ code: "invalid_params" });
+ });
+
+ test("a thrower-supplied code is untouched", async () => {
+ const data = { code: "budget_exceeded", limit: 10, size: 12 };
+ const res = await call(
+ serverWith(() => {
+ throw new MCPError(INVALID_PARAMS, "over budget", data);
+ }),
+ );
+ expect(res["error"]["data"]).toEqual(data);
+ expect(Object.keys(res["error"]["data"])).toEqual(["code", "limit", "size"]);
+ expect(lines).toEqual([]);
+ });
+
+ test("a thrower-supplied code outside the registry is kept and named on stderr", async () => {
+ // Kept, not replaced: a replaced code would hide which producer sent
+ // it, and the stderr line is what points a maintainer at that site.
+ const res = await call(
+ serverWith(() => {
+ throw new MCPError(INVALID_PARAMS, "refused", { code: "not_a_registered_code" });
+ }),
+ );
+ expect(res["error"]["data"]).toEqual({ code: "not_a_registered_code" });
+ expect(lines).toEqual([
+ 'warning: unregistered error code on the wire: "not_a_registered_code"\n',
+ ]);
+ });
+
+ test("an unregistered code is quoted and capped, so it cannot forge stderr lines", async () => {
+ const forged = `x\nwarning: forged line${"y".repeat(200)}`;
+ const res = await call(
+ serverWith(() => {
+ throw new MCPError(INVALID_PARAMS, "refused", { code: forged });
+ }),
+ );
+ expect(res["error"]["data"]).toEqual({ code: forged });
+ // One line, the newline escaped inside the quoted code, and a bound
+ // on the length however long the code is.
+ expect(lines).toHaveLength(1);
+ const [line] = lines;
+ expect(line!.indexOf("\n")).toBe(line!.length - 1);
+ expect(line).toStartWith(
+ 'warning: unregistered error code on the wire: "x\\nwarning: forged line',
+ );
+ expect(line!.length).toBeLessThanOrEqual(UNREGISTERED_LINE_MAX);
+ });
+
+ test("a record without a code keeps every member and gains code last", async () => {
+ const data = { tool: TOOL, unknown_arguments: ["x"], declared_arguments: [] };
+ const res = await call(
+ serverWith(() => {
+ throw new MCPError(INVALID_PARAMS, "unknown argument", data);
+ }),
+ );
+ expect(res["error"]["data"]).toEqual({ ...data, code: "invalid_params" });
+ expect(Object.keys(res["error"]["data"])).toEqual([
+ "tool",
+ "unknown_arguments",
+ "declared_arguments",
+ "code",
+ ]);
+ });
+
+ test("a JSON-RPC refusal of a call with a refused progress token carries the refusal", async () => {
+ // The refusal is not only for isError results: a call that asked for
+ // progress and was refused as a protocol error never got any either.
+ const res = await call(
+ serverWith(() => {
+ throw new MCPError(INVALID_PARAMS, "limit must be positive", { limit: -1 });
+ }),
+ { progressToken: "tok-2" },
+ );
+ expect(res["error"]["message"]).toBe("limit must be positive");
+ const data = res["error"]["data"] as JsonObject;
+ expect(Object.keys(data)).toEqual(["limit", PROGRESS_META_KEY, "code"]);
+ expect(data[PROGRESS_META_KEY]["progressToken"]).toBe("tok-2");
+ expect(data["code"]).toBe("invalid_params");
+ });
+
+ test("a non-string code member is replaced by the default", async () => {
+ const res = await call(
+ serverWith(() => {
+ throw new MCPError(INVALID_PARAMS, "refused", { code: 42, limit: 3 });
+ }),
+ );
+ expect(res["error"]["data"]).toEqual({ code: "invalid_params", limit: 3 });
+ });
+
+ test("an array is refused as data by name, never merged into", () => {
+ // `{ ...[a, b], code }` would go out as `{"0":a,"1":b,"code":...}`.
+ expect(() => new MCPError(INVALID_PARAMS, "refused", ["a", "b"])).toThrow(
+ MCPErrorDataArrayError,
+ );
+ });
+
+ test("a plain throw outside tools/call is internal_error and is logged", async () => {
+ const server = new MCPServer({ vault: tmp });
+ (server as any).handleResourcesList = () => {
+ throw new Error("boom");
+ };
+ const res = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 2,
+ method: "resources/list",
+ })) as JsonObject;
+ expect(res["error"]["code"]).toBe(-32603);
+ expect(res["error"]["message"]).toBe("internal error: boom");
+ expect(res["error"]["data"]).toEqual({ code: "internal_error" });
+ expect(lines).toEqual([UNCLASSIFIED_LINE]);
+ });
+
+ test("a stdio parse error answers parse_error", async () => {
+ const out = await serveStdioFromString({ vault: tmp }, "{not json}\n");
+ const res = JSON.parse(out.trim()) as JsonObject;
+ expect(res["error"]["code"]).toBe(-32700);
+ expect(res["error"]["data"]).toEqual({ code: "parse_error" });
+ });
+});
+
+describe("channel B: _meta code on every isError result", () => {
+ test("a safeguard timeout carries safeguard_timeout, text unchanged", async () => {
+ const thrown = new SafeguardTimeoutError("probe", 5);
+ const res = await call(
+ serverWith(() => {
+ throw thrown;
+ }),
+ );
+ const result = res["result"];
+ expect(result["isError"]).toBe(true);
+ expect(result["content"]).toEqual([{ type: "text", text: thrown.message }]);
+ expect(result["structuredContent"]).toBeUndefined();
+ expect(result["_meta"]).toEqual({
+ [TOOL_ERROR_META_KEY]: { schema: TOOL_ERROR_SCHEMA, code: "safeguard_timeout" },
+ });
+ expect(lines).toEqual([]);
+ });
+
+ test("a failed call with a refused progress token carries both _meta keys", async () => {
+ const res = await call(
+ serverWith(() => {
+ throw new SafeguardTimeoutError("probe", 5);
+ }),
+ { progressToken: "tok-1" },
+ );
+ const meta = res["result"]["_meta"] as JsonObject;
+ expect(Object.keys(meta).toSorted()).toEqual(
+ [PROGRESS_META_KEY, TOOL_ERROR_META_KEY].toSorted(),
+ );
+ expect(meta[TOOL_ERROR_META_KEY]).toEqual({
+ schema: TOOL_ERROR_SCHEMA,
+ code: "safeguard_timeout",
+ });
+ expect(meta[PROGRESS_META_KEY]["progressToken"]).toBe("tok-1");
+ });
+
+ test("a successful call with no progress token has no _meta key at all", async () => {
+ const res = await call(serverWith(() => ({ ok: true })));
+ expect(Object.keys(res["result"]).toSorted()).toEqual([
+ "content",
+ "isError",
+ "structuredContent",
+ ]);
+ });
+
+ test("an unclassified throw carries internal_error and is logged once", async () => {
+ const res = await call(
+ serverWith(() => {
+ throw new Error("something private");
+ }),
+ );
+ expect(res["result"]["content"]).toEqual([{ type: "text", text: "something private" }]);
+ expect(readToolErrorCode(res["result"])).toBe("internal_error");
+ expect(lines).toEqual([UNCLASSIFIED_LINE]);
+ });
+});
diff --git a/tests/python/test_memory_provider.py b/tests/python/test_memory_provider.py
index 4457875b..4f1d0d9d 100644
--- a/tests/python/test_memory_provider.py
+++ b/tests/python/test_memory_provider.py
@@ -1639,6 +1639,30 @@ class JsonRpcStdioClientTests(unittest.TestCase):
with self.assertRaises(BridgeError):
client.request("missing", {})
+ def test_error_response_exposes_the_stable_code(self):
+ # Every JSON-RPC error carries error.data.code; the bridge hands it
+ # over as an attribute so Hermes need not parse the rendered dict.
+ error = {"code": -32601, "message": "nope", "data": {"code": "method_not_found"}}
+ reader = _ScriptedReader([{"jsonrpc": "2.0", "id": 1, "error": error}])
+ client = JsonRpcStdioClient(io.BytesIO(), reader)
+ with self.assertRaises(BridgeError) as caught:
+ client.request("missing", {})
+ self.assertEqual(caught.exception.code, "method_not_found")
+ self.assertEqual(str(caught.exception), str(error))
+
+ def test_error_response_without_a_string_code_has_none(self):
+ for error in (
+ {"code": -32601, "message": "nope"},
+ {"code": -32601, "message": "nope", "data": ["x"]},
+ {"code": -32601, "message": "nope", "data": {"code": 42}},
+ ):
+ with self.subTest(error=error):
+ reader = _ScriptedReader([{"jsonrpc": "2.0", "id": 1, "error": error}])
+ client = JsonRpcStdioClient(io.BytesIO(), reader)
+ with self.assertRaises(BridgeError) as caught:
+ client.request("missing", {})
+ self.assertIsNone(caught.exception.code)
+
def test_eof_raises(self):
client = JsonRpcStdioClient(io.BytesIO(), _ScriptedReader([]))
with self.assertRaises(BridgeError):
diff --git a/uv.lock b/uv.lock
index 6ae1db7a..fea388cd 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4,5 +4,5 @@ requires-python = ">=3.11"
[[package]]
name = "open-second-brain"
-version = "1.65.0"
+version = "1.66.0"
source = { editable = "." }