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
fix: v1.19.1 - cross-vault cards, event-trace exit codes, registry-guard hygiene (#113)
Sol Aitkena3ea3151e1e1
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 5aa3a562..25f21ea4 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.19.0",+ "version": "1.19.1","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.jsonindex 77ce35bd..4113eb80 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.19.0",+ "version": "1.19.1","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex abeb458a..e6bcda81 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,38 @@ 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.19.1] - 2026-06-26++Three correctness and hygiene follow-ups deferred from the v1.18.0 review,+shipped together. No behaviour changes beyond the fixes; the kernel still+calls no LLM and the default `full` search path stays byte-identical.++### Fixed++- **Cross-vault search now returns `disclosure: "cards"` results+ (`t_fd411665`).** In `--global` (cross-vault) mode a cards search returned+ nothing: single-vault `search()` puts cards on `outcome.cards` and leaves+ `outcome.results` empty, but `searchAcrossVaults` merged only `results`, so+ every origin's cards were dropped. The union now merges each origin's cards+ (labelled by origin, ranked and capped like results) and returns them on+ `outcome.cards` with `results` empty, mirroring single-vault semantics. The+ normalized-confidence chain-stop now gates on the top card score when cards+ mode leaves `results` empty.+- **A genuine event-trace IO error is a runtime failure, not a usage error+ (`t_27ea0daa`).** `o2b brain event-trace` mapped any throw from the resolver+ to a usage error (exit 2). A real IO failure from the log-shard reader (an+ existing-but-unreadable `Brain/log`: EACCES / EIO / ENOTDIR) is now exit 1,+ while a bad `--date` / `--at` / `--kind` selector stays exit 2. The MCP twin+ `brain_event_trace` likewise maps a runtime IO error to `INTERNAL_ERROR` and+ a bad selector to `INVALID_PARAMS`, via a shared `EventTraceSelectorError`+ tag thrown only by the pre-IO selector checks.+- **Registry-guard exempt membership is own-key only (`t_6fbdba4b`).**+ `auditPreviewBudgets` tested exemption with `name in PREVIEW_BUDGET_EXEMPT`,+ which walks the prototype chain - so a tool named like an `Object.prototype`+ member (`constructor`, `toString`, ...) would be falsely treated as exempt+ and escape the unbudgeted-output guard. Membership now uses a name set+ hoisted once at module load, removing the per-call `Object.keys` as well.+## [1.19.0] - 2026-06-24Session-boundary capture durability and a post-compaction survival@@ -6018,6 +6050,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.19.1]: https://github.com/itechmeat/open-second-brain/compare/v1.19.0...v1.19.1[1.19.0]: https://github.com/itechmeat/open-second-brain/compare/v1.18.1...v1.19.0[1.18.1]: https://github.com/itechmeat/open-second-brain/compare/v1.18.0...v1.18.1[1.18.0]: https://github.com/itechmeat/open-second-brain/compare/v1.17.0...v1.18.0diff --git a/README.md b/README.mdindex c79006b7..22fe99e9 100644--- a/README.md+++ b/README.md@@ -98,7 +98,7 @@ Each non-Hermes target writes a sidecar manifest under `<vault>/.open-second-bra- **Operational readability for code partners and large vaults.** Open Second Brain now exposes a read-only CodeGraph report (`o2b partner codegraph report`, `brain_codegraph_report`) that resolves the in-scope code project, reports the codegraph index state with node and edge counts, and structurally parses Cargo.toml for Rust workspace members. The report is honest about missing CLIs, missing indexes, and non-Rust projects. For large vaults, community materialization can run in fixed-size batches (`o2b brain clusters run --batch-size N`, `brain_clusters` `batch_size`) with per-batch success or isolated failure reporting, while the default run stays byte-identical.- **Consistent feedback categorization.** A vault-local `feedback.default_scope` in `Brain/_brain.yaml` gives agent-recorded signals a consistent category (for example `coding`) when no explicit scope is provided, with the same precedence across the inbox signal, its shared-namespace mirror, and any force-confirmed preference. The effective scope is computed once at the signal write boundary and byte-identical output is preserved when the setting is absent or no explicit scope is given.- **Path-safe vault writes.** The write-session commit chokepoint now re-resolves every target through `ensureInsideVault` before any directory creation, read, or write, catching symlinked ancestors that point outside the vault root. The backstop fails closed: a target resolving outside the configured vault is rejected and nothing is written. All other caller-derived vault paths already funnel through guarded constructors; regression tests pin both invariants.-- **Recall that pays for depth only on demand.** General vault search now offers the same progressive 3-layer disclosure session-recall already had. `o2b search "<q>" --disclosure cards` (and the `brain_search` `disclosure: "cards"` field) returns compact layer-1 cards - path, title, score, reasons, a bounded snippet, and a `path:Lstart-Lend` pointer - instead of full content per hit, so recall stays token-cheap. Drill a hit with `o2b search expand --chunk <id>` (or `brain_search_expand`) to get layer 2 (the fuller note) and layer 3 (the raw chunk transcript, paginated by cursor). It reuses the existing index read - no new index, no model - and the default `full` mode is byte-identical to before.+- **Recall that pays for depth only on demand.** General vault search now offers the same progressive 3-layer disclosure session-recall already had. `o2b search "<q>" --disclosure cards` (and the `brain_search` `disclosure: "cards"` field) returns compact layer-1 cards - path, title, score, reasons, a bounded snippet, and a `path:Lstart-Lend` pointer - instead of full content per hit, so recall stays token-cheap. Drill a hit with `o2b search expand --chunk <id>` (or `brain_search_expand`) to get layer 2 (the fuller note) and layer 3 (the raw chunk transcript, paginated by cursor). It reuses the existing index read - no new index, no model - and the default `full` mode is byte-identical to before. Cards compose with cross-vault recall too: `--global --disclosure cards` returns the token-cheap layer-1 cards merged across every origin (each labelled by its origin), not an empty result set.That is the day-to-day picture. The full capability surface, every CLI verb, and the mental model live in the [documentation](#documentation) below.diff --git a/docs/brainstorm/crossvault-cards-eventtrace-fixes/design.md b/docs/brainstorm/crossvault-cards-eventtrace-fixes/design.mdnew file mode 100644index 00000000..1e48fb52--- /dev/null+++ b/docs/brainstorm/crossvault-cards-eventtrace-fixes/design.md@@ -0,0 +1,112 @@+# Design - Cross-vault cards, event-trace exit codes, registry-guard hygiene++## Problem++Three follow-ups deferred from the v1.18.0 CodeRabbit review on PR #110, all+correctness/hygiene gaps on primary paths:++1. **Cross-vault search drops `disclosure: "cards"` results (t_fd411665).**+ In `--global` mode a cards-mode search returns nothing. Single-vault+ `search()` in cards mode puts hits on `outcome.cards` and leaves+ `outcome.results` empty; `searchAcrossVaults` only merges and ranks+ `outcome.results`, so every origin's cards are dropped and the union is+ empty. Cards mode is the recommended token-cheap first layer, so the gap+ sits on a primary recall path. The chain-stop also no-ops in cards mode+ because it gates on `results`.++2. **A genuine IO error from event-trace surfaces as a usage error+ (t_27ea0daa).** `cmdBrainEventTrace`'s blanket `catch` maps ANY throw from+ `resolveLogEventTraces` to `usageError` (exit 2). That is correct for the+ selector checks (`--date` / `--at` / `--kind`) which run before any IO,+ but `readLogDay -> listLogShardFiles` calls `readdirSync` guarded only by+ `existsSync`: an existing-but-unreadable log dir (EACCES) or an EIO is a+ runtime failure that must be exit 1, not exit 2. The MCP twin+ `toolBrainEventTrace` has the identical blanket catch, mapping a runtime IO+ error to `INVALID_PARAMS` instead of an internal error.++3. **Registry-guard membership check uses the `in` operator (t_6fbdba4b).**+ `auditPreviewBudgets` tests exemption with `tool.name in+ PREVIEW_BUDGET_EXEMPT` and recomputes `Object.keys(...)` on every call.+ `in` walks the prototype chain, so a tool whose name collides with an+ `Object.prototype` member (`constructor`, `toString`, `hasOwnProperty`, ...)+ is falsely reported exempt; the per-call `Object.keys` is avoidable work.++## Scope++- `src/core/search/cross-vault.ts` - make `searchAcrossVaults` cards-aware.+- `src/core/brain/event-trace.ts` - tag selector-validation errors with a+ distinct error type.+- `src/cli/brain/verbs/event-trace.ts` - route selector errors to exit 2 and+ runtime errors to exit 1.+- `src/mcp/brain/pack-tools.ts` - route the MCP twin's selector errors to+ `INVALID_PARAMS` and runtime errors to `INTERNAL_ERROR`.+- `src/mcp/registry-guard.ts` - hoist the exempt-name set once; use own-key+ membership instead of `in`.++## Out of scope++- No change to single-vault cards semantics, `expandHit` layers, or the+ progressive-disclosure grammar.+- No change to the continuity store, the log shard format, or selector syntax.+- No new MCP tools, flags, or output fields beyond making `cards` flow through+ the union (the `SearchCard.origin` field already exists).++## Chosen approach (Variant B - focused per-seam fixes)++1. **Cross-vault cards.** Accumulate each origin's `outcome.cards` into a+ `mergedCards` array, labelled by origin via a `labelledCard` helper that+ mirrors the existing `labelled` (sets `origin` and an `origin:<label>`+ reason). Detect cards mode from `opts.disclosure === "cards"`. The+ chain-stop gate reads the active origin's top score over whichever+ collection is populated (cards in cards mode, results otherwise). On return:+ full mode is byte-identical to today (`results` capped, no `cards`); cards+ mode returns sorted/capped `cards` with `results` empty, mirroring+ single-vault semantics. A shared comparator orders by score desc, then+ origin label, path, chunk id.++2. **Event-trace error classification.** Introduce+ `EventTraceSelectorError extends Error` in `event-trace.ts`. The three+ selector checks (`validateIsoDate` wrap, `--at` format, `--kind` membership)+ throw it; nothing on the IO path does. The CLI verb catch returns+ `usageError` (exit 2) for `EventTraceSelectorError` and `fail` (exit 1)+ otherwise. The MCP handler returns `INVALID_PARAMS` for the selector error+ and `INTERNAL_ERROR` otherwise.++3. **Registry-guard hygiene.** Precompute+ `PREVIEW_BUDGET_EXEMPT_NAMES = new Set(Object.keys(PREVIEW_BUDGET_EXEMPT))`+ at module load and use `.has()` for membership; reuse it for the+ `exemptButUnknown` scan. This removes the per-call `Object.keys` and the+ prototype-chain false positive in one change.++## Design decisions++- **One shared selector-error type for both event-trace entry points.** The+ CLI verb and the MCP tool wrap the same resolver and had the same blanket+ catch; classifying once in the resolver fixes both without duplicating+ format-validation logic. (Avoids a cheap one-surface-only fix.)+- **Cards flow through the existing union, not a parallel function.** The+ read-only invariants, session-focus resolution, and chain-stop policy are+ identical for cards and full mode; only the collection being merged differs.+- **`Set` over `Object.hasOwn`.** Both fix the prototype gotcha; the hoisted+ `Set` additionally removes the repeated `Object.keys` allocation.++## File changes++| File | Change |+|---|---|+| `src/core/search/cross-vault.ts` | cards accumulator + `labelledCard` + card comparator; cards-mode chain-stop gate and return shape |+| `src/core/brain/event-trace.ts` | export `EventTraceSelectorError`; selector checks throw it |+| `src/cli/brain/verbs/event-trace.ts` | catch routes selector vs runtime to exit 2 vs exit 1 |+| `src/mcp/brain/pack-tools.ts` | catch routes selector vs runtime to `INVALID_PARAMS` vs `INTERNAL_ERROR` |+| `src/mcp/registry-guard.ts` | hoisted exempt-name `Set`; `.has()` membership |++## Risks++- **Cross-vault return-shape regression.** Mitigated: full mode must stay+ byte-identical; covered by the existing union tests plus a new cards-mode+ test asserting `results` empty and `cards` labelled per origin.+- **Mis-tagging a runtime error as a selector error (or vice versa).** Mitigated+ by throwing the typed error ONLY in the three pre-IO checks and asserting an+ EACCES/EIO surfaces as exit 1 / `INTERNAL_ERROR` in tests.+- **A real tool legitimately named like a prototype member.** None exists today;+ the `Set` makes the guard correct if one is ever added.diff --git a/docs/brainstorm/crossvault-cards-eventtrace-fixes/plan.md b/docs/brainstorm/crossvault-cards-eventtrace-fixes/plan.mdnew file mode 100644index 00000000..a0eb4993--- /dev/null+++ b/docs/brainstorm/crossvault-cards-eventtrace-fixes/plan.md@@ -0,0 +1,62 @@+# Plan - per-task implementation (TDD)++Release scope (ship together, one PR, branch `feat/crossvault-cards-eventtrace-fixes`):++- `t_fd411665` (p3) - cross-vault cards merge+- `t_27ea0daa` (p1) - event-trace IO error exit code (+ MCP twin)+- `t_6fbdba4b` (p1) - registry-guard membership hygiene++Cards are driven one at a time on the shared branch; each commit builds on the+previous. Follow each section under TDD: failing test first, watch it fail,+minimal code, green.++## t_fd411665 - cross-vault cards-aware union++**Files:** `src/core/search/cross-vault.ts`; test `tests/core/search/cross-vault.test.ts`.++**Acceptance (failing test first):**+- `searchAcrossVaults(config, active, { query, limit, disclosure: "cards" })`+ with a recall source returns `outcome.cards` containing cards from BOTH+ origins, each carrying its `origin` label and an `origin:<label>` reason, and+ `outcome.results` is empty.+- `limit` caps the merged cards; `total` sums per-origin totals.+- Full mode (no `disclosure`) stays byte-identical (existing tests pass).+- Cards-mode chain-stop: a confident active origin (threshold 0) skips the+ remaining origins and records `chainStop` gated on the top CARD score.++**Steps:** add `labelledCard`; add a `mergedCards` accumulator in the loop;+derive `cardsMode`; gate chain-stop on the populated collection; return cards+(sorted/capped, `results: []`) in cards mode, results otherwise.++## t_27ea0daa - event-trace runtime IO error is exit 1, not exit 2++**Files:** `src/core/brain/event-trace.ts`, `src/cli/brain/verbs/event-trace.ts`,+`src/mcp/brain/pack-tools.ts`; tests `tests/cli/brain-event-trace.test.ts`,+`tests/mcp/event-trace-tool.test.ts`.++**Acceptance (failing test first):**+- An unreadable/erroring log dir makes the CLI verb exit 1 (runtime), while a+ bad `--date`/`--at`/`--kind` stays exit 2 (usage).+- The MCP tool maps the same runtime IO error to `INTERNAL_ERROR`, and a bad+ selector to `INVALID_PARAMS`.++**Steps:** export `EventTraceSelectorError`; throw it from the three pre-IO+selector checks (wrap `validateIsoDate`); branch on `instanceof` in both+catches.++## t_6fbdba4b - registry-guard exempt membership++**Files:** `src/mcp/registry-guard.ts`; test `tests/mcp/registry-guard.test.ts`.++**Acceptance (failing test first):**+- A tool named like an `Object.prototype` member (e.g. `toString`) with neither+ a budget nor an exempt entry is reported in `unbudgetedAndUnexempted` (today+ `in` falsely treats it exempt).++**Steps:** hoist `PREVIEW_BUDGET_EXEMPT_NAMES = new Set(Object.keys(...))`; use+`.has()` for the exempt check and the `exemptButUnknown` scan.++## Depends on++Independent fixes; no inter-task code dependency. Order chosen for smallest+review surface: event-trace, then cross-vault, then registry-guard.diff --git a/docs/brainstorm/crossvault-cards-eventtrace-fixes/variants.md b/docs/brainstorm/crossvault-cards-eventtrace-fixes/variants.mdnew file mode 100644index 00000000..be5f5df4--- /dev/null+++ b/docs/brainstorm/crossvault-cards-eventtrace-fixes/variants.md@@ -0,0 +1,42 @@+# Variants++Three approaches to shipping the three v1.18.0 review follow-ups together.++## Variant A - Minimal independent patches++Fix each site in isolation: add a second `catch`-branch heuristic in the CLI+verb only (string-match the error), special-case cards in the cross-vault+return, swap `in` for `Object.hasOwn` in the guard.++- **Trade-offs:** smallest diff; but the event-trace fix would be string/shape+ heuristics (fragile), would leave the MCP twin broken (a half fix), and would+ not share the classification.+- **Complexity:** small. **Risk:** medium (fragile heuristics; known broken twin).++## Variant B - Focused per-seam fixes with one shared error type (RECOMMENDED)++Classify event-trace selector errors once in the resolver via a typed error,+consumed by both the CLI verb and the MCP tool; flow cards through the existing+cross-vault union (not a parallel path); hoist the guard's exempt set.++- **Trade-offs:** fixes both event-trace entry points without duplicating+ format-validation; reuses the union's read-only invariants and chain-stop+ policy for cards; one cohesive change per concern.+- **Complexity:** medium. **Risk:** low.++## Variant C - Broader refactor++Introduce a generic `runVerb` error-policy wrapper for ALL brain verbs, and+generalize `searchAcrossVaults` to fold results and cards through one+collection-agnostic merge pipeline shared with single-vault `search()`.++- **Trade-offs:** most future-proof, but far exceeds three bug fixes; touches+ unrelated verbs and the single-vault path, inflating review and regression+ surface for a patch release.+- **Complexity:** large. **Risk:** high.++## Recommended: Variant B++It does each fix right (no known-broken twin, no fragile heuristics) while+keeping the diff scoped to a patch release. Variant A is rejected for shipping a+half fix; Variant C for scope creep disproportionate to three deferred bugs.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 67a32970..c5ec3f6c 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.19.0",+ "version": "1.19.1","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 832b81e7..5fbe7df8 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.19.0",+ "version": "1.19.1","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.yamlindex 7850318e..6aa10cfc 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.19.0"+version: "1.19.1"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 8497fddb..23acbb19 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.19.0",+ "version": "1.19.1","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/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 7850318e..6aa10cfc 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.19.0"+version: "1.19.1"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex a6072803..90b24681 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.19.0"+version = "1.19.1"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/cli/brain/verbs/event-trace.ts b/src/cli/brain/verbs/event-trace.tsindex 87d60621..024ce4d3 100644--- a/src/cli/brain/verbs/event-trace.ts+++ b/src/cli/brain/verbs/event-trace.ts@@ -1,10 +1,11 @@import {+ EventTraceSelectorError,resolveLogEventTraces,type AttachedTrace,type LogEventTrace,} from "../../../core/brain/event-trace.ts";import { BRAIN_LOG_EVENT_KIND_SET, type BrainLogEventKind } from "../../../core/brain/types.ts";-import { brainVerbContext, parse, usageError } from "../helpers.ts";+import { brainVerbContext, fail, parse, usageError } from "../helpers.ts";/*** `o2b brain event-trace` — given one or more logged Brain events,@@ -53,10 +54,14 @@ export async function cmdBrainEventTrace(argv: string[]): Promise<number> {...(flags["keep-private"] === true ? { keepPrivate: true } : {}),});} catch (err) {- // The resolver validates selectors (--date, --at, --kind) before any IO- // and a missing log day reads as empty rather than throwing, so a throw- // here is a selector usage error: exit 2, not the runtime exit-1 path.- return usageError(`brain event-trace: ${(err as Error).message}`);+ // A selector-validation error (bad --date/--at/--kind, checked before any+ // IO) is a usage error: exit 2. ANY OTHER throw is a runtime failure - e.g.+ // an existing-but-unreadable log dir (EACCES/EIO/ENOTDIR) from the shard+ // reader - and must be the runtime exit-1 path, not a usage error.+ if (err instanceof EventTraceSelectorError) {+ return usageError(`brain event-trace: ${err.message}`);+ }+ return fail(`brain event-trace: ${(err as Error).message}`);}if (flags["json"]) {diff --git a/src/core/brain/event-trace.ts b/src/core/brain/event-trace.tsindex 3072eea2..5a7a78bd 100644--- a/src/core/brain/event-trace.ts+++ b/src/core/brain/event-trace.ts@@ -40,6 +40,21 @@ import type { NormalizedContinuityRecord } from "./continuity/read-model.ts";import { validateIsoDate } from "./paths.ts";import { BRAIN_LOG_EVENT_KIND_SET, type BrainLogEventKind } from "./types.ts";+/**+ * A selector-validation failure: a bad `--date` / `--at` / `--kind`, detected+ * BEFORE any IO. Entry points map this to a usage error (CLI exit 2 / MCP+ * `INVALID_PARAMS`); ANY OTHER throw from {@link resolveLogEventTraces} is a+ * runtime IO failure (e.g. an existing-but-unreadable log dir: EACCES / EIO /+ * ENOTDIR) and must surface as a runtime error (CLI exit 1 / MCP+ * `INTERNAL_ERROR`), never as a usage error. (t_27ea0daa)+ */+export class EventTraceSelectorError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "EventTraceSelectorError";+ }+}+/** Why a continuity record was attached to a given log event. */export type TraceJoinReason = "session" | "turn" | "artifact";@@ -171,12 +186,14 @@ export function resolveLogEventTraces(vault: string,selector: EventTraceSelector = {},): ReadonlyArray<LogEventTrace> {- const date = selector.date !== undefined ? validateIsoDate(selector.date) : todayUtc();+ const date = selector.date !== undefined ? validateSelectorDate(selector.date) : todayUtc();if (selector.at !== undefined && !/^\d{2}:\d{2}:\d{2}$/.test(selector.at)) {- throw new Error(`event-trace: --at must be HH:MM:SS (UTC); got ${JSON.stringify(selector.at)}`);+ throw new EventTraceSelectorError(+ `event-trace: --at must be HH:MM:SS (UTC); got ${JSON.stringify(selector.at)}`,+ );}if (selector.kind !== undefined && !BRAIN_LOG_EVENT_KIND_SET.has(selector.kind)) {- throw new Error(`event-trace: unknown event kind '${selector.kind}'`);+ throw new EventTraceSelectorError(`event-trace: unknown event kind '${selector.kind}'`);}const { entries } = readLogDay(vault, date);@@ -298,3 +315,16 @@ function readBodyString(value: unknown): string | undefined {function todayUtc(): string {return new Date().toISOString().slice(0, 10);}++/**+ * Validate the `--date` selector. `validateIsoDate` throws a generic `Error`;+ * re-tag a bad date as a selector error so callers route it to the usage path,+ * not the runtime-failure path. (t_27ea0daa)+ */+function validateSelectorDate(date: string): string {+ try {+ return validateIsoDate(date);+ } catch (err) {+ throw new EventTraceSelectorError((err as Error).message);+ }+}diff --git a/src/core/search/cross-vault.ts b/src/core/search/cross-vault.tsindex dbb8de47..a3265756 100644--- a/src/core/search/cross-vault.ts+++ b/src/core/search/cross-vault.ts@@ -30,6 +30,7 @@ import { readActiveSessionFocus } from "./session-focus.ts";import type {BrainSearchResult,ResolvedSearchConfig,+ SearchCard,SearchOptions,SearchOutcome,} from "./types.ts";@@ -42,8 +43,25 @@ function labelled(result: BrainSearchResult, label: string): BrainSearchResult {});}+/** Cards mirror results: same origin label, same `origin:<label>` reason. */+function labelledCard(card: SearchCard, label: string): SearchCard {+ return Object.freeze({+ ...card,+ origin: label,+ reasons: Object.freeze([...card.reasons, `origin:${label}`]),+ });+}++/** The fields the merge order reads - shared by results and cards. */+interface MergeKey {+ readonly score: number;+ readonly origin?: string;+ readonly path: string;+ readonly chunkId: number;+}+/** Deterministic merge order: score desc, then label, path, chunk id. */-function compareMerged(a: BrainSearchResult, b: BrainSearchResult): number {+function compareMerged(a: MergeKey, b: MergeKey): number {if (a.score !== b.score) return b.score - a.score;const al = a.origin ?? "";const bl = b.origin ?? "";@@ -66,7 +84,12 @@ export async function searchAcrossVaults(): Promise<SearchOutcome> {const origins = listSearchOrigins(configPath, activeVault);const limit = Math.max(1, Math.min(100, opts.limit ?? 10));+ // Cards mode (disclosure: "cards") puts each origin's hits on `outcome.cards`+ // and leaves `outcome.results` empty; full mode is the reverse. Merge the+ // collection this mode populates and mirror single-vault return semantics.+ const cardsMode = opts.disclosure === "cards";const merged: BrainSearchResult[] = [];+ const mergedCards: SearchCard[] = [];const warnings: string[] = [];let total = 0;@@ -119,6 +142,9 @@ export async function searchAcrossVaults(...(isActive ? {} : { selfHeal: false }),});merged.push(...outcome.results.map((result) => labelled(result, origin.label)));+ if (outcome.cards !== undefined) {+ mergedCards.push(...outcome.cards.map((card) => labelledCard(card, origin.label)));+ }warnings.push(...outcome.warnings.map((warning) => `[${origin.label}] ${warning}`));total += outcome.total;// Chain-stop: if this origin answered confidently (its top NORMALIZED@@ -131,11 +157,16 @@ export async function searchAcrossVaults(// does not short-circuit. Only recorded when origins were actually// skipped, keeping the single-origin and never-triggered paths identical.const remaining = origins.slice(i + 1);- const topScore = outcome.results.reduce((max, r) => Math.max(max, r.score), 0);+ // Gate on whichever collection THIS mode populates: in cards mode results+ // is empty, so reading it would never short-circuit (the latent bug).+ const hits: ReadonlyArray<{ readonly score: number }> = cardsMode+ ? (outcome.cards ?? [])+ : outcome.results;+ const topScore = hits.reduce((max, h) => Math.max(max, h.score), 0);if (activeRecall.chainStopEnabled &&remaining.length > 0 &&- outcome.results.length > 0 &&+ hits.length > 0 &&topScore >= activeRecall.chainStopScore) {chainStop = Object.freeze({@@ -151,11 +182,15 @@ export async function searchAcrossVaults(}merged.sort(compareMerged);+ mergedCards.sort(compareMerged);return Object.freeze({- results: Object.freeze(merged.slice(0, limit)),+ // Cards mode mirrors single-vault semantics: hits ride `cards`, `results`+ // is empty. Full mode is byte-identical to before (no `cards` key).+ results: cardsMode ? Object.freeze([]) : Object.freeze(merged.slice(0, limit)),+ ...(cardsMode ? { cards: Object.freeze(mergedCards.slice(0, limit)) } : {}),warnings: Object.freeze(warnings),// Sum of per-origin totals - informational, mirrors single-vault- // semantics where `total` can exceed the capped `results` length.+ // semantics where `total` can exceed the capped result/card length.total,...(chainStop ? { chainStop } : {}),});diff --git a/src/mcp/brain/pack-tools.ts b/src/mcp/brain/pack-tools.tsindex 6b5442bd..afaacfaf 100644--- a/src/mcp/brain/pack-tools.ts+++ b/src/mcp/brain/pack-tools.ts@@ -33,9 +33,9 @@ import {type ContextPresetCurrentConfig,} from "../../core/brain/context-presets.ts";import { extractPreCompactRecords } from "../../core/brain/pre-compact-extract.ts";-import { resolveLogEventTraces } from "../../core/brain/event-trace.ts";+import { EventTraceSelectorError, resolveLogEventTraces } from "../../core/brain/event-trace.ts";import { BRAIN_LOG_EVENT_KIND_SET, type BrainLogEventKind } from "../../core/brain/types.ts";-import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";import type { ServerContext, ToolDefinition } from "../tools.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import { coerceStr, coerceStrList, coerceBool } from "../coerce.ts";@@ -226,7 +226,14 @@ async function toolBrainEventTrace(...(keepPrivate === true ? { keepPrivate: true } : {}),});} catch (err) {- throw new MCPError(INVALID_PARAMS, `brain_event_trace: ${(err as Error).message}`);+ // A selector-validation error (bad date/at/kind, checked before any IO) is+ // a caller error (INVALID_PARAMS). ANY OTHER throw is a runtime IO failure -+ // e.g. an existing-but-unreadable log dir (EACCES/EIO/ENOTDIR) - and must be+ // an internal error, not a parameter error.+ if (err instanceof EventTraceSelectorError) {+ throw new MCPError(INVALID_PARAMS, `brain_event_trace: ${err.message}`);+ }+ throw new MCPError(INTERNAL_ERROR, `brain_event_trace: ${(err as Error).message}`);}return {diff --git a/src/mcp/registry-guard.ts b/src/mcp/registry-guard.tsindex 2f55d091..cb9a6ae7 100644--- a/src/mcp/registry-guard.ts+++ b/src/mcp/registry-guard.ts@@ -131,6 +131,17 @@ export const PREVIEW_BUDGET_EXEMPT: Readonly<Record<string, string>> = Object.fr// themselves in the 1.0.0 sweep (tombstones in REMOVED_TOOLS).});+/**+ * Own-key membership set for {@link PREVIEW_BUDGET_EXEMPT}, computed once at+ * module load. Replaces `name in PREVIEW_BUDGET_EXEMPT`, which walks the+ * prototype chain (so a tool named like an `Object.prototype` member -+ * `constructor`, `toString`, `hasOwnProperty` - would be falsely treated as+ * exempt) and recomputed `Object.keys` on every call. (t_6fbdba4b)+ */+const PREVIEW_BUDGET_EXEMPT_NAMES: ReadonlySet<string> = new Set(+ Object.keys(PREVIEW_BUDGET_EXEMPT),+);+export interface PreviewBudgetAudit {/** Tools with neither a budget nor an exempt entry - the guard fails on these. */readonly unbudgetedAndUnexempted: ReadonlyArray<string>;@@ -145,11 +156,11 @@ export function auditPreviewBudgets(tools: ReadonlyArray<ToolDefinition>): Previconst unbudgetedAndUnexempted: string[] = [];const exemptButBudgeted: string[] = [];for (const tool of tools) {- const exempt = tool.name in PREVIEW_BUDGET_EXEMPT;+ const exempt = PREVIEW_BUDGET_EXEMPT_NAMES.has(tool.name);if (tool.previewBudget === undefined && !exempt) unbudgetedAndUnexempted.push(tool.name);if (tool.previewBudget !== undefined && exempt) exemptButBudgeted.push(tool.name);}- const exemptButUnknown = Object.keys(PREVIEW_BUDGET_EXEMPT).filter((n) => !names.has(n));+ const exemptButUnknown = [...PREVIEW_BUDGET_EXEMPT_NAMES].filter((n) => !names.has(n));return Object.freeze({unbudgetedAndUnexempted: Object.freeze(unbudgetedAndUnexempted),exemptButBudgeted: Object.freeze(exemptButBudgeted),diff --git a/tests/cli/brain-event-trace.test.ts b/tests/cli/brain-event-trace.test.tsindex eb40b8ed..22a3a054 100644--- a/tests/cli/brain-event-trace.test.ts+++ b/tests/cli/brain-event-trace.test.ts@@ -5,7 +5,7 @@*/import { afterEach, beforeEach, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -45,3 +45,15 @@ test("a clean run over an empty log exits 0", async () => {const r = await runCli(["brain", "event-trace", "--vault", vault, "--json"]);expect(r.returncode).toBe(0);});++test("a runtime IO error reading the log dir is exit 1, not a usage error (exit 2)", async () => {+ // Brain/log exists but is a FILE, not a directory: existsSync passes the+ // guard in listLogShardFiles, then readdirSync throws ENOTDIR. That is a+ // runtime failure (exit 1), distinct from a selector usage error (exit 2) -+ // the selectors here are all valid, so the only throw is the IO one.+ const ioVault = join(tmp, "io-vault");+ mkdirSync(join(ioVault, "Brain"), { recursive: true });+ writeFileSync(join(ioVault, "Brain", "log"), "not a directory\n");+ const r = await runCli(["brain", "event-trace", "--vault", ioVault, "--json"]);+ expect(r.returncode).toBe(1);+});diff --git a/tests/core/search/cross-vault.test.ts b/tests/core/search/cross-vault.test.tsindex 3dc049d3..8d13351a 100644--- a/tests/core/search/cross-vault.test.ts+++ b/tests/core/search/cross-vault.test.ts@@ -94,6 +94,58 @@ test("single-origin union (no profiles, no sources) matches plain search shape",expect(outcome.results.every((r) => r.origin === "local")).toBe(true);});+// t_fd411665 - cards-mode (disclosure: "cards") must compose with the union:+// each origin returns its hits on `outcome.cards` with `results` empty, and the+// union has to merge the cards, not silently drop them.+test("cards mode: cards from every origin merge, labelled, with results empty", async () => {+ addRecallSource(configPath, active, "team", external);+ const outcome = await searchAcrossVaults(configPath, active, {+ query: "griffin",+ limit: 10,+ disclosure: "cards",+ });+ expect(outcome.results).toHaveLength(0);+ expect(outcome.cards).toBeDefined();+ const labels = new Set((outcome.cards ?? []).map((c) => c.origin));+ expect(labels).toEqual(new Set(["local", "source/team"]));+ for (const c of outcome.cards ?? []) {+ expect(c.reasons.some((reason) => reason.startsWith("origin:"))).toBe(true);+ }+ const scores = (outcome.cards ?? []).map((c) => c.score);+ expect([...scores].toSorted((a, b) => b - a)).toEqual(scores);+});++test("cards mode: limit caps the merged card set", async () => {+ addRecallSource(configPath, active, "team", external);+ const outcome = await searchAcrossVaults(configPath, active, {+ query: "griffin",+ limit: 1,+ disclosure: "cards",+ });+ expect(outcome.cards).toHaveLength(1);+ expect(outcome.results).toHaveLength(0);+ expect(outcome.total).toBeGreaterThanOrEqual(2);+});++test("cards mode: chain-stop gates on the top CARD score and skips remaining origins", async () => {+ addRecallSource(configPath, active, "team", external);+ // Threshold 0: the active origin's cards clear it, so the external origin is+ // never searched. Proves the gate reads the card score when results is empty.+ writeFileSync(+ configPath,+ `vault: "${active}"\nsearch_chain_stop_enabled: true\nsearch_chain_stop_score: 0\n`,+ );+ const outcome = await searchAcrossVaults(configPath, active, {+ query: "griffin",+ limit: 10,+ disclosure: "cards",+ });+ expect((outcome.cards ?? []).every((c) => c.origin === "local")).toBe(true);+ expect(outcome.chainStop?.triggered).toBe(true);+ expect(outcome.chainStop?.stoppedAfter).toBe("local");+ expect(outcome.chainStop?.skipped).toEqual(["source/team"]);+});+// D4 t_23c1b929 - normalized-confidence chain-stop for cross-vault early termination.function withChainStop(score: number): void {// Re-resolve every origin from config.yaml, so the knob reaches thediff --git a/tests/mcp/event-trace-tool.test.ts b/tests/mcp/event-trace-tool.test.tsindex 33374213..06a4550a 100644--- a/tests/mcp/event-trace-tool.test.ts+++ b/tests/mcp/event-trace-tool.test.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -121,4 +121,21 @@ describe("brain_event_trace tool", () => {})) as { error?: { code: number } };expect(response.error?.code).toBe(-32602);});++ test("a runtime IO error surfaces as INTERNAL_ERROR, not INVALID_PARAMS", async () => {+ // Brain/log exists but is a FILE: existsSync passes, readdirSync throws+ // ENOTDIR inside the resolver's IO path. A bad selector is a caller error+ // (-32602); a runtime IO failure must be an internal error (-32603).+ rmSync(join(vault, "Brain", "log"), { recursive: true, force: true });+ writeFileSync(join(vault, "Brain", "log"), "not a directory\n");+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const response = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 9,+ method: "tools/call",+ params: { name: "brain_event_trace", arguments: { date: "2026-06-15" } },+ })) as { error?: { code: number } };+ expect(response.error?.code).toBe(-32603);+ });});diff --git a/tests/mcp/registry-guard.test.ts b/tests/mcp/registry-guard.test.tsindex 1320af76..b869710b 100644--- a/tests/mcp/registry-guard.test.ts+++ b/tests/mcp/registry-guard.test.ts@@ -43,4 +43,18 @@ describe("preview-budget default", () => {expect(reason.trim().length, name).toBeGreaterThan(10);}});++ test("a tool named like an Object.prototype member is not falsely exempt (t_6fbdba4b)", () => {+ // The exempt membership test must be own-key only: `name in EXEMPT` walks+ // the prototype chain, so a budget-less tool named "toString" (or+ // "constructor", "hasOwnProperty", ...) would be wrongly treated as exempt+ // and silently escape the unbudgeted-output guard.+ const tool = {+ name: "toString",+ description: "x",+ inputSchema: { type: "object" },+ } as unknown as (typeof TOOLS)[number];+ const audit = auditPreviewBudgets([tool]);+ expect(audit.unbudgetedAndUnexempted).toContain("toString");+ });});