@opengeni/jev 0.1.0-canary.36199476632001

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts","../src/circuit-breaker.ts","../src/code-search/config.ts","../src/code-search/judge.ts","../src/code-search/workspace.ts","../src/code-search/session.ts","../src/code-search/text.ts","../src/code-search/leads.ts","../src/code-search/windows.ts","../src/code-search/pack.ts","../src/code-search/recall.ts","../src/code-search/search.ts","../src/code-search/tool.ts"],"sourcesContent":["/**\n * Minimal client for TypeSafe Jev (\"System One\"): POST {baseUrl}/v1/systemone with\n * {state, model, questions} and get one typed answer per question back.\n *\n * - Splits a large question map across several requests so each stays inside the documented\n * limits (32k tokens for state + longest question, 64k for state + all questions).\n * - Retries only network errors (including per-attempt timeouts), 429 and 5xx, with bounded\n * backoff that honours `retry-after` up to `maxRetryAfterMs`. Other 4xx are never retried.\n * - The caller's AbortSignal cancels queued and in-flight requests and rejects with its reason.\n * - The API key is only ever sent in the Authorization header; it never appears in errors.\n */\n\nexport const JEV_DEFAULT_BASE_URL = \"https://api.typesafe.ai\";\nexport const JEV_DEFAULT_MODEL = \"jev-latest\";\n/** USD per 1M input tokens; output tokens are free. */\nexport const JEV_PRICE_PER_MILLION_INPUT_TOKENS_USD = 0.042;\n\n// ---------------------------------------------------------------------------\n// Questions and answers\n// ---------------------------------------------------------------------------\n\n/** Instructions and criteria may be a string or structured JSON. */\nexport type JevInstructions = string | Record<string, unknown> | unknown[];\n\nexport interface JevNoulQuestion {\n type: \"noul\";\n instructions: JevInstructions;\n criteria?: { true?: JevInstructions; false?: JevInstructions };\n}\n\nexport interface JevChoiceQuestion {\n type: \"choice\";\n instructions: JevInstructions;\n criteria: Record<string, JevInstructions | null>;\n}\n\nexport interface JevScoreQuestion {\n type: \"score\";\n instructions: JevInstructions;\n criteria: JevInstructions[];\n}\n\nexport type JevQuestion = JevNoulQuestion | JevChoiceQuestion | JevScoreQuestion;\n\nexport interface JevNoulAnswer {\n type: \"noul\";\n /** Probability of \"yes\" in [0, 1]; NaN when the API returned no usable number. */\n probability: number;\n}\n\nexport interface JevChoiceAnswer {\n type: \"choice\";\n option: string;\n probabilities?: Record<string, number>;\n confidence?: number;\n}\n\n/** Passed through as the API returns it. */\nexport interface JevScoreAnswer {\n type: \"score\";\n score: number;\n legend?: Record<string, string>;\n probabilities?: Record<string, number>;\n confidence?: number;\n}\n\nexport type JevAnswer = JevNoulAnswer | JevChoiceAnswer | JevScoreAnswer;\n\nexport type JevAnswerFor<Q> = Q extends JevNoulQuestion\n ? JevNoulAnswer\n : Q extends JevChoiceQuestion\n ? JevChoiceAnswer\n : Q extends JevScoreQuestion\n ? JevScoreAnswer\n : JevAnswer;\n\nexport interface JevAskResult<Q extends Record<string, JevQuestion>> {\n answers: { [K in keyof Q]: JevAnswerFor<Q[K]> };\n /** Versioned model id that answered (for example jev-1.13.0). */\n model: string;\n usage: { inputTokens: number };\n /** HTTP requests (chunks) that made up this ask. */\n requests: number;\n costUsd: number;\n}\n\nexport interface JevAskOptions {\n /** Short label used in error messages (for example \"code_search:wave1\"). */\n tag?: string | undefined;\n signal?: AbortSignal | undefined;\n}\n\nexport function noul(\n instructions: JevInstructions,\n criteria?: { true?: JevInstructions; false?: JevInstructions },\n): JevNoulQuestion {\n return criteria ? { type: \"noul\", instructions, criteria } : { type: \"noul\", instructions };\n}\n\nexport function jevCostUsd(inputTokens: number): number {\n return (inputTokens * JEV_PRICE_PER_MILLION_INPUT_TOKENS_USD) / 1_000_000;\n}\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\nexport class JevError extends Error {\n /** HTTP status of the failed response, when there was one. */\n readonly status: number | undefined;\n /** Machine-readable reason when known (for example \"max_tokens_exceeded\" or \"state_too_large\"). */\n readonly code: string | undefined;\n\n constructor(message: string, options: { status?: number; code?: string; cause?: unknown } = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = new.target.name;\n this.status = options.status;\n this.code = options.code;\n }\n}\n\n/** Jev cannot be used right now: network, timeout, 5xx, 429 after retries, or 401/402/403 auth and billing. */\nexport class JevUnavailableError extends JevError {}\n\n/** Jev rejected the request itself (other 4xx), or the request cannot fit the limits. Never retried. */\nexport class JevRequestError extends JevError {}\n\n// ---------------------------------------------------------------------------\n// Limits and chunking\n// ---------------------------------------------------------------------------\n\nexport interface JevLimits {\n /** Documented: state + longest question. */\n stateLongestMax: number;\n /** Documented: state + all questions. */\n stateAllMax: number;\n /** Fraction of each limit used (token estimates are approximate). */\n safety: number;\n /** Measured fixed overhead per request (~265 tokens). */\n perRequestOverhead: number;\n /** Measured framing overhead per question (~7-10 tokens) on top of its own text. */\n perQuestionOverhead: number;\n /** No documented cap; keeps one request reasonable. */\n maxQuestionsPerRequest: number;\n}\n\nexport const JEV_DEFAULT_LIMITS: JevLimits = {\n stateLongestMax: 32_000,\n stateAllMax: 64_000,\n safety: 0.9,\n perRequestOverhead: 300,\n perQuestionOverhead: 12,\n maxQuestionsPerRequest: 256,\n};\n\n/** Measured: TS code 3.2-3.5 chars/token, prose 4.4-4.7; 3.0 keeps the limit math conservative. */\nexport const JEV_CHARS_PER_TOKEN = 3.0;\n\nexport function estimateJevTokens(value: unknown, charsPerToken = JEV_CHARS_PER_TOKEN): number {\n const s = typeof value === \"string\" ? value : JSON.stringify(value ?? \"\");\n return Math.ceil(s.length / charsPerToken);\n}\n\n/**\n * Greedy packing of question ids into requests that respect both limits.\n * Throws JevRequestError (code state_too_large) when the state plus one question cannot fit.\n */\nexport function planChunks(\n stateTokens: number,\n questionTokens: ReadonlyArray<readonly [string, number]>,\n limits: JevLimits = JEV_DEFAULT_LIMITS,\n): string[][] {\n const longestCap = limits.stateLongestMax * limits.safety;\n const allCap = limits.stateAllMax * limits.safety;\n const base = stateTokens + limits.perRequestOverhead;\n const chunks: string[][] = [];\n let cur: string[] = [];\n let curSum = 0;\n for (const [id, qt] of questionTokens) {\n const cost = qt + limits.perQuestionOverhead;\n if (base + cost > longestCap) {\n throw new JevRequestError(\n `Jev state (~${stateTokens} tokens) plus question \"${id}\" (~${qt} tokens) exceeds ~${Math.floor(longestCap)} tokens`,\n { code: \"state_too_large\" },\n );\n }\n if (\n cur.length > 0 &&\n (base + curSum + cost > allCap || cur.length >= limits.maxQuestionsPerRequest)\n ) {\n chunks.push(cur);\n cur = [];\n curSum = 0;\n }\n cur.push(id);\n curSum += cost;\n }\n if (cur.length) chunks.push(cur);\n return chunks;\n}\n\n// ---------------------------------------------------------------------------\n// Concurrency limiter (abortable while queued)\n// ---------------------------------------------------------------------------\n\nexport class JevLimiter {\n private active = 0;\n private readonly queue: Array<{ grant: () => void }> = [];\n\n constructor(readonly max: number) {}\n\n async run<T>(fn: () => Promise<T>, signal?: AbortSignal): Promise<T> {\n await this.acquire(signal);\n try {\n return await fn();\n } finally {\n this.release();\n }\n }\n\n private acquire(signal?: AbortSignal): Promise<void> {\n signal?.throwIfAborted();\n if (this.active < this.max) {\n this.active += 1;\n return Promise.resolve();\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n const i = this.queue.indexOf(entry);\n if (i >= 0) this.queue.splice(i, 1);\n reject(signal?.reason);\n };\n const entry = {\n grant: () => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n },\n };\n this.queue.push(entry);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n\n /** A released slot passes straight to the next waiter, so `active` never overshoots `max`. */\n private release(): void {\n const next = this.queue.shift();\n if (next) next.grant();\n else this.active -= 1;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Client\n// ---------------------------------------------------------------------------\n\nexport type JevFetch = (url: string, init: RequestInit) => Promise<Response>;\n\nexport interface JevClientOptions {\n apiKey: string;\n baseUrl?: string | undefined;\n model?: string | undefined;\n /** Per-attempt timeout. */\n timeoutMs?: number | undefined;\n /** Retries after the first attempt. */\n maxRetries?: number | undefined;\n /** Cap on a server `retry-after` hint; an interactive tool fails fast rather than sleeping 30 s. */\n maxRetryAfterMs?: number | undefined;\n /** Max concurrent HTTP requests from this client. */\n concurrency?: number | undefined;\n /** First backoff delay; doubles per attempt up to maxRetryAfterMs. */\n retryBaseDelayMs?: number | undefined;\n fetch?: JevFetch | undefined;\n}\n\nconst RETRYABLE_STATUS = (status: number) => status === 429 || (status >= 500 && status <= 599);\nconst AUTH_STATUS = (status: number) => status === 401 || status === 402 || status === 403;\n/** Keep-alive connections are reused for a few seconds after a request; no warm-up is needed inside that window. */\nconst WARM_WINDOW_MS = 4_000;\nconst WARM_TIMEOUT_MS = 3_000;\nconst MAX_DETAIL_CHARS = 200;\n\nexport class JevClient {\n readonly baseUrl: string;\n readonly model: string;\n private readonly apiKey: string;\n private readonly timeoutMs: number;\n private readonly maxRetries: number;\n private readonly maxRetryAfterMs: number;\n private readonly retryBaseDelayMs: number;\n private readonly fetchImpl: JevFetch;\n private readonly limiter: JevLimiter;\n private lastActivityAt = -Infinity;\n\n constructor(options: JevClientOptions) {\n if (!options.apiKey) throw new JevUnavailableError(\"Jev API key is not configured\");\n this.apiKey = options.apiKey;\n this.baseUrl = (options.baseUrl ?? JEV_DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n this.model = options.model ?? JEV_DEFAULT_MODEL;\n this.timeoutMs = options.timeoutMs ?? 10_000;\n this.maxRetries = Math.max(0, options.maxRetries ?? 2);\n this.maxRetryAfterMs = Math.max(0, options.maxRetryAfterMs ?? 2_000);\n this.retryBaseDelayMs = Math.max(0, options.retryBaseDelayMs ?? 250);\n this.limiter = new JevLimiter(Math.max(1, options.concurrency ?? 16));\n this.fetchImpl = options.fetch ?? ((url, init) => fetch(url, init));\n }\n\n /**\n * Ask many questions about one state. Splits the questions into several requests when they exceed the\n * limits, runs them concurrently (bounded by `concurrency`) and merges the answers.\n */\n async ask<Q extends Record<string, JevQuestion>>(\n state: unknown,\n questions: Q,\n options: JevAskOptions = {},\n ): Promise<JevAskResult<Q>> {\n const { signal } = options;\n signal?.throwIfAborted();\n const ids = Object.keys(questions);\n if (!ids.length) throw new JevRequestError(\"Jev ask() needs at least one question\");\n const stateTokens = estimateJevTokens(state);\n const chunks = planChunks(\n stateTokens,\n ids.map((id) => [id, estimateJevTokens(questions[id])] as const),\n );\n const label = options.tag ? `${options.tag}: ` : \"\";\n const results = await Promise.all(\n chunks.map((chunk) =>\n this.limiter.run(\n () =>\n this.post(\n JSON.stringify({\n state,\n model: this.model,\n questions: Object.fromEntries(chunk.map((id) => [id, questions[id]])),\n }),\n label,\n signal,\n ),\n signal,\n ),\n ),\n );\n const answers: Record<string, JevAnswer> = {};\n let inputTokens = 0;\n let model = \"\";\n results.forEach((json, i) => {\n const got = isRecord(json.answers) ? json.answers : {};\n for (const id of chunks[i]!) {\n const answer = normalizeAnswer(got[id]);\n if (!answer)\n throw new JevUnavailableError(`${label}Jev response is missing the answer \"${id}\"`);\n answers[id] = answer;\n }\n const usage = isRecord(json.usage) ? json.usage : {};\n inputTokens += Number(usage.input_tokens ?? 0) || 0;\n if (typeof json.model === \"string\" && json.model) model = json.model;\n });\n return {\n answers: answers as JevAskResult<Q>[\"answers\"],\n model,\n usage: { inputTokens },\n requests: results.length,\n costUsd: jevCostUsd(inputTokens),\n };\n }\n\n /**\n * Open keep-alive connections before a burst of parallel requests (a cold TLS connection costs ~0.7 s).\n * GET /healthz is free. Skipped when the client was active within the last few seconds; never throws.\n */\n warmUp(connections: number): void {\n const now = Date.now();\n if (connections <= 0 || now - this.lastActivityAt < WARM_WINDOW_MS) return;\n this.lastActivityAt = now;\n for (let i = 0; i < connections; i++) {\n const timeout = AbortSignal.timeout(WARM_TIMEOUT_MS);\n this.fetchImpl(`${this.baseUrl}/healthz`, { method: \"GET\", signal: timeout })\n .then((res) => res.arrayBuffer())\n .catch(() => undefined);\n }\n }\n\n /** One HTTP request with retries. Returns the parsed JSON body of a 2xx response. */\n private async post(\n body: string,\n label: string,\n signal: AbortSignal | undefined,\n ): Promise<Record<string, unknown>> {\n const url = `${this.baseUrl}/v1/systemone`;\n const headers = { \"content-type\": \"application/json\", authorization: `Bearer ${this.apiKey}` };\n let lastError = \"unknown error\";\n let lastStatus: number | undefined;\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n signal?.throwIfAborted();\n const attemptSignal = withTimeout(signal, this.timeoutMs);\n let delay = this.backoff(attempt);\n let response: { res: Response; text: string } | null = null;\n try {\n const res = await this.fetchImpl(url, {\n method: \"POST\",\n headers,\n body,\n signal: attemptSignal.signal,\n });\n response = { res, text: await res.text() };\n } catch (error) {\n if (signal?.aborted) throw signal.reason;\n lastStatus = undefined;\n lastError = attemptSignal.timedOut()\n ? `timed out after ${this.timeoutMs} ms`\n : describeError(error);\n } finally {\n attemptSignal.dispose();\n this.lastActivityAt = Date.now();\n }\n if (response) {\n const { res, text } = response;\n if (res.ok) {\n const json = parseJson(text);\n if (!isRecord(json))\n throw new JevUnavailableError(`${label}Jev returned an invalid response body`);\n return json;\n }\n const detail = errorDetail(text);\n const suffix = detail.message ? `: ${detail.message}` : \"\";\n if (AUTH_STATUS(res.status)) {\n const what = res.status === 402 ? \"billing or credits\" : \"authentication\";\n throw new JevUnavailableError(\n `${label}Jev ${what} failed (HTTP ${res.status}${suffix})`,\n errorOptions(res.status, detail.code),\n );\n }\n if (!RETRYABLE_STATUS(res.status)) {\n throw new JevRequestError(\n `${label}Jev rejected the request (HTTP ${res.status}${suffix})`,\n errorOptions(res.status, detail.code),\n );\n }\n lastStatus = res.status;\n lastError = `HTTP ${res.status}${suffix}`;\n const retryAfter = parseRetryAfter(res.headers.get(\"retry-after\"));\n if (retryAfter !== null) delay = Math.min(retryAfter, this.maxRetryAfterMs);\n }\n if (attempt < this.maxRetries) await sleep(delay, signal);\n }\n throw new JevUnavailableError(\n `${label}Jev unavailable after ${this.maxRetries + 1} attempts (${lastError})`,\n lastStatus === undefined ? {} : { status: lastStatus },\n );\n }\n\n private backoff(attempt: number): number {\n const base = Math.min(this.maxRetryAfterMs, this.retryBaseDelayMs * 2 ** attempt);\n return Math.round(base * (1 - Math.random() * 0.25));\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return text ? JSON.parse(text) : null;\n } catch {\n return null;\n }\n}\n\nfunction normalizeAnswer(raw: unknown): JevAnswer | null {\n if (!isRecord(raw)) return null;\n if (raw.type === \"noul\") {\n return { type: \"noul\", probability: typeof raw.noul === \"number\" ? raw.noul : Number.NaN };\n }\n if (raw.type === \"choice\") {\n const answer: JevChoiceAnswer = {\n type: \"choice\",\n option: String(raw.choice ?? raw.option ?? \"\"),\n };\n if (isRecord(raw.probabilities))\n answer.probabilities = raw.probabilities as Record<string, number>;\n if (typeof raw.confidence === \"number\") answer.confidence = raw.confidence;\n return answer;\n }\n if (raw.type === \"score\")\n return { ...raw, type: \"score\", score: Number(raw.score) } as JevScoreAnswer;\n return null;\n}\n\nfunction errorOptions(status: number, code: string | undefined): { status: number; code?: string } {\n return code === undefined ? { status } : { status, code };\n}\n\n/** Best-effort code and message from an error body; bounded so a large body never floods a message. */\nfunction errorDetail(text: string): { code: string | undefined; message: string } {\n const json = parseJson(text);\n const codes: string[] = [];\n let message = \"\";\n const visit = (value: unknown) => {\n if (typeof value === \"string\") {\n if (!message) message = value;\n return;\n }\n if (Array.isArray(value)) {\n if (!message) message = JSON.stringify(value);\n return;\n }\n if (!isRecord(value)) return;\n for (const key of [\"code\", \"type\"]) {\n const v = value[key];\n if (typeof v === \"string\" && v !== \"error\") codes.push(v);\n }\n for (const key of [\"detail\", \"error\", \"message\", \"msg\"]) if (key in value) visit(value[key]);\n };\n if (json === null) message = text.trim();\n else visit(json);\n let code = codes[0];\n if (!code && /^[a-z][a-z0-9_]{2,60}$/.test(message)) code = message;\n return { code, message: message.replace(/\\s+/g, \" \").slice(0, MAX_DETAIL_CHARS) };\n}\n\nfunction parseRetryAfter(header: string | null): number | null {\n if (!header) return null;\n const secs = Number(header);\n if (Number.isFinite(secs)) return Math.max(0, secs * 1000);\n const at = Date.parse(header);\n return Number.isFinite(at) ? Math.max(0, at - Date.now()) : null;\n}\n\nfunction describeError(error: unknown): string {\n const text = error instanceof Error ? `${error.name}: ${error.message}` : String(error);\n return text.slice(0, MAX_DETAIL_CHARS);\n}\n\n/** A per-attempt signal that fires on the caller's abort or after timeoutMs (no AbortSignal.any: Node 18). */\nfunction withTimeout(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; timedOut: () => boolean; dispose: () => void } {\n const controller = new AbortController();\n let timedOut = false;\n const onAbort = () => controller.abort(parent?.reason);\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort(new JevUnavailableError(`Jev request timed out after ${timeoutMs} ms`));\n }, timeoutMs);\n if (parent?.aborted) controller.abort(parent.reason);\n else parent?.addEventListener(\"abort\", onAbort, { once: true });\n return {\n signal: controller.signal,\n timedOut: () => timedOut,\n dispose: () => {\n clearTimeout(timer);\n parent?.removeEventListener(\"abort\", onAbort);\n },\n };\n}\n\nfunction sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n if (ms <= 0) return Promise.resolve();\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n if (signal?.aborted) onAbort();\n else signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","/**\n * In-process circuit breaker for Jev. Consecutive JevUnavailableError failures open it for a cooldown, so a\n * Jev outage costs one fast refusal per call instead of a full retry cycle. After the cooldown the breaker is\n * half-open and tryAcquire() admits exactly one trial call at a time.\n *\n * Every admitted call gets a lease and settles it exactly once:\n * - recordSuccess(lease) from any call closes the breaker, because any success proves Jev works.\n * - recordFailure(unavailable, now, lease) from any call counts, and reopens a half-open breaker at once.\n * - release(lease) (the call never reached Jev) or recordFailure with another error (a rejected request, a\n * workspace failure, an abort) neither counts nor resets the streak. It ends the trial only when that\n * lease is the trial, so a call admitted while closed cannot free the slot of a trial running now.\n * isOpen() and status() are for metrics and diagnostics. Do not use them to decide which tools a turn is\n * offered: that list is part of the model's cached prompt prefix and must not change with transient health.\n * The worker keeps one breaker per process.\n */\nimport { JevUnavailableError } from \"./client\";\n\nexport interface JevCircuitBreakerOptions {\n /** Consecutive unavailable failures that open the breaker. */\n failureThreshold?: number | undefined;\n /** Cooldown after an outage-style failure. */\n cooldownMs?: number | undefined;\n /** Cooldown when the opening failure was HTTP 401/402/403 (key or billing problem). */\n authCooldownMs?: number | undefined;\n /** A half-open trial that has not ended after this long no longer blocks the next trial. */\n trialTimeoutMs?: number | undefined;\n}\n\n/** One admitted call. Leases are matched by identity, so only the issued object ends its trial. */\nexport interface JevCircuitLease {\n readonly id: number;\n /** This call is the half-open trial. */\n readonly trial: boolean;\n}\n\nexport type JevCircuitState = \"closed\" | \"open\" | \"half_open\";\n\nexport interface JevCircuitStatus {\n state: JevCircuitState;\n consecutiveFailures: number;\n /** Epoch ms until which calls are refused; null when not open. */\n openUntil: number | null;\n /** Half-open and the one trial call is running. */\n trialInFlight: boolean;\n lastFailure: { message: string; status: number | null; at: number } | null;\n}\n\nexport class JevCircuitBreaker {\n private readonly failureThreshold: number;\n private readonly cooldownMs: number;\n private readonly authCooldownMs: number;\n private readonly trialTimeoutMs: number;\n private consecutiveFailures = 0;\n private openUntil: number | null = null;\n private trial: { lease: JevCircuitLease; startedAt: number } | null = null;\n private nextLeaseId = 1;\n private lastFailure: JevCircuitStatus[\"lastFailure\"] = null;\n\n constructor(options: JevCircuitBreakerOptions = {}) {\n this.failureThreshold = Math.max(1, options.failureThreshold ?? 3);\n this.cooldownMs = options.cooldownMs ?? 5 * 60_000;\n this.authCooldownMs = options.authCooldownMs ?? 30 * 60_000;\n // Longer than one Jev retry cycle at the largest allowed request timeout (3 attempts of up to\n // 120 s, OPENGENI_JEV_REQUEST_TIMEOUT_MS) plus backoff and sandbox recall, so a slow trial is not\n // mistaken for a stuck one and joined by a second trial.\n this.trialTimeoutMs = options.trialTimeoutMs ?? 10 * 60_000;\n }\n\n /** True while calls should be refused without contacting Jev (the cooldown is running). */\n isOpen(now: number = Date.now()): boolean {\n return this.openUntil !== null && now < this.openUntil;\n }\n\n /**\n * Admit one call and return its lease, or null when refused. Closed: always. Open: never. Half-open:\n * only the first caller, as the trial, until its lease is settled or it has run for trialTimeoutMs, so\n * a trial that never ends cannot block the tool for good.\n */\n tryAcquire(now: number = Date.now()): JevCircuitLease | null {\n if (this.openUntil === null) return this.issue(false);\n if (now < this.openUntil) return null;\n if (this.trial !== null && now - this.trial.startedAt < this.trialTimeoutMs) return null;\n const lease = this.issue(true);\n this.trial = { lease, startedAt: now };\n return lease;\n }\n\n /** End an admitted call that did not contact Jev, so its outcome says nothing about Jev. */\n release(lease: JevCircuitLease): void {\n if (this.trial !== null && this.trial.lease === lease) this.trial = null;\n }\n\n /** Any call's success proves Jev works, so the lease does not change the outcome. */\n recordSuccess(_lease?: JevCircuitLease | null): void {\n this.consecutiveFailures = 0;\n this.openUntil = null;\n this.trial = null;\n }\n\n /** Settle a failed call. A failure without a lease counts the same but never ends a trial. */\n recordFailure(error: unknown, now: number = Date.now(), lease?: JevCircuitLease | null): void {\n if (!(error instanceof JevUnavailableError)) {\n if (lease) this.release(lease);\n return;\n }\n const halfOpen = this.openUntil !== null && now >= this.openUntil;\n this.consecutiveFailures += 1;\n this.lastFailure = { message: error.message, status: error.status ?? null, at: now };\n if (halfOpen || this.consecutiveFailures >= this.failureThreshold) {\n const auth = error.status === 401 || error.status === 402 || error.status === 403;\n this.openUntil = now + (auth ? this.authCooldownMs : this.cooldownMs);\n // A new cooldown starts: whatever trial was running no longer blocks the next one.\n this.trial = null;\n }\n }\n\n status(now: number = Date.now()): JevCircuitStatus {\n const state: JevCircuitState =\n this.openUntil === null ? \"closed\" : now < this.openUntil ? \"open\" : \"half_open\";\n return {\n state,\n consecutiveFailures: this.consecutiveFailures,\n openUntil: state === \"open\" ? this.openUntil : null,\n trialInFlight:\n state === \"half_open\" &&\n this.trial !== null &&\n now - this.trial.startedAt < this.trialTimeoutMs,\n lastFailure: this.lastFailure,\n };\n }\n\n private issue(trial: boolean): JevCircuitLease {\n return Object.freeze({ id: this.nextLeaseId++, trial });\n }\n}\n","/**\n * Every code_search threshold, budget and cap in one place. The defaults are scout-0.3.1's Jev\n * configuration, tuned on the E1 DEV split (2026-09-24); change them only with a new evaluation.\n */\n\nexport interface CodeSearchConfig {\n recall: {\n /** Candidate files passed to wave 1. */\n maxCandidates: number;\n /** Matching lines kept per file per keyword. */\n maxMatchesPerFile: number;\n /** rg --max-filesize (bytes); also the read cap for candidate files. */\n maxFileBytes: number;\n /** rg --max-columns: lines longer than this (minified / generated / data blobs) are ignored entirely. */\n maxLineColumns: number;\n /** Multiplier for test files unless the question is about tests. */\n testWeight: number;\n /** Path-name match bonus as a fraction of the keyword's IDF. */\n pathBonus: number;\n /** Extra weight per log(1 + matching lines) (tie breaker). */\n hitCountWeight: number;\n /** Single plain words up to this length are searched with a leading word boundary (`\\bturn`, not `return`). */\n shortWordMaxLen: number;\n /** Compound keywords with zero hits retry their 2-part fragments (e.g. shouldCompactContext -> compactContext). */\n fragmentFallback: boolean;\n /** If paths restrict the search and fewer candidates than this are found, widen to the whole workspace. */\n minCandidatesBeforeWiden: number;\n /** Extra rg exclude globs (on top of the built-in list). */\n extraExcludes: string[];\n /** Also search hidden files/dirs (.github/workflows, .env.example, .changeset); .git is always excluded. */\n searchHidden: boolean;\n /** Multiplier for release notes (CHANGELOG*, .changeset/) unless the question is about history/releases. */\n changelogWeight: number;\n /** Time limit per ripgrep call; a timed-out search continues with partial output. */\n ripgrepTimeoutMs: number;\n };\n wave1: {\n filesPerRequest: number;\n hitLinesPerFile: number;\n hitLineChars: number;\n /** Hard cap on files selected for windowing. */\n maxFiles: number;\n /** Always take at least this many files by judge score (guards against an over-strict T1). */\n minFiles: number;\n /** Always keep the top-N lexical files (fusion guard against judge misses). */\n lexicalGuard: number;\n };\n wave2: {\n windowsPerFile: number;\n /** How many of a file's strongest hit lines seed windows (before merging/splitting). */\n seedHitsPerFile: number;\n /** Max lines to walk up from a hit looking for the enclosing declaration. */\n maxUp: number;\n /** Max lines below a hit kept in its window. */\n maxDown: number;\n /** Windows longer than this are split around hit clusters. */\n maxWindowLines: number;\n /** Fallback context when no enclosing declaration is found within maxUp. */\n fallbackBefore: number;\n fallbackAfter: number;\n /** Merge windows whose gap is at most this many lines. */\n mergeGap: number;\n /** Windows shorter than this get surrounding context. */\n minWindowLines: number;\n passagesPerRequest: number;\n /** Max passage text chars per Jev request. */\n maxRequestChars: number;\n /** Max passages verified in wave 2. */\n maxPassages: number;\n /** Code lines longer than this are cut with an explicit marker. */\n maxLineChars: number;\n /** Same for prose files (md/mdx/txt/rst), which often have single-line paragraphs of 1-6k chars. */\n maxProseLineChars: number;\n /** Windows whose rendered text is longer are split into whole-line sub-windows around their hits. */\n maxWindowChars: number;\n /** Same for markdown (sections are long, paragraphs independent). */\n maxProseWindowChars: number;\n };\n wave3: {\n enabled: boolean;\n maxLeadCandidates: number;\n maxLeadsFollowed: number;\n /** Leads are extracted from at most this many of the most relevant passages (all >= T2). */\n seedPassages: number;\n defsPerLead: number;\n };\n status: {\n enabled: boolean;\n /** Max evidence chars sent to the status check (best passages first); keeps the request under Jev's 32k-token limit. */\n maxEvidenceChars: number;\n /** sufficient: overall >= hi and every sub-question >= hi. */\n hi: number;\n /** partial: overall >= lo or any sub-question >= hi. */\n lo: number;\n };\n pack: {\n charsPerToken: number;\n /** Include passages below T2 only if fewer than this many passed (top by score, above minRelevance). */\n minPassages: number;\n minRelevance: number;\n /** Fill the remaining budget with passages below T2 (ranked). */\n fillBudget: boolean;\n moreCandidates: number;\n leadsNotFollowed: number;\n /** A trimmed passage must keep at least this many lines. */\n minTrimLines: number;\n /** File-diversity penalty: a second passage of one file must beat the first passage of another by this margin. */\n filePenalty: number;\n /** Passages whose rendered block is longer are trimmed around their hits to this many chars (0 = off). */\n maxPassageChars: number;\n /** Multiplier on the rel used for pack ORDERING of release-note passages; 1 = off. */\n changelogPrior: number;\n /** Same for prose docs (md/mdx/txt/rst, not release notes); 1 = off. */\n docPrior: number;\n /** Same for test files unless the question is about tests; 1 = off. */\n testPrior: number;\n /** Pack ordering score = (rel + lexWeight x lexical passage score) x prior. */\n lexWeight: number;\n };\n jev: {\n /** Inline the question text in every Jev question when it is at most this long; else reference `question`. */\n inlineQuestionMaxChars: number;\n /** Wave 1: put the true/false rubric on every file question instead of once in the state. */\n fileCriteriaPerQuestion: boolean;\n /** Keep-alive connections opened while recall runs (0 = off). */\n warmConnections: number;\n };\n thresholds: {\n /** Wave 1: file triage floor (p >= T1 selects, up to maxFiles). */\n T1: number;\n /** Wave 2: passage relevance floor for inclusion in the pack, lead seeding and sub-question coverage. */\n T2: number;\n /** Wave 3: lead floor (p >= T3 is followed, up to maxLeadsFollowed). */\n T3: number;\n };\n}\n\nexport type CodeSearchConfigOverride = {\n [K in keyof CodeSearchConfig]?: Partial<CodeSearchConfig[K]>;\n};\n\nexport const DEFAULT_CODE_SEARCH_CONFIG: Readonly<CodeSearchConfig> = deepFreeze({\n recall: {\n maxCandidates: 240,\n maxMatchesPerFile: 25,\n maxFileBytes: 4_000_000,\n maxLineColumns: 8000,\n testWeight: 0.6,\n pathBonus: 0.5,\n hitCountWeight: 0.1,\n shortWordMaxLen: 5,\n fragmentFallback: true,\n minCandidatesBeforeWiden: 5,\n extraExcludes: [],\n searchHidden: true,\n changelogWeight: 0.6,\n ripgrepTimeoutMs: 30_000,\n },\n wave1: {\n filesPerRequest: 60,\n hitLinesPerFile: 3,\n hitLineChars: 160,\n maxFiles: 16,\n minFiles: 8,\n lexicalGuard: 5,\n },\n wave2: {\n windowsPerFile: 5,\n seedHitsPerFile: 24,\n maxUp: 40,\n maxDown: 120,\n maxWindowLines: 150,\n fallbackBefore: 10,\n fallbackAfter: 30,\n mergeGap: 2,\n minWindowLines: 12,\n passagesPerRequest: 4,\n maxRequestChars: 24_000,\n maxPassages: 80,\n maxLineChars: 400,\n maxProseLineChars: 1600,\n maxWindowChars: 8000,\n maxProseWindowChars: 4000,\n },\n wave3: {\n enabled: true,\n maxLeadCandidates: 60,\n maxLeadsFollowed: 6,\n seedPassages: 12,\n defsPerLead: 1,\n },\n status: { enabled: true, maxEvidenceChars: 60_000, hi: 0.7, lo: 0.4 },\n pack: {\n charsPerToken: 3.2,\n minPassages: 4,\n minRelevance: 0.1,\n fillBudget: false,\n moreCandidates: 10,\n leadsNotFollowed: 8,\n minTrimLines: 15,\n filePenalty: 0.1,\n maxPassageChars: 3200,\n changelogPrior: 0.5,\n docPrior: 0.85,\n testPrior: 1,\n lexWeight: 0,\n },\n jev: {\n inlineQuestionMaxChars: 600,\n fileCriteriaPerQuestion: false,\n warmConnections: 12,\n },\n // calibrated on the DEV split from the observed score distributions (relevant files mostly 0.6-0.9;\n // minFiles and the lexical guard keep recall when few files pass)\n thresholds: { T1: 0.6, T2: 0.5, T3: 0.5 },\n});\n\n/** Defaults with a partial override merged on top (unknown keys and wrong types are rejected), validated. */\nexport function codeSearchConfig(override: CodeSearchConfigOverride = {}): CodeSearchConfig {\n const base = structuredClone(DEFAULT_CODE_SEARCH_CONFIG) as CodeSearchConfig;\n const out = base as unknown as Record<string, Record<string, unknown>>;\n for (const [section, values] of Object.entries(override as Record<string, unknown>)) {\n const target = out[section];\n if (!target) throw new Error(`unknown code_search config section: ${section}`);\n if (!isPlainObject(values)) throw new Error(`code_search config ${section}: expected object`);\n for (const [key, value] of Object.entries(values)) {\n if (!(key in target)) throw new Error(`unknown code_search config key: ${section}.${key}`);\n const current = target[key];\n if (Array.isArray(current) ? !Array.isArray(value) : typeof current !== typeof value) {\n throw new Error(\n `code_search config ${section}.${key}: expected ${Array.isArray(current) ? \"array\" : typeof current}`,\n );\n }\n target[key] = value;\n }\n }\n validateCodeSearchConfig(base);\n return base;\n}\n\nexport function validateCodeSearchConfig(c: CodeSearchConfig): void {\n const probs: string[] = [];\n for (const [k, v] of Object.entries(c.thresholds))\n if (!(v >= 0 && v <= 1)) probs.push(`thresholds.${k} must be in [0,1]`);\n if (c.wave1.maxFiles < 1) probs.push(\"wave1.maxFiles must be >= 1\");\n if (c.wave1.minFiles > c.wave1.maxFiles) probs.push(\"wave1.minFiles must be <= wave1.maxFiles\");\n if (c.wave1.filesPerRequest < 1 || c.wave1.filesPerRequest > 250)\n probs.push(\"wave1.filesPerRequest must be 1..250\");\n if (c.wave2.passagesPerRequest < 1) probs.push(\"wave2.passagesPerRequest must be >= 1\");\n if (c.wave2.maxWindowLines < 10) probs.push(\"wave2.maxWindowLines must be >= 10\");\n if (c.wave2.maxWindowChars < 4 * c.wave2.maxLineChars)\n probs.push(\"wave2.maxWindowChars must be >= 4 x wave2.maxLineChars\");\n if (c.wave2.maxProseWindowChars < 2 * c.wave2.maxProseLineChars + 200) {\n probs.push(\"wave2.maxProseWindowChars must be >= 2 x wave2.maxProseLineChars + 200\");\n }\n if (c.wave3.maxLeadCandidates > 250) probs.push(\"wave3.maxLeadCandidates must be <= 250\");\n if (!(c.status.lo <= c.status.hi)) probs.push(\"status.lo must be <= status.hi\");\n if (c.pack.charsPerToken <= 0) probs.push(\"pack.charsPerToken must be > 0\");\n if (c.pack.filePenalty < 0) probs.push(\"pack.filePenalty must be >= 0\");\n if (c.pack.maxPassageChars !== 0 && c.pack.maxPassageChars < 600)\n probs.push(\"pack.maxPassageChars must be 0 or >= 600\");\n for (const k of [\"changelogPrior\", \"docPrior\", \"testPrior\"] as const) {\n if (!(c.pack[k] > 0 && c.pack[k] <= 1)) probs.push(`pack.${k} must be in (0,1]`);\n }\n if (!(c.pack.lexWeight >= 0)) probs.push(\"pack.lexWeight must be >= 0\");\n if (!(c.recall.changelogWeight > 0 && c.recall.changelogWeight <= 1))\n probs.push(\"recall.changelogWeight must be in (0,1]\");\n if (!(c.recall.ripgrepTimeoutMs > 0)) probs.push(\"recall.ripgrepTimeoutMs must be > 0\");\n if (probs.length) throw new Error(`invalid code_search config: ${probs.join(\"; \")}`);\n}\n\nfunction isPlainObject(x: unknown): x is Record<string, unknown> {\n return typeof x === \"object\" && x !== null && !Array.isArray(x);\n}\n\nfunction deepFreeze<T>(value: T): T {\n if (typeof value === \"object\" && value !== null) {\n for (const v of Object.values(value)) deepFreeze(v);\n Object.freeze(value);\n }\n return value;\n}\n","/**\n * judge.ts - the only place where scores come from: Jev answers one probability per judged item.\n *\n * All Jev wording lives in PROMPTS below (one place to review). Design rules followed:\n * - one state + many narrow Nouls per request (fan-out); one Noul per candidate (multi-select)\n * - criteria text is explicit (in the state for 60-file triage batches, per question for passages)\n * - the literal question text is inlined in every question (no `collections[i]`-style indirection)\n * - state holds only the candidates being judged (filtered by code first)\n * - no counting, math or dates asked of Jev; code combines answers\n * A Jev failure is not replaced by lexical scores: it propagates and the whole search fails.\n */\nimport { noul, type JevAnswer, type JevClient, type JevNoulQuestion } from \"../client\";\nimport type { CodeSearchConfig } from \"./config\";\n\nexport interface JudgeContext {\n question: string;\n subQuestions: string[];\n}\n\nexport interface FileItem {\n id: string;\n path: string;\n /** path + best hit lines, as shown to the judge */\n descriptor: string;\n /** Normalized lexical score; used only if Jev returns no usable number for this item. */\n lex: number;\n}\n\nexport interface PassageItem {\n id: string;\n path: string;\n start: number;\n end: number;\n /** rendered `N| text` */\n text: string;\n label?: string | undefined;\n lex: number;\n lexCov: number[];\n}\n\nexport interface LeadItem {\n id: string;\n name: string;\n seenAt: string;\n context: string;\n lex: number;\n}\n\nexport interface PassageScore {\n rel: number;\n cov: number[];\n}\n\nexport interface StatusScore {\n overall: number;\n subs: number[];\n}\n\nexport interface StageStats {\n requests: number;\n inputTokens: number;\n costUsd: number;\n ms: number;\n}\n\nexport type JudgeEvent = (stage: string, data: Record<string, unknown>) => void;\n\n// ---------------------------------------------------------------------------\n// Prompts (all Jev wording; identical to scout-0.3.1)\n// ---------------------------------------------------------------------------\n\nexport const PROMPTS = {\n fileTask:\n \"Code search triage for a software repository. A developer asked `question`. `files` lists candidate files found by keyword search; each entry is the file path followed by up to 3 matching lines as `line: text`. Judge each file independently by its path and matching lines.\",\n fileCriteria: {\n yes: \"Reading this file would likely help answer the question: it probably implements, decides, computes, configures, enforces or documents the asked behavior. A doc or design note that explains the behavior counts.\",\n no: \"The file probably only mentions the same words, imports or passes values through, belongs to an unrelated feature that shares keywords, or is a test that is not about the asked behavior.\",\n },\n fileQuestion: (id: string, path: string, q: string) =>\n `Would reading file \\`files.${id}\\` (${path}) help answer the question${q}? Apply \\`criteria\\`.`,\n fileQuestionPerQ: (id: string, path: string, q: string) =>\n `Would reading file \\`files.${id}\\` (${path}) help answer the question${q}?`,\n\n passageTask:\n \"Evidence check for a question about a software repository. Each entry in `passages` is a verbatim excerpt of one repository file with its original line numbers (`N| text`). `in` names the enclosing declaration when the excerpt starts inside one. Judge each passage on its own content only.\",\n passageQuestion: (id: string, path: string, a: number, b: number, q: string) =>\n `Does \\`passages.${id}\\` (${path} lines ${a}-${b}) contain code or text needed to answer the question${q}?`,\n passageCriteria: {\n true: \"The passage implements, decides, computes, configures, enforces or documents part of the asked behavior. A helper that performs one asked step counts, and so does a doc passage that states the behavior.\",\n false:\n \"The passage only mentions, imports, calls or passes through names related to the question, is a test or type declaration that does not show the behavior, or is unrelated code that shares keywords.\",\n },\n coverageQuestion: (id: string, path: string, a: number, b: number, sub: string) =>\n `Does \\`passages.${id}\\` (${path} lines ${a}-${b}) show the answer to this part of the question: \"${sub}\"?`,\n coverageCriteria: {\n true: \"The passage itself states or implements the answer to this part.\",\n false:\n \"The passage does not address this part, or only mentions it without showing the answer.\",\n },\n\n leadTask:\n \"Follow-up selection for a question about a software repository. Evidence passages already found reference the identifiers in `leads`, whose definitions have not been read yet. Each lead shows the identifier, where it was seen, and the line it appears on.\",\n leadCriteria: {\n yes: \"The definition likely computes, decides, configures or enforces part of the asked behavior, or holds a constant, setting or rule that the answer depends on.\",\n no: \"It is a generic helper (logging, formatting, errors, type plumbing, database or HTTP plumbing) or it is unrelated to the question.\",\n },\n leadQuestion: (id: string, name: string, q: string) =>\n `Would reading where \\`${name}\\` (\\`leads.${id}\\`) is defined help answer the question${q}? Apply \\`criteria\\`.`,\n\n statusTask:\n \"Sufficiency check. `evidence` is a set of verbatim excerpts of repository files (with original line numbers) collected to answer `question`.\",\n statusQuestion: (q: string) =>\n `Do the \\`evidence\\` passages show the answer to the question${q}?`,\n statusSubQuestion: (sub: string) =>\n `Do the \\`evidence\\` passages show the answer to this part of the question: \"${sub}\"?`,\n statusCriteria: {\n true: \"Together the passages state or implement the answer concretely enough to cite file and line.\",\n false:\n \"Some part of the answer is missing: the passages only mention the topic, or the deciding code is elsewhere.\",\n },\n};\n\nfunction inlineQ(question: string, maxChars: number): string {\n return question.length <= maxChars ? `: \"${question}\"` : \" in `question`\";\n}\n\nfunction withSubs(ctx: JudgeContext): Record<string, unknown> {\n return ctx.subQuestions.length\n ? { sub_questions: Object.fromEntries(ctx.subQuestions.map((s, i) => [`s${i + 1}`, s])) }\n : {};\n}\n\n// ---------------------------------------------------------------------------\n// Request builders (exported for tests)\n// ---------------------------------------------------------------------------\n\nexport function buildFileRequest(items: FileItem[], ctx: JudgeContext, cfg: CodeSearchConfig) {\n const q = inlineQ(ctx.question, cfg.jev.inlineQuestionMaxChars);\n // default: the rubric is stated once in the state and referenced (~65% fewer question tokens);\n // fileCriteriaPerQuestion puts it on every Noul instead\n const perQ = cfg.jev.fileCriteriaPerQuestion;\n const state = {\n task: PROMPTS.fileTask,\n question: ctx.question,\n ...withSubs(ctx),\n ...(perQ ? {} : { criteria: PROMPTS.fileCriteria }),\n files: Object.fromEntries(items.map((f) => [f.id, f.descriptor])),\n };\n const questions: Record<string, JevNoulQuestion> = Object.fromEntries(\n items.map((f) => [\n f.id,\n perQ\n ? noul(PROMPTS.fileQuestionPerQ(f.id, f.path, q), {\n true: PROMPTS.fileCriteria.yes,\n false: PROMPTS.fileCriteria.no,\n })\n : noul(PROMPTS.fileQuestion(f.id, f.path, q)),\n ]),\n );\n return { state, questions };\n}\n\nexport function buildPassageRequest(\n items: PassageItem[],\n ctx: JudgeContext,\n cfg: CodeSearchConfig,\n) {\n const q = inlineQ(ctx.question, cfg.jev.inlineQuestionMaxChars);\n const state = {\n task: PROMPTS.passageTask,\n question: ctx.question,\n ...withSubs(ctx),\n passages: Object.fromEntries(\n items.map((p) => [\n p.id,\n {\n file: p.path,\n lines: `${p.start}-${p.end}`,\n ...(p.label ? { in: p.label } : {}),\n text: p.text,\n },\n ]),\n ),\n };\n const questions: Record<string, JevNoulQuestion> = {};\n for (const p of items) {\n questions[`rel::${p.id}`] = noul(\n PROMPTS.passageQuestion(p.id, p.path, p.start, p.end, q),\n PROMPTS.passageCriteria,\n );\n ctx.subQuestions.forEach((sub, j) => {\n questions[`cov::${p.id}::${j}`] = noul(\n PROMPTS.coverageQuestion(p.id, p.path, p.start, p.end, sub),\n PROMPTS.coverageCriteria,\n );\n });\n }\n return { state, questions };\n}\n\nexport function buildLeadRequest(items: LeadItem[], ctx: JudgeContext, cfg: CodeSearchConfig) {\n const q = inlineQ(ctx.question, cfg.jev.inlineQuestionMaxChars);\n const state = {\n task: PROMPTS.leadTask,\n question: ctx.question,\n ...withSubs(ctx),\n criteria: PROMPTS.leadCriteria,\n leads: Object.fromEntries(\n items.map((l) => [l.id, `${l.name} (seen at ${l.seenAt}) ${l.context}`]),\n ),\n };\n const questions: Record<string, JevNoulQuestion> = Object.fromEntries(\n items.map((l) => [l.id, noul(PROMPTS.leadQuestion(l.id, l.name, q))]),\n );\n return { state, questions };\n}\n\nexport function buildStatusRequest(evidence: string, ctx: JudgeContext, cfg: CodeSearchConfig) {\n const q = inlineQ(ctx.question, cfg.jev.inlineQuestionMaxChars);\n const state = { task: PROMPTS.statusTask, question: ctx.question, ...withSubs(ctx), evidence };\n const questions: Record<string, JevNoulQuestion> = {\n overall: noul(PROMPTS.statusQuestion(q), PROMPTS.statusCriteria),\n };\n ctx.subQuestions.forEach((sub, j) => {\n questions[`sub::${j}`] = noul(PROMPTS.statusSubQuestion(sub), PROMPTS.statusCriteria);\n });\n return { state, questions };\n}\n\n/** Group passages into requests: consecutive (same-file first) up to perRequest items and maxChars of text. */\nexport function chunkPassages(\n items: PassageItem[],\n perRequest: number,\n maxChars: number,\n): PassageItem[][] {\n const out: PassageItem[][] = [];\n let cur: PassageItem[] = [];\n let chars = 0;\n for (const p of items) {\n const c = p.text.length;\n if (cur.length && (cur.length >= perRequest || chars + c > maxChars)) {\n out.push(cur);\n cur = [];\n chars = 0;\n }\n cur.push(p);\n chars += c;\n }\n if (cur.length) out.push(cur);\n return out;\n}\n\n/** Split into the fewest groups of at most n items, as equal in size as possible (69 -> 35 + 34, not 60 + 9). */\nexport function chunkEven<T>(xs: T[], n: number): T[][] {\n if (!xs.length) return [];\n const groups = Math.ceil(xs.length / n);\n const size = Math.ceil(xs.length / groups);\n return chunk(xs, size);\n}\n\nfunction chunk<T>(xs: T[], n: number): T[][] {\n const out: T[][] = [];\n for (let i = 0; i < xs.length; i += n) out.push(xs.slice(i, i + n));\n return out;\n}\n\nconst noulOf = (a: JevAnswer | undefined): number =>\n a && a.type === \"noul\" && Number.isFinite(a.probability) ? a.probability : Number.NaN;\n\nfunction orLex(p: number, lex: number): number {\n return Number.isFinite(p) ? p : lex;\n}\n\n// ---------------------------------------------------------------------------\n// Jev judge\n// ---------------------------------------------------------------------------\n\nexport class JevJudge {\n private readonly stageStats: Record<string, StageStats> = {};\n private jevModel: string | null = null;\n\n constructor(\n private readonly o: {\n client: JevClient;\n config: CodeSearchConfig;\n signal: AbortSignal;\n onEvent?: JudgeEvent | undefined;\n },\n ) {}\n\n stats(): Record<string, StageStats> {\n return this.stageStats;\n }\n\n model(): string | null {\n return this.jevModel;\n }\n\n private stat(stage: string): StageStats {\n return (this.stageStats[stage] ??= { requests: 0, inputTokens: 0, costUsd: 0, ms: 0 });\n }\n\n /** One logical request (the client may split its questions into several HTTP requests). */\n private async ask(\n stage: string,\n state: unknown,\n questions: Record<string, JevNoulQuestion>,\n ): Promise<Record<string, JevAnswer>> {\n const t0 = performance.now();\n const r = await this.o.client.ask(state, questions, {\n tag: stage,\n signal: this.o.signal,\n });\n const st = this.stat(stage);\n st.requests += r.requests;\n st.inputTokens += r.usage.inputTokens;\n st.costUsd += r.costUsd;\n this.jevModel = r.model || this.jevModel;\n this.o.onEvent?.(\"jev\", {\n jevStage: stage,\n ms: Math.round(performance.now() - t0),\n requests: r.requests,\n model: r.model,\n inputTokens: r.usage.inputTokens,\n costUsd: r.costUsd,\n state,\n questions,\n answers: r.answers,\n });\n return r.answers;\n }\n\n /** Run a stage's batches in parallel; the first failure rejects the stage. */\n private async stage<I, R>(\n stage: string,\n batches: I[][],\n build: (b: I[]) => { state: unknown; questions: Record<string, JevNoulQuestion> },\n read: (b: I[], answers: Record<string, JevAnswer>) => Array<[string, R]>,\n ): Promise<Map<string, R>> {\n const t0 = performance.now();\n try {\n const results = await Promise.all(\n batches.map(async (b) => {\n const req = build(b);\n return read(b, await this.ask(stage, req.state, req.questions));\n }),\n );\n return new Map(results.flat());\n } finally {\n this.stat(stage).ms += Math.round(performance.now() - t0);\n }\n }\n\n async scoreFiles(items: FileItem[], ctx: JudgeContext): Promise<Map<string, number>> {\n if (!items.length) return new Map();\n return this.stage(\n \"wave1\",\n chunkEven(items, this.o.config.wave1.filesPerRequest),\n (b) => buildFileRequest(b, ctx, this.o.config),\n (b, a) => b.map((f) => [f.id, orLex(noulOf(a[f.id]), f.lex)]),\n );\n }\n\n async scorePassages(\n items: PassageItem[],\n ctx: JudgeContext,\n stage = \"wave2\",\n ): Promise<Map<string, PassageScore>> {\n if (!items.length) return new Map();\n const w = this.o.config.wave2;\n return this.stage(\n stage,\n chunkPassages(items, w.passagesPerRequest, w.maxRequestChars),\n (b) => buildPassageRequest(b, ctx, this.o.config),\n (b, a) =>\n b.map((p) => [\n p.id,\n {\n rel: orLex(noulOf(a[`rel::${p.id}`]), p.lex),\n cov: ctx.subQuestions.map((_, j) =>\n orLex(noulOf(a[`cov::${p.id}::${j}`]), p.lexCov[j] ?? 0),\n ),\n },\n ]),\n );\n }\n\n async scoreLeads(items: LeadItem[], ctx: JudgeContext): Promise<Map<string, number>> {\n if (!items.length) return new Map();\n return this.stage(\n \"leads\",\n chunk(items, 250),\n (b) => buildLeadRequest(b, ctx, this.o.config),\n (b, a) => b.map((l) => [l.id, orLex(noulOf(a[l.id]), l.lex)]),\n );\n }\n\n /** null = nothing to check (empty evidence). */\n async status(evidence: string, ctx: JudgeContext): Promise<StatusScore | null> {\n if (!evidence.trim()) return null;\n const req = buildStatusRequest(evidence, ctx, this.o.config);\n const t0 = performance.now();\n try {\n const a = await this.ask(\"status\", req.state, req.questions);\n return {\n overall: noulOf(a.overall),\n subs: ctx.subQuestions.map((_, j) => noulOf(a[`sub::${j}`])),\n };\n } finally {\n this.stat(\"status\").ms += Math.round(performance.now() - t0);\n }\n }\n}\n","/**\n * The only way the code_search engine touches files and processes. The sandbox side implements it.\n *\n * The engine passes ripgrep only these flags, so an adapter may enforce an allowlist:\n * --files, --null, --line-number, --with-filename, --no-heading, --color never, -i, -w, --no-require-git,\n * --hidden, -m N, --max-columns N, --max-filesize N, -g GLOB, -e PATTERN, then `--` followed by\n * workspace-relative paths (\".\" or paths without a leading \"-\", no absolute paths, no \"..\").\n * A PATTERN is never longer than CODE_SEARCH_MAX_PATTERN_CHARS: the engine splits a longer alternation\n * into several ripgrep calls and merges their output.\n */\n\n/**\n * Longest `-e` pattern the engine passes to ripgrep, so an adapter may cap pattern length (the sandbox\n * adapter rejects patterns over 16,384 characters).\n */\nexport const CODE_SEARCH_MAX_PATTERN_CHARS = 16_000;\n\nexport type CodeSearchRipgrepResult = {\n stdout: string;\n exitCode: number | null;\n truncated: boolean;\n timedOut: boolean;\n};\n\nexport interface CodeSearchWorkspace {\n /** Run ripgrep in the workspace root. `args` excludes the binary. stdout is exactly what rg prints (up to the adapter's byte cap; `truncated` reports a cut). exitCode follows rg: 0 matches, 1 none, 2 error. Throws CodeSearchWorkspaceError when ripgrep is missing or the workspace is unreachable. */\n ripgrep(\n args: readonly string[],\n options: { signal?: AbortSignal; timeoutMs: number },\n ): Promise<CodeSearchRipgrepResult>;\n /** Read a workspace-relative file as UTF-8. Null when missing. */\n readText(\n path: string,\n options: { signal?: AbortSignal; maxBytes: number },\n ): Promise<{ text: string; truncated: boolean; binary: boolean } | null>;\n /** Classify workspace-relative paths. */\n pathKinds(\n paths: readonly string[],\n options: { signal?: AbortSignal },\n ): Promise<Record<string, \"file\" | \"directory\" | \"missing\">>;\n}\n\nexport class CodeSearchWorkspaceError extends Error {}\n\n/**\n * Thrown by an adapter when the ripgrep binary is not installed, so the tool can tell the model to use\n * other search commands. A plain CodeSearchWorkspaceError whose message says ripgrep is missing is\n * recognised too.\n */\nexport class CodeSearchRipgrepMissingError extends CodeSearchWorkspaceError {\n constructor(message = \"ripgrep (rg) is not installed in this workspace\") {\n super(message);\n this.name = \"CodeSearchRipgrepMissingError\";\n }\n}\n","/**\n * session.ts - one search's view of the workspace: counts calls, records partial ripgrep output and\n * makes every call honour the search's AbortSignal.\n */\nimport { CodeSearchWorkspaceError, type CodeSearchWorkspace } from \"./workspace\";\n\n/** Parallel reads per search. */\nexport const READ_CONCURRENCY = 8;\n/** Parallel ripgrep calls for one pattern split under CODE_SEARCH_MAX_PATTERN_CHARS. */\nexport const RIPGREP_SPLIT_CONCURRENCY = 4;\n\nexport class WorkspaceSession {\n calls = 0;\n /** A ripgrep call returned output cut at the adapter's byte cap. */\n truncated = false;\n /** A ripgrep call hit its time limit (its output is partial). */\n timedOut = false;\n\n constructor(\n private readonly workspace: CodeSearchWorkspace,\n readonly signal: AbortSignal,\n private readonly ripgrepTimeoutMs: number,\n ) {}\n\n get partial(): boolean {\n return this.truncated || this.timedOut;\n }\n\n /**\n * ripgrep stdout. Exit code 2 (error) with some output keeps the output (for example unreadable files);\n * with no output it throws unless `allowFailure`, which then yields \"\".\n */\n async ripgrep(\n args: readonly string[],\n options: { allowFailure?: boolean } = {},\n ): Promise<string> {\n this.signal.throwIfAborted();\n this.calls++;\n const r = await this.workspace.ripgrep(args, {\n signal: this.signal,\n timeoutMs: this.ripgrepTimeoutMs,\n });\n this.signal.throwIfAborted();\n if (r.truncated) this.truncated = true;\n if (r.timedOut) this.timedOut = true;\n if (r.exitCode === 2 && !r.stdout && !r.truncated && !r.timedOut && !options.allowFailure) {\n throw new CodeSearchWorkspaceError(\"ripgrep failed (exit code 2) without output\");\n }\n return r.stdout;\n }\n\n /** File text, or null when missing or binary (NUL bytes). */\n async readText(path: string, maxBytes: number): Promise<string | null> {\n this.signal.throwIfAborted();\n this.calls++;\n const r = await this.workspace.readText(path, { signal: this.signal, maxBytes });\n this.signal.throwIfAborted();\n if (!r || r.binary || r.text.includes(\"\\u0000\")) return null;\n return r.text;\n }\n\n async pathKinds(\n paths: readonly string[],\n ): Promise<Record<string, \"file\" | \"directory\" | \"missing\">> {\n this.signal.throwIfAborted();\n this.calls++;\n const r = await this.workspace.pathKinds(paths, { signal: this.signal });\n this.signal.throwIfAborted();\n return r;\n }\n}\n\n/** Map with at most `limit` calls in flight; results keep the input order. */\nexport async function mapLimit<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n const out = new Array<R>(items.length);\n let next = 0;\n const worker = async () => {\n while (next < items.length) {\n const i = next++;\n out[i] = await fn(items[i]!);\n }\n };\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n return out;\n}\n","/**\n * text.ts - keyword variants, word splitting, stopwords and small text helpers.\n */\n\n/** Split an identifier or phrase into lowercase words: fooBarBAZ_qux-v2 -> [foo, bar, baz, qux, v2]. */\nexport function splitWords(s: string): string[] {\n return s\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1 $2\")\n .split(/[^A-Za-z0-9]+/)\n .filter(Boolean)\n .map((w) => w.toLowerCase());\n}\n\nconst cap = (w: string) => (w ? w[0]!.toUpperCase() + w.slice(1) : w);\n\n/**\n * Identifier variants of a keyword. The search is case-insensitive, so only the\n * separator forms matter: concatenated (camel/Pascal/flat), snake/SCREAMING, kebab, spaced phrase.\n * Returned in display casing (camel, snake, kebab, spaced) for the trace; deduped case-insensitively.\n */\nexport function keywordVariants(kw: string): string[] {\n const raw = kw.trim();\n if (!raw) return [];\n const words = splitWords(raw);\n const out: string[] = [raw];\n if (words.length >= 2) {\n out.push(words[0] + words.slice(1).map(cap).join(\"\")); // camelCase (== PascalCase / flat under -i)\n out.push(words.join(\"_\")); // snake_case (== SCREAMING_SNAKE under -i)\n out.push(words.join(\"-\")); // kebab-case\n out.push(words.join(\" \")); // spaced phrase (prose in docs)\n }\n const seen = new Set<string>();\n return out.filter((v) => {\n const k = v.toLowerCase();\n if (seen.has(k) || k.length < 2) return false;\n seen.add(k);\n return true;\n });\n}\n\n/** Contiguous 2-word fragments of a compound with >= 3 words (fallback when the full name has no hits). */\nexport function compoundFragments(kw: string): string[] {\n const words = splitWords(kw);\n if (words.length < 3) return [];\n const out: string[] = [];\n for (let i = 0; i + 1 < words.length; i++) {\n const a = words[i]!;\n const b = words[i + 1]!;\n if (a.length + b.length < 8) continue; // skip tiny fragments like \"is\" + \"on\"\n out.push(a + cap(b));\n }\n return [...new Set(out)];\n}\n\n/** A single plain word (no case change, no separator) short enough to need a word boundary. */\nexport function isShortPlainWord(kw: string, maxLen: number): boolean {\n return /^[A-Za-z]+$/.test(kw) && kw.length <= maxLen && splitWords(kw).length === 1;\n}\n\n/** Escape for Rust regex (ripgrep). */\nexport function escapeRegex(s: string): string {\n return s.replace(/[\\\\.+*?()|[\\]{}^$#&\\-~]/g, (m) => `\\\\${m}`);\n}\n\nexport const STOPWORDS = new Set(\n (\n \"a an and are as at be been but by can could did do does doing done for from had has have how i if in into is it its \" +\n \"just me my no not of on or our should so some such than that the their them then there these they this those to \" +\n \"too was we were what when where which while who why will with would you your also any each else ever every much \" +\n \"more most other same very about above after again against all am before being below between both during few \" +\n \"further here him his her hers himself itself let may might must nor now off once only own over under until up \" +\n \"use used using want way get got make makes happen happens happening still actually really even whether instead \" +\n \"rather something someone thing things one two three kind already mean means\"\n ).split(\" \"),\n);\n\n/** Crude stemmer: good enough for overlap scoring (not for display). */\nexport function stem(w: string): string {\n let s = w.toLowerCase();\n if (s.length > 5 && s.endsWith(\"ies\")) s = s.slice(0, -3) + \"y\";\n else if (s.length > 5 && (s.endsWith(\"ing\") || s.endsWith(\"ers\"))) s = s.slice(0, -3);\n else if (s.length > 4 && (s.endsWith(\"ed\") || s.endsWith(\"es\") || s.endsWith(\"er\")))\n s = s.slice(0, -2);\n else if (s.length > 3 && s.endsWith(\"s\") && !s.endsWith(\"ss\")) s = s.slice(0, -1);\n return s;\n}\n\n/** Content terms of a text (identifiers split into words, stopwords dropped, stemmed, deduped). */\nexport function contentTerms(text: string, minLen = 3): string[] {\n const out = new Set<string>();\n for (const tok of text.match(/[A-Za-z][A-Za-z0-9_]*/g) ?? []) {\n for (const w of splitWords(tok)) {\n if (w.length < minLen || STOPWORDS.has(w)) continue;\n out.add(stem(w));\n }\n }\n return [...out];\n}\n\n/** Fraction of `terms` present in `textTerms`. */\nexport function overlap(terms: string[], textTerms: Set<string>): number {\n if (!terms.length) return 0;\n let n = 0;\n for (const t of terms) if (textTerms.has(t)) n++;\n return n / terms.length;\n}\n\nexport function isTestPath(p: string): boolean {\n return (\n /(^|\\/)(test|tests|__tests__|spec|e2e|fixtures?)\\//.test(p) || /\\.(test|spec)\\.[a-z]+$/.test(p)\n );\n}\n\n/** Release notes: CHANGELOG*, HISTORY*, RELEASE_NOTES*, .changeset/ entries (describe past changes, not current code). */\nexport function isChangelogPath(p: string): boolean {\n return (\n /(^|\\/)(CHANGELOG|HISTORY|RELEASE[-_]?NOTES)[^/]*$/i.test(p) || /(^|\\/)\\.changeset\\//.test(p)\n );\n}\n\n/** Is the question about history / releases (then release notes are not down-weighted)? */\nexport function questionMentionsHistory(q: string): boolean {\n return /\\b(changelog|release notes?|released|history|historical|when (?:was|did)|which version|since version|changed in)\\b/i.test(\n q,\n );\n}\n\nexport function isDocPath(p: string): boolean {\n return /\\.(md|mdx|txt|rst)$/i.test(p);\n}\n\nexport function questionMentionsTests(q: string): boolean {\n return /\\b(test|tests|testing|spec|specs|unit test|e2e|fixture)\\b/i.test(q);\n}\n\n/** Trim a line to maxChars around the first occurrence of any needle (case-insensitive). */\nexport function trimAround(line: string, needles: string[], maxChars: number): string {\n const t = line.replace(/\\t/g, \" \").trim();\n if (t.length <= maxChars) return t;\n const lower = t.toLowerCase();\n let at = -1;\n for (const n of needles) {\n const i = lower.indexOf(n.toLowerCase());\n if (i >= 0 && (at < 0 || i < at)) at = i;\n }\n if (at < 0) return t.slice(0, maxChars - 3) + \"...\";\n const start = Math.max(0, Math.min(at - Math.floor(maxChars / 3), t.length - maxChars));\n const s = t.slice(start, start + maxChars - 6);\n return (start > 0 ? \"...\" : \"\") + s + (start + maxChars - 6 < t.length ? \"...\" : \"\");\n}\n\nexport function estTokens(chars: number, charsPerToken: number): number {\n return Math.ceil(chars / charsPerToken);\n}\n\nexport function fmtK(n: number): string {\n return n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n);\n}\n","/**\n * leads.ts - wave 3: identifiers referenced by relevant passages whose definitions were not read.\n *\n * Extraction (code only): called functions, imported names, PascalCase types, UPPER_CASE constants,\n * env/config keys and camelCase member accesses. Excluded: names already searched (keywords and their\n * variants), names defined inside the selected passages, a stoplist of builtins/common helpers, and\n * names shorter than 4 chars. Definitions are located with one ripgrep regex call (a few when the names do\n * not fit one pattern under CODE_SEARCH_MAX_PATTERN_CHARS).\n */\nimport type { CodeSearchConfig } from \"./config\";\nimport { mapLimit, RIPGREP_SPLIT_CONCURRENCY, type WorkspaceSession } from \"./session\";\nimport { escapeRegex, isTestPath, splitWords } from \"./text\";\nimport { CODE_SEARCH_MAX_PATTERN_CHARS } from \"./workspace\";\n\nexport interface SeedPassage {\n path: string;\n start: number;\n /** raw file lines of the passage (no `N|` prefixes) */\n lines: string[];\n rel: number;\n}\n\nexport interface LeadCandidate {\n name: string;\n /** weighted frequency: sum of relevance of seed passages mentioning it + occurrence bonus */\n weight: number;\n occurrences: number;\n called: boolean;\n seenAt: { path: string; line: number };\n context: string;\n kinds: string[];\n}\n\nexport const LEAD_STOPLIST = new Set(\n // JS/TS builtins, globals, utility types\n (\n \"Promise Array Object String Number Boolean Map Set WeakMap WeakSet Symbol Error TypeError RangeError SyntaxError \" +\n \"JSON Math Date RegExp BigInt Buffer URL URLSearchParams console require parseInt parseFloat setTimeout clearTimeout \" +\n \"setInterval clearInterval setImmediate queueMicrotask isNaN isFinite encodeURIComponent decodeURIComponent \" +\n \"structuredClone fetch Response Request Headers FormData Blob File AbortController AbortSignal TextEncoder TextDecoder \" +\n \"Uint8Array Int32Array Float64Array ArrayBuffer DataView Record Partial Readonly ReadonlyArray Pick Omit Exclude Extract \" +\n \"ReturnType Parameters Awaited NonNullable Required InstanceType Iterable AsyncIterable Generator AsyncGenerator \" +\n \"PromiseLike Function Uppercase Lowercase keyof typeof instanceof undefined null true false this super \" +\n \"process Bun Deno globalThis window document performance crypto \" +\n // test helpers\n \"expect describe test beforeEach afterEach beforeAll afterAll mock spyOn toBe toEqual toStrictEqual toMatch \" +\n \"toContain toThrow toHaveBeenCalled toHaveBeenCalledWith toHaveLength toBeDefined toBeUndefined toBeNull toBeTruthy \" +\n \"toBeFalsy toMatchObject toBeGreaterThan toBeLessThan resolves rejects \" +\n // very common methods\n \"push pop shift unshift map filter reduce forEach find findIndex some every includes join split slice splice concat \" +\n \"indexOf lastIndexOf keys values entries from assign freeze stringify parse toString valueOf trim trimStart trimEnd \" +\n \"replace replaceAll match matchAll exec startsWith endsWith toLowerCase toUpperCase padStart padEnd localeCompare \" +\n \"then catch finally resolve reject allSettled race floor ceil round abs sqrt random sort reverse flat flatMap fill \" +\n \"length size delete clear warn error info debug trace assert emit once listen close write read send next done \" +\n \"toISOString getTime toFixed charAt charCodeAt codePointAt fromEntries isArray hasOwnProperty defineProperty \" +\n \"getOwnPropertyNames create apply call bind \" +\n // drizzle / zod / sql helpers\n \"select insert update values returning where from innerJoin leftJoin orderBy groupBy limit offset execute \" +\n \"inArray isNull isNotNull desc asc sql eq ne gt gte lt lte and or not like ilike between exists \" +\n \"object string number boolean array optional nullable nullish literal union enum infer default describe \" +\n \"safeParse parseAsync strict passthrough extend merge partial refine superRefine transform coerce positive \" +\n \"nonnegative int min max email uuid regex \" +\n // SQL functions\n \"coalesce count now greatest least jsonb_build_object jsonb_set jsonb_agg array_agg format lower upper nullif \" +\n \"current_setting set_config gen_random_uuid clock_timestamp \" +\n // Rust\n \"Ok Err Some None Box Vec Arc Mutex RwLock Option Result clone unwrap expect into iter collect map_err ok_or as_ref \" +\n \"to_string to_owned println eprintln format vec\"\n ).split(/\\s+/),\n);\n\nconst CONTROL = new Set([\n \"if\",\n \"for\",\n \"while\",\n \"switch\",\n \"catch\",\n \"return\",\n \"function\",\n \"typeof\",\n \"await\",\n \"async\",\n \"new\",\n \"else\",\n \"case\",\n \"void\",\n \"delete\",\n \"yield\",\n \"import\",\n \"export\",\n \"constructor\",\n \"super\",\n \"this\",\n \"static\",\n \"private\",\n \"public\",\n \"protected\",\n]);\n\n/** Names declared inside a passage (so they are not leads). */\nexport function definedNames(text: string): Set<string> {\n const out = new Set<string>();\n const res = [\n /\\bfunction\\*?\\s+([A-Za-z_$][\\w$]*)/g,\n /\\b(?:const|let|var)\\s+([A-Za-z_$][\\w$]*)/g,\n /\\b(?:class|interface|type|enum|namespace|struct|trait|fn|def|func|mod)\\s+([A-Za-z_$][\\w$]*)/g,\n /(?:FUNCTION|function)\\s+(?:[\\w\"]+\\.)?\"?([A-Za-z_][\\w]*)\"?\\s*\\(/g,\n /^\\s*(?:(?:public|private|protected|static|async|readonly|override|get|set)\\s+)*([A-Za-z_$][\\w$]*)\\s*(?:<[^>()]*>)?\\s*\\([^;]*\\)\\s*(?::[^={;]+)?\\{\\s*$/gm,\n ];\n for (const re of res) for (const m of text.matchAll(re)) if (!CONTROL.has(m[1]!)) out.add(m[1]!);\n // destructured consts: const { a, b: c } = ...\n for (const m of text.matchAll(/\\b(?:const|let|var)\\s*\\{([^}]*)\\}/g)) {\n for (const part of m[1]!.split(\",\")) {\n const name = part.split(\":\").pop()!.split(\"=\")[0]!.trim();\n if (/^[A-Za-z_$][\\w$]*$/.test(name)) out.add(name);\n }\n }\n return out;\n}\n\n/** Raw identifier occurrences (name, kind) in one line. */\nexport function identifiersInLine(line: string): Array<{ name: string; kind: string }> {\n const out: Array<{ name: string; kind: string }> = [];\n for (const m of line.matchAll(/\\b([A-Za-z_$][\\w$]*)\\s*(?:<[^<>()]*>)?\\s*\\(/g))\n out.push({ name: m[1]!, kind: \"call\" });\n const imp = /import\\s+(?:type\\s+)?\\{([^}]*)\\}/.exec(line);\n if (imp) {\n for (const part of imp[1]!.split(\",\")) {\n const name = part\n .replace(/^\\s*type\\s+/, \"\")\n .split(/\\s+as\\s+/)[0]!\n .trim();\n if (/^[A-Za-z_$][\\w$]*$/.test(name)) out.push({ name, kind: \"import\" });\n }\n }\n for (const m of line.matchAll(/\\b([A-Z][a-z0-9]+(?:[A-Z][A-Za-z0-9]*)+)\\b/g))\n out.push({ name: m[1]!, kind: \"type\" });\n for (const m of line.matchAll(/\\b([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+)\\b/g))\n out.push({ name: m[1]!, kind: \"constant\" });\n for (const m of line.matchAll(/\\.([a-z][a-z0-9]*[A-Z][A-Za-z0-9]*)\\b/g))\n out.push({ name: m[1]!, kind: \"member\" });\n return out;\n}\n\nfunction trimContext(line: string, name: string, max = 160): string {\n const t = line.trim().replace(/\\s+/g, \" \");\n if (t.length <= max) return t;\n const i = Math.max(0, t.indexOf(name) - 50);\n return (i > 0 ? \"...\" : \"\") + t.slice(i, i + max - 6) + \"...\";\n}\n\n/**\n * Extract lead candidates from seed passages (most relevant first), ranked by weighted frequency.\n * `searched` = lowercased keywords + variants (already searched; not leads).\n */\nexport function extractLeads(\n seeds: SeedPassage[],\n searched: Set<string>,\n questionWords: Set<string>,\n max: number,\n): LeadCandidate[] {\n const defined = new Set<string>();\n for (const s of seeds) for (const n of definedNames(s.lines.join(\"\\n\"))) defined.add(n);\n const byName = new Map<string, LeadCandidate>();\n for (const s of seeds) {\n const inThis = new Set<string>();\n const prose = /\\.(md|mdx|txt|rst)$/i.test(s.path);\n const sql = /\\.sql$/i.test(s.path);\n s.lines.forEach((line, i) => {\n if (!prose && /^\\s*(\\/\\/|\\*|\\/\\*|#(?!\\[)|--)/.test(line)) return; // code comments: skip\n // prose: only identifiers inside `backticks`\n const scan = prose ? (line.match(/`[^`]+`/g) ?? []).join(\" \") : line;\n if (!scan) return;\n for (const { name, kind } of identifiersInLine(scan)) {\n if (name.length < 4 || CONTROL.has(name) || LEAD_STOPLIST.has(name) || defined.has(name))\n continue;\n if (sql && /^[A-Z]+$/.test(name)) continue; // SQL keywords followed by \"(\" (CHECK, EXISTS, VALUES) are not calls\n if (searched.has(name.toLowerCase()) || searched.has(splitWords(name).join(\" \"))) continue;\n let c = byName.get(name);\n if (!c) {\n c = {\n name,\n weight: 0,\n occurrences: 0,\n called: false,\n seenAt: { path: s.path, line: s.start + i },\n context: trimContext(line, name),\n kinds: [],\n };\n byName.set(name, c);\n }\n c.occurrences++;\n if (kind === \"call\") c.called = true;\n if (!c.kinds.includes(kind)) c.kinds.push(kind);\n if (!inThis.has(name)) {\n c.weight += s.rel;\n inThis.add(name);\n }\n }\n });\n }\n const score = (c: LeadCandidate) => {\n const words = splitWords(c.name);\n const ov = words.filter((w) => questionWords.has(w)).length / Math.max(1, words.length);\n return c.weight + 0.1 * Math.min(5, c.occurrences - 1) + (c.called ? 0.2 : 0) + ov;\n };\n return [...byName.values()]\n .sort((a, b) => score(b) - score(a) || (a.name < b.name ? -1 : 1))\n .slice(0, max)\n .map((c) => ({ ...c, weight: Math.round(score(c) * 1000) / 1000 }));\n}\n\nexport interface DefinitionHit {\n name: string;\n path: string;\n line: number;\n kind: \"decl\" | \"sqlfn\" | \"method\" | \"key\";\n text: string;\n}\n\n/** The JS regexes used to classify an rg match line for one name (priority order). */\nexport function definitionKinds(name: string): Array<{ kind: DefinitionHit[\"kind\"]; re: RegExp }> {\n const n = escapeRegex(name);\n return [\n {\n kind: \"decl\",\n re: new RegExp(\n `\\\\b(?:function\\\\*?|const|let|var|class|interface|type|enum|namespace|struct|trait|fn|def|func|mod)\\\\s+${n}\\\\b`,\n ),\n },\n { kind: \"sqlfn\", re: new RegExp(`\\\\bfunction\\\\s+(?:[\\\\w\"]+\\\\.)?\"?${n}\"?\\\\s*\\\\(`, \"i\") },\n {\n kind: \"method\",\n re: new RegExp(\n `^\\\\s*(?:(?:public|private|protected|static|async|readonly|override|get|set)\\\\s+)*${n}\\\\s*(?:<[^>()]*>)?\\\\s*\\\\([^;]*(?:\\\\{|\\\\(|,)\\\\s*$`,\n ),\n },\n { kind: \"key\", re: new RegExp(`^\\\\s*[\"']?${n}[\"']?\\\\??\\\\s*[:=]`) },\n ];\n}\n\n/**\n * rg pattern (ASCII mode) for definition-shaped lines of any of the names: declarations, SQL functions,\n * methods and object keys / fields / config keys. Classified per name in JS with definitionKinds().\n */\nexport function definitionPattern(names: readonly string[]): string {\n const alt = names.map(escapeRegex).join(\"|\");\n return (\n \"(?-u:\" +\n [\n `\\\\b(?:function\\\\*?|const|let|var|class|interface|type|enum|namespace|struct|trait|fn|def|func|mod)\\\\s+(?:${alt})\\\\b`,\n `(?i:function)\\\\s+(?:[\\\\w\"]+\\\\.)?\"?(?:${alt})\"?\\\\s*\\\\(`,\n `^\\\\s*(?:(?:public|private|protected|static|async|readonly|override|get|set)\\\\s+)*(?:${alt})\\\\s*(?:<[^>()]*>)?\\\\s*\\\\(`,\n `^\\\\s*[\"']?(?:${alt})[\"']?\\\\??\\\\s*[:=]`,\n ].join(\"|\") +\n \")\"\n );\n}\n\n/**\n * definitionPattern over consecutive groups of names, each pattern at most maxChars. A name whose own pattern\n * is longer is left out: it gets no definition, as after a failed search.\n */\nexport function definitionPatterns(\n names: readonly string[],\n maxChars = CODE_SEARCH_MAX_PATTERN_CHARS,\n): string[] {\n const out: string[] = [];\n let group: string[] = [];\n for (const name of names) {\n if (definitionPattern([name]).length > maxChars) continue;\n if (group.length && definitionPattern([...group, name]).length > maxChars) {\n out.push(definitionPattern(group));\n group = [];\n }\n group.push(name);\n }\n if (group.length) out.push(definitionPattern(group));\n return out;\n}\n\nconst KIND_RANK: Record<DefinitionHit[\"kind\"], number> = { decl: 3, sqlfn: 3, method: 2, key: 1 };\n\n/** Package root of a path: the first two segments for apps/ and packages/ (apps/worker, packages/runtime), else the first. */\nexport function packageOf(path: string): string {\n const parts = path.split(\"/\");\n return /^(apps|packages|services|libs|crates)$/.test(parts[0] ?? \"\") && parts.length > 2\n ? parts.slice(0, 2).join(\"/\")\n : (parts[0] ?? \"\");\n}\n\n/**\n * Choose the best definitions per name. A name can be defined in many places (`search`, `isRecord`), so locality\n * dominates: the file where the lead was seen, then its package; then kind rank (declaration > method > key),\n * non-test, an already-selected file, a config-ish path for keys, path, line.\n */\nexport function chooseDefinitions(\n hits: DefinitionHit[],\n preferPaths: Set<string>,\n perName: number,\n allowTests = false,\n seenAt: Map<string, string> = new Map(),\n): Map<string, DefinitionHit[]> {\n const by = new Map<string, DefinitionHit[]>();\n for (const h of hits) {\n if (!allowTests && isTestPath(h.path)) continue;\n const arr = by.get(h.name) ?? [];\n arr.push(h);\n by.set(h.name, arr);\n }\n const rank = (h: DefinitionHit) =>\n (seenAt.get(h.name) === h.path ? 100 : 0) +\n (seenAt.has(h.name) && packageOf(seenAt.get(h.name)!) === packageOf(h.path) ? 50 : 0) +\n KIND_RANK[h.kind] * 10 +\n (isTestPath(h.path) ? 0 : 4) +\n (preferPaths.has(h.path) ? 2 : 0) +\n (h.kind === \"key\" && /config|setting|schema|env/i.test(h.path) ? 1 : 0);\n const out = new Map<string, DefinitionHit[]>();\n for (const [name, arr] of by) {\n arr.sort(\n (a, b) => rank(b) - rank(a) || (a.path < b.path ? -1 : a.path > b.path ? 1 : a.line - b.line),\n );\n out.set(name, arr.slice(0, perName));\n }\n return out;\n}\n\nexport interface DefinitionSearch {\n hits: DefinitionHit[];\n /** name -> number of repository files that mention it as a word (for an IDF-style genericity penalty) */\n fileCounts: Map<string, number>;\n ms: number;\n}\n\n/** Files a definition search never needs: prose/data (definitions of code identifiers live in code or SQL). */\nexport const DEF_SCAN_EXCLUDES = [\"!*.{md,mdx,txt,rst,json,jsonc,html,csv,svg,snap,xml}\"];\n/** Test files, excluded from the definition scan unless the question is about tests. */\nexport const TEST_EXCLUDES = [\n \"!**/test/**\",\n \"!**/tests/**\",\n \"!**/__tests__/**\",\n \"!**/e2e/**\",\n \"!**/fixtures/**\",\n \"!*.test.*\",\n \"!*.spec.*\",\n];\n\n/**\n * ONE rg pass (ASCII-mode regex, full lines) for definition-shaped lines of all names over code and SQL files\n * (tests only when the question is about tests), classified per name in JS: declarations/SQL functions/methods\n * first; object keys / fields / config keys (`name:` / `name =`) only for names without a stronger definition,\n * and a name whose only definitions are more than maxKeyOnlyDefs keys is a generic field (sessionId, accountId)\n * and gets none. fileCounts = files with any definition-shaped line for the name (generic fields and helpers\n * redefined everywhere score high), used as a genericity penalty. About 0.4 CPU-s on a 6k-file repository; a\n * second pass that counted every mention cost another ~0.7 CPU-s and full-line mention output was 80k lines.\n * Names that do not fit one pattern under the cap are searched in a few passes, merged line by line.\n * A failed definition search yields no hits (the leads are then dropped), as in scout.\n */\nexport async function locateDefinitions(\n session: WorkspaceSession,\n names: string[],\n cfg: CodeSearchConfig,\n excludeArgs: string[],\n maxKeyOnlyDefs = 12,\n allowTests = false,\n): Promise<DefinitionSearch> {\n const t0 = performance.now();\n if (!names.length) return { hits: [], fileCounts: new Map(), ms: 0 };\n const extra = [...DEF_SCAN_EXCLUDES, ...(allowTests ? [] : TEST_EXCLUDES)].flatMap((g) => [\n \"-g\",\n g,\n ]);\n const defOuts = await mapLimit(definitionPatterns(names), RIPGREP_SPLIT_CONCURRENCY, (pattern) =>\n session.ripgrep(\n [\n \"--null\",\n \"--line-number\",\n \"--with-filename\",\n \"--no-heading\",\n \"--color\",\n \"never\",\n \"--no-require-git\",\n \"--max-columns\",\n String(cfg.recall.maxLineColumns),\n \"--max-filesize\",\n String(cfg.recall.maxFileBytes),\n ...excludeArgs,\n ...extra,\n \"-e\",\n pattern,\n \"--\",\n \".\",\n ],\n { allowFailure: true },\n ),\n );\n const kinds = new Map(names.map((n) => [n, definitionKinds(n)]));\n const nameSet = new Set(names);\n const files = new Map<string, Set<string>>();\n const strong: DefinitionHit[] = [];\n const keys: DefinitionHit[] = [];\n const seenRows = new Set<string>();\n for (const row of defOuts.flatMap((out) => out.split(\"\\n\"))) {\n const z = row.indexOf(\"\\0\");\n if (z <= 0) continue;\n const colon = row.indexOf(\":\", z + 1);\n if (colon < 0) continue;\n // a line matched by two of the split patterns is classified once, as with one pattern\n const at = row.slice(0, colon);\n if (seenRows.has(at)) continue;\n seenRows.add(at);\n const text = row.slice(colon + 1);\n if (text.length > 400 || text.startsWith(\"[Omitted long line\")) continue; // a definition line is short\n const path = row.slice(0, z).replace(/^\\.\\//, \"\");\n const line = Number(row.slice(z + 1, colon));\n const present = new Set((text.match(/[A-Za-z_$][\\w$]*/g) ?? []).filter((t) => nameSet.has(t)));\n for (const name of present) {\n for (const k of kinds.get(name)!) {\n if (!k.re.test(text)) continue;\n (k.kind === \"key\" ? keys : strong).push({\n name,\n path,\n line,\n kind: k.kind,\n text: text.trim().slice(0, 200),\n });\n let fs = files.get(name);\n if (!fs) files.set(name, (fs = new Set()));\n fs.add(path);\n break;\n }\n }\n }\n const hasStrong = new Set(strong.map((h) => h.name));\n const keyHits = keys.filter((h) => !hasStrong.has(h.name));\n const keyCount = new Map<string, number>();\n for (const h of keyHits) keyCount.set(h.name, (keyCount.get(h.name) ?? 0) + 1);\n const hits = [...strong, ...keyHits.filter((h) => (keyCount.get(h.name) ?? 0) <= maxKeyOnlyDefs)];\n hits.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : a.line - b.line));\n const fileCounts = new Map(names.map((n) => [n, files.get(n)?.size ?? 0]));\n return { hits, fileCounts, ms: Math.round(performance.now() - t0) };\n}\n","/**\n * windows.ts - turn hit lines into readable passages.\n *\n * For each hit: walk up (<= maxUp lines) to the nearest declaration line at lower-or-equal indentation\n * whose block encloses the hit (function/class/const/export/interface/type/enum/describe/route handler,\n * markdown heading, SQL statement, python def/class), then walk down to where that block closes\n * (<= maxDown lines below the hit). No enclosing declaration -> fixed context around the hit, labelled\n * with the nearest enclosing declaration further up. Overlapping windows merge; windows longer than\n * maxWindowLines split around hit clusters; each file keeps its best windowsPerFile windows.\n * All line numbers in this module's public API are 1-based. A line past the end of the file as read (it\n * changed after ripgrep saw it, or could not be read) is skipped by the callers and treated as blank here.\n */\nimport type { CodeSearchConfig } from \"./config\";\nimport type { HitLine, KeywordInfo } from \"./recall\";\n\nexport type Lang = \"brace\" | \"indent\" | \"markdown\" | \"sql\" | \"other\";\n\nexport interface Window {\n start: number;\n end: number;\n /** Hit lines inside the window (1-based). */\n hits: number[];\n /** Enclosing declaration when it is above the window start (or the window starts at it). */\n label?: { line: number; text: string } | undefined;\n kind: \"hit\" | \"header\" | \"def\";\n score: number;\n}\n\nexport function langOf(path: string): Lang {\n const ext = path.toLowerCase().split(\".\").pop() ?? \"\";\n if (\n [\n \"ts\",\n \"tsx\",\n \"js\",\n \"jsx\",\n \"mjs\",\n \"cjs\",\n \"mts\",\n \"cts\",\n \"rs\",\n \"go\",\n \"java\",\n \"c\",\n \"h\",\n \"cc\",\n \"cpp\",\n \"hpp\",\n \"cs\",\n \"swift\",\n \"kt\",\n \"scala\",\n \"css\",\n \"scss\",\n \"json\",\n \"jsonc\",\n \"proto\",\n \"tf\",\n \"hcl\",\n ].includes(ext)\n ) {\n return \"brace\";\n }\n if ([\"py\", \"yaml\", \"yml\"].includes(ext)) return \"indent\";\n if ([\"md\", \"mdx\"].includes(ext)) return \"markdown\";\n if (ext === \"sql\") return \"sql\";\n return \"other\";\n}\n\nexport function indentOf(line: string): number {\n let n = 0;\n for (const ch of line) {\n if (ch === \" \") n += 1;\n else if (ch === \"\\t\") n += 4;\n else break;\n }\n return n;\n}\n\nconst CONTROL = new Set([\n \"if\",\n \"for\",\n \"while\",\n \"switch\",\n \"catch\",\n \"return\",\n \"else\",\n \"do\",\n \"try\",\n \"with\",\n \"await\",\n \"new\",\n \"typeof\",\n \"function\",\n \"throw\",\n \"yield\",\n \"delete\",\n \"void\",\n \"in\",\n \"of\",\n \"case\",\n \"super\",\n \"this\",\n \"import\",\n \"export\",\n]);\n\nconst TS_DECL =\n /^\\s*(?:export\\s+)?(?:default\\s+)?(?:declare\\s+)?(?:abstract\\s+)?(?:async\\s+)?(?:function\\b|class\\s|interface\\s|type\\s+[A-Za-z_$][\\w$]*\\s*(?:<[^>]*>)?\\s*=|enum\\s|const\\s+[A-Za-z_$[{]|let\\s+[A-Za-z_$[{]|var\\s+[A-Za-z_$]|namespace\\s|module\\s)/;\nconst EXPORT_DEFAULT = /^\\s*export\\s+default\\b/;\nconst RUST_DECL =\n /^\\s*(?:pub(?:\\([^)]*\\))?\\s+)?(?:async\\s+)?(?:unsafe\\s+)?(?:const\\s+)?(?:fn|struct|enum|trait|impl|mod|macro_rules!)[\\s<]/;\nconst GO_DECL = /^\\s*func\\s/;\nconst TEST_DECL = /^\\s*(?:describe|it|test)(?:\\.\\w+)?\\s*\\(/;\nconst METHOD =\n /^\\s*(?:(?:public|private|protected|static|readonly|async|override|get|set)\\s+)*\\*?\\s*([A-Za-z_$][\\w$]*)\\s*(?:<[^>()]*>)?\\s*\\([^;]*$/;\nconst PROP_FN =\n /^\\s*(?:(?:public|private|protected|static|readonly)\\s+)*[A-Za-z_$][\\w$]*\\s*[:=]\\s*(?:async\\s*)?(?:function\\b|\\([^)]*\\)?[^;]*=>|[A-Za-z_$][\\w$]*\\s*=>)/;\nconst OBJ_KEY_OPEN = /^\\s*[\"']?[A-Za-z_$][\\w$-]*[\"']?\\s*:\\s*(?:[\\w$.]+\\()?[{[]\\s*$/;\nconst CALLBACK_OPEN = /^\\s*(?:await\\s+)?[\\w$]+(?:\\.[\\w$]+)+\\s*\\(.*(?:=>|function\\b).*\\{\\s*$/;\nconst MD_HEADING = /^(#{1,6})\\s/;\nconst SQL_STMT =\n /^(?:CREATE|ALTER|DROP|INSERT|UPDATE|DELETE|WITH|SELECT|DO|COMMENT|GRANT|REVOKE|BEGIN|SET|LOCK|TRUNCATE)\\b/i;\nconst PY_DECL = /^\\s*(?:async\\s+)?(?:def|class)\\s/;\nconst YAML_KEY = /^\\s*(?:- )?[\"']?[A-Za-z_$][\\w$ .-]*[\"']?\\s*:(?:\\s|$)/;\n\nexport function isDeclLine(line: string, lang: Lang): boolean {\n if (!line.trim()) return false;\n switch (lang) {\n case \"markdown\":\n return MD_HEADING.test(line);\n case \"sql\":\n return indentOf(line) === 0 && SQL_STMT.test(line);\n case \"indent\":\n return PY_DECL.test(line) || YAML_KEY.test(line);\n case \"brace\": {\n if (\n TS_DECL.test(line) ||\n EXPORT_DEFAULT.test(line) ||\n RUST_DECL.test(line) ||\n GO_DECL.test(line) ||\n TEST_DECL.test(line)\n )\n return true;\n if (PROP_FN.test(line) || OBJ_KEY_OPEN.test(line) || CALLBACK_OPEN.test(line)) return true;\n const m = METHOD.exec(line);\n if (\n m &&\n !CONTROL.has(m[1]!) &&\n /(\\{|\\(|,)\\s*$/.test(line.trimEnd()) &&\n !/^\\s*[\\w$]+\\s*\\(.*\\)\\s*;?\\s*$/.test(line)\n ) {\n return true;\n }\n return false;\n }\n default:\n return false;\n }\n}\n\n/** Remove string literals and comments so bracket counting is roughly right. */\nexport function stripForBrackets(line: string): string {\n const t = line.trim();\n if (t.startsWith(\"*\") || t.startsWith(\"/*\") || t.startsWith(\"//\")) return \"\";\n return line\n .replace(/\"(?:[^\"\\\\]|\\\\.)*\"/g, '\"\"')\n .replace(/'(?:[^'\\\\]|\\\\.)*'/g, \"''\")\n .replace(/`(?:[^`\\\\]|\\\\.)*`/g, \"``\")\n .replace(/\\/\\*.*?\\*\\//g, \"\")\n .replace(/\\/\\/.*$/, \"\");\n}\n\nconst blockEndCache = new WeakMap<string[], Map<number, number | null>>();\n\n/**\n * 0-based index of the last line of the block starting at 0-based line d, or null if unknown\n * (no structure, or longer than maxScan lines).\n */\nexport function blockEnd(lines: string[], d: number, lang: Lang, maxScan = 3000): number | null {\n let cache = blockEndCache.get(lines);\n if (!cache) {\n cache = new Map();\n blockEndCache.set(lines, cache);\n }\n const key = d * 8 + [\"brace\", \"indent\", \"markdown\", \"sql\", \"other\"].indexOf(lang);\n if (cache.has(key)) return cache.get(key)!;\n const r = computeBlockEnd(lines, d, lang, maxScan);\n cache.set(key, r);\n return r;\n}\n\nfunction computeBlockEnd(lines: string[], d: number, lang: Lang, maxScan: number): number | null {\n const n = lines.length;\n if (d < 0 || d >= n) return null;\n const last = Math.min(n - 1, d + maxScan);\n if (lang === \"brace\") {\n let depth = 0;\n let maxDepth = 0;\n for (let i = d; i <= last; i++) {\n const s = stripForBrackets(lines[i]!);\n for (const ch of s) {\n if (ch === \"{\" || ch === \"(\" || ch === \"[\") {\n depth++;\n if (depth > maxDepth) maxDepth = depth;\n } else if (ch === \"}\" || ch === \")\" || ch === \"]\") depth--;\n }\n if (maxDepth > 0 && depth <= 0) return i;\n if (maxDepth === 0 && /;\\s*$/.test(s)) return i;\n }\n return null;\n }\n if (lang === \"indent\") {\n const ind = indentOf(lines[d]!);\n let lastNonEmpty = d;\n for (let i = d + 1; i <= last; i++) {\n const l = lines[i]!;\n if (!l.trim()) continue;\n if (indentOf(l) <= ind) return lastNonEmpty;\n lastNonEmpty = i;\n }\n return last === n - 1 ? lastNonEmpty : null;\n }\n if (lang === \"markdown\") {\n const m = MD_HEADING.exec(lines[d]!);\n if (!m) return null;\n const level = m[1]!.length;\n let inFence = false;\n for (let i = d + 1; i <= last; i++) {\n const l = lines[i]!;\n if (/^\\s*(```|~~~)/.test(l)) inFence = !inFence;\n if (inFence) continue;\n const h = MD_HEADING.exec(l);\n if (h && h[1]!.length <= level) return i - 1;\n }\n return last === n - 1 ? n - 1 : null;\n }\n if (lang === \"sql\") {\n let inDollar = false;\n for (let i = d; i <= last; i++) {\n const l = lines[i]!.replace(/--.*$/, \"\");\n const toggles = (l.match(/\\$[A-Za-z_]*\\$/g) ?? []).length;\n if (toggles % 2 === 1) inDollar = !inDollar;\n if (!inDollar && /;\\s*$/.test(l)) return i;\n }\n return null;\n }\n return null;\n}\n\nfunction isCommentOrDecorator(line: string): boolean {\n return /^(\\/\\/|\\/\\*\\*?|\\*|#\\[|@[A-Za-z]|--)/.test(line.trim());\n}\n\n/** Include up to maxLines of doc comments / decorators directly above a declaration (0-based). */\nfunction leadingComments(lines: string[], d: number, lang: Lang, maxLines = 6): number {\n if (lang === \"markdown\" || lang === \"other\") return d;\n let s = d;\n while (s > 0 && d - s < maxLines && isCommentOrDecorator(lines[s - 1] ?? \"\")) s--;\n return s;\n}\n\n/** Nearest declaration above (0-based idx) with indentation below the given one; cheap, for labels only. */\nexport function nearestEnclosingLabel(\n lines: string[],\n idx: number,\n lang: Lang,\n maxScan = 2000,\n): { line: number; text: string } | undefined {\n const ind = indentOf(lines[idx] ?? \"\");\n for (let i = idx; i >= Math.max(0, idx - maxScan); i--) {\n const l = lines[i] ?? \"\";\n if (!isDeclLine(l, lang)) continue;\n if (\n lang === \"markdown\" ||\n lang === \"sql\" ||\n i === idx ||\n indentOf(l) < ind ||\n (ind === 0 && indentOf(l) === 0)\n ) {\n return { line: i + 1, text: l.trim().slice(0, 140) };\n }\n }\n return undefined;\n}\n\n/** The window around one hit line (1-based in, 1-based out). */\nexport function enclosingWindow(\n lines: string[],\n hitLine: number,\n lang: Lang,\n cfg: CodeSearchConfig,\n): Window {\n const w = cfg.wave2;\n const hi = hitLine - 1;\n const n = lines.length;\n const hitIndent = indentOf(lines[hi] ?? \"\");\n if (lang !== \"other\") {\n for (let i = hi; i >= Math.max(0, hi - w.maxUp); i--) {\n const l = lines[i] ?? \"\";\n if (!isDeclLine(l, lang)) continue;\n if ((lang === \"brace\" || lang === \"indent\") && i !== hi && indentOf(l) > hitIndent) continue;\n const e = blockEnd(lines, i, lang);\n if (e === null || e < hi) continue;\n // a short statement starting on the hit line (`const x = f(...);`) does not enclose anything\n if (i === hi && e - hi < 2) continue;\n const start = leadingComments(lines, i, lang);\n const end = Math.min(e, hi + w.maxDown, n - 1);\n return padWindow(\n {\n start: start + 1,\n end: end + 1,\n hits: [hitLine],\n label: { line: i + 1, text: l.trim().slice(0, 140) },\n kind: \"hit\",\n score: 0,\n },\n n,\n cfg,\n );\n }\n }\n const start = Math.max(0, hi - w.fallbackBefore);\n const end = Math.min(n - 1, hi + w.fallbackAfter);\n const label = lang === \"other\" ? undefined : nearestEnclosingLabel(lines, hi, lang);\n return { start: start + 1, end: end + 1, hits: [hitLine], label, kind: \"hit\", score: 0 };\n}\n\n/** Grow windows shorter than minWindowLines with surrounding context (1/3 above, 2/3 below). */\nexport function padWindow(win: Window, nLines: number, cfg: CodeSearchConfig): Window {\n const min = cfg.wave2.minWindowLines;\n const len = win.end - win.start + 1;\n if (len >= min) return win;\n const need = min - len;\n const up = Math.floor(need / 3);\n let start = Math.max(1, win.start - up);\n let end = Math.min(nLines, win.end + (need - (win.start - start)));\n if (end - start + 1 < min) start = Math.max(1, end - min + 1);\n return { ...win, start, end };\n}\n\n/** Merge overlapping windows or windows separated by <= gap lines. Input any order; output by start. */\nexport function mergeWindows(ws: Window[], gap: number): Window[] {\n const sorted = [...ws].sort((a, b) => a.start - b.start || a.end - b.end);\n const out: Window[] = [];\n for (const w of sorted) {\n const prev = out[out.length - 1];\n if (prev && w.start <= prev.end + gap + 1) {\n prev.end = Math.max(prev.end, w.end);\n prev.hits = [...new Set([...prev.hits, ...w.hits])].sort((a, b) => a - b);\n // keep the outermost label (earliest declaration)\n if (w.label && (!prev.label || w.label.line < prev.label.line)) prev.label = w.label;\n if (prev.kind !== w.kind && w.kind === \"def\") prev.kind = \"def\";\n } else {\n out.push({ ...w, hits: [...w.hits] });\n }\n }\n return out;\n}\n\n/** Split a window longer than maxLines into chunks around its hit clusters (chunks without hits are dropped). */\nexport function splitWindow(w: Window, maxLines: number, before = 20): Window[] {\n if (w.end - w.start + 1 <= maxLines) return [w];\n const hits = [...w.hits].sort((a, b) => a - b);\n if (!hits.length) return [{ ...w, end: w.start + maxLines - 1 }];\n const out: Window[] = [];\n let i = 0;\n while (i < hits.length) {\n let start = Math.max(w.start, hits[i]! - before);\n // keep the declaration line if it is close\n if (w.start >= hits[i]! - 2 * before) start = w.start;\n const end = Math.min(w.end, start + maxLines - 1);\n const chunkHits: number[] = [];\n while (i < hits.length && hits[i]! <= end) chunkHits.push(hits[i++]!);\n if (!chunkHits.length) {\n // hit before start cannot happen; guard against infinite loops\n i++;\n continue;\n }\n out.push({\n ...w,\n start,\n end,\n hits: chunkHits,\n label: w.label && w.label.line < start ? w.label : w.label,\n });\n }\n return out;\n}\n\n/** Keywords (indices) whose pattern occurs anywhere in lines[start..end] (1-based inclusive). */\nconst kwRegexCache = new WeakMap<KeywordInfo, RegExp | null>();\nexport function keywordRegex(k: KeywordInfo): RegExp | null {\n if (!kwRegexCache.has(k)) {\n let re: RegExp | null = null;\n try {\n re = new RegExp(k.pattern, \"i\");\n } catch {\n re = null;\n }\n kwRegexCache.set(k, re);\n }\n return kwRegexCache.get(k)!;\n}\n\nexport function textHasKeyword(text: string, k: KeywordInfo): boolean {\n const re = keywordRegex(k);\n if (re) return re.test(text);\n const lower = text.toLowerCase();\n return k.variants.some((v) => lower.includes(v.toLowerCase()));\n}\n\nexport function keywordsInRange(\n lines: string[],\n start: number,\n end: number,\n keywords: KeywordInfo[],\n): number[] {\n const text = lines.slice(start - 1, end).join(\"\\n\");\n return keywords.filter((k) => k.idf > 0 && textHasKeyword(text, k)).map((k) => k.index);\n}\n\nexport function scoreWindow(\n lines: string[],\n w: Window,\n keywords: KeywordInfo[],\n hitWeight = 0.1,\n): number {\n const kws = keywordsInRange(lines, w.start, w.end, keywords);\n return kws.reduce((s, k) => s + keywords[k]!.idf, 0) + hitWeight * Math.log(1 + w.hits.length);\n}\n\n/**\n * Windows for one file: window the strongest hit lines (skipping hits already covered), merge,\n * split long ones, score, keep the best windowsPerFile, return in line order.\n */\nexport function buildFileWindows(\n lines: string[],\n hitLines: HitLine[],\n keywords: KeywordInfo[],\n lang: Lang,\n cfg: CodeSearchConfig,\n render?: RenderOpts,\n): Window[] {\n const w = cfg.wave2;\n const ro: RenderOpts = render ?? { maxLineChars: w.maxLineChars };\n // prose sections are long and their paragraphs independent: smaller sub-windows around each hit\n const maxChars = lang === \"markdown\" ? w.maxProseWindowChars : w.maxWindowChars;\n if (!lines.length) return [];\n if (!hitLines.length) {\n // path-only match: the top of the file (or its first section)\n const e = lang === \"markdown\" ? Math.min(lines.length, 80) : Math.min(lines.length, 60);\n return splitByChars(\n lines,\n { start: 1, end: e, hits: [], kind: \"header\", score: 0 },\n maxChars,\n ro,\n ).slice(0, 1);\n }\n // hits past the end of the file as read (it changed after ripgrep saw it) are dropped\n const inRange = hitLines.filter((h) => h.line >= 1 && h.line <= lines.length);\n const weight = (h: HitLine) => h.kws.reduce((s, k) => s + (keywords[k]?.idf ?? 0), 0);\n const ranked = [...inRange].sort((a, b) => weight(b) - weight(a) || a.line - b.line);\n const budgetHits = w.seedHitsPerFile;\n const raw: Window[] = [];\n let used = 0;\n for (const h of ranked) {\n if (used >= budgetHits) break;\n const inside = raw.find((r) => h.line >= r.start && h.line <= r.end);\n if (inside) {\n inside.hits.push(h.line);\n continue;\n }\n raw.push(enclosingWindow(lines, h.line, lang, cfg));\n used++;\n }\n // hits that fall inside kept windows but were not windowed themselves still count\n for (const h of inRange) {\n for (const r of raw)\n if (h.line >= r.start && h.line <= r.end && !r.hits.includes(h.line)) r.hits.push(h.line);\n }\n const merged = mergeWindows(raw, w.mergeGap)\n .flatMap((x) => splitWindow(x, w.maxWindowLines))\n .flatMap((x) => splitByChars(lines, x, maxChars, ro));\n for (const x of merged) x.score = scoreWindow(lines, x, keywords, cfg.recall.hitCountWeight);\n return merged\n .sort((a, b) => b.score - a.score || a.start - b.start)\n .slice(0, w.windowsPerFile)\n .sort((a, b) => a.start - b.start);\n}\n\n/** Window for a definition found at 1-based defLine (lead following). */\nexport function definitionWindow(\n lines: string[],\n defLine: number,\n lang: Lang,\n cfg: CodeSearchConfig,\n render?: RenderOpts,\n): Window {\n const w = cfg.wave2;\n const d = defLine - 1;\n const start = leadingComments(lines, d, lang);\n const e = lang === \"other\" ? null : blockEnd(lines, d, lang);\n let end =\n e === null ? Math.min(lines.length - 1, d + w.fallbackAfter) : Math.min(e, d + w.maxDown);\n end = Math.min(end, start + w.maxWindowLines - 1, lines.length - 1);\n const win: Window = {\n start: start + 1,\n end: end + 1,\n hits: [defLine],\n label: { line: defLine, text: (lines[d] ?? \"\").trim().slice(0, 140) },\n kind: \"def\",\n score: 0,\n };\n // over the char cap: keep the part starting at the definition (the first sub-window)\n const maxChars = lang === \"markdown\" ? w.maxProseWindowChars : w.maxWindowChars;\n return splitByChars(\n lines,\n win,\n maxChars,\n render ?? { maxLineChars: w.maxLineChars },\n defLine - win.start,\n )[0]!;\n}\n\nexport interface RenderOpts {\n /** Lines longer than this are cut (with an explicit marker). */\n maxLineChars: number;\n /** When a cut line has a match beyond the head, the cut keeps the region around the first match. */\n needles?: RegExp[];\n}\n\n/**\n * Cut one over-long line to about maxChars, marked explicitly. If a needle matches beyond the first ~60% of\n * the budget, keep a short head plus the region around the match (prose docs such as AGENTS.md have\n * single-line paragraphs of 1-6k chars whose key sentence is often far from the start).\n */\nexport function cutLine(t: string, maxChars: number, needles: RegExp[] = []): string {\n if (t.length <= maxChars) return t;\n let at = -1;\n for (const re of needles) {\n const m = re.exec(t);\n if (m && (at < 0 || m.index < at)) at = m.index;\n }\n if (at < 0 || at < maxChars * 0.6)\n return `${t.slice(0, maxChars)} ...[line cut, ${t.length} chars]`;\n const head = Math.floor(maxChars * 0.25);\n const before = Math.floor(maxChars * 0.3);\n const s = Math.max(head, at - before);\n const e = Math.min(t.length, s + (maxChars - head));\n return `${t.slice(0, head)} ...[cut]... ${t.slice(s, e)}${e < t.length ? ` ...[line cut, ${t.length} chars]` : \"\"}`;\n}\n\n/** Render lines[start..end] (1-based inclusive) as `N| text`, cutting very long lines with an explicit marker. */\nexport function renderLines(\n lines: string[],\n start: number,\n end: number,\n opts: number | RenderOpts,\n): string {\n const o: RenderOpts = typeof opts === \"number\" ? { maxLineChars: opts } : opts;\n const out: string[] = [];\n for (let i = start; i <= end && i <= lines.length; i++) {\n out.push(`${i}| ${cutLine(lines[i - 1]!.replace(/\\t/g, \" \"), o.maxLineChars, o.needles)}`);\n }\n return out.join(\"\\n\");\n}\n\n/** Rendered length of one line (as renderLines would produce it, plus the newline). */\nexport function renderedLineLength(lines: string[], i: number, o: RenderOpts): number {\n return renderLines(lines, i, i, o).length + 1;\n}\n\n/**\n * Split a window whose rendered text exceeds maxChars into whole-line sub-windows around its hits:\n * each sub-window starts a few lines above the first uncovered hit (up to a quarter of the budget) and\n * extends down until the budget is used. Windows without hits (headers, definitions) keep their top.\n */\nexport function splitByChars(\n lines: string[],\n w: Window,\n maxChars: number,\n o: RenderOpts,\n ctxUp = 3,\n): Window[] {\n const len = (i: number) => renderedLineLength(lines, i, o);\n let total = 0;\n for (let i = w.start; i <= w.end; i++) total += len(i);\n if (total <= maxChars) return [w];\n const hits = [...w.hits].filter((h) => h >= w.start && h <= w.end).sort((a, b) => a - b);\n const anchors = hits.length ? hits : [w.start];\n const out: Window[] = [];\n let covered = w.start - 1;\n for (const h of anchors) {\n if (h <= covered) continue;\n let s = h;\n let used = len(h);\n while (\n s - 1 >= w.start &&\n s - 1 > covered &&\n h - (s - 1) <= ctxUp &&\n used + len(s - 1) <= maxChars / 4\n )\n used += len(--s);\n let e = h;\n while (e + 1 <= w.end && used + len(e + 1) <= maxChars) used += len(++e);\n out.push({ ...w, start: s, end: e, hits: hits.filter((x) => x >= s && x <= e) });\n covered = e;\n }\n return out;\n}\n\nexport function splitLines(text: string): string[] {\n const lines = text.split(/\\r?\\n/);\n if (lines.length && lines[lines.length - 1] === \"\") lines.pop();\n return lines;\n}\n","/**\n * pack.ts - bounded evidence pack.\n *\n * Priority: (1) for each sub-question, the best passage covering it (coverage >= T2), (2) passages with\n * relevance >= T2 by relevance, (3) if fewer than minPassages passed, the next best above minRelevance,\n * (4) optionally (fillBudget) the rest. Greedy under a char budget (tokens * charsPerToken); a passage that\n * does not fit is trimmed to whole lines around its hits (>= minTrimLines) and marked, never cut mid-line.\n * Output groups passages by file (files by best relevance, passages by line).\n */\nimport type { CodeSearchConfig } from \"./config\";\nimport { isChangelogPath, isDocPath, isTestPath } from \"./text\";\nimport { renderLines, type RenderOpts } from \"./windows\";\n\nexport interface EvidencePassage {\n id: string;\n path: string;\n start: number;\n end: number;\n fileLines: string[];\n hits: number[];\n label?: { line: number; text: string } | undefined;\n kind: \"hit\" | \"header\" | \"def\";\n rel: number;\n cov: number[];\n /** Lexical passage score (used by pack.lexWeight). */\n lex?: number | undefined;\n lead?: string | undefined;\n /** How lines are rendered (line cap + needles for cutting very long lines around a hit). */\n render?: RenderOpts | undefined;\n}\n\nexport interface PackedPassage {\n id: string;\n path: string;\n start: number;\n end: number;\n origStart: number;\n origEnd: number;\n trimmed: boolean;\n rel: number;\n cov: number[];\n kind: EvidencePassage[\"kind\"];\n lead?: string | undefined;\n label?: { line: number; text: string } | undefined;\n /** rendered block including its `==` header line */\n block: string;\n}\n\nexport interface PackOptions {\n subQuestions: string[];\n T2: number;\n /** Chars available for passage blocks (header/footer excluded). */\n bodyChars: number;\n cfg: CodeSearchConfig;\n /** Apply pack.changelogPrior (false when the question is about history / releases). */\n downweightChangelogs?: boolean;\n /** Apply pack.testPrior (false when the question is about tests). */\n downweightTests?: boolean;\n}\n\nexport interface PackBody {\n included: PackedPassage[];\n excluded: EvidencePassage[];\n body: string;\n priority: string[];\n}\n\nconst r2 = (x: number) => (Number.isFinite(x) ? x.toFixed(2) : \"?\");\n\n/**\n * Greedy file-diverse order: repeatedly take the passage with the highest eff(x) - penalty x (passages already\n * taken from its file). penalty 0 = plain descending eff.\n */\nexport function diverseOrder(\n xs: EvidencePassage[],\n eff: (x: EvidencePassage) => number,\n penalty: number,\n taken: Map<string, number>,\n): EvidencePassage[] {\n const tie = (a: EvidencePassage, b: EvidencePassage) =>\n a.path < b.path ? -1 : a.path > b.path ? 1 : a.start - b.start;\n if (penalty <= 0) return [...xs].sort((a, b) => eff(b) - eff(a) || tie(a, b));\n const left = [...xs];\n const out: EvidencePassage[] = [];\n while (left.length) {\n let bi = 0;\n let bv = -Infinity;\n left.forEach((x, i) => {\n const v = eff(x) - penalty * (taken.get(x.path) ?? 0);\n if (v > bv || (v === bv && tie(x, left[bi]!) < 0)) {\n bv = v;\n bi = i;\n }\n });\n const x = left.splice(bi, 1)[0]!;\n taken.set(x.path, (taken.get(x.path) ?? 0) + 1);\n out.push(x);\n }\n return out;\n}\n\n/** Path prior for pack ordering (release notes, prose docs, tests); 1 for code. */\nexport function pathPrior(\n path: string,\n o: Pick<PackOptions, \"cfg\" | \"downweightChangelogs\" | \"downweightTests\">,\n): number {\n const p = o.cfg.pack;\n if (isChangelogPath(path)) return o.downweightChangelogs !== false ? p.changelogPrior : 1;\n if (isTestPath(path)) return o.downweightTests !== false ? p.testPrior : 1;\n if (isDocPath(path)) return p.docPrior;\n return 1;\n}\n\n/** Pack ordering score: (rel + lexWeight x lex) x path prior. Inclusion floors (T2, minRelevance) still use raw rel. */\nexport function packScore(\n x: EvidencePassage,\n o: Pick<PackOptions, \"cfg\" | \"downweightChangelogs\" | \"downweightTests\">,\n): number {\n return (x.rel + o.cfg.pack.lexWeight * (x.lex ?? 0)) * pathPrior(x.path, o);\n}\n\nexport function priorityOrder(\n passages: EvidencePassage[],\n o: Pick<PackOptions, \"subQuestions\" | \"T2\" | \"cfg\" | \"downweightChangelogs\" | \"downweightTests\">,\n): EvidencePassage[] {\n const p = o.cfg.pack;\n const effCache = new Map<EvidencePassage, number>();\n const eff = (x: EvidencePassage) => {\n let v = effCache.get(x);\n if (v === undefined) effCache.set(x, (v = packScore(x, o)));\n return v;\n };\n const byRel = [...passages].sort(\n (a, b) => eff(b) - eff(a) || (a.path < b.path ? -1 : a.path > b.path ? 1 : a.start - b.start),\n );\n const out: EvidencePassage[] = [];\n const taken = new Map<string, number>();\n const add = (x: EvidencePassage) => {\n if (!out.includes(x)) {\n out.push(x);\n taken.set(x.path, (taken.get(x.path) ?? 0) + 1);\n }\n };\n o.subQuestions.forEach((_, j) => {\n const best = [...passages]\n .filter((x) => (x.cov[j] ?? 0) >= o.T2 && x.rel >= p.minRelevance)\n .sort((a, b) => (b.cov[j] ?? 0) - (a.cov[j] ?? 0) || b.rel - a.rel)[0];\n if (best) add(best);\n });\n for (const x of diverseOrder(\n byRel.filter((y) => y.rel >= o.T2 && !out.includes(y)),\n eff,\n p.filePenalty,\n new Map(taken),\n ))\n add(x);\n for (const x of byRel) {\n if (out.length >= p.minPassages) break;\n if (x.rel >= p.minRelevance) add(x);\n }\n if (p.fillBudget)\n for (const x of diverseOrder(\n byRel.filter((y) => y.rel >= p.minRelevance && !out.includes(y)),\n eff,\n p.filePenalty,\n new Map(taken),\n ))\n add(x);\n return out;\n}\n\nfunction blockHeader(x: EvidencePassage, start: number, end: number, o: PackOptions): string {\n const covTags = o.subQuestions\n .map((_, j) => ((x.cov[j] ?? 0) >= o.T2 ? `s${j + 1}` : \"\"))\n .filter(Boolean);\n const parts = [`== ${x.path}:${start}-${end} rel ${r2(x.rel)}`];\n if (covTags.length) parts.push(`[${covTags.join(\" \")}]`);\n if (x.kind === \"def\" && x.lead) parts.push(`(definition of ${x.lead})`);\n if (start !== x.start || end !== x.end) parts.push(`(trimmed from ${x.start}-${x.end})`);\n let h = parts.join(\" \");\n if (x.label && x.label.line < start) h += `\\n in L${x.label.line}: ${x.label.text}`;\n return h;\n}\n\nexport function renderBlock(\n x: EvidencePassage,\n start: number,\n end: number,\n o: PackOptions,\n): string {\n return `${blockHeader(x, start, end, o)}\\n${renderLines(x.fileLines, start, end, x.render ?? o.cfg.wave2.maxLineChars)}`;\n}\n\n/** Largest contiguous whole-line sub-range around the passage's hits whose block fits in maxChars. */\nexport function trimToFit(\n x: EvidencePassage,\n maxChars: number,\n o: PackOptions,\n): { start: number; end: number } | null {\n const lineLen = (i: number) =>\n renderLines(x.fileLines, i, i, x.render ?? o.cfg.wave2.maxLineChars).length + 1;\n const hdr = blockHeader(x, x.start, x.end, o).length + 40; // + \"(trimmed from a-b)\"\n const inside = x.hits.filter((h) => h >= x.start && h <= x.end).sort((a, b) => a - b);\n const center = inside.length ? inside[Math.floor((inside.length - 1) / 2)]! : x.start;\n let s = center;\n let e = center;\n let used = hdr + lineLen(center);\n if (used > maxChars) return null;\n // grow 2 lines down per line up (code after a hit usually matters more), until neither side fits\n let stuckUp = false;\n let stuckDown = false;\n let turn = 0;\n while (!(stuckUp && stuckDown)) {\n const goDown = !stuckDown && (stuckUp || turn % 3 !== 2);\n turn++;\n if (goDown) {\n if (e + 1 > x.end) {\n stuckDown = true;\n continue;\n }\n const c = lineLen(e + 1);\n if (used + c > maxChars) stuckDown = true;\n else {\n e++;\n used += c;\n }\n } else {\n if (s - 1 < x.start) {\n stuckUp = true;\n continue;\n }\n const c = lineLen(s - 1);\n if (used + c > maxChars) stuckUp = true;\n else {\n s--;\n used += c;\n }\n }\n }\n if (e - s + 1 < o.cfg.pack.minTrimLines && e - s + 1 < x.end - x.start + 1) return null;\n return { start: s, end: e };\n}\n\nexport function packBody(passages: EvidencePassage[], o: PackOptions): PackBody {\n const order = priorityOrder(passages, o);\n let remaining = o.bodyChars;\n const included: PackedPassage[] = [];\n for (const x of order) {\n if (remaining < 200) break;\n let s = x.start;\n let e = x.end;\n let block = renderBlock(x, s, e, o);\n const cap = o.cfg.pack.maxPassageChars;\n if (cap > 0 && block.length > cap) {\n const t = trimToFit(x, cap, o);\n if (t) {\n s = t.start;\n e = t.end;\n block = renderBlock(x, s, e, o);\n }\n }\n if (block.length + 2 > remaining) {\n const t = trimToFit({ ...x, start: s, end: e }, remaining - 2, o);\n if (!t) continue;\n s = t.start;\n e = t.end;\n block = renderBlock(x, s, e, o);\n if (block.length + 2 > remaining) continue;\n }\n remaining -= block.length + 2;\n included.push({\n id: x.id,\n path: x.path,\n start: s,\n end: e,\n origStart: x.start,\n origEnd: x.end,\n trimmed: s !== x.start || e !== x.end,\n rel: x.rel,\n cov: x.cov,\n kind: x.kind,\n lead: x.lead,\n label: x.label,\n block,\n });\n }\n const inc = new Set(included.map((p) => p.id));\n const excluded = passages.filter((x) => !inc.has(x.id)).sort((a, b) => b.rel - a.rel);\n // group by file: files by best relevance, passages by line\n const fileBest = new Map<string, number>();\n for (const p of included) fileBest.set(p.path, Math.max(fileBest.get(p.path) ?? 0, p.rel));\n const grouped = [...included].sort(\n (a, b) =>\n fileBest.get(b.path)! - fileBest.get(a.path)! ||\n (a.path < b.path ? -1 : a.path > b.path ? 1 : a.start - b.start),\n );\n return {\n included: grouped,\n excluded,\n body: grouped.map((p) => p.block).join(\"\\n\\n\"),\n priority: order.map((x) => x.id),\n };\n}\n\nexport interface FooterInput {\n excluded: EvidencePassage[];\n otherFiles: Array<{ path: string; score: number }>;\n leadsNotFollowed: Array<{ name: string; score: number; seenAt: string; note?: string }>;\n zeroHitKeywords: Array<{ raw: string; fragments: string[] }>;\n widenedNote?: string;\n cfg: CodeSearchConfig;\n maxChars: number;\n}\n\n/** Footer lines, dropping list entries from the end until it fits maxChars. */\nexport function renderFooter(f: FooterInput): string {\n const p = f.cfg.pack;\n const more: string[] = f.excluded\n .slice(0, p.moreCandidates)\n .map((x) => `${x.path}:${x.start}-${x.end} (${r2(x.rel)})`);\n const moreFiles = f.otherFiles\n .slice(0, Math.max(0, p.moreCandidates - more.length))\n .map((x) => `${x.path} (${r2(x.score)})`);\n const leads = f.leadsNotFollowed\n .slice(0, p.leadsNotFollowed)\n .map((l) => `${l.name} (${r2(l.score)}${l.note ? `, ${l.note}` : \"\"}) @${l.seenAt}`);\n const zero = f.zeroHitKeywords.map((k) =>\n k.fragments.length ? `${k.raw} (matched fragments: ${k.fragments.join(\", \")})` : k.raw,\n );\n const build = (m: string[], mf: string[], l: string[]) => {\n const lines: string[] = [];\n if (m.length || mf.length) {\n lines.push(\"More candidates (not included; read if needed):\");\n if (m.length) lines.push(` ${m.join(\", \")}`);\n if (mf.length) lines.push(` files: ${mf.join(\", \")}`);\n }\n if (l.length) lines.push(`Leads not followed: ${l.join(\", \")}`);\n if (zero.length) lines.push(`Keywords with zero hits: ${zero.join(\", \")}`);\n if (f.widenedNote) lines.push(f.widenedNote);\n return lines.join(\"\\n\");\n };\n let m = more;\n let mf = moreFiles;\n let l = leads;\n let out = build(m, mf, l);\n while (out.length > f.maxChars && (m.length || mf.length || l.length)) {\n if (mf.length) mf = mf.slice(0, -1);\n else if (l.length > 2) l = l.slice(0, -1);\n else if (m.length) m = m.slice(0, -1);\n else l = l.slice(0, -1);\n out = build(m, mf, l);\n }\n return out;\n}\n","/**\n * recall.ts - wide, deterministic lexical recall with ripgrep.\n *\n * One ripgrep pass over the union of every keyword's identifier variants, searched case-insensitively\n * (camelCase <-> snake_case <-> kebab <-> spaced phrase; SCREAMING and Pascal forms are covered by -i);\n * a union longer than CODE_SEARCH_MAX_PATTERN_CHARS is split into several passes and merged. Lines are\n * attributed to keywords in JS. Short plain words get a leading word boundary so `turn` does not\n * match `return`. Per-file score = sum over DISTINCT matched keywords of IDF + path bonus + a small\n * hit-count tie breaker; tests are down-weighted unless the question is about tests.\n */\nimport type { CodeSearchConfig } from \"./config\";\nimport {\n mapLimit,\n READ_CONCURRENCY,\n RIPGREP_SPLIT_CONCURRENCY,\n type WorkspaceSession,\n} from \"./session\";\nimport {\n compoundFragments,\n escapeRegex,\n isChangelogPath,\n isDocPath,\n isShortPlainWord,\n isTestPath,\n keywordVariants,\n questionMentionsHistory,\n questionMentionsTests,\n splitWords,\n} from \"./text\";\nimport { CODE_SEARCH_MAX_PATTERN_CHARS } from \"./workspace\";\n\nexport const BUILTIN_EXCLUDES = [\n \"!**/node_modules/**\",\n \"!**/dist/**\",\n \"!**/build/**\",\n \"!**/.next/**\",\n \"!**/coverage/**\",\n \"!**/target/**\",\n \"!**/vendor/**\",\n \"!**/.git/**\",\n // a linked worktree has a `.git` FILE (gitdir pointer), which --hidden would otherwise search\n \"!**/.git\",\n \"!**/.turbo/**\",\n \"!*.lock\",\n \"!**/package-lock.json\",\n \"!**/pnpm-lock.yaml\",\n \"!**/yarn.lock\",\n \"!**/bun.lockb\",\n \"!*.min.js\",\n \"!*.min.css\",\n \"!*.map\",\n \"!*.snap\",\n \"!**/*.gen.*\",\n \"!**/*.generated.*\",\n \"!**/gen/**\",\n \"!**/*_pb.*\",\n \"!**/*.pb.go\",\n \"!*.{svg,png,jpg,jpeg,gif,ico,webp,woff,woff2,ttf,otf,eot,wasm,pdf,zip,gz,tgz,mp4,mp3,mov}\",\n];\n\nexport interface KeywordInfo {\n index: number;\n raw: string;\n variants: string[];\n /** \"phrase\" = any variant as a substring; \"word-prefix\" = `\\bword`. */\n mode: \"phrase\" | \"word-prefix\";\n /** JS-dialect pattern (attribution, window scoring, line cutting). */\n pattern: string;\n /** ripgrep-dialect pattern: same language, but word boundaries are ASCII `(?-u:\\b)`. */\n rgPattern: string;\n /** Number of files with at least one matching line (content). */\n df: number;\n /** Files whose path matches (no content needed). */\n pathDf: number;\n hitLines: number;\n idf: number;\n /** Fragments used because the full keyword had zero hits. */\n fragments: string[];\n}\n\nexport interface HitLine {\n line: number;\n text: string;\n kws: number[];\n}\n\nexport interface FileCandidate {\n path: string;\n lexScore: number;\n /** keyword index -> matching line count */\n kwHits: Record<number, number>;\n pathKws: number[];\n hitLines: Map<number, HitLine>;\n isTest: boolean;\n isDoc: boolean;\n}\n\nexport interface RecallResult {\n keywords: KeywordInfo[];\n totalFiles: number;\n candidates: FileCandidate[];\n scoredFiles: number;\n searchPaths: string[];\n widened: boolean;\n /** Path prefixes that do not exist in the workspace (or are not workspace-relative); ignored. */\n missingPrefixes: string[];\n /** The path prefixes that exist, workspace-relative. */\n validPrefixes: string[];\n /** Path-only candidates dropped because their content is binary (NUL in the first 8 KB). */\n binaryDropped: number;\n ms: number;\n}\n\nexport interface RecallInput {\n session: WorkspaceSession;\n question: string;\n keywords: string[];\n pathPrefixes: string[];\n config: CodeSearchConfig;\n}\n\nexport function excludeArgs(cfg: CodeSearchConfig): string[] {\n return [\n ...BUILTIN_EXCLUDES,\n ...cfg.recall.extraExcludes.map((g) => (g.startsWith(\"!\") ? g : `!${g}`)),\n ].flatMap((g) => [\"-g\", g]);\n}\n\n/** `--hidden` (rg skips dot-dirs such as .github/ by default); `.git/` stays excluded by BUILTIN_EXCLUDES. */\nexport function hiddenArgs(cfg: CodeSearchConfig): string[] {\n return cfg.recall.searchHidden ? [\"--hidden\"] : [];\n}\n\nexport async function listFiles(\n session: WorkspaceSession,\n paths: string[],\n cfg: CodeSearchConfig,\n): Promise<string[]> {\n // exit 2 without output means nothing could be listed (for example only unreadable directories)\n const out = await session.ripgrep(\n [\n \"--files\",\n \"--no-require-git\",\n ...hiddenArgs(cfg),\n \"--max-filesize\",\n String(cfg.recall.maxFileBytes),\n ...excludeArgs(cfg),\n \"--\",\n ...paths,\n ],\n { allowFailure: true },\n );\n return out\n .split(\"\\n\")\n .filter(Boolean)\n .map((p) => p.replace(/^\\.\\//, \"\"))\n .sort();\n}\n\n/**\n * Search pattern for one keyword. `pattern` is JS-dialect; `rgPattern` is the same for ripgrep except that the\n * word boundary is ASCII: a Unicode `\\b` under -i disables ripgrep's fast engines (measured on repo-snap: 5.6 s\n * user CPU for one pass vs 0.2 s with `(?-u:\\b)`), and JS `\\b` is ASCII anyway.\n */\nexport function buildPattern(\n kw: string,\n cfg: CodeSearchConfig,\n): { pattern: string; rgPattern: string; mode: \"phrase\" | \"word-prefix\"; variants: string[] } {\n const variants = keywordVariants(kw);\n if (variants.length === 1 && isShortPlainWord(variants[0]!, cfg.recall.shortWordMaxLen)) {\n const lit = escapeRegex(variants[0]!);\n return { pattern: `\\\\b${lit}`, rgPattern: `(?-u:\\\\b)${lit}`, mode: \"word-prefix\", variants };\n }\n // spaced-phrase variants match any run of whitespace\n const alts = variants.map((v) => escapeRegex(v).replace(/ /g, \"\\\\s+\"));\n return { pattern: alts.join(\"|\"), rgPattern: alts.join(\"|\"), mode: \"phrase\", variants };\n}\n\n/** Pattern for the 2-word fragments of a compound keyword (used only if the full keyword has zero hits). */\nexport function fragmentPattern(frags: string[]): string {\n return frags\n .flatMap((f) => keywordVariants(f))\n .map((v) => escapeRegex(v).replace(/ /g, \"\\\\s+\"))\n .join(\"|\");\n}\n\nexport interface RgMatch {\n path: string;\n line: number;\n text: string;\n}\n\n/** Parse `rg --null --line-number --with-filename --no-heading` output. Omitted long lines are skipped. */\nexport function parseRgOutput(out: string): RgMatch[] {\n const matches: RgMatch[] = [];\n let pos = 0;\n while (pos < out.length) {\n let nl = out.indexOf(\"\\n\", pos);\n if (nl < 0) nl = out.length;\n const z = out.indexOf(\"\\0\", pos);\n if (z > pos && z < nl) {\n const colon = out.indexOf(\":\", z + 1);\n if (colon > z && colon < nl) {\n const line = Number(out.slice(z + 1, colon));\n const text = out.slice(colon + 1, nl).replace(/\\r$/, \"\");\n if (Number.isFinite(line) && !text.startsWith(\"[Omitted long line\")) {\n matches.push({ path: out.slice(pos, z).replace(/^\\.\\//, \"\"), line, text });\n }\n }\n }\n pos = nl + 1;\n }\n return matches;\n}\n\nconst byPathLine = (a: RgMatch, b: RgMatch) =>\n a.path < b.path ? -1 : a.path > b.path ? 1 : a.line - b.line;\n\n/**\n * Whether a pattern built by this engine compiles: checked as a JS regex after mapping ripgrep's inline flag\n * groups (`(?-u:`, `(?i:`) to plain groups. It tells an invalid pattern apart from ripgrep's exit 2 for an\n * unreadable path.\n */\nexport function ripgrepPatternCompiles(pattern: string): boolean {\n return jsRegex(pattern.replace(/\\(\\?[A-Za-z-]+:/g, \"(?:\")) !== null;\n}\n\n/** One rg pass for a pattern (any number of alternatives), all matching lines, sorted by path then line. */\nexport async function searchPattern(\n session: WorkspaceSession,\n pattern: string,\n paths: string[],\n cfg: CodeSearchConfig,\n opts: { caseInsensitive?: boolean; word?: boolean; maxPerFile?: number } = {},\n): Promise<RgMatch[]> {\n const args = [\n \"--null\",\n \"--line-number\",\n \"--with-filename\",\n \"--no-heading\",\n \"--color\",\n \"never\",\n ...(opts.caseInsensitive === false ? [] : [\"-i\"]),\n ...(opts.word ? [\"-w\"] : []),\n \"--no-require-git\",\n ...hiddenArgs(cfg),\n ...(opts.maxPerFile ? [\"-m\", String(opts.maxPerFile)] : []),\n // very long lines (minified / generated / data) are omitted by rg and skipped by the parser\n \"--max-columns\",\n String(cfg.recall.maxLineColumns),\n \"--max-filesize\",\n String(cfg.recall.maxFileBytes),\n ...excludeArgs(cfg),\n \"-e\",\n pattern,\n \"--\",\n ...paths,\n ];\n // rg also exits 2 without output when nothing matched and some path was unreadable; that is no match\n const out = await session.ripgrep(args, { allowFailure: ripgrepPatternCompiles(pattern) });\n const matches = parseRgOutput(out);\n // rg searches in parallel; sort for determinism (same effect as --sort path, without serializing the search)\n matches.sort(byPathLine);\n return matches;\n}\n\n/** Split a regex at its top-level `|` (outside groups, character classes and escapes). */\nexport function splitAlternation(pattern: string): string[] {\n const out: string[] = [];\n let depth = 0;\n let inClass = false;\n let start = 0;\n for (let i = 0; i < pattern.length; i++) {\n const ch = pattern[i];\n if (ch === \"\\\\\") i++;\n else if (inClass) inClass = ch !== \"]\";\n else if (ch === \"[\") inClass = true;\n else if (ch === \"(\") depth++;\n else if (ch === \")\") depth--;\n else if (ch === \"|\" && depth === 0) {\n out.push(pattern.slice(start, i));\n start = i + 1;\n }\n }\n out.push(pattern.slice(start));\n return out;\n}\n\n/**\n * Join alternatives with `|`, in order, into as few patterns of at most maxChars as possible. An alternative\n * longer than maxChars on its own gets a pattern of its own.\n */\nexport function packAlternatives(alternatives: readonly string[], maxChars: number): string[] {\n const out: string[] = [];\n let cur: string | null = null;\n for (const alt of alternatives) {\n if (cur !== null && cur.length + 1 + alt.length <= maxChars) {\n cur += `|${alt}`;\n } else {\n if (cur !== null) out.push(cur);\n cur = alt;\n }\n }\n if (cur !== null) out.push(cur);\n return out;\n}\n\n/** Matches of several searches, as one search over their union returns them: by path then line, each line once. */\nexport function mergeMatches(lists: readonly RgMatch[][]): RgMatch[] {\n const all = lists.flat().sort(byPathLine);\n return all.filter(\n (m, i) => i === 0 || m.path !== all[i - 1]!.path || m.line !== all[i - 1]!.line,\n );\n}\n\n/**\n * The lines matching `(?:a)|(?:b)|...` over the alternatives. A union longer than maxPatternChars is split\n * into several rg passes (an alternative too long on its own is split at its own top-level `|`), run a few\n * at a time and merged, so the result is the same as one pass. A part that still does not fit (a keyword\n * of thousands of characters) is not searched, so it reports zero hits.\n */\nexport async function searchAlternatives(\n session: WorkspaceSession,\n alternatives: readonly string[],\n paths: string[],\n cfg: CodeSearchConfig,\n maxPatternChars = CODE_SEARCH_MAX_PATTERN_CHARS,\n): Promise<RgMatch[]> {\n const groups = alternatives\n .flatMap((p) =>\n p.length + 4 <= maxPatternChars ? [`(?:${p})`] : splitAlternation(p).map((a) => `(?:${a})`),\n )\n .filter((g) => g.length <= maxPatternChars);\n const patterns = packAlternatives(groups, maxPatternChars);\n if (patterns.length <= 1) {\n return patterns.length ? searchPattern(session, patterns[0]!, paths, cfg) : [];\n }\n const found = await mapLimit(patterns, RIPGREP_SPLIT_CONCURRENCY, (p) =>\n searchPattern(session, p, paths, cfg),\n );\n return mergeMatches(found);\n}\n\nexport function idfOf(df: number, n: number): number {\n return Math.log(1 + n / (1 + df));\n}\n\n/** Does the path mention the keyword (any variant, separators ignored)? */\nexport function pathMatches(path: string, variants: string[]): boolean {\n const flatPath = path.toLowerCase().replace(/[-_ .]/g, \"\");\n return variants.some((v) => {\n const flat = v.toLowerCase().replace(/[-_ ]/g, \"\");\n return flat.length >= 4 && flatPath.includes(flat);\n });\n}\n\n/** JS regex for an rg pattern built by buildPattern/fragmentPattern (the escapes used are valid in both dialects). */\nexport function jsRegex(pattern: string): RegExp | null {\n try {\n return new RegExp(pattern, \"i\");\n } catch {\n return null;\n }\n}\n\nexport interface Slot {\n /** keyword index */\n ki: number;\n fragment: boolean;\n re: RegExp | null;\n literals: string[];\n}\n\n/**\n * Attribute rg lines to keyword slots. Returns per slot the matches (all lines; the caller caps what it stores).\n * A JS regex that fails to compile falls back to a case-insensitive literal test on the variants.\n */\nexport function attribute(matches: RgMatch[], slots: Slot[]): RgMatch[][] {\n const out: RgMatch[][] = slots.map(() => []);\n for (const m of matches) {\n const lower = m.text.toLowerCase();\n slots.forEach((s, i) => {\n const hit = s.re ? s.re.test(m.text) : s.literals.some((l) => lower.includes(l));\n if (hit) out[i]!.push(m);\n });\n }\n return out;\n}\n\n/**\n * Normalize path prefixes to workspace-relative form (\"./src/\" -> \"src\"); prefixes that do not exist, are\n * absolute or climb out with \"..\" are reported as missing instead of crashing ripgrep (exit 2, no output).\n */\nexport async function normalizePrefixes(\n session: WorkspaceSession,\n prefixes: string[],\n): Promise<{ ok: string[]; missing: string[] }> {\n const cleaned = prefixes.map((raw) => ({ raw, rel: cleanPrefix(raw) }));\n const lookup = [\n ...new Set(cleaned.map((c) => c.rel).filter((r): r is string => r !== null && r !== \".\")),\n ];\n const kinds = lookup.length ? await session.pathKinds(lookup) : {};\n const ok: string[] = [];\n const missing: string[] = [];\n for (const { raw, rel } of cleaned) {\n if (rel === \".\") ok.push(\".\");\n else if (rel !== null && (kinds[rel] === \"file\" || kinds[rel] === \"directory\")) ok.push(rel);\n else missing.push(raw);\n }\n return { ok: [...new Set(ok)], missing };\n}\n\n/** Workspace-relative form of a prefix, or null when it is absolute, climbs out, or starts with \"-\". */\nexport function cleanPrefix(p: string): string | null {\n let s = p.trim().replace(/\\\\/g, \"/\");\n if (!s || s.startsWith(\"/\") || s.startsWith(\"~\") || /^[A-Za-z]:\\//.test(s)) return null;\n while (s.startsWith(\"./\")) s = s.slice(2);\n s = s.replace(/\\/+$/, \"\").replace(/\\/{2,}/g, \"/\");\n if (s === \"\" || s === \".\") return \".\";\n if (s.startsWith(\"-\") || s.split(\"/\").some((seg) => seg === \"..\")) return null;\n return s;\n}\n\n/** Binary (NUL in the first 8 KB, ripgrep's own heuristic) or unreadable. */\nasync function looksBinary(\n session: WorkspaceSession,\n path: string,\n bytes = 8192,\n): Promise<boolean> {\n return (await session.readText(path, bytes)) === null;\n}\n\nexport async function recall(input: RecallInput): Promise<RecallResult> {\n const t0 = performance.now();\n const cfg = input.config;\n const session = input.session;\n // any whitespace run (newline, tab) becomes one space: a literal newline is not allowed in an rg pattern\n const kwsRaw = [\n ...new Set(\n input.keywords.map((k) => k.replace(/\\s+/g, \" \").trim()).filter((k) => k.length >= 2),\n ),\n ];\n const prefixes = await normalizePrefixes(session, input.pathPrefixes);\n let searchPaths = prefixes.ok.length ? prefixes.ok : [\".\"];\n // every -p prefix missing: search the whole repository (reported as widened)\n let widened = input.pathPrefixes.length > 0 && prefixes.ok.length === 0;\n\n const keywordsFresh = (): KeywordInfo[] =>\n kwsRaw.map((raw, index) => {\n const { pattern, rgPattern, mode, variants } = buildPattern(raw, cfg);\n return {\n index,\n raw,\n variants,\n mode,\n pattern,\n rgPattern,\n df: 0,\n pathDf: 0,\n hitLines: 0,\n idf: 0,\n fragments: [],\n };\n });\n\n /**\n * ONE rg pass over the union of every keyword pattern (and, speculatively, the 2-word fragments of\n * compound keywords); lines are then attributed to keywords in JS. ~0.2 s on a 6k-file repo versus\n * ~1-2 s for one rg process per keyword. A union over the pattern cap takes a few passes instead.\n */\n const attempt = async (paths: string[]) => {\n const keywords = keywordsFresh();\n const slots: Slot[] = [];\n const fragsOf = new Map<number, { frags: string[]; pattern: string }>();\n for (const k of keywords) {\n slots.push({\n ki: k.index,\n fragment: false,\n re: jsRegex(k.pattern),\n literals: k.variants.map((v) => v.toLowerCase()),\n });\n const frags = cfg.recall.fragmentFallback ? compoundFragments(k.raw) : [];\n if (frags.length) {\n const pattern = fragmentPattern(frags);\n fragsOf.set(k.index, { frags, pattern });\n slots.push({\n ki: k.index,\n fragment: true,\n re: jsRegex(pattern),\n literals: frags.flatMap((f) => keywordVariants(f)).map((v) => v.toLowerCase()),\n });\n }\n }\n const alternatives = [\n ...keywords.map((k) => k.rgPattern),\n ...[...fragsOf.values()].map((f) => f.pattern),\n ];\n const [files, matches] = await Promise.all([\n listFiles(session, paths, cfg),\n searchAlternatives(session, alternatives, paths, cfg),\n ]);\n const bySlot = attribute(matches, slots);\n const results: RgMatch[][] = keywords.map(() => []);\n slots.forEach((s, i) => {\n if (!s.fragment) results[s.ki] = bySlot[i]!;\n });\n // zero-hit compound keywords use their fragments (the model guessed a name that does not exist)\n slots.forEach((s, i) => {\n if (s.fragment && results[s.ki]!.length === 0 && bySlot[i]!.length > 0) {\n results[s.ki] = bySlot[i]!;\n keywords[s.ki]!.fragments = fragsOf.get(s.ki)!.frags;\n }\n });\n return { files, keywords, results };\n };\n\n let { files, keywords, results } = await attempt(searchPaths);\n const countFiles = (rs: RgMatch[][]) => new Set(rs.flat().map((m) => m.path)).size;\n if (prefixes.ok.length && countFiles(results) < cfg.recall.minCandidatesBeforeWiden) {\n searchPaths = [\".\"];\n widened = true;\n ({ files, keywords, results } = await attempt(searchPaths));\n }\n\n const n = Math.max(files.length, 1);\n const byPath = new Map<string, FileCandidate>();\n const get = (path: string) => {\n let c = byPath.get(path);\n if (!c) {\n c = {\n path,\n lexScore: 0,\n kwHits: {},\n pathKws: [],\n hitLines: new Map(),\n isTest: isTestPath(path),\n isDoc: isDocPath(path),\n };\n byPath.set(path, c);\n }\n return c;\n };\n const kwFiles = keywords.map(() => new Set<string>());\n const maxStored = cfg.recall.maxMatchesPerFile;\n results.forEach((matches, ki) => {\n const kw = keywords[ki]!;\n const seen = kwFiles[ki]!;\n for (const m of matches) {\n seen.add(m.path);\n const c = get(m.path);\n const cnt = (c.kwHits[ki] = (c.kwHits[ki] ?? 0) + 1);\n // every matching line counts for scoring; only the first maxMatchesPerFile per keyword are kept as hit lines\n if (cnt > maxStored) continue;\n let h = c.hitLines.get(m.line);\n if (!h) {\n h = { line: m.line, text: m.text, kws: [] };\n c.hitLines.set(m.line, h);\n }\n if (!h.kws.includes(ki)) h.kws.push(ki);\n }\n kw.df = seen.size;\n kw.hitLines = matches.length;\n });\n // path-name matches (also for files without content hits)\n for (const kw of keywords) {\n const variants = kw.fragments.length\n ? kw.fragments.flatMap((f) => keywordVariants(f))\n : kw.variants;\n for (const f of files) {\n if (pathMatches(f, variants)) {\n kw.pathDf++;\n kwFiles[kw.index]!.add(f);\n const c = get(f);\n if (!c.pathKws.includes(kw.index)) c.pathKws.push(kw.index);\n }\n }\n }\n // IDF over files matching by content OR path\n for (const kw of keywords)\n kw.idf = kwFiles[kw.index]!.size > 0 ? idfOf(kwFiles[kw.index]!.size, n) : 0;\n\n const testsOk = questionMentionsTests(input.question);\n const historyOk = questionMentionsHistory(input.question);\n for (const c of byPath.values()) {\n let s = 0;\n let lines = 0;\n for (const [ki, cnt] of Object.entries(c.kwHits)) {\n s += keywords[Number(ki)]!.idf;\n lines += cnt;\n }\n for (const ki of c.pathKws) s += cfg.recall.pathBonus * keywords[ki]!.idf;\n s += cfg.recall.hitCountWeight * Math.log(1 + lines);\n if (c.isTest && !testsOk) s *= cfg.recall.testWeight;\n if (!historyOk && isChangelogPath(c.path)) s *= cfg.recall.changelogWeight;\n c.lexScore = s;\n }\n const scored = [...byPath.values()].filter((c) => c.lexScore > 0);\n scored.sort((a, b) => b.lexScore - a.lexScore || (a.path < b.path ? -1 : 1));\n // `rg --files` lists binary files too; one that matches only by path (no content hit) would be windowed as text.\n // Same result as a sequential scan: each batch holds at most the number of slots still open.\n const candidates: FileCandidate[] = [];\n let binaryDropped = 0;\n let next = 0;\n while (next < scored.length && candidates.length < cfg.recall.maxCandidates) {\n const batch = scored.slice(next, next + cfg.recall.maxCandidates - candidates.length);\n next += batch.length;\n const pathOnly = batch.filter((c) => c.hitLines.size === 0);\n const binary = new Set<FileCandidate>();\n const flags = await mapLimit(pathOnly, READ_CONCURRENCY, (c) => looksBinary(session, c.path));\n pathOnly.forEach((c, i) => {\n if (flags[i]) binary.add(c);\n });\n for (const c of batch) {\n if (binary.has(c)) binaryDropped++;\n else candidates.push(c);\n }\n }\n return {\n keywords,\n totalFiles: files.length,\n candidates,\n scoredFiles: scored.length,\n searchPaths,\n widened,\n missingPrefixes: prefixes.missing,\n validPrefixes: prefixes.ok,\n binaryDropped,\n ms: Math.round(performance.now() - t0),\n };\n}\n\n/** Weight of one hit line: sum of IDF of the distinct keywords on it. */\nexport function lineWeight(h: HitLine, keywords: KeywordInfo[]): number {\n return h.kws.reduce((s, k) => s + (keywords[k]?.idf ?? 0), 0);\n}\n\n/** Up to n best hit lines of a file (by distinct-keyword IDF), returned in line order (long lines are trimmed by the caller). */\nexport function bestHitLines(c: FileCandidate, keywords: KeywordInfo[], n: number): HitLine[] {\n return [...c.hitLines.values()]\n .sort((a, b) => lineWeight(b, keywords) - lineWeight(a, keywords) || a.line - b.line)\n .slice(0, n)\n .sort((a, b) => a.line - b.line);\n}\n\n/** Words of all keywords (for overlap scoring). */\nexport function keywordWords(keywords: KeywordInfo[]): Set<string> {\n return new Set(keywords.flatMap((k) => splitWords(k.raw)));\n}\n","/**\n * search.ts - the code_search pipeline (scout-0.3.1 with the Jev judge):\n *\n * 1. recall (ripgrep) -> top maxCandidates files by distinct-keyword IDF\n * 2. wave 1 (file triage, 1 Noul per file) -> up to maxFiles files (+ lexical guard)\n * 3. wave 2 (passage verification) -> relevance + per-sub-question coverage per passage\n * 4. wave 3 (leads, exactly one round) -> <= maxLeadsFollowed definitions, verified like wave 2\n * 5. pack (bounded, verbatim, line-numbered) + status (1 request over the packed evidence)\n *\n * Every file and process access goes through the injected CodeSearchWorkspace. A Jev failure fails the\n * search (JevUnavailableError / JevRequestError propagate); only a failed final status check keeps the\n * fully Jev-scored pack and reports the status as unknown.\n */\nimport { JevRequestError, JevUnavailableError, type JevClient } from \"../client\";\nimport { DEFAULT_CODE_SEARCH_CONFIG, type CodeSearchConfig } from \"./config\";\nimport {\n JevJudge,\n type FileItem,\n type JudgeContext,\n type LeadItem,\n type PassageItem,\n} from \"./judge\";\nimport { chooseDefinitions, extractLeads, locateDefinitions, type LeadCandidate } from \"./leads\";\nimport { packBody, renderFooter, type EvidencePassage } from \"./pack\";\nimport {\n bestHitLines,\n excludeArgs,\n idfOf,\n recall,\n type FileCandidate,\n type KeywordInfo,\n type RecallResult,\n} from \"./recall\";\nimport { mapLimit, READ_CONCURRENCY, WorkspaceSession } from \"./session\";\nimport {\n contentTerms,\n escapeRegex,\n estTokens,\n fmtK,\n isDocPath,\n keywordVariants,\n overlap,\n questionMentionsHistory,\n questionMentionsTests,\n splitWords,\n STOPWORDS,\n trimAround,\n} from \"./text\";\nimport {\n buildFileWindows,\n definitionWindow,\n keywordRegex,\n keywordsInRange,\n langOf,\n renderLines,\n splitLines,\n type RenderOpts,\n type Window,\n} from \"./windows\";\nimport type { CodeSearchWorkspace } from \"./workspace\";\n\n/** The validated research version this engine ports (ranking, thresholds and defaults are unchanged). */\nexport const CODE_SEARCH_ENGINE_VERSION = \"scout-0.3.1\";\nexport const CODE_SEARCH_DEFAULT_BUDGET_TOKENS = 12_000;\n\nexport interface CodeSearchInput {\n question: string;\n keywords: string[];\n subQuestions?: string[] | undefined;\n /** Workspace-relative path prefixes to search; default the whole workspace. */\n paths?: string[] | undefined;\n workspace: CodeSearchWorkspace;\n jev: JevClient;\n signal?: AbortSignal | undefined;\n /** Max pack size in tokens (default 12000). */\n budgetTokens?: number | undefined;\n /** Tuning and tests only; defaults to DEFAULT_CODE_SEARCH_CONFIG. */\n config?: CodeSearchConfig | undefined;\n /** In-memory stage trace (recall, wave1, wave2, leads, pack, summary, and one \"jev\" event per Jev request). */\n onStage?: ((stage: string, data: Record<string, unknown>) => void) | undefined;\n}\n\nexport interface CodeSearchStatus {\n label: \"sufficient\" | \"partial\" | \"insufficient\" | \"unknown\";\n overall: number | null;\n subs: Array<number | null>;\n /** Set when the final Jev sufficiency check failed (the pack itself is fully Jev-scored). */\n error?: string;\n}\n\nexport interface CodeSearchStats {\n wallMs: number;\n stageMs: Record<string, number>;\n candidates: number;\n filesSelected: number;\n passagesVerified: number;\n passagesIncluded: number;\n packChars: number;\n packTokensEst: number;\n workspaceCalls: number;\n /** A ripgrep call returned partial output (byte cap or time limit); the pack header says so. */\n ripgrepTruncated: boolean;\n jev: { requests: number; inputTokens: number; costUsd: number; model: string | null };\n}\n\nexport interface CodeSearchResult {\n version: string;\n /** The rendered pack: a status header line, verbatim line-numbered passages, then the footer. */\n text: string;\n status: CodeSearchStatus;\n stats: CodeSearchStats;\n /** The error of a failed final status check, for a circuit breaker (the search itself succeeded). */\n statusCheckError?: JevUnavailableError | JevRequestError;\n}\n\nconst r2 = (x: number | null | undefined) =>\n x === null || x === undefined || !Number.isFinite(x) ? \"?\" : x.toFixed(2);\n\n/** Lexical passage relevance in [0,1]: keyword IDF mass present, question-term overlap, file prior. */\nexport function lexicalPassageScore(\n text: string,\n kwPresent: number[],\n keywords: KeywordInfo[],\n qTerms: string[],\n fileNorm: number,\n): number {\n const total = keywords.reduce((s, k) => s + k.idf, 0) || 1;\n const mass = kwPresent.reduce((s, k) => s + keywords[k]!.idf, 0) / total;\n const qov = overlap(qTerms, new Set(contentTerms(text)));\n return Math.max(0, Math.min(1, 0.55 * mass + 0.3 * qov + 0.15 * fileNorm));\n}\n\nexport function selectFiles(\n cands: FileCandidate[],\n scores: Map<string, number>,\n ids: string[],\n T1: number,\n cfg: CodeSearchConfig,\n): { selected: number[]; ranked: number[] } {\n // cands are in lexical order; ids[i] is the judge id of cands[i]\n const ranked = cands\n .map((_, i) => i)\n .sort(\n (a, b) =>\n (scores.get(ids[b]!) ?? 0) - (scores.get(ids[a]!) ?? 0) ||\n cands[b]!.lexScore - cands[a]!.lexScore ||\n a - b,\n );\n const selected: number[] = [];\n for (let i = 0; i < Math.min(cfg.wave1.lexicalGuard, cands.length); i++) selected.push(i);\n ranked.forEach((i, rank) => {\n if (selected.length >= cfg.wave1.maxFiles || selected.includes(i)) return;\n if ((scores.get(ids[i]!) ?? 0) >= T1 || rank < cfg.wave1.minFiles) selected.push(i);\n });\n // priority order for windowing = judge rank order\n selected.sort((a, b) => ranked.indexOf(a) - ranked.indexOf(b));\n return { selected, ranked };\n}\n\n/** Round-robin across files (priority order), each file's windows by score, up to max. */\nexport function capPassages<T extends { score: number }>(perFile: T[][], max: number): T[][] {\n const sorted = perFile.map((ws) => [...ws].sort((a, b) => b.score - a.score));\n const out: T[][] = perFile.map(() => []);\n let taken = 0;\n for (let pass = 0; taken < max; pass++) {\n let any = false;\n for (let f = 0; f < sorted.length && taken < max; f++) {\n const w = sorted[f]![pass];\n if (w) {\n out[f]!.push(w);\n taken++;\n any = true;\n }\n }\n if (!any) break;\n }\n return out;\n}\n\n/** Evidence text for the status check: included passages, best first, up to maxChars (whole blocks only). */\nexport function statusEvidence(\n included: Array<{ block: string; rel: number }>,\n maxChars: number,\n): string {\n const out: string[] = [];\n let used = 0;\n for (const p of [...included].sort((a, b) => b.rel - a.rel)) {\n if (used + p.block.length + 2 > maxChars) continue;\n out.push(p.block);\n used += p.block.length + 2;\n }\n return out.join(\"\\n\\n\");\n}\n\nexport function statusLabel(\n s: { overall: number; subs: number[] } | null,\n cfg: CodeSearchConfig,\n): CodeSearchStatus {\n if (!s || !Number.isFinite(s.overall)) return { label: \"unknown\", overall: null, subs: [] };\n const { hi, lo } = cfg.status;\n const subsOk = s.subs.every((x) => x >= hi);\n const anySub = s.subs.some((x) => x >= hi);\n const label =\n s.overall >= hi && subsOk\n ? \"sufficient\"\n : s.overall >= lo || anySub\n ? \"partial\"\n : \"insufficient\";\n return { label, overall: s.overall, subs: s.subs };\n}\n\n/** Footer note about paths that were missing, or a search that had to widen to the whole workspace. */\nexport function prefixNote(\n rec: Pick<RecallResult, \"missingPrefixes\" | \"widened\" | \"validPrefixes\">,\n): string | undefined {\n const notes: string[] = [];\n if (rec.missingPrefixes.length) {\n notes.push(\n `Note: paths not found in the workspace (ignored): ${rec.missingPrefixes.join(\", \")}.`,\n );\n }\n if (rec.widened) {\n notes.push(\n !rec.validPrefixes.length\n ? \"Note: the whole workspace was searched.\"\n : \"Note: nothing matched under the given paths; the whole workspace was searched.\",\n );\n }\n return notes.length ? notes.join(\" \") : undefined;\n}\n\n/** Header label for partial ripgrep output, in the same position scout used for its other partial states. */\nfunction partialLabel(session: WorkspaceSession): string {\n if (!session.partial) return \"\";\n const why = session.timedOut\n ? \"a ripgrep search hit its time limit\"\n : \"ripgrep output was cut at its size limit\";\n return `(partial search: ${why}; some matches may be missing)`;\n}\n\nexport async function runCodeSearch(input: CodeSearchInput): Promise<CodeSearchResult> {\n const outer = input.signal;\n outer?.throwIfAborted();\n // One controller per search: an error in one parallel branch cancels the others.\n const controller = new AbortController();\n const onOuterAbort = () => controller.abort(outer?.reason);\n outer?.addEventListener(\"abort\", onOuterAbort, { once: true });\n try {\n return await pipeline(input, controller.signal);\n } catch (error) {\n controller.abort(error);\n if (outer?.aborted) throw outer.reason;\n throw error;\n } finally {\n outer?.removeEventListener(\"abort\", onOuterAbort);\n }\n}\n\nasync function pipeline(o: CodeSearchInput, signal: AbortSignal): Promise<CodeSearchResult> {\n const cfg = o.config ?? DEFAULT_CODE_SEARCH_CONFIG;\n const t0 = performance.now();\n const stageMs: Record<string, number> = {};\n const mark = (stage: string, since: number) => {\n stageMs[stage] = Math.round(performance.now() - since);\n };\n const emit = (stage: string, data: Record<string, unknown>) => {\n try {\n o.onStage?.(stage, data);\n } catch {\n // tracing never breaks a search\n }\n };\n const session = new WorkspaceSession(o.workspace, signal, cfg.recall.ripgrepTimeoutMs);\n const judge = new JevJudge({ client: o.jev, config: cfg, signal, onEvent: emit });\n const subQuestions = (o.subQuestions ?? [])\n .map((s) => s.trim())\n .filter(Boolean)\n .slice(0, 4);\n const ctx: JudgeContext = { question: o.question.trim(), subQuestions };\n const budgetTokens = o.budgetTokens ?? CODE_SEARCH_DEFAULT_BUDGET_TOKENS;\n const thr = cfg.thresholds;\n emit(\"start\", {\n version: CODE_SEARCH_ENGINE_VERSION,\n question: ctx.question,\n subQuestions,\n keywords: o.keywords,\n paths: o.paths ?? [],\n budgetTokens,\n });\n // open keep-alive connections while recall runs\n o.jev.warmUp(cfg.jev.warmConnections);\n\n // ---- 1. recall\n let ts = performance.now();\n const rec: RecallResult = await recall({\n session,\n question: ctx.question + \" \" + subQuestions.join(\" \"),\n keywords: o.keywords,\n pathPrefixes: o.paths ?? [],\n config: cfg,\n });\n mark(\"recall\", ts);\n const kws = rec.keywords;\n emit(\"recall\", {\n ms: rec.ms,\n totalFiles: rec.totalFiles,\n scoredFiles: rec.scoredFiles,\n searchPaths: rec.searchPaths,\n widened: rec.widened,\n missingPrefixes: rec.missingPrefixes,\n binaryDropped: rec.binaryDropped,\n partial: session.partial,\n keywords: kws.map((k) => ({\n raw: k.raw,\n mode: k.mode,\n pattern: k.pattern,\n df: k.df,\n pathDf: k.pathDf,\n hitLines: k.hitLines,\n idf: round(k.idf),\n fragments: k.fragments,\n })),\n candidates: rec.candidates.map((c) => ({\n path: c.path,\n lex: round(c.lexScore),\n kws: Object.keys(c.kwHits).map(Number),\n pathKws: c.pathKws,\n lines: c.hitLines.size,\n test: c.isTest,\n })),\n });\n\n // ---- 2. wave 1: file triage\n ts = performance.now();\n const maxLex = rec.candidates[0]?.lexScore || 1;\n const fileIds = rec.candidates.map((_, i) => `f${String(i).padStart(3, \"0\")}`);\n const fileItems: FileItem[] = rec.candidates.map((c, i) => {\n const hits = bestHitLines(c, kws, cfg.wave1.hitLinesPerFile);\n const needles = Object.keys(c.kwHits).flatMap((k) => kws[Number(k)]!.variants);\n const lines = hits.map(\n (h) => ` ${h.line}: ${trimAround(h.text, needles, cfg.wave1.hitLineChars)}`,\n );\n return {\n id: fileIds[i]!,\n path: c.path,\n descriptor: [c.path, ...lines].join(\"\\n\"),\n lex: c.lexScore / maxLex,\n };\n });\n const fileScores = await judge.scoreFiles(fileItems, ctx);\n const { selected, ranked } = selectFiles(rec.candidates, fileScores, fileIds, thr.T1, cfg);\n mark(\"wave1\", ts);\n emit(\"wave1\", {\n T1: thr.T1,\n scores: rec.candidates.map((c, i) => ({\n path: c.path,\n p: round(fileScores.get(fileIds[i]!) ?? Number.NaN),\n lex: round(fileItems[i]!.lex),\n })),\n selected: selected.map((i) => rec.candidates[i]!.path),\n });\n\n // ---- 3. wave 2: windows + verification\n ts = performance.now();\n // file contents are read in parallel up front; the windowing below is synchronous\n const fileLines = new Map<string, string[]>();\n const loadLines = async (paths: string[]) => {\n const missing = [...new Set(paths)].filter((p) => !fileLines.has(p));\n const texts = await mapLimit(missing, READ_CONCURRENCY, (p) =>\n session.readText(p, cfg.recall.maxFileBytes),\n );\n missing.forEach((p, i) => {\n const text = texts[i];\n // binary content (NUL bytes) is never rendered as a passage\n fileLines.set(p, text === null || text === undefined ? [] : splitLines(text));\n });\n };\n const readLines = (path: string): string[] => fileLines.get(path) ?? [];\n await loadLines(selected.map((i) => rec.candidates[i]!.path));\n const kwNeedles = kws\n .filter((k) => k.idf > 0)\n .map((k) => keywordRegex(k))\n .filter((re): re is RegExp => re !== null);\n const renderFor = (path: string, needles: RegExp[] = kwNeedles): RenderOpts => ({\n maxLineChars: isDocPath(path) ? cfg.wave2.maxProseLineChars : cfg.wave2.maxLineChars,\n needles,\n });\n const perFileWindows: Window[][] = selected.map((i) => {\n const c = rec.candidates[i]!;\n const lines = readLines(c.path);\n const hits = [...c.hitLines.values()];\n return buildFileWindows(lines, hits, kws, langOf(c.path), cfg, renderFor(c.path));\n });\n const capped = capPassages(perFileWindows, cfg.wave2.maxPassages);\n const qTerms = contentTerms(ctx.question);\n const subTerms = subQuestions.map((s) => contentTerms(s));\n const evidence: EvidencePassage[] = [];\n const passageItems: PassageItem[] = [];\n let pid = 0;\n const makePassage = (path: string, w: Window, fileNorm: number, lead?: string) => {\n const lines = readLines(path);\n const render = renderFor(path, lead ? [new RegExp(`\\\\b${escapeRegex(lead)}\\\\b`)] : kwNeedles);\n const text = renderLines(lines, w.start, w.end, render);\n const raw = lines.slice(w.start - 1, w.end).join(\"\\n\");\n const present = keywordsInRange(lines, w.start, w.end, kws);\n const rawTerms = new Set(contentTerms(raw));\n const id = `p${String(pid++).padStart(3, \"0\")}`;\n const lex = lexicalPassageScore(raw, present, kws, qTerms, fileNorm);\n const lexCov = subTerms.map((t) => overlap(t, rawTerms));\n const label =\n w.label && w.label.line < w.start ? `L${w.label.line}: ${w.label.text}` : undefined;\n passageItems.push({ id, path, start: w.start, end: w.end, text, label, lex, lexCov });\n evidence.push({\n id,\n path,\n start: w.start,\n end: w.end,\n fileLines: lines,\n hits: w.hits,\n label: w.label,\n kind: w.kind,\n rel: lex,\n cov: lexCov,\n lex,\n lead,\n render,\n });\n };\n selected.forEach((ci, f) => {\n const c = rec.candidates[ci]!;\n for (const w of [...capped[f]!].sort((a, b) => a.start - b.start))\n makePassage(c.path, w, c.lexScore / maxLex);\n });\n const wave2Scores = await judge.scorePassages(passageItems, ctx, \"wave2\");\n for (const e of evidence) {\n const s = wave2Scores.get(e.id);\n if (s) {\n e.rel = s.rel;\n e.cov = s.cov;\n }\n }\n mark(\"wave2\", ts);\n emit(\"wave2\", {\n T2: thr.T2,\n passages: evidence.map((e) => ({\n id: e.id,\n path: e.path,\n start: e.start,\n end: e.end,\n kind: e.kind,\n hits: e.hits.length,\n rel: round(e.rel),\n cov: e.cov.map(round),\n lex: round(e.lex ?? Number.NaN),\n })),\n });\n\n // ---- 4. wave 3: leads (exactly one round)\n ts = performance.now();\n let leadCands: LeadCandidate[] = [];\n let leadScores = new Map<string, number>();\n const chosenNames = new Set<string>();\n if (cfg.wave3.enabled) {\n const leadsFollowed: Array<{ name: string; score: number; def: string | null }> = [];\n const seeds = evidence\n .filter((e) => e.rel >= thr.T2)\n .sort((a, b) => b.rel - a.rel)\n .slice(0, cfg.wave3.seedPassages)\n .map((e) => ({\n path: e.path,\n start: e.start,\n lines: e.fileLines.slice(e.start - 1, e.end),\n rel: e.rel,\n }));\n const searched = new Set<string>();\n for (const k of kws) {\n for (const v of [...k.variants, ...k.fragments.flatMap((f) => keywordVariants(f))]) {\n searched.add(v.toLowerCase());\n searched.add(splitWords(v).join(\" \"));\n }\n }\n const qWords = new Set(\n [\n ...splitWords(ctx.question + \" \" + subQuestions.join(\" \")),\n ...kws.flatMap((k) => splitWords(k.raw)),\n ].filter((w) => w.length >= 3 && !STOPWORDS.has(w)),\n );\n // extract generously, keep only leads whose definition exists and is not already in the evidence\n const extracted = extractLeads(\n seeds,\n searched,\n qWords,\n Math.ceil(cfg.wave3.maxLeadCandidates * 1.5),\n );\n const selectedPaths = new Set(selected.map((i) => rec.candidates[i]!.path));\n const allowTests = questionMentionsTests(ctx.question);\n const defSearch = await locateDefinitions(\n session,\n extracted.map((l) => l.name),\n cfg,\n excludeArgs(cfg),\n 12,\n allowTests,\n );\n const seenAt = new Map(extracted.map((l) => [l.name, l.seenAt.path]));\n const defs = chooseDefinitions(\n defSearch.hits,\n selectedPaths,\n cfg.wave3.defsPerLead,\n allowTests,\n seenAt,\n );\n const inEvidence = (path: string, line: number) =>\n evidence.some((e) => e.path === path && line >= e.start && line <= e.end);\n const leadDrops: Record<string, string> = {};\n // genericity penalty: a name defined/used as a key in many files (sessionId, workspaceId, isRecord) is rarely\n // what the answer hinges on\n const nFiles = Math.max(rec.totalFiles, 1);\n const genericity = (name: string) =>\n idfOf(defSearch.fileCounts.get(name) ?? 0, nFiles) / idfOf(0, nFiles);\n leadCands = extracted\n .filter((l) => {\n const ds = defs.get(l.name) ?? [];\n if (!ds.length) leadDrops[l.name] = \"no definition found\";\n else if (ds.every((d) => inEvidence(d.path, d.line)))\n leadDrops[l.name] = \"definition already in evidence\";\n return ds.length > 0 && !ds.every((d) => inEvidence(d.path, d.line));\n })\n .map((l) => ({ ...l, weight: Math.round(l.weight * genericity(l.name) * 1000) / 1000 }))\n .sort((a, b) => b.weight - a.weight || (a.name < b.name ? -1 : 1))\n .slice(0, cfg.wave3.maxLeadCandidates);\n const maxW = Math.max(...leadCands.map((l) => l.weight), 1e-9);\n const leadItems: LeadItem[] = leadCands.map((l, i) => ({\n id: `l${String(i).padStart(3, \"0\")}`,\n name: l.name,\n seenAt: `${l.seenAt.path}:${l.seenAt.line}`,\n context: l.context,\n lex: l.weight / maxW,\n }));\n leadScores = await judge.scoreLeads(leadItems, ctx);\n const chosen = leadItems\n .map((l) => ({ l, p: leadScores.get(l.id) ?? 0 }))\n .filter((x) => x.p >= thr.T3)\n .sort((a, b) => b.p - a.p || (a.l.id < b.l.id ? -1 : 1))\n .slice(0, cfg.wave3.maxLeadsFollowed);\n for (const x of chosen) chosenNames.add(x.l.name);\n await loadLines(chosen.flatMap((x) => (defs.get(x.l.name) ?? []).map((d) => d.path)));\n const defItemsStart = passageItems.length;\n for (const x of chosen) {\n for (const d of defs.get(x.l.name) ?? []) {\n const lines = readLines(d.path);\n // the file could not be read as text (missing, binary, UTF-16) or changed after ripgrep saw it\n if (d.line > lines.length) {\n leadsFollowed.push({\n name: x.l.name,\n score: x.p,\n def: `${d.path}:${d.line} (not in the file as read)`,\n });\n continue;\n }\n const w = definitionWindow(\n lines,\n d.line,\n langOf(d.path),\n cfg,\n renderFor(d.path, [new RegExp(`\\\\b${escapeRegex(x.l.name)}\\\\b`)]),\n );\n const overlapsExisting = evidence.some(\n (e) => e.path === d.path && !(w.end < e.start || w.start > e.end),\n );\n leadsFollowed.push({\n name: x.l.name,\n score: x.p,\n def: `${d.path}:${d.line}${overlapsExisting ? \" (overlaps evidence)\" : \"\"}`,\n });\n if (overlapsExisting) continue;\n makePassage(d.path, w, 0, x.l.name);\n }\n }\n const defItems = passageItems.slice(defItemsStart);\n if (defItems.length) {\n const defScores = await judge.scorePassages(defItems, ctx, \"lead_defs\");\n for (const e of evidence) {\n const s = defScores.get(e.id);\n if (s) {\n e.rel = s.rel;\n e.cov = s.cov;\n }\n }\n }\n emit(\"leads\", {\n T3: thr.T3,\n seeds: seeds.map((s) => `${s.path}:${s.start}`),\n candidates: leadItems.map((l) => ({\n id: l.id,\n name: l.name,\n seenAt: l.seenAt,\n lex: round(l.lex),\n p: round(leadScores.get(l.id) ?? Number.NaN),\n })),\n followed: leadsFollowed,\n defsFound: defSearch.hits.length,\n defSearchMs: defSearch.ms,\n extracted: extracted.length,\n dropped: leadDrops,\n defPassages: evidence\n .filter((e) => e.kind === \"def\")\n .map((e) => ({\n id: e.id,\n path: e.path,\n start: e.start,\n end: e.end,\n lead: e.lead,\n rel: round(e.rel),\n })),\n });\n }\n mark(\"wave3\", ts);\n\n // ---- 5. pack + status\n ts = performance.now();\n const cpt = cfg.pack.charsPerToken;\n const totalChars = Math.floor(budgetTokens * cpt);\n const headerReserve = 420 + subQuestions.reduce((s, q) => s + q.length + 8, 0);\n const footerReserve = Math.min(1800, Math.floor(totalChars * 0.12));\n const body = packBody(evidence, {\n subQuestions,\n T2: thr.T2,\n bodyChars: Math.max(0, totalChars - headerReserve - footerReserve),\n cfg,\n downweightChangelogs: !questionMentionsHistory(ctx.question + \" \" + subQuestions.join(\" \")),\n downweightTests: !questionMentionsTests(ctx.question),\n });\n const includedFiles = new Set(body.included.map((p) => p.path));\n const windowedFiles = new Set(evidence.map((e) => e.path));\n const otherFiles = ranked\n .filter((i) => !windowedFiles.has(rec.candidates[i]!.path))\n .map((i) => ({ path: rec.candidates[i]!.path, score: fileScores.get(fileIds[i]!) ?? 0 }))\n .filter((x) => x.score > 0);\n const leadIdByName = new Map(leadCands.map((l, i) => [l.name, `l${String(i).padStart(3, \"0\")}`]));\n const notFollowed = leadCands\n .filter((l) => !chosenNames.has(l.name))\n .map((l) => ({\n name: l.name,\n score: leadScores.get(leadIdByName.get(l.name)!) ?? 0,\n seenAt: `${l.seenAt.path}:${l.seenAt.line}`,\n }))\n .sort((a, b) => b.score - a.score);\n const zero = kws.filter((k) => k.df === 0 && k.pathDf === 0);\n const fragmentOnly = kws.filter((k) => k.fragments.length > 0 && (k.df > 0 || k.pathDf > 0));\n const zeroHitKeywords = [\n ...zero.map((k) => ({ raw: k.raw, fragments: [] as string[] })),\n ...fragmentOnly.map((k) => ({ raw: k.raw, fragments: k.fragments })),\n ];\n const widenedNote = prefixNote(rec);\n const footer = renderFooter({\n excluded: body.excluded,\n otherFiles,\n leadsNotFollowed: notFollowed,\n zeroHitKeywords,\n ...(widenedNote ? { widenedNote } : {}),\n cfg,\n maxChars: footerReserve,\n });\n mark(\"pack\", ts);\n\n // A failure of the status request alone (after the pack) keeps the Jev pack with status unknown.\n ts = performance.now();\n let status: CodeSearchStatus = { label: \"unknown\", overall: null, subs: [] };\n let statusCheckError: JevUnavailableError | JevRequestError | undefined;\n let statusEvidenceChars = 0;\n if (cfg.status.enabled && body.included.length) {\n const ev = statusEvidence(body.included, cfg.status.maxEvidenceChars);\n statusEvidenceChars = ev.length;\n try {\n status = statusLabel(await judge.status(ev, ctx), cfg);\n } catch (error) {\n if (\n signal.aborted ||\n !(error instanceof JevUnavailableError || error instanceof JevRequestError)\n )\n throw error;\n statusCheckError = error;\n status = { label: \"unknown\", overall: null, subs: [], error: error.message.slice(0, 200) };\n }\n } else if (!body.included.length) {\n status = { label: \"insufficient\", overall: null, subs: [] };\n }\n mark(\"status\", ts);\n emit(\"pack\", {\n T2: thr.T2,\n budgetTokens,\n totalChars,\n priority: body.priority,\n included: body.included.map((p) => ({\n id: p.id,\n path: p.path,\n start: p.start,\n end: p.end,\n trimmed: p.trimmed,\n rel: round(p.rel),\n cov: p.cov.map(round),\n chars: p.block.length,\n })),\n excluded: body.excluded.map((e) => ({\n id: e.id,\n path: e.path,\n start: e.start,\n end: e.end,\n rel: round(e.rel),\n })),\n status,\n statusEvidenceChars,\n });\n\n // ---- render\n const jevTotals = Object.values(judge.stats()).reduce(\n (a, s) => ({\n requests: a.requests + s.requests,\n inputTokens: a.inputTokens + s.inputTokens,\n costUsd: a.costUsd + s.costUsd,\n }),\n { requests: 0, inputTokens: 0, costUsd: 0 },\n );\n const wallMs = Math.round(performance.now() - t0);\n const label = partialLabel(session);\n // A number, not a verdict: \"sufficient\" read as permission to stop, but the\n // check only sees the passages the search returned.\n const statusText =\n status.label === \"unknown\" || status.overall === null\n ? status.error\n ? \"evidence rating unknown (check failed)\"\n : \"evidence rating unknown (no check)\"\n : `evidence rating ${r2(status.overall)}` +\n (status.subs.length\n ? ` (${status.subs.map((x, j) => `s${j + 1} ${r2(x)}`).join(\", \")})`\n : \"\");\n const buildText = (packTok: number) => {\n const head = [\n `code_search${label ? \" \" + label : \"\"}: ${statusText} | ${body.included.length} passages from ${includedFiles.size} files, ~${fmtK(packTok)} tokens | ${(wallMs / 1000).toFixed(1)}s`,\n ];\n if (subQuestions.length) head.push(subQuestions.map((s, j) => `s${j + 1}: ${s}`).join(\"\\n\"));\n head.push(\n body.included.length\n ? \"Passages are verbatim with original line numbers (N| text), grouped by file, best first; rel = relevance, [sN] = covers sub-question N. The rating covers only these passages; it cannot see other entry points, defaults, flags or exceptions the search did not return.\"\n : \"No passage passed verification. Try other keywords (exact identifiers, config keys, error strings) or read the candidates below.\",\n );\n return [head.join(\"\\n\"), body.body, footer].filter(Boolean).join(\"\\n\\n\") + \"\\n\";\n };\n let text = buildText(0);\n text = buildText(estTokens(text.length, cpt));\n const stats: CodeSearchStats = {\n wallMs,\n stageMs,\n candidates: rec.candidates.length,\n filesSelected: selected.length,\n passagesVerified: evidence.length,\n passagesIncluded: body.included.length,\n packChars: text.length,\n packTokensEst: estTokens(text.length, cpt),\n workspaceCalls: session.calls,\n ripgrepTruncated: session.partial,\n jev: { ...jevTotals, model: judge.model() },\n };\n emit(\"summary\", { wallMs, stageMs, stats, status, jevByStage: judge.stats() });\n const result: CodeSearchResult = { version: CODE_SEARCH_ENGINE_VERSION, text, status, stats };\n if (statusCheckError) result.statusCheckError = statusCheckError;\n return result;\n}\n\nfunction round(x: number): number {\n return Number.isFinite(x) ? Math.round(x * 1000) / 1000 : x;\n}\n","/**\n * tool.ts - the model-facing surface of code_search: name, description, input schema, argument\n * parsing and short error texts. The worker wires these to runCodeSearch.\n */\nimport { JevRequestError, JevUnavailableError } from \"../client\";\nimport { CodeSearchRipgrepMissingError, CodeSearchWorkspaceError } from \"./workspace\";\n\nexport const CODE_SEARCH_TOOL_NAME = \"code_search\";\n\nexport const CODE_SEARCH_TOOL_DESCRIPTION =\n \"Find where something is implemented, configured or decided in the code under the working directory, in one call \" +\n \"instead of many separate searches and file reads. Give one precise question and 6-15 keywords: likely identifiers, \" +\n \"file-name fragments, config keys, error strings and synonyms. Optional subQuestions split distinct parts (for \" +\n \"'is X required?', add one for what could skip or override X); optional paths limit the search. It ranks files and \" +\n \"passages with a fast relevance model, follows definitions one level, and returns the best passages verbatim with \" +\n \"file paths and line numbers, plus an evidence rating for those passages. The rating cannot see what the search \" +\n \"missed: use the passages instead of re-reading them, then check what they do not cover (other entry points, \" +\n \"defaults, flags, exceptions) before concluding.\";\n\nexport const CODE_SEARCH_LIMITS = {\n questionMinChars: 3,\n questionMaxChars: 2000,\n keywordsMax: 20,\n keywordMaxChars: 120,\n subQuestionsMax: 3,\n subQuestionMaxChars: 1000,\n pathsMax: 8,\n pathMaxChars: 1000,\n} as const;\n\nconst L = CODE_SEARCH_LIMITS;\n\n/** Plain JSON (mutable arrays), so it fits any JSON-schema slot of a tool definition. */\nexport type CodeSearchJsonValue =\n | string\n | number\n | boolean\n | null\n | CodeSearchJsonValue[]\n | { [key: string]: CodeSearchJsonValue };\n\n/** JSON schema of the tool input; parseCodeSearchArguments enforces the same rules. */\nexport const codeSearchInputSchema: { [key: string]: CodeSearchJsonValue } = {\n type: \"object\",\n properties: {\n question: {\n type: \"string\",\n minLength: L.questionMinChars,\n maxLength: L.questionMaxChars,\n description:\n \"One precise question about the code, for example where a behavior is implemented or how a value is computed.\",\n },\n keywords: {\n type: \"array\",\n minItems: 1,\n maxItems: L.keywordsMax,\n items: { type: \"string\", minLength: 1, maxLength: L.keywordMaxChars },\n description:\n \"6-15 search keywords: likely identifiers (camelCase, snake_case, UPPER_CASE), file-name fragments, config or env keys, error strings, synonyms. Case and camel/snake/kebab variants are searched automatically.\",\n },\n subQuestions: {\n type: \"array\",\n maxItems: L.subQuestionsMax,\n items: { type: \"string\", minLength: 1, maxLength: L.subQuestionMaxChars },\n description: \"Optional: the distinct parts of a multi-part question, one per entry.\",\n },\n paths: {\n type: \"array\",\n maxItems: L.pathsMax,\n items: { type: \"string\", minLength: 1, maxLength: L.pathMaxChars },\n description:\n \"Optional: workspace-relative directories or files to limit the search to. Default: the whole workspace.\",\n },\n },\n required: [\"question\", \"keywords\"],\n additionalProperties: false,\n};\n\nexport interface CodeSearchArguments {\n question: string;\n keywords: string[];\n subQuestions: string[];\n paths: string[];\n}\n\n/** Invalid tool arguments; the message is written for the model. */\nexport class CodeSearchArgumentError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CodeSearchArgumentError\";\n }\n}\n\nconst KNOWN_ARGUMENTS = new Set([\"question\", \"keywords\", \"subQuestions\", \"paths\"]);\n\n/** Validate and normalize tool arguments (trim, drop empty entries, dedupe, workspace-relative paths). */\nexport function parseCodeSearchArguments(args: Record<string, unknown>): CodeSearchArguments {\n const unknown = Object.keys(args).filter((k) => !KNOWN_ARGUMENTS.has(k));\n if (unknown.length) {\n throw new CodeSearchArgumentError(\n `unknown argument ${unknown.map((k) => `\"${k}\"`).join(\", \")}; allowed: question, keywords, subQuestions, paths`,\n );\n }\n\n if (typeof args.question !== \"string\")\n throw new CodeSearchArgumentError(\"question is required and must be a string\");\n const question = args.question.trim();\n if (question.length < L.questionMinChars)\n throw new CodeSearchArgumentError(`question must be at least ${L.questionMinChars} characters`);\n if (question.length > L.questionMaxChars)\n throw new CodeSearchArgumentError(`question must be at most ${L.questionMaxChars} characters`);\n\n const keywords = stringList(args.keywords, \"keywords\", true);\n if (!keywords.length)\n throw new CodeSearchArgumentError(\"keywords must contain at least one non-empty keyword\");\n if (keywords.length > L.keywordsMax)\n throw new CodeSearchArgumentError(\n `keywords accepts at most ${L.keywordsMax} entries; keep the ${L.keywordsMax} most specific`,\n );\n const longKeyword = keywords.find((k) => k.length > L.keywordMaxChars);\n if (longKeyword)\n throw new CodeSearchArgumentError(\n `each keyword must be at most ${L.keywordMaxChars} characters; use short identifiers or phrases`,\n );\n\n const subQuestions = stringList(args.subQuestions, \"subQuestions\", false);\n if (subQuestions.length > L.subQuestionsMax)\n throw new CodeSearchArgumentError(`subQuestions accepts at most ${L.subQuestionsMax} entries`);\n if (subQuestions.some((s) => s.length > L.subQuestionMaxChars)) {\n throw new CodeSearchArgumentError(\n `each sub-question must be at most ${L.subQuestionMaxChars} characters`,\n );\n }\n\n const paths = [...new Set(stringList(args.paths, \"paths\", false).map(normalizePath))];\n if (paths.length > L.pathsMax)\n throw new CodeSearchArgumentError(`paths accepts at most ${L.pathsMax} entries`);\n\n return { question, keywords, subQuestions, paths };\n}\n\nfunction stringList(value: unknown, name: string, required: boolean): string[] {\n if (value === undefined || value === null) {\n if (required)\n throw new CodeSearchArgumentError(`${name} is required and must be an array of strings`);\n return [];\n }\n if (!Array.isArray(value) || value.some((v) => typeof v !== \"string\")) {\n throw new CodeSearchArgumentError(`${name} must be an array of strings`);\n }\n return [...new Set((value as string[]).map((v) => v.trim()).filter(Boolean))];\n}\n\nfunction normalizePath(raw: string): string {\n if (raw.length > L.pathMaxChars)\n throw new CodeSearchArgumentError(`each path must be at most ${L.pathMaxChars} characters`);\n if (raw.startsWith(\"/\") || raw.startsWith(\"~\") || /^[A-Za-z]:[\\\\/]/.test(raw)) {\n throw new CodeSearchArgumentError(\n `path \"${raw}\" is absolute; give paths relative to the working directory`,\n );\n }\n let p = raw;\n while (p.startsWith(\"./\")) p = p.slice(2);\n p = p.replace(/\\/+$/, \"\");\n if (!p) p = \".\";\n if (p.split(\"/\").some((seg) => seg === \"..\")) {\n throw new CodeSearchArgumentError(\n `path \"${raw}\" leaves the working directory; \"..\" is not allowed`,\n );\n }\n if (p.startsWith(\"-\")) throw new CodeSearchArgumentError(`path \"${raw}\" must not start with \"-\"`);\n return p;\n}\n\nconst FALLBACK = \"Search with exec_command (rg, sed) instead.\";\n\n/** Short model-facing text for a failed code_search call. */\nexport function renderCodeSearchError(error: unknown): string {\n const detail = (e: unknown) =>\n (e instanceof Error ? e.message : String(e)).replace(/\\s+/g, \" \").trim().slice(0, 240);\n if (error instanceof CodeSearchArgumentError)\n return `code_search: invalid arguments: ${error.message}.`;\n if (error instanceof JevUnavailableError)\n return `code_search is unavailable right now (${detail(error)}). ${FALLBACK}`;\n if (error instanceof JevRequestError)\n return `code_search failed: the relevance model rejected the request (${detail(error)}). ${FALLBACK}`;\n if (isRipgrepMissing(error)) {\n return \"code_search cannot run here: ripgrep (rg) is not installed in this workspace. Search with exec_command (grep, find, sed) instead.\";\n }\n if (error instanceof CodeSearchWorkspaceError)\n return `code_search could not search this workspace (${detail(error)}). ${FALLBACK}`;\n if (isAbort(error)) return \"code_search was cancelled.\";\n return `code_search failed unexpectedly (${detail(error)}). ${FALLBACK}`;\n}\n\nfunction isRipgrepMissing(error: unknown): boolean {\n if (error instanceof CodeSearchRipgrepMissingError) return true;\n if (!(error instanceof CodeSearchWorkspaceError)) return false;\n const m = error.message;\n return /ripgrep|\\brg\\b/i.test(m) && /not (installed|found)|missing|ENOENT|no such file/i.test(m);\n}\n\nfunction isAbort(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n (error as { name?: unknown }).name === \"AbortError\"\n );\n}\n"],"mappings":";AAYO,IAAM,uBAAuB;AAC7B,IAAM,oBAAoB;AAE1B,IAAM,yCAAyC;AA6E/C,SAAS,KACd,cACA,UACiB;AACjB,SAAO,WAAW,EAAE,MAAM,QAAQ,cAAc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