/** * Cross-encoder rerank stage (issue #26, ADR-005 cloud-parity seam). * * ADR-005 ruled local ships v1 with "no reranker (CPU budget)" — this stage * is the OFF-by-default seam that lets a future rerank rollout happen via * config flip + eval evidence, without ever touching search()'s default * behavior. It mirrors the cloud engine's `ICrossEncoderRanker` shape * (StubCrossEncoderRanker / HttpCrossEncoderRanker, config * `Search:CrossEncoder.{Enabled,TopK,Provider,TimeoutMs}`) described in * issue #26, adapted to this repo's provider-abstraction pattern * (contracts/embed.ts's `EmbedProvider`). * * Contract: * - `CrossEncoderProvider.score()` returns a query-conditioned relevance * score per candidate id, clamped to [0,1] by the stage (defense-in-depth, * same posture as fuseScores() in fuse.ts) so the wire score contract * holds regardless of what a future provider returns. * - The stage only reranks the top `topK` fused hits (cost control) and * leaves everything beyond that position untouched, in its original * fused order. * - On timeout or provider error, the stage falls back to the un-reranked * fused order for the WHOLE call (never a partial reorder) — degrades * quality, never availability, matching the cloud engine's fallback * contract from issue #26. * - FEAT-452: a hit the stage actually reorders gains `reranked`/ * `rerank_score`/`explanation` (see `RerankFields` below) rather than * having its `score` overwritten in place — `score` always stays the * original fused value, so a caller can tell a fused score from a * reranked one instead of losing the fused value the moment rerank runs. */ import type { Config } from '../config/config.js'; /** One post-fusion candidate handed to the reranker. */ export interface CrossEncoderCandidate { id: string; text: string; /** Pre-rerank fused score — providers may ignore it or blend with it. */ fusedScore: number; } export interface CrossEncoderProvider { readonly name: 'mock' | 'http' | 'onnx'; /** * Score every candidate against `query`. Returned map need not cover every * id — a missing id falls back to its original fused score (see * `applyRerank`). Scores need not be pre-clamped to [0,1]; the stage clamps * defensively before use. * * `signal` (issue #261): fires when `applyRerank`'s timeout budget * elapses. `HttpCrossEncoderProvider` must combine it with its own * internal `AbortSignal.timeout` (never replace it) so a timeout actually * cancels the in-flight HTTP request instead of abandoning it. * `MockCrossEncoderProvider` ignores it — it never does I/O. */ score(query: string, candidates: CrossEncoderCandidate[], signal?: AbortSignal): Promise>; } /** * Deterministic MOCK cross-encoder: lexical (Jaccard) token overlap between * the query and candidate text, in [0,1]. This is NOT a real cross-encoder — * it carries no semantic signal beyond shared tokens — but it is fully * deterministic (no network, no model, no seed drift across OSes/CI), which * is exactly what a rerank-stage unit test and the ADR-005 eval harness need * to prove the stage is correctly wired end-to-end. `HttpCrossEncoderProvider` * (below) plugs a real sidecar in behind the same `CrossEncoderProvider` * interface without touching `applyRerank`. */ export declare class MockCrossEncoderProvider implements CrossEncoderProvider { readonly name: "mock"; score(query: string, candidates: CrossEncoderCandidate[]): Promise>; } export interface HttpCrossEncoderConfig { /** Base URL of the sidecar's rerank endpoint (config.crossEncoder.sidecarUrl). */ url: string; /** Optional model id forwarded in the request body (config.crossEncoder.model). */ model?: string; /** Per-request abort budget. Independent of (but normally set to) * `RerankOpts.timeoutMs` — see `buildCrossEncoderProvider`. */ timeoutMs?: number; /** Test-only seam: injected fetch so unit tests never hit the network. */ fetchImpl?: typeof fetch; } /** * Real HTTP cross-encoder provider (issue #26/#94). Speaks the common * cross-encoder sidecar contract: a Hugging Face Text Embeddings Inference * (TEI) `/rerank`-shaped endpoint. * * Request: `POST ` with JSON body `{ query, texts, model? }`, where * `texts[i]` corresponds positionally to `candidates[i]`. * Response: either a bare array of `{ index, score }` (TEI's native shape, * `index` into `texts`) or `{ results: [{ index, score }] }` * (the wrapped shape some sidecars use). Either is accepted. * * Errors (non-2xx status, network failure, malformed/missing response * shape) are thrown rather than swallowed here — `applyRerank` is the single * place that converts a provider failure into the whole-call fallback to the * un-reranked fused order, so this provider must not silently return a * partial or empty map on failure (that would look like "no candidate * matched" instead of "the sidecar is unreachable"). */ export declare class HttpCrossEncoderProvider implements CrossEncoderProvider { readonly name: "http"; private readonly url; private readonly model; private readonly timeoutMs; private readonly fetchImpl; constructor(config: HttpCrossEncoderConfig); score(query: string, candidates: CrossEncoderCandidate[], signal?: AbortSignal): Promise>; } /** Resolved rerank options as consumed by `applyRerank` / `SearchOpts.rerank`. */ export interface RerankOpts { topK: number; timeoutMs: number; provider: CrossEncoderProvider; } /** * Build a `CrossEncoderProvider` from config. `provider: 'http'` requires * `sidecarUrl` — throws a clear config error at build time (startup) rather * than at first-search-time if it's missing. `provider: 'onnx'` (P2 * retrieval overhaul, 2026-07-20) never throws at build time — the model * loads lazily on first `score()` call, same posture as * `OnnxEmbedProvider` (providers/embed/onnx.ts): selecting the provider * without a reachable model artifact does not crash daemon boot, it * surfaces through the first real rerank call's timeout/error fallback * instead (`applyRerank` degrades to the un-reranked order — quality, never * availability). See docs/runbooks/cross-encoder-rerank.md for the endpoint * contract and how to run an http sidecar. * * `dataDir` (optional, second param — `resolveRerankOpts` below passes * `config.dataDir`) only matters for `provider: 'onnx'`: it derives the * default weight-cache directory `/models/onnx/`, the SAME root * `providers/index.ts` uses for the embed model (ADR-018 S2) — different HF * repo ids nest under distinct subdirectories there, so embed and rerank * weights coexist without collision. `config.crossEncoder.onnx.cacheDir` * overrides this when set; omitting both `dataDir` and the override defers * to `@huggingface/transformers`' own default cache resolution (matches * `buildCrossEncoderProvider`'s existing test-call signature, which never * passed a second argument before this change). */ export declare function buildCrossEncoderProvider(config: Config['crossEncoder'], dataDir?: string): CrossEncoderProvider; /** * Resolve `SearchOpts.rerank` from config: `undefined` when disabled (so the * search pipeline takes zero extra branches when the feature is off), or a * fully-built `RerankOpts` (provider instantiated once, reused per call) when * enabled. */ export declare function resolveRerankOpts(config: Config): RerankOpts | undefined; /** * ADR-005 `ScoreExplanation.signals[name]` shape * (contracts/schemas/retrieval-result.v1.schema.json), reused here so a * reranked hit's cross-encoder provenance is additive to — and validates * against — the shared retrieval-result contract's open signals map (FEAT-452). */ export interface RerankSignal { /** Fused score this hit carried into the cross-encoder call — same value as `score`. */ raw: number; /** Rerank fully determines a reranked hit's position within `topK`, no blending with other signals — always 1. */ weight: number; /** Clamped cross-encoder score — same value as the flat `rerank_score` below. */ final: number; } /** * Rerank provenance a hit gains once the cross-encoder stage actually scores * it (FEAT-452). Present + `reranked: true` only on hits the stage scored * this call — i.e. within `opts.topK`, and the call didn't hit the * whole-call timeout/error fallback; absent everywhere else (not just * `false`), so an un-reranked hit's shape is identical to before this field * existed. `score` is left untouched by `applyRerank` regardless — it always * stays the original fused value. */ export interface RerankFields { reranked: true; rerank_score: number; explanation: { signals: { cross_encoder: RerankSignal; }; }; } /** * Builds the text a candidate is scored against — `query + atom text + * evidence excerpt`, not atom text alone (P2 retrieval overhaul plan, * 2026-07-20: "Rerank `query + atom text + evidence excerpt`, not atom text * alone"). `evidence` is an OPTIONAL, forward-compatible field on the * generic hit type `applyRerank` accepts: today's actual call site * (`search.ts`'s `SearchHit`) does not populate it, so this degrades to * atom text alone until a future change threads `Memory.evidence` * (`contracts/memory.ts`) through `SearchHit` — that's a `search.ts` * change, out of this file's ownership (see docs/runbooks/cross-encoder- * rerank.md's "Rerank input" note for the full status). Exported standalone * so this text-composition rule is independently testable. */ export declare function buildRerankCandidateText(h: { text: string; evidence?: string | null; }): string; /** * Apply the rerank stage to an already-fused, already-ordered hit list. * Reorders only the first `opts.topK` hits by cross-encoder score; hits * beyond that position are appended unchanged, in their original relative * order. On timeout or provider error, returns `hits` completely unchanged * (whole-call fallback, not a partial reorder) — availability over quality. * * FEAT-452: reordered hits gain `RerankFields` (see above) rather than * having `score` overwritten with the cross-encoder value — `score` stays * the fused score, `rerank_score`/`explanation` carry the cross-encoder's * verdict as a distinct, additive signal. */ export declare function applyRerank(query: string, hits: T[], opts: RerankOpts): Promise>>;