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
refactor: remove all import cycles, decompose search.ts (v1.30.1) (#137)
Sol Aitken13bde6c36fc7
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 50cde983..81716441 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.30.0",+ "version": "1.30.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 8ff33a55..b0c3fc8d 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.30.0",+ "version": "1.30.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 926afbbc..b563aa29 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,15 @@ 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.30.1] - 2026-07-17++A structural maintenance release with zero behavior change: every import cycle in the TypeScript source tree is removed and the largest source file is decomposed. The analysis and the verification gate come from code-ranker (v5.0.3); the full suite (5687 tests) is byte-for-byte green before and after.++### Changed++- **All seven import cycles removed from `src/`.** Dependency inversion at the type level, cycle by cycle: doctor/trust and procedural-* shapes move to the leaf module `src/core/brain/types.ts`; `LinkOutputFormat` moves from `config.ts` to its only consumer `wikilink.ts`; the ~35-file `src/mcp` component dissolves into a one-directional layering over a new `src/mcp/tool-contract.ts` contract leaf; `src/core/search` gains `embeddings/contract.ts`, `rerank/contract.ts`, and `embeddings/configured-provider.ts` while `search/types.ts` becomes a pure leaf; and a new `search/tuning-store.ts` splits the tuned-parameter read side from the grid optimizer, closing the last `search -> tuning -> benchmark` triangle. `code-ranker` now reports zero `cycle.chain` violations and zero cycles in the file graph.+- **`src/core/search/search.ts` decomposed.** The worst-ranked file in the tree (maintainability index -85.8, cognitive complexity 442, 1722 lines) keeps only the `search()` orchestration; progressive disclosure (`cards.ts`), structured-lane application (`structured-lanes.ts`), the semantic phase (`semantic-phase.ts`), frontmatter result filters (`result-filters.ts`), graph expansion phases (`graph-phases.ts`), and evidence-pack coverage (`evidence-verification.ts`) move to focused leaf modules with byte-identical function bodies.+## [1.30.0] - 2026-07-11A governance-visibility release that adds two aggregate views over the preference set the existing per-item hygiene lints could not answer, plus an efficiency refinement to how one of them sources its data. Both new surfaces are additive and read-only over `Brain/preferences/`; the release adds no new dependency and the kernel still calls no LLM.@@ -6460,6 +6469,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.30.1]: https://github.com/itechmeat/open-second-brain/compare/v1.30.0...v1.30.1[1.30.0]: https://github.com/itechmeat/open-second-brain/compare/v1.29.0...v1.30.0[1.29.0]: https://github.com/itechmeat/open-second-brain/compare/v1.28.0...v1.29.0[1.28.0]: https://github.com/itechmeat/open-second-brain/compare/v1.27.1...v1.28.0diff --git a/docs/plans/2026-07-17-structural-refactor.md b/docs/plans/2026-07-17-structural-refactor.mdnew file mode 100644index 00000000..f70c5a9f--- /dev/null+++ b/docs/plans/2026-07-17-structural-refactor.md@@ -0,0 +1,93 @@+# Structural refactor: dependency cycles and complexity hotspots++Date: 2026-07-17+Status: done (shipped as 1.30.1)+Branch: `refactor/structural-cleanup`++## Goal++Remove import cycles from the TypeScript source tree and reduce the+complexity of the worst-ranked modules, without any behavior change.+Every step is verified with `bun run validate` (typecheck + lint + tests).++## Baseline (code-ranker snapshot, commit fd5661f9)++672 internal TypeScript files analyzed. Seven import cycles (strongly+connected components) and a cluster of low-maintainability files.++### Import cycles++| # | Scope | Files | Notes |+|---|-------|-------|-------|+| 0 | `src/mcp/**` | ~35 | `capabilities.ts`, `tools.ts`, and every `brain/*-tools.ts` form one component |+| 1 | `src/core/brain` | 3 | `doctor.ts`, `trust/instruction-file-ceiling.ts`, `trust/compute-trust-verdict.ts` |+| 2 | `src/core/search` | 11 | `index.ts`, `search.ts`, `store.ts` orbit: rerank, benchmark, tuning, profiles |+| 3 | `src/core/search/embeddings` | 5 | `provider.ts` and its four implementations |+| 4 | `src/core/brain` | 3 | `procedural-memory.ts`, `procedural-graph.ts`, `procedural-hints.ts` |+| 5 | `src/core/search` | 4 | `types.ts`, `structured-query.ts`, `session-focus.ts`, `evidence-pack.ts` |+| 6 | `src/core` | 3 | `config.ts`, `brain/wikilink.ts`, `brain/link-graph/format-wikilink.ts` |++### Worst files by maintainability index++| File | MI | Cognitive | SLOC | fan_in |+|------|----|-----------|------|--------|+| `src/core/search/search.ts` | -85.8 | 442 | 1223 | 5 |+| `src/core/search/store.ts` | -69.8 | 199 | 1520 | 17 |+| `src/core/brain/policy.ts` | -68.7 | 396 | 1314 | 37 |+| `src/cli/search.ts` | -66.0 | 287 | 1070 | 1 |+| `src/core/brain/preference.ts` | -56.3 | 226 | 927 | 34 |+| `src/core/brain/dream.ts` | -54.6 | 344 | 970 | 11 |+| `src/core/brain/doctor.ts` | -51.6 | 256 | 1010 | 9 |++## Plan++The standard remedy for each cycle is dependency inversion at the type+level: extract the shared contract (types, interfaces) into a leaf+module that owns no imports back into the component, then point both+sides at it. No re-export shims left behind unless an external caller+requires the old path.++### Wave 1 - small, independent cycle breaks (parallel)++- W1a: cycle 1 (`doctor.ts` and `trust/*`)+- W1b: cycle 4 (`procedural-*` triple)+- W1c: cycle 6 (`config.ts`, `wikilink.ts`, `format-wikilink.ts`)++### Wave 2 - subsystem components (parallel)++- W2a: `src/core/search` - cycles 2, 3, 5 in one pass, since they share files+- W2b: `src/mcp` - cycle 0, expected fix is extracting the tool-registry+ contract out of `capabilities.ts`/`tools.ts` so leaf tool modules stop+ importing the aggregator++### Wave 3 - complexity decomposition++- W3a: split `src/core/search/search.ts` (worst MI in the tree) into+ focused modules along its existing internal seams++### Explicit non-goals (follow-up candidates, not this branch)++- Decomposing `policy.ts`, `preference.ts` (fan_in 37 and 34 - high blast+ radius, deserve their own reviewed plans)+- Decomposing `store.ts`, `dream.ts`, `doctor.ts`, `cli/search.ts`+- Behavior or API changes of any kind++## Verification++- `bun run validate` green after every wave+- `code-ranker report` re-run at the end; cycle count for touched+ components must be zero and no file's MI may regress++## Outcome (code-ranker 5.0.3, baseline at fd5661f9 vs final)++- Cycles: 7 -> 0; `code-ranker check` reports zero violations+- `search.ts`: MI -85.8 -> -48.7, cognitive 442 -> 318, sloc 1223 -> 763+- 11 new focused leaf modules (MI 41 to 98): six search concern modules,+ three search contracts/stores, `mcp/tool-contract.ts`,+ `embeddings/configured-provider.ts`+- Accepted deviation from the MI gate: the pure type leaves+ `search/types.ts` (14.5 -> 11.5) and `brain/types.ts` (2.5 -> 1.2)+ absorbed relocated data shapes; MI penalizes their added lines, but+ they contain no logic, so this is the cost of the inversion, not a+ quality regression+- Full suite identical before and after: 5687 pass, 0 faildiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 0f6969a2..b1f418e0 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.30.0",+ "version": "1.30.1","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 9e66b9da..4018bef4 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.30.0",+ "version": "1.30.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 b9eeeea4..41fb4ad2 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.30.0"+version: "1.30.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 45493c67..ef38b28f 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.30.0",+ "version": "1.30.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 b9eeeea4..41fb4ad2 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.30.0"+version: "1.30.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 c2769740..4626032c 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.30.0"+version = "1.30.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/scripts/measure-token-surface.ts b/scripts/measure-token-surface.tsindex 446676c7..1901c69a 100644--- a/scripts/measure-token-surface.ts+++ b/scripts/measure-token-surface.ts@@ -19,7 +19,8 @@ import { budgetActiveBody } from "../src/core/brain/active-budget.ts";import { parseFrontmatterText } from "../src/core/vault.ts";import { estimateTokens } from "../src/core/brain/text/tokenizer.ts";import { buildInstructions } from "../src/mcp/instructions.ts";-import { buildToolTable, type ToolDefinition } from "../src/mcp/tools.ts";+import { buildToolTable } from "../src/mcp/tools.ts";+import type { ToolDefinition } from "../src/mcp/tool-contract.ts";interface ToolRow {readonly name: string;diff --git a/src/cli/brain/verbs/tune.ts b/src/cli/brain/verbs/tune.tsindex cd1b24ae..2a58c959 100644--- a/src/cli/brain/verbs/tune.ts+++ b/src/cli/brain/verbs/tune.ts@@ -13,7 +13,8 @@import { readFileSync } from "node:fs";import { parseRecallBenchmarkDataset } from "../../../core/search/benchmark.ts";-import { loadTunedParameters, resetTuning, tuneRecall } from "../../../core/search/tuning.ts";+import { tuneRecall } from "../../../core/search/tuning.ts";+import { loadTunedParameters, resetTuning } from "../../../core/search/tuning-store.ts";import { appendMetric } from "../../../core/brain/metrics.ts";import { isoSecond } from "../../../core/brain/time.ts";import { resolveSearchConfig } from "../../../core/search/index.ts";diff --git a/src/core/brain/context-pack.ts b/src/core/brain/context-pack.tsindex 1b5c5931..45b0e3d0 100644--- a/src/core/brain/context-pack.ts+++ b/src/core/brain/context-pack.ts@@ -58,11 +58,8 @@ import {type ContextLanesReport,} from "./context-lanes.ts";import { buildAttentionContextBlock } from "./attention-flows.ts";-import {- scoreSessionFocusTarget,- sessionFocusIsActive,- type SearchSessionFocus,-} from "../search/session-focus.ts";+import { scoreSessionFocusTarget, sessionFocusIsActive } from "../search/session-focus.ts";+import type { SearchSessionFocus } from "../search/types.ts";const TIER_ORDER: ReadonlyArray<PageTier> = [PAGE_TIER.core,diff --git a/src/core/brain/digest.ts b/src/core/brain/digest.tsindex f4f5a97c..fbce4c2d 100644--- a/src/core/brain/digest.ts+++ b/src/core/brain/digest.ts@@ -38,14 +38,11 @@import { existsSync, readdirSync } from "node:fs";import { join } from "node:path";-import type { LinkOutputFormat } from "../config.ts";-import { backlinkCount, buildBacklinkIndex, type BacklinkIndex } from "./backlinks.ts";import { computeAgentSummary, type AgentSummaryEntry } from "./digest-agent-summary.ts";import { findMergeCandidates } from "./merge-candidates.ts";import { computeMostApplied } from "./most-applied.ts";import { brainDirs, vaultRelative } from "./paths.ts";-import type { TrustVerdict } from "./doctor.ts";import { collectMaintenanceActions } from "./maintenance/collect.ts";import type { ActionItem } from "./maintenance/action-scorer.ts";import {@@ -53,7 +50,7 @@ import {MOST_APPLIED_WINDOW_DAYS_DEFAULT,loadBrainConfig,} from "./policy.ts";-import { normaliseWikilinkTarget, renderPrefLink } from "./wikilink.ts";+import { normaliseWikilinkTarget, renderPrefLink, type LinkOutputFormat } from "./wikilink.ts";import { parsePreference, parseRetired } from "./preference.ts";import type { BrainLogEntry } from "./log.ts";import { listLogDates, readLogDay } from "./log-jsonl.ts";@@ -63,7 +60,7 @@ import {BRAIN_PREFERENCE_STATUS,BRAIN_RETIRED_REASON,} from "./types.ts";-import type { BrainConfidence, BrainPreference, BrainRetired } from "./types.ts";+import type { BrainConfidence, BrainPreference, BrainRetired, TrustVerdict } from "./types.ts";// ----- Public types ---------------------------------------------------------diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.tsindex 1edb542b..9f9bd198 100644--- a/src/core/brain/doctor.ts+++ b/src/core/brain/doctor.ts@@ -89,26 +89,19 @@ import {BRAIN_LOG_EVENT_KIND,BRAIN_PREFERENCE_STATUS,type BrainConfig,+ type DoctorIssue,+ type InstructionFileCeilingWarning,type ResolvedBrainHealthConfig,+ type TrustVerdict,} from "./types.ts";import { normaliseWikilinkTarget, parseArtifactRef } from "./wikilink.ts";// ----- Public types -----------------------------------------------------------export type DoctorSeverity = "warning" | "error";--/**- * One structured finding. `code` is a stable identifier so callers can- * filter or aggregate without parsing the `message`.- */-export interface DoctorIssue {- readonly severity: DoctorSeverity;- readonly code: string;- /** Vault-absolute path of the offending file, when known. */- readonly path?: string;- /** Human-readable description, suitable for `--text` rendering. */- readonly message: string;-}+//+// `DoctorSeverity`, `DoctorIssue`, `TrustVerdict`, and+// `InstructionFileCeilingWarning` live in `./types.ts` — a leaf module+// with no imports of its own — so the `trust/` helpers below can depend+// on those shapes without importing this file.export interface RunDoctorOptions {/**@@ -145,13 +138,6 @@ export interface RunDoctorOptions {readonly guardrails?: import("./types.ts").ResolvedBrainGuardrailConfig;}-/**- * Aggregate verdict introduced in v0.10.16. Compresses doctor errors,- * dream warnings, and verification-delta counts into one of three- * states an operator can act on at a glance.- */-export type TrustVerdict = "clean" | "watch" | "investigate";-/*** Compact counts attached to a `RunDoctorResult` so callers can render* a one-line "verification delta: X drift, Y regression, Z missing"@@ -165,21 +151,6 @@ export interface VerificationDeltaSummary {readonly missing_evidence: number;}-/**- * Warning entry produced by the instruction-file-ceiling helper- * (v0.10.16). Doctor surfaces these as a parallel array so the- * trust verdict has structured input without having to grep the- * generic `warnings` list.- */-export interface InstructionFileCeilingWarning {- /** Vault-relative path of the offending instruction file. */- readonly path: string;- /** Observed line count. */- readonly lines: number;- /** Configured ceiling at the time of the check. */- readonly ceiling: number;-}-/*** Per-check uncertainty entry. Distinct from `warnings` / `errors`:* these are sub-operations the doctor attempted but cannot claimdiff --git a/src/core/brain/entities/semantic-dedup.ts b/src/core/brain/entities/semantic-dedup.tsindex a801731e..1a342b99 100644--- a/src/core/brain/entities/semantic-dedup.ts+++ b/src/core/brain/entities/semantic-dedup.ts@@ -22,8 +22,8 @@import { discoverConfig } from "../../config.ts";import { parseFrontmatter } from "../../vault.ts";import { envOrConfig, parseBool, parseFloat01 } from "../../validate.ts";-import { resolveConfiguredEmbeddingProvider } from "../../search/embeddings/provider-resolve.ts";-import type { EmbeddingProvider } from "../../search/embeddings/provider.ts";+import { resolveConfiguredEmbeddingProvider } from "../../search/embeddings/configured-provider.ts";+import type { EmbeddingProvider } from "../../search/embeddings/contract.ts";import { jaccard, tokenise } from "../similarity.ts";import { buildEntityIndex } from "./index-builder.ts";import { normalizeEntityName } from "./canonical.ts";diff --git a/src/core/brain/hygiene/detectors/dedup.ts b/src/core/brain/hygiene/detectors/dedup.tsindex ee7384ad..45c22679 100644--- a/src/core/brain/hygiene/detectors/dedup.ts+++ b/src/core/brain/hygiene/detectors/dedup.ts@@ -20,7 +20,8 @@ import { existsSync, readdirSync } from "node:fs";import { join } from "node:path";import { resolveSearchConfig } from "../../../search/index.ts";-import { makeProvider, type EmbeddingProvider } from "../../../search/embeddings/provider.ts";+import { makeProvider } from "../../../search/embeddings/provider.ts";+import type { EmbeddingProvider } from "../../../search/embeddings/contract.ts";import { findMergeCandidates } from "../../merge-candidates.ts";import { brainDirs } from "../../paths.ts";import { parsePreference } from "../../preference.ts";diff --git a/src/core/brain/procedural-graph.ts b/src/core/brain/procedural-graph.tsindex a786b87d..8ac7d5b1 100644--- a/src/core/brain/procedural-graph.ts+++ b/src/core/brain/procedural-graph.ts@@ -11,7 +11,7 @@ import {skillProposalPendingPath,skillProposalRejectedPath,} from "./paths.ts";-import type { ProceduralMemoryEntry } from "./procedural-memory.ts";+import type { ProceduralMemoryEntry } from "./types.ts";export type ProceduralGraphNodeKind = "procedure" | "skill" | "runbook" | "proposal" | "entity";export type ProceduralGraphEdgeKind =diff --git a/src/core/brain/procedural-memory.ts b/src/core/brain/procedural-memory.tsindex d0fb4fc3..3d092cfd 100644--- a/src/core/brain/procedural-memory.ts+++ b/src/core/brain/procedural-memory.ts@@ -8,34 +8,7 @@ import { parseFrontmatter } from "../vault.ts";import { rebuildProceduralHints } from "./procedural-hints.ts";import { rebuildProceduralGraph } from "./procedural-graph.ts";import { proceduralMemoryIndexPath, proceduralMemoryUsagePath } from "./paths.ts";--export type ProceduralEntryKind = "skill" | "runbook" | "procedure";--export interface ProceduralMemoryEntry {- readonly id: string;- readonly kind: ProceduralEntryKind;- readonly sourcePath: string;- readonly title: string;- readonly triggers: ReadonlyArray<string>;- readonly tags: ReadonlyArray<string>;- readonly permissions: ReadonlyArray<string>;- readonly source: string | null;- readonly version: string | null;- readonly lastUsedAt: string | null;- readonly usedCount: number;- /**- * Outcome-validated recall (t_703f7b18). Times this procedure was applied- * and the host reported the downstream result. `successRate` ranks recall- * (see {@link rankProceduralMemory}); usage count is the fallback prior- * for procedures with no recorded outcomes. Additive: absent in an- * outcome-free vault (defaults 0), so pre-outcome indexes read identically.- */- readonly successCount: number;- readonly failureCount: number;-}--/** Host-reported outcome of applying a procedure. */-export type ProceduralOutcome = "success" | "failure";+import type { ProceduralEntryKind, ProceduralMemoryEntry, ProceduralOutcome } from "./types.ts";interface UsageRecord {readonly usedCount: number;diff --git a/src/core/brain/query-demand.ts b/src/core/brain/query-demand.tsindex b2f9860d..8902a0dc 100644--- a/src/core/brain/query-demand.ts+++ b/src/core/brain/query-demand.ts@@ -37,8 +37,8 @@ import {COMPLETENESS_COMPLETE_THRESHOLD,COMPLETENESS_PARTIAL_THRESHOLD,significantTerms,- type CompletenessVerdict,} from "../search/coverage.ts";+import type { CompletenessVerdict } from "../search/types.ts";/** Longest single normalized term kept; longer tokens are dropped as a* privacy guard (a 40+ char alnum run is far likelier a secret/id than adiff --git a/src/core/brain/trust/compute-trust-verdict.ts b/src/core/brain/trust/compute-trust-verdict.tsindex 18d9a6f2..22e7cdb1 100644--- a/src/core/brain/trust/compute-trust-verdict.ts+++ b/src/core/brain/trust/compute-trust-verdict.ts@@ -16,8 +16,8 @@* are the positive case).*/-import type { DoctorIssue, TrustVerdict } from "../doctor.ts";import type { DreamWarning } from "../dream.ts";+import type { DoctorIssue, TrustVerdict } from "../types.ts";import type { VerificationDeltaSummaryCounts } from "./compute-verification-delta.ts";const DEFAULT_DRIFT_WATCH_THRESHOLD = 3;diff --git a/src/core/brain/trust/instruction-file-ceiling.ts b/src/core/brain/trust/instruction-file-ceiling.tsindex d2f5f71b..7218579e 100644--- a/src/core/brain/trust/instruction-file-ceiling.ts+++ b/src/core/brain/trust/instruction-file-ceiling.ts@@ -17,7 +17,7 @@import { existsSync, readFileSync, statSync } from "node:fs";import { join } from "node:path";-import type { InstructionFileCeilingWarning } from "../doctor.ts";+import type { InstructionFileCeilingWarning } from "../types.ts";const TRACKED_FILES: ReadonlyArray<string> = Object.freeze(["CLAUDE.md", "AGENTS.md", "GEMINI.md"]);diff --git a/src/core/brain/trust/operator-summary.ts b/src/core/brain/trust/operator-summary.tsindex 0f8283c5..3d55d8fd 100644--- a/src/core/brain/trust/operator-summary.ts+++ b/src/core/brain/trust/operator-summary.ts@@ -20,21 +20,24 @@import { existsSync, readdirSync, statSync } from "node:fs";-import type { DoctorIssue } from "../doctor.ts";-import { runDoctor, type RunDoctorResult, type TrustVerdict } from "../doctor.ts";+import { runDoctor, type RunDoctorResult } from "../doctor.ts";import type { DreamRunSummary } from "../dream.ts";import { collectMaintenanceActions } from "../maintenance/collect.ts";import type { ActionItem } from "../maintenance/action-scorer.ts";import { brainDirs } from "../paths.ts";import { BRAIN_GUARDRAIL_DEFAULTS } from "../policy.ts";-import type { ResolvedBrainGuardrailConfig } from "../types.ts";+import type {+ DoctorIssue,+ InstructionFileCeilingWarning,+ ResolvedBrainGuardrailConfig,+ TrustVerdict,+} from "../types.ts";import {computeVerificationDelta,type VerificationDeltaResult,} from "./compute-verification-delta.ts";import { computeTrustVerdict } from "./compute-trust-verdict.ts";import { checkInstructionFileCeiling } from "./instruction-file-ceiling.ts";-import type { InstructionFileCeilingWarning } from "../doctor.ts";export interface OperatorSummary {readonly trust_verdict: TrustVerdict;diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex a62e7f8a..eeac3e41 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -817,6 +817,36 @@ export type BrainLogEvent =| BrainNoteLogEvent| BrainSessionLifecycleLogEvent;+// ----- Procedural memory entry shapes ---------------------------------------++export type ProceduralEntryKind = "skill" | "runbook" | "procedure";++/** Host-reported outcome of applying a procedure. */+export type ProceduralOutcome = "success" | "failure";++export interface ProceduralMemoryEntry {+ readonly id: string;+ readonly kind: ProceduralEntryKind;+ readonly sourcePath: string;+ readonly title: string;+ readonly triggers: ReadonlyArray<string>;+ readonly tags: ReadonlyArray<string>;+ readonly permissions: ReadonlyArray<string>;+ readonly source: string | null;+ readonly version: string | null;+ readonly lastUsedAt: string | null;+ readonly usedCount: number;+ /**+ * Outcome-validated recall (t_703f7b18). Times this procedure was applied+ * and the host reported the downstream result. `successRate` ranks recall+ * (see {@link rankProceduralMemory}); usage count is the fallback prior+ * for procedures with no recorded outcomes. Additive: absent in an+ * outcome-free vault (defaults 0), so pre-outcome indexes read identically.+ */+ readonly successCount: number;+ readonly failureCount: number;+}+// ----- Configuration (`Brain/_brain.yaml`) ----------------------------------export interface BrainDreamConfig {@@ -1365,3 +1395,48 @@ export interface ResolvedBrainHealthConfig {readonly stale_claim_max_age_days: number;readonly remediation_step_cap: number;}++// ----- Doctor / trust-layer shapes -------------------------------------------+//+// Shared between `doctor.ts` and the `trust/` helpers it calls+// (`compute-trust-verdict.ts`, `instruction-file-ceiling.ts`,+// `operator-summary.ts`). Living here — a plain-data leaf module with+// no imports of its own — lets those helpers depend on the shapes+// without importing `doctor.ts` itself.++export type DoctorSeverity = "warning" | "error";++/**+ * One structured finding. `code` is a stable identifier so callers can+ * filter or aggregate without parsing the `message`.+ */+export interface DoctorIssue {+ readonly severity: DoctorSeverity;+ readonly code: string;+ /** Vault-absolute path of the offending file, when known. */+ readonly path?: string;+ /** Human-readable description, suitable for `--text` rendering. */+ readonly message: string;+}++/**+ * Aggregate verdict introduced in v0.10.16. Compresses doctor errors,+ * dream warnings, and verification-delta counts into one of three+ * states an operator can act on at a glance.+ */+export type TrustVerdict = "clean" | "watch" | "investigate";++/**+ * Warning entry produced by the instruction-file-ceiling helper+ * (v0.10.16). Doctor surfaces these as a parallel array so the+ * trust verdict has structured input without having to grep the+ * generic `warnings` list.+ */+export interface InstructionFileCeilingWarning {+ /** Vault-relative path of the offending instruction file. */+ readonly path: string;+ /** Observed line count. */+ readonly lines: number;+ /** Configured ceiling at the time of the check. */+ readonly ceiling: number;+}diff --git a/src/core/brain/wikilink.ts b/src/core/brain/wikilink.tsindex df5aa015..c7604218 100644--- a/src/core/brain/wikilink.ts+++ b/src/core/brain/wikilink.ts@@ -28,8 +28,6 @@import { basename } from "node:path";-import type { LinkOutputFormat } from "../config.ts";-/** Canonical wikilink regex variants.*@@ -257,6 +255,9 @@ export const MAX_PREF_LINK_TITLE_LEN = 80;* signal and external-artifact wikilinks stay bare-id because they have* no useful title source.*/+/** Where a wikilink renders to: Obsidian `[[wikilink]]` or portable `[markdown](path)`. */+export type LinkOutputFormat = "wikilink" | "markdown";+export function renderPrefLink(input: {readonly id: string;readonly principle?: string;diff --git a/src/core/config.ts b/src/core/config.tsindex 3a1a85e5..101c7290 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -23,14 +23,13 @@ import {WIKI_LINK_FORMATS,type WikiLinkFormat,} from "./brain/link-graph/format-wikilink.ts";+import type { LinkOutputFormat } from "./brain/wikilink.ts";import type { ConfigDiscovery } from "./types.ts";const SECRET_KEY_PARTS = ["key", "token", "secret", "password", "credential"] as const;const CONFIG_VALUE_REJECTED_CHARS = ['"', "\\", "\n", "\r"] as const;-export type LinkOutputFormat = "wikilink" | "markdown";-/*** Resolve the location of the plugin config file.*diff --git a/src/core/search/cards.ts b/src/core/search/cards.tsnew file mode 100644index 00000000..9d0692f0--- /dev/null+++ b/src/core/search/cards.ts@@ -0,0 +1,117 @@+/**+ * Progressive disclosure (D1-D3): project a ranked result into a+ * token-cheap layer-1 card, and expand a card the agent already holds+ * into its fuller note (layer 2) and paginated raw chunks (layer 3).+ */++import { formatLinePointer } from "./line-numbering.ts";+import { Store } from "./store.ts";+import { SearchError } from "./types.ts";+import type {+ BrainSearchResult,+ ExpandHitInput,+ ExpandHitResult,+ ResolvedSearchConfig,+ SearchCard,+} from "./types.ts";++/** Max chars of a layer-1 card snippet — enough to judge a hit, cheap to carry. */+const CARD_SNIPPET_CHARS = 240;+/** Default layer-3 raw-chunk page size for `expandHit`. */+const DEFAULT_EXPAND_RAW_LIMIT = 10;++/**+ * Project a ranked result into a layer-1 card (progressive disclosure):+ * identity + score + the same `reasons`, a whitespace-collapsed snippet+ * capped at {@link CARD_SNIPPET_CHARS}, and a `path:Lstart-Lend` pointer+ * (D2 grammar) over the chunk's stored line span. No full content.+ */+export function toSearchCard(result: BrainSearchResult): SearchCard {+ return Object.freeze({+ chunkId: result.chunkId,+ documentId: result.documentId,+ path: result.path,+ title: result.title,+ score: result.score,+ reasons: result.reasons,+ snippet: cardSnippet(result.content),+ pointer: formatLinePointer(result.path, result.startLine, result.endLine),+ ...(result.origin !== undefined ? { origin: result.origin } : {}),+ });+}++export function cardSnippet(content: string): string {+ const collapsed = content.replace(/\s+/g, " ").trim();+ // Truncate on code points, not UTF-16 units: a raw `.slice` can cut an+ // astral character (emoji, rare CJK) mid-surrogate-pair, shipping a lone+ // surrogate that renders as U+FFFD. Spreading into an array iterates by+ // code point, so the cap never splits a character.+ const points = [...collapsed];+ return points.length <= CARD_SNIPPET_CHARS+ ? collapsed+ : `${points.slice(0, CARD_SNIPPET_CHARS).join("")}...`;+}++/**+ * Progressive disclosure (D3): layers 2 and 3 of a hit the agent already+ * holds as a layer-1 card. Given the card's `chunkId`, reconstruct the+ * fuller note (layer 2) from the document's stored chunks and return a+ * paginated slice of those raw chunks (layer 3), mirroring+ * `expandSessionRecall`'s cursor contract.+ *+ * Read-only by construction: it opens the index in read mode and never+ * self-heals — a card can only exist because a prior search built the+ * index, and a rebuild would WRITE it. The layer-2/3 data is pure store+ * reads (`hydrateChunks` + `getChunksByDocument`), never a new index.+ */+export async function expandHit(+ config: ResolvedSearchConfig,+ input: ExpandHitInput,+): Promise<ExpandHitResult> {+ if (!Number.isInteger(input.chunkId) || input.chunkId < 1) {+ throw new SearchError("INVALID_INPUT", "chunkId must be a positive integer");+ }+ const store = await Store.open(config, { mode: "read" });+ try {+ const hit = store.hydrateChunks([input.chunkId]).get(input.chunkId);+ if (hit === undefined) {+ throw new SearchError("INVALID_INPUT", `chunk not found: ${input.chunkId}`);+ }+ // Document chunks in `chunkIndex` order: the fuller note (layer 2) is+ // their concatenation; the raw transcript (layer 3) is the same rows.+ const chunks = store.getChunksByDocument(hit.documentId);+ const lineStart = chunks.length > 0 ? chunks[0]!.startLine : hit.startLine;+ const lineEnd = chunks.length > 0 ? chunks[chunks.length - 1]!.endLine : hit.endLine;+ const note = Object.freeze({+ documentId: hit.documentId,+ path: hit.path,+ title: hit.title,+ lineStart,+ lineEnd,+ pointer: formatLinePointer(hit.path, lineStart, lineEnd),+ content: chunks.map((c) => c.content).join("\n"),+ });++ const offset = Math.max(0, Number.parseInt(input.cursor ?? "0", 10) || 0);+ const rawLimit = Math.max(1, input.rawLimit ?? DEFAULT_EXPAND_RAW_LIMIT);+ const page = chunks.slice(offset, offset + rawLimit).map((c) =>+ Object.freeze({+ chunkId: c.id,+ chunkIndex: c.chunkIndex,+ startLine: c.startLine,+ endLine: c.endLine,+ pointer: formatLinePointer(hit.path, c.startLine, c.endLine),+ content: c.content,+ }),+ );+ const nextOffset = offset + rawLimit;+ return Object.freeze({+ chunkId: input.chunkId,+ note,+ raw_content: Object.freeze(page),+ next_cursor: nextOffset < chunks.length ? String(nextOffset) : null,+ });+ } finally {+ await store.close();+ }+}diff --git a/src/core/search/coverage.ts b/src/core/search/coverage.tsindex b09350a0..ceb3b3f1 100644--- a/src/core/search/coverage.ts+++ b/src/core/search/coverage.ts@@ -14,6 +14,8 @@* in. Deterministic, no LLM, no clock.*/+import type { CompletenessReport, CompletenessVerdict } from "./types.ts";+/** Share of the corpus a term may appear in and still count as rare. */export const RARE_TERM_CORPUS_SHARE = 0.02;@@ -95,23 +97,6 @@ export const COMPLETENESS_COMPLETE_THRESHOLD = 0.8;/** IDF-weighted coverage at/above this (below complete) is partial. */export const COMPLETENESS_PARTIAL_THRESHOLD = 0.4;-export type CompletenessVerdict = "complete" | "partial" | "sparse";--/**- * Search-completeness guard (Feature E): a deterministic verdict over- * how well the returned results cover the query, plus the- * false-absence guard — uncovered terms the corpus DOES contain. A- * summarizer seeing a term in `uncoveredButPresentInCorpus` cannot- * honestly claim the vault has nothing on it.- */-export interface CompletenessReport {- readonly verdict: CompletenessVerdict;- readonly idfWeightedCoverage: number;- readonly coveredTerms: ReadonlyArray<string>;- readonly uncoveredTerms: ReadonlyArray<string>;- readonly uncoveredButPresentInCorpus: ReadonlyArray<string>;-}-export function buildCompletenessReport(coverage: CoverageReport): CompletenessReport {const covered = coverage.terms.filter((t) => t.covered).map((t) => t.term);const uncovered = coverage.terms.filter((t) => !t.covered);diff --git a/src/core/search/embeddings/configured-provider.ts b/src/core/search/embeddings/configured-provider.tsnew file mode 100644index 00000000..57414613--- /dev/null+++ b/src/core/search/embeddings/configured-provider.ts@@ -0,0 +1,33 @@+/**+ * Configured-provider resolution (semantic-retrieval-precision, parent+ * t_47fd9523).+ *+ * Resolves the vault's configured embedding provider through the full+ * `resolveSearchConfig` path. Split out from `provider-resolve.ts` so that+ * the low-level endpoint seam stays free of a dependency on the search+ * config barrel (`index.ts`); this module is the one that carries it.+ */++import { discoverConfig } from "../../config.ts";+import { resolveSearchConfig } from "../index.ts";+import { makeProvider } from "./provider.ts";+import type { EmbeddingProvider } from "./contract.ts";++/**+ * Resolve the vault's configured embedding provider. Returns `null` when+ * semantic search is disabled (the null provider) or when resolution+ * throws — callers then fall back to a deterministic path rather than+ * failing. Mirrors the inline guard in the hygiene dedup detector.+ */+export function resolveConfiguredEmbeddingProvider(+ vault: string,+ opts: { readonly configPath?: string } = {},+): EmbeddingProvider | null {+ try {+ const configPath = opts.configPath ?? discoverConfig().path;+ const provider = makeProvider(resolveSearchConfig({ vault, configPath }).semantic);+ return provider.name === "null" ? null : provider;+ } catch {+ return null;+ }+}diff --git a/src/core/search/embeddings/contract.ts b/src/core/search/embeddings/contract.tsnew file mode 100644index 00000000..e91030e3--- /dev/null+++ b/src/core/search/embeddings/contract.ts@@ -0,0 +1,22 @@+/**+ * Embedding-provider contract. The interface every embedding provider+ * implements, split out from the factory (`provider.ts`) so implementations+ * depend only on this leaf and never on the module that constructs them.+ *+ * Anchored in docs/plans/2026-05-16-brain-search-design.md §11.+ */++export interface EmbeddingProvider {+ readonly name: string;+ readonly model: string;+ readonly dimension: number | null;+ embed(texts: ReadonlyArray<string>): Promise<number[][]>;+ ping(): Promise<{ ok: true; dimension: number } | { ok: false; reason: string }>;+ /**+ * Optional read-and-reset of provider-internal retry tally. The+ * indexer consumes this after each `embed()` to populate+ * `IndexStats.embeddingsRetries`. Providers that never retry+ * (NullProvider, MockEmbeddingProvider) leave this undefined.+ */+ consumeRetryCount?(): number;+}diff --git a/src/core/search/embeddings/local-provider.ts b/src/core/search/embeddings/local-provider.tsindex b12ad4b3..36e64452 100644--- a/src/core/search/embeddings/local-provider.ts+++ b/src/core/search/embeddings/local-provider.ts@@ -16,7 +16,7 @@* this one.*/-import type { EmbeddingProvider } from "./provider.ts";+import type { EmbeddingProvider } from "./contract.ts";import { LOCAL_EMBEDDING_MODEL } from "./signature.ts";/** Default vector width when `embedding_dimension` is not configured. */diff --git a/src/core/search/embeddings/null-provider.ts b/src/core/search/embeddings/null-provider.tsindex 50cdab22..389778f2 100644--- a/src/core/search/embeddings/null-provider.ts+++ b/src/core/search/embeddings/null-provider.ts@@ -8,7 +8,7 @@*/import { SearchError } from "../types.ts";-import type { EmbeddingProvider } from "./provider.ts";+import type { EmbeddingProvider } from "./contract.ts";export class NullProvider implements EmbeddingProvider {readonly name = "null";diff --git a/src/core/search/embeddings/openai-compat.ts b/src/core/search/embeddings/openai-compat.tsindex 23fd882c..ef6cbef1 100644--- a/src/core/search/embeddings/openai-compat.ts+++ b/src/core/search/embeddings/openai-compat.ts@@ -19,7 +19,7 @@import { SearchError } from "../types.ts";import type { ResolvedEmbeddingConfig } from "../types.ts";-import type { EmbeddingProvider } from "./provider.ts";+import type { EmbeddingProvider } from "./contract.ts";import {AUTH_STATUSES,RETRYABLE_STATUSES,diff --git a/src/core/search/embeddings/provider-resolve.ts b/src/core/search/embeddings/provider-resolve.tsindex ff73a868..b700353e 100644--- a/src/core/search/embeddings/provider-resolve.ts+++ b/src/core/search/embeddings/provider-resolve.ts@@ -18,29 +18,7 @@* provider resolution is not re-implemented per feature.*/-import { discoverConfig } from "../../config.ts";import { SearchError } from "../types.ts";-import { makeProvider, type EmbeddingProvider } from "./provider.ts";-import { resolveSearchConfig } from "../index.ts";--/**- * Resolve the vault's configured embedding provider. Returns `null` when- * semantic search is disabled (the null provider) or when resolution- * throws — callers then fall back to a deterministic path rather than- * failing. Mirrors the inline guard in the hygiene dedup detector.- */-export function resolveConfiguredEmbeddingProvider(- vault: string,- opts: { readonly configPath?: string } = {},-): EmbeddingProvider | null {- try {- const configPath = opts.configPath ?? discoverConfig().path;- const provider = makeProvider(resolveSearchConfig({ vault, configPath }).semantic);- return provider.name === "null" ? null : provider;- } catch {- return null;- }-}/** A fully-resolved OpenAI-compatible endpoint (base_url + model + key). */export interface OpenAiCompatEndpoint {diff --git a/src/core/search/embeddings/provider.ts b/src/core/search/embeddings/provider.tsindex 6923535a..c3360367 100644--- a/src/core/search/embeddings/provider.ts+++ b/src/core/search/embeddings/provider.ts@@ -8,21 +8,7 @@import { SearchError } from "../types.ts";import type { ResolvedEmbeddingConfig } from "../types.ts";--export interface EmbeddingProvider {- readonly name: string;- readonly model: string;- readonly dimension: number | null;- embed(texts: ReadonlyArray<string>): Promise<number[][]>;- ping(): Promise<{ ok: true; dimension: number } | { ok: false; reason: string }>;- /**- * Optional read-and-reset of provider-internal retry tally. The- * indexer consumes this after each `embed()` to populate- * `IndexStats.embeddingsRetries`. Providers that never retry- * (NullProvider, MockEmbeddingProvider) leave this undefined.- */- consumeRetryCount?(): number;-}+import type { EmbeddingProvider } from "./contract.ts";export function makeProvider(config: ResolvedEmbeddingConfig): EmbeddingProvider {// Lazy imports to keep the module graph small for users who neverdiff --git a/src/core/search/embeddings/zeroentropy.ts b/src/core/search/embeddings/zeroentropy.tsindex d6a4c3dd..4baa2f35 100644--- a/src/core/search/embeddings/zeroentropy.ts+++ b/src/core/search/embeddings/zeroentropy.ts@@ -22,7 +22,7 @@import { SearchError } from "../types.ts";import type { ResolvedEmbeddingConfig } from "../types.ts";-import type { EmbeddingProvider } from "./provider.ts";+import type { EmbeddingProvider } from "./contract.ts";import {RETRYABLE_STATUSES,Semaphore,diff --git a/src/core/search/evidence-pack.ts b/src/core/search/evidence-pack.tsindex e88ed1c5..2068ef29 100644--- a/src/core/search/evidence-pack.ts+++ b/src/core/search/evidence-pack.ts@@ -4,42 +4,9 @@ import {significantTerms,termIncludedIn,} from "./coverage.ts";-import type { CompletenessReport, CoverageReport } from "./coverage.ts";+import type { CoverageReport } from "./coverage.ts";import { formatLinePointer } from "./line-numbering.ts";-import type { BrainSearchResult } from "./types.ts";--export interface EvidenceRecord {- readonly path: string;- readonly documentId: number;- readonly chunkId: number;- /**- * Read-time line-anchored citation for this chunk, formatted- * `path:Lstart-Lend` (or `path:Lstart` for a single line) from the chunk's- * 1-based `startLine`/`endLine`. Resolves by opening the file and slicing- * the range with {@link extractLineRange}; the stored bytes are never- * mutated, so the pointer stays valid across idempotent re-mining.- */- readonly linePointer: string;- readonly matchedTerms: ReadonlyArray<string>;- readonly missingTerms: ReadonlyArray<string>;- readonly supportCoverage: number;- readonly terminalState: boolean;- readonly whyRetrieved: ReadonlyArray<string>;- readonly droppedCandidateReasons: ReadonlyArray<string>;-}--/**- * One per-token recall-union record (recall-trust-suite, Feature C): a- * document fetched specifically because it covers a significant term- * the ranked result set left uncovered. Union records live in the pack- * only — the primary `results` contract stays untouched.- */-export interface EvidenceUnionRecord {- readonly term: string;- readonly path: string;- readonly documentId: number;- readonly chunkId: number;-}+import type { BrainSearchResult, EvidencePack, EvidenceUnionRecord } from "./types.ts";/*** Verification extras computed by the coverage engine when the search@@ -50,37 +17,6 @@ export interface EvidenceVerification {readonly unionRecords: ReadonlyArray<EvidenceUnionRecord>;}-export interface EvidencePack {- readonly significantTerms: ReadonlyArray<string>;- readonly matchedTerms: ReadonlyArray<string>;- readonly missingTerms: ReadonlyArray<string>;- readonly supportCoverage: number;- readonly records: ReadonlyArray<EvidenceRecord>;- readonly droppedCandidates: ReadonlyArray<{- readonly path: string;- readonly reason: string;- }>;- readonly abstention: string | null;- /**- * IDF-weighted support coverage (Feature C): the share of the query's- * IDF mass the covered terms carry. Present only when the search ran- * with coverage verification.- */- readonly idfWeightedCoverage?: number;- /** Rare (high-signal) significant terms per the corpus statistics. */- readonly rareTerms?: ReadonlyArray<string>;- /** Rare terms no returned record covers — the abstention trigger. */- readonly uncoveredRareTerms?: ReadonlyArray<string>;- /** Per-token recall union for uncovered significant terms. */- readonly unionRecords?: ReadonlyArray<EvidenceUnionRecord>;- /**- * Search-completeness guard (Feature E): verdict + false-absence- * report from the same coverage engine. Present only when the search- * ran with coverage verification.- */- readonly completeness?: CompletenessReport;-}-/*** Controlled terminal-status vocabulary. These are accepted values of* the frontmatter `status:` field - a controlled enum the system owns -diff --git a/src/core/search/evidence-verification.ts b/src/core/search/evidence-verification.tsnew file mode 100644index 00000000..c2a9aff5--- /dev/null+++ b/src/core/search/evidence-verification.ts@@ -0,0 +1,115 @@+/**+ * Evidence-pack coverage verification (recall-trust-suite, Feature C):+ * IDF-weighted coverage of the query terms over a candidate pool (the+ * partial self-correcting retry trigger) and over the returned result+ * set, plus the bounded per-token recall union that surfaces records the+ * primary ranking never returned.+ */++import {+ buildCoverageReport,+ significantTerms,+ termIncludedIn,+ type CoverageReport,+} from "./coverage.ts";+import type { EvidenceVerification } from "./evidence-pack.ts";+import { runFtsQueryDetailed } from "./fts.ts";+import { Store } from "./store.ts";+import type { BrainSearchResult, EvidenceUnionRecord } from "./types.ts";++/** Cap on extra records fetched per uncovered term (Feature C union). */+const UNION_RECORDS_PER_TERM = 2;+/** Cap on the total recall-union fetch per query. */+const UNION_RECORDS_TOTAL = 8;++/**+ * Coverage verification for evidence-pack mode (recall-trust-suite,+ * Feature C): corpus document frequencies for the significant terms,+ * the covered-term set over the returned results, and a bounded+ * per-token recall union — for each term the ranked set left uncovered,+ * fetch up to {@link UNION_RECORDS_PER_TERM} records that DO cover it+ * (evidence can span records the primary ranking never surfaced).+ */+/**+ * IDF-weighted coverage of the query over a candidate POOL (the partial+ * self-correcting retry trigger, t_8eb5ca32). Mirrors the result-set+ * coverage in {@link buildEvidenceVerification} but scores the+ * pre-ranking candidate chunks: a term is covered when any candidate's+ * path/title/content contains it. Corpus document frequencies and the+ * document count come from the store, exactly as the result-set pass+ * does, so the two reports share one definition of "covered" and one+ * IDF scale.+ */+export function coverageOverChunks(+ store: Store,+ query: string,+ chunkIds: ReadonlyArray<number>,+): CoverageReport {+ const terms = significantTerms(query);+ const dfByTerm = store.documentFrequencies(terms);+ const documentCount = store.counts().documents;+ const hydrated = store.hydrateChunks(chunkIds);+ const covered = new Set<string>();+ for (const h of hydrated.values()) {+ const haystack = `${h.path}\n${h.title ?? ""}\n${h.content}`;+ for (const t of terms) {+ if (!covered.has(t) && termIncludedIn(haystack, t)) covered.add(t);+ }+ }+ return buildCoverageReport({+ significantTerms: terms,+ coveredTerms: covered,+ documentCount,+ dfByTerm,+ });+}++export function buildEvidenceVerification(+ store: Store,+ query: string,+ results: ReadonlyArray<BrainSearchResult>,+ pathPrefix: string | undefined,+): EvidenceVerification {+ const terms = significantTerms(query);+ const dfByTerm = store.documentFrequencies(terms);+ const documentCount = store.counts().documents;+ const covered = new Set<string>();+ for (const r of results) {+ const haystack = `${r.path}\n${r.title ?? ""}\n${r.content}`;+ for (const t of terms) {+ if (!covered.has(t) && termIncludedIn(haystack, t)) covered.add(t);+ }+ }+ const coverage = buildCoverageReport({+ significantTerms: terms,+ coveredTerms: covered,+ documentCount,+ dfByTerm,+ });++ const unionRecords: EvidenceUnionRecord[] = [];+ for (const t of coverage.terms) {+ if (t.covered || t.df === 0) continue; // nothing in the corpus covers a df=0 term+ if (unionRecords.length >= UNION_RECORDS_TOTAL) break;+ const outcome = runFtsQueryDetailed(store, t.term, {+ limit: UNION_RECORDS_PER_TERM,+ pathPrefix,+ });+ const ids = outcome.hits.map((h) => h.chunkId);+ const hydrated = store.hydrateChunks(ids);+ for (const hit of outcome.hits) {+ if (unionRecords.length >= UNION_RECORDS_TOTAL) break;+ const h = hydrated.get(hit.chunkId);+ if (!h) continue;+ unionRecords.push(+ Object.freeze({+ term: t.term,+ path: h.path,+ documentId: h.documentId,+ chunkId: h.chunkId,+ }),+ );+ }+ }+ return Object.freeze({ coverage, unionRecords: Object.freeze(unionRecords) });+}diff --git a/src/core/search/graph-phases.ts b/src/core/search/graph-phases.tsnew file mode 100644index 00000000..addb2419--- /dev/null+++ b/src/core/search/graph-phases.ts@@ -0,0 +1,119 @@+/**+ * Store-backed link-graph expansion phases: fetch the outbound adjacency+ * / typed-relation edges the pure scoring layers need, then delegate the+ * bounded scoring to `expandByTraversal` (link-graph traversal) and+ * `applyRelationPolarity` (typed relation polarity).+ */++import { applyRelationPolarity } from "./relation-polarity.ts";+import { Store } from "./store.ts";+import { expandByTraversal, type TraversalOptions } from "./traversal.ts";+import type { BrainSearchResult } from "./types.ts";++/**+ * Walk outbound links from the ranked hits and merge in related+ * documents. Fetches the outbound adjacency level-by-level (each+ * document fetched once) up to `maxHops`, then delegates the bounded+ * scoring to the pure `expandByTraversal`.+ */+export function applyTraversal(+ store: Store,+ ranked: BrainSearchResult[],+ opts: TraversalOptions,+): BrainSearchResult[] {+ const seedDocIds = Array.from(new Set(ranked.map((r) => r.documentId)));+ const present = new Set(seedDocIds);+ const outbound = new Map<number, ReadonlyArray<number>>();+ const seen = new Set<number>(seedDocIds);+ let level = new Set<number>(seedDocIds);++ for (let hop = 0; hop < opts.maxHops && level.size > 0; hop++) {+ const toFetch = Array.from(level).filter((id) => !outbound.has(id));+ if (toFetch.length === 0) break;+ const adjacency = store.outboundLinkTargets(toFetch);+ const next = new Set<number>();+ for (const [src, targets] of adjacency) {+ outbound.set(src, targets);+ for (const t of targets) {+ if (!seen.has(t)) {+ seen.add(t);+ next.add(t);+ }+ }+ }+ level = next;+ }++ const expansionIds = Array.from(seen).filter((id) => !present.has(id));+ if (expansionIds.length === 0) return ranked;+ const reps = store.representativeChunks(expansionIds);++ return expandByTraversal(+ {+ ranked,+ outbound,+ expansionDoc: (docId) => {+ const h = reps.get(docId);+ if (!h) return null;+ return {+ documentId: h.documentId,+ chunkId: h.chunkId,+ path: h.path,+ title: h.title,+ content: h.content,+ startLine: h.startLine,+ endLine: h.endLine,+ };+ },+ },+ opts,+ );+}++/**+ * Fetch the typed relation edges declared by the pool's documents and+ * delegate the polarity adjustment to the pure `applyRelationPolarity`.+ * Successor pull-in reuses the traversal layer's representative-chunk+ * mechanism (document head as the surfaced chunk).+ */+export function applyRelationPolarityPhase(+ store: Store,+ ranked: ReadonlyArray<BrainSearchResult>,+ includeSuperseded: boolean,+): ReadonlyArray<BrainSearchResult> {+ if (ranked.length === 0) return ranked;+ const docIds = Array.from(new Set(ranked.map((r) => r.documentId)));+ const edges = store.typedRelationEdgesForDocuments(docIds);+ if (edges.length === 0) return ranked;++ const present = new Set(docIds);+ const successorIds = Array.from(+ new Set(+ edges+ .map((e) => e.targetDocumentId)+ .filter((id): id is number => id !== null && !present.has(id)),+ ),+ );+ const reps = store.representativeChunks(successorIds);++ return applyRelationPolarity(+ {+ ranked,+ edges,+ successorDoc: (docId) => {+ const h = reps.get(docId);+ if (!h) return null;+ return {+ documentId: h.documentId,+ chunkId: h.chunkId,+ path: h.path,+ title: h.title,+ content: h.content,+ startLine: h.startLine,+ endLine: h.endLine,+ };+ },+ },+ { includeSuperseded },+ );+}diff --git a/src/core/search/index.ts b/src/core/search/index.tsindex c3c0ddfe..36279882 100644--- a/src/core/search/index.ts+++ b/src/core/search/index.ts@@ -39,6 +39,7 @@ type SearchConfigOverrides = Partial<export type {BrainSearchResult,DisclosureMode,+ EvidencePack,ExpandedNote,ExpandedRawChunk,ExpandHitInput,@@ -54,13 +55,14 @@ export type {SearchErrorCode,SearchOptions,SearchOutcome,+ SearchSessionFocus,+ StructuredRecallQueryDocument,VaultIgnoreRule,} from "./types.ts";export { SearchError, SEARCH_ERROR_CODES } from "./types.ts";export {parseStructuredRecallQueryDocument,structuredRecallQueryText,- type StructuredRecallQueryDocument,} from "./structured-query.ts";export {clearSessionFocus,@@ -68,10 +70,9 @@ export {readSessionFocus,sessionFocusIsActive,writeSessionFocus,- type SearchSessionFocus,} from "./session-focus.ts";export { evaluateSurfacingGate, type SurfacingGateDecision } from "./surfacing-gate.ts";-export { buildEvidencePack, serializeEvidencePack, type EvidencePack } from "./evidence-pack.ts";+export { buildEvidencePack, serializeEvidencePack } from "./evidence-pack.ts";export { serializeSearchCard, serializeIndexStatus } from "./serialize.ts";export {loadProviderRegistry,@@ -111,7 +112,8 @@ export {type IndexVaultOptions,type IndexProgressEvent,} from "./indexer.ts";-export { search, expandHit, SEARCH_LIMIT_MIN, SEARCH_LIMIT_MAX } from "./search.ts";+export { search, SEARCH_LIMIT_MIN, SEARCH_LIMIT_MAX } from "./search.ts";+export { expandHit } from "./cards.ts";export { planReadShortlist, planRead } from "./graph-prepass.ts";export type { GraphPrepassOptions, GraphPrepassResult, ShouldReadEntry } from "./graph-prepass.ts";export {diff --git a/src/core/search/profiles.ts b/src/core/search/profiles.tsindex 24b41497..2d04d382 100644--- a/src/core/search/profiles.ts+++ b/src/core/search/profiles.ts@@ -16,7 +16,7 @@* existing config path, byte-for-byte.*/-import type { TunedParameters } from "./tuning.ts";+import type { TunedParameters } from "./types.ts";import { SearchError } from "./types.ts";/** The selectable profile names, narrowest-to-widest. */diff --git a/src/core/search/query-expansion.ts b/src/core/search/query-expansion.tsindex c4d6451f..0a3563db 100644--- a/src/core/search/query-expansion.ts+++ b/src/core/search/query-expansion.ts@@ -25,7 +25,7 @@import { listEntities } from "../brain/entities/registry.ts";import { tokenizeForExpansion } from "./synonyms.ts";-import type { StructuredRecallQueryDocument } from "./structured-query.ts";+import type { StructuredRecallQueryDocument } from "./types.ts";/** Default cap on lex include terms. */export const EXPANSION_MAX_LEX_TERMS = 8;diff --git a/src/core/search/ranker.ts b/src/core/search/ranker.tsindex d2cd4e5b..9b0e3d9f 100644--- a/src/core/search/ranker.ts+++ b/src/core/search/ranker.ts@@ -12,10 +12,15 @@import { clamp01 } from "../math.ts";import { PAGE_TIER_DEFAULT, tierWeight, type PageTier } from "../brain/page-meta/tier.ts";import { weibullDecay, DEFAULT_RECENCY, type WeibullRecencyOptions } from "./recency.ts";-import { scoreSessionFocusTarget, type SearchSessionFocus } from "./session-focus.ts";+import { scoreSessionFocusTarget } from "./session-focus.ts";import { rrfFuse, DEFAULT_RRF_K, type FusionMode } from "./fusion.ts";import type { KeywordHit, SemanticHit, HydratedChunk } from "./store.ts";-import type { BrainSearchResult, ScoreBreakdown, WeightProfile } from "./types.ts";+import type {+ BrainSearchResult,+ ScoreBreakdown,+ SearchSessionFocus,+ WeightProfile,+} from "./types.ts";export interface RankerInputs {readonly keyword: ReadonlyArray<KeywordHit>;diff --git a/src/core/search/rerank/contract.ts b/src/core/search/rerank/contract.tsnew file mode 100644index 00000000..2db5155f--- /dev/null+++ b/src/core/search/rerank/contract.ts@@ -0,0 +1,22 @@+/**+ * Cross-encoder rerank contract (retrieval-precision-quality-loop,+ * card A / t_110867f5).+ *+ * The interface every rerank provider implements, split out from the+ * factory (`provider.ts`) so implementations depend only on this leaf and+ * never on the module that constructs them. A rerank provider jointly+ * re-scores a query against a set of candidate documents and returns one+ * relevance score per document, aligned to the input order.+ */++export interface RerankProvider {+ readonly name: string;+ readonly model: string;+ /**+ * Score each document's relevance to the query. Returns an array of the+ * same length as `documents`, aligned by index. Higher is more relevant.+ * Throws on any provider/transport failure — the caller+ * ({@link applyCrossEncoderRerank}) is responsible for the fail-open.+ */+ rerank(query: string, documents: ReadonlyArray<string>): Promise<number[]>;+}diff --git a/src/core/search/rerank/cross-encoder.ts b/src/core/search/rerank/cross-encoder.tsindex 7ab0d65c..7be1de4b 100644--- a/src/core/search/rerank/cross-encoder.ts+++ b/src/core/search/rerank/cross-encoder.ts@@ -20,7 +20,7 @@import { SearchError } from "../types.ts";import type { OpenAiCompatEndpoint } from "../embeddings/provider-resolve.ts";-import type { RerankProvider } from "./provider.ts";+import type { RerankProvider } from "./contract.ts";/** Default per-request timeout when the caller does not override it. */export const DEFAULT_RERANK_TIMEOUT_MS = 5000;diff --git a/src/core/search/rerank/index.ts b/src/core/search/rerank/index.tsindex fc12b2c7..bae331f9 100644--- a/src/core/search/rerank/index.ts+++ b/src/core/search/rerank/index.ts@@ -24,7 +24,8 @@import { resolveOpenAiCompatEndpoint } from "../embeddings/provider-resolve.ts";import type { BrainSearchResult, ResolvedRerankConfig } from "../types.ts";-import { makeRerankProvider, type RerankProvider } from "./provider.ts";+import { makeRerankProvider } from "./provider.ts";+import type { RerankProvider } from "./contract.ts";/** Fixed-precision so the reason string is stable for a given score. */function fmtScore(x: number): string {diff --git a/src/core/search/rerank/local.ts b/src/core/search/rerank/local.tsindex fd273f8e..6e077cb2 100644--- a/src/core/search/rerank/local.ts+++ b/src/core/search/rerank/local.ts@@ -18,7 +18,7 @@* (query, documents) always yields identical scores.*/-import type { RerankProvider } from "./provider.ts";+import type { RerankProvider } from "./contract.ts";const TOKEN_RE = /[\p{L}\p{N}]{2,}/gu;diff --git a/src/core/search/rerank/provider.ts b/src/core/search/rerank/provider.tsindex bda229ee..56339848 100644--- a/src/core/search/rerank/provider.ts+++ b/src/core/search/rerank/provider.ts@@ -19,18 +19,7 @@*/import type { OpenAiCompatEndpoint } from "../embeddings/provider-resolve.ts";--export interface RerankProvider {- readonly name: string;- readonly model: string;- /**- * Score each document's relevance to the query. Returns an array of the- * same length as `documents`, aligned by index. Higher is more relevant.- * Throws on any provider/transport failure — the caller- * ({@link applyCrossEncoderRerank}) is responsible for the fail-open.- */- rerank(query: string, documents: ReadonlyArray<string>): Promise<number[]>;-}+import type { RerankProvider } from "./contract.ts";/*** Build the default OpenAI-compatible cross-encoder rerank provider for adiff --git a/src/core/search/result-filters.ts b/src/core/search/result-filters.tsnew file mode 100644index 00000000..cc0daf42--- /dev/null+++ b/src/core/search/result-filters.ts@@ -0,0 +1,149 @@+/**+ * Frontmatter-driven post-rank filters and annotations over a ranked+ * result set: the shared per-call frontmatter read cache, property /+ * visibility-scope / agent-ownership filtering, terminal-status+ * collection for evidence downranking, and inline trust metadata.+ */++import { statSync } from "node:fs";+import { join } from "node:path";++import { parseFrontmatter } from "../vault.ts";+import type { FrontmatterMap } from "../types.ts";+import { isVisible, pageVisibility } from "../graph/visibility.ts";+import { isOwnerVisible, pageOwner } from "../graph/agent-scope.ts";+import { filterByProperties } from "./property-filter.ts";+import { deriveTrust } from "./enrich.ts";+import { isTerminalStatus } from "./evidence-pack.ts";+import type { BrainSearchResult } from "./types.ts";++/**+ * One frontmatter read per (vault, path) pair, shared across every filter+ * stage of a single `search()` call. `parseFrontmatter` never throws (a+ * read failure resolves to empty metadata internally), so caching the raw+ * result changes no call site's fallback behaviour - it only stops the+ * same file being read and parsed once per stage instead of once total.+ */+export function readCachedFrontmatter(+ cache: Map<string, FrontmatterMap>,+ vault: string,+ path: string,+): FrontmatterMap {+ const cached = cache.get(path);+ if (cached !== undefined) return cached;+ const [meta] = parseFrontmatter(join(vault, path));+ cache.set(path, meta);+ return meta;+}++/**+ * Build the set of terminal-state paths for evidence-pack downranking.+ * Reads each unique candidate path's frontmatter `status:` field once+ * and includes the path when the declared status is terminal (controlled+ * vocabulary). A missing or unreadable status is non-terminal. This is+ * the language-agnostic replacement for scanning note prose for English+ * status words.+ */+export function buildTerminalPaths(+ vault: string,+ results: ReadonlyArray<BrainSearchResult>,+ frontmatterCache: Map<string, FrontmatterMap>,+): ReadonlySet<string> {+ const terminal = new Set<string>();+ const seen = new Set<string>();+ for (const r of results) {+ if (seen.has(r.path)) continue;+ seen.add(r.path);+ try {+ const meta = readCachedFrontmatter(frontmatterCache, vault, r.path);+ if (isTerminalStatus((meta as Record<string, unknown>)["status"])) terminal.add(r.path);+ } catch {+ // Unreadable frontmatter is non-terminal.+ }+ }+ return terminal;+}++export function applyPropertyFilter(+ ranked: ReadonlyArray<BrainSearchResult>,+ filters: ReadonlyMap<string, ReadonlyArray<string>>,+ vault: string,+ frontmatterCache: Map<string, FrontmatterMap>,+): ReadonlyArray<BrainSearchResult> {+ const reader = (path: string): Record<string, unknown> | null => {+ try {+ return readCachedFrontmatter(frontmatterCache, vault, path) as Record<string, unknown>;+ } catch {+ return null;+ }+ };+ return filterByProperties(ranked, filters, reader);+}++/**+ * Stamp inline trust metadata (Search & Recall Quality Suite) onto each+ * result: age from the document mtime, plus the superseded / conflict+ * flags from the typed relations the result already carries. Read-time+ * and never stored. One `statSync` per surfaced result (≤ limit); a path+ * that cannot be stat'd is left without trust rather than reporting a+ * bogus age.+ */+export function attachTrustMetadata(+ vault: string,+ results: ReadonlyArray<BrainSearchResult>,+): ReadonlyArray<BrainSearchResult> {+ const nowMs = Date.now();+ return results.map((r) => {+ let mtimeMs: number;+ try {+ mtimeMs = statSync(join(vault, r.path)).mtimeMs;+ } catch {+ return r;+ }+ return Object.freeze({+ ...r,+ trust: deriveTrust({ mtimeMs, nowMs, ...(r.relations ? { relations: r.relations } : {}) }),+ });+ });+}++export function applyVisibilityScope(+ ranked: ReadonlyArray<BrainSearchResult>,+ scope: ReadonlySet<string>,+ vault: string,+ frontmatterCache: Map<string, FrontmatterMap>,+): ReadonlyArray<BrainSearchResult> {+ const tagsFor = (path: string): string[] => {+ try {+ return pageVisibility(readCachedFrontmatter(frontmatterCache, vault, path));+ } catch {+ return [];+ }+ };+ return ranked.filter((r) => isVisible(tagsFor(r.path), scope));+}++export function applyAgentScope(+ ranked: ReadonlyArray<BrainSearchResult>,+ scope: string,+ vault: string,+ frontmatterCache: Map<string, FrontmatterMap>,+): ReadonlyArray<BrainSearchResult> {+ // Fail-closed sentinel: a page whose frontmatter cannot be parsed has+ // an unknowable owner, so under an active scope it is dropped rather+ // than leaked. This is stricter than visibility scoping's fail-open+ // default - deliberate, because agent-scope is an isolation boundary.+ const UNPARSEABLE = " unparseable-owner";+ const ownerFor = (path: string): string => {+ try {+ return pageOwner(readCachedFrontmatter(frontmatterCache, vault, path)) ?? "";+ } catch {+ return UNPARSEABLE;+ }+ };+ return ranked.filter((r) => {+ const owner = ownerFor(r.path);+ if (owner === UNPARSEABLE) return false; // fail closed+ return isOwnerVisible(owner === "" ? null : owner, scope);+ });+}diff --git a/src/core/search/search.ts b/src/core/search/search.tsindex 2d02ebc7..f7ee0a2f 100644--- a/src/core/search/search.ts+++ b/src/core/search/search.ts@@ -12,11 +12,9 @@import { statSync } from "node:fs";import { join } from "node:path";-import { parseFrontmatter } from "../vault.ts";import type { FrontmatterMap } from "../types.ts";-import { isVisible, normalizeVisibilityScope, pageVisibility } from "../graph/visibility.ts";-import { isOwnerVisible, normalizeAgentScope, pageOwner } from "../graph/agent-scope.ts";-import { makeProvider } from "./embeddings/provider.ts";+import { normalizeVisibilityScope } from "../graph/visibility.ts";+import { normalizeAgentScope } from "../graph/agent-scope.ts";import { isLowSelectivity, planTrigramPrefilter } from "./trigram-prefilter.ts";import {composeWeightProfiles,@@ -39,68 +37,54 @@ import {import { extractEntities } from "./entities.ts";import { expandQueryEntities } from "./entity-alias.ts";import {- buildCoverageReport,COMPLETENESS_COMPLETE_THRESHOLD,planTargetedRetry,significantTerms,- termIncludedIn,- type CoverageReport,} from "./coverage.ts";-import {- buildEvidencePack,- downrankTerminalEvidenceResults,- isTerminalStatus,-} from "./evidence-pack.ts";-import type { EvidenceUnionRecord, EvidenceVerification } from "./evidence-pack.ts";+import { buildEvidencePack, downrankTerminalEvidenceResults } from "./evidence-pack.ts";import { runFtsQueryDetailed } from "./fts.ts";import { mmrRerank } from "./mmr.ts";import { buildQueryPlan } from "./query-plan.ts";import { buildCacheKey, getCachedOutcome, putCachedOutcome } from "./query-cache.ts";import { deriveExpansionTerms, tokenizeForExpansion, DEFAULT_EXPANSION } from "./synonyms.ts";-import { filterByProperties } from "./property-filter.ts";-import { applyRelationPolarity } from "./relation-polarity.ts";import { rankResults } from "./ranker.ts";-import { deriveTrust, detectHybridDegrade, rerankByRelevance } from "./enrich.ts";+import { detectHybridDegrade, rerankByRelevance } from "./enrich.ts";import { applyReinforceBoost, loadReinforceStrengths, reinforceFingerprint } from "./reinforce.ts";import { readActiveSessionFocus } from "./session-focus.ts";import { applyTemporalBridge } from "./temporal-bridge.ts";import { resolveTimeRange } from "./time-range.ts";import { eventTimeInRange, parseValidityWindow, type ValidityWindow } from "./validity.ts";-import { expandByTraversal, type TraversalOptions } from "./traversal.ts";import { Store } from "./store.ts";-import { formatLinePointer } from "./line-numbering.ts";import { SearchError } from "./types.ts";import type {BrainSearchResult,- ExpandHitInput,- ExpandHitResult,ResolvedSearchConfig,- SearchCard,SearchOptions,SearchOutcome,} from "./types.ts";-import type { StructuredRecallQueryDocument } from "./structured-query.ts";import { expandQuery } from "./query-expansion.ts";-import { applyTunedParameters, loadTunedParameters } from "./tuning.ts";+import { applyTunedParameters, loadTunedParameters } from "./tuning-store.ts";import { resolveRecallProfile } from "./profiles.ts";import { applyCrossEncoderRerank } from "./rerank/index.ts";import { emitGatedTelemetry } from "../brain/continuity/emit.ts";--interface SemanticPolicy {- /** caller asked for semantic on or off (true), or accepted the default (false). */- readonly explicit: boolean;- /** does the caller want semantic at all? */- readonly wantSemantic: boolean;-}--function resolveSemanticPolicy(config: ResolvedSearchConfig, opts: SearchOptions): SemanticPolicy {- if (opts.keywordOnly === true) {- return { explicit: true, wantSemantic: false };- }- if (opts.semantic === true) return { explicit: true, wantSemantic: true };- if (opts.semantic === false) return { explicit: true, wantSemantic: false };- return { explicit: false, wantSemantic: config.semantic.enabled };-}+import {+ addStructuredReasons,+ applyStructuredExclusions,+ structuredKeywordQuery,+ structuredSemanticQuery,+} from "./structured-lanes.ts";+import { resolveSemanticPolicy, runSemanticPhase, semanticPoolSize } from "./semantic-phase.ts";+import { toSearchCard } from "./cards.ts";+import {+ applyAgentScope,+ applyPropertyFilter,+ applyVisibilityScope,+ attachTrustMetadata,+ buildTerminalPaths,+ readCachedFrontmatter,+} from "./result-filters.ts";+import { applyRelationPolarityPhase, applyTraversal } from "./graph-phases.ts";+import { buildEvidenceVerification, coverageOverChunks } from "./evidence-verification.ts";/*** A compact fingerprint of the resolved-config fields that change search@@ -151,62 +135,6 @@ function assertSafePathPrefix(prefix: string | undefined): string | undefined {return prefix;}-function structuredKeywordQuery(- query: string,- structured: StructuredRecallQueryDocument | undefined,-): string {- if (!structured || structured.lex.include.length === 0) return query;- return structured.lex.include.join(" ");-}--function structuredSemanticQuery(- structured: StructuredRecallQueryDocument | undefined,-): string | null {- if (!structured) return null;- const text = [...structured.vec, ...structured.hyde].join("\n\n").trim();- return text.length > 0 ? text : null;-}--function includesFolded(haystack: string, needle: string): boolean {- return haystack.toLocaleLowerCase().includes(needle.toLocaleLowerCase());-}--function applyStructuredExclusions(- results: ReadonlyArray<BrainSearchResult>,- structured: StructuredRecallQueryDocument | undefined,-): ReadonlyArray<BrainSearchResult> {- if (!structured || structured.lex.exclude.length === 0) return results;- return results.filter((result) => {- const haystack = `${result.path}\n${result.title ?? ""}\n${result.content}`;- return !structured.lex.exclude.some((term) => includesFolded(haystack, term));- });-}--function addStructuredReasons(- results: ReadonlyArray<BrainSearchResult>,- structured: StructuredRecallQueryDocument | undefined,-): ReadonlyArray<BrainSearchResult> {- if (!structured) return results;- return results.map((result) => {- const additions: string[] = [];- if (structured.lex.include.length > 0 && result.keywordScore > 0) {- additions.push(`lane:lex/fts5 ${result.keywordScore.toFixed(3)}`);- }- if (structured.vec.length > 0 && result.semanticScore > 0) {- additions.push(`lane:vec/semantic ${result.semanticScore.toFixed(3)}`);- }- if (structured.hyde.length > 0 && result.semanticScore > 0) {- additions.push(`lane:hyde/semantic ${result.semanticScore.toFixed(3)}`);- }- if (structured.intent !== null) additions.push(`intent:${structured.intent}`);- if (additions.length === 0) return result;- return Object.freeze({- ...result,- reasons: Object.freeze([...result.reasons, ...additions]),- });- });-}-/*** Open the index for reading, self-healing a stale, absent, or unreadable* index. After a plugin upgrade the on-disk index can be a different schema@@ -246,39 +174,6 @@ async function openReadOrSelfHeal(config: ResolvedSearchConfig): Promise<Store>export const SEARCH_LIMIT_MIN = 1;export const SEARCH_LIMIT_MAX = 100;-/**- * Semantic candidate-pool over-fetch policy: rank more than `limit` rows- * so downstream filtering (property/visibility scope, MMR diversify) has- * enough headroom to still fill the final window. `floor` is the minimum- * pool size regardless of `limit`; `overfetch` is the multiplier applied- * to `limit` itself.- */-const POOL_OVERFETCH = 5;-const POOL_FLOOR = 50;--function semanticPoolSize(limit: number): number {- return Math.max(limit * POOL_OVERFETCH, POOL_FLOOR);-}--/**- * One frontmatter read per (vault, path) pair, shared across every filter- * stage of a single `search()` call. `parseFrontmatter` never throws (a- * read failure resolves to empty metadata internally), so caching the raw- * result changes no call site's fallback behaviour - it only stops the- * same file being read and parsed once per stage instead of once total.- */-function readCachedFrontmatter(- cache: Map<string, FrontmatterMap>,- vault: string,- path: string,-): FrontmatterMap {- const cached = cache.get(path);- if (cached !== undefined) return cached;- const [meta] = parseFrontmatter(join(vault, path));- cache.set(path, meta);- return meta;-}-export async function search(config: ResolvedSearchConfig,opts: SearchOptions,@@ -1188,167 +1083,6 @@ export async function search(}}-/** Max chars of a layer-1 card snippet — enough to judge a hit, cheap to carry. */-const CARD_SNIPPET_CHARS = 240;-/** Default layer-3 raw-chunk page size for `expandHit`. */-const DEFAULT_EXPAND_RAW_LIMIT = 10;--/**- * Project a ranked result into a layer-1 card (progressive disclosure):- * identity + score + the same `reasons`, a whitespace-collapsed snippet- * capped at {@link CARD_SNIPPET_CHARS}, and a `path:Lstart-Lend` pointer- * (D2 grammar) over the chunk's stored line span. No full content.- */-function toSearchCard(result: BrainSearchResult): SearchCard {- return Object.freeze({- chunkId: result.chunkId,- documentId: result.documentId,- path: result.path,- title: result.title,- score: result.score,- reasons: result.reasons,- snippet: cardSnippet(result.content),- pointer: formatLinePointer(result.path, result.startLine, result.endLine),- ...(result.origin !== undefined ? { origin: result.origin } : {}),- });-}--export function cardSnippet(content: string): string {- const collapsed = content.replace(/\s+/g, " ").trim();- // Truncate on code points, not UTF-16 units: a raw `.slice` can cut an- // astral character (emoji, rare CJK) mid-surrogate-pair, shipping a lone- // surrogate that renders as U+FFFD. Spreading into an array iterates by- // code point, so the cap never splits a character.- const points = [...collapsed];- return points.length <= CARD_SNIPPET_CHARS- ? collapsed- : `${points.slice(0, CARD_SNIPPET_CHARS).join("")}...`;-}--/**- * Progressive disclosure (D3): layers 2 and 3 of a hit the agent already- * holds as a layer-1 card. Given the card's `chunkId`, reconstruct the- * fuller note (layer 2) from the document's stored chunks and return a- * paginated slice of those raw chunks (layer 3), mirroring- * `expandSessionRecall`'s cursor contract.- *- * Read-only by construction: it opens the index in read mode and never- * self-heals — a card can only exist because a prior search built the- * index, and a rebuild would WRITE it. The layer-2/3 data is pure store- * reads (`hydrateChunks` + `getChunksByDocument`), never a new index.- */-export async function expandHit(- config: ResolvedSearchConfig,- input: ExpandHitInput,-): Promise<ExpandHitResult> {- if (!Number.isInteger(input.chunkId) || input.chunkId < 1) {- throw new SearchError("INVALID_INPUT", "chunkId must be a positive integer");- }- const store = await Store.open(config, { mode: "read" });- try {- const hit = store.hydrateChunks([input.chunkId]).get(input.chunkId);- if (hit === undefined) {- throw new SearchError("INVALID_INPUT", `chunk not found: ${input.chunkId}`);- }- // Document chunks in `chunkIndex` order: the fuller note (layer 2) is- // their concatenation; the raw transcript (layer 3) is the same rows.- const chunks = store.getChunksByDocument(hit.documentId);- const lineStart = chunks.length > 0 ? chunks[0]!.startLine : hit.startLine;- const lineEnd = chunks.length > 0 ? chunks[chunks.length - 1]!.endLine : hit.endLine;- const note = Object.freeze({- documentId: hit.documentId,- path: hit.path,- title: hit.title,- lineStart,- lineEnd,- pointer: formatLinePointer(hit.path, lineStart, lineEnd),- content: chunks.map((c) => c.content).join("\n"),- });-- const offset = Math.max(0, Number.parseInt(input.cursor ?? "0", 10) || 0);- const rawLimit = Math.max(1, input.rawLimit ?? DEFAULT_EXPAND_RAW_LIMIT);- const page = chunks.slice(offset, offset + rawLimit).map((c) =>- Object.freeze({- chunkId: c.id,- chunkIndex: c.chunkIndex,- startLine: c.startLine,- endLine: c.endLine,- pointer: formatLinePointer(hit.path, c.startLine, c.endLine),- content: c.content,- }),- );- const nextOffset = offset + rawLimit;- return Object.freeze({- chunkId: input.chunkId,- note,- raw_content: Object.freeze(page),- next_cursor: nextOffset < chunks.length ? String(nextOffset) : null,- });- } finally {- await store.close();- }-}--/**- * Walk outbound links from the ranked hits and merge in related- * documents. Fetches the outbound adjacency level-by-level (each- * document fetched once) up to `maxHops`, then delegates the bounded- * scoring to the pure `expandByTraversal`.- */-function applyTraversal(- store: Store,- ranked: BrainSearchResult[],- opts: TraversalOptions,-): BrainSearchResult[] {- const seedDocIds = Array.from(new Set(ranked.map((r) => r.documentId)));- const present = new Set(seedDocIds);- const outbound = new Map<number, ReadonlyArray<number>>();- const seen = new Set<number>(seedDocIds);- let level = new Set<number>(seedDocIds);-- for (let hop = 0; hop < opts.maxHops && level.size > 0; hop++) {- const toFetch = Array.from(level).filter((id) => !outbound.has(id));- if (toFetch.length === 0) break;- const adjacency = store.outboundLinkTargets(toFetch);- const next = new Set<number>();- for (const [src, targets] of adjacency) {- outbound.set(src, targets);- for (const t of targets) {- if (!seen.has(t)) {- seen.add(t);- next.add(t);- }- }- }- level = next;- }-- const expansionIds = Array.from(seen).filter((id) => !present.has(id));- if (expansionIds.length === 0) return ranked;- const reps = store.representativeChunks(expansionIds);-- return expandByTraversal(- {- ranked,- outbound,- expansionDoc: (docId) => {- const h = reps.get(docId);- if (!h) return null;- return {- documentId: h.documentId,- chunkId: h.chunkId,- path: h.path,- title: h.title,- content: h.content,- startLine: h.startLine,- endLine: h.endLine,- };- },- },- opts,- );-}-/** A token in at least this share of the corpus is treated as common. */const COMMON_TOKEN_CORPUS_SHARE = 0.5;/**@@ -1386,336 +1120,3 @@ function highFrequencyTokens(store: Store, query: string): ReadonlySet<string> {}return common;}--/**- * Build the set of terminal-state paths for evidence-pack downranking.- * Reads each unique candidate path's frontmatter `status:` field once- * and includes the path when the declared status is terminal (controlled- * vocabulary). A missing or unreadable status is non-terminal. This is- * the language-agnostic replacement for scanning note prose for English- * status words.- */-function buildTerminalPaths(- vault: string,- results: ReadonlyArray<BrainSearchResult>,- frontmatterCache: Map<string, FrontmatterMap>,-): ReadonlySet<string> {- const terminal = new Set<string>();- const seen = new Set<string>();- for (const r of results) {- if (seen.has(r.path)) continue;- seen.add(r.path);- try {- const meta = readCachedFrontmatter(frontmatterCache, vault, r.path);- if (isTerminalStatus((meta as Record<string, unknown>)["status"])) terminal.add(r.path);- } catch {- // Unreadable frontmatter is non-terminal.- }- }- return terminal;-}--/** Cap on extra records fetched per uncovered term (Feature C union). */-const UNION_RECORDS_PER_TERM = 2;-/** Cap on the total recall-union fetch per query. */-const UNION_RECORDS_TOTAL = 8;--/**- * Coverage verification for evidence-pack mode (recall-trust-suite,- * Feature C): corpus document frequencies for the significant terms,- * the covered-term set over the returned results, and a bounded- * per-token recall union — for each term the ranked set left uncovered,- * fetch up to {@link UNION_RECORDS_PER_TERM} records that DO cover it- * (evidence can span records the primary ranking never surfaced).- */-/**- * IDF-weighted coverage of the query over a candidate POOL (the partial- * self-correcting retry trigger, t_8eb5ca32). Mirrors the result-set- * coverage in {@link buildEvidenceVerification} but scores the- * pre-ranking candidate chunks: a term is covered when any candidate's- * path/title/content contains it. Corpus document frequencies and the- * document count come from the store, exactly as the result-set pass- * does, so the two reports share one definition of "covered" and one- * IDF scale.- */-function coverageOverChunks(- store: Store,- query: string,- chunkIds: ReadonlyArray<number>,-): CoverageReport {- const terms = significantTerms(query);- const dfByTerm = store.documentFrequencies(terms);- const documentCount = store.counts().documents;- const hydrated = store.hydrateChunks(chunkIds);- const covered = new Set<string>();- for (const h of hydrated.values()) {- const haystack = `${h.path}\n${h.title ?? ""}\n${h.content}`;- for (const t of terms) {- if (!covered.has(t) && termIncludedIn(haystack, t)) covered.add(t);- }- }- return buildCoverageReport({- significantTerms: terms,- coveredTerms: covered,- documentCount,- dfByTerm,- });-}--function buildEvidenceVerification(- store: Store,- query: string,- results: ReadonlyArray<BrainSearchResult>,- pathPrefix: string | undefined,-): EvidenceVerification {- const terms = significantTerms(query);- const dfByTerm = store.documentFrequencies(terms);- const documentCount = store.counts().documents;- const covered = new Set<string>();- for (const r of results) {- const haystack = `${r.path}\n${r.title ?? ""}\n${r.content}`;- for (const t of terms) {- if (!covered.has(t) && termIncludedIn(haystack, t)) covered.add(t);- }- }- const coverage = buildCoverageReport({- significantTerms: terms,- coveredTerms: covered,- documentCount,- dfByTerm,- });-- const unionRecords: EvidenceUnionRecord[] = [];- for (const t of coverage.terms) {- if (t.covered || t.df === 0) continue; // nothing in the corpus covers a df=0 term- if (unionRecords.length >= UNION_RECORDS_TOTAL) break;- const outcome = runFtsQueryDetailed(store, t.term, {- limit: UNION_RECORDS_PER_TERM,- pathPrefix,- });- const ids = outcome.hits.map((h) => h.chunkId);- const hydrated = store.hydrateChunks(ids);- for (const hit of outcome.hits) {- if (unionRecords.length >= UNION_RECORDS_TOTAL) break;- const h = hydrated.get(hit.chunkId);- if (!h) continue;- unionRecords.push(- Object.freeze({- term: t.term,- path: h.path,- documentId: h.documentId,- chunkId: h.chunkId,- }),- );- }- }- return Object.freeze({ coverage, unionRecords: Object.freeze(unionRecords) });-}--/**- * Fetch the typed relation edges declared by the pool's documents and- * delegate the polarity adjustment to the pure `applyRelationPolarity`.- * Successor pull-in reuses the traversal layer's representative-chunk- * mechanism (document head as the surfaced chunk).- */-function applyRelationPolarityPhase(- store: Store,- ranked: ReadonlyArray<BrainSearchResult>,- includeSuperseded: boolean,-): ReadonlyArray<BrainSearchResult> {- if (ranked.length === 0) return ranked;- const docIds = Array.from(new Set(ranked.map((r) => r.documentId)));- const edges = store.typedRelationEdgesForDocuments(docIds);- if (edges.length === 0) return ranked;-- const present = new Set(docIds);- const successorIds = Array.from(- new Set(- edges- .map((e) => e.targetDocumentId)- .filter((id): id is number => id !== null && !present.has(id)),- ),- );- const reps = store.representativeChunks(successorIds);-- return applyRelationPolarity(- {- ranked,- edges,- successorDoc: (docId) => {- const h = reps.get(docId);- if (!h) return null;- return {- documentId: h.documentId,- chunkId: h.chunkId,- path: h.path,- title: h.title,- content: h.content,- startLine: h.startLine,- endLine: h.endLine,- };- },- },- { includeSuperseded },- );-}--function applyPropertyFilter(- ranked: ReadonlyArray<BrainSearchResult>,- filters: ReadonlyMap<string, ReadonlyArray<string>>,- vault: string,- frontmatterCache: Map<string, FrontmatterMap>,-): ReadonlyArray<BrainSearchResult> {- const reader = (path: string): Record<string, unknown> | null => {- try {- return readCachedFrontmatter(frontmatterCache, vault, path) as Record<string, unknown>;- } catch {- return null;- }- };- return filterByProperties(ranked, filters, reader);-}--/**- * Stamp inline trust metadata (Search & Recall Quality Suite) onto each- * result: age from the document mtime, plus the superseded / conflict- * flags from the typed relations the result already carries. Read-time- * and never stored. One `statSync` per surfaced result (≤ limit); a path- * that cannot be stat'd is left without trust rather than reporting a- * bogus age.- */-function attachTrustMetadata(- vault: string,- results: ReadonlyArray<BrainSearchResult>,-): ReadonlyArray<BrainSearchResult> {- const nowMs = Date.now();- return results.map((r) => {- let mtimeMs: number;- try {- mtimeMs = statSync(join(vault, r.path)).mtimeMs;- } catch {- return r;- }- return Object.freeze({- ...r,- trust: deriveTrust({ mtimeMs, nowMs, ...(r.relations ? { relations: r.relations } : {}) }),- });- });-}--function applyVisibilityScope(- ranked: ReadonlyArray<BrainSearchResult>,- scope: ReadonlySet<string>,- vault: string,- frontmatterCache: Map<string, FrontmatterMap>,-): ReadonlyArray<BrainSearchResult> {- const tagsFor = (path: string): string[] => {- try {- return pageVisibility(readCachedFrontmatter(frontmatterCache, vault, path));- } catch {- return [];- }- };- return ranked.filter((r) => isVisible(tagsFor(r.path), scope));-}--function applyAgentScope(- ranked: ReadonlyArray<BrainSearchResult>,- scope: string,- vault: string,- frontmatterCache: Map<string, FrontmatterMap>,-): ReadonlyArray<BrainSearchResult> {- // Fail-closed sentinel: a page whose frontmatter cannot be parsed has- // an unknowable owner, so under an active scope it is dropped rather- // than leaked. This is stricter than visibility scoping's fail-open- // default - deliberate, because agent-scope is an isolation boundary.- const UNPARSEABLE = " unparseable-owner";- const ownerFor = (path: string): string => {- try {- return pageOwner(readCachedFrontmatter(frontmatterCache, vault, path)) ?? "";- } catch {- return UNPARSEABLE;- }- };- return ranked.filter((r) => {- const owner = ownerFor(r.path);- if (owner === UNPARSEABLE) return false; // fail closed- return isOwnerVisible(owner === "" ? null : owner, scope);- });-}--interface SemanticPhaseOutcome {- readonly attempted: boolean;- readonly hits: ReturnType<Store["semanticTopK"]>;- readonly warnings: string[];-}--async function runSemanticPhase(- store: Store,- config: ResolvedSearchConfig,- query: string,- opts: { limit: number; pathPrefix: string | undefined; explicit: boolean },-): Promise<SemanticPhaseOutcome> {- const warnings: string[] = [];-- const counts = store.counts();- if (counts.embeddings === 0) {- warnings.push("no compatible embeddings; run: o2b search index --embeddings");- return { attempted: false, hits: [], warnings };- }-- if (!store.vecLoaded()) {- if (opts.explicit) {- throw new SearchError(- "VEC_EXTENSION_UNAVAILABLE",- "semantic search unavailable: sqlite-vec extension not loaded",- );- }- warnings.push("sqlite-vec unavailable, semantic disabled this session");- return { attempted: false, hits: [], warnings };- }- if (!config.semantic.enabled) {- // Defensive: should be handled at policy layer, but in case caller- // forced wantSemantic without enabling, treat as implicit warning.- warnings.push("semantic not enabled in config; using keyword-only");- return { attempted: false, hits: [], warnings };- }- // The offline local provider needs no key; every remote provider does.- if (config.semantic.provider !== "local" && !config.semantic.apiKey) {- if (opts.explicit) {- throw new SearchError("EMBEDDING_KEY_MISSING", "embedding key not configured");- }- warnings.push("embedding key not configured; semantic disabled");- return { attempted: false, hits: [], warnings };- }-- let queryVec: number[];- try {- const provider = makeProvider(config.semantic);- const vectors = await provider.embed([query]);- queryVec = vectors[0] ?? [];- } catch (e) {- if (opts.explicit) {- // Defensive: provider methods are expected to throw SearchError,- // but wrap anything else (e.g. an unexpected runtime failure)- // so callers always see a typed code rather than a bare Error.- if (e instanceof SearchError) throw e;- const msg = e instanceof Error ? e.message : String(e);- throw new SearchError("EMBEDDING_PROVIDER_HTTP", `embedding provider failure: ${msg}`);- }- const msg = e instanceof Error ? e.message : String(e);- warnings.push(`embedding provider unavailable: ${msg}`);- return { attempted: false, hits: [], warnings };- }-- if (queryVec.length === 0) {- warnings.push("embedding provider returned an empty vector; semantic skipped");- return { attempted: false, hits: [], warnings };- }-- const hits = store.semanticTopK(queryVec, {- limit: opts.limit,- pathPrefix: opts.pathPrefix,- });- return { attempted: true, hits, warnings };-}diff --git a/src/core/search/semantic-phase.ts b/src/core/search/semantic-phase.tsnew file mode 100644index 00000000..cb48a114--- /dev/null+++ b/src/core/search/semantic-phase.ts@@ -0,0 +1,120 @@+/**+ * Semantic candidate lane: the on/off policy the caller's options resolve+ * to, the candidate-pool over-fetch sizing, and the guarded semantic+ * phase that embeds the query and runs the vector top-K (self-degrading+ * to keyword-only with warnings when the lane cannot run).+ */++import { makeProvider } from "./embeddings/provider.ts";+import { Store } from "./store.ts";+import { SearchError } from "./types.ts";+import type { ResolvedSearchConfig, SearchOptions } from "./types.ts";++export interface SemanticPolicy {+ /** caller asked for semantic on or off (true), or accepted the default (false). */+ readonly explicit: boolean;+ /** does the caller want semantic at all? */+ readonly wantSemantic: boolean;+}++export function resolveSemanticPolicy(+ config: ResolvedSearchConfig,+ opts: SearchOptions,+): SemanticPolicy {+ if (opts.keywordOnly === true) {+ return { explicit: true, wantSemantic: false };+ }+ if (opts.semantic === true) return { explicit: true, wantSemantic: true };+ if (opts.semantic === false) return { explicit: true, wantSemantic: false };+ return { explicit: false, wantSemantic: config.semantic.enabled };+}++/**+ * Semantic candidate-pool over-fetch policy: rank more than `limit` rows+ * so downstream filtering (property/visibility scope, MMR diversify) has+ * enough headroom to still fill the final window. `floor` is the minimum+ * pool size regardless of `limit`; `overfetch` is the multiplier applied+ * to `limit` itself.+ */+const POOL_OVERFETCH = 5;+const POOL_FLOOR = 50;++export function semanticPoolSize(limit: number): number {+ return Math.max(limit * POOL_OVERFETCH, POOL_FLOOR);+}++interface SemanticPhaseOutcome {+ readonly attempted: boolean;+ readonly hits: ReturnType<Store["semanticTopK"]>;+ readonly warnings: string[];+}++export async function runSemanticPhase(+ store: Store,+ config: ResolvedSearchConfig,+ query: string,+ opts: { limit: number; pathPrefix: string | undefined; explicit: boolean },+): Promise<SemanticPhaseOutcome> {+ const warnings: string[] = [];++ const counts = store.counts();+ if (counts.embeddings === 0) {+ warnings.push("no compatible embeddings; run: o2b search index --embeddings");+ return { attempted: false, hits: [], warnings };+ }++ if (!store.vecLoaded()) {+ if (opts.explicit) {+ throw new SearchError(+ "VEC_EXTENSION_UNAVAILABLE",+ "semantic search unavailable: sqlite-vec extension not loaded",+ );+ }+ warnings.push("sqlite-vec unavailable, semantic disabled this session");+ return { attempted: false, hits: [], warnings };+ }+ if (!config.semantic.enabled) {+ // Defensive: should be handled at policy layer, but in case caller+ // forced wantSemantic without enabling, treat as implicit warning.+ warnings.push("semantic not enabled in config; using keyword-only");+ return { attempted: false, hits: [], warnings };+ }+ // The offline local provider needs no key; every remote provider does.+ if (config.semantic.provider !== "local" && !config.semantic.apiKey) {+ if (opts.explicit) {+ throw new SearchError("EMBEDDING_KEY_MISSING", "embedding key not configured");+ }+ warnings.push("embedding key not configured; semantic disabled");+ return { attempted: false, hits: [], warnings };+ }++ let queryVec: number[];+ try {+ const provider = makeProvider(config.semantic);+ const vectors = await provider.embed([query]);+ queryVec = vectors[0] ?? [];+ } catch (e) {+ if (opts.explicit) {+ // Defensive: provider methods are expected to throw SearchError,+ // but wrap anything else (e.g. an unexpected runtime failure)+ // so callers always see a typed code rather than a bare Error.+ if (e instanceof SearchError) throw e;+ const msg = e instanceof Error ? e.message : String(e);+ throw new SearchError("EMBEDDING_PROVIDER_HTTP", `embedding provider failure: ${msg}`);+ }+ const msg = e instanceof Error ? e.message : String(e);+ warnings.push(`embedding provider unavailable: ${msg}`);+ return { attempted: false, hits: [], warnings };+ }++ if (queryVec.length === 0) {+ warnings.push("embedding provider returned an empty vector; semantic skipped");+ return { attempted: false, hits: [], warnings };+ }++ const hits = store.semanticTopK(queryVec, {+ limit: opts.limit,+ pathPrefix: opts.pathPrefix,+ });+ return { attempted: true, hits, warnings };+}diff --git a/src/core/search/session-focus.ts b/src/core/search/session-focus.tsindex 60d506b7..ce87f9ce 100644--- a/src/core/search/session-focus.ts+++ b/src/core/search/session-focus.ts@@ -3,13 +3,7 @@ import { dirname, join } from "node:path";import { resolveSessionScope } from "../brain/session-scope.ts";import { resolveIndexPath } from "./paths.ts";-import { SearchError, type ResolvedSearchConfig } from "./types.ts";--export interface SearchSessionFocus {- readonly query: string | null;- readonly pathPrefix: string | null;- readonly expiresAt: number | null;-}+import { SearchError, type ResolvedSearchConfig, type SearchSessionFocus } from "./types.ts";export interface SessionFocusInput {readonly query?: string | null;diff --git a/src/core/search/structured-lanes.ts b/src/core/search/structured-lanes.tsnew file mode 100644index 00000000..834f3aee--- /dev/null+++ b/src/core/search/structured-lanes.ts@@ -0,0 +1,64 @@+/**+ * Structured-recall query document (t_2fa95db1) application helpers: fold+ * an explicit structured query into the keyword / semantic lane inputs,+ * apply its lexical exclusions, and attribute the lanes it activated on+ * each surfaced result. Parsing lives in `structured-query.ts`.+ */++import type { BrainSearchResult, StructuredRecallQueryDocument } from "./types.ts";++export function structuredKeywordQuery(+ query: string,+ structured: StructuredRecallQueryDocument | undefined,+): string {+ if (!structured || structured.lex.include.length === 0) return query;+ return structured.lex.include.join(" ");+}++export function structuredSemanticQuery(+ structured: StructuredRecallQueryDocument | undefined,+): string | null {+ if (!structured) return null;+ const text = [...structured.vec, ...structured.hyde].join("\n\n").trim();+ return text.length > 0 ? text : null;+}++function includesFolded(haystack: string, needle: string): boolean {+ return haystack.toLocaleLowerCase().includes(needle.toLocaleLowerCase());+}++export function applyStructuredExclusions(+ results: ReadonlyArray<BrainSearchResult>,+ structured: StructuredRecallQueryDocument | undefined,+): ReadonlyArray<BrainSearchResult> {+ if (!structured || structured.lex.exclude.length === 0) return results;+ return results.filter((result) => {+ const haystack = `${result.path}\n${result.title ?? ""}\n${result.content}`;+ return !structured.lex.exclude.some((term) => includesFolded(haystack, term));+ });+}++export function addStructuredReasons(+ results: ReadonlyArray<BrainSearchResult>,+ structured: StructuredRecallQueryDocument | undefined,+): ReadonlyArray<BrainSearchResult> {+ if (!structured) return results;+ return results.map((result) => {+ const additions: string[] = [];+ if (structured.lex.include.length > 0 && result.keywordScore > 0) {+ additions.push(`lane:lex/fts5 ${result.keywordScore.toFixed(3)}`);+ }+ if (structured.vec.length > 0 && result.semanticScore > 0) {+ additions.push(`lane:vec/semantic ${result.semanticScore.toFixed(3)}`);+ }+ if (structured.hyde.length > 0 && result.semanticScore > 0) {+ additions.push(`lane:hyde/semantic ${result.semanticScore.toFixed(3)}`);+ }+ if (structured.intent !== null) additions.push(`intent:${structured.intent}`);+ if (additions.length === 0) return result;+ return Object.freeze({+ ...result,+ reasons: Object.freeze([...result.reasons, ...additions]),+ });+ });+}diff --git a/src/core/search/structured-query.ts b/src/core/search/structured-query.tsindex d3042823..0d7d8e7b 100644--- a/src/core/search/structured-query.ts+++ b/src/core/search/structured-query.ts@@ -1,16 +1,9 @@-import { SearchError, type QueryIntent } from "./types.ts";--export interface StructuredLexLane {- readonly include: ReadonlyArray<string>;- readonly exclude: ReadonlyArray<string>;-}--export interface StructuredRecallQueryDocument {- readonly intent: QueryIntent | null;- readonly lex: StructuredLexLane;- readonly vec: ReadonlyArray<string>;- readonly hyde: ReadonlyArray<string>;-}+import {+ SearchError,+ type QueryIntent,+ type StructuredLexLane,+ type StructuredRecallQueryDocument,+} from "./types.ts";const ALLOWED_INTENTS = new Set<QueryIntent>(["neutral", "exact", "entity", "broad"]);const ALLOWED_LANES = new Set(["intent", "lex", "vec", "hyde"]);diff --git a/src/core/search/tuning-store.ts b/src/core/search/tuning-store.tsnew file mode 100644index 00000000..f702a489--- /dev/null+++ b/src/core/search/tuning-store.ts@@ -0,0 +1,89 @@+/**+ * Persisted tuned-parameters store (link-recall-intelligence, t_ae973491).+ *+ * The read/reset side of `Brain/search/tuning.json`, the bounded grid+ * axes, and `applyTunedParameters` - split out of `tuning.ts` so+ * `search.ts` can depend on the tuned-parameter READ path without+ * pulling in `tuneRecall`'s benchmark dependency. `tuning.ts` imports+ * the grid bounds and `tuningPath` back from here for its write side+ * (the module graph stays a DAG: tuning.ts -> tuning-store.ts and+ * tuning.ts -> benchmark.ts -> search.ts -> tuning-store.ts, never back+ * to tuning.ts or benchmark.ts).+ */++import { existsSync, readFileSync, rmSync } from "node:fs";+import { join } from "node:path";++import type { ResolvedSearchConfig, TunedParameters } from "./types.ts";++export const TUNING_SCHEMA_VERSION = "o2b.tuning.v1";++/** Bounded grid axes - loadTunedParameters enforces these on read. */+export const TUNING_POOL_MULTIPLIERS: ReadonlyArray<number> = Object.freeze([3, 4, 5]);+export const TUNING_TRAVERSAL_DEPTHS: ReadonlyArray<number> = Object.freeze([1, 2]);++/**+ * A config with one grid point applied. Always disarms+ * `selfTuningEnabled` so an applied config can never re-apply itself.+ */+export function applyTunedParameters(+ config: ResolvedSearchConfig,+ params: TunedParameters,+): ResolvedSearchConfig {+ return Object.freeze({+ ...config,+ recall: Object.freeze({+ ...config.recall,+ poolMultiplier: params.poolMultiplier,+ maxHops: params.traversalDepth,+ learnedWeightsEnabled: params.learnedWeights,+ selfTuningEnabled: false,+ }),+ });+}++export function tuningPath(vault: string): string {+ return join(vault, "Brain", "search", "tuning.json");+}++/**+ * The persisted tuned parameters, re-validated against the grid+ * bounds. Fail-soft: missing file, torn JSON, or any out-of-bounds+ * value reads as null (search falls back to configured defaults).+ */+export function loadTunedParameters(vault: string): TunedParameters | null {+ const path = tuningPath(vault);+ if (!existsSync(path)) return null;+ try {+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));+ const chosen = (parsed as { chosen?: unknown }).chosen;+ if (chosen === null || typeof chosen !== "object") return null;+ const c = chosen as Record<string, unknown>;+ if (+ typeof c["poolMultiplier"] !== "number" ||+ !TUNING_POOL_MULTIPLIERS.includes(c["poolMultiplier"]) ||+ typeof c["traversalDepth"] !== "number" ||+ !TUNING_TRAVERSAL_DEPTHS.includes(c["traversalDepth"]) ||+ typeof c["learnedWeights"] !== "boolean" ||+ typeof c["expansion"] !== "boolean"+ ) {+ return null;+ }+ return Object.freeze({+ poolMultiplier: c["poolMultiplier"],+ traversalDepth: c["traversalDepth"],+ learnedWeights: c["learnedWeights"],+ expansion: c["expansion"],+ });+ } catch {+ return null;+ }+}++/** Delete the persisted tuning state. Returns true when it existed. */+export function resetTuning(vault: string): boolean {+ const path = tuningPath(vault);+ if (!existsSync(path)) return false;+ rmSync(path);+ return true;+}diff --git a/src/core/search/tuning.ts b/src/core/search/tuning.tsindex 94805943..7e6abee2 100644--- a/src/core/search/tuning.ts+++ b/src/core/search/tuning.ts@@ -19,28 +19,28 @@* is enabled (`search_self_tuning_enabled` /* `OPEN_SECOND_BRAIN_SEARCH_SELF_TUNING`), values re-validated* against the grid bounds on every read, fail-soft to defaults.+ *+ * The persisted read/reset side (`loadTunedParameters`, `resetTuning`)+ * and `applyTunedParameters` live in `tuning-store.ts`, a leaf module:+ * `search()` needs the tuned-parameter READ path but must not pull in+ * this module's `runRecallBenchmark` dependency, which itself calls+ * back into `search()`.*/-import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";-import { dirname, join } from "node:path";+import { mkdirSync, writeFileSync } from "node:fs";+import { dirname } from "node:path";import { createHash } from "node:crypto";import { runRecallBenchmark } from "./benchmark.ts";import type { RecallBenchmarkDataset } from "./benchmark.ts";-import type { ResolvedSearchConfig } from "./types.ts";--export const TUNING_SCHEMA_VERSION = "o2b.tuning.v1";--/** Bounded grid axes - loadTunedParameters enforces these on read. */-export const TUNING_POOL_MULTIPLIERS: ReadonlyArray<number> = Object.freeze([3, 4, 5]);-export const TUNING_TRAVERSAL_DEPTHS: ReadonlyArray<number> = Object.freeze([1, 2]);--export interface TunedParameters {- readonly poolMultiplier: number;- readonly traversalDepth: number;- readonly learnedWeights: boolean;- readonly expansion: boolean;-}+import {+ applyTunedParameters,+ TUNING_POOL_MULTIPLIERS,+ TUNING_SCHEMA_VERSION,+ TUNING_TRAVERSAL_DEPTHS,+ tuningPath,+} from "./tuning-store.ts";+import type { ResolvedSearchConfig, TunedParameters } from "./types.ts";export interface TuningEvaluation {readonly params: TunedParameters;@@ -80,30 +80,6 @@ export function defaultTuningGrid(): TunedParameters[] {return grid;}-/**- * A config with one grid point applied. Always disarms- * `selfTuningEnabled` so an applied config can never re-apply itself.- */-export function applyTunedParameters(- config: ResolvedSearchConfig,- params: TunedParameters,-): ResolvedSearchConfig {- return Object.freeze({- ...config,- recall: Object.freeze({- ...config.recall,- poolMultiplier: params.poolMultiplier,- maxHops: params.traversalDepth,- learnedWeightsEnabled: params.learnedWeights,- selfTuningEnabled: false,- }),- });-}--function tuningPath(vault: string): string {- return join(vault, "Brain", "search", "tuning.json");-}-/*** Grid-evaluate against the benchmark and persist the winner.* Deterministic for a fixed index state and dataset.@@ -165,45 +141,3 @@ export async function tuneRecall(datasetHash,});}--/**- * The persisted tuned parameters, re-validated against the grid- * bounds. Fail-soft: missing file, torn JSON, or any out-of-bounds- * value reads as null (search falls back to configured defaults).- */-export function loadTunedParameters(vault: string): TunedParameters | null {- const path = tuningPath(vault);- if (!existsSync(path)) return null;- try {- const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));- const chosen = (parsed as { chosen?: unknown }).chosen;- if (chosen === null || typeof chosen !== "object") return null;- const c = chosen as Record<string, unknown>;- if (- typeof c["poolMultiplier"] !== "number" ||- !TUNING_POOL_MULTIPLIERS.includes(c["poolMultiplier"]) ||- typeof c["traversalDepth"] !== "number" ||- !TUNING_TRAVERSAL_DEPTHS.includes(c["traversalDepth"]) ||- typeof c["learnedWeights"] !== "boolean" ||- typeof c["expansion"] !== "boolean"- ) {- return null;- }- return Object.freeze({- poolMultiplier: c["poolMultiplier"],- traversalDepth: c["traversalDepth"],- learnedWeights: c["learnedWeights"],- expansion: c["expansion"],- });- } catch {- return null;- }-}--/** Delete the persisted tuning state. Returns true when it existed. */-export function resetTuning(vault: string): boolean {- const path = tuningPath(vault);- if (!existsSync(path)) return false;- rmSync(path);- return true;-}diff --git a/src/core/search/types.ts b/src/core/search/types.tsindex 72323f55..bdd537d8 100644--- a/src/core/search/types.ts+++ b/src/core/search/types.ts@@ -5,9 +5,6 @@*/import type { VaultIgnoreRule } from "../vault-scope/defaults.ts";-import type { EvidencePack } from "./evidence-pack.ts";-import type { SearchSessionFocus } from "./session-focus.ts";-import type { StructuredRecallQueryDocument } from "./structured-query.ts";export type { VaultIgnoreRule };@@ -143,6 +140,23 @@ export interface BrainSearchResult {*/export type QueryIntent = "neutral" | "exact" | "entity" | "broad";+/** One parsed `lex:` lane of a structured recall query document. */+export interface StructuredLexLane {+ readonly include: ReadonlyArray<string>;+ readonly exclude: ReadonlyArray<string>;+}++/**+ * A parsed structured recall query document: explicit intent plus the+ * lex / vec / hyde retrieval lanes. Parsed by `structured-query.ts`.+ */+export interface StructuredRecallQueryDocument {+ readonly intent: QueryIntent | null;+ readonly lex: StructuredLexLane;+ readonly vec: ReadonlyArray<string>;+ readonly hyde: ReadonlyArray<string>;+}+/*** Per-query ranking multipliers emitted by the query plan. Each is a* bounded multiplier applied to the corresponding ranking layer; the@@ -371,6 +385,102 @@ export interface ExpandHitResult {readonly next_cursor: string | null;}+/** Active session-focus steering. Persisted/parsed by `session-focus.ts`. */+export interface SearchSessionFocus {+ readonly query: string | null;+ readonly pathPrefix: string | null;+ readonly expiresAt: number | null;+}++/** One bounded grid point in the self-tuning parameter space (`tuning.ts`). */+export interface TunedParameters {+ readonly poolMultiplier: number;+ readonly traversalDepth: number;+ readonly learnedWeights: boolean;+ readonly expansion: boolean;+}++export interface EvidenceRecord {+ readonly path: string;+ readonly documentId: number;+ readonly chunkId: number;+ /**+ * Read-time line-anchored citation for this chunk, formatted+ * `path:Lstart-Lend` (or `path:Lstart` for a single line) from the chunk's+ * 1-based `startLine`/`endLine`. Resolves by opening the file and slicing+ * the range with {@link extractLineRange}; the stored bytes are never+ * mutated, so the pointer stays valid across idempotent re-mining.+ */+ readonly linePointer: string;+ readonly matchedTerms: ReadonlyArray<string>;+ readonly missingTerms: ReadonlyArray<string>;+ readonly supportCoverage: number;+ readonly terminalState: boolean;+ readonly whyRetrieved: ReadonlyArray<string>;+ readonly droppedCandidateReasons: ReadonlyArray<string>;+}++/**+ * One per-token recall-union record (recall-trust-suite, Feature C): a+ * document fetched specifically because it covers a significant term+ * the ranked result set left uncovered. Union records live in the pack+ * only — the primary `results` contract stays untouched.+ */+export interface EvidenceUnionRecord {+ readonly term: string;+ readonly path: string;+ readonly documentId: number;+ readonly chunkId: number;+}++export type CompletenessVerdict = "complete" | "partial" | "sparse";++/**+ * Search-completeness guard (Feature E): a deterministic verdict over+ * how well the returned results cover the query, plus the+ * false-absence guard — uncovered terms the corpus DOES contain. A+ * summarizer seeing a term in `uncoveredButPresentInCorpus` cannot+ * honestly claim the vault has nothing on it.+ */+export interface CompletenessReport {+ readonly verdict: CompletenessVerdict;+ readonly idfWeightedCoverage: number;+ readonly coveredTerms: ReadonlyArray<string>;+ readonly uncoveredTerms: ReadonlyArray<string>;+ readonly uncoveredButPresentInCorpus: ReadonlyArray<string>;+}++export interface EvidencePack {+ readonly significantTerms: ReadonlyArray<string>;+ readonly matchedTerms: ReadonlyArray<string>;+ readonly missingTerms: ReadonlyArray<string>;+ readonly supportCoverage: number;+ readonly records: ReadonlyArray<EvidenceRecord>;+ readonly droppedCandidates: ReadonlyArray<{+ readonly path: string;+ readonly reason: string;+ }>;+ readonly abstention: string | null;+ /**+ * IDF-weighted support coverage (Feature C): the share of the query's+ * IDF mass the covered terms carry. Present only when the search ran+ * with coverage verification.+ */+ readonly idfWeightedCoverage?: number;+ /** Rare (high-signal) significant terms per the corpus statistics. */+ readonly rareTerms?: ReadonlyArray<string>;+ /** Rare terms no returned record covers — the abstention trigger. */+ readonly uncoveredRareTerms?: ReadonlyArray<string>;+ /** Per-token recall union for uncovered significant terms. */+ readonly unionRecords?: ReadonlyArray<EvidenceUnionRecord>;+ /**+ * Search-completeness guard (Feature E): verdict + false-absence+ * report from the same coverage engine. Present only when the search+ * ran with coverage verification.+ */+ readonly completeness?: CompletenessReport;+}+export interface SearchOptions {readonly query: string;readonly limit?: number;diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.tsindex 7df89100..36170e8f 100644--- a/src/mcp/brain-tools.ts+++ b/src/mcp/brain-tools.ts@@ -36,7 +36,7 @@ import { SYNTHESIS_TOOLS } from "./brain/synthesis-tools.ts";import { GENERATION_TOOLS } from "./brain/generation-tools.ts";import { CALENDAR_TOOLS } from "./brain/calendar-tools.ts";import { MEMORY_BRIDGE_TOOLS } from "./brain/memory-bridge-tools.ts";-import type { ToolDefinition } from "./tools.ts";+import type { ToolDefinition } from "./tool-contract.ts";export { vaultRelativeSafe } from "./brain/shared.ts";diff --git a/src/mcp/brain/admin-tools.ts b/src/mcp/brain/admin-tools.tsindex f7822519..114baef9 100644--- a/src/mcp/brain/admin-tools.ts+++ b/src/mcp/brain/admin-tools.ts@@ -41,7 +41,7 @@ import { dream } from "../../core/brain/dream.ts";import { isoSecond } from "../../core/brain/time.ts";import { normalizeAgentArgument } from "../../core/agent-identity.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";/** Controlled-vocabulary classification over the schema pack's labels. */diff --git a/src/mcp/brain/analytics-tools.ts b/src/mcp/brain/analytics-tools.tsindex bb277e0d..826eef5f 100644--- a/src/mcp/brain/analytics-tools.ts+++ b/src/mcp/brain/analytics-tools.ts@@ -18,7 +18,7 @@ import {} from "../../core/brain/attention-flows.ts";import { normaliseWikilinkTarget } from "../../core/brain/wikilink.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import {coerceIsoTimestampOrDate,diff --git a/src/mcp/brain/brief-tools.ts b/src/mcp/brain/brief-tools.tsindex efb45f89..61c5cd63 100644--- a/src/mcp/brain/brief-tools.ts+++ b/src/mcp/brain/brief-tools.ts@@ -26,7 +26,7 @@ import { buildOperatorSummary } from "../../core/brain/trust/operator-summary.tsimport { isoDate } from "../../core/brain/time.ts";import { captureReportDelta } from "../../core/brain/report-snapshot.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import { coerceIsoDate, coerceFormat } from "../coerce.ts";import {diff --git a/src/mcp/brain/calendar-tools.ts b/src/mcp/brain/calendar-tools.tsindex 57cf163b..5b3db202 100644--- a/src/mcp/brain/calendar-tools.ts+++ b/src/mcp/brain/calendar-tools.ts@@ -22,7 +22,7 @@ import {type AgendaSnapshot,} from "../../core/brain/agenda.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import { coerceStr, coerceStrList } from "../coerce.ts";diff --git a/src/mcp/brain/context-tools.ts b/src/mcp/brain/context-tools.tsindex e16fc138..988eefd1 100644--- a/src/mcp/brain/context-tools.ts+++ b/src/mcp/brain/context-tools.ts@@ -35,7 +35,7 @@ import {type PinnedOperation,} from "../../core/brain/pinned.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { coerceStr, coerceInt } from "../coerce.ts";import { vaultRelativeSafe } from "./shared.ts";diff --git a/src/mcp/brain/derive-tools.ts b/src/mcp/brain/derive-tools.tsindex b67a655e..9418e9db 100644--- a/src/mcp/brain/derive-tools.ts+++ b/src/mcp/brain/derive-tools.ts@@ -15,7 +15,7 @@ import { deriveFact, DeriveFactError } from "../../core/brain/derived-fact.ts";import { loadGuardrailsConfigSafe } from "../../core/brain/policy.ts";import { asProvenanceLevel } from "../../core/brain/provenance/provenance.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { coerceStr, coerceStrList } from "../coerce.ts";import { wrapToolErrors } from "./shared.ts";diff --git a/src/mcp/brain/distill-tools.ts b/src/mcp/brain/distill-tools.tsindex c7f044fe..c61c62c9 100644--- a/src/mcp/brain/distill-tools.ts+++ b/src/mcp/brain/distill-tools.ts@@ -17,7 +17,7 @@ import {import { resolveAgentName } from "../../core/config.ts";import { coerceStr } from "../coerce.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { wrapToolErrors } from "./shared.ts";const TOOL = "brain_distill_source";diff --git a/src/mcp/brain/entity-tools.ts b/src/mcp/brain/entity-tools.tsindex c66c10d7..bad6b73f 100644--- a/src/mcp/brain/entity-tools.ts+++ b/src/mcp/brain/entity-tools.ts@@ -15,7 +15,7 @@ import { validateEntityCategory } from "../../core/brain/entities/canonical.ts";import { switchProfile, listProfiles } from "../../core/brain/portability/profiles.ts";import { defaultConfigPath } from "../../core/config.ts";import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import { coerceStr } from "../coerce.ts";diff --git a/src/mcp/brain/feedback-tools.ts b/src/mcp/brain/feedback-tools.tsindex 374f5b79..b262a547 100644--- a/src/mcp/brain/feedback-tools.ts+++ b/src/mcp/brain/feedback-tools.ts@@ -40,7 +40,7 @@ import { appendLogEvent } from "../../core/brain/log.ts";import { appendBrainNote } from "../../core/brain/note.ts";import { mirrorSignal, resolveSharedNamespace } from "../../core/brain/shared-namespace.ts";import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import {emitObservedUse,isObservedUseVerdict,diff --git a/src/mcp/brain/generation-tools.ts b/src/mcp/brain/generation-tools.tsindex 6a0d1e89..c88ff7e0 100644--- a/src/mcp/brain/generation-tools.ts+++ b/src/mcp/brain/generation-tools.ts@@ -29,7 +29,7 @@ import {import { isCanonicalUtcTimestamp } from "../../core/brain/continuity/store.ts";import type { ContinuitySourceRef } from "../../core/brain/continuity/types.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import { coercePositiveInteger, optionalStringArg, requiredStringArg } from "./shared.ts";diff --git a/src/mcp/brain/health-tools.ts b/src/mcp/brain/health-tools.tsindex 4af27b0b..45814b2c 100644--- a/src/mcp/brain/health-tools.ts+++ b/src/mcp/brain/health-tools.ts@@ -9,7 +9,7 @@import { resolveSearchConfig } from "../../core/search/index.ts";import { collectMaintenanceActions } from "../../core/brain/maintenance/collect.ts";import { runDoctor } from "../../core/brain/doctor.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { coerceBool, coerceFormat } from "../coerce.ts";import { vaultRelativeSafe } from "./shared.ts";diff --git a/src/mcp/brain/hygiene-tools.ts b/src/mcp/brain/hygiene-tools.tsindex 5260a52f..d9fec466 100644--- a/src/mcp/brain/hygiene-tools.ts+++ b/src/mcp/brain/hygiene-tools.ts@@ -33,7 +33,7 @@ import { executeRecompile, planRecompile } from "../../core/brain/recompile.ts";import { coerceBool } from "../coerce.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { enforceCountGuard, readCountGuardArgs, vaultRelativeSafe } from "./shared.ts";function coerceStringArray(args: Record<string, unknown>, key: string): string[] | undefined {diff --git a/src/mcp/brain/ingest-tools.ts b/src/mcp/brain/ingest-tools.tsindex c0080ae0..072cab2d 100644--- a/src/mcp/brain/ingest-tools.ts+++ b/src/mcp/brain/ingest-tools.ts@@ -22,7 +22,7 @@ import {import { resolveAgentName } from "../../core/config.ts";import { coerceBoolOptional, coerceInt, coerceStr } from "../coerce.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { parseExtractionIntakeArgs } from "./intake-args.ts";import { enforceCountGuard, readCountGuardArgs, wrapToolErrors } from "./shared.ts";diff --git a/src/mcp/brain/knowledge-tools.ts b/src/mcp/brain/knowledge-tools.tsindex 01eebff1..46967cf3 100644--- a/src/mcp/brain/knowledge-tools.ts+++ b/src/mcp/brain/knowledge-tools.ts@@ -42,7 +42,7 @@ import { detectAgentCollisions } from "../../core/brain/truth/collision.ts";import { computeTruthStateWithConflicts } from "../../core/brain/truth/conflicts.ts";import { appendClaimEvent, readClaimEvents } from "../../core/brain/truth/store.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import { coerceStr, coerceBool } from "../coerce.ts";import { coercePositiveInteger } from "./shared.ts";diff --git a/src/mcp/brain/landscape-tools.ts b/src/mcp/brain/landscape-tools.tsindex 5043ec68..9dddaee9 100644--- a/src/mcp/brain/landscape-tools.ts+++ b/src/mcp/brain/landscape-tools.ts@@ -7,7 +7,7 @@*/import { buildMcpLandscape } from "../../core/graph/mcp-config.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";async function toolMcpLandscape(ctx: ServerContext): Promise<Record<string, unknown>> {const landscape = buildMcpLandscape(ctx.vault);diff --git a/src/mcp/brain/memory-bridge-tools.ts b/src/mcp/brain/memory-bridge-tools.tsindex 7973c340..3027fa41 100644--- a/src/mcp/brain/memory-bridge-tools.ts+++ b/src/mcp/brain/memory-bridge-tools.ts@@ -25,7 +25,7 @@ import {} from "../../core/brain/host-memory-write.ts";import type { ContinuityRecord } from "../../core/brain/continuity/types.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { coerceStr } from "../coerce.ts";function coerceMetadata(value: unknown): Readonly<Record<string, unknown>> | undefined {diff --git a/src/mcp/brain/ner-tools.ts b/src/mcp/brain/ner-tools.tsindex 5edc2ef5..23de61a0 100644--- a/src/mcp/brain/ner-tools.ts+++ b/src/mcp/brain/ner-tools.ts@@ -16,7 +16,7 @@import { intakeExtraction, IntakeValidationError } from "../../core/brain/intake/extract-intake.ts";import { resolveAgentName } from "../../core/config.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { parseExtractionIntakeArgs } from "./intake-args.ts";import { wrapToolErrors } from "./shared.ts";diff --git a/src/mcp/brain/notes-tools.ts b/src/mcp/brain/notes-tools.tsindex 34bfffd1..244f1b48 100644--- a/src/mcp/brain/notes-tools.ts+++ b/src/mcp/brain/notes-tools.ts@@ -12,7 +12,7 @@import type { FrontmatterMap, FrontmatterValue } from "../../core/types.ts";import { createNote, CreateNoteError } from "../../core/brain/notes/create-note.ts";import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { coerceStr } from "../coerce.ts";/**diff --git a/src/mcp/brain/pack-tools.ts b/src/mcp/brain/pack-tools.tsindex 83e0cfb4..fde66a23 100644--- a/src/mcp/brain/pack-tools.ts+++ b/src/mcp/brain/pack-tools.ts@@ -41,7 +41,7 @@ import { extractPreCompactRecords } from "../../core/brain/pre-compact-extract.timport { EventTraceSelectorError, resolveLogEventTraces } from "../../core/brain/event-trace.ts";import { BRAIN_LOG_EVENT_KIND_SET, type BrainLogEventKind } from "../../core/brain/types.ts";import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import { coerceStr, coerceStrList, coerceBool } from "../coerce.ts";import {diff --git a/src/mcp/brain/procedure-tools.ts b/src/mcp/brain/procedure-tools.tsindex e64a81c1..8cbd4aa3 100644--- a/src/mcp/brain/procedure-tools.ts+++ b/src/mcp/brain/procedure-tools.ts@@ -30,7 +30,7 @@ import {purgeRecurrenceSource,} from "../../core/brain/recurrence.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { coerceStrList } from "../coerce.ts";import { coercePositiveInteger, optionalStringArg, requiredStringArg } from "./shared.ts";diff --git a/src/mcp/brain/query-tools.ts b/src/mcp/brain/query-tools.tsindex cfe0c4a7..77b12ae1 100644--- a/src/mcp/brain/query-tools.ts+++ b/src/mcp/brain/query-tools.ts@@ -27,7 +27,7 @@ import {} from "../../core/brain/types.ts";import type { BrainLogEntry } from "../../core/brain/log.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import {coerceStr,diff --git a/src/mcp/brain/recall-tools.ts b/src/mcp/brain/recall-tools.tsindex a79e8964..47107390 100644--- a/src/mcp/brain/recall-tools.ts+++ b/src/mcp/brain/recall-tools.ts@@ -9,7 +9,8 @@import { resolveSearchConfig } from "../../core/search/index.ts";import { appendMetric } from "../../core/brain/metrics.ts";import { parseRecallBenchmarkDataset, runRecallBenchmark } from "../../core/search/benchmark.ts";-import { loadTunedParameters, resetTuning, tuneRecall } from "../../core/search/tuning.ts";+import { tuneRecall } from "../../core/search/tuning.ts";+import { loadTunedParameters, resetTuning } from "../../core/search/tuning-store.ts";import { listGateTelemetry, summarizeGateTelemetry } from "../../core/brain/gate-telemetry.ts";import { computeMemoryCostMeter } from "../../core/brain/memory-cost-meter.ts";import { observedReuseRates } from "../../core/brain/observed-use.ts";@@ -58,7 +59,7 @@ import {import { aggregateQueryDemand, serializeQueryDemandReport } from "../../core/brain/query-demand.ts";import { isoSecond } from "../../core/brain/time.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import { coercePositiveInteger, optionalStringArg, requiredStringArg } from "./shared.ts";diff --git a/src/mcp/brain/research-tools.ts b/src/mcp/brain/research-tools.tsindex 17b0dc17..e050753b 100644--- a/src/mcp/brain/research-tools.ts+++ b/src/mcp/brain/research-tools.ts@@ -15,7 +15,7 @@ import {} from "../../core/brain/research/research.ts";import { resolveAgentName } from "../../core/config.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { coerceStr } from "../coerce.ts";import { isRecord, requiredString } from "./intake-args.ts";import { wrapToolErrors } from "./shared.ts";diff --git a/src/mcp/brain/review-tools.ts b/src/mcp/brain/review-tools.tsindex 8a870893..7c6d4ca1 100644--- a/src/mcp/brain/review-tools.ts+++ b/src/mcp/brain/review-tools.ts@@ -13,7 +13,7 @@ import { loadTemporalConfigSafe } from "../../core/brain/policy.ts";import { buildIntentReview } from "../../core/brain/intent-review.ts";import { buildRetentionReview } from "../../core/brain/retention.ts";import { buildReviewCandidates } from "../../core/brain/review-candidates.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { coerceIsoDate } from "../coerce.ts";async function toolBrainIntentReview(diff --git a/src/mcp/brain/shared.ts b/src/mcp/brain/shared.tsindex c028ec27..0c651c30 100644--- a/src/mcp/brain/shared.ts+++ b/src/mcp/brain/shared.ts@@ -10,7 +10,7 @@ import { type RecallTelemetryOptions } from "../../core/brain/recall-telemetry.timport { isoSecond } from "../../core/brain/time.ts";import { formatLocalTimestamp } from "../../core/brain/present-time.ts";import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext } from "../tools.ts";+import type { ServerContext } from "../tool-contract.ts";import { coerceBool } from "../coerce.ts";import {CountGuardError,diff --git a/src/mcp/brain/synthesis-tools.ts b/src/mcp/brain/synthesis-tools.tsindex f1410dbb..a3eb823b 100644--- a/src/mcp/brain/synthesis-tools.ts+++ b/src/mcp/brain/synthesis-tools.ts@@ -30,7 +30,7 @@ import {} from "../../core/brain/idea-lineage.ts";import { decomposeNoteHistory } from "../../core/brain/note-history.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";const SUMMARY_TOOL = "brain_session_summary";diff --git a/src/mcp/brain/workspace-tools.ts b/src/mcp/brain/workspace-tools.tsindex 1f363b64..0de8b44c 100644--- a/src/mcp/brain/workspace-tools.ts+++ b/src/mcp/brain/workspace-tools.ts@@ -17,7 +17,7 @@ import {showIntention,} from "../../core/brain/intentions.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tools.ts";+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import { coerceStr } from "../coerce.ts";diff --git a/src/mcp/capabilities.ts b/src/mcp/capabilities.tsindex 8925adbb..b044ff1e 100644--- a/src/mcp/capabilities.ts+++ b/src/mcp/capabilities.ts@@ -1,4 +1,9 @@-import type { ToolDefinition, ToolScope } from "./tools.ts";+import type {+ ToolCapabilityEntry,+ ToolCapabilityReport,+ ToolDefinition,+ ToolScope,+} from "./tool-contract.ts";export interface RuntimeCapabilityWindow {readonly allowedTools?: ReadonlyArray<string>;@@ -12,20 +17,6 @@ export interface RuntimeCapabilityContext {readonly window?: RuntimeCapabilityWindow;}-export interface ToolCapabilityEntry {- readonly name: string;- readonly reason: string;-}--export interface ToolCapabilityReport {- readonly scope: ToolScope;- readonly server_name: string;- readonly static_tool_count: number;- readonly available_tool_count: number;- readonly available: ToolCapabilityEntry[];- readonly withheld: ToolCapabilityEntry[];-}-export interface ToolCapabilityEvaluation {readonly tools: ToolDefinition[];readonly report: ToolCapabilityReport;diff --git a/src/mcp/hydrate-tool.ts b/src/mcp/hydrate-tool.tsindex bdc1861d..291bc8d3 100644--- a/src/mcp/hydrate-tool.ts+++ b/src/mcp/hydrate-tool.ts@@ -18,7 +18,7 @@import { toolDescriptors } from "../core/surface/descriptor.ts";import { coerceStrList } from "./coerce.ts";-import type { ToolDefinition } from "./tools.ts";+import type { ToolDefinition } from "./tool-contract.ts";export const TOOL_HYDRATE_NAME = "tool_hydrate";diff --git a/src/mcp/index.ts b/src/mcp/index.tsindex 3f7b6b05..29f803a1 100644--- a/src/mcp/index.ts+++ b/src/mcp/index.ts@@ -18,7 +18,8 @@ export {export { MCPServer, errorResponse, type JsonRpcRequest, type JsonRpcResponse } from "./server.ts";export { serveHttp, startHttp, type ServeHttpOptions, type HttpServerHandle } from "./http.ts";export { serveStdio, serveStdioFromString } from "./stdio.ts";-export { buildToolTable, PLACEHOLDER_AGENT_VALUES, type ToolDefinition } from "./tools.ts";+export { buildToolTable, PLACEHOLDER_AGENT_VALUES } from "./tools.ts";+export type { ToolDefinition } from "./tool-contract.ts";export { evaluateToolCapabilities, type RuntimeCapabilityWindow } from "./capabilities.ts";export { buildInstructions } from "./instructions.ts";export { slugify } from "../core/vault.ts";diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.tsindex 24bde871..02940767 100644--- a/src/mcp/instructions.ts+++ b/src/mcp/instructions.ts@@ -8,7 +8,7 @@* the deferred full server.*/-import type { ToolScope } from "./tools.ts";+import type { ToolScope } from "./tool-contract.ts";export interface BuildInstructionsOpts {/** Resolved agent identity (e.g. "hermes-vps-agent"). */diff --git a/src/mcp/profiles.ts b/src/mcp/profiles.tsindex 49e27ec2..fc2c72d4 100644--- a/src/mcp/profiles.ts+++ b/src/mcp/profiles.ts@@ -17,7 +17,7 @@*/import type { RuntimeCapabilityWindow } from "./capabilities.ts";-import type { ToolScope } from "./tools.ts";+import type { ToolScope } from "./tool-contract.ts";export interface ToolSurfaceProfile {readonly name: string;diff --git a/src/mcp/registry-guard.ts b/src/mcp/registry-guard.tsindex 8e6ccade..61b7f37d 100644--- a/src/mcp/registry-guard.ts+++ b/src/mcp/registry-guard.ts@@ -16,7 +16,7 @@* Test-time module: nothing here runs on the MCP request path.*/-import type { ToolDefinition } from "./tools.ts";+import type { ToolDefinition } from "./tool-contract.ts";export const TOOL_DESCRIPTION_MAX = 300;export const PROPERTY_DESCRIPTION_MAX = 160;diff --git a/src/mcp/schema-tools.ts b/src/mcp/schema-tools.tsindex 5f7f6984..d42f7a18 100644--- a/src/mcp/schema-tools.ts+++ b/src/mcp/schema-tools.ts@@ -14,7 +14,7 @@ import { resolveSearchConfig } from "../core/search/index.ts";import { INVALID_PARAMS, MCPError } from "./protocol.ts";import { coerceStr } from "./coerce.ts";import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";-import type { ServerContext, ToolDefinition } from "./tools.ts";+import type { ServerContext, ToolDefinition } from "./tool-contract.ts";// Read-side handlers behind the consolidated `schema_inspect` views.// The per-view alias tools were removed in 1.0.0 (tombstones indiff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.tsindex 6b5ca0a0..f729ed19 100644--- a/src/mcp/search-tools.ts+++ b/src/mcp/search-tools.ts@@ -35,7 +35,7 @@ import {} from "../core/config.ts";import { assessRecallAdequacy } from "../core/brain/recall-adequacy.ts";import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";-import type { ServerContext, ToolDefinition } from "./tools.ts";+import type { ServerContext, ToolDefinition } from "./tool-contract.ts";import { coerceBoolOptional, coerceStr, coerceStringOptional } from "./coerce.ts";import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";import { deriveRecallHint } from "../core/search/recall-hint.ts";diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex e0298eb8..6df27a4f 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -19,21 +19,17 @@ import {SERVER_VERSION,} from "./protocol.ts";import { listResources, listResourceTemplates, readResource } from "./resources.ts";-import {- buildToolTable,- findTool,- type ServerContext,- type ToolDefinition,- type ToolScope,-} from "./tools.ts";+import { buildToolTable, findTool } from "./tools.ts";+import type {+ ServerContext,+ ToolCapabilityReport,+ ToolDefinition,+ ToolScope,+} from "./tool-contract.ts";import { assertOutputContract } from "./output-contract.ts";import { ArtifactStore } from "./artifact-store.ts";import { applyPreviewBudget } from "./preview-budget.ts";-import {- evaluateToolCapabilities,- type RuntimeCapabilityWindow,- type ToolCapabilityReport,-} from "./capabilities.ts";+import { evaluateToolCapabilities, type RuntimeCapabilityWindow } from "./capabilities.ts";/** TTL after which a prior process's artifact run directory is pruned. */const ARTIFACT_TTL_MS = 24 * 60 * 60 * 1000;diff --git a/src/mcp/skill-tools.ts b/src/mcp/skill-tools.tsindex bfd3389e..8e812113 100644--- a/src/mcp/skill-tools.ts+++ b/src/mcp/skill-tools.ts@@ -20,7 +20,7 @@ import { discoverSkills, readSkillFile, skillRoots, SkillError } from "../core/simport { 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 "./tools.ts";+import type { ServerContext, ToolDefinition } from "./tool-contract.ts";function rootsFor(ctx: ServerContext): string[] {const skillsDir = resolveSkillsDir(ctx.configPath ?? undefined);diff --git a/src/mcp/tool-contract.ts b/src/mcp/tool-contract.tsnew file mode 100644index 00000000..1bc56f0d--- /dev/null+++ b/src/mcp/tool-contract.ts@@ -0,0 +1,71 @@+/**+ * Shared MCP tool contract types. Extracted from `./tools.ts` so that+ * leaf tool modules (and `./capabilities.ts`) depend only on this pure+ * leaf for the handler / definition shape, instead of importing back+ * from the `tools.ts` aggregator that assembles them — which formed one+ * large import cycle spanning the whole `src/mcp` tool surface.+ *+ * `ToolScope` and the capability-report shapes live here rather than in+ * `./capabilities.ts` because `ServerContext.capabilityReport` references+ * `ToolCapabilityReport`, and `./capabilities.ts` in turn needs+ * `ToolDefinition`; keeping the report types below both preserves a+ * single downward dependency direction.+ */++import type { OutputSchema } from "./output-contract.ts";+import type { ArtifactStore } from "./artifact-store.ts";++export type ToolScope = "full" | "writer" | "catalog";++export interface ToolCapabilityEntry {+ readonly name: string;+ readonly reason: string;+}++export interface ToolCapabilityReport {+ readonly scope: ToolScope;+ readonly server_name: string;+ readonly static_tool_count: number;+ readonly available_tool_count: number;+ readonly available: ToolCapabilityEntry[];+ readonly withheld: ToolCapabilityEntry[];+}++export interface ServerContext {+ readonly vault: string;+ readonly configPath: string | null;+ readonly repoRoot: string | null;+ readonly capabilityReport?: ToolCapabilityReport;+ /**+ * Per-process preview-artifact store (v0.18.0). Present on the live MCP+ * server context; `brain_artifact_get` reads parked tool-result payloads+ * back through it. Optional so manually-built contexts stay valid.+ */+ readonly artifactStore?: ArtifactStore;+}++export interface ToolDefinition {+ readonly name: string;+ readonly description: string;+ readonly inputSchema: Record<string, unknown>;+ readonly outputSchema?: OutputSchema;+ /**+ * Optional MCP preview budget in characters (v0.18.0). When set and+ * the serialized result exceeds it, the JSON-RPC `tools/call` path+ * parks the full payload in the artifact store and returns a bounded+ * preview envelope in `content[0].text` instead, leaving+ * `structuredContent` intact. A tool with no budget is never truncated+ * - opt-in only. The CLI bridge ignores the budget entirely.+ */+ readonly previewBudget?: number;+ /**+ * When true the tool stays callable via `tools/call` but is omitted+ * from `tools/list` (token-diet): deprecated aliases keep working+ * for old clients without re-paying their schema in every list.+ */+ readonly hidden?: boolean;+ readonly handler: (+ ctx: ServerContext,+ args: Record<string, unknown>,+ ) => Promise<unknown> | unknown;+}diff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex 7afef3b6..124c4fa8 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -40,49 +40,14 @@ import { listVaultPages } from "../core/vault.ts";import { INVALID_PARAMS, METHOD_NOT_FOUND, MCPError } from "./protocol.ts";import { coerceStr, coerceInt } from "./coerce.ts";import type { OutputSchema } from "./output-contract.ts";-import type { ArtifactStore } from "./artifact-store.ts";import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";-import type { ToolCapabilityReport } from "./capabilities.ts";import { CAPABILITY_DIAGNOSTIC_TOOL } from "./capabilities.ts";--export interface ServerContext {- readonly vault: string;- readonly configPath: string | null;- readonly repoRoot: string | null;- readonly capabilityReport?: ToolCapabilityReport;- /**- * Per-process preview-artifact store (v0.18.0). Present on the live MCP- * server context; `brain_artifact_get` reads parked tool-result payloads- * back through it. Optional so manually-built contexts stay valid.- */- readonly artifactStore?: ArtifactStore;-}--export interface ToolDefinition {- readonly name: string;- readonly description: string;- readonly inputSchema: Record<string, unknown>;- readonly outputSchema?: OutputSchema;- /**- * Optional MCP preview budget in characters (v0.18.0). When set and- * the serialized result exceeds it, the JSON-RPC `tools/call` path- * parks the full payload in the artifact store and returns a bounded- * preview envelope in `content[0].text` instead, leaving- * `structuredContent` intact. A tool with no budget is never truncated- * - opt-in only. The CLI bridge ignores the budget entirely.- */- readonly previewBudget?: number;- /**- * When true the tool stays callable via `tools/call` but is omitted- * from `tools/list` (token-diet): deprecated aliases keep working- * for old clients without re-paying their schema in every list.- */- readonly hidden?: boolean;- readonly handler: (- ctx: ServerContext,- args: Record<string, unknown>,- ) => Promise<unknown> | unknown;-}+import type {+ ServerContext,+ ToolCapabilityReport,+ ToolDefinition,+ ToolScope,+} from "./tool-contract.ts";// PLACEHOLDER_AGENT_VALUES + normalizeAgentArgument live in// `src/core/agent-identity.ts` so the OpenClaw native plugin can import@@ -295,8 +260,6 @@ const CAPABILITIES_OUTPUT_SCHEMA: OutputSchema = {},};-export type ToolScope = "full" | "writer" | "catalog";-/*** Tombstones for the deprecated aliases removed in 1.0.0 (epic* t_a77ade0a). The token-diet pass (t_3920db77) consolidated these 18diff --git a/src/mcp/watchdog-tools.ts b/src/mcp/watchdog-tools.tsindex 4f936f68..a4e238c2 100644--- a/src/mcp/watchdog-tools.ts+++ b/src/mcp/watchdog-tools.ts@@ -1,6 +1,6 @@import { runBrainWatchdog } from "../core/brain/watchdog.ts";import { coerceBool, coerceInt, coerceStr } from "./coerce.ts";-import type { ToolDefinition } from "./tools.ts";+import type { ToolDefinition } from "./tool-contract.ts";export const WATCHDOG_TOOLS: ReadonlyArray<ToolDefinition> = [{diff --git a/tests/core/brain/entities.semantic-dedup.test.ts b/tests/core/brain/entities.semantic-dedup.test.tsindex 4e293f95..1c3bc939 100644--- a/tests/core/brain/entities.semantic-dedup.test.ts+++ b/tests/core/brain/entities.semantic-dedup.test.ts@@ -25,7 +25,7 @@ import {deriveIdentityType,ENTITY_DEDUP_EMBEDDING_THRESHOLD,} from "../../../src/core/brain/entities/semantic-dedup.ts";-import type { EmbeddingProvider } from "../../../src/core/search/embeddings/provider.ts";+import type { EmbeddingProvider } from "../../../src/core/search/embeddings/contract.ts";let vault: string;let configHome: string;diff --git a/tests/core/brain/hygiene-dedup.test.ts b/tests/core/brain/hygiene-dedup.test.tsindex 72b56de4..8398e86a 100644--- a/tests/core/brain/hygiene-dedup.test.ts+++ b/tests/core/brain/hygiene-dedup.test.ts@@ -15,7 +15,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { join } from "node:path";import { tmpdir } from "node:os";-import type { EmbeddingProvider } from "../../../src/core/search/embeddings/provider.ts";+import type { EmbeddingProvider } from "../../../src/core/search/embeddings/contract.ts";import { detectSemanticDedup } from "../../../src/core/brain/hygiene/detectors/dedup.ts";let vault: string;diff --git a/tests/core/brain/owner-scoped-facts.test.ts b/tests/core/brain/owner-scoped-facts.test.tsindex 31e6b494..9e77094a 100644--- a/tests/core/brain/owner-scoped-facts.test.ts+++ b/tests/core/brain/owner-scoped-facts.test.ts@@ -20,7 +20,7 @@ import {preferenceOwner,} from "../../../src/core/brain/owner-scoped-facts.ts";import { QUERY_TOOLS } from "../../../src/mcp/brain/query-tools.ts";-import type { ServerContext } from "../../../src/mcp/tools.ts";+import type { ServerContext } from "../../../src/mcp/tool-contract.ts";let vault: string;let configHome: string;diff --git a/tests/core/brain/shared-namespace.test.ts b/tests/core/brain/shared-namespace.test.tsindex fe2b16f2..d1b55d3f 100644--- a/tests/core/brain/shared-namespace.test.ts+++ b/tests/core/brain/shared-namespace.test.ts@@ -17,7 +17,8 @@ import {import { appendBrainNote } from "../../../src/core/brain/note.ts";import { parseSignal } from "../../../src/core/brain/signal.ts";import { parseLogDay } from "../../../src/core/brain/log.ts";-import { buildToolTable, findTool, type ServerContext } from "../../../src/mcp/tools.ts";+import { buildToolTable, findTool } from "../../../src/mcp/tools.ts";+import type { ServerContext } from "../../../src/mcp/tool-contract.ts";let tmp: string;let vault: string;diff --git a/tests/core/brain/trust/compute-trust-verdict.test.ts b/tests/core/brain/trust/compute-trust-verdict.test.tsindex 99d9fd59..281106e0 100644--- a/tests/core/brain/trust/compute-trust-verdict.test.ts+++ b/tests/core/brain/trust/compute-trust-verdict.test.ts@@ -1,7 +1,7 @@import { describe, expect, test } from "bun:test";-import type { DoctorIssue } from "../../../../src/core/brain/doctor.ts";import type { DreamWarning } from "../../../../src/core/brain/dream.ts";+import type { DoctorIssue } from "../../../../src/core/brain/types.ts";import { computeTrustVerdict } from "../../../../src/core/brain/trust/compute-trust-verdict.ts";import type { VerificationDeltaSummaryCounts } from "../../../../src/core/brain/trust/compute-verification-delta.ts";diff --git a/tests/core/search/card-snippet.test.ts b/tests/core/search/card-snippet.test.tsindex 83aca10f..7008cea3 100644--- a/tests/core/search/card-snippet.test.ts+++ b/tests/core/search/card-snippet.test.ts@@ -8,7 +8,7 @@import { describe, expect, test } from "bun:test";-import { cardSnippet } from "../../../src/core/search/search.ts";+import { cardSnippet } from "../../../src/core/search/cards.ts";const CARD_SNIPPET_CHARS = 240;const REPLACEMENT_CHAR = "�";diff --git a/tests/core/search/coverage-targeted-recall.test.ts b/tests/core/search/coverage-targeted-recall.test.tsindex 4b16ae01..52d2c042 100644--- a/tests/core/search/coverage-targeted-recall.test.ts+++ b/tests/core/search/coverage-targeted-recall.test.ts@@ -15,7 +15,7 @@ import { buildCoverageReport, planTargetedRetry } from "../../../src/core/searchimport { indexVault } from "../../../src/core/search/indexer.ts";import { search } from "../../../src/core/search/search.ts";import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";-import type { StructuredRecallQueryDocument } from "../../../src/core/search/structured-query.ts";+import type { StructuredRecallQueryDocument } from "../../../src/core/search/types.ts";describe("planTargetedRetry (pure decision)", () => {const report = (diff --git a/tests/core/search/profiles.test.ts b/tests/core/search/profiles.test.tsindex 13379300..4fb56401 100644--- a/tests/core/search/profiles.test.ts+++ b/tests/core/search/profiles.test.ts@@ -16,7 +16,7 @@ import {import {TUNING_POOL_MULTIPLIERS,TUNING_TRAVERSAL_DEPTHS,-} from "../../../src/core/search/tuning.ts";+} from "../../../src/core/search/tuning-store.ts";import { SearchError } from "../../../src/core/search/types.ts";test("the three profiles resolve to distinct knob tuples", () => {diff --git a/tests/core/search/recall-profile.integration.test.ts b/tests/core/search/recall-profile.integration.test.tsindex 8452d3a3..cea14948 100644--- a/tests/core/search/recall-profile.integration.test.ts+++ b/tests/core/search/recall-profile.integration.test.ts@@ -18,7 +18,7 @@ import { join } from "node:path";import { indexVault } from "../../../src/core/search/indexer.ts";import { search } from "../../../src/core/search/search.ts";import { SearchError } from "../../../src/core/search/types.ts";-import { TUNING_SCHEMA_VERSION } from "../../../src/core/search/tuning.ts";+import { TUNING_SCHEMA_VERSION } from "../../../src/core/search/tuning-store.ts";import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";let vault: string;diff --git a/tests/core/search/rerank.test.ts b/tests/core/search/rerank.test.tsindex ffa8c5b4..e3ed2e06 100644--- a/tests/core/search/rerank.test.ts+++ b/tests/core/search/rerank.test.ts@@ -17,7 +17,7 @@ import {applyCrossEncoderRerank,type RerankTelemetryEvent,} from "../../../src/core/search/rerank/index.ts";-import type { RerankProvider } from "../../../src/core/search/rerank/provider.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";diff --git a/tests/core/search/tuning.test.ts b/tests/core/search/tuning.test.tsindex 576f99e1..b1db8f5d 100644--- a/tests/core/search/tuning.test.ts+++ b/tests/core/search/tuning.test.ts@@ -13,13 +13,12 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSyncimport { tmpdir } from "node:os";import { join } from "node:path";+import { defaultTuningGrid, tuneRecall } from "../../../src/core/search/tuning.ts";import {applyTunedParameters,- defaultTuningGrid,loadTunedParameters,resetTuning,- tuneRecall,-} from "../../../src/core/search/tuning.ts";+} from "../../../src/core/search/tuning-store.ts";import { parseRecallBenchmarkDataset } from "../../../src/core/search/benchmark.ts";import { indexVault } from "../../../src/core/search/indexer.ts";import { search } from "../../../src/core/search/search.ts";diff --git a/tests/helpers/mock-embedding.ts b/tests/helpers/mock-embedding.tsindex 4cb1eb95..d21918a2 100644--- a/tests/helpers/mock-embedding.ts+++ b/tests/helpers/mock-embedding.ts@@ -10,7 +10,7 @@import { createHash } from "node:crypto";-import type { EmbeddingProvider } from "../../src/core/search/embeddings/provider.ts";+import type { EmbeddingProvider } from "../../src/core/search/embeddings/contract.ts";export class MockEmbeddingProvider implements EmbeddingProvider {readonly name = "mock";diff --git a/tests/mcp/brain-calendar-tools.test.ts b/tests/mcp/brain-calendar-tools.test.tsindex c9143a53..3d9b2f2c 100644--- a/tests/mcp/brain-calendar-tools.test.ts+++ b/tests/mcp/brain-calendar-tools.test.ts@@ -3,7 +3,8 @@ import { mkdirSync, mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let tmp: string;let ctx: ServerContext;diff --git a/tests/mcp/brain-create-note.test.ts b/tests/mcp/brain-create-note.test.tsindex 5d4329fc..a7203bf9 100644--- a/tests/mcp/brain-create-note.test.ts+++ b/tests/mcp/brain-create-note.test.ts@@ -15,7 +15,7 @@ import { bootstrapBrain } from "../../src/core/brain/init.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";import { NOTES_TOOLS } from "../../src/mcp/brain/notes-tools.ts";import { MCPError } from "../../src/mcp/protocol.ts";-import type { ServerContext } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let vault: string;let configHome: string;diff --git a/tests/mcp/brain-file-context.test.ts b/tests/mcp/brain-file-context.test.tsindex 72731d42..5ae2499a 100644--- a/tests/mcp/brain-file-context.test.ts+++ b/tests/mcp/brain-file-context.test.ts@@ -16,7 +16,7 @@ import { indexVault } from "../../src/core/search/indexer.ts";import { resolveSearchConfig } from "../../src/core/search/index.ts";import { SEARCH_TOOLS } from "../../src/mcp/search-tools.ts";import { MCPError } from "../../src/mcp/protocol.ts";-import type { ServerContext } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let vault: string;let configHome: string;diff --git a/tests/mcp/brain-intention-tool.test.ts b/tests/mcp/brain-intention-tool.test.tsindex 472e32c6..28c2867f 100644--- a/tests/mcp/brain-intention-tool.test.ts+++ b/tests/mcp/brain-intention-tool.test.ts@@ -3,7 +3,8 @@ import { mkdirSync, mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let tmp: string;let ctx: ServerContext;diff --git a/tests/mcp/brain-query-telemetry.test.ts b/tests/mcp/brain-query-telemetry.test.tsindex 5313cf80..0649117d 100644--- a/tests/mcp/brain-query-telemetry.test.ts+++ b/tests/mcp/brain-query-telemetry.test.ts@@ -11,7 +11,8 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { listRecallTelemetry } from "../../src/core/brain/recall-telemetry.ts";-import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let tmp: string;let vault: string;diff --git a/tests/mcp/brain-trigger-tool.test.ts b/tests/mcp/brain-trigger-tool.test.tsindex 591af402..528d190c 100644--- a/tests/mcp/brain-trigger-tool.test.ts+++ b/tests/mcp/brain-trigger-tool.test.ts@@ -10,7 +10,8 @@ import { join } from "node:path";import { createTriggers } from "../../src/core/brain/triggers/store.ts";import type { InsightCandidate } from "../../src/core/brain/triggers/types.ts";-import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let tmp: string;let vault: string;diff --git a/tests/mcp/brain-write-session.test.ts b/tests/mcp/brain-write-session.test.tsindex c5bc2cd0..28590f6e 100644--- a/tests/mcp/brain-write-session.test.ts+++ b/tests/mcp/brain-write-session.test.ts@@ -9,7 +9,8 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "nodimport { tmpdir } from "node:os";import { join } from "node:path";-import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let tmp: string;let vault: string;diff --git a/tests/mcp/catalog-scope.test.ts b/tests/mcp/catalog-scope.test.tsindex 6d54d47c..5bd903c1 100644--- a/tests/mcp/catalog-scope.test.ts+++ b/tests/mcp/catalog-scope.test.ts@@ -3,7 +3,8 @@ import { mkdtempSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";import { MCPServer } from "../../src/mcp/server.ts";function ctx(): ServerContext {diff --git a/tests/mcp/consolidated-tools.test.ts b/tests/mcp/consolidated-tools.test.tsindex bc125c08..bc13b1ad 100644--- a/tests/mcp/consolidated-tools.test.ts+++ b/tests/mcp/consolidated-tools.test.ts@@ -15,7 +15,8 @@ import { join } from "node:path";import { bootstrapBrain } from "../../src/core/brain/init.ts";import { writePreference } from "../../src/core/brain/preference.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";-import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let tmp: string;let vault: string;diff --git a/tests/mcp/deep-synthesis-tool.test.ts b/tests/mcp/deep-synthesis-tool.test.tsindex 1e0834a3..60717977 100644--- a/tests/mcp/deep-synthesis-tool.test.ts+++ b/tests/mcp/deep-synthesis-tool.test.ts@@ -10,7 +10,8 @@ import { join } from "node:path";import { indexVault } from "../../src/core/search/indexer.ts";import { resolveSearchConfig } from "../../src/core/search/index.ts";import { listTriggers } from "../../src/core/brain/triggers/store.ts";-import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";import { writeMd } from "../helpers/search-fixtures.ts";let tmp: string;diff --git a/tests/mcp/derive-tool.test.ts b/tests/mcp/derive-tool.test.tsindex ea9af5bf..e7cbe7ae 100644--- a/tests/mcp/derive-tool.test.ts+++ b/tests/mcp/derive-tool.test.ts@@ -15,7 +15,7 @@ import { brainConfigPath, preferencePath } from "../../src/core/brain/paths.ts";import { writePreference, parsePreference } from "../../src/core/brain/preference.ts";import { DERIVE_TOOLS } from "../../src/mcp/brain/derive-tools.ts";import { MCPError } from "../../src/mcp/protocol.ts";-import type { ServerContext } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let vault: string;let configHome: string;diff --git a/tests/mcp/distill-tool.test.ts b/tests/mcp/distill-tool.test.tsindex 599f84bf..dd18a214 100644--- a/tests/mcp/distill-tool.test.ts+++ b/tests/mcp/distill-tool.test.ts@@ -13,7 +13,7 @@ import { bootstrapBrain } from "../../src/core/brain/init.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";import { DISTILL_TOOLS } from "../../src/mcp/brain/distill-tools.ts";import { MCPError } from "../../src/mcp/protocol.ts";-import type { ServerContext } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let vault: string;let configHome: string;diff --git a/tests/mcp/idea-discovery-tool.test.ts b/tests/mcp/idea-discovery-tool.test.tsindex 471658fd..c46d09da 100644--- a/tests/mcp/idea-discovery-tool.test.ts+++ b/tests/mcp/idea-discovery-tool.test.ts@@ -8,7 +8,8 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { listTriggers } from "../../src/core/brain/triggers/store.ts";-import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let tmp: string;let vault: string;diff --git a/tests/mcp/ingest-tool.test.ts b/tests/mcp/ingest-tool.test.tsindex 793ac6ec..f937bb58 100644--- a/tests/mcp/ingest-tool.test.ts+++ b/tests/mcp/ingest-tool.test.ts@@ -16,7 +16,7 @@ import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";import { listEntities } from "../../src/core/brain/entities/registry.ts";import { INGEST_TOOLS } from "../../src/mcp/brain/ingest-tools.ts";import { MCPError } from "../../src/mcp/protocol.ts";-import type { ServerContext } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let vault: string;let configHome: string;diff --git a/tests/mcp/ner-tool.test.ts b/tests/mcp/ner-tool.test.tsindex 523b4e80..6bd06fed 100644--- a/tests/mcp/ner-tool.test.ts+++ b/tests/mcp/ner-tool.test.ts@@ -18,7 +18,7 @@ import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";import { getEntity, listEntities } from "../../src/core/brain/entities/registry.ts";import { NER_TOOLS } from "../../src/mcp/brain/ner-tools.ts";import { MCPError } from "../../src/mcp/protocol.ts";-import type { ServerContext } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let vault: string;let configHome: string;diff --git a/tests/mcp/preview-budget-dispatch.test.ts b/tests/mcp/preview-budget-dispatch.test.tsindex a8f4ca02..04c8e016 100644--- a/tests/mcp/preview-budget-dispatch.test.ts+++ b/tests/mcp/preview-budget-dispatch.test.ts@@ -5,7 +5,7 @@ import { join } from "node:path";import { buildMcpToolResult } from "../../src/mcp/server.ts";import { ArtifactStore } from "../../src/mcp/artifact-store.ts";-import type { ToolDefinition } from "../../src/mcp/tools.ts";+import type { ToolDefinition } from "../../src/mcp/tool-contract.ts";let tmp: string;let vault: string;diff --git a/tests/mcp/recall-adequacy-tool.test.ts b/tests/mcp/recall-adequacy-tool.test.tsindex 2b477d84..0c4ba7f5 100644--- a/tests/mcp/recall-adequacy-tool.test.ts+++ b/tests/mcp/recall-adequacy-tool.test.ts@@ -10,7 +10,8 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let tmp: string;let vault: string;diff --git a/tests/mcp/recall-gate-telemetry.test.ts b/tests/mcp/recall-gate-telemetry.test.tsindex 59ebe92a..d3149f3d 100644--- a/tests/mcp/recall-gate-telemetry.test.ts+++ b/tests/mcp/recall-gate-telemetry.test.ts@@ -9,7 +9,8 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { listGateTelemetry } from "../../src/core/brain/gate-telemetry.ts";-import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let tmp: string;let vault: string;diff --git a/tests/mcp/research-tool.test.ts b/tests/mcp/research-tool.test.tsindex a7d6b3d7..b6fa04c9 100644--- a/tests/mcp/research-tool.test.ts+++ b/tests/mcp/research-tool.test.ts@@ -13,7 +13,7 @@ import { bootstrapBrain } from "../../src/core/brain/init.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";import { RESEARCH_TOOLS } from "../../src/mcp/brain/research-tools.ts";import { MCPError } from "../../src/mcp/protocol.ts";-import type { ServerContext } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let vault: string;let configHome: string;diff --git a/tests/mcp/search-global.test.ts b/tests/mcp/search-global.test.tsindex f3b32b1e..226a5b92 100644--- a/tests/mcp/search-global.test.ts+++ b/tests/mcp/search-global.test.ts@@ -11,7 +11,8 @@ import { join } from "node:path";import { addRecallSource } from "../../src/core/brain/portability/recall-sources.ts";import { indexVault } from "../../src/core/search/indexer.ts";import { resolveSearchConfig } from "../../src/core/search/index.ts";-import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";import { writeMd } from "../helpers/search-fixtures.ts";let tmp: string;diff --git a/tests/mcp/skill-tools.test.ts b/tests/mcp/skill-tools.test.tsindex 00fe08ed..1e793bae 100644--- a/tests/mcp/skill-tools.test.ts+++ b/tests/mcp/skill-tools.test.ts@@ -4,7 +4,8 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { SKILL_TOOLS } from "../../src/mcp/skill-tools.ts";-import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let tmp: string;let ctx: ServerContext;diff --git a/tests/mcp/skills-attach-tool.test.ts b/tests/mcp/skills-attach-tool.test.tsindex 5da4383d..b81ef67e 100644--- a/tests/mcp/skills-attach-tool.test.ts+++ b/tests/mcp/skills-attach-tool.test.ts@@ -4,7 +4,8 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { SKILL_TOOLS } from "../../src/mcp/skill-tools.ts";-import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";let tmp: string;let configPath: string;