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
v0.13.0 - Hybrid Search and Recall Quality: explainable recall, MMR, link traversal, entity boost, header anchoring (#37)
Sol Aitken21476403d79a
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 0b33f282..5e0c2874 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.12.0",+ "version": "0.13.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 57455fd8..af428298 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.12.0",+ "version": "0.13.0","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 e64791a2..2b261859 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,52 @@ 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).+## [0.13.0] - 2026-05-26++Hybrid Search and Recall Quality suite: the fused FTS5 + semantic+ranking is now completed by four scoring/expansion layers and made+introspectable. Every search result carries a `why_retrieved` list of+the layers that ranked it. Maximal Marginal Relevance diversifies the+top pool so near-identical paraphrases stop crowding out complementary+notes. Link-graph traversal walks outbound wikilinks from the top hits+and surfaces related documents one or more hops away, decayed by+distance. A deterministic, language-agnostic entity signal boosts+proper-noun overlaps between query and note. Header-anchored chunking+keeps a mid-document chunk's section context searchable. MMR and+traversal are enabled by default and tunable via config; entity-boosting+and header anchoring populate on the next reindex - so v0.13.0 is a+deliberate ranking change and requires `o2b search reindex`.++### Added++- `src/core/search/mmr.ts` (`mmrRerank`) - greedy Maximal Marginal+ Relevance with deterministic token-set Jaccard similarity. Config+ `search_mmr_lambda` (default `0.7`; `1` disables).+- `src/core/search/traversal.ts` (`expandByTraversal`) - pure two-stage+ retrieve-then-walk expansion. Config `search_max_hops` (default `1`;+ `0` disables), `search_hop_decay` (`0.5`), `search_max_expansion_per_hit`+ (`3`). Backed by store `outboundLinkTargets` + `representativeChunks`.+- `src/core/search/entities.ts` (`extractEntities`) - structural,+ language-agnostic entity extraction (wikilink targets/aliases, quoted+ spans, capitalized runs, CamelCase, ALLCAPS, digit tokens). No NER+ dependency, no per-language word list.+- `reasons: string[]` on `BrainSearchResult` (explainable recall),+ surfaced in `brain_search` MCP output and `o2b search --verbose`/`--json`.+- `headingPath` on chunks plus a searchable `chunks.heading_path` FTS+ column (header-anchored chunking), weighted below content in bm25.+- Recall config block (`ResolvedRecallConfig`) on `ResolvedSearchConfig`,+ with matching env vars and per-query `mmrLambda` / `maxHops` overrides.++### Changed++- Search index schema migrated to version 2: adds the `chunk_entities`+ table and the `chunks.heading_path` column, and rebuilds `chunk_fts`+ as a two-column external-content FTS (`content`, `heading_path`).+ Requires `o2b search reindex`.+- The fused ranker now accepts an optional entity-match map and adds a+ capped (`0.04`) entity boost; the rank pool widens when MMR or+ traversal is active so expansions cannot displace genuine hits.+## [0.12.0] - 2026-05-26Brain Integrity Suite: the write path for confirmed preferences is now@@ -2955,6 +3001,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.+[0.13.0]: https://github.com/itechmeat/open-second-brain/compare/v0.12.0...v0.13.0[0.12.0]: https://github.com/itechmeat/open-second-brain/compare/v0.11.0...v0.12.0[0.10.9]: https://github.com/itechmeat/open-second-brain/compare/v0.10.8...v0.10.9[0.10.8]: https://github.com/itechmeat/open-second-brain/compare/v0.10.7...v0.10.8diff --git a/README.md b/README.mdindex b2473d74..e326d1cf 100644--- a/README.md+++ b/README.md@@ -109,10 +109,10 @@ The capabilities you actually feel day to day:| 6 | Browse your memory as a graph | `o2b brain explorer` opens a force-directed HTML graph of every rule, every link, every retirement. Double-click a node β Obsidian opens the underlying note. || 7 | Undo the agent if it gets it wrong | Every Brain mutation lands a verified snapshot before touching anything. One command (`o2b brain rollback <id>`) restores yesterday's state, and drift detection refuses to clobber unintended local edits. || 8 | Pin, merge, retire by hand | When a rule is wrong, you fix it. `o2b brain pin` keeps a good one safe from auto-retire, `merge` folds duplicates, `reject` puts a bad rule in the bin with a reason. The CLI is the operator's seat. |-| 9 | Full-text search across the whole vault | `o2b search "<query>" --property type=decision --property status=open` β SQLite + FTS5 plus frontmatter property filters. Faster and more precise than Obsidian's built-in search when you need to grep across thousands of notes. |+| 9 | Hybrid search that explains itself | `o2b search "<query>" --property type=decision --property status=open` β SQLite + FTS5 and an optional semantic layer, fused and then sharpened by a recall-quality suite: MMR diversity so near-duplicates do not crowd the top, link-graph traversal that surfaces notes one hop from a hit, entity-boosting for proper-noun precision, and header-anchored chunking so a mid-document chunk keeps its section context. Every result carries a `why_retrieved` breakdown of the layers that ranked it. || 10 | Pay Memory β audit every paid action | When the agent spends money (Solana-Foundation `pay`, third-party APIs) every receipt lands in `Brain/payments/<date>/`. Spending policy, approval gate, daily Telegram report. The agent never holds wallet keys. |-These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron, cross-project pointers for shared vaults, the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.+These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron, cross-project pointers for shared vaults, the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), and the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.## CLIdiff --git a/docs/brainstorm/search-recall-suite/cli-output/claude.md b/docs/brainstorm/search-recall-suite/cli-output/claude.mdnew file mode 100644index 00000000..7811d9a9--- /dev/null+++ b/docs/brainstorm/search-recall-suite/cli-output/claude.md@@ -0,0 +1,36 @@+### Variant 1: Incremental in-place extension+- **Approach**: Keep `rankResults` as the single scoring authority and extend it to emit a `reasons: string[]` per result (built from the layer scores it already computes). Add MMR and link-traversal as two new *pure* modules invoked sequentially in `search.ts` after ranking (rank β traverse-expand β re-rank merged set β MMR-diversify β property-filter). Entity extraction and heading breadcrumbs each get their own schema migration with dedicated storage (entity table + a breadcrumb-bearing FTS column), feeding the existing keyword/semantic phases; each of the five degrades independently.+- **Trade-offs**:+ - Pro: matches existing conventions exactly β pure ranker, I/O confined to `store.ts`/`search.ts`, each feature is a self-contained testable unit fitting "one PR, separate commits".+ - Pro: per-layer `reasons` fall directly out of the ranker's existing intermediate values; no contortion to expose them.+ - Pro: graceful-degrade is per-feature and obvious (empty entity table β zero boost; pre-migration breadcrumb column β today's BM25; no embeddings β no MMR).+ - Con: `search.ts` orchestrator grows several sequential phases and more wiring; no shared framework to enforce uniform shape across stages.+ - Con: traversal's "expand then re-rank merged set" requires a second hydrate/rank pass, adding a moderate code path to keep bounded.+- **Complexity**: medium+- **Risk**: low++### Variant 2: Formalized retrieval pipeline+- **Approach**: Introduce a `Stage` abstraction β each stage is a declared pure transform over a shared mutable-but-frozen-at-end candidate record (fts β semantic β fuse/rank β entity-boost β traversal-expand β mmr-diversify β property-filter). Reasons accumulate automatically because every stage appends its contribution to each candidate's annotation list. The existing ranker logic is decomposed into fuse + boost stages, and the pipeline order/toggles become config-driven.+- **Trade-offs**:+ - Pro: maximally introspectable β `reasons` is a first-class byproduct of the stage contract, and stages can be reordered, toggled, or unit-tested in isolation.+ - Pro: future scoring layers (a sixth signal) slot in without touching `search.ts`.+ - Pro: uniform bounding/caps can be enforced at the stage-runner level.+ - Con: large refactor of working, tested code (`ranker.ts` + `search.ts`) β high churn against a load-bearing determinism contract for features that don't yet need dynamic reordering.+ - Con: a shared candidate record mutated across stages is harder to keep `Object.freeze`-clean and to reason about than the current single pure function.+ - Con: over-engineered for five known, fixed layers; the abstraction earns its keep only if many more layers arrive.+- **Complexity**: large+- **Risk**: medium++### Variant 3: FTS-centric, schema-light+- **Approach**: Push as many signals as possible into the existing external-content FTS5 so they fall out of BM25 with minimal query-time code: entity tokens and heading breadcrumbs become extra indexed FTS columns, so entity-boost and header-anchored recall need no new query-time store β they emerge from keyword scoring over enriched columns. MMR and traversal remain query-time but their effects are folded into the single fused score rather than carried as separate layers.+- **Trade-offs**:+ - Pro: smallest query-time surface; entity/header recall require almost no new ranking logic, just enriched indexing.+ - Pro: fewer moving parts at search time, naturally bounded by FTS.+ - Con: directly fights feature #1 β folding signals into one BM25 column muddies per-layer `reasons` (you can't cleanly attribute "entity vs keyword" once both live in FTS).+ - Con: determinism risk β entity tokens injected into FTS must be extracted machine-identically and synced via triggers; column-level FTS weighting (bm25 weights) is coarser than an explicit additive boost and harder to keep bit-identical for un-reindexed vaults.+ - Con: couples two independent features to the FTS schema, so tuning one (entity weight) perturbs the shared BM25 space affecting the other.+- **Complexity**: medium+- **Risk**: medium-high++### Recommended: Variant 1+**Rationale**: It aligns with the codebase's strongest conventions β a pure ranker that already computes every layer, I/O isolated to the store, and explicit tested tie-breaks β so `reasons` is a near-free byproduct and each of the five lands as an independently graceful-degrading commit. It avoids Variant 2's premature pipeline framework (a large refactor of load-bearing deterministic code for layers that aren't yet dynamic) and Variant 3's FTS coupling, which would undermine the very explainability feature #1 exists to provide and put the Syncthing-critical determinism contract at risk.diff --git a/docs/brainstorm/search-recall-suite/cli-output/prompt.md b/docs/brainstorm/search-recall-suite/cli-output/prompt.mdnew file mode 100644index 00000000..0ec7793e--- /dev/null+++ b/docs/brainstorm/search-recall-suite/cli-output/prompt.md@@ -0,0 +1,68 @@+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.++# Task++Ship a "Hybrid Search & Recall Quality" suite for Open Second Brain - five related additions to the existing `src/core/search/` pipeline that complete and make introspectable the hybrid retrieval layer. The five atomic units (one PR, separate commits):++1. **Explainable recall (`why_retrieved`)** - every search result carries a `reasons: string[]` array, one entry per scoring layer that contributed (e.g. `["fts5_bm25: 0.82", "semantic_cos: 0.74", "link_boost: 0.03", "recency: 0.05"]`). No new ranking logic - expose what `rankResults` already computes. Foundation for tuning the layers below.++2. **MMR diversity rerank** - after the fused ranking, apply Maximal Marginal Relevance to the top-K so near-identical results don't flood the list. Classic formula `argmax over remaining of lambda*sim(q,d) - (1-lambda)*max(sim(d,selected))`. Single tunable lambda (default ~0.7). Similarity between candidates uses the embeddings already computed in the semantic phase; when semantic is unavailable, degrade gracefully (no MMR or a content-overlap fallback).++3. **Link-graph traversal during recall** - two-stage: (1) hybrid retrieval returns top-K by relevance; (2) for each hit follow outbound wikilinks up to depth N, scoring linked docs as parent_score * decay^hop, merge into the result set with dedup. Tunables: max_hops (default 1), hop_decay (default 0.5), max_expansion_per_hit (default 3). The `links` table already persists `target_document_id`; today only INBOUND links feed a small ranking boost - no outbound walk exists.++4. **Entity-boosted retrieval (third hybrid signal)** - extract entities at index time into a parallel store; at query time, entities extracted from the query deterministically boost results that mention them. Must be language-agnostic and dependency-free: extract candidate entities via Unicode-category heuristics (wikilink targets, quoted spans, capitalized/CamelCase/ALLCAPS runs) - NO NER library, NO per-language word lists. Graceful: a vault with no extractable entities ranks bit-identically to today.++5. **Header-anchored chunking** - long documents split into multiple chunks; mid-document chunks lose the section's heading context, hurting recall ("facts established under a heading that the chunk no longer contains"). Compute a heading breadcrumb (ancestor heading path) per chunk and make it searchable WITHOUT polluting the stored display content. The chunker already detects heading blocks and resolves a title.++# Project context++Open Second Brain - TypeScript on the Bun runtime. An Obsidian-vault-backed agent-memory system; markdown files on disk, indexed into a per-vault SQLite database (FTS5 + optional sqlite-vec semantic vectors). Search is the core value proposition versus competitors (mem0, mnemosyne, agentmemory, gbrain).++Recent commits:+84886d1 v0.12.0 - Brain Integrity Suite (typed collision detection, content-hash drift, durable dream workruns)+c002268 v0.11.0 - Brain-centric vault layout+a8d4803 v0.10.18 - temporal axis (timeline, belief evolution, stale watch)+d0598af v0.10.17 - link graph surfaces (aliases, anchors, mentions, synthesis, MOC audit, property filter)+3b7dfe9 v0.10.16 - trust and operator surfaces++Related files (current pipeline):+- src/core/search/search.ts - orchestrator: FTS candidates -> semantic candidates -> hydrate -> rankResults -> optional property filter+- src/core/search/ranker.ts - pure `rankResults`; already computes keywordScore, semanticScore, linkBoost (inbound), recencyBoost per result+- src/core/search/store.ts - SQLite access: keywordTopK, semanticTopK, hydrateChunks, inboundLinkSources, tagsByChunkDocument, replaceLinks, resolveLinkTargets+- src/core/search/types.ts - BrainSearchResult, SearchOptions, SearchOutcome, ResolvedSearchConfig+- src/core/search/schema.ts - DDL; LATEST_SCHEMA_VERSION = 1; chunk_fts is EXTERNAL-content FTS5 (content='chunks') synced by triggers from chunks.content; `links` table with target_document_id + idx+- src/core/search/chunker.ts - pure two-pass markdown chunker; emits MarkdownChunk { chunkIndex, content, startLine, endLine, tokenCount }; detects heading blocks; resolveTitle+- src/core/search/indexer.ts - walks vault, chunks, writes documents/chunks/links, populates embeddings+- src/mcp/search-tools.ts - `brain_search` MCP tool (read-only); maps BrainSearchResult to a flat JSON object+- src/cli/search.ts - `o2b search` CLI surface++Conventions:+- TDD throughout (Bun test). Pure functions where possible; the ranker imports no I/O.+- Determinism is load-bearing: the same vault must hash the same chunks on every Syncthing peer. Chunker is dependency-free and machine-independent.+- Results are `Object.freeze`d. Tie-break order is explicit and tested.+- Schema migrations append to `MIGRATIONS` and bump `LATEST_SCHEMA_VERSION`; a newer-than-supported DB raises `SCHEMA_MISMATCH`.+- "Graceful degrade to existing behaviour" is a hard requirement: an untagged / unembedded / un-reindexed vault must rank bit-identically to today.++Constraints:+- No hardcoded human-language phrases or per-language word lists anywhere; handle other languages abstractly (Unicode categories, structural cues).+- No new runtime dependencies without strong justification (prefer dependency-free / deterministic).+- Do not change the meaning of existing `BrainSearchResult` fields; additions only.+- Keep search response time bounded and predictable (the traversal/MMR steps must cap their work).+- Two of the five features (entity store, header-anchored chunking) appear to require a schema migration + reindex; the design should state how a pre-migration index degrades until reindex.++# Required output format++Produce exactly 3 distinct architectural variants. For each variant:++### Variant N: <short name>+- **Approach**: 2-3 sentences describing the variant.+- **Trade-offs**: bullet list of pros and cons.+- **Complexity**: small | medium | large+- **Risk**: low | medium | high++After the three variants, add exactly one recommendation:++### Recommended: Variant N+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.++Output nothing outside of these sections.diff --git a/docs/brainstorm/search-recall-suite/design.md b/docs/brainstorm/search-recall-suite/design.mdnew file mode 100644index 00000000..2b5fbeaf--- /dev/null+++ b/docs/brainstorm/search-recall-suite/design.md@@ -0,0 +1,168 @@+# Hybrid Search and Recall Quality Suite - complete and introspect the retrieval layer++**Status:** draft+**Author:** claude-vps-agent (via feature-release-playbook)+**Audience:** implementation++## Problem statement++Open Second Brain search fuses FTS5 keyword scoring and optional semantic+vectors, but the hybrid layer is incomplete and opaque. There is no+diversification (near-identical paraphrases flood the top-K), no walk of the+link graph at query time (densely linked context one hop away is missed), no+proper-noun signal (entity matches are not distinguished from keyword+matches), no recall anchor for mid-document chunks (a chunk that splits off+from its section loses the heading context), and no per-result explanation of+why a hit ranked where it did. Each gap is something every memory competitor+already addresses; together they are the core value proposition of the+product.++## Scope++Five atomic units shipped in one pull request, separate commits, in this+order (each builds on the introspection surface of the first):++- **F1 - Explainable recall (`why_retrieved`).** Every result carries a+ `reasons: ReadonlyArray<string>` listing each scoring layer that+ contributed. Pure exposure of values `rankResults` already computes.+- **F2 - MMR diversity rerank.** Maximal Marginal Relevance over the fused+ top pool so near-identical results do not crowd out complementary ones.+ Single tunable `lambda`. Deterministic lexical similarity (no embedding+ round-trip).+- **F3 - Link-graph traversal during recall.** Two-stage retrieve-then-walk:+ follow outbound wikilinks from top hits, score expansion docs as+ `parent_score * decay^hop`, merge with dedup. Bounded by `max_hops`,+ `hop_decay`, `max_expansion_per_hit`.+- **F4 - Entity-boosted retrieval.** A third hybrid signal. Deterministic,+ language-agnostic entity extraction at index time into a parallel table;+ query-time entity overlap adds a capped boost. No NER dependency, no+ per-language word lists.+- **F5 - Header-anchored chunking.** Each chunk carries the ancestor heading+ breadcrumb in a dedicated, searchable FTS column so mid-document chunks+ retain topical anchors - without polluting the stored display content.++## Out of scope++- Embedding-based MMR similarity (lexical similarity ships now; a vector+ variant can follow if measured to help).+- Pluggable external vector backends (Qdrant/Milvus/etc.) - separate task.+- Full conversation/session transcript indexing - F5 addresses the+ long-document recall problem in the existing chunker, which is the+ OSB-shaped form of the upstream "header injection" idea.+- Any change to the meaning of existing `BrainSearchResult` fields.++## Chosen approach++Variant 1 - incremental in-place extension. `rankResults` stays the single+scoring authority and gains: a per-result `reasons` array assembled from the+layer values it already computes, plus an optional entity-boost component.+MMR and traversal land as new pure modules (`mmr.ts`, `traversal.ts`) invoked+sequentially by `search.ts` after ranking. Entity storage and heading+breadcrumbs each get backing in a single schema migration (v1 -> v2). I/O stays+confined to `store.ts`; the new ranking math stays pure and unit-testable.++Pipeline after the change (`search.ts`):++```text+fts candidates -> semantic candidates -> hydrate+ -> rankResults (keyword + semantic + link + recency + tier + ENTITY) [F1 reasons, F4 boost]+ -> traversal expand (outbound links, decayed) -> re-merge + re-sort [F3]+ -> MMR diversify the pool [F2]+ -> property filter -> slice to limit+```++Graceful degradation is per-feature and explicit:++- F1: additive field; always present.+- F2: no-op when fewer than two results or `lambda == 1`.+- F3: no-op when `max_hops == 0` or a doc has no resolved outbound links.+- F4: zero boost when `chunk_entities` is empty (pre-reindex) - bit-identical+ to today.+- F5: empty `heading_path` column (pre-reindex) contributes nothing to bm25 -+ bit-identical to today.++## Design decisions++- **`why_retrieved` is built in the ranker, not bolted on in `search.ts`.**+ The ranker is the only place that holds every component value; assembling+ the array there keeps a single source of truth and falls out for free.+ Format `"<layer>: <fixed-precision value>"`, one entry per layer that+ actually fired (zero-valued layers omitted to keep the array meaningful).+- **MMR similarity is lexical (token-set), not vector.** A deterministic+ token-set cosine over chunk content catches the near-duplicate paraphrases+ MMR targets, works uniformly whether or not semantic is enabled, needs no+ vector retrieval, and preserves the Syncthing determinism contract. The+ relevance term reuses the already-computed fused `score`.+- **MMR and traversal are enabled by default but fully tunable.** Value to the+ operator is the priority; both are bounded and deterministic. `lambda = 0.7`,+ `max_hops = 1`, `hop_decay = 0.5`, `max_expansion_per_hit = 3`. Each can be+ turned off via config (`lambda = 1`, `max_hops = 0`). The pure `rankResults`+ unit tests are unaffected because the new phases live in `search.ts`;+ affected search-integration fixtures are updated as part of the change since+ the new behaviour is intentional.+- **Entity extraction is structural, not linguistic.** Candidates come from+ wikilink targets, quoted spans, and Unicode uppercase-initial / CamelCase /+ ALLCAPS token runs. Normalisation is lowercase + trim. No human-language+ phrase or word list appears anywhere, satisfying the project constraint and+ keeping extraction identical across locales.+- **One schema migration (v2) backs F4 and F5.** It adds the `chunk_entities`+ table, adds a `heading_path` column to `chunks`, and rebuilds `chunk_fts` as+ a two-column external-content FTS (`content`, `heading_path`) with refreshed+ triggers. `LATEST_SCHEMA_VERSION` becomes 2; a newer-than-supported DB still+ raises `SCHEMA_MISMATCH`. Both features need a reindex to populate; until+ then their columns/tables are empty and ranking is unchanged.+- **bm25 column weighting keeps content dominant.** The heading column gets a+ smaller bm25 weight than content so a breadcrumb match nudges recall without+ overpowering a body match.++## File changes++New:++- `src/core/search/mmr.ts` - pure `mmrRerank(results, opts)`.+- `src/core/search/traversal.ts` - pure expansion/scoring given outbound map.+- `src/core/search/entities.ts` - pure `extractEntities(text)` + normaliser.+- `src/core/search/heading-path.ts` - pure breadcrumb builder over heading+ blocks (or folded into `chunker.ts` if cleaner).+- Test files under `tests/core/search/` for each new module, plus integration+ tests in the existing search/indexer/chunker suites.++Modified:++- `src/core/search/types.ts` - add `reasons` to `BrainSearchResult`; add+ config fields (`mmrLambda`, `maxHops`, `hopDecay`, `maxExpansionPerHit`,+ entity/heading bm25 weights) to `ResolvedSearchConfig`; matching+ `SearchOptions` opt-outs.+- `src/core/search/ranker.ts` - emit `reasons`; accept optional entity-match+ map and add a capped entity boost.+- `src/core/search/search.ts` - wire traversal + MMR phases; fetch entity+ matches and outbound links from the store.+- `src/core/search/store.ts` - `outboundLinkTargets`, `chunkEntityMatches`,+ `replaceEntities`; heading_path read/write; two-column FTS queries.+- `src/core/search/schema.ts` - migration v2 (`chunk_entities`,+ `chunks.heading_path`, rebuilt `chunk_fts` + triggers); bump+ `LATEST_SCHEMA_VERSION`.+- `src/core/search/chunker.ts` - emit `headingPath` per chunk.+- `src/core/search/indexer.ts` - persist heading_path; extract + store+ entities per chunk.+- `src/mcp/search-tools.ts` - surface `reasons` in `brain_search` output.+- `src/cli/search.ts` - render `reasons` in CLI output.+- `README.md`, `CHANGELOG.md`, affected `docs/`.++## Risks and open questions++- **FTS rebuild correctness.** Migrating an external-content FTS to two+ columns is delicate; the migration must drop/recreate the virtual table and+ triggers atomically and a reindex must repopulate. Mitigation: dedicated+ migration test that opens a v1 fixture DB, migrates, and asserts both+ columns query correctly; assert pre-reindex bit-identical ranking.+- **Default-on MMR/traversal changing existing search-integration+ expectations.** Accepted and intentional; fixtures updated under TDD. Pure+ ranker/chunker unit tests stay green.+- **Traversal hydration cost.** Expansion hydrates a representative chunk per+ linked doc; capped by `max_expansion_per_hit` and applied only to the top+ hits so response time stays bounded.+- **Entity precision.** Structural extraction is recall-oriented and may admit+ noise (e.g. sentence-initial capitalised words). Mitigation: cap the entity+ boost low and require multi-character / multi-token entities; the boost can+ only reorder within an already-relevant set, never inject unrelated docs.diff --git a/docs/brainstorm/search-recall-suite/plan.md b/docs/brainstorm/search-recall-suite/plan.mdnew file mode 100644index 00000000..c286207a--- /dev/null+++ b/docs/brainstorm/search-recall-suite/plan.md@@ -0,0 +1,100 @@+# Hybrid Search and Recall Quality Suite - implementation plan++Five atomic units, one per commit, in dependency order on the same+`feat/search-recall-suite` branch. Each: failing test first, watch it fail,+minimal implementation, refactor green, commit.++## Task 1: Explainable recall (`why_retrieved`)++- **Files**: `src/core/search/types.ts` (add `reasons` to `BrainSearchResult`),+ `src/core/search/ranker.ts` (assemble `reasons` per result),+ `src/mcp/search-tools.ts` (surface `reasons`), `src/cli/search.ts` (render),+ `tests/core/search/ranker-reasons.test.ts`,+ `tests/mcp/brain-search-reasons.test.ts`.+- **Acceptance**: ranker emits one `"<layer>: <value>"` entry per layer that+ fired (keyword/semantic/link/recency/tier); zero-valued layers omitted;+ ordering stable; MCP `brain_search` output includes `reasons`. A+ keyword-only hit lists exactly `fts5_bm25`; a hybrid hit lists keyword and+ semantic; a recent linked hit also lists link and recency.+- **Depends on**: none.++## Task 2: MMR diversity rerank++- **Files**: `src/core/search/mmr.ts` (new pure module),+ `src/core/search/types.ts` (config `mmrLambda` + `SearchOptions` opt-out),+ `src/core/search/search.ts` (wire after rank), `src/core/search/index.ts`+ (resolve config default), `tests/core/search/mmr.test.ts`,+ search-integration fixture updates.+- **Acceptance**: `mmrRerank` with `lambda < 1` demotes a near-duplicate of an+ already-selected result below a less-similar but slightly-lower-relevance+ result; `lambda == 1` is identity; fewer than two results is identity;+ deterministic token-set similarity; `reasons` gains an `mmr_rank` note when+ MMR moved a result. Bounded to a fixed pool size.+- **Depends on**: Task 1 (reasons surface).++## Task 3: Link-graph traversal during recall++- **Files**: `src/core/search/traversal.ts` (new pure module),+ `src/core/search/store.ts` (`outboundLinkTargets`),+ `src/core/search/search.ts` (expand + merge before MMR),+ `src/core/search/types.ts` (config `maxHops`, `hopDecay`,+ `maxExpansionPerHit`), `tests/core/search/traversal.test.ts`,+ `tests/core/search/store-outbound-links.test.ts`,+ search-integration test.+- **Acceptance**: a doc linked from a top hit appears in results scored as+ `parent_score * hop_decay`, capped at `max_expansion_per_hit` per hit and+ `max_hops` depth; an already-present doc keeps its higher score (dedup); a+ result added by traversal carries a `link_traversal: <hops>` reason;+ `max_hops == 0` is a no-op (bit-identical).+- **Depends on**: Task 1.++## Task 4: Entity-boosted retrieval++- **Files**: `src/core/search/entities.ts` (new pure extractor + normaliser),+ `src/core/search/schema.ts` (migration v2: `chunk_entities` table; bump+ `LATEST_SCHEMA_VERSION`), `src/core/search/store.ts` (`replaceEntities`,+ `chunkEntityMatches`), `src/core/search/indexer.ts` (extract + store per+ chunk), `src/core/search/ranker.ts` (optional entity-match map -> capped+ boost + reason), `src/core/search/search.ts` (extract query entities, fetch+ matches), `tests/core/search/entities.test.ts`,+ `tests/core/search/ranker-entity-boost.test.ts`,+ `tests/core/search/store-entities.test.ts`,+ `tests/core/search/schema-migration-v2.test.ts`.+- **Acceptance**: extractor pulls wikilink targets, quoted spans, and+ Unicode-uppercase / CamelCase / ALLCAPS runs from mixed-script text with no+ language word list; a result whose entities overlap the query entities gets+ a capped boost and an `entity_match: N` reason; an empty `chunk_entities`+ table yields zero boost (bit-identical); migration v2 creates the table and+ a v1 DB upgrades cleanly.+- **Depends on**: Task 1; shares migration v2 with Task 5.++## Task 5: Header-anchored chunking++- **Files**: `src/core/search/heading-path.ts` (or fold into `chunker.ts`),+ `src/core/search/chunker.ts` (emit `headingPath` per chunk),+ `src/core/search/schema.ts` (migration v2: `chunks.heading_path` column ++ rebuilt two-column `chunk_fts` + triggers), `src/core/search/store.ts`+ (write heading_path; two-column FTS query + bm25 weights),+ `src/core/search/indexer.ts` (persist heading_path), `src/core/search/fts.ts`+ (column-aware query if needed),+ `tests/core/search/chunker-heading-path.test.ts`,+ `tests/core/search/heading-anchored-recall.test.ts`,+ migration test extended.+- **Acceptance**: a chunk split off from its section carries the ancestor+ heading breadcrumb (e.g. `"Parent > Child"`); a query matching only the+ heading recalls the chunk via the heading FTS column; display `content` is+ unchanged (breadcrumb never appears in returned content); heading bm25+ weight is lower than content; empty heading_path (pre-reindex) is+ bit-identical.+- **Depends on**: shares migration v2 with Task 4.++## Cross-cutting++- Migration v2 is authored once (Task 4 lands the table; Task 5 extends the+ same migration version with the column + FTS rebuild) so a single+ `LATEST_SCHEMA_VERSION = 2` covers both. Order the commits so the migration+ is internally consistent at each commit.+- After all five: full `bun test`, `bun run typecheck`, lint,+ `bun run sync-version:check`, and a live `o2b search` smoke test on a+ scratch vault (index -> query -> confirm `reasons`, diversified order,+ traversal expansion, entity boost, heading recall).diff --git a/docs/brainstorm/search-recall-suite/variants.md b/docs/brainstorm/search-recall-suite/variants.mdnew file mode 100644index 00000000..c5f53730--- /dev/null+++ b/docs/brainstorm/search-recall-suite/variants.md@@ -0,0 +1,82 @@+# Variant audit trail - Hybrid Search and Recall Quality Suite++Primary consultant: Claude Code (`claude -p`), exit 0, three parseable+variants. Fallback (Codex) not invoked.++Note on environment: the consultant CLI could not be streamed directly through+the orchestrator's shell (a harness-level output fault on sub-CLI spawn). It+was run via a detached wrapper script writing to+`cli-output/claude.md`; the raw output is preserved there unedited.++## Variants produced by the consultant (verbatim)++### Variant 1: Incremental in-place extension+- **Approach**: Keep `rankResults` as the single scoring authority and extend+ it to emit a `reasons: string[]` per result (built from the layer scores it+ already computes). Add MMR and link-traversal as two new *pure* modules+ invoked sequentially in `search.ts` after ranking (rank -> traverse-expand ->+ re-rank merged set -> MMR-diversify -> property-filter). Entity extraction and+ heading breadcrumbs each get their own schema migration with dedicated+ storage (entity table + a breadcrumb-bearing FTS column), feeding the+ existing keyword/semantic phases; each of the five degrades independently.+- **Trade-offs**: matches existing conventions exactly (pure ranker, I/O in+ store/search, self-contained testable units); per-layer reasons fall out of+ existing intermediate values; per-feature graceful degrade is obvious.+ Cons: `search.ts` grows several sequential phases with no shared framework;+ traversal's expand-then-rerank needs a second hydrate/rank pass to keep+ bounded.+- **Complexity**: medium+- **Risk**: low++### Variant 2: Formalized retrieval pipeline+- **Approach**: Introduce a `Stage` abstraction - each stage a declared pure+ transform over a shared candidate record (fts -> semantic -> fuse/rank ->+ entity-boost -> traversal-expand -> mmr-diversify -> property-filter).+ Reasons accumulate automatically. Ranker decomposed into fuse + boost+ stages; order/toggles config-driven.+- **Trade-offs**: maximally introspectable and reorderable; future signals+ slot in without touching `search.ts`; uniform caps at the runner. Cons:+ large refactor of working, tested, determinism-critical code; shared mutated+ candidate record is harder to keep frozen and reason about; over-engineered+ for five fixed layers.+- **Complexity**: large+- **Risk**: medium++### Variant 3: FTS-centric, schema-light+- **Approach**: Push signals into FTS5 - entity tokens and heading breadcrumbs+ become extra indexed columns so entity-boost and header recall emerge from+ BM25 with minimal query-time code; MMR and traversal effects folded into the+ single fused score.+- **Trade-offs**: smallest query-time surface; entity/header recall need+ almost no new ranking logic. Cons: fights F1 (folding signals into one BM25+ column muddies per-layer attribution); determinism risk from injected FTS+ tokens and coarse column weighting; couples two independent features to the+ FTS schema.+- **Complexity**: medium+- **Risk**: medium-high++### Consultant recommendation: Variant 1+Rationale: aligns with the codebase's strongest conventions (pure ranker,+I/O-in-store, explicit tested tie-breaks), so `reasons` is near-free and each+feature lands as an independently graceful-degrading commit. Avoids Variant+2's premature pipeline framework and Variant 3's FTS coupling, which would+undermine the explainability F1 exists to provide and risk the+Syncthing-critical determinism contract.++## Orchestrator decision: Variant 1 (no override)++Agreed with the consultant. The decisive project-context factors:++1. **F1 is the spine of the suite.** Variant 3 actively degrades per-layer+ attribution by folding signals into shared BM25 columns - it trades away+ the feature that makes the other four tunable. Disqualifying.+2. **Determinism is a hard contract** (identical chunk hashes across Syncthing+ peers). Variant 3's injected FTS tokens and Variant 2's mutated shared+ record both add determinism surface; Variant 1's pure modules add none.+3. **Five fixed layers do not justify a pipeline framework.** Variant 2's+ `Stage` abstraction is a large refactor of load-bearing tested code whose+ payoff (dynamic reordering) is not needed. KISS favours Variant 1.++The one Variant-1 con worth managing - `search.ts` accreting sequential phases+- is contained by keeping each phase a pure module with its own tests and a+single documented ordering in `search.ts`.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex 22506afd..5b33a9d6 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -112,13 +112,29 @@ Full Pay Memory walkthrough: [`pay-memory.md`](pay-memory.md).## Search```text-o2b search "<query>" FTS5 full-text search across the vault+o2b search "<query>" Hybrid full-text + semantic search across the vault--property type=decision --property status=openfilters on frontmatter scalars (post-FTS phase)- --json for structured output+ --verbose adds per-result why_retrieved reasons+ --json for structured output (includes reasons[])o2b search reindex Rebuild the SQLite + FTS5 index from scratch+ (required after upgrading to the v0.13.0 schema)```+The fused ranking is sharpened by a recall-quality suite (v0.13.0), each+layer config-tunable and bounded:++| Config key | Env var | Default | Effect |+|---|---|---|---|+| `search_mmr_lambda` | `OPEN_SECOND_BRAIN_SEARCH_MMR_LAMBDA` | `0.7` | MMR relevance-vs-diversity tradeoff; `1` disables diversification |+| `search_max_hops` | `OPEN_SECOND_BRAIN_SEARCH_MAX_HOPS` | `1` | Link-graph traversal depth during recall; `0` disables |+| `search_hop_decay` | `OPEN_SECOND_BRAIN_SEARCH_HOP_DECAY` | `0.5` | Per-hop score multiplier for traversal-surfaced docs |+| `search_max_expansion_per_hit` | `OPEN_SECOND_BRAIN_SEARCH_MAX_EXPANSION_PER_HIT` | `3` | Cap on outbound links followed per node |++Entity-boosted retrieval and header-anchored chunking populate on the+next reindex and need no configuration. Every result carries a+`why_retrieved` list naming the scoring layers that ranked it.+## Helpers```textdiff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex d041699a..67425e5d 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -601,8 +601,10 @@ flowchart LRChunker --> Store[(SQLite store<br/>documents / chunks / links / embeddings)]Chunker --> Links[extract wikilinks /<br/>markdown links / tags]Links --> Store- Store --> FTS[(chunk_fts<br/>FTS5 BM25)]+ Store --> FTS[(chunk_fts<br/>FTS5 BM25<br/>content + heading_path)]Store -.optional.-> Vec[(chunk_vec<br/>sqlite-vec)]+ Chunker --> Ents[extract entities<br/>structural / Unicode]+ Ents --> StoreTexts[chunk content] -. on --embeddings .-> Provider[OpenAI-compat<br/>embeddings provider]Provider --> Vecend@@ -612,9 +614,11 @@ flowchart LRQ["o2b search '<q>'<br/>brain_search"] --> KW[FTS5 keyword<br/>limit Γ 3 candidates]Q -. semantic on .-> SemQ[provider.embed query]SemQ --> SemS[vec_search<br/>limit Γ 5 candidates]- KW --> Ranker[ranker<br/>min-max BM25 + cosine<br/>+ link boost + recency boost]+ KW --> Ranker[ranker<br/>BM25 + cosine + link<br/>+ recency + entity boost<br/>+ why_retrieved]SemS --> Ranker- Ranker --> Results[ranked results]+ Ranker --> Trav[link-graph traversal<br/>retrieve-then-walk]+ Trav --> MMR[MMR diversity rerank]+ MMR --> Results[ranked results]end```@@ -632,12 +636,23 @@ Key behaviours, all driven from `Brain/_brain.yaml`-free `search_*` /writer exclusivity (three attempts, 1 s backoff, then`INDEX_LOCKED`).- **Ranking.** `final_score = clamp01(keyword_weightΒ·norm_BM25 +- semantic_weightΒ·cosine + link_boost + recency_boost)`. BM25 is- min-max-normalised within the candidate set; cosine is+ semantic_weightΒ·cosine + link_boost + recency_boost + entity_boost)`.+ BM25 is min-max-normalised within the candidate set; cosine is`1 - L2Β² / 2` on unit-normalised vectors; link boost rewardscandidates that other candidates reference via `[[wikilink]]` /markdown link (capped at 0.03) or share a tag with (capped at- 0.02); recency is a step function on `mtime`.+ 0.02); recency is a step function on `mtime`; entity boost (capped+ at 0.04) rewards proper-noun overlap between query and chunk. Every+ result carries a `why_retrieved` list of the layers that fired.+- **Recall layers (v0.13.0).** After ranking, link-graph traversal+ walks outbound wikilinks from the top hits and merges in related+ documents scored `parentΒ·hop_decay^hop` (bounded by `search_max_hops`+ / `search_max_expansion_per_hit`); then MMR reranks the pool with a+ deterministic token-set similarity so near-duplicates do not crowd+ the top (`search_mmr_lambda`, `1` disables). Header-anchored chunking+ indexes each chunk's heading breadcrumb in a dedicated FTS column+ (weighted below content) so a mid-document chunk keeps its topical+ anchor. Entity and heading layers populate on the next reindex.- **Semantic policy.** Implicit semantic (config default) warns andfalls back to keyword-only when sqlite-vec is unavailable, the keyis missing, the provider is down, or no embeddings exist yet.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex ae45a58b..325d5dd3 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": "0.12.0",+ "version": "0.13.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 7caa9ac7..ad44a945 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.12.0",+ "version": "0.13.0","type": "module","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",diff --git a/plugin.yaml b/plugin.yamlindex 67a9c180..b62b1ef8 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.12.0"+version: "0.13.0"description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex f6623579..d58538e8 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.12.0",+ "version": "0.13.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex ce053274..2730e996 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.12.0"+version: "0.13.0"description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/pyproject.toml b/pyproject.tomlindex aa28018c..46d192ad 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 = "0.12.0"+version = "0.13.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/search.ts b/src/cli/search.tsindex 8c4490be..8fc53ab6 100644--- a/src/cli/search.ts+++ b/src/cli/search.ts@@ -216,6 +216,7 @@ function jsonForOutcome(o: SearchOutcome): unknown {start_line: r.startLine,end_line: r.endLine,search_type: r.searchType,+ reasons: r.reasons,document_id: r.documentId,chunk_id: r.chunkId,})),@@ -240,6 +241,9 @@ function renderOutcomeHuman(o: SearchOutcome, verbose: boolean): string {);const snippet = r.content.trim().replace(/\s+/g, " ").slice(0, 140);lines.push(` ${snippet}${r.content.length > 140 ? "β¦" : ""}`);+ if (verbose && r.reasons.length > 0) {+ lines.push(` why: ${r.reasons.join(", ")}`);+ }lines.push("");});for (const w of o.warnings) lines.push(`warning: ${w}`);diff --git a/src/core/search/chunker.ts b/src/core/search/chunker.tsindex 8e20dc1c..24359348 100644--- a/src/core/search/chunker.ts+++ b/src/core/search/chunker.ts@@ -24,6 +24,15 @@ export interface MarkdownChunk {readonly startLine: number;readonly endLine: number;readonly tokenCount: number;+ /**+ * Breadcrumb of headings the chunk falls under, joined by " > "+ * (e.g. "Top > Section A"). Computed at the chunk's end so a chunk+ * spanning into a deeper subsection is anchored to the deepest+ * heading it covers. Empty when no heading precedes the chunk.+ * Indexed in a dedicated FTS column so a mid-document chunk keeps its+ * topical anchor; never part of the display content.+ */+ readonly headingPath: string;}export interface ChunkResult {@@ -282,6 +291,7 @@ function emitChunk(startLine: bodyLines[0]?.num ?? overlap[0]?.num ?? 1,endLine: bodyLines[bodyLines.length - 1]?.num ?? overlap[overlap.length - 1]?.num ?? 1,tokenCount,+ headingPath: "",});}@@ -317,6 +327,7 @@ function packBlocks(startLine: block.lines[0]!.num,endLine: block.lines[block.lines.length - 1]!.num,tokenCount: countTokens(fmContent),+ headingPath: "",}),);// The next chunk should NOT include frontmatter text as overlap.@@ -395,6 +406,42 @@ function resolveTitle(return null;}+interface HeadingMark {+ readonly line: number;+ readonly level: number;+ readonly text: string;+}++/** Collect heading marks (line, level, text) in document order. */+function collectHeadings(blocks: ReadonlyArray<Block>): HeadingMark[] {+ const out: HeadingMark[] = [];+ for (const b of blocks) {+ if (b.kind !== "heading") continue;+ const raw = b.lines[0]!.text;+ const hashes = raw.match(/^#{1,6}/);+ const level = hashes ? hashes[0].length : 1;+ const text = raw.replace(/^#{1,6}\s+/, "").trim();+ if (text) out.push({ line: b.lines[0]!.num, level, text });+ }+ return out;+}++/**+ * Breadcrumb of headings in effect at `atLine` (the chunk's end line):+ * replay heading marks at or before the line, maintaining a level-stack+ * (a heading pops every entry at its level or deeper). Returns the stack+ * texts joined " > ".+ */+function headingPathAt(headings: ReadonlyArray<HeadingMark>, atLine: number): string {+ const stack: HeadingMark[] = [];+ for (const h of headings) {+ if (h.line > atLine) break;+ while (stack.length > 0 && stack[stack.length - 1]!.level >= h.level) stack.pop();+ stack.push(h);+ }+ return stack.map((h) => h.text).join(" > ");+}+/*** Two-pass markdown chunker. Pure function: same input β same output.*@@ -422,7 +469,17 @@ export function chunkMarkdown(const { blocks, warnings } = splitIntoBlocks(allLines);const frontmatter = blocks.find((b) => b.kind === "frontmatter") ?? null;const title = resolveTitle(frontmatter, blocks, filenameBase);- const chunks = packBlocks(blocks, { maxTokens, minTokens, overlapTokens });+ const packed = packBlocks(blocks, { maxTokens, minTokens, overlapTokens });++ // Anchor each chunk to the heading breadcrumb active at its end (the+ // deepest section it spans).+ const headings = collectHeadings(blocks);+ const chunks =+ headings.length === 0+ ? packed+ : packed.map((c) =>+ Object.freeze({ ...c, headingPath: headingPathAt(headings, c.endLine) }),+ );return Object.freeze({title,diff --git a/src/core/search/entities.ts b/src/core/search/entities.tsnew file mode 100644index 00000000..1a4ebf74--- /dev/null+++ b/src/core/search/entities.ts@@ -0,0 +1,76 @@+/**+ * Deterministic, language-agnostic entity extraction.+ *+ * Entities are proper-noun-ish anchors a query and a memory can share:+ * project names, people, identifiers, acronyms. We do NOT use an NER+ * model or any per-language word list - extraction relies purely on+ * structural Unicode cues, so it behaves identically across locales and+ * produces bit-stable output on every Syncthing peer:+ *+ * - wikilink targets and their alias display text;+ * - double-quoted spans;+ * - capitalized token runs (one or more tokens each starting with a+ * Unicode uppercase letter);+ * - CamelCase tokens (internal uppercase), ALLCAPS tokens, and tokens+ * mixing letters with digits (FTS5, v0.13.0).+ *+ * Entity matching is a re-ranking boost over already-retrieved+ * candidates, never a retrieval mechanism, so liberal extraction cannot+ * inject unrelated documents - it only nudges ordering. Output is+ * normalised (lowercased, whitespace-collapsed, deduped) and frozen.+ */++const WIKILINK_RE = /\[\[([^\]\n|]+?)(?:\|([^\]\n]+))?\]\]/gu;+const QUOTED_RE = /"([^"\n]{2,})"/gu;+// One or more consecutive uppercase-initial tokens (covers "Sergey" and+// "Open Second Brain"). Tokens may carry trailing letters/numbers.+const CAP_RUN_RE = /\p{Lu}[\p{L}\p{N}]*(?:[ \t]+\p{Lu}[\p{L}\p{N}]*)*/gu;+// Single tokens that are notable regardless of position: CamelCase,+// ALLCAPS, or letter+digit mixes.+const CAMEL_RE = /\p{Ll}+\p{Lu}[\p{L}\p{N}]*/gu;+const ALLCAPS_OR_DIGIT_RE = /[\p{Lu}\p{N}]*\p{Lu}[\p{Lu}\p{N}]+|\p{L}+\p{N}+|\p{N}+\p{L}+/gu;++/** Lowercase + collapse internal whitespace. */+function normalize(raw: string): string {+ return raw.trim().replace(/[ \t]+/g, " ").toLowerCase();+}++/** Last path segment without a markdown extension, for wikilink targets. */+function basename(target: string): string {+ const seg = target.split("/").pop() ?? target;+ return seg.replace(/\.md$/i, "");+}++export function extractEntities(text: string): ReadonlyArray<string> {+ if (!text) return Object.freeze([] as string[]);+ const seen = new Set<string>();+ const out: string[] = [];+ const add = (raw: string): void => {+ const n = normalize(raw);+ if (n.length < 2) return;+ if (seen.has(n)) return;+ seen.add(n);+ out.push(n);+ };++ for (const m of text.matchAll(WIKILINK_RE)) {+ const target = m[1] ?? "";+ const alias = m[2];+ if (alias) add(alias);+ if (target) add(basename(target));+ }+ for (const m of text.matchAll(QUOTED_RE)) add(m[1] ?? "");+ for (const m of text.matchAll(CAP_RUN_RE)) {+ // Emit the full run ("Open Second Brain") and, for multi-token+ // runs, each constituent token ("open", "second", "brain") so a+ // query naming one of them still matches. Single-token runs add+ // just themselves.+ add(m[0]);+ const tokens = m[0].split(/[ \t]+/);+ if (tokens.length > 1) for (const t of tokens) add(t);+ }+ for (const m of text.matchAll(CAMEL_RE)) add(m[0]);+ for (const m of text.matchAll(ALLCAPS_OR_DIGIT_RE)) add(m[0]);++ return Object.freeze(out);+}diff --git a/src/core/search/index.ts b/src/core/search/index.tsindex da412417..a14630d5 100644--- a/src/core/search/index.ts+++ b/src/core/search/index.ts@@ -15,6 +15,7 @@ import { resolveIndexPath } from "./paths.ts";import { SearchError } from "./types.ts";import type {ResolvedEmbeddingConfig,+ ResolvedRecallConfig,ResolvedSearchConfig,VaultIgnoreRule,} from "./types.ts";@@ -30,6 +31,7 @@ export type {IndexStats,IndexStatusSnapshot,ResolvedEmbeddingConfig,+ ResolvedRecallConfig,ResolvedSearchConfig,SearchErrorCode,SearchOptions,@@ -58,6 +60,10 @@ const DEFAULTS = {timeoutMs: 10_000,concurrency: 4,batchSize: 32,+ mmrLambda: 0.7,+ maxHops: 1,+ hopDecay: 0.5,+ maxExpansionPerHit: 3,};type IntegerRange = { readonly min?: number; readonly max?: number };@@ -238,6 +244,40 @@ export function resolveSearchConfig(opts: {batchSize,});+ const mmrLambda = parseFloat01(+ envOrConfig(env, config, "OPEN_SECOND_BRAIN_SEARCH_MMR_LAMBDA", "search_mmr_lambda"),+ DEFAULTS.mmrLambda,+ "search_mmr_lambda",+ );+ const maxHops = parseInteger(+ envOrConfig(env, config, "OPEN_SECOND_BRAIN_SEARCH_MAX_HOPS", "search_max_hops"),+ DEFAULTS.maxHops,+ "search_max_hops",+ { min: 0 },+ );+ const hopDecay = parseFloat01(+ envOrConfig(env, config, "OPEN_SECOND_BRAIN_SEARCH_HOP_DECAY", "search_hop_decay"),+ DEFAULTS.hopDecay,+ "search_hop_decay",+ );+ const maxExpansionPerHit = parseInteger(+ envOrConfig(+ env,+ config,+ "OPEN_SECOND_BRAIN_SEARCH_MAX_EXPANSION_PER_HIT",+ "search_max_expansion_per_hit",+ ),+ DEFAULTS.maxExpansionPerHit,+ "search_max_expansion_per_hit",+ { min: 0 },+ );+ const recall: ResolvedRecallConfig = Object.freeze({+ mmrLambda,+ maxHops,+ hopDecay,+ maxExpansionPerHit,+ });+const base: ResolvedSearchConfig = Object.freeze({vault: opts.vault,dbPath,@@ -247,6 +287,7 @@ export function resolveSearchConfig(opts: {keywordWeight,semanticWeight,semantic,+ recall,});if (!opts.overrides) {diff --git a/src/core/search/indexer.ts b/src/core/search/indexer.tsindex c8a94e19..56e85989 100644--- a/src/core/search/indexer.ts+++ b/src/core/search/indexer.ts@@ -28,6 +28,7 @@ import { basename, dirname } from "node:path";import { chunkMarkdown } from "./chunker.ts";import { makeProvider } from "./embeddings/provider.ts";import { extractLinks } from "./links.ts";+import { extractEntities } from "./entities.ts";import { Store } from "./store.ts";import { SearchError } from "./types.ts";import { walkVault } from "./walker.ts";@@ -195,13 +196,15 @@ async function indexInto(startLine: c.startLine,endLine: c.endLine,tokenCount: c.tokenCount,+ headingPath: c.headingPath,}));const chunkIds = store.replaceChunks(docId, chunkInputs);const links: LinkInput[] = [];for (let i = 0; i < chunkResult.chunks.length; i++) {const cid = chunkIds[i]!;- const extracted = extractLinks(chunkResult.chunks[i]!.content);+ const content = chunkResult.chunks[i]!.content;+ const extracted = extractLinks(content);for (const l of extracted) {links.push({sourceChunkId: cid,@@ -210,6 +213,9 @@ async function indexInto(linkType: l.linkType,});}+ // Entity-boosted retrieval (v0.13.0): persist the chunk's+ // deterministic entity set alongside its links.+ store.replaceEntities(cid, extractEntities(content));}store.replaceLinks(docId, links);diff --git a/src/core/search/mmr.ts b/src/core/search/mmr.tsnew file mode 100644index 00000000..3dd8dfe5--- /dev/null+++ b/src/core/search/mmr.ts@@ -0,0 +1,106 @@+/**+ * Maximal Marginal Relevance diversity rerank.+ *+ * After the fused ranking, near-identical results (paraphrases, the+ * same idea re-chunked) can crowd out complementary content. MMR+ * greedily reselects from the pool, trading each candidate's relevance+ * against its similarity to the already-selected set:+ *+ * argmax over remaining of lambda * rel(d) - (1 - lambda) * max sim(d, s)+ *+ * `rel(d)` reuses the fused `score` (already in [0, 1]). Similarity is+ * a deterministic token-set Jaccard over chunk content - no embedding+ * round-trip, no language word lists, identical on every Syncthing+ * peer. The function is pure: same input, same output.+ */++import type { BrainSearchResult } from "./types.ts";++export interface MmrOptions {+ /**+ * Relevance-vs-diversity tradeoff in [0, 1]. 1 is pure relevance+ * (identity order); lower values diversify harder. Out-of-range or+ * non-finite values clamp into [0, 1].+ */+ readonly lambda: number;+}++/** Unicode-aware token set: lowercased letter/number runs. */+function tokenize(text: string): Set<string> {+ const out = new Set<string>();+ const matches = text.toLowerCase().match(/[\p{L}\p{N}]+/gu);+ if (matches) for (const m of matches) out.add(m);+ return out;+}++/** Jaccard overlap of two token sets, in [0, 1]. */+function jaccard(a: Set<string>, b: Set<string>): number {+ if (a.size === 0 || b.size === 0) return 0;+ let inter = 0;+ const [small, large] = a.size <= b.size ? [a, b] : [b, a];+ for (const t of small) if (large.has(t)) inter++;+ const union = a.size + b.size - inter;+ return union === 0 ? 0 : inter / union;+}++function clampLambda(x: number): number {+ if (!Number.isFinite(x)) return 1;+ if (x < 0) return 0;+ if (x > 1) return 1;+ return x;+}++function withMmrReason(r: BrainSearchResult): BrainSearchResult {+ if (r.reasons.some((x) => x.startsWith("mmr"))) return r;+ return Object.freeze({+ ...r,+ reasons: Object.freeze([...r.reasons, "mmr: reordered"]),+ });+}++/**+ * Reorder `results` (assumed already sorted by fused score desc) using+ * greedy MMR. Returns a new array; results whose final position differs+ * from their input position gain an `"mmr: reordered"` reason. Identity+ * for `lambda == 1` or fewer than two results.+ */+export function mmrRerank(+ results: ReadonlyArray<BrainSearchResult>,+ opts: MmrOptions,+): BrainSearchResult[] {+ const lambda = clampLambda(opts.lambda);+ if (results.length < 2 || lambda >= 1) {+ return results.slice();+ }++ const tokens = results.map((r) => tokenize(r.content));+ const remaining = results.map((_, i) => i);+ const selected: number[] = [];++ while (remaining.length > 0) {+ let bestPos = 0;+ let bestVal = -Infinity;+ for (let k = 0; k < remaining.length; k++) {+ const idx = remaining[k]!;+ let maxSim = 0;+ for (const s of selected) {+ const sim = jaccard(tokens[idx]!, tokens[s]!);+ if (sim > maxSim) maxSim = sim;+ }+ const val = lambda * results[idx]!.score - (1 - lambda) * maxSim;+ // Strict greater keeps the earlier (higher-relevance, since input+ // is score-sorted) candidate on ties - deterministic.+ if (val > bestVal) {+ bestVal = val;+ bestPos = k;+ }+ }+ selected.push(remaining[bestPos]!);+ remaining.splice(bestPos, 1);+ }++ return selected.map((origIdx, finalIdx) => {+ const r = results[origIdx]!;+ return origIdx === finalIdx ? r : withMmrReason(r);+ });+}diff --git a/src/core/search/ranker.ts b/src/core/search/ranker.tsindex c34a832a..161b5fe1 100644--- a/src/core/search/ranker.ts+++ b/src/core/search/ranker.ts@@ -32,6 +32,13 @@ export interface RankerInputs {* bit-identically to pre-tier behaviour.*/readonly tierByDoc?: ReadonlyMap<number, PageTier>;+ /**+ * Optional per-chunk count of query entities the chunk also carries+ * (v0.13.0). Missing entries (and the absent map) contribute zero+ * boost, so the entity layer adds nothing until the index is+ * populated by a reindex.+ */+ readonly entityMatchByChunk?: ReadonlyMap<number, number>;}export interface RankerOptions {@@ -96,6 +103,38 @@ interface Candidate {mtime: number;}+/** Fixed-precision so the same vault yields the same reason strings. */+function fmt(x: number): string {+ return x.toFixed(3);+}++/**+ * Assemble the explainable-recall `reasons` array from the per-layer+ * values the ranker already computed. One entry per layer that fired;+ * a layer contributing exactly zero is omitted so the array stays+ * meaningful. The tier layer is reported only when it is not the+ * neutral 1.0 multiplier.+ */+function buildReasons(parts: {+ keywordScore: number;+ semanticScore: number;+ linkBoost: number;+ recency: number;+ tierMul: number;+ entityBoost?: number;+}): ReadonlyArray<string> {+ const reasons: string[] = [];+ if (parts.keywordScore > 0) reasons.push(`fts5_bm25: ${fmt(parts.keywordScore)}`);+ if (parts.semanticScore > 0) reasons.push(`semantic_cos: ${fmt(parts.semanticScore)}`);+ if (parts.entityBoost && parts.entityBoost > 0) {+ reasons.push(`entity_match: ${fmt(parts.entityBoost)}`);+ }+ if (parts.linkBoost > 0) reasons.push(`link_boost: ${fmt(parts.linkBoost)}`);+ if (parts.recency > 0) reasons.push(`recency: ${fmt(parts.recency)}`);+ if (parts.tierMul !== 1) reasons.push(`tier: ${fmt(parts.tierMul)}`);+ return Object.freeze(reasons);+}+export function rankResults(inputs: RankerInputs, opts: RankerOptions): BrainSearchResult[] {const nowMs = opts.nowMs ?? Date.now();const semanticEnabled = opts.semanticEnabled !== false;@@ -198,7 +237,12 @@ export function rankResults(inputs: RankerInputs, opts: RankerOptions): BrainSea// `supporting` β 1.0 keeps untagged vaults bit-identical.const tier = inputs.tierByDoc?.get(c.documentId) ?? PAGE_TIER_DEFAULT;const tierMul = tierWeight(tier);- const score = clamp01(weighted * tierMul + linkBoost + recency);+ // Entity boost: capped contribution from shared query entities.+ // Per-match 0.02, capped at 0.04 so it only re-ranks an already+ // relevant set - never enough to float an irrelevant chunk.+ const entityMatches = inputs.entityMatchByChunk?.get(c.chunkId) ?? 0;+ const entityBoost = Math.min(0.04, entityMatches * 0.02);+ const score = clamp01(weighted * tierMul + linkBoost + recency + entityBoost);ranked.push(Object.freeze({@@ -215,6 +259,14 @@ export function rankResults(inputs: RankerInputs, opts: RankerOptions): BrainSealinkBoost,recencyBoost: recency,searchType: c.searchType,+ reasons: buildReasons({+ keywordScore: c.keywordScore,+ semanticScore: semanticEnabled ? c.semanticScore : 0,+ linkBoost,+ recency,+ tierMul,+ entityBoost,+ }),}),);}diff --git a/src/core/search/schema.ts b/src/core/search/schema.tsindex 2a17e7bc..8e6b1646 100644--- a/src/core/search/schema.ts+++ b/src/core/search/schema.ts@@ -16,7 +16,7 @@ import { SearchError } from "./types.ts";* this raises `SCHEMA_MISMATCH` on open β the operator must reindex* with a newer binary.*/-export const LATEST_SCHEMA_VERSION = 1;+export const LATEST_SCHEMA_VERSION = 2;const DDL_V1 = `CREATE TABLE IF NOT EXISTS documents (@@ -107,6 +107,65 @@ interface Migration {readonly up: (db: Database) => void;}+/**+ * v2 (v0.13.0) - recall-quality backing store:+ *+ * - parallel `chunk_entities` table feeding entity-boosted retrieval;+ * - `chunks.heading_path` column plus a rebuilt two-column+ * `chunk_fts` (content, heading_path) so a chunk's heading+ * breadcrumb is searchable without polluting the display content.+ *+ * Existing rows carry no entities and an empty heading_path until a+ * reindex repopulates them, so those two layers contribute nothing to+ * scoring until then. (The MMR and traversal recall layers are enabled+ * by default and do change ordering versus prior versions - v0.13.0 is+ * a deliberate ranking change and requires `o2b search reindex`.) The+ * FTS rebuild reindexes whatever chunks already exist against the new+ * column layout.+ */+const DDL_V2_ENTITIES = `+CREATE TABLE IF NOT EXISTS chunk_entities (+ chunk_id INTEGER NOT NULL REFERENCES chunks(id) ON DELETE CASCADE,+ entity TEXT NOT NULL,+ PRIMARY KEY (chunk_id, entity)+);+CREATE INDEX IF NOT EXISTS idx_chunk_entities_entity ON chunk_entities(entity);+`;++// FTS rebuild is split from the column add because `ALTER TABLE ADD+// COLUMN` is not idempotent; the column add is guarded in `up()`.+const DDL_V2_FTS = `+DROP TRIGGER IF EXISTS chunks_ai;+DROP TRIGGER IF EXISTS chunks_ad;+DROP TRIGGER IF EXISTS chunks_au;+DROP TABLE IF EXISTS chunk_fts;++CREATE VIRTUAL TABLE chunk_fts USING fts5(+ content,+ heading_path,+ content='chunks',+ content_rowid='id',+ tokenize='unicode61 remove_diacritics 2'+);++CREATE TRIGGER chunks_ai AFTER INSERT ON chunks BEGIN+ INSERT INTO chunk_fts(rowid, content, heading_path)+ VALUES (new.id, new.content, new.heading_path);+END;+CREATE TRIGGER chunks_ad AFTER DELETE ON chunks BEGIN+ INSERT INTO chunk_fts(chunk_fts, rowid, content, heading_path)+ VALUES('delete', old.id, old.content, old.heading_path);+END;+CREATE TRIGGER chunks_au AFTER UPDATE ON chunks BEGIN+ INSERT INTO chunk_fts(chunk_fts, rowid, content, heading_path)+ VALUES('delete', old.id, old.content, old.heading_path);+ INSERT INTO chunk_fts(rowid, content, heading_path)+ VALUES (new.id, new.content, new.heading_path);+END;++INSERT INTO chunk_fts(chunk_fts) VALUES('rebuild');+`;+export const MIGRATIONS: ReadonlyArray<Migration> = Object.freeze([{version: 1,@@ -114,6 +173,19 @@ export const MIGRATIONS: ReadonlyArray<Migration> = Object.freeze([db.exec(DDL_V1);},},+ {+ version: 2,+ up(db) {+ db.exec(DDL_V2_ENTITIES);+ const cols = db+ .query<{ name: string }, []>("PRAGMA table_info(chunks)")+ .all();+ if (!cols.some((c) => c.name === "heading_path")) {+ db.exec("ALTER TABLE chunks ADD COLUMN heading_path TEXT NOT NULL DEFAULT ''");+ }+ db.exec(DDL_V2_FTS);+ },+ },]);/** Read the current schema version from `index_state`. Returns 0 if not yet recorded. */diff --git a/src/core/search/search.ts b/src/core/search/search.tsindex a54df74a..8a44d247 100644--- a/src/core/search/search.ts+++ b/src/core/search/search.ts@@ -13,9 +13,12 @@ import { join } from "node:path";import { parseFrontmatter } from "../vault.ts";import { makeProvider } from "./embeddings/provider.ts";+import { extractEntities } from "./entities.ts";import { runFtsQuery } from "./fts.ts";+import { mmrRerank } from "./mmr.ts";import { filterByProperties } from "./property-filter.ts";import { rankResults } from "./ranker.ts";+import { expandByTraversal, type TraversalOptions } from "./traversal.ts";import { Store } from "./store.ts";import { SearchError } from "./types.ts";import type {@@ -104,6 +107,15 @@ export async function search(const inboundLinkSources = store.inboundLinkSources(idsList);const tagsByDoc = store.tagsByChunkDocument(idsList);+ // Entity-boosted retrieval (v0.13.0): extract entities from the+ // query and count overlaps with each candidate chunk. Empty when the+ // query names no entities or the index predates the entity store.+ const queryEntities = extractEntities(query);+ const entityMatchByChunk =+ queryEntities.length > 0+ ? store.chunkEntityMatches(idsList, queryEntities)+ : undefined;+// When a property filter is active, overfetch the ranked// candidates so the post-filter result set still has a chance// of producing `limit` matching rows. Without this, the@@ -112,15 +124,28 @@ export async function search(// matches exist deeper in the rank.const hasPropertyFilter =opts.properties !== undefined && opts.properties.size > 0;- const rankLimit = hasPropertyFilter ? Math.max(limit * 5, 50) : limit;- const ranked = rankResults(+ // MMR and traversal both need a candidate pool wider than `limit`:+ // MMR diversifies from it, and traversal seeds expansion from it (a+ // narrow pool lets a high-parent expansion crowd a genuine but+ // lower-ranked hit out of the final window). When both are disabled+ // the pool collapses back to the historical rankLimit.+ const mmrLambda = opts.mmrLambda ?? config.recall.mmrLambda;+ const mmrActive = mmrLambda < 1;+ const maxHops = opts.maxHops ?? config.recall.maxHops;+ const traversalActive = maxHops > 0;+ const baseRankLimit = hasPropertyFilter ? Math.max(limit * 5, 50) : limit;+ const rankLimit =+ mmrActive || traversalActive ? Math.max(baseRankLimit, limit * 3, 30) : baseRankLimit;++ let ranked = rankResults({keyword: kwHits,semantic: semHits,hydrated,inboundLinkSources,tagsByDoc,+ ...(entityMatchByChunk !== undefined ? { entityMatchByChunk } : {}),},{keywordWeight: opts.keywordWeight ?? config.keywordWeight,@@ -130,6 +155,23 @@ export async function search(},);+ // Link-graph traversal (v0.13.0): walk outbound links from the top+ // hits and surface related documents not already matched, scored by+ // decay. No-op when maxHops == 0. Runs before MMR so expansions are+ // subject to the same diversity pass.+ if (traversalActive && ranked.length > 0) {+ ranked = applyTraversal(store, ranked, {+ maxHops,+ hopDecay: config.recall.hopDecay,+ maxExpansionPerHit: config.recall.maxExpansionPerHit,+ });+ }++ // Diversity rerank (v0.13.0). No-op when lambda >= 1 or < 2 results.+ if (mmrActive) {+ ranked = mmrRerank(ranked, { lambda: mmrLambda });+ }+// Optional post-rank property filter (v0.10.17). Reads each// result's source frontmatter and drops rows whose scalars do// not match the requested key/value pairs. Caching by document@@ -152,6 +194,66 @@ export async function search(}}+/**+ * 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,+ );+}+function applyPropertyFilter(ranked: ReadonlyArray<BrainSearchResult>,filters: ReadonlyMap<string, ReadonlyArray<string>>,diff --git a/src/core/search/store.ts b/src/core/search/store.tsindex 8ec6bee5..3d238f18 100644--- a/src/core/search/store.ts+++ b/src/core/search/store.ts@@ -61,6 +61,12 @@ export interface ChunkInput {readonly startLine: number;readonly endLine: number;readonly tokenCount: number;+ /**+ * Heading breadcrumb in effect at the chunk (v0.13.0). Indexed in the+ * dedicated FTS column; defaults to "" so callers that do not supply+ * it (and pre-v0.13.0 fixtures) index an empty heading column.+ */+ readonly headingPath?: string;}export interface ChunkRow {@@ -486,10 +492,10 @@ export class Store {this.db.run("DELETE FROM chunks WHERE document_id = ?", [documentId]);const insert = this.db.prepare<{ id: number },- [number, number, string, string, number, number, number, string, string]+ [number, number, string, string, number, number, number, string, string, string]>(- "INSERT INTO chunks(document_id, chunk_index, content, content_hash, start_line, end_line, token_count, created_at, updated_at) " +- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",+ "INSERT INTO chunks(document_id, chunk_index, content, content_hash, start_line, end_line, token_count, heading_path, created_at, updated_at) " ++ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",);const now = nowIso();for (const c of chunks) {@@ -501,6 +507,7 @@ export class Store {c.startLine,c.endLine,c.tokenCount,+ c.headingPath ?? "",now,now,);@@ -752,7 +759,7 @@ export class Store {{ chunk_id: number; document_id: number; bm25: number },[string, string, string, number]>(- "SELECT c.id AS chunk_id, c.document_id AS document_id, bm25(chunk_fts) AS bm25 " ++ "SELECT c.id AS chunk_id, c.document_id AS document_id, bm25(chunk_fts, 1.0, 0.3) AS bm25 " +"FROM chunk_fts " +"JOIN chunks c ON c.id = chunk_fts.rowid " +"JOIN documents d ON d.id = c.document_id " +@@ -765,7 +772,7 @@ export class Store {const rows = this.db.query<{ chunk_id: number; document_id: number; bm25: number }, [string, number]>(- "SELECT c.id AS chunk_id, c.document_id AS document_id, bm25(chunk_fts) AS bm25 " ++ "SELECT c.id AS chunk_id, c.document_id AS document_id, bm25(chunk_fts, 1.0, 0.3) AS bm25 " +"FROM chunk_fts JOIN chunks c ON c.id = chunk_fts.rowid " +"WHERE chunk_fts MATCH ? ORDER BY bm25 ASC LIMIT ?",)@@ -892,6 +899,140 @@ export class Store {return out;}+ /**+ * For each source document id, the list of resolved outbound link+ * target document ids (wikilink / markdown_link only; tags and+ * unresolved targets excluded; self-links dropped). Used by the+ * recall traversal layer to walk one or more hops out from a hit.+ */+ outboundLinkTargets(sourceDocumentIds: ReadonlyArray<number>): Map<number, number[]> {+ const out = new Map<number, number[]>();+ if (sourceDocumentIds.length === 0) return out;+ const placeholders = sourceDocumentIds.map(() => "?").join(",");+ const rows = this.db+ .query<+ { source_document_id: number; target_document_id: number },+ number[]+ >(+ "SELECT DISTINCT l.source_document_id, l.target_document_id " ++ `FROM links l ` ++ `WHERE l.source_document_id IN (${placeholders}) ` ++ ` AND l.target_document_id IS NOT NULL ` ++ ` AND l.target_document_id != l.source_document_id ` ++ ` AND l.link_type IN ('wikilink','markdown_link') ` ++ `ORDER BY l.source_document_id, l.target_document_id`,+ )+ .all(...(sourceDocumentIds as number[]));+ for (const r of rows) {+ let list = out.get(r.source_document_id);+ if (!list) {+ list = [];+ out.set(r.source_document_id, list);+ }+ list.push(r.target_document_id);+ }+ return out;+ }++ /**+ * One representative chunk per document - the lowest `chunk_index`,+ * which for markdown is the document head (title / opening section).+ * The traversal layer surfaces this when a linked document is not+ * already a relevance hit.+ */+ representativeChunks(documentIds: ReadonlyArray<number>): Map<number, HydratedChunk> {+ const out = new Map<number, HydratedChunk>();+ if (documentIds.length === 0) return out;+ const placeholders = documentIds.map(() => "?").join(",");+ const rows = this.db+ .query<+ {+ chunk_id: number;+ document_id: number;+ path: string;+ title: string | null;+ content: string;+ start_line: number;+ end_line: number;+ mtime: number;+ },+ number[]+ >(+ "SELECT c.id AS chunk_id, c.document_id AS document_id, d.path AS path, " ++ "d.title AS title, c.content AS content, c.start_line AS start_line, " ++ "c.end_line AS end_line, d.mtime AS mtime " ++ "FROM chunks c JOIN documents d ON d.id = c.document_id " ++ `WHERE c.document_id IN (${placeholders}) ` ++ "ORDER BY c.document_id, c.chunk_index ASC",+ )+ .all(...(documentIds as number[]));+ for (const r of rows) {+ if (out.has(r.document_id)) continue; // first row per doc = lowest chunk_index+ out.set(+ r.document_id,+ Object.freeze({+ chunkId: r.chunk_id,+ documentId: r.document_id,+ path: r.path,+ title: r.title,+ content: r.content,+ startLine: r.start_line,+ endLine: r.end_line,+ mtime: r.mtime,+ }),+ );+ }+ return out;+ }++ // ββ entities βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++ /**+ * Replace a chunk's entity set (v0.13.0). Deletes any prior entries+ * for the chunk, then inserts the deduped list. Entities are expected+ * pre-normalised (lowercased) by the extractor.+ */+ replaceEntities(chunkId: number, entities: ReadonlyArray<string>): void {+ this.db.exec("BEGIN");+ try {+ this.db.run("DELETE FROM chunk_entities WHERE chunk_id = ?", [chunkId]);+ if (entities.length > 0) {+ const insert = this.db.prepare<undefined, [number, string]>(+ "INSERT OR IGNORE INTO chunk_entities(chunk_id, entity) VALUES (?, ?)",+ );+ for (const e of entities) insert.run(chunkId, e);+ }+ this.db.exec("COMMIT");+ } catch (e) {+ this.db.exec("ROLLBACK");+ throw e;+ }+ }++ /**+ * For each candidate chunk, the count of distinct query entities it+ * also carries. Empty `queryEntities` yields an empty map (no work).+ * Pure read; used by the ranker to add a capped entity boost.+ */+ chunkEntityMatches(+ candidateChunkIds: ReadonlyArray<number>,+ queryEntities: ReadonlyArray<string>,+ ): Map<number, number> {+ const out = new Map<number, number>();+ if (candidateChunkIds.length === 0 || queryEntities.length === 0) return out;+ const chunkPlaceholders = candidateChunkIds.map(() => "?").join(",");+ const entityPlaceholders = queryEntities.map(() => "?").join(",");+ const rows = this.db+ .query<{ chunk_id: number; c: number }, (number | string)[]>(+ "SELECT chunk_id, COUNT(DISTINCT entity) AS c FROM chunk_entities " ++ `WHERE chunk_id IN (${chunkPlaceholders}) AND entity IN (${entityPlaceholders}) ` ++ "GROUP BY chunk_id",+ )+ .all(...(candidateChunkIds as number[]), ...(queryEntities as string[]));+ for (const r of rows) out.set(r.chunk_id, r.c);+ return out;+ }+/*** For each chunk id, the set of tag link_text values associated with* its document. Two chunks "share a tag" iff their tag sets intersect.diff --git a/src/core/search/traversal.ts b/src/core/search/traversal.tsnew file mode 100644index 00000000..1de9175a--- /dev/null+++ b/src/core/search/traversal.ts@@ -0,0 +1,159 @@+/**+ * Link-graph traversal during recall.+ *+ * Relevance ranking answers "which documents match the query". This+ * second stage answers "what is one or two hops away from a strong+ * match" - common in vault workflows where one principle links to+ * several application notes. For each top hit we follow outbound+ * wikilinks, surfacing linked documents scored as+ * `parent_score * hop_decay^hop`, deduped against the existing result+ * set (an already-present document keeps its higher relevance score).+ *+ * Pure function: `search.ts` precomputes the outbound adjacency and a+ * representative chunk per document; this module does the bounded walk+ * and scoring. No I/O.+ */++import type { BrainSearchResult } from "./types.ts";++/** Representative chunk of an expansion document (one per documentId). */+export interface TraversalDoc {+ readonly documentId: number;+ readonly chunkId: number;+ readonly path: string;+ readonly title: string | null;+ readonly content: string;+ readonly startLine: number;+ readonly endLine: number;+}++export interface TraversalInputs {+ /** Relevance-ranked results, sorted by score descending. */+ readonly ranked: ReadonlyArray<BrainSearchResult>;+ /** documentId -> outbound-linked documentIds (resolved targets). */+ readonly outbound: ReadonlyMap<number, ReadonlyArray<number>>;+ /** Representative chunk for an expansion document, or null if absent. */+ readonly expansionDoc: (documentId: number) => TraversalDoc | null;+}++export interface TraversalOptions {+ /** Maximum hop depth. 0 disables traversal (identity). */+ readonly maxHops: number;+ /** Per-hop score multiplier in (0, 1]. */+ readonly hopDecay: number;+ /** Cap on links followed per node. */+ readonly maxExpansionPerHit: number;+}++/** Hard ceiling on seed hits we expand from, to keep recall bounded. */+const MAX_SEEDS = 10;++function makeLinkResult(+ doc: TraversalDoc,+ score: number,+ hop: number,+ fromPath: string,+): BrainSearchResult {+ return Object.freeze({+ documentId: doc.documentId,+ chunkId: doc.chunkId,+ path: doc.path,+ title: doc.title,+ content: doc.content,+ startLine: doc.startLine,+ endLine: doc.endLine,+ score,+ keywordScore: 0,+ semanticScore: 0,+ linkBoost: 0,+ recencyBoost: 0,+ searchType: "link" as const,+ reasons: Object.freeze([`link_traversal: hop ${hop} from ${fromPath}`]),+ });+}++/**+ * Expand the ranked set by walking outbound links. Returns a new array+ * (ranked results first, then deduped expansions) re-sorted by score+ * descending. Identity when `maxHops <= 0` or there is nothing to walk.+ */+export function expandByTraversal(+ inputs: TraversalInputs,+ opts: TraversalOptions,+): BrainSearchResult[] {+ if (opts.maxHops <= 0 || inputs.ranked.length === 0) {+ return inputs.ranked.slice();+ }+ const decay = opts.hopDecay > 0 && opts.hopDecay <= 1 ? opts.hopDecay : 1;+ const perHit = Math.max(0, opts.maxExpansionPerHit | 0);+ if (perHit === 0) return inputs.ranked.slice();++ // Documents already represented by a relevance hit must never be+ // replaced by a lower-scored traversal copy.+ const present = new Set<number>();+ for (const r of inputs.ranked) present.add(r.documentId);++ // Best traversal score per newly-surfaced document (dedup; keep max).+ const added = new Map<number, BrainSearchResult>();++ // BFS frontier of (documentId, hop, score). Seeds are the top hits.+ interface Node {+ readonly documentId: number;+ readonly hop: number;+ readonly score: number;+ readonly fromPath: string;+ }+ const queue: Node[] = [];+ for (const seed of inputs.ranked.slice(0, MAX_SEEDS)) {+ queue.push({+ documentId: seed.documentId,+ hop: 0,+ score: seed.score,+ fromPath: seed.path,+ });+ }++ while (queue.length > 0) {+ const node = queue.shift()!;+ if (node.hop >= opts.maxHops) continue;+ const targets = inputs.outbound.get(node.documentId);+ if (!targets || targets.length === 0) continue;+ let expanded = 0;+ for (const targetId of targets) {+ if (expanded >= perHit) break;+ if (targetId === node.documentId || present.has(targetId)) continue;+ const hopScore = node.score * decay;+ const existing = added.get(targetId);+ if (existing && existing.score >= hopScore) {+ // Already surfaced at an equal-or-better score; do not enqueue+ // a weaker path again (keeps the walk terminating).+ continue;+ }+ const doc = inputs.expansionDoc(targetId);+ if (!doc) continue;+ // Count only expansions that actually surface a document, so a+ // skipped target (dup / weaker path / missing chunk) does not burn+ // the per-hit budget and starve a valid later target.+ expanded++;+ added.set(+ targetId,+ makeLinkResult(doc, hopScore, node.hop + 1, node.fromPath),+ );+ queue.push({+ documentId: targetId,+ hop: node.hop + 1,+ score: hopScore,+ fromPath: doc.path,+ });+ }+ }++ if (added.size === 0) return inputs.ranked.slice();++ const merged = [...inputs.ranked, ...added.values()];+ merged.sort((a, b) => {+ if (b.score !== a.score) return b.score - a.score;+ return a.chunkId - b.chunkId;+ });+ return merged;+}diff --git a/src/core/search/types.ts b/src/core/search/types.tsindex 647b80ba..775ad12b 100644--- a/src/core/search/types.ts+++ b/src/core/search/types.ts@@ -45,7 +45,14 @@ export interface BrainSearchResult {readonly semanticScore: number;readonly linkBoost: number;readonly recencyBoost: number;- readonly searchType: "keyword" | "semantic" | "hybrid";+ readonly searchType: "keyword" | "semantic" | "hybrid" | "link";+ /**+ * Explainable recall: one entry per scoring layer that contributed+ * to `score`, formatted `"<layer>: <fixed-precision value>"`. Layers+ * that did not fire (zero contribution) are omitted. Always present;+ * never empty for a result that surfaced.+ */+ readonly reasons: ReadonlyArray<string>;}export interface IndexStats {@@ -122,6 +129,16 @@ export interface SearchOptions {* filter (existing behaviour).*/readonly properties?: ReadonlyMap<string, ReadonlyArray<string>>;+ /**+ * Per-query MMR override (v0.13.0). Absent uses the resolved config+ * default; `1` disables diversification for this query.+ */+ readonly mmrLambda?: number;+ /**+ * Per-query link-graph traversal depth (v0.13.0). Absent uses the+ * resolved config default; `0` disables traversal for this query.+ */+ readonly maxHops?: number;}export interface SearchOutcome {@@ -142,6 +159,23 @@ export interface ResolvedEmbeddingConfig {readonly batchSize: number;}+/**+ * Recall-quality tunables (v0.13.0). Each layer is bounded and+ * deterministic; the defaults enable the layer while leaving a clear+ * off switch (`mmrLambda = 1`, `maxHops = 0`). A vault that never opts+ * out ranks by the documented defaults.+ */+export interface ResolvedRecallConfig {+ /** MMR relevance-vs-diversity tradeoff in [0, 1]; 1 disables MMR. */+ readonly mmrLambda: number;+ /** Link-graph traversal hop depth during recall; 0 disables. */+ readonly maxHops: number;+ /** Per-hop score multiplier in (0, 1]. */+ readonly hopDecay: number;+ /** Cap on outbound links followed per node. */+ readonly maxExpansionPerHit: number;+}+export interface ResolvedSearchConfig {readonly vault: string;readonly dbPath: string;@@ -160,4 +194,5 @@ export interface ResolvedSearchConfig {readonly keywordWeight: number;readonly semanticWeight: number;readonly semantic: ResolvedEmbeddingConfig;+ readonly recall: ResolvedRecallConfig;}diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.tsindex 06cc513e..89aab885 100644--- a/src/mcp/search-tools.ts+++ b/src/mcp/search-tools.ts@@ -191,6 +191,7 @@ async function toolBrainSearch(startLine: r.startLine,endLine: r.endLine,searchType: r.searchType,+ reasons: r.reasons,})),warnings: outcome.warnings,total: outcome.total,diff --git a/tests/cli/search.test.ts b/tests/cli/search.test.tsindex 4ef10583..bf2e450e 100644--- a/tests/cli/search.test.ts+++ b/tests/cli/search.test.ts@@ -69,7 +69,7 @@ test("search status --json after an index returns documents count", async () =>const obj = JSON.parse(out.stdout);expect(obj.exists).toBe(true);expect(obj.documents).toBe(2);- expect(obj.schema_version).toBe(1);+ expect(obj.schema_version).toBe(2);});test("search query returns a human-readable hit for indexed content", async () => {diff --git a/tests/core/search/chunker-heading-path.test.ts b/tests/core/search/chunker-heading-path.test.tsnew file mode 100644index 00000000..20768f42--- /dev/null+++ b/tests/core/search/chunker-heading-path.test.ts@@ -0,0 +1,71 @@+/**+ * Header-anchored chunking: each chunk carries the breadcrumb of the+ * headings in effect at its start ("Top > Section A"), so a mid-document+ * chunk that split off from its section still records its topical+ * anchor. The breadcrumb is metadata - it never appears in the chunk's+ * display content.+ */++import { test, expect } from "bun:test";++import { chunkMarkdown } from "../../../src/core/search/chunker.ts";++test("chunks carry the ancestor heading breadcrumb", () => {+ const md = [+ "# Top",+ "",+ "Intro paragraph under the top heading.",+ "",+ "## Section A",+ "",+ "Body text that lives under section A and should be anchored.",+ "",+ "## Section B",+ "",+ "Different body under section B.",+ ].join("\n");++ // Small token budget forces each section to split into its own chunk+ // so a body chunk is anchored by its heading rather than swallowing+ // the whole document into one chunk.+ const { chunks } = chunkMarkdown(md, "doc", { maxTokens: 8, minTokens: 1, overlapTokens: 0 });+ expect(chunks.length).toBeGreaterThan(0);+ for (const c of chunks) {+ expect(typeof c.headingPath).toBe("string");+ }+ // The chunk containing Section A body is anchored under Top > Section A.+ const aChunk = chunks.find((c) => c.content.includes("under section A"));+ expect(aChunk).toBeDefined();+ expect(aChunk!.headingPath).toBe("Top > Section A");+ // Section B body is anchored under Top > Section B.+ const bChunk = chunks.find((c) => c.content.includes("under section B"));+ expect(bChunk!.headingPath).toBe("Top > Section B");+});++test("a document with no headings yields an empty breadcrumb", () => {+ const { chunks } = chunkMarkdown("Just a flat paragraph with no headings at all.", "flat");+ expect(chunks.length).toBeGreaterThan(0);+ expect(chunks[0]!.headingPath).toBe("");+});++test("breadcrumb pops to the correct level when heading depth decreases", () => {+ const md = [+ "# Root",+ "",+ "## Child",+ "",+ "### Grandchild",+ "",+ "deep content here",+ "",+ "## Sibling",+ "",+ "sibling content here",+ ].join("\n");+ const { chunks } = chunkMarkdown(md, "doc", { maxTokens: 8, minTokens: 1, overlapTokens: 0 });+ const deep = chunks.find((c) => c.content.includes("deep content"));+ expect(deep!.headingPath).toBe("Root > Child > Grandchild");+ const sibling = chunks.find((c) => c.content.includes("sibling content"));+ // The deeper "Grandchild" must have been popped when "## Sibling" opened.+ expect(sibling!.headingPath).toBe("Root > Sibling");+});diff --git a/tests/core/search/entities.test.ts b/tests/core/search/entities.test.tsnew file mode 100644index 00000000..f08fcf4b--- /dev/null+++ b/tests/core/search/entities.test.ts@@ -0,0 +1,56 @@+/**+ * Deterministic, language-agnostic entity extraction. Candidates come+ * from structural Unicode cues only - wikilink targets/aliases, quoted+ * spans, capitalized token runs, CamelCase, ALLCAPS, and digit-bearing+ * tokens. No NER dependency, no per-language word list, so extraction+ * is identical across locales and bit-stable across Syncthing peers.+ */++import { test, expect } from "bun:test";++import { extractEntities } from "../../../src/core/search/entities.ts";++test("extracts a capitalized multi-word run", () => {+ const e = extractEntities("Open Second Brain ships a recall suite.");+ expect(e).toContain("open second brain");+});++test("extracts wikilink target and alias display text", () => {+ const e = extractEntities("See [[Pay Memory]] and [[notes/ledger.md|Receipt Ledger]].");+ expect(e).toContain("pay memory");+ expect(e).toContain("receipt ledger");+});++test("extracts CamelCase identifiers", () => {+ const e = extractEntities("Route every write through writePreferenceTxn please.");+ expect(e).toContain("writepreferencetxn");+});++test("extracts ALLCAPS acronyms and digit-bearing tokens", () => {+ const e = extractEntities("It fuses FTS5 keyword scoring with MMR diversity.");+ expect(e).toContain("fts5");+ expect(e).toContain("mmr");+});++test("extracts a double-quoted span", () => {+ const e = extractEntities('The term "second brain" matters here.');+ expect(e).toContain("second brain");+});++test("uses Unicode categories, not an English word list (Cyrillic name)", () => {+ const e = extractEntities("ΠΠ²ΡΠΎΡ Π‘Π΅ΡΠ³Π΅ΠΉ ΠΏΠΈΡΠ΅Ρ ΠΊΠΎΠ΄.");+ expect(e).toContain("ΡΠ΅ΡΠ³Π΅ΠΉ");+});++test("dedupes and drops single-character noise", () => {+ const e = extractEntities(+ "Alpha runs first. Alpha runs again. Open Second Brain ships, then Open Second Brain ships once more. A lone letter.",+ );+ expect(e.filter((x) => x === "alpha")).toHaveLength(1);+ expect(e).not.toContain("a");+ expect(e.filter((x) => x === "open second brain")).toHaveLength(1);+});++test("returns a frozen array", () => {+ expect(Object.isFrozen(extractEntities("Open Second Brain"))).toBe(true);+});diff --git a/tests/core/search/entity-boost-recall.test.ts b/tests/core/search/entity-boost-recall.test.tsnew file mode 100644index 00000000..c6c630cc--- /dev/null+++ b/tests/core/search/entity-boost-recall.test.ts@@ -0,0 +1,50 @@+/**+ * End-to-end entity-boosted retrieval: among two documents that match+ * the query's keyword equally, the one that also names the query's+ * entity ranks higher and exposes an entity_match reason.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, writeFileSync } from "node:fs";+import { join } from "node:path";++import { indexVault, search } from "../../../src/core/search/index.ts";+import { makeConfig, createTempVault } from "../../helpers/search-fixtures.ts";++let tmp: ReturnType<typeof createTempVault>;++beforeEach(async () => {+ tmp = createTempVault("entity-boost");+ mkdirSync(join(tmp.vault, "notes"), { recursive: true });+ // Both notes contain the keyword tokens (payment, pay, memory) so the+ // FTS AND-query retrieves both equally. Only with-entity names the+ // capitalized entity "Pay Memory"; plain uses the same words in lower+ // case, so only with-entity carries the entity the query also names.+ writeFileSync(+ join(tmp.vault, "notes", "with-entity.md"),+ "---\ntitle: With Entity\n---\n\nThe payment flow runs through Pay Memory to pay memory costs.\n",+ );+ writeFileSync(+ join(tmp.vault, "notes", "plain.md"),+ "---\ntitle: Plain\n---\n\nThe payment system will pay memory fees generically on demand.\n",+ );+ const config = makeConfig({ vault: tmp.vault, dbPath: tmp.dbPath, maxHops: 0 });+ await indexVault(config, {});+});++afterEach(() => {+ tmp.cleanup();+});++test("a doc naming the query entity ranks above an equal keyword-only doc", async () => {+ // maxHops 0 isolates the entity signal from traversal.+ const config = makeConfig({ vault: tmp.vault, dbPath: tmp.dbPath, maxHops: 0 });+ const out = await search(config, { query: "payment Pay Memory", limit: 10 });+ const withEntity = out.results.findIndex((r) => r.path === "notes/with-entity.md");+ const plain = out.results.findIndex((r) => r.path === "notes/plain.md");+ expect(withEntity).toBeGreaterThanOrEqual(0);+ expect(plain).toBeGreaterThanOrEqual(0);+ expect(withEntity).toBeLessThan(plain); // entity doc ranks first+ const top = out.results[withEntity]!;+ expect(top.reasons.some((x) => x.startsWith("entity_match"))).toBe(true);+});diff --git a/tests/core/search/heading-anchored-recall.test.ts b/tests/core/search/heading-anchored-recall.test.tsnew file mode 100644index 00000000..0689c735--- /dev/null+++ b/tests/core/search/heading-anchored-recall.test.ts@@ -0,0 +1,49 @@+/**+ * End-to-end header-anchored chunking: a query whose terms appear only+ * in a chunk's heading breadcrumb (not its body) still recalls the+ * chunk via the dedicated heading FTS column - and the heading text+ * never leaks into the returned display content.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, writeFileSync } from "node:fs";+import { join } from "node:path";++import { indexVault, search } from "../../../src/core/search/index.ts";+import { makeConfig, createTempVault } from "../../helpers/search-fixtures.ts";++let tmp: ReturnType<typeof createTempVault>;++beforeEach(async () => {+ tmp = createTempVault("heading-recall");+ mkdirSync(join(tmp.vault, "notes"), { recursive: true });+ // A long section whose later chunk's body never repeats the heading+ // word "Kingfisher"; only the heading carries it.+ // Long enough (> default 800-token chunk budget) to split into+ // multiple chunks, so later chunks carry no heading word in their body.+ const body = Array.from(+ { length: 220 },+ (_, i) => `Sentence number ${i} about diving and water.`,+ ).join("\n\n");+ writeFileSync(+ join(tmp.vault, "notes", "birds.md"),+ `---\ntitle: Birds\n---\n\n# Kingfisher\n\n${body}\n`,+ );+ const config = makeConfig({ vault: tmp.vault, dbPath: tmp.dbPath, maxHops: 0 });+ await indexVault(config, {});+});++afterEach(() => {+ tmp.cleanup();+});++test("a chunk is recalled by a heading-only term and content stays clean", async () => {+ const config = makeConfig({ vault: tmp.vault, dbPath: tmp.dbPath, maxHops: 0 });+ const out = await search(config, { query: "Kingfisher diving", limit: 20 });+ expect(out.results.length).toBeGreaterThan(0);+ // At least one recalled chunk's body does NOT contain the heading word,+ // proving the match came from the heading_path column rather than the+ // body - and that the breadcrumb is not appended to display content.+ const headingOnly = out.results.find((r) => !r.content.includes("Kingfisher"));+ expect(headingOnly).toBeDefined();+});diff --git a/tests/core/search/indexer.test.ts b/tests/core/search/indexer.test.tsindex d293e5e1..32a8da59 100644--- a/tests/core/search/indexer.test.ts+++ b/tests/core/search/indexer.test.ts@@ -94,7 +94,7 @@ test("indexStatus reports accurate counts after an index run", async () => {const status = await indexStatus(cfg);expect(status.exists).toBe(true);- expect(status.schemaVersion).toBe(1);+ expect(status.schemaVersion).toBe(2);expect(status.documents).toBe(2);expect(status.chunks).toBeGreaterThanOrEqual(2);expect(status.lastIndexedAt).toBeTruthy();diff --git a/tests/core/search/mmr.test.ts b/tests/core/search/mmr.test.tsnew file mode 100644index 00000000..a8794145--- /dev/null+++ b/tests/core/search/mmr.test.ts@@ -0,0 +1,79 @@+/**+ * MMR diversity rerank. Greedy Maximal Marginal Relevance over the+ * fused result pool so near-identical paraphrases don't crowd out+ * complementary content. Similarity is a deterministic token-set+ * Jaccard over chunk content; relevance reuses the fused `score`.+ */++import { test, expect } from "bun:test";++import { mmrRerank } from "../../../src/core/search/mmr.ts";+import type { BrainSearchResult } from "../../../src/core/search/types.ts";++let nextId = 1;+function res(content: string, score: number): BrainSearchResult {+ const id = nextId++;+ return Object.freeze({+ documentId: id,+ chunkId: id,+ path: `doc${id}.md`,+ title: `Doc ${id}`,+ content,+ startLine: 1,+ endLine: 1,+ score,+ keywordScore: score,+ semanticScore: 0,+ linkBoost: 0,+ recencyBoost: 0,+ searchType: "keyword" as const,+ reasons: Object.freeze([`fts5_bm25: ${score.toFixed(3)}`]),+ });+}++test("lambda == 1 preserves input order (pure relevance)", () => {+ const input = [res("alpha beta", 0.9), res("alpha beta gamma", 0.85), res("zeta", 0.8)];+ const out = mmrRerank(input, { lambda: 1 });+ expect(out.map((r) => r.chunkId)).toEqual(input.map((r) => r.chunkId));+});++test("fewer than two results is identity", () => {+ const a = res("solo", 0.5);+ expect(mmrRerank([a], { lambda: 0.5 })).toEqual([a]);+ expect(mmrRerank([], { lambda: 0.5 })).toEqual([]);+});++test("near-duplicate of the top hit is demoted below a dissimilar lower-relevance hit", () => {+ const top = res("alpha beta gamma", 0.9);+ const dup = res("alpha beta gamma delta", 0.85); // 0.75 Jaccard with top+ const diverse = res("zeta eta theta", 0.8); // disjoint from top+ const out = mmrRerank([top, dup, diverse], { lambda: 0.5 });+ const order = out.map((r) => r.chunkId);+ expect(order[0]).toBe(top.chunkId); // highest relevance picked first+ expect(order[1]).toBe(diverse.chunkId); // diversity beats the near-dup+ expect(order[2]).toBe(dup.chunkId);+});++test("is deterministic across repeated runs", () => {+ const mk = () => [+ res("alpha beta gamma", 0.9),+ res("alpha beta gamma delta", 0.85),+ res("zeta eta theta", 0.8),+ ];+ // Same logical input β same output ordering by content.+ const a = mmrRerank(mk(), { lambda: 0.5 }).map((r) => r.content);+ const b = mmrRerank(mk(), { lambda: 0.5 }).map((r) => r.content);+ expect(a).toEqual(b);+});++test("a result reordered by MMR carries an mmr reason", () => {+ const top = res("alpha beta gamma", 0.9);+ const dup = res("alpha beta gamma delta", 0.85);+ const diverse = res("zeta eta theta", 0.8);+ const out = mmrRerank([top, dup, diverse], { lambda: 0.5 });+ const movedDup = out.find((r) => r.chunkId === dup.chunkId)!;+ expect(movedDup.reasons.some((x) => x.startsWith("mmr"))).toBe(true);+ // The untouched top result keeps its original reasons unchanged.+ const stayedTop = out.find((r) => r.chunkId === top.chunkId)!;+ expect(stayedTop.reasons.some((x) => x.startsWith("mmr"))).toBe(false);+});diff --git a/tests/core/search/ranker-entity-boost.test.ts b/tests/core/search/ranker-entity-boost.test.tsnew file mode 100644index 00000000..bb9ae1cb--- /dev/null+++ b/tests/core/search/ranker-entity-boost.test.ts@@ -0,0 +1,83 @@+/**+ * Entity-boosted ranking: when a candidate chunk shares entities with+ * the query, the ranker adds a small capped boost and records an+ * entity_match reason. With no entity-match map (or zero matches),+ * ranking is bit-identical to pre-entity behaviour.+ */++import { test, expect } from "bun:test";++import { rankResults } from "../../../src/core/search/ranker.ts";+import type {+ KeywordHit,+ HydratedChunk,+} from "../../../src/core/search/store.ts";++function hyd(chunkId: number, docId: number): HydratedChunk {+ return Object.freeze({+ chunkId,+ documentId: docId,+ path: `doc${docId}.md`,+ title: `Doc ${docId}`,+ content: `chunk ${chunkId}`,+ startLine: 1,+ endLine: 1,+ mtime: 0,+ });+}++const NOW = 1_750_000_000_000;++function baseInputs() {+ return {+ keyword: [+ { chunkId: 1, documentId: 10, bm25: -5 },+ { chunkId: 2, documentId: 11, bm25: -5 },+ ] as KeywordHit[],+ semantic: [],+ hydrated: new Map([+ [1, hyd(1, 10)],+ [2, hyd(2, 11)],+ ]),+ inboundLinkSources: new Map(),+ tagsByDoc: new Map(),+ };+}++test("a chunk with entity matches scores above an equal chunk without", () => {+ const ranked = rankResults(+ { ...baseInputs(), entityMatchByChunk: new Map([[2, 2]]) },+ { keywordWeight: 0.6, semanticWeight: 0.4, limit: 10, nowMs: NOW },+ );+ const one = ranked.find((r) => r.chunkId === 1)!;+ const two = ranked.find((r) => r.chunkId === 2)!;+ // Same bm25, but chunk 2 carries the entity boost.+ expect(two.score).toBeGreaterThan(one.score);+ expect(two.reasons.some((x) => x.startsWith("entity_match"))).toBe(true);+ expect(one.reasons.some((x) => x.startsWith("entity_match"))).toBe(false);+});++test("entity boost is capped regardless of match count", () => {+ const ranked = rankResults(+ { ...baseInputs(), entityMatchByChunk: new Map([[1, 50]]) },+ { keywordWeight: 0.6, semanticWeight: 0.4, limit: 10, nowMs: NOW },+ );+ const one = ranked.find((r) => r.chunkId === 1)!;+ // bm25 normalises to 1.0 here; with the cap the score stays <= 1.+ expect(one.score).toBeLessThanOrEqual(1);+ expect(one.score).toBeGreaterThan(0.6 * 1); // boosted above pure keyword+});++test("no entity-match map leaves scores bit-identical to pre-entity ranking", () => {+ const withoutArg = rankResults(baseInputs(), {+ keywordWeight: 0.6,+ semanticWeight: 0.4,+ limit: 10,+ nowMs: NOW,+ });+ const withEmpty = rankResults(+ { ...baseInputs(), entityMatchByChunk: new Map() },+ { keywordWeight: 0.6, semanticWeight: 0.4, limit: 10, nowMs: NOW },+ );+ expect(withEmpty.map((r) => r.score)).toEqual(withoutArg.map((r) => r.score));+});diff --git a/tests/core/search/ranker-reasons.test.ts b/tests/core/search/ranker-reasons.test.tsnew file mode 100644index 00000000..3682a326--- /dev/null+++ b/tests/core/search/ranker-reasons.test.ts@@ -0,0 +1,134 @@+/**+ * Explainable recall: every ranked result carries a `reasons` array,+ * one entry per scoring layer that actually contributed. Pure exposure+ * of the values `rankResults` already computes - no new ranking logic.+ */++import { test, expect } from "bun:test";++import { rankResults } from "../../../src/core/search/ranker.ts";+import type {+ KeywordHit,+ SemanticHit,+ HydratedChunk,+} from "../../../src/core/search/store.ts";++function hyd(chunkId: number, docId: number, mtime: number): HydratedChunk {+ return Object.freeze({+ chunkId,+ documentId: docId,+ path: `doc${docId}.md`,+ title: `Doc ${docId}`,+ content: `chunk ${chunkId}`,+ startLine: 1,+ endLine: 1,+ mtime,+ });+}++const NOW = 1_750_000_000_000;+const RECENT = NOW / 1000 - 3 * 24 * 3600; // ~0.05 recency+const OLD = NOW / 1000 - 365 * 24 * 3600; // 0 recency++function reasonLayers(reasons: ReadonlyArray<string>): string[] {+ return reasons.map((r) => r.split(":")[0]!.trim());+}++test("keyword-only hit lists exactly the fts5_bm25 layer", () => {+ const ranked = rankResults(+ {+ keyword: [{ chunkId: 1, documentId: 10, bm25: -5 }] as KeywordHit[],+ semantic: [] as SemanticHit[],+ hydrated: new Map([[1, hyd(1, 10, OLD)]]),+ inboundLinkSources: new Map(),+ tagsByDoc: new Map(),+ },+ { keywordWeight: 0.6, semanticWeight: 0.4, limit: 10, nowMs: NOW },+ );+ const r = ranked.find((x) => x.chunkId === 1)!;+ expect(Array.isArray(r.reasons)).toBe(true);+ expect(reasonLayers(r.reasons)).toEqual(["fts5_bm25"]);+});++test("hybrid hit lists both keyword and semantic layers", () => {+ const ranked = rankResults(+ {+ keyword: [{ chunkId: 2, documentId: 11, bm25: -3 }] as KeywordHit[],+ semantic: [{ chunkId: 2, documentId: 11, distance: 0.3 }] as SemanticHit[],+ hydrated: new Map([[2, hyd(2, 11, OLD)]]),+ inboundLinkSources: new Map(),+ tagsByDoc: new Map(),+ },+ { keywordWeight: 0.6, semanticWeight: 0.4, limit: 10, nowMs: NOW },+ );+ const r = ranked.find((x) => x.chunkId === 2)!;+ const layers = reasonLayers(r.reasons);+ expect(layers).toContain("fts5_bm25");+ expect(layers).toContain("semantic_cos");+});++test("recent + linked hit also lists link and recency layers", () => {+ // Two candidate docs that link to each other so the inbound link boost+ // fires; both recent so recency fires.+ const ranked = rankResults(+ {+ keyword: [+ { chunkId: 1, documentId: 10, bm25: -5 },+ { chunkId: 2, documentId: 11, bm25: -5 },+ ] as KeywordHit[],+ semantic: [] as SemanticHit[],+ hydrated: new Map([+ [1, hyd(1, 10, RECENT)],+ [2, hyd(2, 11, RECENT)],+ ]),+ // doc 11 links to chunk 1's doc (10) and vice-versa.+ inboundLinkSources: new Map([+ [1, new Set([11])],+ [2, new Set([10])],+ ]),+ tagsByDoc: new Map(),+ },+ { keywordWeight: 0.6, semanticWeight: 0.4, limit: 10, nowMs: NOW },+ );+ const r = ranked.find((x) => x.chunkId === 1)!;+ const layers = reasonLayers(r.reasons);+ expect(layers).toContain("fts5_bm25");+ expect(layers).toContain("link_boost");+ expect(layers).toContain("recency");+});++test("semantic layer omitted when its contribution is zero", () => {+ // semanticEnabled false β semantic score forced to 0 β no semantic reason.+ const ranked = rankResults(+ {+ keyword: [{ chunkId: 1, documentId: 10, bm25: -5 }] as KeywordHit[],+ semantic: [{ chunkId: 1, documentId: 10, distance: 0.1 }] as SemanticHit[],+ hydrated: new Map([[1, hyd(1, 10, OLD)]]),+ inboundLinkSources: new Map(),+ tagsByDoc: new Map(),+ },+ {+ keywordWeight: 0.6,+ semanticWeight: 0.4,+ limit: 10,+ nowMs: NOW,+ semanticEnabled: false,+ },+ );+ const r = ranked.find((x) => x.chunkId === 1)!;+ expect(reasonLayers(r.reasons)).not.toContain("semantic_cos");+});++test("reasons array is frozen", () => {+ const ranked = rankResults(+ {+ keyword: [{ chunkId: 1, documentId: 10, bm25: -5 }] as KeywordHit[],+ semantic: [] as SemanticHit[],+ hydrated: new Map([[1, hyd(1, 10, OLD)]]),+ inboundLinkSources: new Map(),+ tagsByDoc: new Map(),+ },+ { keywordWeight: 0.6, semanticWeight: 0.4, limit: 10, nowMs: NOW },+ );+ expect(Object.isFrozen(ranked[0]!.reasons)).toBe(true);+});diff --git a/tests/core/search/schema-migration-v2.test.ts b/tests/core/search/schema-migration-v2.test.tsnew file mode 100644index 00000000..31a0ae37--- /dev/null+++ b/tests/core/search/schema-migration-v2.test.ts@@ -0,0 +1,71 @@+/**+ * Schema migration v1 -> v2 (v0.13.0). v2 adds the `chunk_entities`+ * table feeding entity-boosted retrieval. A fresh index lands at v2; an+ * existing v1 index upgrades cleanly without losing data.+ */++import { test, expect, beforeEach, afterEach } from "bun:test";+import { Database } from "bun:sqlite";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ applyMigrations,+ LATEST_SCHEMA_VERSION,+ readSchemaVersion,+} from "../../../src/core/search/schema.ts";++let tmp: string;+let dbPath: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "osb-mig-v2-"));+ dbPath = join(tmp, "test.sqlite");+});+afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function hasTable(db: Database, name: string): boolean {+ return (+ db+ .query<{ name: string }, [string]>(+ "SELECT name FROM sqlite_master WHERE type='table' AND name = ?",+ )+ .get(name) !== null+ );+}++test("fresh migration reaches v2 and creates chunk_entities", () => {+ const db = new Database(dbPath);+ expect(applyMigrations(db)).toBe(2);+ expect(LATEST_SCHEMA_VERSION).toBe(2);+ expect(hasTable(db, "chunk_entities")).toBe(true);+ db.close();+});++test("a v1 index upgrades to v2, adding chunk_entities and preserving data", () => {+ const db = new Database(dbPath);+ applyMigrations(db); // -> v2+ // Seed a document + chunk, then simulate an older v1 index by dropping+ // the v2 table and rewinding the recorded version.+ db.run(+ "INSERT INTO documents(id, path, title, content_hash, mtime, size, created_at, updated_at, indexed_at) " ++ "VALUES (1, 'a.md', 'A', 'h', 1, 1, 't', 't', 't')",+ );+ db.run(+ "INSERT INTO chunks(id, document_id, chunk_index, content, content_hash, start_line, end_line, token_count, created_at, updated_at) " ++ "VALUES (1, 1, 0, 'body', 'c', 1, 1, 1, 't', 't')",+ );+ db.run("DROP TABLE chunk_entities");+ db.run("UPDATE index_state SET value = '1' WHERE key = 'schema_version'");+ expect(readSchemaVersion(db)).toBe(1);++ expect(applyMigrations(db)).toBe(2);+ expect(hasTable(db, "chunk_entities")).toBe(true);+ // Pre-existing rows survive the upgrade.+ const docs = db.query<{ c: number }, []>("SELECT count(*) AS c FROM documents").get();+ expect(docs?.c).toBe(1);+ db.close();+});diff --git a/tests/core/search/schema.test.ts b/tests/core/search/schema.test.tsindex 38976114..d18f55f4 100644--- a/tests/core/search/schema.test.ts+++ b/tests/core/search/schema.test.ts@@ -64,7 +64,7 @@ test("applyMigrations on a fresh db creates the v1 schema", () => {// FTS5 virtual table is registered as type 'table'.expect(tables.has("chunk_fts")).toBe(true);- expect(readSchemaVersion(db)).toBe(1);+ expect(readSchemaVersion(db)).toBe(LATEST_SCHEMA_VERSION);db.close();});@@ -75,7 +75,7 @@ test("applyMigrations is idempotent", () => {applyMigrations(db);applyMigrations(db);expect(tableNames(db).size).toBe(first);- expect(readSchemaVersion(db)).toBe(1);+ expect(readSchemaVersion(db)).toBe(LATEST_SCHEMA_VERSION);db.close();});diff --git a/tests/core/search/store-entities.test.ts b/tests/core/search/store-entities.test.tsnew file mode 100644index 00000000..14def238--- /dev/null+++ b/tests/core/search/store-entities.test.ts@@ -0,0 +1,71 @@+/**+ * Store support for entity-boosted retrieval: `replaceEntities` writes+ * a chunk's entity set (replacing any prior set), and+ * `chunkEntityMatches` counts how many query entities each candidate+ * chunk shares - the raw signal the ranker turns into a capped boost.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";++import { Store } from "../../../src/core/search/store.ts";+import { makeConfig, createTempVault } from "../../helpers/search-fixtures.ts";++let tmp: ReturnType<typeof createTempVault>;++beforeEach(() => {+ tmp = createTempVault("store-entities");+});+afterEach(() => {+ tmp.cleanup();+});++async function open() {+ return Store.open(makeConfig({ vault: tmp.vault, dbPath: tmp.dbPath }), {+ mode: "write",+ loadVec: false,+ });+}++async function seedChunk(store: Store): Promise<number> {+ const doc = store.upsertDocument({ path: "a.md", title: "A", contentHash: "h", mtime: 1, size: 1 });+ const ids = store.replaceChunks(doc, [+ { chunkIndex: 0, content: "body", contentHash: "c0", startLine: 1, endLine: 1, tokenCount: 1 },+ ]);+ return ids[0]!;+}++test("replaceEntities stores a chunk's entity set", async () => {+ const store = await open();+ const chunkId = await seedChunk(store);+ store.replaceEntities(chunkId, ["pay memory", "sergey"]);+ const matches = store.chunkEntityMatches([chunkId], ["pay memory"]);+ expect(matches.get(chunkId)).toBe(1);+ await store.close();+});++test("replaceEntities replaces the prior set rather than appending", async () => {+ const store = await open();+ const chunkId = await seedChunk(store);+ store.replaceEntities(chunkId, ["alpha", "beta"]);+ store.replaceEntities(chunkId, ["gamma"]);+ const matches = store.chunkEntityMatches([chunkId], ["alpha", "beta", "gamma"]);+ expect(matches.get(chunkId)).toBe(1); // only gamma remains+ await store.close();+});++test("chunkEntityMatches counts distinct query-entity overlaps per chunk", async () => {+ const store = await open();+ const chunkId = await seedChunk(store);+ store.replaceEntities(chunkId, ["pay memory", "sergey", "fts5"]);+ const matches = store.chunkEntityMatches([chunkId], ["pay memory", "fts5", "absent"]);+ expect(matches.get(chunkId)).toBe(2);+ await store.close();+});++test("chunkEntityMatches returns empty when there are no query entities", async () => {+ const store = await open();+ const chunkId = await seedChunk(store);+ store.replaceEntities(chunkId, ["alpha"]);+ expect(store.chunkEntityMatches([chunkId], []).size).toBe(0);+ await store.close();+});diff --git a/tests/core/search/store-outbound-links.test.ts b/tests/core/search/store-outbound-links.test.tsnew file mode 100644index 00000000..92e973d1--- /dev/null+++ b/tests/core/search/store-outbound-links.test.ts@@ -0,0 +1,75 @@+/**+ * Store support for link-graph traversal: `outboundLinkTargets` returns+ * the resolved outbound adjacency for a set of documents, and+ * `representativeChunks` returns one chunk per document (the lowest+ * chunk_index) so the traversal layer has something to surface.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";++import { Store } from "../../../src/core/search/store.ts";+import { makeConfig, createTempVault } from "../../helpers/search-fixtures.ts";++let tmp: ReturnType<typeof createTempVault>;++beforeEach(() => {+ tmp = createTempVault("store-outbound");+});+afterEach(() => {+ tmp.cleanup();+});++async function seed() {+ const store = await Store.open(makeConfig({ vault: tmp.vault, dbPath: tmp.dbPath }), {+ mode: "write",+ loadVec: false,+ });+ const a = store.upsertDocument({ path: "a.md", title: "A", contentHash: "ha", mtime: 1, size: 1 });+ const b = store.upsertDocument({ path: "b.md", title: "B", contentHash: "hb", mtime: 1, size: 1 });+ const c = store.upsertDocument({ path: "c.md", title: "C", contentHash: "hc", mtime: 1, size: 1 });+ const aChunks = store.replaceChunks(a, [+ { chunkIndex: 0, content: "alpha head", contentHash: "a0", startLine: 1, endLine: 1, tokenCount: 2 },+ { chunkIndex: 1, content: "alpha tail", contentHash: "a1", startLine: 2, endLine: 2, tokenCount: 2 },+ ]);+ store.replaceChunks(b, [+ { chunkIndex: 0, content: "beta body", contentHash: "b0", startLine: 1, endLine: 1, tokenCount: 2 },+ ]);+ store.replaceChunks(c, [+ { chunkIndex: 0, content: "gamma body", contentHash: "c0", startLine: 1, endLine: 1, tokenCount: 2 },+ ]);+ // a -> b (wikilink), a -> c (markdown_link), a -> a (self, must be ignored),+ // a -> #tag (tag, must be ignored for traversal).+ store.replaceLinks(a, [+ { sourceChunkId: aChunks[0]!, targetPath: "b.md", linkText: "B", linkType: "wikilink" },+ { sourceChunkId: aChunks[0]!, targetPath: "c.md", linkText: "C", linkType: "markdown_link" },+ { sourceChunkId: aChunks[0]!, targetPath: "a.md", linkText: "A", linkType: "wikilink" },+ { sourceChunkId: aChunks[0]!, targetPath: null, linkText: "topic", linkType: "tag" },+ ]);+ store.resolveLinkTargets();+ return { store, a, b, c };+}++test("outboundLinkTargets returns resolved wikilink/markdown targets, excluding self and tags", async () => {+ const { store, a, b, c } = await seed();+ const map = store.outboundLinkTargets([a]);+ const targets = (map.get(a) ?? []).slice().sort((x, y) => x - y);+ expect(targets).toEqual([b, c].sort((x, y) => x - y));+ await store.close();+});++test("outboundLinkTargets omits documents with no outbound links", async () => {+ const { store, b } = await seed();+ const map = store.outboundLinkTargets([b]);+ expect(map.get(b)).toBeUndefined();+ await store.close();+});++test("representativeChunks returns the lowest chunk_index per document", async () => {+ const { store, a } = await seed();+ const reps = store.representativeChunks([a]);+ const rep = reps.get(a);+ expect(rep).toBeDefined();+ expect(rep!.content).toBe("alpha head"); // chunk_index 0, not the tail+ expect(rep!.path).toBe("a.md");+ await store.close();+});diff --git a/tests/core/search/store.test.ts b/tests/core/search/store.test.tsindex d1f1b1d3..63d2e9e5 100644--- a/tests/core/search/store.test.ts+++ b/tests/core/search/store.test.ts@@ -31,6 +31,7 @@ function makeConfig(overrides?: Partial<ResolvedSearchConfig>): ResolvedSearchCokeywordWeight: 0.6,semanticWeight: 0.4,semantic,+ recall: Object.freeze({ mmrLambda: 0.7, maxHops: 1, hopDecay: 0.5, maxExpansionPerHit: 3 }),...(overrides ?? {}),});}@@ -47,7 +48,7 @@ afterEach(() => {test("open in write mode creates file and applies migrations", async () => {const store = await Store.open(makeConfig(), { mode: "write", loadVec: false });expect(existsSync(dbPath)).toBe(true);- expect(store.schemaVersion()).toBe(1);+ expect(store.schemaVersion()).toBe(2);await store.close();});@@ -65,7 +66,7 @@ test("open in read mode succeeds after writer creates the file", async () => {const w = await Store.open(makeConfig(), { mode: "write", loadVec: false });await w.close();const r = await Store.open(makeConfig(), { mode: "read", loadVec: false });- expect(r.schemaVersion()).toBe(1);+ expect(r.schemaVersion()).toBe(2);await r.close();});diff --git a/tests/core/search/store.vec.test.ts b/tests/core/search/store.vec.test.tsindex 7ca4e18a..e8456c7f 100644--- a/tests/core/search/store.vec.test.ts+++ b/tests/core/search/store.vec.test.ts@@ -30,6 +30,7 @@ function semanticConfig(model: string, dim: number, overrides?: Partial<ResolvedkeywordWeight: 0.6,semanticWeight: 0.4,semantic,+ recall: Object.freeze({ mmrLambda: 0.7, maxHops: 1, hopDecay: 0.5, maxExpansionPerHit: 3 }),...(overrides ?? {}),});}diff --git a/tests/core/search/traversal-recall.test.ts b/tests/core/search/traversal-recall.test.tsnew file mode 100644index 00000000..7c05a22e--- /dev/null+++ b/tests/core/search/traversal-recall.test.ts@@ -0,0 +1,54 @@+/**+ * End-to-end link-graph traversal: a document that does NOT match the+ * query but is linked from a strong hit is surfaced via traversal, and+ * disabling traversal (maxHops 0) hides it again.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, writeFileSync } from "node:fs";+import { join } from "node:path";++import { indexVault, search } from "../../../src/core/search/index.ts";+import { makeConfig, createTempVault } from "../../helpers/search-fixtures.ts";++let tmp: ReturnType<typeof createTempVault>;++beforeEach(async () => {+ tmp = createTempVault("traversal-recall");+ mkdirSync(join(tmp.vault, "notes"), { recursive: true });+ // hub.md matches "kingfisher" and links to spoke.md, which talks about+ // something else entirely (no query-term overlap).+ writeFileSync(+ join(tmp.vault, "notes", "hub.md"),+ "---\ntitle: Hub\n---\n\nThe kingfisher dives fast. See [[notes/spoke.md|spoke]] for the related note.\n",+ );+ writeFileSync(+ join(tmp.vault, "notes", "spoke.md"),+ "---\ntitle: Spoke\n---\n\nUnrelated content about migration patterns and tides.\n",+ );+ const config = makeConfig({ vault: tmp.vault, dbPath: tmp.dbPath });+ await indexVault(config, {});+});++afterEach(() => {+ tmp.cleanup();+});++test("a linked-but-non-matching doc is surfaced by traversal", async () => {+ const config = makeConfig({ vault: tmp.vault, dbPath: tmp.dbPath });+ const out = await search(config, { query: "kingfisher", limit: 10 });+ const paths = out.results.map((r) => r.path);+ expect(paths).toContain("notes/hub.md");+ expect(paths).toContain("notes/spoke.md");+ const spoke = out.results.find((r) => r.path === "notes/spoke.md")!;+ expect(spoke.searchType).toBe("link");+ expect(spoke.reasons.some((x) => x.startsWith("link_traversal"))).toBe(true);+});++test("maxHops 0 hides the linked-but-non-matching doc", async () => {+ const config = makeConfig({ vault: tmp.vault, dbPath: tmp.dbPath, maxHops: 0 });+ const out = await search(config, { query: "kingfisher", limit: 10 });+ const paths = out.results.map((r) => r.path);+ expect(paths).toContain("notes/hub.md");+ expect(paths).not.toContain("notes/spoke.md");+});diff --git a/tests/core/search/traversal.test.ts b/tests/core/search/traversal.test.tsnew file mode 100644index 00000000..bf151991--- /dev/null+++ b/tests/core/search/traversal.test.ts@@ -0,0 +1,135 @@+/**+ * Link-graph traversal during recall. Two-stage retrieve-then-walk:+ * after relevance ranking, follow outbound wikilinks from the top hits+ * and surface linked documents scored as parent_score * hop_decay^hop,+ * bounded by max_hops and max_expansion_per_hit, deduped against the+ * existing result set. Pure function over precomputed inputs.+ */++import { test, expect } from "bun:test";++import { expandByTraversal } from "../../../src/core/search/traversal.ts";+import type { BrainSearchResult } from "../../../src/core/search/types.ts";+import type { TraversalDoc } from "../../../src/core/search/traversal.ts";++let nextChunk = 100;+function res(docId: number, score: number): BrainSearchResult {+ const chunkId = nextChunk++;+ return Object.freeze({+ documentId: docId,+ chunkId,+ path: `doc${docId}.md`,+ title: `Doc ${docId}`,+ content: `content of ${docId}`,+ startLine: 1,+ endLine: 1,+ score,+ keywordScore: score,+ semanticScore: 0,+ linkBoost: 0,+ recencyBoost: 0,+ searchType: "keyword" as const,+ reasons: Object.freeze([`fts5_bm25: ${score.toFixed(3)}`]),+ });+}++function docFor(docId: number): TraversalDoc {+ return {+ documentId: docId,+ chunkId: 900 + docId,+ path: `doc${docId}.md`,+ title: `Doc ${docId}`,+ content: `content of ${docId}`,+ startLine: 1,+ endLine: 1,+ };+}++const OPTS = { maxHops: 1, hopDecay: 0.5, maxExpansionPerHit: 3 };++test("maxHops == 0 returns the ranked set unchanged", () => {+ const ranked = [res(1, 0.8)];+ const out = expandByTraversal(+ {+ ranked,+ outbound: new Map([[1, [2]]]),+ expansionDoc: docFor,+ },+ { ...OPTS, maxHops: 0 },+ );+ expect(out).toEqual(ranked);+});++test("a doc linked from a top hit is surfaced with a decayed score", () => {+ const out = expandByTraversal(+ {+ ranked: [res(1, 0.8)],+ outbound: new Map([[1, [2]]]),+ expansionDoc: docFor,+ },+ OPTS,+ );+ const added = out.find((r) => r.documentId === 2);+ expect(added).toBeDefined();+ expect(added!.score).toBeCloseTo(0.4, 6); // 0.8 * 0.5+ expect(added!.searchType).toBe("link");+ expect(added!.reasons.some((x) => x.startsWith("link_traversal"))).toBe(true);+});++test("a doc already present is not duplicated and keeps its higher score", () => {+ const out = expandByTraversal(+ {+ ranked: [res(1, 0.8), res(2, 0.7)],+ outbound: new Map([[1, [2]]]),+ expansionDoc: docFor,+ },+ OPTS,+ );+ const twos = out.filter((r) => r.documentId === 2);+ expect(twos).toHaveLength(1);+ expect(twos[0]!.score).toBeCloseTo(0.7, 6); // original relevance, not 0.4+});++test("expansion per hit is capped by maxExpansionPerHit", () => {+ const out = expandByTraversal(+ {+ ranked: [res(1, 0.8)],+ outbound: new Map([[1, [2, 3, 4, 5, 6]]]),+ expansionDoc: docFor,+ },+ { ...OPTS, maxExpansionPerHit: 2 },+ );+ const added = out.filter((r) => r.searchType === "link");+ expect(added).toHaveLength(2);+});++test("decay compounds across hops up to maxHops", () => {+ const out = expandByTraversal(+ {+ ranked: [res(1, 0.8)],+ outbound: new Map([+ [1, [2]],+ [2, [3]],+ ]),+ expansionDoc: docFor,+ },+ { maxHops: 2, hopDecay: 0.5, maxExpansionPerHit: 3 },+ );+ const c = out.find((r) => r.documentId === 3);+ expect(c).toBeDefined();+ expect(c!.score).toBeCloseTo(0.2, 6); // 0.8 * 0.5 * 0.5+});++test("results stay sorted by score descending after expansion", () => {+ const out = expandByTraversal(+ {+ ranked: [res(1, 0.8), res(9, 0.3)],+ outbound: new Map([[1, [2]]]),+ expansionDoc: docFor,+ },+ OPTS,+ );+ const scores = out.map((r) => r.score);+ const sorted = [...scores].sort((a, b) => b - a);+ expect(scores).toEqual(sorted);+});diff --git a/tests/helpers/search-fixtures.ts b/tests/helpers/search-fixtures.tsindex 3b77c096..696ec41f 100644--- a/tests/helpers/search-fixtures.ts+++ b/tests/helpers/search-fixtures.ts@@ -54,6 +54,10 @@ export function makeConfig(opts: {*/ignorePaths?: ReadonlyArray<string>;semantic?: Partial<ResolvedEmbeddingConfig>;+ /** MMR tradeoff; defaults to 0.7. Pass 1 to disable diversification. */+ mmrLambda?: number;+ /** Link-graph traversal depth; defaults to 1. Pass 0 to disable. */+ maxHops?: number;}): ResolvedSearchConfig {const baseSemantic: ResolvedEmbeddingConfig = Object.freeze({enabled: false,@@ -83,5 +87,11 @@ export function makeConfig(opts: {keywordWeight: 0.6,semanticWeight: 0.4,semantic,+ recall: Object.freeze({+ mmrLambda: opts.mmrLambda ?? 0.7,+ maxHops: opts.maxHops ?? 1,+ hopDecay: 0.5,+ maxExpansionPerHit: 3,+ }),});}diff --git a/tests/mcp/brain-search-reasons.test.ts b/tests/mcp/brain-search-reasons.test.tsnew file mode 100644index 00000000..9a8953bc--- /dev/null+++ b/tests/mcp/brain-search-reasons.test.ts@@ -0,0 +1,57 @@+/**+ * `brain_search` surfaces the explainable-recall `reasons` array on+ * every result. Exercises the tool through the same handler path the+ * MCP server uses, against a freshly indexed scratch vault.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { SEARCH_TOOLS } from "../../src/mcp/search-tools.ts";+import { indexVault, resolveSearchConfig } from "../../src/core/search/index.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";++let vault: string;+let configHome: string;+let ctx: { vault: string; configPath: string };++beforeEach(async () => {+ vault = mkdtempSync(join(tmpdir(), "o2b-reasons-vault-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-reasons-cfg-"));+ const configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ mkdirSync(join(vault, "notes"), { recursive: true });+ writeFileSync(+ join(vault, "notes", "alpha.md"),+ "---\ntitle: Alpha\n---\n\nThe quick brown fox jumps over the lazy dog.\n",+ );+ ctx = { vault, configPath };+ const config = resolveSearchConfig({ vault, configPath });+ await indexVault(config, {});+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++describe("brain_search reasons", () => {+ test("every result carries a non-empty reasons array", async () => {+ const tool = SEARCH_TOOLS.find((t) => t.name === "brain_search");+ expect(tool).toBeDefined();+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const out = (await tool!.handler(ctx as any, { query: "quick fox" })) as {+ results: Array<{ reasons: string[] }>;+ total: number;+ };+ expect(out.total).toBeGreaterThan(0);+ for (const r of out.results) {+ expect(Array.isArray(r.reasons)).toBe(true);+ expect(r.reasons.length).toBeGreaterThan(0);+ // keyword-only scratch vault β at least the bm25 layer is present.+ expect(r.reasons.some((x) => x.startsWith("fts5_bm25"))).toBe(true);+ }+ });+});diff --git a/tests/mcp/search.test.ts b/tests/mcp/search.test.tsindex 1c4a5eb8..868d5c58 100644--- a/tests/mcp/search.test.ts+++ b/tests/mcp/search.test.ts@@ -172,7 +172,7 @@ test("second_brain_status includes search block after indexing", async () => {expect(search).toBeDefined();expect(search!["exists"]).toBe(true);expect(search!["documents"]).toBe(1);- expect(search!["schema_version"]).toBe(1);+ expect(search!["schema_version"]).toBe(2);});test("second_brain_status reports search.exists=false when index missing", async () => {