import type { FtsIndex } from "../fts5.js"; import type { FileEntry, Vault } from "../vault.js"; /** * Token-matching mode for {@link searchText}. * * - `"all"` — every whitespace-separated token must occur in the note (AND). * - `"any"` — at least one token must occur (OR). * - `"phrase"` — the raw query string must occur as a contiguous substring. */ export type SearchMode = "all" | "any" | "phrase"; /** * A single hit from {@link searchText}. * * Hits expose the surrounding snippet and the 1-based line where the first * matched token landed so the agent can scroll a UI directly to the relevant * passage. `score` is the total per-token occurrence count (higher = more * matches), not normalized — compare scores within the same response only. */ export interface SearchHit { /** Vault-relative path of the matching note (e.g. `"Reference/Foo.md"`). */ path: string; /** ~120-char excerpt centered on the first matched token, with `…` truncation. */ snippet: string; /** Total occurrences of all matched tokens. Sort key (desc). */ score: number; /** 1-based line number where the first match starts. `0` when no match. */ line: number; /** Original-case tokens that matched (subset of the query tokens). */ matched_terms: string[]; } /** * Envelope returned by {@link searchText}. * * Includes `scanned_notes` for observability — agents can detect when an * empty `matches[]` is "I searched 4000 notes and nothing matched" vs. "the * `folder` filter excluded everything". */ export interface SearchResponse { /** Echo of the input query (untouched). */ query: string; /** Mode that was actually used (after `args.mode ?? "all"` defaulting). */ mode: SearchMode; /** Total markdown notes considered (post-`folder`-filter, pre-match). */ scanned_notes: number; /** Sorted by `score` desc, truncated to `args.limit ?? 25`. */ matches: SearchHit[]; } /** * Substring-grep search over the vault: scans every `.md` body for token * occurrences in `all` / `any` / `phrase` mode and ranks by occurrence count. * * This is the simplest retrieval primitive — no index, no embeddings, no * native deps. Useful when the agent already knows specific keywords; for * fuzzier semantic recall prefer {@link searchHybrid} or {@link semanticSearch}. * Read concurrency is bounded to 16 to avoid blowing the fd limit on large * vaults. Tokenization is whitespace-split + lowercased; case-insensitive. * * @param vault - The vault to search. * @param args - Search arguments. `query` is required and must be non-empty. * `folder` restricts the scan to a subdirectory (vault-relative). * `limit` caps results (default 25). `mode` defaults to `"all"`. * @returns A {@link SearchResponse} with sorted `matches` and a * `scanned_notes` observability count. * @throws {Error} If `query` is empty / whitespace-only. * @throws {VaultPathError} If `folder` resolves outside the vault root. * @example * ```ts * const result = await searchText(vault, { * query: "RAG retrieval", * folder: "Reference", * mode: "all", * limit: 10 * }); * for (const hit of result.matches) { * console.log(`${hit.path}:${hit.line} — ${hit.snippet}`); * } * ``` */ export declare function searchText(vault: Vault, args: { query: string; folder?: string; limit?: number; mode?: SearchMode; }): Promise; /** * One row of the {@link findSimilar} response. Exposes the per-signal * breakdown so the agent can explain *why* a note is considered similar. */ export interface SimilarNote { /** Vault-relative path of the candidate. */ path: string; /** `.md`-stripped basename for display. */ title: string; /** Composite weighted score in approximately `[0, 8.5]`. Sort key (desc). */ score: number; /** Per-signal contributions in `[0, 1]` before weighting. */ signals: { tag_jaccard: number; title_3gram: number; shared_outbound: number; co_backlink: number; }; /** Tags shared between the target and this candidate (lowercased, sorted). */ shared_tags: string[]; /** ISO-8601 modification time of the candidate note. */ mtime: string; /** v3.10 — whole days since `mtime` (freshness signal; never negative). */ age_days: number; /** v3.10 — `true` when older than the default stale threshold (365d). */ stale: boolean; } /** * Lexical-hybrid similarity over vault-native signals — finds notes related * to the target without any embeddings. * * Combines four structural signals: tag Jaccard (×3.0), title character * 3-gram Jaccard (×1.5), shared-outbound link overlap (×2.0), and co-backlink * Jaccard (×2.0). Tag overlap dominates by design — that's the strongest * "this is the same topic" signal a human would use. Skips body cosine on * purpose: structural signals converge fast at vault scale (5k × 5KB) without * a full TF-IDF pass per call. * * Use this when the agent has *one specific note* and wants neighbors. For * "find notes about " use {@link searchHybrid} or {@link semanticSearch}. * * @param vault - The vault to search. * @param args - One of `path` or `title` is required to identify the target. * `limit` defaults to 10. `min_score` (default 0.05) prunes weak matches. * @returns Sorted `SimilarNote[]` (desc by `score`), capped at `limit`. * Empty array if the target was excluded by `--exclude-glob`. * @throws {Error} If neither `path` nor `title` is provided, or the target * cannot be resolved. * @example * ```ts * const related = await findSimilar(vault, { * path: "Reference/Hybrid Retrieval.md", * limit: 5 * }); * for (const n of related) { * console.log(n.path, n.score, n.signals); * } * ``` */ export declare function findSimilar(vault: Vault, args: { path?: string; title?: string; limit?: number; min_score?: number; }): Promise; interface DocVector { relPath: string; basename: string; mtimeMs: number; /** Sparse term-frequency-IDF vector. Map. L2-normalized. */ weights: Map; } /** * Unicode-aware tokenizer used by the TF-IDF index and {@link semanticSearch}. * * For Latin / Cyrillic / Greek / Arabic / Hebrew etc., matches `\p{L}\p{N}` * runs (length 2–40, stop-word filtered). For CJK / Thai / Khmer / Lao * (no-whitespace scripts), uses `Intl.Segmenter` with `granularity: "word"` * to get real word boundaries — without this, a sentence like * "認可サーバーがアクセストークン" becomes a single 12-char token that the * length filter would drop, gutting non-Latin TF-IDF precision. * * @internal * @param text - Raw text to tokenize. Will be lowercased. * @returns A flat array of tokens in document order. May contain duplicates * (TF is computed downstream). * @example * ```ts * tokenizeForTfidf("Hybrid RAG retrieval"); * // → ["hybrid", "rag", "retrieval"] * tokenizeForTfidf("認可サーバーがアクセストークン"); * // → ["認可", "サーバー", "アクセス", "トークン"] * ``` */ export declare function tokenizeForTfidf(text: string): string[]; /** * Build (or fetch from per-vault cache) the L2-normalized TF-IDF index over * every markdown body in the vault. * * Uses smoothed IDF (`ln(1 + N / (1 + df))`) which keeps every-doc terms * non-zero and tames inflation on small vaults. Cache invalidates on * `entries` length / order / mtime mismatch — the same {@link Vault} instance * reuses the index across consecutive {@link semanticSearch} calls. * * @internal * @param vault - The vault whose corpus to index. * @returns `{ docs, idf, entriesRef }` — `docs` are L2-normalized sparse * vectors keyed by relPath; `idf` maps term → smoothed IDF weight; * `entriesRef` is the `FileEntry` snapshot used for cache validation. * @example * ```ts * const { docs, idf } = await buildTfidfIndex(vault); * console.log(`${docs.length} docs, ${idf.size} unique terms`); * ``` */ export declare function buildTfidfIndex(vault: Vault): Promise<{ docs: DocVector[]; idf: Map; entriesRef: FileEntry[]; }>; /** * One hit from {@link semanticSearch}. `matched_terms` are the query tokens * that contributed to the cosine score, sorted by IDF (rarest first). */ export interface SemanticHit { /** Vault-relative path of the matching note. */ path: string; /** `.md`-stripped basename for display. */ title: string; /** Cosine similarity in `[0, 1]`, rounded to 4 decimals. Sort key. */ score: number; /** ~120-char excerpt centered on the first matched term in the body. */ snippet: string; /** Up to 8 query tokens that contributed, sorted by IDF desc (rarest first). */ matched_terms: string[]; /** ISO-8601 modification time of the note. */ mtime: string; /** v3.10 — whole days since `mtime` (freshness signal; never negative). */ age_days: number; /** v3.10 — `true` when older than the default stale threshold (365d). */ stale: boolean; } /** * Pure-JS lexical-semantic search via TF-IDF cosine similarity. * * Builds (or reuses cached) per-vault TF-IDF index, then ranks notes by * cosine similarity of the query vector against each body vector. Catches * "related-term" recall that the substring path of {@link searchText} misses * (e.g. searching `"retrieval"` will surface notes about `"recall"` if the * vocabulary co-occurs). Zero native deps — works on every platform with * no model download. For full ML retrieval use {@link embeddingsSearch}; * for graceful-degradation fusion use {@link searchHybrid}. * * @param vault - The vault to search. * @param args - `query` is required. `limit` defaults to 10. `min_score` * defaults to 0.05 — anything below is pruned. `folder` restricts to a * subdirectory. * @returns An envelope with `query`, `total_docs` (corpus size), `method` * (always `"tfidf-cosine"`), and `matches` sorted by `score` desc. * @throws {Error} If `query` is empty / whitespace-only. * @example * ```ts * const result = await semanticSearch(vault, { * query: "vector retrieval cosine", * limit: 5 * }); * for (const hit of result.matches) { * console.log(hit.path, hit.score, hit.matched_terms); * } * ``` */ export declare function semanticSearch(vault: Vault, args: { query: string; folder?: string; limit?: number; min_score?: number; }): Promise<{ query: string; total_docs: number; method: "tfidf-cosine"; matches: SemanticHit[]; }>; /** * One chunk-level hit from {@link embeddingsSearch}. * * Unlike {@link SemanticHit}, embedding hits are chunk-scoped (not note- * scoped) — `chunk_index` / `line_start` / `line_end` let the agent jump to * the exact paragraph that matched. */ export interface EmbedHit { /** Vault-relative path of the source file (markdown or PDF). */ path: string; /** `.md`/`.pdf`-stripped basename for display. */ title: string; /** Cosine score in `[-1, 1]`, rounded to 4 decimals. Sort key. */ score: number; /** ~240-char excerpt from the matching chunk. */ snippet: string; /** 0-based chunk number within the source file. */ chunk_index: number; /** 1-based start line of the chunk in the source file. */ line_start: number; /** 1-based end line of the chunk (inclusive). */ line_end: number; /** v2.8.0 — content-source kind ("md" | "pdf"). */ kind: "md" | "pdf"; } /** * Envelope returned by {@link embeddingsSearch}. * * `total_chunks` is the full index size (post-exclusion filtering), useful * for sanity-checking that the agent's `build-embeddings` actually ran on * the expected corpus. */ export interface EmbedSearchResponse { query: string; method: "embeddings-cosine"; model: string; total_chunks: number; matches: EmbedHit[]; /** * v3.1.0 — present + true when retrieval used the agent-supplied * `hypothetical_answer` as the embedding seed (HyDE). Lets clients * audit whether they're seeing raw-query or HyDE-augmented results. */ hyde?: boolean; } /** * v2.13.0 — optional HNSW context. When passed, embeddingsSearch routes * the k-NN lookup through the in-memory HNSW index (sub-10ms at any * scale) instead of the O(n) brute-force cosine in EmbedDb.search(). * `rowByLabel` is the label → source-row mapping established at HNSW * build time (typically labels are `embeddings.id`, set in * `EmbedDb.getAllVectors()`). */ export interface HnswSearchContext { index: { searchKnn(q: Float32Array, k: number, opts?: { ef?: number; }): { labels: number[]; distances: number[]; }; }; rowByLabel: ReadonlyMap; ef?: number; /** * v3.6.2 HN-4 — embedding-model alias the HNSW index was built with * (e.g. "multilingual" or "bge"). At search time we verify that the * embedder used to encode the query produces vectors in the SAME * vector space as the index. CRIT-1 (v3.6.1) fixed the build-side * silent destruction; this is the corresponding search-side guard. * * If the search-time embedder model doesn't match this alias, the * stored vectors and the query vector are from different vector * spaces — cosine returns garbage similarities. We throw instead of * returning garbage; the agent / user can correct the * `--embedding-model` flag and retry. */ modelAlias: string; } /** * v3.6.2 HN-4 — assert that the query-time embedder model matches the * HNSW index's build-time model. Standalone helper so the check is * unit-testable in isolation from `embeddingsSearch` (which depends on * loading the real ONNX embedder runtime). * * Throws a clear, actionable error on mismatch instead of letting the * caller compute cosine distances between vectors from two different * vector spaces (which would silently return garbage similarities). * * @param embedderAlias - The alias of the embedder being used at search * time (typically `embedder.model.alias` after `loadEmbedder(...)`). * @param hnswAlias - The alias the HNSW index was built with (stored * on the {@link HnswSearchContext} at server boot). * @throws {Error} If the aliases differ. */ export declare function assertHnswModelMatchesEmbedder(embedderAlias: string, hnswAlias: string): void; /** * v3.9.0-rc.3 R-10 — adaptive HNSW refill loop for under-returned * semantic-search queries. * * Background: the embed-db can contain entries for paths that the * privacy filter (`vault.isExcluded`) then drops at response-build * time. Pre-3.9.0-rc.3: * - v2.13.0 fetched `limit * 2` from HNSW. * - v3.8.0-rc.9 raised to `max(overFetch * 3, 50)` (effective 6× limit). * - But both were STATIC multipliers — a vault with 80% excluded * entries still under-returned because filtering left < limit. * * The adaptive loop solves this self-tuningly: if after filtering * the result set is < limit AND k < maxLabels, double k and try again. * Bounded by `maxAttempts` (default 3) so a fully-exhausted query * doesn't burn arbitrary CPU. Most vaults converge on the first * attempt (typical exclude ratio < 20%); the refill engages only * for long-tail privacy-heavy configurations. * * Pure function. The HNSW search and filter callbacks are injected so * tests can drive the loop with stub searchKnn + filter implementations. * * @param ctx - Loop inputs: * - `initialK`: first attempt's k (typically `max(overFetch * 3, 50)`) * - `maxLabels`: index size; k is capped at this * - `limit`: caller's desired top-K (loop stops once filtered ≥ limit) * - `searchKnn(k)`: HNSW search returning labels + distances arrays * - `filter(labels, distances)`: apply min_score / folder / privacy * filters; returns a post-filtered hit array * - `maxAttempts`: bound on iterations (default 3) * @returns the final filtered hit array (may still be < limit if even * the saturated k+filter couldn't satisfy — caller must handle). */ export declare function adaptiveHnswRefill(ctx: { initialK: number; maxLabels: number; limit: number; searchKnn: (k: number) => { labels: number[]; distances: number[]; }; filter: (labels: number[], distances: number[]) => T[]; maxAttempts?: number; }): T[]; /** * v3.1.0 — pick the text that should be embedded for an embeddings-search * call. HyDE-augmented retrieval prefers the agent-supplied * `hypothetical_answer` (Gao et al 2023); falls back to the raw query * when that's absent / empty / whitespace-only. * * Pure helper so we can unit-test the decision in isolation (the real * `embeddingsSearch` function loads the @huggingface/transformers * embedder, which is out of scope for unit tests). */ export declare function pickEmbedTextForHyde(args: { query: string; hypothetical_answer?: string; }): { text: string; usedHyde: boolean; }; /** * ML embeddings retrieval — k-NN over a persistent vector index. * * Hits a `.embed.db` (SQLite) built by `enquire-mcp build-embeddings`. The * index is **opt-in and out-of-band**: this function lazy-loads the * `@huggingface/transformers` runtime + the embedder model only when called. * If the user hasn't run `build-embeddings`, returns a clean error pointing * to the setup command instead of blocking inside model load. * * Supports HyDE (Hypothetical Document Embeddings, Gao et al 2023): pass * `hypothetical_answer` and that text is embedded instead of `query` — * typically +2-5 NDCG@10 on under-specified queries. Optional HNSW * acceleration (sub-10ms k-NN at any scale) when an {@link HnswSearchContext} * is provided; otherwise falls back to brute-force cosine in `EmbedDb`. * * Privacy contract: hits are filtered through `vault.isExcluded()` before * return — entries in the `.embed.db` for paths now matched by * `--exclude-glob` / `--read-paths` never leak through. To keep the returned * count stable under normal exclude-glob use, the search over-fetches by 2× * (brute-force) or 6× (HNSW). Under extreme configurations where the majority * of the embed-db is excluded, fewer than `limit` results may be returned — * this is accepted behavior: privacy takes precedence over result count. * * @param vault - The vault. Used for path-exclusion filtering and to error * on missing index with a guidance message. * @param args - `query` is required + non-empty. `limit` defaults to 10, * `min_score` to 0.3 (relatively high cosine floor — embeddings cosine * has a tighter distribution than TF-IDF). `model` overrides the * embedder alias. `hypothetical_answer` enables HyDE. * @param embedFile - Absolute path to the `.embed.db`. Existence is checked * before any model load so the error message is fast and clear. * @param hnsw - Optional HNSW index context. When passed, k-NN routes * through HNSW instead of brute-force cosine. * @returns An {@link EmbedSearchResponse} with chunk-level matches and a * `hyde: true` marker iff HyDE actually fired. * @throws {Error} If `query` is empty, the embed db doesn't exist, the * embedder fails to load, or returns no vectors for the query. * @example * ```ts * const result = await embeddingsSearch( * vault, * { * query: "How do BM25 and embeddings compare on multilingual recall?", * limit: 10, * hypothetical_answer: "BM25 dominates on rare-term Latin queries..." * }, * "/path/to/vault.embed.db" * ); * console.log(result.matches[0]?.path, result.hyde); // true * ``` */ export declare function embeddingsSearch(vault: Vault, args: { query: string; folder?: string; limit?: number; min_score?: number; model?: string; /** * v3.1.0 — HyDE (Hypothetical Document Embeddings) augmentation. * When set, this string is embedded instead of `query`. The agent * generates a synthetic answer to its own question, embeds *that*, * and retrieves against the answer-shaped vector — typically beats * raw-query retrieval on under-specified queries by +2-5 NDCG@10. * The `query` string is still echoed in the response for caller * audit-trail; it does NOT influence retrieval when `hypothetical_answer` * is present. */ hypothetical_answer?: string; }, embedFile: string, hnsw?: HnswSearchContext | null): Promise; /** * One row of the fused {@link searchHybrid} response. * * Exposes `per_signal` for full observability — agents can see *which* * retrieval signal contributed (BM25 / TF-IDF / embeddings) and at what * rank/score, which is critical for debugging recall regressions and for * explaining results to end users. */ /** * v3.11.6 (S-5) — per-hit ranking EXPLANATION, attached to a {@link SearchHybridHit} * ONLY when the search was called with `explain: true`. It makes every re-rank * stage's contribution — and the rank MOVEMENT it caused — visible, so you can * see WHY a hit landed where it did and, crucially, whether the opt-in * `--recency-weight` / `--feedback-weight` stages actually changed the order * (both were previously evidence-poor: the response showed the final order but * never which stage produced it). Every field is a score / rank / age only — no * note content beyond what the hit already carries (privacy-safe). Ranks are * 0-based positions in the fused candidate list at each stage boundary. */ export interface SearchHitExplain { /** RRF-fused rank + score right after Reciprocal Rank Fusion, BEFORE any re-rank stage. The three ranker arms that fed it live in the hit's `per_signal`. */ rrf: { rank: number; score: number; }; /** Wikilink graph-boost (v2.3.0): in-degree among the fused top-K + the score added (α × in_degree). Present only when graph-boost ran AND this hit received a boost. */ graph_boost?: { in_degree: number; score_delta: number; }; /** Cross-encoder reranker (v2.9.0): the reranker score + rank before/after the rerank re-sort. Present only when a reranker ran and scored this hit. */ reranker?: { score: number; rank_before: number; rank_after: number; }; /** Opt-in recency re-rank (`--recency-weight`): the note's age + recency score + rank before/after. Present only when recency re-rank was active AND the note's mtime was stattable (a path deleted mid-flight contributes recency 0 and is omitted here); `rank_before === rank_after` means recency did NOT move this hit. */ recency?: { age_days: number; recency_score: number; rank_before: number; rank_after: number; }; /** Opt-in closed-loop feedback re-rank (`--feedback-weight`): the note's feedback score + rank before/after. Present only when feedback re-rank was active; `rank_before === rank_after` means feedback did NOT move this hit. */ feedback?: { feedback_score: number; rank_before: number; rank_after: number; }; /** Final 0-based rank of this hit in the returned `matches`. */ final_rank: number; } export interface SearchHybridHit { /** Vault-relative path of the matching note (or `path#chunk` for `granularity: "block"`). */ path: string; /** Stripped basename for display (`.md` or `.pdf` removed per `kind`). */ title: string; /** Fused RRF score (sum of 1/(k+rank) terms across signals). */ score: number; /** Snippet from whichever signal produced the best chunk hit. */ snippet: string; chunk_index?: number; line_start?: number; line_end?: number; /** * v2.8.0 — content-source kind. Lets agents distinguish markdown notes * from PDF chunks when both are indexed. Defaults to "md" for backward * compatibility (legacy DBs and TF-IDF hits have no kind metadata). */ kind: "md" | "pdf"; /** Per-signal observability — which signals contributed at what rank/score. */ per_signal: { bm25?: { rank: number; score: number; }; tfidf?: { rank: number; score: number; }; embeddings?: { rank: number; score: number; }; }; /** * v2.9.0 — cross-encoder reranker score in [0, 1] (sigmoid of the model's * relevance logit). Present only when the server was started with * `--enable-reranker` AND this hit was within the reranker's top-N * candidate set (default 50). Higher = more relevant. Compare across * results within the same response, NOT across queries (the absolute * value depends on the query). */ reranker_score?: number; /** * v3.10 — whole days since the note's current on-disk `mtime` (freshness * signal for forgetting-aware recall; never negative). Computed by statting * the final hit paths, so it reflects the live file mtime, not the possibly- * lagging indexed mtime in FTS5/embed-db `source_state`. Omitted (along with * `stale`) only when the stat fails — e.g. the file was deleted between * fusion and response assembly (fail-soft, never throws). */ age_days?: number; /** * v3.10 — `true` when `age_days >= DEFAULT_STALE_DAYS` (365). Lets an agent * flag a recalled fact as potentially out-of-date instead of presenting it * as current (the Memora stale-memory-reuse frontier). Read-only signal — * does NOT reorder results (opt-in recency re-ranking is a separate flag). */ stale?: boolean; /** * v3.11.6 (S-5) — per-stage ranking explanation. Present ONLY when the search * was called with `explain: true`. See {@link SearchHitExplain}. */ explain?: SearchHitExplain; } /** * Envelope returned by {@link searchHybrid}. * * `signals_used` tells the agent which rankers actually fired (BM25 needs * `--persistent-index`; embeddings needs `build-embeddings`). `signal_errors` * surfaces failed-but-attempted rankers so an empty `matches[]` can be * distinguished from "all rankers crashed". */ export interface SearchHybridResponse { /** Echo of the input query. */ query: string; /** Always `"rrf"` in v3.x — present as a versioned discriminator. */ method: "rrf"; /** RRF constant `k` (60 per Cormack 2009; documented for transparency). */ k: number; /** Which rankers contributed to the fused result. */ signals_used: ("bm25" | "tfidf" | "embeddings")[]; /** v2.0.0-beta.2: per-signal failure reasons. Pre-fix, ranker exceptions * were silently swallowed (only stderr-logged). The MCP response just * showed `signals_used: []` with `matches: []` — caller couldn't tell * "no hits" from "all rankers crashed". Now any catch'ed exception * surfaces here as a string so agents can reason about reliability. * v2.9.0 added `reranker` for cross-encoder failure surfacing. */ signal_errors?: { bm25?: string; tfidf?: string; embeddings?: string; reranker?: string; }; /** v3.10.0-rc.13 — reranker outcome, present ONLY when a cross-encoder was * requested (`--enable-reranker` / `ctx.reranker`). `{applied:true, pairs:N}` * when it re-scored N candidates; `{applied:false, reason}` when requested but * it didn't run — `reason` mirrors `signal_errors.reranker` on a load/download * failure, or notes there were no candidates. Closes the v3.9.1 bug-report * Issue 9 (reranker silently fell back to RRF with no way to tell whether it * was downloading, failed, or disabled). The stderr lifecycle log * (`reranker '' loading…` / `loaded; reranked N pairs`) is the * serve-side companion. */ reranked?: { applied: boolean; pairs?: number; reason?: string; }; total_candidates: number; matches: SearchHybridHit[]; } /** * Hybrid retrieval — fuses BM25 + TF-IDF + ML embeddings via Reciprocal Rank * Fusion (Cormack et al, 2009). The recommended search entry point. * * **Most agents should call this** rather than the single-ranker variants * ({@link searchText}, {@link semanticSearch}, {@link embeddingsSearch}) * because the umbrella auto-detects which signals are available and produces * consistent recall across user setups. Gracefully degrades: * - All 3 signals → fuse all 3 * - No FTS5 (no `--persistent-index`) → TF-IDF + embeddings (or just TF-IDF) * - No embeddings (no `build-embeddings`) → BM25 + TF-IDF * - Only TF-IDF → fall back to TF-IDF-only ranking * * Two unique signal layers ride on top of RRF: * - **Wikilink graph-boost** (v2.3.0): re-rank fused top-K by counting how * many other top-K hits link to each one. Only enquire-mcp does this — * wikilinks are the differentiating Obsidian primitive. * - **Cross-encoder reranker** (v2.9.0, opt-in): re-score top-N candidates * with a BGE-style cross-encoder. ~30-50ms / query overhead on M1 CPU. * * @param vault - The vault to search. * @param args - `query` is required + non-empty. `limit` defaults to 10. * `min_signals` (default 1) requires that many rankers fired for a hit. * `granularity: "note"` (default) collapses to best chunk per note (fused by * path — unaffected by chunking differences); `"block"` keeps each chunk * distinct (fused by `path#chunk_index`). NB for notes WITH frontmatter the * embeddings ranker chunks the body while BM25 chunks the full content, so a * `block` chunk INDEX may not denote the same span across the two rankers — * prefer the default `note` granularity for frontmatter-heavy vaults (audit M1). * `graph_boost` defaults to `true`. * @param ctx - Server-side context: `ftsIndex` (nullable), `embedFile` * (path may not exist), optional `reranker` config, optional * `rerankerOverride` (test injection point), optional `hnsw` context for * accelerated k-NN. * @returns A {@link SearchHybridResponse} with sorted `matches`, observability * in `signals_used` / `signal_errors`, and per-hit `per_signal` breakdown. * @throws {Error} If `query` is empty / whitespace-only. * @example * ```ts * const result = await searchHybrid( * vault, * { query: "RAG hybrid retrieval", limit: 10, folder: "Reference" }, * { ftsIndex, embedFile: "/path/to/vault.embed.db" } * ); * for (const hit of result.matches) { * console.log(hit.path, hit.score, hit.per_signal); * } * console.log("Rankers fired:", result.signals_used); * ``` */ /** * v3.10.0-rc.8 — prune excluded paths from a fused ranking list, at the * fusion-stage source. Defense-in-depth parity with the rc.18 L-HYB-1 * response-build guard: the fusion-stage consumers of the fused list * (graph-boost reads candidate CONTENT via `readNote`; recency stats candidate * mtime) run before that terminal guard, and this keeps them excluded-free even * if a future ranker arm forgets its own per-arm filter. * * Pure (the `isExcluded` predicate is injected) and granularity-aware: for * `"block"` ids of the form `path#chunk`, the chunk suffix is stripped before * the membership test — matching the response-build guard's `lastIndexOf("#")` * logic exactly so the two layers never disagree. * * @param hits - fused ranking entries (each carries an `id` = path or `path#chunk`). * @param isExcluded - returns true if a vault-relative path is excluded (`vault.isExcluded`). * @param granularity - `"note"` (id IS the path) or `"block"` (id is `path#chunk`). * @returns a new array with excluded-path entries removed (order preserved). */ export declare function pruneExcludedHits(hits: T[], isExcluded: (relPath: string) => boolean, granularity: "note" | "block"): T[]; /** * v3.10.0-rc.22 (audit M8) — pure privacy filter for embed-search hits; the * `embeddingsSearch` sibling of {@link pruneExcludedHits}. Drops rows whose * `rel_path` is excluded by the injected predicate (`vault.isExcluded`). Embed * hits carry a bare `rel_path` (no `#chunk` suffix), so — unlike * `pruneExcludedHits` — there's no id-splitting. * * Extracted so the actual filter `embeddingsSearch` applies (it ran inline at * two sites: the HNSW refill path + the brute-force path) is unit-testable * WITHOUT loading the ML embedder the function needs to encode a query. Before * rc.22 the security test "reimplemented" this filter inline and never exercised * the real code path — a vacuous (theater) test that would have passed even if * `embeddingsSearch` had dropped its guard. * * @param hits - embed-search rows (each carries a vault-relative `rel_path`). * @param isExcluded - true if a vault-relative path is excluded. * @returns a new array with excluded-path rows removed (order preserved). */ export declare function filterExcludedEmbedHits(hits: T[], isExcluded: (relPath: string) => boolean): T[]; /** v3.10 (rc.10) — a scalar a frontmatter filter can match against. */ export type FrontmatterFilterScalar = string | number | boolean; /** v3.10 (rc.10) — one filter value: a scalar, or an array of scalars (OR-semantics). */ export type FrontmatterFilterValue = FrontmatterFilterScalar | FrontmatterFilterScalar[]; /** * v3.10 (rc.10) — does a note's frontmatter satisfy a frontmatter filter? * * AND across keys (every `key: value` pair must match); per-key matching is * scalar-equality or array-membership, with OR over an array filter value * (see `frontmatterValueMatches`). A note with NO frontmatter, or missing any filtered * key, does NOT match (a filter is a positive assertion — absence ≠ match). Pure * + injectable so it's unit-tested directly without spinning up a vault. * * @example * ```ts * frontmatterMatches({ status: "Active", tags: ["proj", "x"] }, { status: "active", tags: "proj" }); // true * frontmatterMatches({ status: "done" }, { status: "active" }); // false * frontmatterMatches(undefined, { status: "active" }); // false (no frontmatter) * ``` */ export declare function frontmatterMatches(frontmatter: Record | undefined | null, filter: Record): boolean; export declare function searchHybrid(vault: Vault, args: { query: string; folder?: string; limit?: number; min_signals?: number; embedding_model?: string; /** v2.2.0: "note" (default) returns 1 hit per note, picking the best * chunk; "block" returns each chunk as a distinct hit so you see the * multiple-paragraph case where one note covers a topic in two places. */ granularity?: "note" | "block"; /** v2.3.0: post-RRF graph boost — rerank by counting how many other * top-K hits link to each one. Default true; set false to disable for * diagnostic comparison (e.g. measuring whether boost helped). */ graph_boost?: boolean; /** * v3.10 (rc.10) — optional frontmatter filter. A `{ key: value }` map; * a hit is kept only if its note's YAML frontmatter satisfies EVERY pair * (AND across keys). Per key, the value matches by scalar-equality * (strings case-insensitive) or array-membership, and a filter value may * itself be an array for OR — see {@link frontmatterMatches}. A note with * no frontmatter, or missing a filtered key, is excluded (a filter is a * positive assertion). Absent ⇒ no filtering (byte-identical to pre-3.10). * Filtering happens on the fused candidate pool (already excluded-pruned), * so a strict filter may return fewer than `limit` hits — that's correct. * @example `{ status: "active", type: ["meeting", "decision"] }` */ filter_frontmatter?: Record; /** * v3.11.6 (S-5) — when true, attach a per-hit {@link SearchHitExplain} * breakdown (RRF rank/score, graph-boost, reranker, and the opt-in recency / * feedback rank movement) to every returned hit. Diagnostic — adds a small * per-hit object and a few `Map`s while ranking. Absent/false ⇒ no `explain` * field and zero extra allocation (byte-identical to pre-S-5). Meaningful * only on the single-query path (`searchHybridMulti` re-fuses sub-query * lists, so per-stage ranks wouldn't map to the final order — it drops it). */ explain?: boolean; }, ctx: { /** FTS5 index, if `--persistent-index` is enabled at server start. */ ftsIndex: FtsIndex | null; /** Path to the `.embed.db` (file may or may not exist — checked at call time). */ embedFile: string; /** * v2.9.0 — optional cross-encoder reranker config. When set, the top-N * hits from RRF (default 50) are re-scored by a BGE-style cross-encoder * and re-sorted before truncation. Adds ~30-50ms per query on M1 CPU * for a 50-candidate set. * * `alias` resolves to a `RERANKER_MODELS` entry. `topN` defaults to 50. * Lazy-loaded — first call downloads the model from HuggingFace * (~25-110 MB depending on alias). Failures are swallowed and surface * via `signal_errors.reranker` so the whole search doesn't break on a * model load issue. */ reranker?: { alias?: string; topN?: number; }; /** * v2.9.0 — test-only injection point. When set, this pre-loaded * reranker is used instead of lazy-loading via `loadReranker(alias)`. * Lets unit tests validate the rerank-and-resort plumbing without * pulling in the real ML model. Unused in production callers. */ rerankerOverride?: { score(query: string, passages: readonly string[]): Promise; }; /** * v2.13.0 — optional HNSW context for the embeddings-search arm. * When passed, the embedding-side k-NN goes through the in-memory * HNSW index (sub-10ms at any scale) instead of the O(n) brute-force * cosine in EmbedDb.search(). Built on serve start; lives in * ServerDeps.hnswContext. Null/undefined → brute-force fallback. */ hnsw?: HnswSearchContext | null; /** * v3.10 (rc.5) — optional opt-in recency re-ranking. When `weight > 0`, * the final fused order is re-sorted by a blend of relevance rank and the * note's live-mtime recency (see `recencyScore` in staleness.ts). `weight = 0` (or * undefined) is a no-op — the default keeps ranking purely relevance-driven. * `staleDays` is the recency half-life (the age at which recency = 0.5). */ recency?: { weight: number; staleDays: number; }; /** * v3.11.0 — optional opt-in closed-loop feedback re-ranking. When `weight > 0` * AND `scores` is non-empty, the final fused order is re-sorted by a blend of * relevance rank and each note's feedback score (`useful/(useful+notUseful+1)`, * from `obsidian_mark_useful` via the `FeedbackStore`). `weight = 0` / empty * `scores` is a provable no-op. Applied AFTER recency so a "human said this * helped" signal is the final tie-break. `scores` is keyed by relPath. */ feedback?: { weight: number; scores: ReadonlyMap; }; }): Promise; /** Max EXTRA phrasings a single `obsidian_search` call may fan out over (rc.7). * The tool handler prepends the main `query`, so the worst case is * MAX_FANOUT_QUERIES + 1 = 9 full hybrid pipeline runs per call. */ export declare const MAX_FANOUT_QUERIES = 8; /** v3.11.6-rc.15 (audit H-1) — how many fan-out sub-queries run concurrently. * Bounds the simultaneous full pipelines (graph-boost / optional reranker / * embedding) so a legal 9-phrasing request can't start 9 heavy pipelines at * once on the event loop. Combined with the `buildTfidfIndex` single-flight * (which collapses the shared corpus BUILD — the expensive read+tokenize scan, * the H-1 amplifier — to ONE regardless), this bounds the worst-case cold * fan-out cost. (rc.16 precision: the corpus *build* is now vault-size- * independent under fan-out; each sub-query still runs its own * `vault.listMarkdown()` directory walk to compute the corpus snapshot — cheap * threadpool readdir/stat metadata I/O, not the content read that made H-1 * HIGH — so total cold cost is dominated by the single build, not the N walks.) */ export declare const MAX_FANOUT_CONCURRENCY = 4; type SearchHybridArgs = Parameters[1]; type SearchHybridCtx = Parameters[2]; /** * v3.11.6-rc.7 (competitive-study C-4) — MULTI-QUERY FAN-OUT. Runs * {@link searchHybrid} once per phrasing and RRF-merges the result LISTS by * note path, so a note that ranks well for ANY phrasing floats to the top. * Useful when the note may use different vocabulary than the caller's first * phrasing (complements HyDE, which reshapes ONE query into an answer vector; * this fuses N independent phrasings). RRF fuses RANKS, not scores, so the * per-query reranker scores — explicitly "not comparable across queries" — are * combined safely by position. * * Each sub-query runs the full hybrid pipeline (BM25 + TF-IDF + embeddings + * optional rerank/recency/feedback); cost scales linearly with the phrasing * count, which is why the caller-facing schema caps it at {@link MAX_FANOUT_QUERIES} * (the tool handler prepends the main `query`, so the worst case is * MAX_FANOUT_QUERIES + 1 = 9 full pipeline runs). * * Granularity caveat (rc.12): the fan-out fuses BY NOTE PATH (`idOf: h.path`), * so `granularity: "block"` degrades to note-level in the fused result — one * hit per note, not per chunk (`chunk_index` reflects the best sub-hit and may * be absent). Use single-query mode when per-chunk hits matter. */ export declare function searchHybridMulti(vault: Vault, args: SearchHybridArgs & { queries: string[]; }, ctx: SearchHybridCtx): Promise; /** * Build a fixed-width snippet centered on a character index within `text`, * plus the 1-based line number where the match starts. * * Window is 60 chars before + `qLen` + 60 chars after, whitespace-collapsed, * with `…` truncation markers when the window is clipped at either end. * Used by {@link searchText} and {@link semanticSearch} to produce human- * readable evidence excerpts. * * @internal * @param text - The full text body to slice. * @param idx - Character offset of the match. Negative values return an * empty snippet. * @param qLen - Length of the matched substring. * @returns `{ snippet, line }` — `line` is 0 if `idx < 0`. * @example * ```ts * sliceSnippet("Hello world, this is a long text", 6, 5); * // → { snippet: "Hello world, this is a long text", line: 1 } * ``` */ /** * Case-fold a string while recording, for every folded code unit, the index in * the ORIGINAL string it came from. * * `String.prototype.toLowerCase()` is NOT length-preserving (`İ` U+0130 → `i̇`, * 1 code unit → 2; final-sigma; the German ẞ; …). So an offset obtained from * `original.toLowerCase().indexOf(needle)` is an index into the FOLDED string and * drifts past the true position in `original` by the cumulative expansion of * every fold-expanding char before the match. Feeding that drifted offset to * {@link sliceSnippet} mis-centres the window and miscounts the line number. * * Iterates by code POINT so a surrogate pair maps to the code-unit index where * the pair begins (matching `sliceSnippet`'s code-unit slicing). `map.length === * folded.length`; `map[k]` is the original code-unit index of folded unit `k`. * * v3.11.0-rc.21 — the read/snippet-path siblings of the rc.18 `replaceLineOnce` * fold-offset class (found by the post-rc.20 re-sweep in `semanticSearch` + * `searchText`, where a folded offset was sliced against the original body). */ export declare function foldWithMap(original: string): { folded: string; map: number[]; }; /** * Case-insensitive `indexOf` that returns the offset into the ORIGINAL string * (not the folded copy). `needleLower` must already be lower-cased. Returns -1 * if not found. See {@link foldWithMap} for why the naive * `original.toLowerCase().indexOf(needle)` is wrong for length-changing folds. * * KNOWN COSMETIC LIMITATION (v3.11.1-rc.1, documented-accept) — `foldWithMap` folds the * haystack per CODE POINT (context-free), but `needleLower` here is the caller's * whole-string-`toLowerCase()` query token, which applies Greek word-final sigma * (`"ΟΔΟΣ"`→`"οδος"`, `ς`) while the body folds to `σ`. So a query token ending in a * capital Σ can return -1 and the snippet falls back to the note start instead of * centring on the hit. This is SNIPPET CENTRING ONLY — TF-IDF SCORING is unaffected * (query and document tokens are both whole-string-folded the same way upstream, so the * hit still ranks). The materially-harmful sibling (a SILENT under-replace in * `replace_in_notes`) was fixed in v3.11.1-rc.1 by folding the needle per code point * (`foldForMatch`, wildcard-match.ts); aligning the read path here would require re-folding the whole * TF-IDF token pipeline per code point (a scoring-path change) — disproportionate for a * snippet-window position, so the cosmetic residual is accepted and pinned by a contract test. */ export declare function foldedIndexOf(original: string, needleLower: string): number; export declare function sliceSnippet(text: string, idx: number, qLen: number): { snippet: string; line: number; }; export {}; //# sourceMappingURL=search.d.ts.map