/** * Search orchestrator — hybrid FTS5 + vector + score fusion. * * Flow: * 1. FTS5 BM25 query on memories_fts * 2. embed(query) via EmbedProvider → vec.search() (mock or real) * 3. fuseHits — merge FTS + cosine scores * 4. apply SQL filters (type, repo, project, since) on the fused id set * 5. join full Memory records, return top-k hits * * VecFilter is intentionally empty on vector search calls because sqlite-vec * does not support pre-filtering. All filters are applied post-fusion. */ import type { DB } from '../storage/db.js'; import type { EmbedProvider } from '../contracts/index.js'; import type { MemoryType, MemoryScope } from '../contracts/index.js'; import { type RerankOpts } from './rerank.js'; import { type DecomposeOpts } from './decompose.js'; import { type QueryRewriteOpts } from './query-rewrite.js'; import { type EvidenceBundlingOpts } from './evidence-bundle.js'; export interface SearchFilters { type?: string[]; /** * atom@2 repo/project consolidation (plan 20260709): UX-alias input only — * GET /search?repo=, POST /recall filters.repo, and the MCP tools still * accept it for back-compat, but it is folded into `project`'s OR-list at * the SQL boundary below (mergeRepoAlias), never queried as its own * `memories.repo` column. A caller that sends both gets the union. */ repo?: string; /** * Project filter (FEAT-423). Exact match on `memories.project`. A single * string → `project = ?`; a string[] → `project IN (...)` (OR-semantics, * mirrors `type[]`). Empty array = no constraint. Absent → all projects. */ project?: string | string[]; /** * Agent filter (FEAT-423 nice-to-have). Exact match on `memories.agent` * (the provenance `agent`/`agent_type` populated at ingest). Single string * or string[] (IN). Absent → all agents. Whether this excludes non-matches * (hard filter) or merely re-ranks matches upward (soft boost) is governed * by `agentMode` below. */ agent?: string | string[]; /** * FEAT-426 (role-scoped soft-boost recall, FEAT-219 consumer): selects how * `agent` above is applied. * - 'filter' (default, omitted): current behavior — `agent` is a HARD * filter, non-matching atoms are excluded at the SQL layer post-fusion. * Byte-identical to pre-FEAT-426 behavior; existing callers are * unaffected without any code change. * - 'boost': `agent` is NOT applied as a SQL filter — every otherwise- * matching atom stays in the result set, but atoms whose * `memories.agent` matches get the η agent-match bonus (see fuse.ts), * ranking them higher without excluding anyone else. Requires * `weights.eta > 0` to have any effect (eta defaults to 0 = OFF). * Ignored when `agent` is undefined. */ agentMode?: 'filter' | 'boost'; since?: number; /** * Bitemporal time-travel (FEAT-401, ADR-001/ADR-005): return memories as * they stood at this instant (epoch ms) rather than the current snapshot. * Absent = current behavior (only currently-valid rows). */ as_of?: number; /** * Entity filter (FEAT-402 slice 2 AC-4). Resolved through * EntityRepo.resolveIds (AC-9 normalize seam: exact match, then LIKE * substring fallback) to one or more entities.id, then intersected with * the FTS+vec candidate set BEFORE fusion — the result is all-and-only * entity-linked members of that candidate set, not a post-fusion filter. * An unresolvable entity name yields zero results (not an unfiltered * search). * * FEAT-453 §3.3: combined with `as_of`, the intersection narrows to * fact-level validity — a memory only qualifies if the matched entity * link's effective window (clipped to the memory's own valid_from/ * valid_to) covers `as_of`, even if the memory itself is still otherwise * "current." `entity` alone (no `as_of`) is unaffected — same as before * FEAT-453. */ entity?: string; /** * FEAT-532 L2: hard filter on `memories.scope` (ADR-009 private|team|org). * A non-empty list produces `scope IN (...)` post-fusion, same shape as * `type[]`. Absent or empty = no constraint (all scopes), byte-identical * to pre-FEAT-532 behavior. */ scope?: MemoryScope[]; } /** * Astramem-retrieval-result@1 `ScoreExplanation.signals[name]` shape * (contracts/schemas/retrieval-result.v1.schema.json) — per-signal raw * score, effective weight, and this signal's contribution to the fused * score (`final`). `raw` is the true un-normalized value (e.g. the negated * SQLite bm25() score, the raw cosine similarity); `final` is * `normalized(raw) * weight`, i.e. this signal's actual share of `score`. */ export interface ScoreSignal { raw: number; weight: number; final: number; } /** * Astramem-retrieval-result@1 `ScoreExplanation` (ADR-005 debugging/trust * surface). `final` always equals the hit's top-level `score` — CONTRACT- * FREEZE §2 (astragenie/memory#759) requires this invariant regardless of * which signals happen to be present. */ export interface ScoreExplanation { final: number; signals: Record; /** * FEAT-500: argmax of `signals` by `.final` — the single signal that * contributed the most to this hit's fused score (Mnemon's `via` * equivalent). Deterministic tie-break: alphabetical by signal name, so * two equal `.final` values always resolve to the same winner regardless * of `Object.keys` iteration order. `undefined` only when `signals` is * empty (never happens in practice — `importance`/`freshness`/ * `usefulness` are always present — but the type stays honest for a * hypothetical empty-signals caller). Computed fresh wherever `signals` * is finalized (base fusion in `buildExplanation`, and again after the * rerank merge below) so it always reflects the actual signals present * on this explanation, not a stale pre-merge winner. OPTIONAL on the wire * schema (contracts/schemas/retrieval-result.v1.schema.json), same * additive-field posture as `reason`. */ top_signal?: string; } /** * Argmax of `signals` by `.final`, alphabetical-by-name tie-break (FEAT-500). * Pure function — no dependency on where `signals` came from, so it is safe * to call both on the base fusion breakdown and again after a later stage * (e.g. rerank) merges an additional signal in. */ export declare function computeTopSignal(signals: Record): string | undefined; export interface SearchHit { id: string; type: MemoryType; text: string; score: number; /** * Fusion-leg indicator: which candidate-gathering stage(s) produced this * id (FTS5 BM25, vector search, or both) — an INTERNAL local-only * debugging field distinct from the canonical wire contract's `source` * (which means memory *provenance*, see `capture_source` below). Never * renamed here to avoid breaking existing consumers (CLI table, dashboard * debug page, tests) that predate the retrieval@1 contract adoption. */ source: 'fts' | 'vec' | 'both'; /** ADR-009 memory scope (private|team|org). Always present — `memories.scope` is NOT NULL. */ scope: MemoryScope; /** `memories.importance` [0,1]. Always present — NOT NULL DEFAULT 0.5. */ importance: number; /** `memories.confidence` [0,1]. Always present — NOT NULL DEFAULT 0.5. */ confidence: number; /** `memories.created_at`, ISO-8601 (wire-ready — contracts/schemas/retrieval-result.v1.schema.json `created_at` is `format: date-time`). */ created_at: string; /** * `memories.capture_source` (migration 024) — CONTRACT-FREEZE §1 maps * this to the canonical wire `source` field ("origin of the memory"). * Named `capture_source` here, not `source`, to avoid colliding with the * pre-existing fusion-leg `source` field above; a route/wire-serialization * layer is the natural place to rename it to `source` on the JSON * response, which is out of this change's scope (contracts/ + src/search/ * only — see astragenie/astramem-local PR for retrieval@1 adoption). * Omitted (not `null`) when the memory has no capture_source, since the * canonical schema's `source` is `{type: "string"}` with no null variant. */ capture_source?: string; /** * ScoreExplanation (ADR-005/CONTRACT-FREEZE §2) — ALWAYS present as of * the retrieval@1 adoption (2026-07-13), not just when reranked. Base * signals are bm25/cosine (only when that leg produced a candidate for * this id)/importance/freshness/usefulness, plus entity_bonus/agent_bonus * when their weight (zeta/eta) is active. Gains a `cross_encoder` signal * (merged in, not replacing the base signals) when the rerank stage * (FEAT-452) actually scored this hit — see `reranked`/`rerank_score` * below. */ explanation: ScoreExplanation; /** * FEAT-452: present + `reranked: true` only when the cross-encoder rerank * stage (issue #26, src/search/rerank.ts) actually scored this hit this * call. `score` above always stays the original fused score — it is never * overwritten by rerank; `rerank_score`/`explanation.signals.cross_encoder` * carry the cross-encoder's own verdict as a distinct, additive signal * (ADR-005 `ScoreExplanation.signals` shape — see * docs/runbooks/cross-encoder-rerank.md). Absent (not just `false`) when * rerank is disabled (the default), when this hit fell beyond * `opts.rerank.topK`, or when the whole-call timeout/error fallback fired. */ reranked?: true; rerank_score?: number; /** * issue #352B (Ask B gap 2): present only when this atom is currently the * LOSER side of an OPEN (`status='pending'`) `kind='contradiction'` * consolidation proposal — a fresher/contradicting atom was already * detected (`winner_id`) but no supersede edge has been created yet, so * this atom keeps surfacing in ordinary recall (unlike a properly * superseded atom, which `validityFilterClause` already hard-hides). * Purely informational — populated regardless of `search.theta` (the θ * fusion weight, see fuse.ts), which defaults to 0 and is governed * separately (`applyFusionGovernance`). Consumers can use this to render * a "possibly outdated" marker even at theta=0. LOCAL-ONLY: deliberately * excluded from the canonical astramem-retrieval-result@1 wire hit * (`toWireHit`, src/contracts/wire-hit.ts) — that schema is * `additionalProperties: false` and cross-repo, so this field is visible * on GET /search and the MCP tools' raw JSON, but not on POST /recall's * envelope, until/unless a cross-repo contract change adds it there. */ correction_pending?: { proposal_id: string; winner_id: string; confidence: number; }; /** * P2 retrieval-overhaul plan (2026-07-20): "Rerank `query + atom text + * evidence excerpt`, not atom text alone" — this is the field * `buildRerankCandidateText` (src/search/rerank.ts) was already reading * before it had a producer. Sourced from the memory's provenance: prefers * `evidence_span` (migration 057 — the exact verbatim transcript text * `locate-evidence.ts` traced the atom back to) over the legacy `evidence` * string (migration 004 — the extractor's own, possibly-paraphrased * excerpt) when both are present, since the located span is strictly more * trustworthy. Bounded to `MAX_EVIDENCE_EXCERPT_CHARS` so a whole-turn * fuzzy-tier match (locate-evidence.ts's tier 2 can return an entire * transcript line) can't blow up the cross-encoder input. Absent (not * `null`) when the memory has neither field — same "omit rather than * fake" convention as `capture_source` above. * * LOCAL-ONLY: deliberately stripped by `toWireHit` (src/contracts/ * wire-hit.ts), same treatment as `source`/`reranked`/`rerank_score`/ * `correction_pending` — the closed astramem-retrieval-result@1 schema * (`additionalProperties: false`) doesn't declare this field yet, so it's * visible on GET /search and the MCP tools' raw JSON but not on POST * /recall's canonical envelope. The rerank stage itself still benefits: * `search()` builds `results` (with `evidence` populated) BEFORE calling * `applyRerank`, so the cross-encoder always sees it regardless of what * the wire response later strips. */ evidence?: string; /** * Wave-6 (P2 retrieval-overhaul, evidence-sufficiency lever, * src/search/evidence-bundle.ts): present + `true` only on a hit the * evidence-bundling stage ADDED to an already-finalized top-k (never on an * ordinarily-fused/reranked hit) — absent (not just `false`) otherwise, * same "additive marker" convention as `reranked`. `score` on a bundled * hit is a synthetic floor value (never a real fusion/rerank score, see * `applyEvidenceBundling`'s doc comment), so a consumer that cares about * hit provenance should key off THIS field, not `score`. * * LOCAL-ONLY: stripped by `toWireHit` (src/contracts/wire-hit.ts), same * treatment as `evidence`/`correction_pending` — the closed * astramem-retrieval-result@1 schema doesn't declare it yet. */ bundled?: true; /** Why the evidence-bundling stage pulled this atom in — which scoped * query (same-entity via `memory_entities`, same-session via * `memories.session_id`) found it. Present only alongside `bundled: true`. */ bundle_reason?: 'same_entity' | 'same_session'; } export interface SearchOpts { db: DB; embed: EmbedProvider; weights: { alpha: number; beta: number; gamma: number; delta: number; epsilon?: number; zeta?: number; eta?: number; theta?: number; /** issue #190: optional so every existing caller (eval harness's own * narrower weights type, hand-built test fixtures) keeps compiling * unchanged — see the DEFAULT_IMPLICIT_POSITIVE_WEIGHT fallback where * this is consumed below. Real production callers pass the full * `Config['search']` (via resolvePresetWeights), which always carries * this field. */ usefulness?: { implicitPositive: { weight: number; }; }; }; /** Multiplier used by vector search (cap to limit vector scan) */ vecK?: number; /** * SLICE-410-3: when true, search() returns SearchDebugHit[] — the * per-candidate fusion intermediates (raw+normalized bm25/cosine, * importance, freshness, usefulness, entityBonus, effective weights, and * the final fused score) instead of collapsing to SearchHit[]. Every * other step (candidate gathering, entity filter, post-fusion SQL * filters, validity/as_of, limit, ranking order) is unchanged — debug is * purely an alternate projection of the same fused list, so debug:false * or omitted is byte-identical to pre-change behavior (AC-2). */ debug?: boolean; /** * Optional post-fusion cross-encoder rerank stage (issue #26, ADR-005). * `undefined` (the default — see config.crossEncoder.enabled / resolveRerankOpts * in rerank.ts) means the stage is never invoked and the SearchHit[] path is * byte-identical to pre-rerank behavior. When present, only the debug:false * path is affected — SearchDebugHit[] (debug:true) always reflects the raw * fusion breakdown, never reranked, since its purpose is explaining fusion. */ rerank?: RerankOpts; /** * Optional multi-hop query-decomposition stage (WS6, src/search/decompose.ts). * `undefined` (the default — see config.multiHop.enabled / resolveDecomposeOpts * in decompose.ts) means the stage is never invoked and search() is * byte-identical to pre-WS6 behavior. When present, sub-query-sourced * candidates are fused in a SEPARATE pass (own normalization) and merged * in as a capped, damped addition — see the merge step in search() for the * dilution bound. debug:true is unaffected: it always reflects the primary * fusion breakdown only, same posture as rerank's debug interaction. */ decompose?: DecomposeOpts; /** * FEAT-532 L2 (astramem-retrieval-query@1 `mode`, contracts/schemas/ * retrieval-query.v1.schema.json): which candidate-gathering leg(s) * gatherCandidates() runs. `undefined` defaults to `'hybrid'` — byte- * identical to pre-FEAT-532 behavior (both legs always ran). `'keyword'` * skips vector gathering entirely (FTS5 BM25 only); `'semantic'` skips FTS * gathering entirely (vector only). Applies to both the primary query and * every WS6 decompose sub-query, so a caller-selected mode isn't a way to * escape it via decomposition. */ mode?: 'keyword' | 'semantic' | 'hybrid'; /** * Optional pre-recall query rewrite/expansion stage (FEAT-550, * src/search/query-rewrite.ts). `undefined` (the default — see * config.search.queryRewrite.mode / resolveQueryRewriteOpts) means the * stage is never invoked and search() is byte-identical to pre-FEAT-550 * behavior (AC-1). Even when present, the stage only actually runs when * `expand` (below) is also `true` this call — this FEAT's latency-gating * requirement ("No default-on for interactive recall until latency * measured") means an enabled config makes the capability AVAILABLE, not * default-on for every search() call. */ queryRewrite?: QueryRewriteOpts; /** * Per-call opt-in for the query-rewrite stage above (FEAT-550 AC-1). * `undefined`/`false` (the default) never invokes the rewrite call even * when `queryRewrite` is configured — see that field's doc comment. */ expand?: boolean; /** * Optional post-rerank evidence-bundling stage (Wave-6, P2 retrieval- * overhaul evidence-sufficiency lever, src/search/evidence-bundle.ts). * `undefined` (the default — see config.evidenceBundling.enabled / * resolveEvidenceBundlingOpts) means the stage is never invoked and * search() is byte-identical to pre-Wave-6 behavior. When present, it runs * once against the FINALIZED top-k (post-rerank when `rerank` is also * set, post-fusion-truncation otherwise) and only ever APPENDS additional * scoped atoms — it never reorders or drops an existing hit. debug:true is * unaffected (that path returns before this stage would ever run), same * posture as rerank/decompose's debug interaction. */ evidenceBundling?: EvidenceBundlingOpts; } /** * Per-candidate fusion breakdown (SLICE-410-3 AC-1) — the upstream contract * for SLICE-410-6's search-debug dashboard page. Mirrors the components * `fuseHits`/`fuseScores` (fuse.ts) compute internally and normally discard. * * Sentinel (AC-4): when a leg has no hit for this candidate (e.g. embed * provider down → no vector leg at all), that leg's `raw` is `null` and * `normalized` is `0` — identical to the no-signal default `fuseHits` * already uses internally, so `score` stays reproducible from these fields * even in a degraded (FTS-only or vec-only) run. * * `usefulness`/`entityBonus`/`weights` are always the *effective* values * actually fed into `fuseScores` (defaults resolved, e.g. usefulness 0.5 / * entityBonus 0 / zeta 0) so `score` can be reconstructed exactly as: * weights.alpha * bm25.normalized + weights.beta * cosine.normalized * + weights.gamma * importance + weights.delta * freshness * + weights.epsilon * usefulness + weights.zeta * entityBonus */ export interface SearchDebugHit { id: string; source: 'fts' | 'vec' | 'both'; bm25: { raw: number | null; normalized: number; }; cosine: { raw: number | null; normalized: number; }; importance: number; freshness: number; usefulness: number; entityBonus: number; weights: { alpha: number; beta: number; gamma: number; delta: number; epsilon: number; zeta: number; }; score: number; } /** * Bitemporal validity SQL clause (FEAT-401) — the ONE shared filter used by * every caller of search() (GET /search, POST /recall, the eval harness). * There is deliberately no second implementation anywhere else: the CLI * `--as-of` flag and the API `as_of` filter both terminate here because the * CLI is a thin HTTP client of the same routes that call search(). * * - No as_of (undefined): current snapshot — only rows with valid_to IS * NULL surface, byte-identical to pre-FEAT-401 behavior (AC-2). * - as_of = T: the row valid AT INSTANT T — valid_from <= T AND (valid_to * IS NULL OR valid_to > T). Half-open interval [valid_from, valid_to): * at the exact instant a supersede/invalidate event lands, the new * generation is already the one considered valid (AC-5). */ export declare function validityFilterClause(asOf?: number, now?: number): { clause: string; params: number[]; }; /** * Parse an `as_of` wire value (ISO-8601 date-time string) into epoch ms. * Shared by every route that accepts the filter (GET /search query param, * POST /recall body) so a malformed value is rejected identically everywhere * — one parsing path, not a per-route reimplementation. Returns undefined * for an absent/empty value; throws for a present-but-unparseable value so * callers can turn it into a 400. */ export declare function parseAsOf(value: string | undefined): number | undefined; /** * Deterministic fake vector for testing — seeded by text hash, dim * defaults to DEFAULT_EMBED_DIM (1024). Exported so tests can call it * directly without importing the EmbedProvider. Pass `dim` to generate a * fixture vector matching a non-default schema (FEAT-409 AC-2). */ export declare function makeFakeVec(text: string, dim?: number): Float32Array; /** * True when `name` appears in `query` as a whole word/phrase — bounded by a * non-alphanumeric character (or the string start/end) on both sides — not * merely as a raw substring (issue #207 AC-3: naked `query.includes(name)` * let an entity named "go" match inside "going"). Both inputs are expected * already lowercased/normalized by the caller. Uses Unicode letter/number * classes (not `\w`, which is ASCII-only and would treat non-ASCII letters * as boundaries) so this behaves correctly for non-English entity names too. * Exported so tests can pin down the matching rule directly, without going * through the full fuse.ts weighted-normalization pipeline (where turning * zeta on at all dilutes every candidate's score via the shared denominator, * independent of whether a real bonus applied — a confound when testing * match/no-match through an end-to-end search() call). */ export declare function entityNameMatchesQuery(query: string, name: string): boolean; /** issue #352B: shape of the corrected-atom marker surfaced on `SearchHit`. */ export interface CorrectionPendingSignal { proposal_id: string; winner_id: string; confidence: number; } export declare function search(query: string, filters: SearchFilters, limit: number, opts: SearchOpts & { debug: true; }): Promise; export declare function search(query: string, filters: SearchFilters, limit: number, opts: SearchOpts): Promise;