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.
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
- Confirmed:
toolError(src/mcp/server.ts:570-575) returns{content, isError: true}with no code; the catch at:463-478routes every non-MCPErrorthere. - Confirmed: skill and workspace errors carry no code on the wire.
SkillErrorhasNOT_FOUND | INVALID_PATHbutskill-tools.ts:90rewraps it asMCPError(INVALID_PARAMS, message);unknown skill(:84) and the workspace refusals (workspace-tools.ts:82, 190, 228, 231) are prose only. - Refuted: "search already does this".
SEARCH_ERROR_CODESexists only in the core;searchErrorToMcp(search-tools.ts:863-887) builds anMCPErrorwith nodata, except the fallback arm which appends[<CODE>]to the prose.recall-tools.ts:959drops it too. - Missed by the card: there are two channels (JSON-RPC error and
isErrorresult), and theerror.data.codeconvention already exists on the first. - 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). - Refuted as named: the engram
invalid_session_id/retry_without_session_idpair. The real counterparts are an unknown write session (write-session/engine.ts:273), a terminal one (:284) and a missingsession_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)
- Confirmed:
RETRIEVAL_DEGRADATION(retrieval-trail.ts:68-150) has no rerank member; the failure travels only asrerank_degraded:(post-rank.ts:178); no rerank hit in doctor; no rerank sunset table. - Refuted:
no_keyas a degradation. Enabled with a missing key fails closed by contract (rerank/index.ts:15-19,provider-resolve.ts:85-91, pinned byrerank.search.test.ts:80-84). It belongs to doctor; the orchestrator also put missing-key-as-degradation out of scope. - Refuted:
disabledas a degradation. Disabled is the default and must keep a healthy answer trail-free (retrieval-trail.test.ts:85, the "absent, not empty" contract). - Corrected: the trail is not an
--explainfeature.retrieval_trailappears in--jsonand MCPbrain_searchwhenever anything degraded (outcome-render.ts:152,search-tools.ts:1167);--explainadds receipts only. The human transcript names a trail code only on an empty window, which rerank cannot produce, so the existingrerank_degraded:warning stays the human signal. - Corrected: the upstream claim behind the survey. ZeroEntropy announced (2026-07-24) that its HOSTED
/models/rerankand/models/embedendpoints 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-hostedzerank-*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-unavailablewith categorygoneornetwork). The one sourced positive found for a model reachable through the Cohere-compatible/rerankshape (cross-encoder.ts:5) is the Coherererank-*-v2.0family, retired 2025-04-30 (source: https://docs.cohere.com/docs/deprecations); the implementer re-reads that page and records only what it states.
Scope
- 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. - Channel B (
isErrorresults):result._meta["open-second-brain/error"] = { schema: "o2b.error.v1", code }, text body byte-identical,structuredContentnever set. - Channel A (JSON-RPC errors):
error.data.codeon every error response, the default derived in the single buildererrorResponse(server.ts) from the numeric JSON-RPC code, a thrower-supplied code always winning. withProgressRefusalmerges into an existing_metainstead of replacing it.- 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. - Rerank: two
RETRIEVAL_DEGRADATIONmembers,rerank-provider-unavailable(detail.categoryfrom a closedRERANK_FAILURE_CATEGORY) andrerank-model-sunset(no HTTP call once the announced date has passed); a rerank sunset survey that reuses the generic embedding classifier; a degradedrerank-provider-unavailableoutcome is not written to the query cache. - A config-only
rerankHealthCheckin doctor, its codes registered inDIAGNOSTIC_SIGNALSorDOCTOR_EXIT_EXCLUSIONSas the census test demands. - Docs: a "Tool errors" section in
docs/mcp.md; the trail table indocs/cli-reference.mdgains the two rerank rows and the missinghybrid-deadline-exceededrow; the doctor codes are documented.
Out of scope
- 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). - The OpenClaw tool envelope (
src/openclaw/index.tsdoes not useMCPServer; the host owns its error shape). - Missing rerank key, base URL or model as a trail degradation (fail-closed by contract; doctor reports it instead).
- Moving any error between channels. The MCP spec prefers
isErrorresults for tool errors, but changing channel is a wire-shape change for every client and is not what the cards ask for. - Renaming or re-casing any code already on the wire (kebab, snake and UPPER stay as they are).
- Retry hints (
retryable,retry_after_ms) on the boundary envelope. - A rerank operator declaration key (
search_rerank.sunset_at); the survey alone satisfies the card, and the classifier keeps itsdeclarationparameter for a later release. - The CLI bridge (
server.callToolhas no envelope; its stderr line stays unchanged). decision-modelandlocalrerank 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
- Where the code lives on channel B:
_meta, keyopen-second-brain/error. (Orchestrator decision 1.) The MCP SDK 1.30 client validatesstructuredContentagainstoutputSchemaeven onisErrorresults, and 16 tools declare one, so an error object there breaks strict clients;_metapasses the loose result schema. The repository already chose a namespaced_metakey for progress for the same reason (progress.ts:53,docs/mcp.md:114-119). Hermes_structured()would misread an error placed instructuredContent. Payload:{ schema: "o2b.error.v1", code }, mirroringPROGRESS_SCHEMA = "o2b.progress.v1". The text body stays byte-identical because two tests pin it withtoBeand Hermes and agents parse it. - Where the code lives on channel A:
error.data.code, defaulted insideerrorResponse. (Orchestrator decision 1.) It is the convention 12 sites andvault_frozenalready use, anderror.dataisunknownin every client. The default is derived inerrorResponse(server.ts:585), the one builder every JSON-RPC error passes through, including thestdio.tsandhttp.tstransport errors (parse error, invalid request), so "every error response carries a code" holds by construction. The numeric code parameter is narrowed to a closedJsonRpcErrorCodeunion of the five constants inprotocol.ts:15-19, and the default map is a totalRecordover it, so no unknown numeric code can reach the builder and no runtime fallback is needed. MCPError.datais narrowed toReadonly<Record<string, unknown>> | undefined. The seam has to merge a code intodata; a non-recorddatawould 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 bytscinstead of a runtime branch. Merge rule:dataabsent gives{ code }; a record without a stringcodegetscodeadded after its own members; a record with a stringcodeis left untouched.- One closed registry that imports the core vocabularies unchanged. (Orchestrator decision 2.)
TOOL_ERROR_CODEis a frozen object of the new generic tokens;TOOL_ERROR_CODESis 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 withsatisfies ReadonlyArray<X>plus a compile-time exhaustiveness assertion, so the core file stays unchanged and a new core member failstscuntil the registry lists it. Duplicate tokens across vocabularies (for exampleinvalid_path) are de-duplicated; the list is unique. Tests already pinbudget_exceeded,invalid_action,invalid_target; nothing is renamed. - 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_invalidandpreference_not_foundare already members of imported vocabularies and are reused, not duplicated; the reach refusal keeps its existing kebab tokencaller-supplied-reachand the owner-scope refusal itsforeign-owner/unresolved-identitytokens, which are already named in their messages. - No generic blank code and no silent fallback. (Orchestrator decision 2.)
codeForError(exc)classifies byinstanceofover a closed table of known classes, walkingError.causeto a fixed depth (the feedback rethrow atfeedback-tools.ts:790-795keeps the original ascause). A class that carries its owncodecontributes it only when the guardisToolErrorCodeaccepts it. Anything else maps to the explicit memberinternal_errorand is logged once per occurrence to stderr aswarning: 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.codewas rejected: Node fs errors carryENOENTand would leak an unregistered token. - Skill wire tokens are
skill_not_foundandskill_invalid_path, notNOT_FOUND/INVALID_PATH. TheSkillErrorcodes never reached the wire, so no public contract binds their spelling, and a bareNOT_FOUNDin a cross-tool registry is ambiguous. The coreSkillErrorvocabulary stays unchanged;skill-tools.tsmaps it through a totalRecord<SkillErrorCode, ToolErrorCode>. - Search keeps its UPPER codes.
SearchError.codeis already partly public through the fallback[CODE]suffix, sosearchErrorToMcpputs the same token indata.codeand the suffix stays as legacy text.search-error-mapping.test.ts:16pinsmessagewithtoBe; the message does not change. - Privacy: one code for "absent" and "not visible".
brain_triggermakes both byte-identical (workspace-tools.ts:213-222); the whole transition catch carriestrigger_transition_refused, so the code does not split them either. withProgressRefusalmerges_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.- 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 underrerank-*, and each needs its own sentence indescribeRetrievalDegradation. Casing is kebab, like every member of that vocabulary. RERANK_FAILURE_CATEGORYis 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 outsidecross-encoder.ts; named, not hidden, and its sentence says so). The cross-encoder throwsRerankEndpointError extends SearchErrorwith codeRERANK_PROVIDER_HTTPunchanged,statuswhere it has one, and acategory; the telemetry event gains a requiredcategoryonstatus: "error". Messages stay byte-identical, so thererank_degraded:warning andrerank.search.test.ts:94keep their text. The plainError("expected N scores ...")atrerank/index.ts:226becomes aRerankEndpointErrorwith categorymalformedand the same message.- How rerank codes reach the trail.
PostRankOutcomegainsdegradedparallel towarnings, merged into the sink atsearch.ts:485like every lane's{warnings, degraded}.PostRankInputgainsnowMs, taken from the clock already insearch.tsscope, so the sunset decision is injectable in tests. - Rerank sunset survey reuses the embedding classifier.
src/core/search/rerank/sunset.tsexportsRERANK_SUNSET_SURVEY(typedEmbeddingSunsetSurvey) andclassifyRerankSunset(model, nowMs, survey = RERANK_SUNSET_SURVEY), a thin delegate toclassifyEmbeddingSunset. 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 itssourcestring; the module header records why ZeroEntropy is an open-checkpoint negative rather than a positive (premise correction 5).embeddings/sunset.tsis not edited. - Sunset skip semantics. Only the
announcedstate withdays_remaining < 0skips the HTTP call and returns the heuristic order with codererank-model-sunset(detailempty: 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. Kindslocalanddecision-modelnever consult the survey. - Cache rule. (Orchestrator decision 3.) An outcome whose trail carries
rerank-provider-unavailableis served but never cached, mirroring thedecisionFallbackbypass atsearch.ts:517, so a transient failure is retried on the next identical query. Arerank-model-sunsetoutcome is deterministic for the build and the date, and is cached as today. - 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 afterembeddingsHealthCheckinDOCTOR_CHECKS(doctor.ts:185). It runs only when rerank is enabled with kindopenai-compat. Codes:rerank-endpoint-unconfigured(error: missing base URL, model or key, or an unregisteredsearch_rerank_providername, 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-unsurveyedandrerank-model-sunset-undetermined(uncertain stream). The two actionable codes go toDIAGNOSTIC_SIGNALSwith next commands (o2b search rerank-provider listfor unconfigured,o2b search rerank-provider addfor an announced sunset, since the act is choosing another endpoint or model); the two uncertain codes go toDOCTOR_EXIT_EXCLUSIONSwith a reason, as the embedding precedent does (doctor-exits.ts:219-235). - Codes are fixed tokens.
visibility-matrix.test.tssweeps the serialized response including_meta; no code is ever interpolated with a path or a name. - Docs over descriptions. Codes are documented in
docs/mcp.mdanddocs/cli-reference.md, not in tool descriptions, becauseregistry-guard.ts:51-52caps descriptions; no inputSchema or description changes, soplugins/hermes/_schemas.pyneeds no regeneration.
Orchestrator overrides of the consultant's Variant 1
- Unclassified errors map to
internal_errorand are logged, not to a newunclassifiedmember: the five JSON-RPC defaults already giveinternal_errorthe exact meaning, and a second member would be a blank code by another name. - Classification is by
instanceofover a closed table, not by reading any.codestructurally (fsENOENTwould leak). - Two rerank codes in kebab case instead of one snake
rerank_skipped, matching the vocabulary's casing and cause-in-name precedent. - No
surfacemember in the_metapayload: the tool name is already the request's own, and a second field could drift. - The rerank code is not claimed to appear in
search --explain; it appears in--jsonand MCPbrain_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, helpertests/helpers/tool-error-envelope.ts
Modified:
src/mcp/protocol.ts,src/mcp/server.ts,src/mcp/progress.ts,src/mcp/output-contract.tssrc/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.tssrc/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.jsonminor bump to 1.66.0 plusscripts/sync-version.ts
Risks and open questions
tscmay flag anMCPErrorsite whosedatais typed wider than a record oncedatais narrowed. Mitigation: lane A runstscright 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.- The
_metamerge 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. - The census scan under
src/core/brain/doctor/may require the four doctor codes ascode: "..."literals orconst *_CODEconstants; the check follows the embedding check's spelling so the scan finds them. - 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
reviewedAtto that day. If the page cannot be read, the survey ships with the ZeroEntropy negatives only (sourced) andrerank-model-sunsetis exercised by injected surveys in tests; the producer still exists on the path. - Hermes reads channel B
_metathrough its whole-result serialization; no Python change is expected. The Python suite runs in phase 4 to confirm. - A new tool added later with a new error class is classified
internal_erroruntil it is registered. That is visible (logged by name) rather than silent, which is the intent.