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 - 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.tsis touched by B only. C's two new degradation codes reach itsbrain_searchoutputSchema automatically (the enum is spread fromRETRIEVAL_DEGRADATION_CODES,search-tools.ts:520-545), so C does not edit it.src/mcp/tool-error-codes.tsis A's. B depends on its exports (contract above) and never edits it.tests/core/architecture/verdict-vocabulary-census.test.tsregisters 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.tsis 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.jsonand 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 typecheckafter A2 flags anMCPErrorsite 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_CODESis 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 tokensbudget_exceeded,invalid_action,invalid_target,vault_frozenare members verbatim; (c) every new token matches^[a-z][a-z0-9_]*$; (d)defaultCodeForRpcmaps each of the five JSON-RPC constants to its snake token; (e)codeForErrorreturns the carried code for aWriteBatchError,SearchError,PinnedBatchError;safeguard_timeout/safeguard_abortedfor the safeguard errors;config_unreadableforConfigReadError;config_invalidforBrainConfigError;preference_not_foundfor a plainErrorwhosecauseisBrainPreferenceNotFoundError; (f) a plainError, a Node fs error carryingcode: "ENOENT", and a non-Error throw all returninternal_error, and each writes exactly one stderr linewarning: unclassified tool error mapped to internal_error: <name>(spy onprocess.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); theinstanceoftable is a closedReadonlyArray<[ctor, code | (e) => code]>; the cause walk has a named depth constant; core files are not edited. - Acceptance: the new test passes;
bun run typecheckis 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 answerserror.data.code === "method_not_found"; (b) a tool throwingMCPError(INVALID_PARAMS, msg)with no data answersdata: { code: "invalid_params" }andmessageunchanged; (c) a thrower-supplieddata.code(pinnedbudget_exceeded) is untouched; (d) a recorddatawithout a code (argument guard shape) keeps every member and gainscodelast; (e) a non-MCPErrorthrow outsidetools/callanswersINTERNAL_ERROR, messageinternal error: <redacted>unchanged,data.code === "internal_error", and logs the stderr line. - Implementation notes: narrow
MCPError.datatoReadonly<Record<string, unknown>> | undefinedand addtype JsonRpcErrorCodeover the five constants (decision 3);errorResponse(requestId, code: JsonRpcErrorCode, message, data?)merges the default code (decision 2);stdio.tsandhttp.tstransport 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.tsstill pass unchanged;bun run typecheckclean. - 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].textbyte-identical to v1.65.0,structuredContentabsent,_meta["open-second-brain/error"]equal to{ schema: "o2b.error.v1", code: "safeguard_timeout" }; (b) the output-contract failure inmcp.test.ts:640-643additionally carriesoutput_contract_failed; (c) a call with a progress token over a single-response transport that then fails carries BOTH_metakeys; (d) a successful call with no progress token has no_metakey at all (byte-identical); (e) an unclassified throw carriesinternal_errorand logs once. - Implementation notes:
toolError(message, code)gets its code fromcodeForErrorat the catch (server.ts:463-478);output-contract.tsthrows a namedOutputContractErrorwith the same message and A1's table maps it;withProgressRefusalmerges (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.tspass 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
SearchErrorcode mapped bysearchErrorToMcpyieldsdata.code === <the SearchError code>, withmessageand numeric code unchanged (theEMBEDDING_QUOTA_MESSAGEtoBepin 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.tspass. - 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"; aSkillErrorNOT_FOUNDanswersskill_not_found,INVALID_PATHanswersskill_invalid_path; messages unchanged. - Implementation notes: a total
Record<SkillErrorCode, ToolErrorCode>(decision 7);src/core/surface/skills.tsis 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_intentionorbrain_triggeroperation answersunknown_operation; an unknown trigger status answersinvalid_status; a transition on an absent id and on an id the caller may not see answer the SAMEtrigger_transition_refusedand 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_idanswerssession_id_required; an unknown id answerswrite_session_unknown; a terminal session answerswrite_session_terminal; an error carryingerrors[]keepsdata.errorsbyte-identical and gains the seam defaultinvalid_params; messages unchanged. - Implementation notes:
WriteSessionRequestErrorgains an optionalcode(constructor option, so every other site stays valid and keeps the seam default, which matches its JSON-RPC code);context-tools.ts:164-173forwards it intodata. - Acceptance: test passes;
tests/core/brain/write-session*andtests/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"withtool,unknown_arguments,declared_argumentsunchanged; a caller-supplied reach answerscaller-supplied-reach; an owner-scope refusal answersforeign-ownerorunresolved-identityas its outcome names. - Acceptance: test passes;
argument-guard.test.ts,reach-refusal.test.ts,owner-scope-refusal.test.tspass 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:
rerankCategoryForStatusmaps 401/403 auth, 402 quota, 404/410 gone, 408/429/5xx transient, other 4xx rejected; withtests/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 keepscode === "RERANK_PROVIDER_HTTP"and its v1.65.0 message; a provider throwing a plainErroryieldsunclassified. - 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.tspasses 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, andretrieval_trail.degradedcontaining{ 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.degradedmerged atsearch.ts:485; the cache bypass sits beside thedecisionFallbackrule atsearch.ts:517. - Acceptance: tests pass;
tests/mcp/search-retrieval-trail.test.tsandtests/cli/search-retrieval-trail.test.tspass 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, andreviewedAtparses; (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 carriesrerank-model-sunset; (c) a future announced date, an off-survey model and a surveyed negative all call the endpoint as today; (d) kindslocalanddecision-modelnever 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.0models with the date and announcement the page states; read https://zeroentropy.dev/articles/zeroentropy-is-joining-notion/ and the model cards for thezerank-*checkpoints and record them as open-checkpoint negatives with that source. SetreviewedAtto 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;
nowMsreaches post-rank from the existing clock insearch.ts, neverDate.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)readsresult._meta[TOOL_ERROR_META_KEY].code;readRpcErrorCode(response)readsresponse.error.data.code; both import A1's constants and throw a named assertion error when the member is missing, never returnundefinedsilently. - Acceptance:
bun run typecheckclean. - 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_CODEandRERANK_FAILURE_CATEGORYas unregistered. - Implementation notes: register both beside the
EMBEDDING_SUNSET*andRETRIEVAL_DEGRADATIONentries; 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-compatwith no base URL, no model, no key, or an unregisteredsearch_rerank_providername: onererank-endpoint-unconfigurederror; (c) an injected survey with an announced date inside 90 days or in the past:rerank-model-sunset-announcedwarning naming the model and the date; (d) off-survey model:rerank-model-sunset-unsurveyeduncertain; stale survey:rerank-model-sunset-undetermineduncertain; (e) the check makes no network call; (f)tests/core/brain/doctor-exit-census.test.tspasses with the four codes registered. - Implementation notes: decision 17; the factory takes the survey as a parameter (as
makeEmbeddingSunsetCheckdoes); the window isEMBEDDING_SUNSET_WARNING_WINDOW_DAYSimported, not a second literal; registered afterembeddingsHealthCheckinDOCTOR_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:checkandcheck:paths. - Content:
docs/mcp.mdgains "### Tool errors (since v1.66.0)" under "Protocol": the two channels,error.data.codeand_meta["open-second-brain/error"], the payload shape, the closed code list (generic tokens plus a pointer to each imported vocabulary), the casing note, theinternal_errorrule, and that text bodies are unchanged.docs/cli-reference.md: trail table gainshybrid-deadline-exceeded(orchestrator decision 4),rerank-provider-unavailable(with thedetail.categorymembers) andrerank-model-sunset; the doctor section lists the four rerank codes.docs/how-it-works.md:1096names the trail code beside thererank_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)