/** * Slice Z-A (2.8.0) — LLM rerank service (Y2 architecture, zero new deps). * * Receives a fuzzy top-N candidate list (from `searchMemory` / * `MemorySearchResult[]`) and asks an LLM to rerank them by relevance * to the query. Returns the top-K in descending relevance. * * Architecture note (locked decision — see * `.peaks/memory/2026-06-18-peaks-zvec-spike-proposal.md` §Y2): * * - "Active IDE LLM" is a deliberate abstraction: peaks-cli itself * has NO direct LLM API key. The chat call is performed by the * active IDE (Claude Code / Trae / Cursor / Codex / ...) using * its own authentication chain. * * - The current `IdeAdapter` interface has no `chat()` method — * `SubAgentDispatcher` returns IDE-private tool-call descriptors * (sub-agent dispatch, not direct chat). This service therefore * takes a `chat` function INJECTION at the call site. The default * is a no-op that fails-open (returns the original fuzzy order). * * - This is a SPIKE artifact for Z-A. The real chat wiring (either * a new `IdeAdapter.chat()` method, or routing through * `SubAgentDispatcher` with a "rerank" role) is a Z-B prerequisite * and is tracked in the GO/NO-GO report at * `.peaks/memory/memory-search-y2-rerank-2026-06-19-decision.md`. * * Why this is split from `memory-search-service.ts`: * * - The fuzzy kernel is pure + synchronous + 100% testable today. * - The rerank layer is async + IO-bound + 100% fallback. Keeping * it separate means the existing 2800+ fuzzy tests are untouched * and the new spike has its own test surface (per the Z-A * proposal's "不重写 memory-search-service.ts" red line). * * Why 4-bytes-per-token: * * - `headroom-client.ts:60` already uses `BYTES_PER_TOKEN = 4` as * its rough English-text approximation. Reusing the same constant * keeps token estimates comparable across the headroom + rerank * pipelines in the AC-ZA-5 benchmark. * * Out of scope (YAGNI per Karpathy #2 Simplicity First): * * - No cross-process cache (AC-ZA-6 deferred — only build if * AC-ZA-5 shows a hot path). * - No rerank-prompt optimization beyond the minimal JSON * output format. * - No integration with `memory-search-service.ts` (Z-A is a spike; * the wiring into `peaks memory search` is Z-B). */ import type { MemorySearchResult } from './memory-search-service.js'; /** * One chat message in OpenAI-compatible format. The rerank layer * sends a single user-role message; `system` is reserved for Z-B * once the prompt-engineering is solid. */ export interface RerankChatMessage { readonly role: 'user' | 'system' | 'assistant'; readonly content: string; } /** * Chat function injection. The caller is responsible for routing * the messages to the active IDE's LLM (or a mock for tests). The * function MUST resolve with the LLM's raw text response, or reject * on timeout / network error. Markdown code fences are tolerated by * `parseRerankResponse` and are NOT the chat function's job to strip. */ export type RerankChatFn = (messages: readonly RerankChatMessage[], signal: AbortSignal) => Promise; /** * Options for `rerank()`. All optional; defaults match the Z-A * proposal's AC-ZA-4 (fuzzy top-10 → rerank → top-5). */ export interface RerankOptions { /** Max candidates fed to the LLM. Default 10 (per AC-ZA-4). */ readonly topN?: number; /** Max results returned to the caller. Default 5 (per AC-ZA-4). */ readonly topK?: number; /** Per-call chat timeout in ms. Default 5000 (per AC-ZA-8 L2). */ readonly chatTimeoutMs?: number; /** Chat function injection. Default fails-open (returns input order). */ readonly chat?: RerankChatFn; } /** * Token accounting for a single rerank call. Exposed so the * AC-ZA-5 benchmark can report per-pipeline cost. */ export interface RerankTokenUsage { /** Tokens used to assemble the rerank prompt (query + candidates). */ readonly promptTokens: number; /** Tokens the LLM emitted (estimated via length/4). */ readonly responseTokens: number; readonly total: number; } /** * Rerank result. Always returns a `topK` array (possibly the * original fuzzy order if rerank failed / was skipped) and a * `warning` describing any degradation. Never throws — the * caller can always use `topK` as a safe drop-in for the * fuzzy top-K. */ export interface RerankResult { /** Final ordered list (length <= topK, never more than input). */ readonly topK: readonly MemorySearchResult[]; /** Token accounting (zeros when rerank was skipped). */ readonly tokens: RerankTokenUsage; /** One of 'reranked' | 'parse-failed-fallback' | 'chat-failed-fallback' * | 'timeout-fallback' | 'skipped-no-chat-fn' | 'noop-empty-input'. */ readonly degradation: string; /** Human-readable detail. null when degradation === 'reranked'. */ readonly warning: string | null; } /** * Estimate token count for a string. `1 token ≈ 4 bytes` for English * text — same approximation as `headroom-client.ts:60`. */ export declare function estimateTokens(text: string): number; /** * Build the rerank prompt. Pure function — no IO, no side effects. * Trivially testable. * * Format (locked for Z-A; Z-B may tune): * * Query: "" * * Rank the following candidate memories by relevance to the * query. Return a JSON array of the candidate indices in * descending relevance. Return only the JSON — no prose, no * markdown. * * Candidates: * [0] name-a — description-a… * [1] name-b — description-b… * ... * * The LLM is expected to return e.g. `[3, 0, 4, 1, 2]`. The * output is parsed by `parseRerankResponse`. */ export declare function renderRerankPrompt(query: string, candidates: readonly MemorySearchResult[]): string; /** * Parse the LLM's raw text response into an ordered list of * candidate indices. Tolerates: * * - Pure JSON arrays: `[3, 0, 4, 1, 2]` * - JSON wrapped in markdown code fences: * ```json * [3, 0, 4, 1, 2] * ``` * - Whitespace and surrounding prose (best-effort: looks for the * first `[...]` block) * * Returns `null` on parse failure (caller falls back to original * fuzzy order per AC-ZA-8 L3). */ export declare function parseRerankResponse(raw: string): readonly number[] | null; /** * Apply a parsed index ordering to a candidate list. Indices that * are out-of-range or duplicated are skipped (defensive). If the * ordering covers fewer candidates than `topK`, the remaining * slots are filled from the original fuzzy order. */ export declare function applyRerankOrder(candidates: readonly MemorySearchResult[], order: readonly number[], topK: number): MemorySearchResult[]; /** * The no-op chat function. Used when no real chat injection is * available — the rerank layer fails-open and the caller gets * the original fuzzy order. */ export declare const noopRerankChat: RerankChatFn; /** * Run the LLM rerank. Always returns a result — never throws. * The caller can use `topK` as a drop-in replacement for the * fuzzy top-K regardless of degradation mode. */ export declare function rerank(query: string, candidates: readonly MemorySearchResult[], options?: RerankOptions): Promise;