github-router 0.3.326 → 0.3.328
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.
- package/dist/{aic-ledger-DRU89gJg.js → aic-ledger-CsBx1crE.js} +2 -2
- package/dist/{aic-ledger-DRU89gJg.js.map → aic-ledger-CsBx1crE.js.map} +1 -1
- package/dist/{attribution-settings-17Ug_BaA.js → attribution-settings-CF1ZV58z.js} +10 -10
- package/dist/attribution-settings-CF1ZV58z.js.map +1 -0
- package/dist/{auth-DSLN1arH.js → auth-xgFZGZbf.js} +3 -3
- package/dist/{auth-DSLN1arH.js.map → auth-xgFZGZbf.js.map} +1 -1
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-B_12ALvf.js → check-usage-vUDk6oV7.js} +4 -4
- package/dist/{check-usage-B_12ALvf.js.map → check-usage-vUDk6oV7.js.map} +1 -1
- package/dist/{claude-D1QpvY-x.js → claude-BdJupNy4.js} +21 -20
- package/dist/{claude-D1QpvY-x.js.map → claude-BdJupNy4.js.map} +1 -1
- package/dist/{codex-BwuTiY0q.js → codex-DgEG2i_w.js} +6 -5
- package/dist/{codex-BwuTiY0q.js.map → codex-DgEG2i_w.js.map} +1 -1
- package/dist/{copilot-discount-D8t7Q3Tp.js → copilot-discount-0lG67i9O.js} +2 -2
- package/dist/{copilot-discount-D8t7Q3Tp.js.map → copilot-discount-0lG67i9O.js.map} +1 -1
- package/dist/{debug-D8iD6G4O.js → debug-a737qcCC.js} +2 -2
- package/dist/{debug-D8iD6G4O.js.map → debug-a737qcCC.js.map} +1 -1
- package/dist/engine-C3SnOV1U.js +2 -0
- package/dist/{gate-discovery-Z0QyjqM7.js → gate-discovery-ufkJQE8V.js} +5 -5
- package/dist/{gate-discovery-Z0QyjqM7.js.map → gate-discovery-ufkJQE8V.js.map} +1 -1
- package/dist/{get-copilot-usage-Bs-FEPMf.js → get-copilot-usage-VKU2IvuE.js} +2 -2
- package/dist/{get-copilot-usage-Bs-FEPMf.js.map → get-copilot-usage-VKU2IvuE.js.map} +1 -1
- package/dist/index-cmd-mPy73hig.js +172 -0
- package/dist/index-cmd-mPy73hig.js.map +1 -0
- package/dist/{internal-aic-status-BaUKlisM.js → internal-aic-status-Cfl5HiAN.js} +3 -3
- package/dist/{internal-aic-status-BaUKlisM.js.map → internal-aic-status-Cfl5HiAN.js.map} +1 -1
- package/dist/{internal-artifact-open-U-Ht7R-O.js → internal-artifact-open-CX2fRP_D.js} +2 -2
- package/dist/{internal-artifact-open-U-Ht7R-O.js.map → internal-artifact-open-CX2fRP_D.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-Dnjoj0pV.js → internal-fast-dispatch-guard-BoTxjO6b.js} +2 -2
- package/dist/{internal-fast-dispatch-guard-Dnjoj0pV.js.map → internal-fast-dispatch-guard-BoTxjO6b.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-uztSu0c8.js → internal-fast-dispatch-guard-Cxattkm4.js} +1 -1
- package/dist/{internal-first-mate-guard-ZqPHrYlh.js → internal-first-mate-guard-97qsseTP.js} +1 -1
- package/dist/{internal-first-mate-guard-Cj_g7RFr.js → internal-first-mate-guard-D_JFcrl_.js} +3 -3
- package/dist/{internal-first-mate-guard-Cj_g7RFr.js.map → internal-first-mate-guard-D_JFcrl_.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-Sp_rCYk_.js → internal-max-dispatch-guard-Cxe8h12x.js} +2 -2
- package/dist/{internal-max-dispatch-guard-Sp_rCYk_.js.map → internal-max-dispatch-guard-Cxe8h12x.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-CxG_c3cc.js → internal-max-dispatch-guard-DQMyOds8.js} +1 -1
- package/dist/{internal-plan-review-Co01iHOW.js → internal-plan-review-DM-Zycyn.js} +3 -3
- package/dist/{internal-plan-review-Co01iHOW.js.map → internal-plan-review-DM-Zycyn.js.map} +1 -1
- package/dist/{internal-prompt-submit-dflz0bqH.js → internal-prompt-submit-6AKy89nq.js} +4 -4
- package/dist/{internal-prompt-submit-dflz0bqH.js.map → internal-prompt-submit-6AKy89nq.js.map} +1 -1
- package/dist/{internal-session-bind-BVQy7Vd4.js → internal-session-bind-CHIOd5ys.js} +2 -2
- package/dist/{internal-session-bind-BVQy7Vd4.js.map → internal-session-bind-CHIOd5ys.js.map} +1 -1
- package/dist/{internal-stop-hook-DihBVzn2.js → internal-stop-hook-CWwkeyf_.js} +5 -5
- package/dist/{internal-stop-hook-DihBVzn2.js.map → internal-stop-hook-CWwkeyf_.js.map} +1 -1
- package/dist/{internal-stop-review-CrnG4IJo.js → internal-stop-review-CPk66wwo.js} +2 -2
- package/dist/{internal-stop-review-CrnG4IJo.js.map → internal-stop-review-CPk66wwo.js.map} +1 -1
- package/dist/{internal-worker-guard-Dd14aDXQ.js → internal-worker-guard-BY5seBqp.js} +2 -2
- package/dist/{internal-worker-guard-Dd14aDXQ.js.map → internal-worker-guard-BY5seBqp.js.map} +1 -1
- package/dist/{internal-workspace-header-booLOzwD.js → internal-workspace-header-CPZNphnk.js} +2 -2
- package/dist/{internal-workspace-header-booLOzwD.js.map → internal-workspace-header-CPZNphnk.js.map} +1 -1
- package/dist/lib/tree-sitter-pool/worker.js +88 -3
- package/dist/lifecycle-B2eB8nRg.js +2 -0
- package/dist/{lifecycle-C1LDvDD6.js → lifecycle-D8vQXfeC.js} +7 -3
- package/dist/{lifecycle-C1LDvDD6.js.map → lifecycle-D8vQXfeC.js.map} +1 -1
- package/dist/lifecycle-Dz-Rq8pD.js +2 -0
- package/dist/{lifecycle-BYPEqFdV.js → lifecycle-MmpJWRcl.js} +2 -2
- package/dist/{lifecycle-BYPEqFdV.js.map → lifecycle-MmpJWRcl.js.map} +1 -1
- package/dist/main.js +21 -20
- package/dist/main.js.map +1 -1
- package/dist/{mcp-workspace-header-BIW0SRgs.js → mcp-workspace-header-DX_mD0JT.js} +2 -2
- package/dist/{mcp-workspace-header-BIW0SRgs.js.map → mcp-workspace-header-DX_mD0JT.js.map} +1 -1
- package/dist/{models-B9tdaM6B.js → models-BjCRO0AC.js} +3 -3
- package/dist/{models-B9tdaM6B.js.map → models-BjCRO0AC.js.map} +1 -1
- package/dist/{orchestration-DvsdorFq.js → orchestration-Dn5v8c0a.js} +2 -2
- package/dist/{orchestration-DvsdorFq.js.map → orchestration-Dn5v8c0a.js.map} +1 -1
- package/dist/paths-DVXBtLyo.js +2 -0
- package/dist/{paths-BnZwolac.js → paths-P5ajjpzU.js} +3 -3
- package/dist/{paths-BnZwolac.js.map → paths-P5ajjpzU.js.map} +1 -1
- package/dist/{peer-mcp-personas-DcAErb_d.js → peer-mcp-personas-Dg2LJ0GF.js} +921 -4915
- package/dist/peer-mcp-personas-Dg2LJ0GF.js.map +1 -0
- package/dist/{plan-review-hook-BlsGnG02.js → plan-review-hook-ChuywYy_.js} +3 -3
- package/dist/{plan-review-hook-BlsGnG02.js.map → plan-review-hook-ChuywYy_.js.map} +1 -1
- package/dist/{prompt-submit-hook-BJFLzCaT.js → prompt-submit-hook-C0ZospPT.js} +3 -3
- package/dist/{prompt-submit-hook-BJFLzCaT.js.map → prompt-submit-hook-C0ZospPT.js.map} +1 -1
- package/dist/{provision-B-a5KUCL.js → provision-l0THw3kO.js} +5 -4
- package/dist/{provision-B-a5KUCL.js.map → provision-l0THw3kO.js.map} +1 -1
- package/dist/runner-BoJPRQsK.js +5762 -0
- package/dist/runner-BoJPRQsK.js.map +1 -0
- package/dist/{self-invocation-opSXHEs0.js → self-invocation-DBWyjvGm.js} +2 -2
- package/dist/{self-invocation-opSXHEs0.js.map → self-invocation-DBWyjvGm.js.map} +1 -1
- package/dist/{serve-jUiGNHEz.js → serve-DZY93dBo.js} +14 -12
- package/dist/{serve-jUiGNHEz.js.map → serve-DZY93dBo.js.map} +1 -1
- package/dist/{server-setup-BfTjAZS2.js → server-setup-Bv7TGDC7.js} +8 -7
- package/dist/{server-setup-BfTjAZS2.js.map → server-setup-Bv7TGDC7.js.map} +1 -1
- package/dist/{start-jdDuyg5T.js → start-2SrUerLA.js} +4 -3
- package/dist/{start-jdDuyg5T.js.map → start-2SrUerLA.js.map} +1 -1
- package/dist/{stop-gate-hook-DvNM8zFf.js → stop-gate-hook-BACb8dlj.js} +3 -3
- package/dist/{stop-gate-hook-DvNM8zFf.js.map → stop-gate-hook-BACb8dlj.js.map} +1 -1
- package/dist/{stop-gate-policy-C5pXbY59.js → stop-gate-policy-D6jIeOXB.js} +2 -2
- package/dist/{stop-gate-policy-C5pXbY59.js.map → stop-gate-policy-D6jIeOXB.js.map} +1 -1
- package/dist/{token-Css-ARGL.js → token-Dlb_84hW.js} +2 -2
- package/dist/{token-Css-ARGL.js.map → token-Dlb_84hW.js.map} +1 -1
- package/dist/{worker-dispatch-CcQygiAA.js → worker-dispatch-DtjQchvM.js} +2 -2
- package/dist/{worker-dispatch-CcQygiAA.js.map → worker-dispatch-DtjQchvM.js.map} +1 -1
- package/package.json +4 -2
- package/dist/attribution-settings-17Ug_BaA.js.map +0 -1
- package/dist/engine-4uuaURb0.js +0 -2
- package/dist/lifecycle-Cz99P30h.js +0 -2
- package/dist/lifecycle-DqTFEJpS.js +0 -2
- package/dist/paths-BzM6uxmd.js +0 -2
- package/dist/peer-mcp-personas-DcAErb_d.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runner-BoJPRQsK.js","names":["path","os","os","path","DEFAULT_LIMIT","MAX_STDOUT_BYTES","path","process","fs","process","process","fs"],"sources":["../src/lib/update-lock.ts","../src/lib/tree-sitter-assets/files.ts","../src/lib/tree-sitter-assets/provision.ts","../src/lib/tree-sitter-grammars.ts","../src/lib/tree-sitter-pool/pool.ts","../src/lib/search-concurrency.ts","../src/lib/rerank.ts","../src/lib/worker-agent/paths.ts","../src/lib/code-search.ts","../src/lib/colbert/manifest.ts","../src/lib/toolbelt/extract.ts","../src/lib/colbert/provision.ts","../src/lib/colbert/index-store.ts","../src/lib/colbert/runner.ts"],"sourcesContent":["/**\n * Cross-process install lock for the auto-update / self-update paths.\n *\n * Multiple concurrent `github-router` launches must not run\n * `npm install -g` (or `claude update`) at the same time — on Windows\n * the global `node_modules` / `.cmd` shim rewrite is fragile and\n * concurrent writers corrupt it. An `O_EXCL` lockfile guarantees\n * exactly one updater runs; others skip.\n */\n\nimport { open, rm, stat } from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\n/** A lock older than this is treated as stale (crashed holder) and stolen. */\nconst STALE_LOCK_MS = 10 * 60 * 1000 // 10 min > the 120s install timeout\n\nfunction lockPath(name: string): string {\n return path.join(os.homedir(), \".local\", \"share\", \"github-router\", name)\n}\n\n/**\n * Run `fn` while holding an exclusive lockfile named `name` under the\n * app dir. Returns `true` if the lock was acquired and `fn` ran,\n * `false` if another process already holds it (caller skips silently).\n *\n * A lock left by a crashed process older than `STALE_LOCK_MS` is\n * stolen so the updater can never be wedged permanently.\n */\nexport async function withInstallLock(\n name: string,\n fn: () => Promise<void>,\n): Promise<boolean> {\n const p = lockPath(name)\n\n let handle = await tryCreateLock(p)\n if (!handle) {\n // Existing lock — steal it if stale, else skip.\n let stale: boolean\n try {\n const s = await stat(p)\n stale = Date.now() - s.mtimeMs > STALE_LOCK_MS\n } catch {\n // Disappeared between create-attempt and stat — try once more.\n stale = true\n }\n if (!stale) return false\n await rm(p, { force: true }).catch(() => {})\n handle = await tryCreateLock(p)\n if (!handle) return false\n }\n\n try {\n await handle.close()\n await fn()\n return true\n } finally {\n await rm(p, { force: true }).catch(() => {})\n }\n}\n\nasync function tryCreateLock(\n p: string,\n): Promise<Awaited<ReturnType<typeof open>> | null> {\n try {\n // \"wx\" = O_CREAT | O_EXCL — fails if the file already exists.\n return await open(p, \"wx\")\n } catch {\n return null\n }\n}\n","/** WASM assets code search loads from tree-sitter-wasms. */\nexport const TREE_SITTER_GRAMMAR_FILES: Readonly<Record<string, string>> = {\n typescript: \"tree-sitter-typescript.wasm\",\n tsx: \"tree-sitter-tsx.wasm\",\n javascript: \"tree-sitter-javascript.wasm\",\n python: \"tree-sitter-python.wasm\",\n go: \"tree-sitter-go.wasm\",\n rust: \"tree-sitter-rust.wasm\",\n java: \"tree-sitter-java.wasm\",\n c: \"tree-sitter-c.wasm\",\n cpp: \"tree-sitter-cpp.wasm\",\n csharp: \"tree-sitter-c_sharp.wasm\",\n}\n\nexport const TREE_SITTER_RUNTIME_FILE = \"tree-sitter.wasm\"\n","/*\n * Copy the tree-sitter runtime WASM and the grammar subset code search uses\n * out of the package tree and into APP_DIR.\n *\n * bunx commonly installs packages under the OS temp directory. Temp reapers\n * can remove those files while leaving the directory skeleton, so resolving\n * node_modules again is not a durability strategy. The stable copies here are\n * best-effort fallbacks: initial startup can still use node_modules, while a\n * later startup survives after that tree has been reaped.\n */\n\nimport { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from \"node:fs\"\nimport { createRequire } from \"node:module\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nimport { PATHS } from \"../paths\"\nimport {\n TREE_SITTER_GRAMMAR_FILES,\n TREE_SITTER_RUNTIME_FILE,\n} from \"./files\"\n\nconst PUBLISH_ATTEMPTS = 3\n\nlet _provisioned = false\nlet _inFlight: Promise<void> | undefined\n\n/** @internal — reset module state between test cases. */\nexport function __resetTreeSitterAssetsForTests(): void {\n _provisioned = false\n _inFlight = undefined\n}\n\n/**\n * Materialize every required WASM asset. Single-flight and success-cached;\n * transient failures remain retryable. Never throws to the launcher.\n */\nexport function provisionTreeSitterAssets(): Promise<void> {\n if (_provisioned) return Promise.resolve()\n if (_inFlight) return _inFlight\n _inFlight = Promise.resolve()\n .then(() => provisionImpl())\n .then((complete) => {\n if (complete) _provisioned = true\n })\n .finally(() => {\n _inFlight = undefined\n })\n return _inFlight\n}\n\nfunction provisionImpl(): boolean {\n try {\n const require = createRequire(import.meta.url)\n const grammarPackage = require.resolve(\"tree-sitter-wasms/package.json\")\n const grammarRoot = path.join(path.dirname(grammarPackage), \"out\")\n const runtime = require.resolve(\"web-tree-sitter/tree-sitter.wasm\")\n const destination = PATHS.TREE_SITTER_ASSETS_DIR\n mkdirSync(destination, { recursive: true })\n\n let complete = publishAsset(\n runtime,\n path.join(destination, TREE_SITTER_RUNTIME_FILE),\n )\n for (const filename of Object.values(TREE_SITTER_GRAMMAR_FILES)) {\n const published = publishAsset(\n path.join(grammarRoot, filename),\n path.join(destination, filename),\n )\n complete = published && complete\n }\n return complete\n } catch (err) {\n consola.debug(\"[tree-sitter-assets] provisioning skipped:\", err)\n return false\n }\n}\n\n/**\n * Publish through a unique same-directory temporary file. Never remove the\n * destination first: a concurrent parser must see either the prior complete\n * file or the new complete file, never a missing/partial path. A losing racer\n * accepts the winner when its bytes match the source.\n */\nfunction publishAsset(source: string, destination: string): boolean {\n let bytes: Buffer\n try {\n bytes = readFileSync(source)\n } catch {\n return false\n }\n if (matchesContent(destination, bytes)) return true\n\n for (let attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt++) {\n const tmp = `${destination}.${process.pid}-${attempt}.tmp`\n try {\n writeFileSync(tmp, bytes)\n renameSync(tmp, destination)\n return true\n } catch {\n try {\n rmSync(tmp, { force: true })\n } catch {\n /* best-effort */\n }\n if (matchesContent(destination, bytes)) return true\n }\n }\n return false\n}\n\n/**\n * Whether the published file is byte-identical to the source.\n *\n * Content, not size: a grammar upgrade that happens to keep the same byte\n * length would otherwise never propagate, and the stale copy would shadow the\n * package's newer file permanently — a silent, self-perpetuating wrong answer.\n * The size check first keeps the common case to one `stat`.\n */\nfunction matchesContent(file: string, bytes: Buffer): boolean {\n try {\n const stat = statSync(file)\n if (!stat.isFile() || stat.size !== bytes.byteLength) return false\n return readFileSync(file).equals(bytes)\n } catch {\n return false\n }\n}\n\n/**\n * Whether the stable directory holds the COMPLETE asset set: the runtime plus\n * every grammar.\n *\n * Callers must gate on the whole set, never on the one file they are about to\n * read. web-tree-sitter enforces a language-ABI version between the runtime and\n * the grammars, so adopting a stable runtime while grammars still come from the\n * package tree (or the reverse) can pair mismatched builds. That surfaces as a\n * caught `Language.load` failure, which silently disables structural ranking —\n * the exact silent degradation this whole change is meant to end.\n */\nexport function stableTreeSitterAssetsComplete(): boolean {\n const dir = PATHS.TREE_SITTER_ASSETS_DIR\n const required = [\n TREE_SITTER_RUNTIME_FILE,\n ...Object.values(TREE_SITTER_GRAMMAR_FILES),\n ]\n return required.every((name) => {\n try {\n return statSync(path.join(dir, name)).isFile()\n } catch {\n return false\n }\n })\n}\n","/**\n * Shared tree-sitter grammar layer.\n *\n * This module is the pure grammar-loading + constant-table layer\n * extracted from `src/lib/code-search.ts`. It owns:\n *\n * - the extension → language and language → wasm-filename tables,\n * - the per-language definition-node-type sets and the shared\n * identifier-node-type set,\n * - the lazy `web-tree-sitter` `Parser.init()` + grammar-load cache\n * (`getGrammarBundle`), pre-warmed at module import time, and\n * - `outlineFile`, a compact navigational outline of a single file.\n *\n * The BM25F scoring, the structural-confirmation pass, and the parsed-\n * tree LRU stay in `code-search.ts` — they are tightly coupled to the\n * ranking flow and would not survive a clean move. `code-search.ts`\n * imports the symbols here and continues to call the same functions, so\n * the extraction is behavior-preserving for the structural pass.\n *\n * There is exactly ONE `Parser.init()` and ONE grammar cache across the\n * whole process: every caller (the structural pass, `outlineFile`)\n * awaits the same `getGrammarBundle().ready` promise.\n *\n * Version pin note (evaluated 2026-09): web-tree-sitter stays at 0.25.10\n * with tree-sitter-wasms 0.1.13 prebuilts. Upgrading the runtime to 0.27.0\n * was spike-tested — all 9 prebuilt grammars fail to load (WASM\n * dynamic-linking format mismatch). The migration path is web-tree-sitter\n * 0.27.0 + tree-sitter-wasm 1.1.3 (verified: all 9 load + parse), but that\n * swaps grammar builds too, so DEFINITION_NODE_TYPES needs node-type\n * parity validation per language before it ships. Deferred until the\n * semantic-service work lands; the cost of staying is only the\n * check-between-files (not mid-parse) structural budget.\n */\n\nimport * as path from \"node:path\"\nimport { statSync } from \"node:fs\"\nimport { readFile } from \"node:fs/promises\"\n\nimport consola from \"consola\"\nimport { Language, Node, Parser, Tree } from \"web-tree-sitter\"\n\nimport { PATHS } from \"~/lib/paths\"\nimport {\n TREE_SITTER_GRAMMAR_FILES,\n TREE_SITTER_RUNTIME_FILE,\n} from \"~/lib/tree-sitter-assets/files\"\nimport { stableTreeSitterAssetsComplete } from \"~/lib/tree-sitter-assets/provision\"\n\n// ============================================================\n// Constants\n// ============================================================\n\n/**\n * Cap the per-file size we'll parse. 1MB of source covers all\n * reasonable hand-written files; bigger files are almost always\n * generated code or vendored bundles whose AST signal is worthless\n * for ranking real definitions.\n */\nexport const STRUCTURAL_MAX_FILE_BYTES = 1024 * 1024\n\n// ============================================================\n// Language / grammar tables\n// ============================================================\n\n/**\n * Extension → grammar key. Grammars not in this map skip structural\n * parsing (the hit falls back to the regex SYMBOL_REGEX heuristic for\n * `symbol_context`). Keep this list aligned with `GRAMMAR_FILES`\n * below — adding a language requires both an extension mapping and a\n * `.wasm` to load.\n */\nexport const EXTENSION_TO_LANG: Readonly<Record<string, string>> = {\n \".ts\": \"typescript\",\n \".tsx\": \"tsx\",\n \".js\": \"javascript\",\n \".mjs\": \"javascript\",\n \".cjs\": \"javascript\",\n \".jsx\": \"javascript\",\n \".py\": \"python\",\n \".go\": \"go\",\n \".rs\": \"rust\",\n \".java\": \"java\",\n \".c\": \"c\",\n \".h\": \"c\",\n \".cpp\": \"cpp\",\n \".cc\": \"cpp\",\n \".cxx\": \"cpp\",\n \".hpp\": \"cpp\",\n \".hxx\": \"cpp\",\n \".cs\": \"csharp\",\n}\n\n/**\n * Grammar key → wasm filename. The stable APP_DIR copy is preferred; the\n * original `node_modules/tree-sitter-wasms/out/` directory remains the\n * first-run fallback while background provisioning completes.\n */\nexport const GRAMMAR_FILES = TREE_SITTER_GRAMMAR_FILES\n\n/**\n * Per-language definition-shape node types. When a matched identifier\n * sits inside one of these nodes AND is at the node's \"name\" position,\n * we have AST-confirmed evidence the line is an identifier-definition\n * site. The brief's enumeration plus a handful of language-idiomatic\n * extras (e.g., `lexical_declaration` for TS/JS top-level `const`s,\n * `mod_item` for Rust modules).\n *\n * The set lookup is per-language so a node type that means\n * \"definition\" in one language but \"reference\" in another won't\n * cross-pollute.\n */\nexport const DEFINITION_NODE_TYPES: Readonly<Record<string, ReadonlySet<string>>> = {\n typescript: new Set([\n \"function_declaration\",\n \"function_signature\",\n \"function_expression\",\n \"method_definition\",\n \"method_signature\",\n \"class_declaration\",\n \"interface_declaration\",\n \"type_alias_declaration\",\n \"enum_declaration\",\n \"variable_declarator\",\n \"generator_function_declaration\",\n \"abstract_method_signature\",\n \"public_field_definition\",\n \"property_signature\",\n ]),\n tsx: new Set([\n \"function_declaration\",\n \"function_signature\",\n \"function_expression\",\n \"method_definition\",\n \"method_signature\",\n \"class_declaration\",\n \"interface_declaration\",\n \"type_alias_declaration\",\n \"enum_declaration\",\n \"variable_declarator\",\n \"generator_function_declaration\",\n \"abstract_method_signature\",\n \"public_field_definition\",\n \"property_signature\",\n ]),\n javascript: new Set([\n \"function_declaration\",\n \"function_expression\",\n \"method_definition\",\n \"class_declaration\",\n \"variable_declarator\",\n \"generator_function_declaration\",\n ]),\n python: new Set([\n \"function_definition\",\n \"class_definition\",\n \"decorated_definition\",\n ]),\n go: new Set([\n \"function_declaration\",\n \"method_declaration\",\n \"type_spec\",\n \"type_alias\",\n \"const_spec\",\n \"var_spec\",\n ]),\n rust: new Set([\n \"function_item\",\n \"impl_item\",\n \"trait_item\",\n \"struct_item\",\n \"enum_item\",\n \"mod_item\",\n \"type_item\",\n \"const_item\",\n \"static_item\",\n \"macro_definition\",\n ]),\n java: new Set([\n \"class_declaration\",\n \"interface_declaration\",\n \"method_declaration\",\n \"constructor_declaration\",\n \"enum_declaration\",\n \"field_declaration\",\n \"annotation_type_declaration\",\n ]),\n c: new Set([\n \"function_definition\",\n \"declaration\",\n \"struct_specifier\",\n \"enum_specifier\",\n \"union_specifier\",\n \"type_definition\",\n ]),\n cpp: new Set([\n \"function_definition\",\n \"declaration\",\n \"struct_specifier\",\n \"class_specifier\",\n \"enum_specifier\",\n \"union_specifier\",\n \"type_definition\",\n \"namespace_definition\",\n \"template_declaration\",\n ]),\n csharp: new Set([\n \"namespace_declaration\",\n \"file_scoped_namespace_declaration\",\n \"class_declaration\",\n \"interface_declaration\",\n \"struct_declaration\",\n \"record_declaration\",\n \"record_struct_declaration\",\n \"enum_declaration\",\n \"enum_member_declaration\",\n \"delegate_declaration\",\n \"method_declaration\",\n \"constructor_declaration\",\n \"destructor_declaration\",\n \"property_declaration\",\n \"indexer_declaration\",\n \"operator_declaration\",\n \"field_declaration\",\n \"event_field_declaration\",\n ]),\n}\n\n/**\n * Per-language definition node types whose declared name carries NO\n * dedicated `name`/`declarator`/`type` field the `isDefiningSite` walk can\n * test positionally. For these shapes the name is recovered positionally:\n * the first declarator's identifier (C# `field_declaration` /\n * `event_field_declaration` are always `modifiers* type declarator\n * (= value)? ;` — no body). The walk is scoped to the declarator itself\n * because BOTH leading attributes AND the type annotation can contain\n * identifiers that precede the name (`[Attr] System.EventHandler Changed;`\n * must resolve to `Changed`).\n *\n * Soundness: the declarator's own name textually precedes any initializer,\n * so initializer references can never match. Multi-declarator fields\n * (`int a = 1, b = 2;`) confirm only the first — incomplete but never\n * wrong, matching the `role` contract (absence is not a usage claim).\n */\nexport const FIRST_LEAF_DEFINITION_TYPES: Readonly<\n Record<string, ReadonlySet<string>>\n> = {\n csharp: new Set([\"field_declaration\", \"event_field_declaration\"]),\n}\n\n/**\n * Node types that the AST exposes as \"this token is an identifier\".\n * The match-position lookup uses these to filter out parent-node hits\n * before checking the definition-site predicate.\n */\nexport const IDENTIFIER_NODE_TYPES = new Set([\n \"identifier\",\n \"type_identifier\",\n \"field_identifier\",\n \"property_identifier\",\n \"shorthand_property_identifier_pattern\",\n \"shorthand_property_identifier\",\n \"scoped_identifier\",\n \"name\",\n])\n\n/**\n * Extension → grammar key resolution. Returns `null` for files with no\n * grammar (the caller falls back to the regex heuristic / skips the\n * structural pass).\n */\nexport function getLanguageKeyForPath(filePath: string): string | null {\n const ext = path.extname(filePath).toLowerCase()\n return EXTENSION_TO_LANG[ext] ?? null\n}\n\n// ============================================================\n// Grammar loading (single shared Parser.init + cache)\n// ============================================================\n\nexport interface GrammarBundle {\n /** Lazy promise of the language registry. Awaited per-call so the\n * init cost overlaps with any other module-load work. */\n ready: Promise<Map<string, Language>>\n}\n\nlet _grammarBundle: GrammarBundle | undefined\n\n/**\n * Resolve the grammar directory. The stable APP_DIR copy wins only when the\n * COMPLETE set is present; otherwise `require.resolve` supplies the\n * package-tree fallback for first launch or a best-effort provisioning failure.\n *\n * All-or-nothing on purpose — see `stableTreeSitterAssetsComplete()`: mixing a\n * stable runtime with package-tree grammars can pair mismatched ABI builds and\n * silently disable structural ranking.\n */\nexport function resolveGrammarRoot(): string | null {\n if (stableTreeSitterAssetsComplete()) return PATHS.TREE_SITTER_ASSETS_DIR\n try {\n const pkgPath = require.resolve(\"tree-sitter-wasms/package.json\")\n return path.join(path.dirname(pkgPath), \"out\")\n } catch {\n return null\n }\n}\n\n/**\n * web-tree-sitter normally resolves this sidecar relative to its JS module.\n * Prefer the durable copy, but only under the same all-present gate the\n * grammars use, so the runtime and the grammars always come from one install.\n */\nfunction parserInitOptions(): Parameters<typeof Parser.init>[0] | undefined {\n if (!stableTreeSitterAssetsComplete()) return undefined\n return {\n locateFile: () =>\n path.join(PATHS.TREE_SITTER_ASSETS_DIR, TREE_SITTER_RUNTIME_FILE),\n }\n}\n\n/**\n * Pre-load all grammars at module-init time so the first search\n * doesn't pay a ~500ms cold-start cost. The Promise is captured at\n * import time and awaited per-call; per-grammar failures are caught\n * individually so one broken grammar can't take the whole tool down.\n */\nexport function getGrammarBundle(): GrammarBundle {\n if (_grammarBundle) return _grammarBundle\n const ready = (async (): Promise<Map<string, Language>> => {\n const out = new Map<string, Language>()\n try {\n await Parser.init(parserInitOptions())\n } catch (err) {\n consola.warn(\n `[code_search] tree-sitter Parser.init failed; structural ranking disabled: ${(err as Error).message}`,\n )\n return out\n }\n const root = resolveGrammarRoot()\n if (!root) {\n consola.warn(\n \"[code_search] tree-sitter-wasms package not resolvable; structural ranking disabled\",\n )\n return out\n }\n for (const [key, filename] of Object.entries(GRAMMAR_FILES)) {\n const wasmPath = path.join(root, filename)\n try {\n const lang = await Language.load(wasmPath)\n out.set(key, lang)\n } catch (err) {\n consola.warn(\n `[code_search] failed to load tree-sitter grammar '${key}' from ${filename}: ${(err as Error).message}`,\n )\n }\n }\n return out\n })()\n _grammarBundle = { ready }\n return _grammarBundle\n}\n\n// Kick off grammar pre-load at module import time. The brief calls\n// this out explicitly: amortize the WASM init cost across module load\n// rather than the first search call.\nvoid getGrammarBundle().ready.catch(() => {\n /* errors already logged per-grammar */\n})\n\n// ============================================================\n// File outline (full structural definition tree)\n// ============================================================\n\n/**\n * Robustness bound on outline entries per file. Normal source is far\n * under it; generated/pathological files hit it and `outlineFile` then\n * sets a `notice` so the model knows the map was truncated.\n */\nconst MAX_OUTLINE_ENTRIES = 1000\n\nexport interface FileOutlineEntry {\n kind: string\n name: string\n line: number\n /** Definition nesting depth: 0 = top-level, 1 = member of a top-level\n * definition (e.g. a class method), 2 = nested inside that, … */\n depth: number\n}\n\nexport interface FileOutlineResult {\n outline: Array<FileOutlineEntry>\n language: string | null\n notice?: string\n}\n\n/**\n * First identifier-typed named child found in a pre-order walk. Mirrors\n * the structural-pass helper in `code-search.ts` (kept local here so\n * the grammar module has no dependency back on the ranking layer).\n */\nfunction firstIdentifierLeaf(\n node: Node,\n): Node | null {\n if (IDENTIFIER_NODE_TYPES.has(node.type)) return node\n for (const child of node.namedChildren) {\n // web-tree-sitter 0.25 types `namedChildren` as `(Node | null)[]`.\n if (child === null) continue\n const r = firstIdentifierLeaf(child)\n if (r) return r\n }\n return null\n}\n\n/**\n * Derive a human-readable name for a definition node. Tries the\n * grammar's standard `name` field first, then the `declarator` /\n * `type` fields (C/C++/Java declarators, Rust/Go type specs), then any\n * identifier-typed named child as a last resort. Returns `null` when no\n * name can be recovered — the caller skips such nodes.\n */\nfunction deriveDefinitionName(node: Node): string | null {\n const nameField = node.childForFieldName(\"name\")\n if (nameField && nameField.text.length > 0) return nameField.text\n\n const declarator = node.childForFieldName(\"declarator\")\n if (declarator) {\n const leaf = firstIdentifierLeaf(declarator)\n if (leaf && leaf.text.length > 0) return leaf.text\n }\n\n const typeField = node.childForFieldName(\"type\")\n if (typeField) {\n const leaf = firstIdentifierLeaf(typeField)\n if (leaf && leaf.text.length > 0) return leaf.text\n }\n\n // Scoped positional fallback: the first declarator's identifier.\n // Catches field-like shapes with no name field at all (C#\n // `field_declaration` / `event_field_declaration`). Scoped to the\n // declarator (not the whole subtree) for two reasons: leading attributes\n // live outside it, and qualified TYPE annotations (`System.EventHandler`)\n // precede the declarator and contain their own identifiers — a whole-\n // subtree first-leaf would return the type's name instead of the field's.\n // Nodes without a declarator fall through to the generic fallback below,\n // so existing languages are unaffected (their name/declarator/type paths\n // already returned above).\n const scoped = firstDeclaratorLeaf(node)\n if (scoped && scoped.text.length > 0) return scoped.text\n\n // Fall back to the first identifier-typed named child anywhere in the\n // subtree (handles grammars that don't expose a `name` field for a\n // given definition shape).\n const fallback = firstIdentifierLeaf(node)\n if (fallback && fallback.text.length > 0) return fallback.text\n\n return null\n}\n\n/**\n * First identifier leaf of the first `variable_declarator` under the first\n * `variable_declaration` child, or null when the shape is absent. Used for\n * field-like definition shapes with no `name` field (C# fields/events):\n * restricting the walk to the declarator skips both leading attributes and\n * the type annotation, either of which can contain identifiers that precede\n * the declared name (`[Attr] System.EventHandler Changed;` must resolve to\n * `Changed`, not `Attr` or `System`).\n *\n * Only the FIRST declarator is considered (`int a = 1, b = 2` confirms `a`\n * alone) — incomplete but never wrong, matching the `role` contract.\n */\nfunction firstDeclaratorLeaf(defNode: Node): Node | null {\n for (const child of defNode.namedChildren) {\n // web-tree-sitter 0.25 types `namedChildren` as `(Node | null)[]`.\n if (child === null || child.type !== \"variable_declaration\") continue\n for (const decl of child.namedChildren) {\n if (decl === null || decl.type !== \"variable_declarator\") continue\n // The declarator's own name textually precedes any initializer, so\n // its first identifier leaf IS the declared name.\n return firstIdentifierLeaf(decl)\n }\n }\n return null\n}\n\n/**\n * Collect declarations that help a model navigate a file: top-level symbols\n * and members of class-like containers. Function-local variables and nested\n * helpers are deliberately omitted because they inflate the summary without\n * identifying useful read targets. Non-definition wrappers (exports,\n * decorators, templates) preserve the surrounding depth.\n */\nconst OUTLINE_MEMBER_CONTAINERS = new Set([\n \"class_declaration\",\n \"class_definition\",\n \"class_specifier\",\n \"interface_declaration\",\n \"annotation_type_declaration\",\n \"impl_item\",\n \"trait_item\",\n \"struct_item\",\n \"struct_declaration\",\n \"record_declaration\",\n \"record_struct_declaration\",\n \"namespace_definition\",\n \"namespace_declaration\",\n \"file_scoped_namespace_declaration\",\n \"module\",\n])\n\n/**\n * One navigable definition with its live AST node. The node is BORROWED —\n * callers must not `.delete()` it and must use it before the owning tree\n * is freed. Used by the outline builder (names + lines) and the semantic\n * unit pipeline (full ranges + source text).\n */\nexport interface UnitNode {\n node: Node\n kind: string\n name: string\n depth: number\n}\n\n/**\n * Walk collecting navigable definitions: top-level symbols plus members of\n * class-like containers. Function-local variables and nested helpers are\n * deliberately excluded (see OUTLINE_MEMBER_CONTAINERS). Pure walk — no\n * read / parse / delete. Never throws (per-node failures skip the node).\n */\nexport function collectUnitNodes(\n root: Node,\n defTypes: ReadonlySet<string>,\n signal?: AbortSignal,\n): Array<UnitNode> {\n const out: Array<UnitNode> = []\n\n const visit = (\n node: Node,\n depth: number,\n includeDefinitions: boolean,\n ): void => {\n if (signal?.aborted || out.length >= MAX_OUTLINE_ENTRIES) return\n for (const child of node.namedChildren) {\n if (signal?.aborted || out.length >= MAX_OUTLINE_ENTRIES) return\n // web-tree-sitter 0.25 types `namedChildren` as `(Node | null)[]`.\n if (child === null) continue\n if (defTypes.has(child.type)) {\n if (includeDefinitions) {\n const name = deriveDefinitionName(child)\n if (name !== null) {\n out.push({ node: child, kind: child.type, name, depth })\n }\n }\n // Only class-like definitions expose navigable members. Do not walk a\n // function body and accidentally publish every local declarator.\n if (includeDefinitions && OUTLINE_MEMBER_CONTAINERS.has(child.type)) {\n visit(child, depth + 1, true)\n }\n continue\n }\n visit(child, depth, includeDefinitions)\n }\n }\n\n visit(root, 0, true)\n return out\n}\n\nfunction collectDefinitions(\n root: Node,\n defTypes: ReadonlySet<string>,\n signal?: AbortSignal,\n): Array<FileOutlineEntry> {\n return collectUnitNodes(root, defTypes, signal).map((u) => ({\n kind: u.kind,\n name: u.name,\n line: u.node.startPosition.row + 1,\n depth: u.depth,\n }))\n}\n\n/**\n * Build a `FileOutlineResult` from an ALREADY-PARSED tree — walk-only,\n * no read / parse / `delete`. The tree's ownership stays with the caller\n * (e.g. the code-search structural pass's `_treeCache`), so this lets the\n * outline step REUSE a tree the structural pass already parsed instead of\n * re-reading + re-parsing the file. Never throws.\n */\nexport function outlineFromTree(\n tree: Tree,\n language: string,\n signal?: AbortSignal,\n): FileOutlineResult {\n if (signal?.aborted) return { outline: [], language }\n const defTypes = DEFINITION_NODE_TYPES[language]\n if (!defTypes) {\n return { outline: [], language, notice: \"outline unavailable (parse error)\" }\n }\n try {\n const outline = collectDefinitions(tree.rootNode, defTypes, signal)\n if (signal?.aborted) return { outline: [], language }\n // Order by line ascending. The walk is pre-order (parent before\n // child), and JS sort is stable, so a parent and its same-line first\n // member keep parent-first order.\n outline.sort((a, b) => a.line - b.line)\n if (outline.length >= MAX_OUTLINE_ENTRIES) {\n return {\n outline,\n language,\n notice: `outline truncated at ${MAX_OUTLINE_ENTRIES} symbols (very large file)`,\n }\n }\n return { outline, language }\n } catch {\n return { outline: [], language, notice: \"outline unavailable (parse error)\" }\n }\n}\n\n// ============================================================\n// Structural definition-site confirmation (shared walk)\n// ============================================================\n//\n// This is the AST-confirmation walk the `code_search` structural pass runs\n// over each parsed file. It lived in `code-search.ts` originally; it moved\n// here so that BOTH the in-process structural pass AND the worker-thread parse\n// pool (`tree-sitter-pool/`) call the SAME implementation over a borrowed\n// `Tree`, guaranteeing byte-identical confirmed-index sets regardless of which\n// path produced them (the load-bearing determinism requirement). Pure: it\n// borrows the tree, never `.delete()`s it, never reads/parses.\n\n/** One matched hit to AST-confirm: line is 1-indexed (ripgrep), match\n * start/end are byte offsets within the matched line. */\nexport interface StructuralHit {\n line: number\n matchStart: number\n matchEnd: number\n}\n\n/**\n * Compute the absolute byte offset where line `lineNumber1` starts in\n * `source`. Lines are counted by LF; CRLF files have the same line starts as\n * LF files (the \\r is part of the previous line's content). 1-indexed to match\n * ripgrep. Returns -1 if the line is past EOF.\n */\nfunction lineStartByte(source: string, lineNumber1: number): number {\n if (lineNumber1 <= 1) return 0\n let line = 1\n for (let i = 0; i < source.length; i++) {\n if (source.charCodeAt(i) === 0x0a /* \\n */) {\n line += 1\n if (line === lineNumber1) return i + 1\n }\n }\n return -1\n}\n\nfunction containsByteRange(\n outer: Node,\n inner: Node,\n): boolean {\n return outer.startIndex <= inner.startIndex && outer.endIndex >= inner.endIndex\n}\n\n/**\n * Walk up from a matched identifier node looking for the closest\n * definition-shape ancestor (per the language's allowed types). When found,\n * verify the matched identifier is at the definition's \"name\" slot — NOT inside\n * a parameter type, a body, or a parent's signature. Returns true iff this is a\n * real definition site for the identifier the rg submatch landed on. Depth\n * bound 6 — definition names sit close to their definition node in every\n * supported grammar; deeper walks risk false positives.\n */\nfunction isDefiningSite(\n matchedNode: Node,\n langKey: string,\n): boolean {\n const defTypes = DEFINITION_NODE_TYPES[langKey]\n if (!defTypes) return false\n let cur: Node | null = matchedNode.parent\n let depth = 0\n while (cur && depth < 6) {\n if (defTypes.has(cur.type)) {\n const nameField = cur.childForFieldName(\"name\")\n if (nameField && containsByteRange(nameField, matchedNode)) {\n return true\n }\n const declarator = cur.childForFieldName(\"declarator\")\n if (declarator && containsByteRange(declarator, matchedNode)) {\n const first = firstIdentifierLeaf(declarator)\n if (first && first.startIndex === matchedNode.startIndex) {\n return true\n }\n }\n const typeField = cur.childForFieldName(\"type\")\n if (typeField && containsByteRange(typeField, matchedNode)) {\n const first = firstIdentifierLeaf(typeField)\n if (first && first.startIndex === matchedNode.startIndex) {\n return true\n }\n }\n // Positional fallback for field-like shapes with no name slot\n // (see FIRST_LEAF_DEFINITION_TYPES): the match is a definition iff\n // it IS the declarator identifier. The helper skips attributes and\n // the type annotation, so neither can false-positive here.\n const firstLeafTypes = FIRST_LEAF_DEFINITION_TYPES[langKey]\n if (firstLeafTypes?.has(cur.type)) {\n const first = firstDeclaratorLeaf(cur)\n if (first && first.startIndex === matchedNode.startIndex) {\n return true\n }\n }\n }\n cur = cur.parent\n depth += 1\n }\n return false\n}\n\n/**\n * Run the AST-confirmation walk over `hits` against an ALREADY-PARSED tree.\n * Returns the subset of input indices whose matched identifier is at a real\n * definition site. Borrowed tree — never deleted. Pure + deterministic: the\n * output set is a function of (tree, source, hits) only, independent of call\n * order, so the in-process path and the worker path return identical sets.\n *\n * Never throws — a per-hit walk failure just omits that index (matches the\n * in-process pass's per-hit try/catch). `signal` short-circuits between hits.\n */\nexport function confirmDefinitionSites(\n tree: Tree,\n source: string,\n language: string,\n hits: ReadonlyArray<StructuralHit>,\n signal?: AbortSignal,\n): Array<number> {\n const confirmed: Array<number> = []\n if (!DEFINITION_NODE_TYPES[language]) return confirmed\n for (let i = 0; i < hits.length; i++) {\n if (signal?.aborted) break\n const hit = hits[i]\n const lineStart = lineStartByte(source, hit.line)\n if (lineStart < 0) continue\n const matchByteStart = lineStart + hit.matchStart\n const matchByteEnd = lineStart + hit.matchEnd\n let node: Node | null\n try {\n node = tree.rootNode.descendantForIndex(matchByteStart, matchByteEnd)\n } catch {\n node = null\n }\n if (!node) continue\n // Climb to the nearest identifier-typed node, since descendantForIndex may\n // land on a parent for off-by-one byte ranges in CRLF files.\n if (!IDENTIFIER_NODE_TYPES.has(node.type)) {\n let cur: Node | null = node\n let depth = 0\n while (cur && !IDENTIFIER_NODE_TYPES.has(cur.type) && depth < 3) {\n const leaf = firstIdentifierLeaf(cur)\n if (leaf && leaf.startIndex === matchByteStart) {\n cur = leaf\n break\n }\n cur = cur.parent\n depth += 1\n }\n node = cur\n }\n if (!node || !IDENTIFIER_NODE_TYPES.has(node.type)) continue\n if (isDefiningSite(node, language)) confirmed.push(i)\n }\n return confirmed\n}\n\n/**\n * Navigational structural outline of a single file: top-level declarations\n * plus class-like members (methods, fields, interface members), excluding\n * function-local variables and nested implementation helpers. Each entry\n * carries a `depth` (0 = top-level). Reuses the\n * shared grammar bundle and the same `Parser` the structural pass uses\n * — no second `Parser.init()`.\n *\n * Never throws. The failure modes are surfaced as `notice` strings with\n * an empty `outline`:\n * - unsupported file type → `language: null`, \"no structural outline\n * for this file type\"\n * - file larger than the 1 MiB parse cap → `language` set, \"file too\n * large for structural outline\"\n * - any parse error / grammar-load miss → `language` set, \"outline\n * unavailable (parse error)\"\n *\n * Honors `signal`: bails cleanly (empty outline, no notice) when the\n * caller aborts before/while parsing.\n */\nexport async function outlineFile(\n absPath: string,\n signal?: AbortSignal,\n): Promise<FileOutlineResult> {\n if (signal?.aborted) return { outline: [], language: null }\n\n // 1. Language detection. Unsupported types never reach the parser.\n const language = getLanguageKeyForPath(absPath)\n if (!language) {\n return {\n outline: [],\n language: null,\n notice: \"no structural outline for this file type\",\n }\n }\n\n // 2. Size gate. Bigger than the parse cap → skip (almost always\n // generated / vendored code).\n let size: number\n try {\n size = statSync(absPath).size\n } catch {\n return { outline: [], language, notice: \"outline unavailable (parse error)\" }\n }\n if (size > STRUCTURAL_MAX_FILE_BYTES) {\n return {\n outline: [],\n language,\n notice: \"file too large for structural outline\",\n }\n }\n\n if (signal?.aborted) return { outline: [], language }\n\n // 3. Grammar load. A missing grammar (init failure, prune) degrades\n // gracefully to the parse-error notice rather than throwing.\n const grammars = await getGrammarBundle().ready\n if (signal?.aborted) return { outline: [], language }\n const lang = grammars.get(language)\n if (!lang) {\n return { outline: [], language, notice: \"outline unavailable (parse error)\" }\n }\n\n const defTypes = DEFINITION_NODE_TYPES[language]\n if (!defTypes) {\n return { outline: [], language, notice: \"outline unavailable (parse error)\" }\n }\n\n // 4. Read + parse + walk. Any failure → parse-error notice, never a\n // throw. The Parser and Tree are freed in `finally` so native\n // memory doesn't leak (outlineFile doesn't share the structural\n // pass's tree cache).\n let source: string\n try {\n source = await readFile(absPath, \"utf8\")\n } catch {\n return { outline: [], language, notice: \"outline unavailable (parse error)\" }\n }\n\n if (signal?.aborted) return { outline: [], language }\n\n let parser: Parser | null = null\n let tree: Tree | null = null\n try {\n parser = new Parser()\n parser.setLanguage(lang)\n tree = parser.parse(source)\n if (!tree) {\n return { outline: [], language, notice: \"outline unavailable (parse error)\" }\n }\n // Walk the freshly-parsed tree (the `finally` below frees it).\n return outlineFromTree(tree, language, signal)\n } catch {\n return { outline: [], language, notice: \"outline unavailable (parse error)\" }\n } finally {\n if (tree) {\n try {\n tree.delete()\n } catch {\n // already collected\n }\n }\n if (parser) {\n try {\n parser.delete()\n } catch {\n // already collected\n }\n }\n }\n}\n","/**\n * Warm `worker_threads` pool that parallelizes the synchronous web-tree-sitter\n * parses the `code_search` structural pass would otherwise serialize on the one\n * module-global WASM heap.\n *\n * Decision + measured evidence: `docs/research/tree-sitter-parallelism.md`\n * (\"Phase 2 decision\"). Reproduce the benchmark with\n * `GH_ROUTER_BENCH_STRUCTURAL=1 BENCH_SPREAD=1 bun\n * scripts/bench-code-search-parallelism.ts`.\n *\n * Load-bearing properties (each has a test in tests/tree-sitter-pool.test.ts):\n *\n * - DETERMINISM: the merge is order-independent. Confirmed hits land in a\n * `Set<number>`; outlines are keyed by file and each file's entries are\n * line-sorted worker-side. The caller assembles output in RESULT order, not\n * worker-completion order. So which worker finishes first cannot change the\n * bytes (the 5-run determinism test stays green).\n * - ABORT: `signal` stops dispatch and posts `cancel` to busy workers; the\n * pass resolves with whatever confirmed pre-abort (a partial Set is valid).\n * - ERROR ISOLATION: a worker `error`/`exit`/`{ok:false}` marks that file a\n * MISS (kept on the regex heuristic / empty outline) and the worker is\n * retired + lazily respawned. A TOTAL pool failure makes `parseFiles`\n * return `null`, and the caller falls back to the in-process path — so\n * Lever 2 can fail completely and `code_search` still returns correct\n * (just less precisely ranked) results.\n * - NEVER ORPHAN: workers are `unref()`-ed (never keep the process alive) and\n * a synchronous `process.once(\"exit\")` sweep `terminate()`s them all. (We\n * deliberately do NOT add SIGINT/SIGTERM listeners — they'd compete with the\n * worker-agent lifecycle handlers; the `exit` sweep fires on every exit\n * path, and unref()-ed workers die with the process regardless.)\n * - BUDGET: a budget/abort drops this call's still-QUEUED jobs (resolving\n * their promises as misses) so `parseFiles` returns at the deadline instead\n * of waiting on jobs that won't be dispatched in time. In-flight jobs finish\n * naturally (sub-50ms per file) and their post-deadline results are\n * discarded by the `stopped` flag.\n *\n * Windows: `worker_threads` + WASM is cross-platform; `worker.terminate()` is\n * the teardown (no child process → no taskkill/PATHEXT). Must be proven green\n * on windows-latest CI (the project's Windows-first gate).\n */\n\nimport { existsSync } from \"node:fs\"\nimport * as os from \"node:os\"\nimport { dirname, join } from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport { Worker } from \"node:worker_threads\"\n\nimport consola from \"consola\"\n\nimport type { FileOutlineEntry, StructuralHit } from \"~/lib/tree-sitter-grammars\"\nimport type {\n ParseJobReply,\n ParseJobRequest,\n WorkerToMain,\n} from \"~/lib/tree-sitter-pool/protocol\"\n\n/**\n * Max time to wait for a freshly-spawned worker to post `ready` (Parser.init +\n * grammar load). A worker that never readies (grammar-load hang, bad layout)\n * must not wedge the spawn promise forever — on timeout we terminate it and\n * treat the spawn as failed, so the pool degrades to fewer workers / the\n * in-process path rather than hanging every search.\n */\nconst READY_TIMEOUT_MS = 10_000\n\n/**\n * After this many cumulative worker deaths, retire the pool permanently\n * (`spawnFailed = true`) and force the in-process path. Guards against a\n * crash-storm — a corrupt grammar that traps on every parse — churning\n * spawn→crash without bound. The threshold is generous (occasional WASM OOM on\n * a pathological file is fine) but finite.\n */\nconst MAX_CRASHES = 50\n\n/** Per-file work the pool dispatches. `file` is the relative key the caller\n * uses to reassemble results in result order. */\nexport interface PoolJob {\n file: string\n absPath: string\n language: string\n mtimeMs: number\n /** Confirm-hit list; the returned indexes are positions into THIS array. */\n confirmHits: Array<StructuralHit>\n /** Whether to also compute the outline for this file. */\n outline: boolean\n}\n\nexport interface PoolFileResult {\n confirmedHitIndexes: Array<number>\n outlineEntries?: Array<FileOutlineEntry>\n ok: boolean\n}\n\nexport interface PoolRunResult {\n /** file → result. Files whose result arrived after the budget timer (or that\n * errored) are absent → the caller treats them as misses. */\n byFile: Map<string, PoolFileResult>\n /** True iff the wall-clock budget fired before all jobs completed. */\n budgetHit: boolean\n}\n\n/**\n * Pool size: `max(1, min(4, cpus-2))`. Cap 4 — the parse work per call is small\n * and bounded, each worker holds a full WASM heap + grammars (memory), and the\n * MCP layer already caps concurrent tool calls at 8, so a per-call pool of 4\n * across 8 concurrent `code` calls already oversubscribes cores. On a 1–2 core\n * box this degrades to a single worker (still better than nothing: parse CPU\n * moves off the main event loop). Override via `GH_ROUTER_TS_POOL_SIZE`.\n */\nfunction computePoolSize(): number {\n const env = process.env.GH_ROUTER_TS_POOL_SIZE\n if (env) {\n const n = Number(env)\n if (Number.isInteger(n) && n >= 1 && n <= 16) return n\n }\n let cpus: number\n try {\n cpus = os.cpus().length\n } catch {\n cpus = 1\n }\n return Math.max(1, Math.min(4, cpus - 2))\n}\n\ninterface PooledWorker {\n worker: Worker\n /** True once the worker posted `ready`. */\n ready: boolean\n /** Grammar keys this worker loaded; empty → useless, retire it. */\n loaded: Set<string>\n /** The job id currently dispatched to this worker, or null if idle. */\n busyJobId: number | null\n}\n\n/** One queued unit of work + the callback that routes its reply back to the\n * `parseFiles` caller that enqueued it. `null` reply = worker died. */\ninterface QueuedJob {\n id: number\n req: ParseJobRequest\n done: (reply: ParseJobReply | null) => void\n /** True once this job has been retried after a worker death (retry once). */\n retried: boolean\n}\n\nclass TreeSitterPool {\n private workers: Array<PooledWorker> = []\n private readonly size: number\n private readonly workerPath: string | null\n private nextJobId = 1\n private spawnFailed = false\n private shuttingDown = false\n private ensuring: Promise<number> | null = null\n /** Count of worker deaths. After too many (a crash storm — e.g. a corrupt\n * grammar that traps the WASM heap on every parse), give up on the pool\n * entirely and force the in-process path, rather than churning spawn→crash\n * forever. */\n private crashCount = 0\n private workersSpawned = 0\n\n /** Test-only observability for crash/respawn assertions. */\n __workerLifecycleForTest(): { crashes: number; spawned: number } {\n return { crashes: this.crashCount, spawned: this.workersSpawned }\n }\n\n /**\n * Launch-time latency optimization: ready ONE worker and its grammar bundle.\n * A single worker keeps startup CPU/memory bounded while removing the first\n * query's initialization wait; normal demand still grows the pool lazily.\n */\n async warm(): Promise<boolean> {\n return (await this.ensureWorkers(1)) > 0\n }\n\n // ---- Central scheduler state (shared across ALL concurrent parseFiles\n // calls). A worker is leased to exactly one job at a time; replies route by\n // job id. This is what makes concurrent `code` searches safe: without a\n // single arbiter, two searches would dispatch to the same worker and clobber\n // each other's pending-reply state → deadlock. ----\n private readonly queue: Array<QueuedJob> = []\n private readonly inflight = new Map<number, QueuedJob>()\n\n constructor() {\n this.size = computePoolSize()\n this.workerPath = resolveWorkerPath()\n }\n\n /** True when the pool can never produce workers (no worker script found). */\n get unavailable(): boolean {\n return this.workerPath === null || this.spawnFailed\n }\n\n /** Lazily spawn up to `size` workers and await their `ready` signals. Safe to\n * call repeatedly; respawns workers retired by crashes. Coalesces concurrent\n * callers onto one in-flight ensure so 8 simultaneous searches don't each\n * spawn a fresh batch. Returns the live worker count (0 → caller must fall\n * back to the in-process path). */\n private ensureWorkers(target = this.size): Promise<number> {\n if (this.unavailable || this.shuttingDown) return Promise.resolve(0)\n const desired = Math.max(1, Math.min(target, this.size))\n const liveNow = this.workers.filter((w) => w.ready && w.loaded.size > 0).length\n if (liveNow >= desired) return Promise.resolve(liveNow)\n if (this.ensuring) {\n // An already-ready worker can serve this query while the pool expands.\n // A truly cold caller still waits for the coalesced ready handshake.\n return liveNow > 0 ? Promise.resolve(liveNow) : this.ensuring\n }\n this.ensuring = this.doEnsureWorkers(desired).finally(() => {\n this.ensuring = null\n })\n // Launch warm-up readies one worker. Do not make the first query wait while\n // the remaining width fills; doEnsureWorkers pumps queued work when ready.\n return liveNow > 0 ? Promise.resolve(liveNow) : this.ensuring\n }\n\n private async doEnsureWorkers(target: number): Promise<number> {\n const need = target - this.workers.length\n const spawns: Array<Promise<PooledWorker | null>> = []\n for (let i = 0; i < need; i++) spawns.push(this.spawnWorker())\n const spawned = await Promise.all(spawns)\n let added = 0\n for (const w of spawned) {\n if (w && w.ready && w.loaded.size > 0) {\n this.workers.push(w)\n added += 1\n }\n }\n const total = this.workers.filter((w) => w.ready && w.loaded.size > 0).length\n if (total === 0 && need > 0) {\n // Every spawn attempt produced a useless/dead worker.\n this.spawnFailed = true\n }\n if (added > 0) this.pump() // newly-ready workers pull queued jobs\n return total\n }\n\n private spawnWorker(): Promise<PooledWorker | null> {\n if (!this.workerPath) return Promise.resolve(null)\n return new Promise((resolve) => {\n let settled = false\n let worker: Worker\n try {\n worker = new Worker(this.workerPath!)\n this.workersSpawned += 1\n } catch (err) {\n consola.debug(\n `[code_search] tree-sitter worker spawn failed: ${(err as Error).message}`,\n )\n resolve(null)\n return\n }\n // unref so the pool never keeps the process alive on its own.\n worker.unref()\n const pw: PooledWorker = {\n worker,\n ready: false,\n loaded: new Set(),\n busyJobId: null,\n }\n // Bound the ready handshake: a worker that spawns but never posts `ready`\n // (e.g. a grammar-load hang) must NOT wedge the spawn promise forever —\n // that would hang `ensureWorkers` and every `parseFiles` awaiting it.\n const readyTimer = setTimeout(() => {\n if (!settled) {\n settled = true\n try {\n void worker.terminate()\n } catch {\n // best effort\n }\n resolve(null)\n }\n }, READY_TIMEOUT_MS)\n readyTimer.unref?.()\n const onError = (err: Error): void => {\n consola.debug(`[code_search] tree-sitter worker error: ${err.message}`)\n this.retire(pw)\n if (!settled) {\n settled = true\n clearTimeout(readyTimer)\n resolve(null)\n }\n }\n const onExit = (): void => {\n this.retire(pw)\n if (!settled) {\n settled = true\n clearTimeout(readyTimer)\n resolve(null)\n }\n }\n worker.on(\"error\", onError)\n worker.on(\"exit\", onExit)\n worker.on(\"message\", (msg: WorkerToMain) => {\n if (\"type\" in msg && msg.type === \"ready\") {\n pw.ready = true\n pw.loaded = new Set(msg.loaded)\n if (!settled) {\n settled = true\n clearTimeout(readyTimer)\n resolve(pw)\n }\n return\n }\n // A job reply → route it to the owning queued job and free the worker.\n const reply = msg as ParseJobReply\n this.completeJob(pw, reply.id, reply)\n })\n })\n }\n\n /** Finish the job `id` that `pw` was running: route the reply, free the\n * worker, and pump the next queued job. `reply === null` means the worker\n * died (the job is routed null → requeued once or degraded by the caller). */\n private completeJob(pw: PooledWorker, id: number, reply: ParseJobReply | null): void {\n const job = this.inflight.get(id)\n if (!job || pw.busyJobId !== id) {\n // Stale/duplicate reply (already completed via retire) — ignore.\n return\n }\n this.inflight.delete(id)\n pw.busyJobId = null\n job.done(reply)\n this.pump()\n }\n\n private retire(pw: PooledWorker): void {\n // Fail the worker's in-flight job (if any) so its caller doesn't hang.\n if (pw.busyJobId !== null) {\n const id = pw.busyJobId\n pw.busyJobId = null\n const job = this.inflight.get(id)\n if (job) {\n this.inflight.delete(id)\n job.done(null)\n }\n }\n pw.ready = false\n pw.loaded = new Set()\n try {\n void pw.worker.terminate()\n } catch {\n // best effort\n }\n this.workers = this.workers.filter((w) => w !== pw)\n // Crash-storm guard: after MAX_CRASHES deaths, retire the pool permanently.\n // Set BEFORE pump() so pump drains the queue instead of respawning again.\n this.crashCount += 1\n if (this.crashCount >= MAX_CRASHES) this.spawnFailed = true\n // Other searches may have queued work that a surviving worker can take\n // (or, if spawnFailed just tripped, pump drains the queue as misses).\n this.pump()\n }\n\n /** Hand queued jobs to idle ready workers, one per worker. Called whenever a\n * worker frees up, a new worker readies, or jobs are enqueued. If the queue\n * is non-empty but no worker can ever serve it (all dead), it triggers a\n * respawn; if respawn yields nothing, the stranded jobs are failed as misses\n * so their `parseFiles` callers don't hang forever. */\n private pump(): void {\n if (this.shuttingDown) return\n for (const pw of this.workers) {\n if (this.queue.length === 0) break\n if (!pw.ready || pw.loaded.size === 0 || pw.busyJobId !== null) continue\n const job = this.queue.shift()\n if (!job) break\n pw.busyJobId = job.id\n this.inflight.set(job.id, job)\n const injectCrash = _testCrashOnceArmed\n // Send an EPHEMERAL crash-flagged copy — never mutate `job.req` in place,\n // or a post-crash retry of the SAME job would still carry `testCrash` and\n // crash again (a crash loop, not a one-shot). The retry re-posts the\n // original unflagged `job.req` and succeeds, so recovery is genuine.\n const reqToPost = injectCrash ? { ...job.req, testCrash: true } : job.req\n try {\n pw.worker.postMessage(reqToPost)\n if (injectCrash) _testCrashOnceArmed = false\n } catch (err) {\n // postMessage failed → treat as a worker death for this job.\n consola.debug(\n `[code_search] tree-sitter worker postMessage failed: ${(err as Error).message}`,\n )\n this.inflight.delete(job.id)\n pw.busyJobId = null\n job.done(null)\n }\n }\n\n // Jobs still queued with no live worker to take them: a crash retired every\n // worker mid-call. Try to respawn (recovery); if that produces no usable\n // worker, drain the stranded queue as misses so no caller hangs.\n if (this.queue.length > 0) {\n const liveOrBusy = this.workers.some((w) => w.ready && w.loaded.size > 0)\n if (!liveOrBusy && !this.ensuring && !this.spawnFailed && !this.shuttingDown) {\n void this.ensureWorkers().then((live) => {\n if (live === 0) this.drainQueue()\n // else: doEnsureWorkers calls pump() on success, draining the queue\n // onto the new workers.\n })\n } else if (this.spawnFailed && !liveOrBusy) {\n // Pool permanently failed AND no worker can serve the queue → drain.\n // The `!liveOrBusy` gate is load-bearing: a sticky `spawnFailed` must\n // NOT drain jobs a still-live worker could process.\n this.drainQueue()\n }\n }\n }\n\n /** Fail every queued job as a miss (null). Used when no worker can serve\n * them. In-flight jobs are handled by `retire` when their worker dies. */\n private drainQueue(): void {\n while (this.queue.length > 0) {\n const job = this.queue.shift()\n job?.done(null)\n }\n }\n\n /** Enqueue one job; resolves with its reply (or null on worker death). When\n * the pool is shutting down, resolve immediately as a miss so a retry after\n * shutdown can't push a job that `pump()` (early-returns while shutting down)\n * would never dispatch → caller hangs. */\n private enqueue(req: ParseJobRequest, retried: boolean): Promise<ParseJobReply | null> {\n if (this.shuttingDown) return Promise.resolve(null)\n return new Promise((resolve) => {\n this.queue.push({ id: req.id, req, done: resolve, retried })\n this.pump()\n })\n }\n\n /** Remove every still-queued (not-yet-dispatched) job whose id is in `ids`\n * and resolve it as a miss. Used by budget/abort so `parseFiles` doesn't wait\n * on jobs that will never be dispatched before the deadline. In-flight jobs\n * (already posted to a worker) are NOT touched — they resolve when the worker\n * replies or dies; `stopped` makes `dispatchFile` discard their result. */\n private cancelQueued(ids: Set<number>): void {\n if (this.queue.length === 0) return\n const remaining: Array<QueuedJob> = []\n const drained: Array<QueuedJob> = []\n for (const job of this.queue) {\n if (ids.has(job.id)) drained.push(job)\n else remaining.push(job)\n }\n if (drained.length === 0) return\n this.queue.length = 0\n this.queue.push(...remaining)\n for (const job of drained) job.done(null)\n }\n\n /**\n * Parse all `jobs` across the pool, racing a `budgetMs` wall-clock timer.\n * Returns `null` if the pool is unavailable / failed as a whole (caller falls\n * back in-process). Order-independent: the returned `byFile` map is keyed by\n * file, so the caller reassembles deterministically regardless of which\n * worker (or which concurrent search) finished first.\n *\n * Concurrency-safe: jobs from every concurrent `parseFiles` call feed ONE\n * shared queue and workers are leased atomically, so two searches never\n * clobber each other's in-flight worker state.\n */\n async parseFiles(\n jobs: Array<PoolJob>,\n opts: { budgetMs: number; signal: AbortSignal },\n ): Promise<PoolRunResult | null> {\n if (jobs.length === 0) return { byFile: new Map(), budgetHit: false }\n if (opts.signal.aborted) return { byFile: new Map(), budgetHit: false }\n\n const byFile = new Map<string, PoolFileResult>()\n let budgetHit = false\n let stopped = false\n // Track job ids THIS call owns so abort/budget cancel only OUR queued jobs\n // and our busy workers, never another concurrent search's.\n const myJobIds = new Set<number>()\n\n // Register abort handling BEFORE awaiting ensureWorkers so an abort during\n // worker spawn is observed before any jobs are queued. The await itself is\n // bounded by READY_TIMEOUT_MS. Worker and grammar initialization deliberately\n // happen before the parse timer starts, so a cold pool cannot consume a\n // user's structural-analysis budget without parsing a file.\n const stop = (): void => {\n stopped = true\n // Drop our still-queued jobs so their enqueue() promises resolve (else\n // Promise.all below waits on jobs that will never be dispatched in time).\n this.cancelQueued(myJobIds)\n // Ask workers currently running OUR jobs to cancel; they reply with\n // whatever they have. (Note: the worker's parse loop is synchronous, so\n // this only takes effect between files — best-effort, not preemptive.)\n for (const pw of this.workers) {\n if (pw.busyJobId !== null && myJobIds.has(pw.busyJobId)) {\n try {\n pw.worker.postMessage({ type: \"cancel\" })\n } catch {\n // ignore\n }\n }\n }\n }\n const onAbort = (): void => stop()\n if (opts.signal.aborted) {\n // Already aborted (caught above for the empty-jobs fast path, but a signal\n // can flip between that check and here).\n return { byFile, budgetHit: false }\n }\n opts.signal.addEventListener(\"abort\", onAbort, { once: true })\n\n let budgetTimer: ReturnType<typeof setTimeout> | undefined\n\n try {\n const liveCount = await this.ensureWorkers()\n if (liveCount === 0) return null\n if (opts.signal.aborted) return { byFile, budgetHit: false }\n\n if (opts.budgetMs <= 0) {\n budgetHit = true\n stop()\n } else {\n budgetTimer = setTimeout(() => {\n budgetHit = true\n stop()\n }, opts.budgetMs)\n budgetTimer.unref?.()\n }\n\n // Per-file dispatch with a single retry on worker death. The `stopped`\n // flag (budget/abort) makes pending dispatches resolve as misses.\n const dispatchFile = async (job: PoolJob, retried: boolean): Promise<void> => {\n if (stopped) return\n const id = this.nextJobId++\n myJobIds.add(id)\n const req: ParseJobRequest = {\n id,\n absPath: job.absPath,\n language: job.language,\n mtimeMs: job.mtimeMs,\n want: {\n confirmHits: job.confirmHits.length > 0 ? job.confirmHits : undefined,\n outline: job.outline || undefined,\n },\n }\n const reply = await this.enqueue(req, retried)\n if (stopped) return\n if (reply === null) {\n // Worker died mid-job → retry once on another worker, else miss.\n if (!retried) await dispatchFile(job, true)\n return\n }\n if (!reply.ok) return // worker-reported failure → miss\n if (reply.mtimeMs !== job.mtimeMs) return // file changed → miss\n byFile.set(job.file, {\n confirmedHitIndexes: reply.confirmedHitIndexes ?? [],\n outlineEntries: reply.outlineEntries,\n ok: true,\n })\n }\n\n await Promise.all(jobs.map((job) => dispatchFile(job, false)))\n } finally {\n if (budgetTimer) clearTimeout(budgetTimer)\n opts.signal.removeEventListener(\"abort\", onAbort)\n }\n\n // Total-failure detection: if NO file produced a result and we weren't\n // stopped by abort/budget, the pool failed as a whole (every job hit a\n // dead worker) → return null so the caller falls back to in-process.\n const stillLive = this.workers.some((w) => w.ready && w.loaded.size > 0)\n if (!stopped && byFile.size === 0 && !stillLive) return null\n\n return { byFile, budgetHit }\n }\n\n /** Terminate every worker. Idempotent. Fails any queued / in-flight jobs as\n * misses so no `parseFiles` caller hangs waiting on a worker that's gone. */\n shutdown(): void {\n this.shuttingDown = true\n for (const job of this.inflight.values()) job.done(null)\n this.inflight.clear()\n while (this.queue.length > 0) {\n const job = this.queue.shift()\n job?.done(null)\n }\n for (const pw of this.workers) {\n try {\n void pw.worker.terminate()\n } catch {\n // best effort\n }\n }\n this.workers = []\n }\n}\n\n// ---------------------------------------------------------------------------\n// Worker-script resolution (dev .ts vs bundled .js)\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the worker entry path for the current layout. Mirrors version.ts's\n * candidate-list pattern: dev runs the `.ts` directly under Bun; the bundled\n * build emits `dist/lib/tree-sitter-pool/worker.js` (separate tsdown entry).\n * Returns null if no candidate exists → the pool is unavailable and the caller\n * falls back to the in-process path.\n */\nfunction resolveWorkerPath(): string | null {\n try {\n const here = dirname(fileURLToPath(import.meta.url))\n const candidates = [\n join(here, \"worker.ts\"), // dev: src/lib/tree-sitter-pool/worker.ts\n join(here, \"worker.js\"), // bundled sibling\n join(here, \"tree-sitter-pool\", \"worker.js\"), // dist/lib/tree-sitter-pool/\n join(here, \"lib\", \"tree-sitter-pool\", \"worker.js\"), // from dist root\n ]\n for (const p of candidates) {\n if (existsSync(p)) return p\n }\n } catch {\n // fall through\n }\n return null\n}\n\n// ---------------------------------------------------------------------------\n// Lazy singleton + never-orphan shutdown\n// ---------------------------------------------------------------------------\n\nlet _pool: TreeSitterPool | null = null\nlet _shutdownRegistered = false\nlet _testCrashOnceArmed = false\nlet _warmOverride: ((pool: TreeSitterPool) => Promise<boolean>) | undefined\n\n/** Test-only: override launch warm-up without changing query-time lazy init. */\nexport function __setWarmTreeSitterPoolForTest(\n fn: ((pool: TreeSitterPool) => Promise<boolean>) | undefined,\n): void {\n _warmOverride = fn\n}\n\n/** Test-only: crash exactly the next dispatched worker job. */\nexport function __armWorkerCrashOnceForTest(): void {\n _testCrashOnceArmed = true\n}\n\n/** Test-only: disarm the one-shot worker crash fault. */\nexport function __disarmWorkerCrashOnceForTest(): void {\n _testCrashOnceArmed = false\n}\n/**\n * The pool is ON by default for real (non-CI) runs and OFF under CI.\n *\n * It gives a large event-loop-latency win under concurrent searches (see\n * `scripts/bench-code-search-parallelism.ts`), but its worker_threads + WASM\n * grammar heap fails to initialize under bun on the hosted CI runners (BOTH\n * ubuntu and windows), where it then yields degraded (role-tag-poorer)\n * RANKING — never wrong recall, the floor is unaffected — instead of the\n * in-process result. So:\n * - `GH_ROUTER_DISABLE_TS_POOL=1` → hard OFF (takes precedence everywhere).\n * - `GH_ROUTER_ENABLE_TS_POOL=1` → hard ON (force it even under CI, e.g.\n * when validating the pool on a CI-like host).\n * - otherwise → ON unless a CI env is detected (`CI=true`/`1`, which\n * GitHub Actions and most CIs set).\n * The in-process structural pass remains the correct fallback when the pool\n * is unavailable.\n */\nfunction isCiEnv(): boolean {\n const ci = process.env.CI\n return ci === \"true\" || ci === \"1\"\n}\nconst poolEnabled = (): boolean => {\n if (process.env.GH_ROUTER_DISABLE_TS_POOL === \"1\") return false\n if (process.env.GH_ROUTER_ENABLE_TS_POOL === \"1\") return true\n return !isCiEnv()\n}\n\n/**\n * Get the process-wide pool, spawning it lazily on first use (NOT at import —\n * a `claude` passthrough session that never calls `code` should pay nothing).\n * Returns null when not opted-in or unavailable.\n */\nexport function getTreeSitterPool(): TreeSitterPool | null {\n if (!poolEnabled()) return null\n if (_pool) return _pool\n _pool = new TreeSitterPool()\n if (_pool.unavailable) {\n _pool = null\n return null\n }\n if (!_shutdownRegistered) {\n _shutdownRegistered = true\n // ONLY an `exit` handler. We deliberately do NOT add SIGINT/SIGTERM\n // listeners: those would compete with the worker-agent lifecycle handlers\n // (src/lib/worker-agent/lifecycle.ts), and calling process.exit() from one\n // signal listener suppresses the others. Because every worker is unref()-ed\n // it can never keep the process alive on its own — so the synchronous\n // `exit` sweep (which fires on EVERY exit path, including after another\n // handler re-raises a signal) is sufficient to terminate them cleanly and\n // never-orphan. terminate() is async but we don't await: the process is\n // already exiting and unref()-ed workers die with it regardless.\n process.once(\"exit\", () => _pool?.shutdown())\n }\n return _pool\n}\n\n/**\n * Best-effort launch warm-up. Returns immediately when disabled/unavailable and\n * never rejects; lazy initialization remains the fallback after any failure.\n */\nexport async function warmTreeSitterPool(): Promise<void> {\n if (process.env.GH_ROUTER_DISABLE_TS_POOL_WARMUP === \"1\") return\n const pool = getTreeSitterPool()\n if (!pool) return\n try {\n if (await (_warmOverride?.(pool) ?? pool.warm())) return\n } catch (err) {\n consola.debug(\n `[code_search] tree-sitter pool warm-up failed; using lazy initialization: ${(err as Error).message}`,\n )\n }\n // Do not let a launch-only failure poison the singleton. The next query gets\n // a fresh pool and follows the established lazy-init/fallback path.\n if (_pool === pool) {\n pool.shutdown()\n _pool = null\n }\n}\n\n/** Test-only: tear down and reset the singleton. */\nexport function __resetTreeSitterPoolForTests(): void {\n shutdownTreeSitterPool()\n _warmOverride = undefined\n __disarmWorkerCrashOnceForTest()\n}\n\n/**\n * Shut down the pool and drop the singleton. Short-lived processes\n * (`bun run` scripts, one-shot CLI commands) MUST call this when done:\n * unref()-ed workers still hold Bun's event loop open, so without an\n * explicit shutdown such a process hangs after completing its work\n * instead of exiting. Long-lived proxy processes never call this —\n * workers stay warm across queries and die with the process via the\n * `exit` sweep. In-flight callers fail as misses, so only call when no\n * search is running.\n */\nexport function shutdownTreeSitterPool(): void {\n _pool?.shutdown()\n _pool = null\n}\n\nexport type { TreeSitterPool }\n","/**\n * Search-specific concurrency control for `code_search`.\n *\n * The MCP-wide `MAX_INFLIGHT_TOOLS_CALL` (128) is shared across ALL tools —\n * it bounds operator-traffic starvation, not CPU. Sixteen parallel\n * `code_search` calls fit under it easily yet oversubscribe a 4-core box:\n * each spawns ripgrep (multi-threaded by default) plus tree-sitter parses.\n * This module bounds ACTIVE search weight so parallel queries degrade\n * gracefully instead of thrashing.\n *\n * Design (Phase 1, A8):\n * - Weight-based FIFO semaphore. Modes carry different CPU costs:\n * ranked/regex/ast do the most work (BM25F two-pass + structural pass\n * or ast-grep spawn); literal is a thin streaming scan.\n * - Small requests naturally fit into freed capacity first (a 0.5-weight\n * exact query proceeds when 0.5 frees, while a 1.0 ranked query waits)\n * — no explicit priority lane needed.\n * - No queue cap in v1: bursts are finite (16 parallel), and the MCP\n * layer already caps at 128. Saturation errors would add failure modes\n * without evidence of queue buildup; revisit with benchmark data.\n * - `recommendedRgThreads()` lets ripgrep spawns size their own thread\n * pools from live concurrency (Phase 1, A5): a sole searcher gets all\n * cores; six concurrent searches get ~1 thread each.\n *\n * `searchCode` (src/lib/code-search.ts) is the choke point — every caller\n * (MCP `code` tool, worker `code_search` tool, direct imports) funnels\n * through it, so acquiring here covers all surfaces. Acquisition happens\n * AFTER input/workspace validation so invalid calls fail fast without\n * holding a slot.\n */\n\nimport * as os from \"node:os\";\n\n/** CPU cost classes for search dispatch. */\nexport type SearchWeightClass = \"ranked\" | \"literal\" | \"regex\" | \"ast\";\n\n/**\n * Per-class weights. Ranked pays for BM25F two-pass + the structural pass;\n * regex can backtrack; ast spawns sg. Literal streams matches with no\n * scoring — cheapest.\n */\nconst WEIGHTS: Record<SearchWeightClass, number> = {\n ranked: 1.0,\n literal: 0.5,\n regex: 1.0,\n ast: 1.0,\n} as const;\n\nfunction cpuCount(): number {\n try {\n const n = os.cpus().length;\n return Number.isSafeInteger(n) && n > 0 ? n : 4;\n } catch {\n return 4;\n }\n}\n\n/**\n * Max aggregate active weight. Default `cpus * 1.5` (4-core → 6.0):\n * six concurrent ranked searches, or twelve literal, or a mix. The 1.5x\n * headroom accounts for searches spending part of their time in I/O\n * (ripgrep streaming, file reads) rather than on-CPU.\n * Override with `GH_ROUTER_SEARCH_MAX_WEIGHT` (positive number).\n */\nexport function maxSearchWeight(): number {\n const raw = process.env.GH_ROUTER_SEARCH_MAX_WEIGHT;\n if (raw !== undefined) {\n const n = Number(raw);\n if (Number.isFinite(n) && n > 0) return n;\n }\n return cpuCount() * 1.5;\n}\n\n/**\n * Bypass switch for tests and single-shot debugging:\n * `GH_ROUTER_SEARCH_NO_LIMIT=1` makes acquisition a no-op.\n */\nfunction bypassed(): boolean {\n const v = process.env.GH_ROUTER_SEARCH_NO_LIMIT;\n return v === \"1\" || v === \"true\";\n}\n\ninterface Waiter {\n weight: number;\n resolve: (release: () => void) => void;\n reject: (err: Error) => void;\n onAbort: () => void;\n signal?: AbortSignal;\n settled: boolean;\n}\n\nlet activeWeight = 0;\nconst queue: Array<Waiter> = [];\n\n/** Test-only: reset active weight + drop queued waiters (rejects them). */\nexport function __resetSearchConcurrencyForTests(): void {\n activeWeight = 0;\n const pending = queue.splice(0, queue.length);\n for (const w of pending) {\n if (w.settled) continue;\n w.settled = true;\n w.signal?.removeEventListener(\"abort\", w.onAbort);\n w.reject(new Error(\"search concurrency reset\"));\n }\n}\n\n/** Current aggregate active weight (telemetry/tests). */\nexport function currentSearchWeight(): number {\n return activeWeight;\n}\n\n/** Current queued waiter count (telemetry/tests). */\nexport function queuedSearchCount(): number {\n return queue.length;\n}\n\nfunction release(weight: number): void {\n activeWeight = Math.max(0, activeWeight - weight);\n drain();\n}\n\n/**\n * Admit queued waiters in FIFO order, skipping entries that don't fit the\n * freed capacity (they wait for the next release). Single pass per release\n * — bursts drain; strict head-of-line blocking would idle freed capacity\n * behind one large waiter while smaller ones could proceed.\n */\nfunction drain(): void {\n if (queue.length === 0) return;\n const max = maxSearchWeight();\n const remaining: Array<Waiter> = [];\n for (const w of queue) {\n if (w.settled) continue;\n if (activeWeight + w.weight <= max) {\n w.settled = true;\n w.signal?.removeEventListener(\"abort\", w.onAbort);\n activeWeight += w.weight;\n w.resolve(() => release(w.weight));\n } else {\n remaining.push(w);\n }\n }\n queue.length = 0;\n queue.push(...remaining);\n}\n\n/**\n * Acquire a search slot. Resolves with a release function the caller MUST\n * invoke exactly once (typically from a `finally` block); the release is\n * idempotent. Rejects immediately if `signal` is already aborted; removes\n * the waiter and rejects if it aborts while queued.\n */\nexport function acquireSearchSlot(\n mode: SearchWeightClass,\n signal?: AbortSignal,\n): Promise<() => void> {\n const weight = WEIGHTS[mode] ?? 1.0;\n if (bypassed()) return Promise.resolve(() => {});\n if (signal?.aborted) {\n return Promise.reject(new Error(\"search aborted before dispatch\"));\n }\n if (queue.length === 0 && activeWeight + weight <= maxSearchWeight()) {\n activeWeight += weight;\n let released = false;\n return Promise.resolve(() => {\n if (released) return;\n released = true;\n release(weight);\n });\n }\n return new Promise<() => void>((resolve, reject) => {\n const waiter: Waiter = {\n weight,\n resolve,\n reject,\n signal,\n settled: false,\n onAbort: () => {\n if (waiter.settled) return;\n waiter.settled = true;\n const i = queue.indexOf(waiter);\n if (i >= 0) queue.splice(i, 1);\n reject(new Error(\"search aborted while queued\"));\n },\n };\n queue.push(waiter);\n signal?.addEventListener(\"abort\", waiter.onAbort, { once: true });\n });\n}\n\n/**\n * Recommended ripgrep `--threads` for a spawn happening RIGHT NOW\n * (Phase 1, A5). Divides cores across live searches so N concurrent\n * searches don't each fan out to `cpus` threads: a sole searcher gets\n * all cores; six concurrent on 4-core get 1 each. Called at spawn time\n * from `buildRgArgs` — no signature changes needed anywhere.\n */\nexport function recommendedRgThreads(): number {\n const cpus = cpuCount();\n // activeSearchCount derives from weight; a lone literal (0.5) still\n // counts as one live searcher for thread-division purposes.\n const active = Math.max(1, Math.ceil(activeWeight));\n return Math.max(1, Math.floor(cpus / active));\n}\n","/**\n * JIT cross-encoder reranking for lexical results (Phase 3).\n *\n * `code_search` ranked mode already orders by BM25F + AST definition signal,\n * which is optimal for single-identifier queries (\"where is X\"). For\n * NATURAL-LANGUAGE queries (\"retry around the upstream fetch\") BM25F's\n * tokenized matching is weak — this module reranks the BM25F top-N with a\n * local ONNX cross-encoder (flashrank-js) so the lexical engine degrades\n * gracefully on intent-shaped queries, including the `lexical-fallback`\n * path when the semantic index isn't ready.\n *\n * Design constraints (highest-value, lowest-risk):\n * - NL-shaped queries ONLY (≥2 whitespace terms). Single identifiers skip\n * reranking entirely — zero latency cost for the common case.\n * - Two warm singletons (`tiny` 4MB / `mini` 23MB); load selects by live\n * queue pressure (`tiny` when searches are queued, `mini` otherwise).\n * ~27MB total, shared across all queries in the process.\n * - Lazy warm: first NL query triggers background load and FALLS BACK to\n * BM25F order within the budget — never blocks on model download.\n * - Hard budget (default 150ms): on timeout/error, BM25F order stands.\n * Reranking is a precision boost, never on the correctness path.\n * - Opt-out: `GH_ROUTER_RERANK=off`. Force a model with `=tiny|mini`.\n * Budget override: `GH_ROUTER_RERANK_BUDGET_MS`.\n */\n\nimport { queuedSearchCount } from \"~/lib/search-concurrency\"\n\ntype RerankerInstance = {\n rerank: (req: {\n query: string\n documents: Array<string>\n topN: number\n }) => Promise<Array<{ index: number; score: number }>>\n dispose?: () => Promise<void>\n}\n\ntype RerankModel = \"tiny\" | \"mini\"\n\nconst RERANK_BUDGET_MS_DEFAULT = 150\n\nfunction rerankMode(): \"off\" | \"auto\" | RerankModel {\n const raw = process.env.GH_ROUTER_RERANK?.toLowerCase()\n if (raw === \"off\" || raw === \"0\" || raw === \"false\") return \"off\"\n if (raw === \"tiny\" || raw === \"mini\") return raw\n return \"auto\"\n}\n\nfunction rerankBudgetMs(): number {\n const raw = Number(process.env.GH_ROUTER_RERANK_BUDGET_MS)\n if (Number.isFinite(raw) && raw > 0) return Math.floor(raw)\n return RERANK_BUDGET_MS_DEFAULT\n}\n\n/** True iff the query is natural-language shaped (multi-word). */\nexport function isNaturalLanguageQuery(query: string): boolean {\n return query.trim().split(/\\s+/).filter(Boolean).length >= 2\n}\n\nconst instances = new Map<RerankModel, Promise<RerankerInstance | null>>()\n\n/**\n * Load-serialization chain. Concurrent ONNX session initializations crash\n * the process under Bun's Node-API compat (reproduced: overlapping tiny +\n * mini `Reranker.create` → C++ exception). Chaining guarantees at most one\n * `create` runs at a time; inference on loaded sessions is unaffected.\n * A burst that needs both models (first query idle → mini starts, second\n * query queued → tiny starts) therefore serializes instead of crashing.\n */\nlet loadChain: Promise<unknown> = Promise.resolve()\n\n/**\n * Every load ever started (never cleared). Budget-short-circuited callers\n * orphan their load — the download + ORT init continue detached. If the\n * process exits while native init is in flight, Bun's teardown crashes\n * (reproduced: C++ exception after a green run). Draining this set before\n * exit (tests: afterAll; proxy: shutdown chain) is what keeps teardown\n * clean. Short-lived by construction: each entry settles on load completion.\n */\nconst inflightLoads = new Set<Promise<unknown>>()\n\n/**\n * Lazily load (and cache) a reranker. Never rejects — load failure\n * (no network, bad cache) resolves null so callers fall back to BM25F.\n */\nfunction getReranker(model: RerankModel): Promise<RerankerInstance | null> {\n const cached = instances.get(model)\n if (cached) return cached\n const p = loadChain.then(async (): Promise<RerankerInstance | null> => {\n try {\n const { Reranker } = await import(\"flashrank-js\")\n return (await Reranker.create({ model })) as RerankerInstance\n } catch {\n return null\n }\n })\n // Advance the chain (swallowing errors so one failed load never wedges\n // later ones); the cached promise itself never rejects (see above).\n loadChain = p.catch(() => {})\n instances.set(model, p)\n const tracked = p.catch(() => {})\n inflightLoads.add(tracked)\n void tracked.finally(() => {\n inflightLoads.delete(tracked)\n })\n return p\n}\n\n/** Test-only: drop cached instances (forces reload / failure paths). */\nexport function __resetRerankerForTests(): void {\n instances.clear()\n}\n\n/**\n * Await every in-flight model load (test/shutdown use). Without this, a\n * budget-short-circuited load orphaned near process exit crashes Bun's\n * native teardown. Bounded by `timeoutMs` so a hung download can't wedge\n * shutdown; callers that time out accept the residual exit-crash risk.\n */\nexport async function drainRerankerLoads(timeoutMs = 30_000): Promise<void> {\n const pending = [...inflightLoads]\n if (pending.length === 0) return\n await Promise.race([\n Promise.all(pending),\n new Promise((resolve) => setTimeout(resolve, timeoutMs).unref?.()),\n ])\n}\n\n/**\n * Dispose all cached sessions and drop them (shutdown/script use). Live\n * ONNX sessions hold event-loop handles that keep a short-lived process\n * from exiting on its own; disposing releases them so the loop drains.\n * The long-lived proxy should call this (after `drainRerankerLoads`) in\n * its shutdown chain. Never throws.\n */\nexport async function disposeRerankers(): Promise<void> {\n const all = [...instances.values()]\n instances.clear()\n for (const p of all) {\n try {\n const r = await p\n await r?.dispose?.()\n } catch {\n // best effort\n }\n }\n}\n\n/**\n * Rerank `documents` against `query`, returning the top `topN` document\n * indexes in reranked order — or null when reranking is disabled,\n * unavailable, over budget, or errors. Null is NOT an error: the caller\n * keeps BM25F order.\n */\nexport async function rerankDocuments(\n query: string,\n documents: ReadonlyArray<string>,\n topN: number,\n signal?: AbortSignal,\n): Promise<Array<number> | null> {\n const mode = rerankMode()\n if (mode === \"off\" || documents.length === 0 || topN <= 0) return null\n if (signal?.aborted) return null\n\n // Load-adaptive model: tiny when searches are queued (burst), else mini\n // (or the forced model). Both singletons stay warm once loaded.\n const model: RerankModel =\n mode === \"auto\" ? (queuedSearchCount() > 0 ? \"tiny\" : \"mini\") : mode\n\n const budget = rerankBudgetMs()\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n const result = await Promise.race([\n (async () => {\n const reranker = await getReranker(model)\n if (!reranker || signal?.aborted) return null\n const ranked = await reranker.rerank({\n query,\n documents: [...documents],\n topN: Math.min(topN, documents.length),\n })\n if (signal?.aborted) return null\n return ranked.map((r) => r.index)\n })(),\n new Promise<null>((resolve) => {\n timer = setTimeout(() => resolve(null), budget)\n timer.unref?.()\n }),\n ])\n return result\n } catch {\n return null\n } finally {\n if (timer) clearTimeout(timer)\n }\n}\n","/**\n * Workspace confinement + sensitive-file denylist for worker tools.\n *\n * Plan: see `plans/we-have-added-a-dreamy-tide.md` (\"Tools\" section).\n *\n * `confineToWorkspace(rawPath, workspaceAbs)` is the single chokepoint\n * every path-touching worker tool routes through (`read`, `glob`,\n * `grep`, `code_search`, `edit`, `write`). It rejects:\n *\n * - explicit `..` segments after normalization (`a/../b` is allowed\n * because it resolves to `a/b`; a path that escapes the workspace\n * via `..` is rejected by the prefix check);\n * - on Windows: UNC paths (`\\\\server\\share`), device paths\n * (`\\\\?\\C:\\…`, `\\\\.\\…`), and drive-relative paths (`C:foo`);\n * - any path whose realpath-resolved form falls outside\n * `workspaceAbs` — trailing-separator-aware so `C:\\work` does not\n * accidentally accept `C:\\workspace2`.\n *\n * Symlink/junction handling uses `fs.realpathSync.native()` (rather\n * than the JS-emulated `realpathSync`) to match the platform's own\n * resolution for case-folding on macOS, reparse points on Windows,\n * etc. — same rule cc-backup's filesystem layer uses.\n *\n * `SENSITIVE_FILE_DENYLIST` covers credential-shaped filenames the\n * worker should never read even when they live inside the confined\n * workspace. `isSensitivePath` returns true when any pattern matches\n * any segment of the path relative to the workspace; callers (the\n * `read`/`glob`/`grep`/`code_search` tools) translate that into a\n * factual \"denied: secret-file pattern\" tool result that Pi sees and\n * decides on.\n */\n\nimport { realpathSync } from \"node:fs\"\nimport * as path from \"node:path\"\n\nconst IS_WINDOWS = process.platform === \"win32\"\n\n/**\n * Sensitive-file regex patterns evaluated against each path segment\n * (the path relative to the workspace root, split on `/` and `\\`).\n *\n * The patterns are deliberately narrow — they target the shapes of\n * common credential / private-key files, not entire categories. They\n * are NOT a sandbox; they are a \"stop fat-fingering through .env\"\n * guardrail. Layered with workspace confinement they suffice for the\n * threat model documented in the plan.\n */\nexport const SENSITIVE_FILE_DENYLIST: ReadonlyArray<RegExp> = [\n // `.env`, `.env.local`, `.env.production`, etc. (dotfile env files).\n /^\\.env(\\..+)?$/i,\n // PEM-encoded keys / certs.\n /^.+\\.pem$/i,\n // OpenSSH private keys (and their `.pub` counterparts; treat both as sensitive).\n /^id_rsa(\\..+)?$/i,\n /^id_ed25519(\\..+)?$/i,\n // npm + curl/wget auth tokens.\n /^\\.npmrc$/i,\n /^\\.netrc$/i,\n]\n\n/**\n * Directory segments treated as sensitive: if any path component\n * matches one of these names, the path is sensitive. Covers `.git/`\n * interior (config, hooks, packed refs), SSH key material, and\n * GPG/PGP keyrings.\n */\nconst SENSITIVE_DIR_SEGMENTS: ReadonlySet<string> = new Set([\n \".git\",\n \".ssh\",\n \".gnupg\",\n])\n\n/**\n * Internal helper: split a path into segments using both POSIX and\n * Windows separators (`/` and `\\`). We don't use `path.sep` because a\n * path can mix separators on Windows (`C:\\work/foo\\bar`).\n */\nfunction splitSegments(p: string): Array<string> {\n return p.split(/[\\\\/]+/).filter((s) => s.length > 0)\n}\n\n/**\n * Check whether `absPath` (already absolute and inside `workspaceAbs`)\n * matches any pattern on the sensitive-file denylist.\n *\n * Returns `true` if the path itself is sensitive, OR if any of its\n * intermediate segments names a sensitive directory (e.g. `.git/`,\n * `.ssh/`). Sensitive-segment matching catches both nested files\n * (`.git/config`, `.ssh/known_hosts`) and the directory listing itself\n * (preventing `glob(\".git/**\")` from leaking refs).\n *\n * The check is performed against the path RELATIVE to the workspace\n * to avoid false positives on workspace-name shapes like `~/keys.pem`\n * being a containing directory (only relevant on weird user setups,\n * but free correctness).\n */\nexport function isSensitivePath(absPath: string, workspaceAbs: string): boolean {\n const rel = path.relative(workspaceAbs, absPath)\n if (rel === \"\") {\n // The workspace root itself is never sensitive.\n return false\n }\n const segments = splitSegments(rel)\n for (const seg of segments) {\n if (SENSITIVE_DIR_SEGMENTS.has(seg)) return true\n for (const pat of SENSITIVE_FILE_DENYLIST) {\n if (pat.test(seg)) return true\n }\n }\n return false\n}\n\n/**\n * Pre-realpath syntactic rejection of Windows paths the worker must\n * not accept under any circumstance.\n *\n * - UNC paths (`\\\\server\\share\\…`) traverse remote filesystems; we\n * only confine the local workspace.\n * - Device / namespace paths (`\\\\?\\C:\\…`, `\\\\.\\PhysicalDrive0`) bypass\n * the normal Win32 path-parser including length/character limits;\n * we'd lose the safety guarantees of the rest of this check.\n * - Drive-relative paths (`C:foo` — note: no separator after the\n * drive) resolve against the per-drive current directory, which the\n * worker has no control over.\n */\nfunction rejectWindowsHostilePath(raw: string): string | null {\n // UNC + device/namespace: leading `\\\\` or `//`.\n if (/^[\\\\/]{2}/.test(raw)) {\n return \"rejected: UNC or device path\"\n }\n // NTFS alternate data streams: `file.png:secret`. A stream lives inside the\n // file yet is invisible to every name-based rule here — `isSensitivePath`\n // matches path SEGMENTS, and `notes.png:secret` reads as an innocuous .png.\n // Nothing a worker tool legitimately does needs one, so reject any colon that\n // is not the drive separator at index 1. POSIX allows `:` in filenames, hence\n // the platform gate.\n if (IS_WINDOWS) {\n const afterDrive = /^[A-Za-z]:/.test(raw) ? raw.slice(2) : raw\n if (afterDrive.includes(\":\")) {\n return \"rejected: alternate data stream\"\n }\n }\n // Drive-relative: `C:foo` but NOT `C:\\foo`, `C:/foo`, or bare `C:`.\n // Bare `C:` is treated as drive-current-dir too, so reject it.\n if (/^[A-Za-z]:(?![\\\\/])/.test(raw)) {\n return \"rejected: drive-relative path\"\n }\n return null\n}\n\nexport interface ConfineOk {\n ok: true\n abs: string\n}\nexport interface ConfineErr {\n ok: false\n error: string\n}\nexport type ConfineResult = ConfineOk | ConfineErr\n\n/**\n * Resolve `rawPath` against `workspaceAbs` and verify the result lives\n * within the workspace.\n *\n * `workspaceAbs` MUST already be absolute and pre-realpath-resolved by\n * the caller (the engine does this once at worker start). We don't\n * realpath it again per-call.\n *\n * Behavior:\n * 1. Syntactic Windows rejection (UNC / device / drive-relative).\n * 2. Reject explicit `..` segments on the RAW input — `..` after\n * normalization is fine (`a/../b` → `a/b`), but a user explicitly\n * writing `..` is almost always trying to escape.\n * 3. If `rawPath` is absolute, use as-is; otherwise join against\n * `workspaceAbs`.\n * 4. realpath-canonicalize with `realpathSync.native()` so symlinks\n * and junctions point at their true target. If the path does not\n * yet exist (e.g. `write` creating a new file), realpath the\n * *parent* and re-join with the basename — same trick cc-backup\n * uses for write-creates inside a confined workspace.\n * 5. Trailing-separator-aware prefix check against `workspaceAbs`:\n * append `path.sep` to both sides before `startsWith` so\n * `C:\\work` does not match `C:\\workspace2`. Allow equality too\n * (the workspace root is a valid path).\n *\n * Returns either `{ok: true, abs}` with the canonical absolute path\n * (suitable for `fs.readFile`, `fs.writeFile`, etc.) or `{ok: false,\n * error}` with a terse human-readable reason.\n *\n * Note: errors are intentionally short — they are returned to the\n * model verbatim (as tool-result text) and don't echo the input path\n * to keep the audit log + log lines compact.\n */\nexport function confineToWorkspace(\n rawPath: string,\n workspaceAbs: string,\n): string {\n const result = confineToWorkspaceResult(rawPath, workspaceAbs)\n if (!result.ok) {\n throw new Error(result.error)\n }\n return result.abs\n}\n\n/**\n * Result-returning variant. Most call sites want the throw form (it\n * composes cleanly into AgentTool.execute which returns errors via\n * `{isError, content}`); tests + tools that want to surface a specific\n * error message to Pi without raising can use this form.\n */\nexport function confineToWorkspaceResult(\n rawPath: string,\n workspaceAbs: string,\n): ConfineResult {\n if (typeof rawPath !== \"string\" || rawPath.length === 0) {\n return { ok: false, error: \"rejected: empty path\" }\n }\n\n if (IS_WINDOWS) {\n const winErr = rejectWindowsHostilePath(rawPath)\n if (winErr) return { ok: false, error: winErr }\n }\n\n // Reject explicit `..` segments in the RAW input. This catches the\n // common escape attempts; `a/../b` (no leading `..`) normalizes\n // safely and is allowed because the realpath check will catch any\n // actual escape.\n const rawSegments = splitSegments(rawPath)\n if (rawSegments.includes(\"..\")) {\n return { ok: false, error: \"rejected: parent-directory segment\" }\n }\n\n // Build the absolute candidate path.\n const candidate = path.isAbsolute(rawPath)\n ? path.normalize(rawPath)\n : path.normalize(path.join(workspaceAbs, rawPath))\n\n // realpath canonicalization. If the path doesn't exist yet (e.g.\n // write-creating a new file), fall back to realpath-ing the parent\n // and joining the basename — same pattern as cc-backup. If even the\n // parent doesn't exist, leave the candidate as-is (the eventual fs\n // call will fail with the right ENOENT; we don't pre-empt).\n let canonical: string\n try {\n canonical = realpathSync.native(candidate)\n } catch {\n const parent = path.dirname(candidate)\n const base = path.basename(candidate)\n try {\n const realParent = realpathSync.native(parent)\n canonical = path.join(realParent, base)\n } catch {\n canonical = candidate\n }\n }\n\n // Trailing-separator-aware prefix check. Without this, `C:\\work` is\n // a prefix of `C:\\workspace2` and the confinement leaks.\n const wsWithSep = workspaceAbs.endsWith(path.sep)\n ? workspaceAbs\n : workspaceAbs + path.sep\n const isInside =\n canonical === workspaceAbs || canonical.startsWith(wsWithSep)\n if (!isInside) {\n return { ok: false, error: \"rejected: outside workspace\" }\n }\n\n return { ok: true, abs: canonical }\n}\n","/**\n * `code_search` MCP tool implementation.\n *\n * Exposes structured code search to clients (Claude Code, codex,\n * gemini callers) via the `mcp__gh-router-peers__code_search` tool.\n * Backed by ripgrep; ranks with BM25F (Robertson, Zaragoza, Taylor\n * 2004) over four code-aware fields (matched line, context window,\n * file path tokens, symbol-context heuristic).\n *\n * Plan: ~/.local/share/.../plans/what-are-the-following-wild-tarjan.md\n * Peer review: same dir, file ending in -agent-af76e3758b0fa7e1a.md.\n *\n * Load-bearing design decisions worth knowing before editing:\n *\n * - Workspace is any absolute path that exists and is a directory.\n * The proxy runs as the user; code_search reads what the proxy\n * process can read, the same way Claude Code's built-in Read /\n * Bash tools do. The earlier allow-set + secret-shape denylist\n * was dropped: the threat model is symmetric; the model already\n * has Bash and Read, so an extra gate on this one tool was just\n * inconsistency, not defense.\n *\n * - rg is spawned with `cwd: canonicalWorkspace` and target `.`,\n * NEVER with the user-supplied path string as an argv positional.\n * This pins the directory at kernel-level at spawn time, closing\n * most of the TOCTOU window between validate and spawn. The\n * residual same-user race is out of scope.\n *\n * - The `--` positional separator is mandatory. A query starting\n * with `-` would otherwise be parsed as a ripgrep flag — CVE.\n *\n * - On Windows, child.kill() does NOT reliably terminate\n * descendants. We invoke `taskkill /T /F /PID <pid>` on abort.\n *\n * - JSON streaming parser short-circuits on `signal.aborted` so a\n * half-flushed truncated chunk never reaches JSON.parse — three-\n * lab confirmed cancel-race fix.\n *\n * - `--max-count` is per-file, not global. We enforce the limit\n * globally in the TS reader; relying on ripgrep would let a\n * 500-file monorepo return 10,000 hits with limit=20.\n *\n * - BM25F is applied at file granularity over the rg hit set. The\n * v1 review's BM25 critique was about snippet-granularity (4-line\n * length-normalization noise); files have varied lengths so\n * length normalization is meaningful here.\n */\n\nimport { spawn, execFileSync, type ChildProcess } from \"node:child_process\";\nimport { existsSync, realpathSync, statSync } from \"node:fs\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { performance } from \"node:perf_hooks\";\nimport { createInterface } from \"node:readline\";\nimport * as path from \"node:path\";\n\nimport consola from \"consola\";\nimport { Language, Parser, Tree } from \"web-tree-sitter\";\n\nimport {\n confirmDefinitionSites,\n type FileOutlineEntry,\n type FileOutlineResult,\n getGrammarBundle,\n getLanguageKeyForPath,\n outlineFile,\n outlineFromTree,\n type StructuralHit,\n STRUCTURAL_MAX_FILE_BYTES,\n} from \"~/lib/tree-sitter-grammars\";\nimport {\n getTreeSitterPool,\n type PoolJob,\n type TreeSitterPool,\n} from \"~/lib/tree-sitter-pool/pool\";\nimport {\n resolveExecutable,\n runManagedExeCapture,\n spawnTaskkillBestEffort,\n} from \"~/lib/exec\";\nimport { PATHS } from \"~/lib/paths\";\nimport { isNaturalLanguageQuery, rerankDocuments } from \"~/lib/rerank\"\nimport { acquireSearchSlot, recommendedRgThreads } from \"~/lib/search-concurrency\";\nimport { isSensitivePath } from \"~/lib/worker-agent/paths\";\n\n// ============================================================\n// Constants\n// ============================================================\n\n/**\n * BM25's `k1` term-frequency saturation parameter. Lucene's default.\n * Robertson & Zaragoza 2009 monograph recommends 1.2-2.0; Lucene\n * ships 1.2, Elasticsearch ships 1.2, we ship 1.2.\n */\nconst BM25F_K1 = 1.2;\n\n/**\n * Per-field BM25F boost weights (`b_f` in the CIKM 2004 paper). The\n * relative ordering follows Sourcegraph Zoekt's published signal\n * priorities — matched line first, then symbol context, then path,\n * then surrounding context.\n */\nconst FIELD_BOOSTS = {\n match_line: 3.0,\n symbol_context: 2.5,\n file_path: 2.0,\n context: 1.0,\n} as const;\n\n/**\n * Per-field length-normalization parameter (`l_f`). 0.0 disables\n * length normalization for short, uniform fields. Lucene's default\n * `b=0.75` for prose-like fields.\n */\nconst FIELD_LEN_NORMS = {\n match_line: 0.0,\n symbol_context: 0.0,\n file_path: 0.0,\n context: 0.75,\n} as const;\n\n/**\n * Shoulder cut threshold: in DEFAULT (non-`complete`) ranked mode, drop\n * hits below this fraction of the top score for precision. `complete:\n * true` disables it — see `docs/code-search-floor.md`.\n */\nconst SHOULDER_THRESHOLD = 0.5;\n\nconst MAX_QUERY_LEN = 1024;\nconst MAX_GLOB_LEN = 512;\nconst DEFAULT_LIMIT = 200;\nconst MAX_CONTEXT_LINES = 10;\n/**\n * `summary: true` outlines at most this many distinct result files (in\n * result order) — a structural map of where the matches live, bounded\n * so a broad query doesn't trigger hundreds of tree-sitter parses.\n */\nconst CODE_SUMMARY_MAX_FILES = 10;\n/**\n * `scan: true` outlines the ENTIRE workspace (every non-ignored,\n * non-sensitive source file), not just the matched result files. Bounded\n * well above `CODE_SUMMARY_MAX_FILES` (a whole-workspace map is the whole\n * point) but still capped so a giant monorepo can't blow the 256 KB\n * response or stall the tree-sitter pool. On truncation the response\n * `notice` reports files-covered vs total.\n */\nconst SCAN_MAX_FILES = 400;\n/**\n * Per-file match cap applied in DEFAULT (non-`complete`) ranked mode:\n * keeps one match-dense file from filling the global limit and blinding\n * BM25F to the rest of the workspace. `complete: true` disables it (and\n * the shoulder cut) to return the full grep set — the floor guarantee.\n */\nconst RANKED_MAX_PER_FILE = 50;\n\n/**\n * Head size for the JIT cross-encoder rerank (Phase 3). Only the first\n * RERANK_HEAD BM25F hits are reranked; beyond that BM25F order stands.\n * Sized so both models fit the rerank budget: tiny ≈12ms, mini ≈120ms\n * (both under the 150ms default). Covers the window a model actually\n * reads; deeper hits keep their BM25F relevance order.\n */\nconst RERANK_HEAD = 25;\n\n/**\n * Per-file cap on outline entries in a SEARCH response.\n *\n * `outlineFile`'s own cap is 1000 symbols, which is right when a caller asks\n * to outline one specific file. It is far too high here: outlines are attached\n * to up to 10 files the caller did NOT ask for, as orientation alongside the\n * hits. One large test file can contribute hundreds of entries and dominate\n * the response — the opposite of the compact map this field is meant to be,\n * and the caller pays that context whether or not they ever open the file.\n *\n * Exported because BOTH response paths must apply it: this lexical builder and\n * `buildOutlines` in unified-code-search.ts (the semantic one). Capping only\n * one leaves the other unbounded, which is exactly the bug this replaced —\n * the semantic path was capped while lexical, which is also the fallback every\n * cold-index query lands on, kept emitting the full 1000-symbol outline.\n *\n * The parser-level cap in tree-sitter-grammars.ts is deliberately untouched so\n * other consumers of `outlineFile` keep full fidelity.\n */\nexport const MAX_OUTLINE_ENTRIES_PER_FILE = 60;\nconst DEFAULT_CONTEXT_LINES = 2;\nconst MAX_SNIPPET_BYTES = 2048;\nconst MAX_STDOUT_BYTES = 10 * 1024 * 1024;\nconst WALL_TIME_MS = 30_000;\n\n/**\n * Structural-pass settings. The wall-clock budget is checked between\n * files (NOT mid-parse — tree-sitter doesn't surface a usable cancel\n * hook in the web-tree-sitter binding we're on), so a single\n * pathological file can overrun by one file's parse-time. Worker/grammar\n * initialization is completed before this timer starts; the 200ms budget\n * therefore measures parsing only, on cold and warm queries alike.\n */\nconst STRUCTURAL_BUDGET_MS = 200;\nlet _structuralBudgetTestOverride: number | null = null;\n\n/** Test-only: override the structural-pass budget; null restores 200ms. */\nexport function __setStructuralBudgetForTest(ms: number | null): void {\n _structuralBudgetTestOverride = ms;\n}\n\nfunction structuralBudgetMs(): number {\n return _structuralBudgetTestOverride ?? STRUCTURAL_BUDGET_MS;\n}\n\nconst STRUCTURAL_TOPN_FULL = 50;\nconst STRUCTURAL_TOPN_FAST = 10;\n\n/**\n * LRU bound on the parsed-tree cache. Each Tree pins ~roughly the\n * size of its source plus tree-sitter's internal node arena. 64 is\n * comfortably under typical Node heap budgets; trees are eagerly\n * `.delete()`-ed on eviction.\n */\nconst STRUCTURAL_CACHE_MAX = 64;\n\n/**\n * Definition-shape heuristic for `symbol_context` field. Match this\n * against the matched line (after leading whitespace strip) to\n * detect \"the match is on a definition.\" This is the regex fallback\n * we use when (a) tree-sitter can't reach the file (unsupported\n * language, grammar load failure, parse error), (b) the file isn't\n * in the structural pass's top-N slice, or (c) the structural budget\n * fired. Keywords are deliberately cross-language (`struct` also\n * catches C definitions, `namespace` C++/TS ones); each requires\n * `keyword + identifier`, so incidental uses (`x := struct {`, assignments)\n * don't match.\n */\nconst SYMBOL_REGEX =\n /^(?:export\\s+)?(?:default\\s+)?(?:async\\s+)?(?:public\\s+|private\\s+|protected\\s+|static\\s+|abstract\\s+|readonly\\s+|sealed\\s+|partial\\s+|internal\\s+)*(?:function|class|interface|type|enum|def|fn|trait|impl|module|namespace|record|struct|delegate|event|const|let|var)\\s+[A-Za-z_$]/;\n\n// ============================================================\n// Types\n// ============================================================\n\nexport interface CodeSearchInput {\n query: string;\n workspace: string;\n mode?: \"ranked\" | \"literal\" | \"regex\";\n file_glob?: string;\n limit?: number;\n context_lines?: number;\n /**\n * Depth of the tree-sitter structural-ranking pass. `\"full\"` parses\n * the top 50 BM25F hits and re-scores them with AST-confirmed\n * definition signal. `\"topN\"` parses only the top 10 — same signal,\n * tighter latency on large repos. Default `\"full\"`. The pass is\n * wrapped in a 200ms wall-clock budget; on overrun, remaining hits\n * fall back to the regex symbol heuristic and `notice` is populated\n * with a human-readable explanation.\n */\n structural?: \"full\" | \"topN\";\n /**\n * Structural summary, OPT-IN. Pass `summary: true` and the response\n * carries a tree-sitter STRUCTURAL OUTLINE (`outlines`) of the distinct\n * files in the result set (top-level symbols + line numbers), capped at\n * the first `CODE_SUMMARY_MAX_FILES` files in result order — a compact\n * map of where the matches live that augments, never replaces, `snippet`.\n * Omitted by default (saves ~2-5KB tokens per call).\n */\n summary?: boolean;\n /**\n * Exhaustiveness control. Default `false`: ranked mode applies a\n * precision shoulder cut (drops hits below 50% of the top score) and a\n * per-file match cap for cross-file diversity, so the model isn't\n * overwhelmed. `true`: BOTH are disabled, so ranked mode returns the\n * COMPLETE ripgrep match set (reordered by relevance), capped only by\n * the explicit `limit` — the provable floor (never drops a match grep\n * would return). When the default hides matches, the response `notice`\n * says so and points the model here.\n */\n complete?: boolean;\n /**\n * Multi-line matching. Default `false` (line-oriented, the proven\n * floor). When `true`, ripgrep runs with `-U --multiline-dotall` so a\n * pattern can span newlines (e.g. `foo[\\s\\S]*?bar` across two lines).\n * The match snippet is the whole spanned region, capped to the snippet\n * byte budget; the reported `line` is the START of the span. Use it with\n * `mode: \"regex\"` — that is the only mode where a cross-line pattern is\n * expressible (the `query` validator rejects literal newlines, so a\n * literal/ranked multi-line LITERAL can't be typed). Composes with every\n * other param.\n */\n multiline?: boolean;\n /**\n * Whole-workspace structural outline. Default `false`. When `true`,\n * `outlines` covers EVERY non-ignored, non-sensitive source file in the\n * workspace (a tree-sitter symbol map of the whole tree), not just the\n * files that text-matched `query`. Capped at `SCAN_MAX_FILES` and\n * budget-fitted into the response; on truncation `notice` reports\n * coverage. Use it to map an unfamiliar codebase's symbols in one call.\n * Independent of the match generation (the hit set still comes from the\n * query / `ast_pattern`).\n */\n scan?: boolean;\n /**\n * ast-grep structural pattern. When set, match generation runs ast-grep\n * (`sg`) with this pattern INSTEAD of ripgrep — results come back in the\n * same `{file, line, snippet}` shape, so a multi-line AST construct the\n * line-oriented regex modes can't express is matched directly. Takes\n * PRECEDENCE over `query` for match generation (`query` is then ignored\n * for matching; it is still required by the schema but unused). Requires\n * ast-grep (`sg`) to be available (toolbelt bin dir or system PATH); if\n * it isn't, `code_search` returns no results plus a `notice` telling you\n * to run ast-grep directly or omit `ast_pattern` (it never silently\n * falls back to regex). Read-only subprocess, workspace-confined.\n */\n ast_pattern?: string;\n /**\n * Language grammar for `ast_pattern` — REQUIRED whenever `ast_pattern` is\n * set. e.g. `\"ts\"`, `\"tsx\"`, `\"js\"`, `\"jsx\"`, `\"py\"`, `\"rust\"`, `\"go\"`,\n * `\"java\"`, `\"cpp\"`, `\"c\"`. ast-grep parses the pattern in this grammar;\n * WITHOUT it ast-grep cross-matches every language (e.g. matching markdown\n * prose) and returns garbage, so if `ast_pattern` is set but `ast_lang`\n * is omitted, `code_search` returns no results plus a `notice` asking for\n * it (it does NOT guess a language).\n */\n ast_lang?: string;\n}\n\nexport interface CodeSearchHit {\n file: string;\n line: number;\n snippet: string;\n match_byte_range: [number, number];\n score?: number;\n field_contributions?: Readonly<Record<string, number>> | null;\n /**\n * Present (always `\"definition\"`) ONLY when the structural pass\n * AST-confirmed this hit is the symbol's definition site. Absent\n * otherwise — absence is NOT a claim that the hit is a usage (the hit\n * may simply not have been AST-checked: unsupported language, file over\n * the 1 MiB cap, parse error, or the structural budget was exhausted).\n */\n role?: \"definition\";\n}\n\nexport interface CodeSearchResponse {\n results: Array<CodeSearchHit>;\n truncated: boolean;\n scanned_files: number;\n elapsed_ms: number;\n ranking: {\n algorithm: \"BM25F\" | \"BM25F+FlashRank\" | \"ripgrep_document_order\";\n citation?: string;\n k1?: number;\n };\n /**\n * Present only when `summary: true` was requested: a tree-sitter\n * structural outline of each distinct file in the result set (capped\n * at `CODE_SUMMARY_MAX_FILES`, in result order). Absent otherwise.\n */\n outlines?: Array<{ file: string; outline: Array<FileOutlineEntry> }>;\n /**\n * Single actionable degradation notice for the model. `null` on the\n * happy path. A string when something the model can correct fired:\n * - structural-budget exhaustion (\"retry with structural: \\\"topN\\\"\n * or narrow query\")\n * - response-size cap (\"response size limit reached at N hits;\n * lower limit or narrow your query\")\n * Size-cap takes priority over structural-budget when both fire,\n * because size-cap means the model is missing results; structural-\n * budget just means the ranking was less precise but the result set\n * is complete.\n *\n * The MCP handler maps this to the `notice` response field (omitted\n * entirely when `null`) — only-when-actionable surface per the\n * docs/peer-mcp-design.md minimality principle.\n */\n notice: string | null;\n}\n\n/**\n * Internal representation of one rg match before scoring.\n * `context_before` and `context_after` are populated via ripgrep's\n * --context flag (rg emits \"context\" JSON events that we associate\n * with the surrounding match).\n */\ninterface RawHit {\n file: string; // path RELATIVE to workspace\n line: number; // 1-indexed\n matched_line: string; // line text without trailing newline\n match_start: number; // byte offset in matched_line\n match_end: number; // byte offset in matched_line\n context_before: Array<string>;\n context_after: Array<string>;\n}\n\n// ============================================================\n// Ripgrep resolution\n// ============================================================\n\ninterface RipgrepResolution {\n rgPath: string;\n source: \"system\" | \"toolbelt\" | \"bundled\";\n}\n\nlet _rgResolution: RipgrepResolution | undefined;\n\n/** @internal — reset memoized resolution between test cases. */\nexport function __resetRipgrepResolverForTest(): void {\n _rgResolution = undefined;\n}\n\n/**\n * Four-tier resolution. Memoized. Mirrors cc-backup\n * `src/utils/ripgrep.ts:31-65`.\n *\n * 1. System rg on PATH — use the literal command name `\"rg\"` (NOT\n * the absolute path). This leverages NoDefaultCurrentDirectory-\n * InExePath on Windows, preventing PATH-hijacking via a\n * malicious ./rg.exe in the proxy's cwd.\n * 2. Router-owned toolbelt copy under APP_DIR. Its absolute path is\n * safe because it cannot resolve to a planted binary in the cwd,\n * and it survives a temp-hosted bunx package tree being reaped.\n * 3. Bundled via `@vscode/ripgrep` — falls back to the per-platform\n * binary that `optionalDependencies` installed.\n * 4. Throw — surfaced to the caller as an MCP isError response.\n */\nexport function resolveRipgrep(): RipgrepResolution {\n if (_rgResolution) return _rgResolution;\n\n // System check: probe PATH for `rg`. We DON'T use the absolute\n // path returned by which/where — using just the command name lets\n // the OS apply NoDefaultCurrentDirectoryInExePath on Windows.\n if (hasSystemRipgrep()) {\n _rgResolution = { rgPath: \"rg\", source: \"system\" };\n return _rgResolution;\n }\n\n // The toolbelt copy is router-owned, so using its absolute path cannot\n // resolve a planted ./rg.exe from the workspace. Unlike the package tree,\n // APP_DIR is not subject to OS temp cleanup.\n const toolbeltPath = path.join(\n PATHS.TOOLBELT_BIN_DIR,\n process.platform === \"win32\" ? \"rg.exe\" : \"rg\",\n );\n if (existsSync(toolbeltPath)) {\n _rgResolution = { rgPath: toolbeltPath, source: \"toolbelt\" };\n return _rgResolution;\n }\n\n // Bundled fallback. require.resolve through the @vscode/ripgrep\n // package's exports — works because v1.18.0 ships per-platform\n // binary packages via optionalDependencies.\n try {\n // Using a dynamic import keeps the dep optional at type level;\n // the package's rgPath export is a string.\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = require(\"@vscode/ripgrep\") as { rgPath: string };\n if (mod.rgPath && existsSync(mod.rgPath)) {\n _rgResolution = { rgPath: mod.rgPath, source: \"bundled\" };\n return _rgResolution;\n }\n } catch {\n // fall through\n }\n\n throw new Error(\n \"ripgrep not found. Either install rg system-wide (brew/apt/winget) \" +\n \"or reinstall the proxy so @vscode/ripgrep's per-platform binary is \" +\n \"fetched. See README's code_search section.\",\n );\n}\n\nfunction hasSystemRipgrep(): boolean {\n // Probe via `which rg` / `where rg`. We don't trust the returned\n // path (PATH-hijack risk) — we just want to know if SOME rg is\n // on PATH. When found, we'll spawn `\"rg\"` and let the OS resolve\n // it again with its own safety guarantees.\n try {\n const cmd = process.platform === \"win32\" ? \"where\" : \"which\";\n const out = execFileSync(cmd, [\"rg\"], {\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 1000,\n });\n return out.length > 0;\n } catch {\n return false;\n }\n}\n\n// ============================================================\n// Input validation\n// ============================================================\n\nfunction validateInputs(input: CodeSearchInput): string | null {\n if (typeof input.query !== \"string\" || input.query.length === 0) {\n return \"code_search: arguments.query is required (non-empty string)\";\n }\n if (input.query.length > MAX_QUERY_LEN) {\n return `code_search: query exceeds ${MAX_QUERY_LEN} chars`;\n }\n if (/[\\0\\r\\n]/.test(input.query)) {\n return \"code_search: query contains null byte or newline (rejected)\";\n }\n if (typeof input.workspace !== \"string\" || input.workspace.length === 0) {\n return \"code_search: arguments.workspace is required (absolute path)\";\n }\n if (input.mode && ![\"ranked\", \"literal\", \"regex\"].includes(input.mode)) {\n return `code_search: mode must be one of \"ranked\", \"literal\", \"regex\"`;\n }\n if (input.file_glob !== undefined) {\n if (typeof input.file_glob !== \"string\") {\n return \"code_search: file_glob must be a string\";\n }\n if (input.file_glob.length > MAX_GLOB_LEN) {\n return `code_search: file_glob exceeds ${MAX_GLOB_LEN} chars`;\n }\n if (/[\\0\\r\\n]/.test(input.file_glob)) {\n return \"code_search: file_glob contains null byte or newline\";\n }\n }\n if (input.limit !== undefined) {\n if (\n typeof input.limit !== \"number\" ||\n !Number.isInteger(input.limit) ||\n input.limit < 1\n ) {\n return \"code_search: limit must be a positive integer\";\n }\n }\n if (input.context_lines !== undefined) {\n if (\n typeof input.context_lines !== \"number\" ||\n !Number.isInteger(input.context_lines) ||\n input.context_lines < 0\n ) {\n return \"code_search: context_lines must be a non-negative integer\";\n }\n }\n return null;\n}\n\n// ============================================================\n// Workspace validation\n// ============================================================\n\ninterface ValidationResult {\n ok: boolean;\n canonical?: string;\n error?: string;\n}\n\n/**\n * Validate a `workspace` arg. The proxy runs as the user; any path\n * the proxy process can `stat` is a legal workspace — mirrors what\n * Claude Code's Read / Bash tools could already reach. Earlier the\n * validator enforced an allow-set + secret-shape file denylist; the\n * holistic threat model showed those were inconsistent guardrails\n * (the model already has filesystem access via its other tools), so\n * they're dropped.\n *\n * Still enforced:\n * - Absolute path (relative paths are an integration-error footgun).\n * - realpath canonicalization (resolves symlinks; output paths are\n * reported relative to this).\n * - Path must exist AND be a directory.\n *\n * Errors do NOT echo the rejected path (output of code_search flows\n * upstream to the model provider; consistent with the\n * COPILOT_HOST_ALLOWLIST pattern in `src/lib/utils.ts`).\n */\nexport function validateWorkspace(workspace: string): ValidationResult {\n if (!path.isAbsolute(workspace)) {\n return { ok: false, error: \"workspace must be an absolute path\" };\n }\n\n let canonical: string;\n try {\n canonical = realpathSync(workspace);\n } catch {\n return { ok: false, error: \"workspace path is not accessible\" };\n }\n\n try {\n if (!statSync(canonical).isDirectory()) {\n // Point at the fix, not just the violation. Passing a file path here is\n // the natural reading of \"any absolute path\", and a bare \"must be a\n // directory\" leaves the caller to guess how to scope to one file.\n return {\n ok: false,\n error:\n \"workspace must be a directory, not a file — pass the containing \" +\n \"directory as `workspace` and use `file_glob` to scope to this file\",\n };\n }\n } catch {\n return { ok: false, error: \"workspace path is not accessible\" };\n }\n\n return { ok: true, canonical };\n}\n\n// ============================================================\n// Tokenization (Vasilescu, Ray, Mockus ESEC/FSE 2021 — rule-based)\n// ============================================================\n\n/**\n * Rule-based identifier splitter per the ESEC/FSE 2021 benchmark.\n *\n * 1. Split on non-word characters.\n * 2. Within each chunk, split on case boundaries with acronym\n * lookahead — `HTTPSConnection` → [`HTTPS`, `Connection`].\n * 3. Attach trailing digit runs to letters — `parseV2Handler` →\n * [`parse`, `V2`, `Handler`] (NOT `[parse, V, 2, Handler]`).\n * 4. Lowercase all tokens.\n * 5. Drop tokens of length < 2 to suppress single-char noise.\n *\n * Limitation: ASCII identifiers only. Unicode identifiers (Cyrillic,\n * CJK, etc.) won't be tokenized. Documented as MVP scope.\n */\nexport function tokenize(text: string): Array<string> {\n const out: Array<string> = [];\n const pieces = text.split(/[^A-Za-z0-9]+/);\n const re = /[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+[0-9]*|[A-Z]+[0-9]*|[0-9]+/g;\n for (const piece of pieces) {\n if (!piece) continue;\n const matches = piece.match(re);\n if (!matches) continue;\n for (const m of matches) {\n const lc = m.toLowerCase();\n if (lc.length >= 2) out.push(lc);\n }\n }\n return out;\n}\n\n// ============================================================\n// Process management\n// ============================================================\n\n/**\n * Platform-aware child termination. On Unix: SIGTERM, then SIGKILL\n * after a brief grace period. On Windows: taskkill /T /F because\n * child.kill() doesn't reliably terminate descendants — a long\n * search with worker threads would leak rg.exe processes.\n */\nfunction killChild(child: ChildProcess): void {\n if (!child.pid || child.killed) return;\n\n if (process.platform === \"win32\") {\n // /T = kill tree (including children of children)\n // /F = force; rg has no graceful-shutdown signal handler on Win.\n // ASYNC (spawn, not spawnSync): killChild fires MID-STREAM on a\n // cap/abort/timeout while the event loop must keep draining ripgrep's\n // output — a synchronous taskkill would block the loop and stall the\n // very read it is racing. (This is why it does NOT use the shutdown-\n // path killChildProcessTree, which is intentionally synchronous.)\n // The shared helper pins System32\\taskkill.exe (a bare name lets\n // CreateProcess resolve a planted binary from the cwd) and attaches the\n // 'error' listener a spawn needs to fail quietly instead of throwing.\n spawnTaskkillBestEffort(child.pid);\n return;\n }\n\n try {\n child.kill(\"SIGTERM\");\n } catch {\n // already dead\n }\n // Hard kill after 500 ms if it didn't go quietly.\n setTimeout(() => {\n if (!child.killed) {\n try {\n child.kill(\"SIGKILL\");\n } catch {\n // already dead\n }\n }\n }, 500).unref();\n}\n\n// ============================================================\n// Identifier skeleton-form query expansion\n// ============================================================\n\n/**\n * Single-identifier query matcher. We only expand queries that look\n * like a single identifier — any whitespace, regex metacharacters, or\n * structural punctuation defeats the expansion and we fall through to\n * the original rg behavior. ASCII-only on purpose (matches the\n * tokenizer's scope; Unicode identifiers are MVP-out).\n */\nconst SINGLE_IDENTIFIER_REGEX = /^[A-Za-z][A-Za-z0-9_-]{0,127}$/;\n\n/**\n * Split an identifier into its constituent word-pieces, recognizing\n *\n * - snake_case (split on `_`)\n * - kebab-case (split on `-`)\n * - camelCase (split on lowercase→uppercase boundaries)\n * - PascalCase (each capitalized run is a piece)\n * - acronym runs (HTTPSConnection → [HTTPS, Connection])\n * - trailing digits attached to letters (parseV2 → [parse, V2])\n *\n * Pieces are returned in source-order, with the original case\n * preserved per piece — re-skeletons compose by re-casing each piece.\n */\nfunction splitIdentifierPieces(identifier: string): Array<string> {\n const pieces: Array<string> = [];\n for (const chunk of identifier.split(/[-_]/)) {\n if (!chunk) continue;\n // Acronym-aware case-boundary split. Same regex as the BM25F\n // tokenizer, minus the lowercasing — we want original-case\n // pieces so we can re-cast them per skeleton.\n const matches = chunk.match(\n /[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+[0-9]*|[A-Z]+[0-9]*|[0-9]+/g,\n );\n if (matches) pieces.push(...matches);\n }\n return pieces;\n}\n\n/**\n * Produce skeleton variants for an identifier query. Returns `null`\n * when the query is not a single identifier or has only one piece\n * (no skeleton structure to vary across) — caller falls through to\n * the literal-search path.\n *\n * The variant set covers the five conventions any real codebase\n * mixes:\n *\n * getUserName (lowerCamelCase)\n * GetUserName (UpperCamelCase / PascalCase)\n * get_user_name (snake_case)\n * get-user-name (kebab-case)\n * GET_USER_NAME (UPPER_SNAKE_CASE)\n *\n * The set is deduplicated so identifiers that collapse skeletons\n * (e.g., single-word queries) don't bloat the regex pointlessly.\n */\nfunction expandIdentifierVariants(query: string): Array<string> | null {\n if (!SINGLE_IDENTIFIER_REGEX.test(query)) return null;\n const pieces = splitIdentifierPieces(query);\n if (pieces.length < 2) return null;\n const lower = pieces.map((p) => p.toLowerCase());\n const upper = pieces.map((p) => p.toUpperCase());\n const cap = lower.map((p) => p.charAt(0).toUpperCase() + p.slice(1));\n const variants = new Set<string>();\n variants.add(query);\n variants.add(lower[0] + cap.slice(1).join(\"\")); // camelCase\n variants.add(cap.join(\"\")); // PascalCase\n variants.add(lower.join(\"_\")); // snake_case\n variants.add(lower.join(\"-\")); // kebab-case\n variants.add(upper.join(\"_\")); // UPPER_SNAKE_CASE\n return Array.from(variants);\n}\n\n/**\n * Build the rg regex pattern for a set of skeleton variants. The\n * variants are already plain identifiers (no regex metacharacters),\n * so simple alternation suffices. Word boundaries are intentionally\n * NOT applied — the user's mental model for \"search for getUserName\"\n * is substring-anywhere, which is also what `-F getUserName` did.\n */\nfunction buildExpansionPattern(variants: ReadonlyArray<string>): string {\n return \"(?:\" + variants.join(\"|\") + \")\";\n}\n\nfunction buildRgArgs(input: {\n mode: \"ranked\" | \"literal\" | \"regex\";\n fileGlob?: string;\n contextLines: number;\n query: string;\n /**\n * When set, the caller has expanded the original query into a\n * regex alternation across skeleton-form variants. We override\n * `-F` (literal) regardless of the user's chosen mode and pass\n * the alternation as a ripgrep regex pattern. The original-mode\n * literal semantics are preserved because the variants are plain\n * identifiers (no regex metacharacters).\n */\n expansionPattern?: string;\n /** When true, skip the per-file `--max-count` cap (floor mode). */\n complete?: boolean;\n /** When true, add `-U --multiline-dotall` so a pattern can span lines. */\n multiline?: boolean;\n}): Array<string> {\n const args: Array<string> = [\"--json\", \"--no-binary\", \"--no-follow\"];\n\n // Thread budget (Phase 1, A5): size ripgrep's own thread pool from LIVE\n // search concurrency. A sole searcher gets all cores (rg default\n // behavior); N concurrent searches divide them so 16 parallel queries\n // don't each fan out to `cpus` threads and thrash a 4-core box.\n // Evaluated at spawn time — after the A8 slot is held, so the count\n // includes this call.\n args.push(\"-j\", String(recommendedRgThreads()));\n\n // Multi-line matching: `-U` lets a pattern span newlines, and\n // `--multiline-dotall` makes `.` match `\\n` too (so `foo.*bar` crosses\n // lines). Opt-in only — the default stays line-oriented, which is the\n // proven recall floor. With `-F` (fixed-string) `-U` still matches a\n // multi-line literal; with regex it enables cross-line patterns.\n if (input.multiline) {\n args.push(\"-U\", \"--multiline-dotall\");\n }\n\n // -C N means N lines BEFORE and N AFTER. We always want context\n // for snippet rendering AND for the BM25F context field.\n if (input.contextLines > 0) {\n args.push(`-C`, String(input.contextLines));\n }\n\n // Literal mode → -F. Ranked mode uses literal too (we want\n // exact-string semantics for the user's query; BM25F handles\n // tokenized matching at scoring time, not at rg time). Regex\n // mode uses ripgrep's default (PCRE2-via-builtin).\n //\n // EXCEPTION: when the caller passed `expansionPattern`, we drop\n // `-F` and feed the alternation as a regex. Skeleton expansion is\n // mutually exclusive with literal-mode semantics — but the\n // variants are still plain identifiers, so it remains\n // identifier-substring matching (the user's intent).\n if (\n !input.expansionPattern &&\n (input.mode === \"literal\" || input.mode === \"ranked\")\n ) {\n args.push(\"-F\");\n }\n\n if (input.fileGlob && input.fileGlob !== \"**/*\") {\n args.push(\"-g\", input.fileGlob);\n }\n\n // Per-file match cap in DEFAULT ranked mode (see RANKED_MAX_PER_FILE):\n // keeps one match-dense file from filling the global limit and blinding\n // BM25F. `complete: true` and literal/regex modes skip it so the full\n // match set is returned.\n if (input.mode === \"ranked\" && !input.complete) {\n args.push(\"--max-count\", String(RANKED_MAX_PER_FILE));\n }\n\n // CVE fix HIGH-2: positional separator. Without `--`, a query\n // starting with `-` (e.g. `--no-ignore`) would be parsed as a\n // ripgrep flag.\n args.push(\"--\", input.expansionPattern ?? input.query, \".\");\n\n return args;\n}\n\n// ============================================================\n// JSON streaming parser\n// ============================================================\n\ninterface RgEvent {\n type: string;\n data: {\n path?: { text: string };\n lines?: { text: string };\n line_number?: number;\n submatches?: Array<{\n match: { text: string };\n start: number;\n end: number;\n }>;\n stats?: { searches?: number };\n };\n}\n\ninterface ParseResult {\n hits: Array<RawHit>;\n scannedFiles: number;\n truncated: boolean;\n cancelled: boolean;\n stdoutBytes: number;\n}\n\n/**\n * Stream-parse ripgrep --json output. Two load-bearing behaviors:\n *\n * 1. GLOBAL limit cap (NOT per-file — MEDIUM-10). Once we've\n * accumulated `limit` hits, send SIGTERM and stop emitting.\n *\n * 2. CANCEL RACE short-circuit (HIGH-9, 3-lab confirmed). The\n * moment `signal.aborted` flips, detach the line listener AND\n * return early. A half-flushed truncated JSON line never\n * reaches JSON.parse — that's the bug we're guarding against.\n */\nasync function parseRgJsonStream(\n child: ChildProcess,\n opts: { limit: number; contextLines: number; signal: AbortSignal },\n): Promise<ParseResult> {\n const hits: Array<RawHit> = [];\n let stdoutBytes = 0;\n let truncatedByCap = false;\n let cancelled = false;\n let scannedFiles = 0;\n\n // Pre-aborted: short-circuit before constructing the reader. Calling\n // rl.close() before the async iterator starts can hang on some\n // platforms (observed on Bun); avoid the readline construction\n // entirely.\n if (opts.signal.aborted) {\n killChild(child);\n return {\n hits,\n scannedFiles: 0,\n truncated: false,\n cancelled: true,\n stdoutBytes: 0,\n };\n }\n\n // Per-file accumulator: rg streams begin → context*before → match\n // → context*after → end. We buffer context_before lines per file\n // so we can attach them to the next match in that file.\n const pendingContextBefore: Array<string> = [];\n let lastHitForContext: RawHit | undefined;\n\n if (!child.stdout) {\n return {\n hits,\n scannedFiles: 0,\n truncated: false,\n cancelled: false,\n stdoutBytes: 0,\n };\n }\n\n child.stdout.setEncoding(\"utf8\"); // match stderr treatment at line 1749\n const rl = createInterface({ input: child.stdout, crlfDelay: Infinity });\n\n // Wire abort: on signal, immediately tear down the reader and\n // kill the child. The early `cancelled = true` flag stops the\n // line handler from attempting JSON.parse on partial chunks.\n const onAbort = (): void => {\n cancelled = true;\n rl.close();\n killChild(child);\n };\n opts.signal.addEventListener(\"abort\", onAbort, { once: true });\n\n try {\n for await (const rawLine of rl) {\n if (cancelled) break;\n stdoutBytes += rawLine.length + 1; // +1 for the elided \\n\n if (stdoutBytes > MAX_STDOUT_BYTES) {\n truncatedByCap = true;\n killChild(child);\n break;\n }\n // Defense-in-depth: strip NUL bytes that survive despite --no-binary\n // (e.g. if rg's binary detection is fooled by a file with NUL only\n // beyond the 8KB detection window). Resource accounting above uses\n // rawLine.length (honest); parsing below uses the sanitized line.\n const line = rawLine.includes(\"\\0\")\n ? rawLine.replace(/\\0/g, \"\")\n : rawLine;\n if (line.length === 0) continue;\n\n let evt: RgEvent;\n try {\n evt = JSON.parse(line) as RgEvent;\n } catch {\n // Skip malformed lines rather than failing the whole call.\n // A truncated chunk at process death would also land here;\n // the cancelled flag check above handles the common case.\n continue;\n }\n\n switch (evt.type) {\n case \"begin\": {\n scannedFiles += 1;\n pendingContextBefore.length = 0;\n lastHitForContext = undefined;\n break;\n }\n case \"context\": {\n const text = stripTrailingNewline(evt.data.lines?.text ?? \"\");\n if (\n lastHitForContext &&\n lastHitForContext.context_after.length < opts.contextLines\n ) {\n lastHitForContext.context_after.push(text);\n } else {\n pendingContextBefore.push(text);\n if (pendingContextBefore.length > opts.contextLines) {\n pendingContextBefore.shift();\n }\n }\n break;\n }\n case \"match\": {\n if (hits.length >= opts.limit) {\n // Global limit reached. Kill child and stop reading.\n killChild(child);\n break;\n }\n const sub = evt.data.submatches?.[0];\n if (\n !evt.data.path ||\n !evt.data.lines ||\n !evt.data.line_number ||\n !sub\n ) {\n break;\n }\n const hit: RawHit = {\n file: evt.data.path.text,\n line: evt.data.line_number,\n matched_line: stripTrailingNewline(evt.data.lines.text),\n match_start: sub.start,\n match_end: sub.end,\n context_before: [...pendingContextBefore],\n context_after: [],\n };\n pendingContextBefore.length = 0;\n lastHitForContext = hit;\n hits.push(hit);\n break;\n }\n case \"end\":\n case \"summary\":\n default:\n // Nothing actionable. The \"summary\" event arrives after\n // the entire stream; \"end\" arrives per-file. Both are\n // informational here.\n break;\n }\n }\n } finally {\n opts.signal.removeEventListener(\"abort\", onAbort);\n }\n\n return {\n hits,\n scannedFiles,\n truncated: truncatedByCap || hits.length >= opts.limit,\n cancelled,\n stdoutBytes,\n };\n}\n\nfunction stripTrailingNewline(s: string): string {\n if (s.endsWith(\"\\r\\n\")) return s.slice(0, -2);\n if (s.endsWith(\"\\n\")) return s.slice(0, -1);\n return s;\n}\n\n/**\n * Normalize a ripgrep-relative path to the form used in the rendered output\n * (strip a leading \"./\" or \".\\\", convert \"\\\" → \"/\"). Used to key the pooled\n * structural-outline map so the outline loop's lookup (which iterates rendered\n * result files) matches regardless of OS path separators or rg's \"./\" prefix.\n */\nfunction normalizeRelFile(file: string): string {\n let f = file;\n if (f.startsWith(\"./\") || f.startsWith(\".\\\\\")) f = f.slice(2);\n return f.replace(/\\\\/g, \"/\");\n}\n\n// ============================================================\n// Tree-sitter structural ranking\n// ============================================================\n//\n// The grammar layer this pass depends on — the extension/grammar\n// tables, the definition-/identifier-node-type sets, and the lazily\n// initialized `web-tree-sitter` parser cache — lives in\n// `~/lib/tree-sitter-grammars` and is imported at the top of this file.\n// Only the BM25F-coupled tree cache + structural-confirmation walk stay\n// here.\n\n/**\n * Tree cache. Keyed by canonical file path with mtime gate — on\n * mtime change the cache entry is invalidated (and the old Tree's\n * native memory is freed via `.delete()`). LRU eviction at\n * STRUCTURAL_CACHE_MAX entries; null trees indicate prior failure\n * and short-circuit re-parsing for the same mtime.\n */\ninterface CachedTree {\n mtimeMs: number;\n /** null = tried, parse failed (or unsupported language). */\n tree: Tree | null;\n /** Source bytes — we need them at structural-walk time to compute\n * byte offsets from line numbers. Kept alongside the tree so the\n * next call on the same (file, mtime) doesn't re-read. */\n source: string | null;\n}\n\nconst _treeCache = new Map<string, CachedTree>();\n\nfunction cacheGet(absPath: string, mtimeMs: number): CachedTree | undefined {\n const cur = _treeCache.get(absPath);\n if (!cur) return undefined;\n if (cur.mtimeMs !== mtimeMs) {\n // File changed since cache entry — discard.\n if (cur.tree) {\n try {\n cur.tree.delete();\n } catch {\n // Tree already collected\n }\n }\n _treeCache.delete(absPath);\n return undefined;\n }\n // Touch for LRU ordering.\n _treeCache.delete(absPath);\n _treeCache.set(absPath, cur);\n return cur;\n}\n\nfunction cachePut(absPath: string, entry: CachedTree): void {\n // Evict oldest if at cap. Map iteration order is insertion order\n // (and we re-insert on access in cacheGet), so the first key is\n // the oldest.\n while (_treeCache.size >= STRUCTURAL_CACHE_MAX) {\n const firstKey = _treeCache.keys().next().value;\n if (firstKey === undefined) break;\n const evicted = _treeCache.get(firstKey);\n if (evicted?.tree) {\n try {\n evicted.tree.delete();\n } catch {\n // Best effort\n }\n }\n _treeCache.delete(firstKey);\n }\n _treeCache.set(absPath, entry);\n}\n\ninterface StructuralPassResult {\n /** Indexes (into the input hits array) where AST confirmed the\n * matched identifier is at a definition site. */\n confirmedHitIndexes: Set<number>;\n /** null = success (entire top-N parsed within budget). String =\n * budget exceeded mid-pass, with explanation suitable for surfacing\n * to the model as the `notice` field (overridden by size-cap notice\n * at the handler boundary when both fire). */\n fallback: string | null;\n /**\n * Outline entries the parse PRODUCED for each file, keyed by RELATIVE file\n * path. Populated ONLY on the worker-pool path: a `Tree` can't cross the\n * thread boundary, so Lever 1's in-process tree reuse can't apply across\n * threads — instead the pool returns outline entries alongside the confirm\n * result (the coalesced job), and `searchCode`'s outline loop reuses these\n * before falling back. On the in-process path this is undefined and the\n * outline loop reuses `_treeCache` directly, exactly as before.\n */\n outlinesByFile?: Map<string, Array<FileOutlineEntry>>;\n}\n\n/**\n * Benchmark-only instrumentation. Zero cost in production: nothing writes\n * here unless `GH_ROUTER_BENCH_STRUCTURAL=1`. Exposes the actual number of\n * DISTINCT files the structural pass parsed (vs the ≤topN *hits* it\n * considered) and the wall-clock spent inside it, so the parallelism\n * benchmark can attribute end-to-end cost honestly rather than infer it.\n * Read + reset by `scripts/bench-code-search-parallelism.ts`.\n */\nexport interface BenchStructuralStats {\n calls: number;\n filesParsed: number;\n filesConsidered: number;\n budgetHit: number;\n parseMsTotal: number;\n}\nconst _benchStructural: BenchStructuralStats = {\n calls: 0,\n filesParsed: 0,\n filesConsidered: 0,\n budgetHit: 0,\n parseMsTotal: 0,\n};\nconst _benchStructuralOn = (): boolean =>\n process.env.GH_ROUTER_BENCH_STRUCTURAL === \"1\";\nexport function __readBenchStructuralStats(): BenchStructuralStats {\n return { ..._benchStructural };\n}\nexport function __resetBenchStructuralStats(): void {\n _benchStructural.calls = 0;\n _benchStructural.filesParsed = 0;\n _benchStructural.filesConsidered = 0;\n _benchStructural.budgetHit = 0;\n _benchStructural.parseMsTotal = 0;\n}\n\n/**\n * Run the structural-confirmation pass over the top-N already-ranked\n * BM25F hits. Wall-clock-bounded — checked between files, not mid-\n * parse. web-tree-sitter 0.26 DOES expose a cancel hook\n * (`ParseOptions.progressCallback`, cancels when it returns true), so\n * mid-parse cancellation is now possible; it is deliberately not wired\n * in here, because the budget only overruns on a single pathological\n * file and tightening that is a behavior change, not part of an upgrade.\n *\n * Per-file failure modes (file too big, language unsupported, parse\n * error, I/O error) are silent: the file's hits keep the regex\n * `symbol_context` heuristic. Only the wall-clock budget fires the\n * user-visible `fallback` message.\n */\n/**\n * Group the top-`topN` ranked hits by file, preserving rank order of files\n * (first-seen). Shared by the in-process and pooled structural passes so both\n * consider the identical file set. Each file maps to its hits' rg offsets +\n * the original hit index.\n */\nfunction groupHitsByFile(\n hitsRanked: Array<{ hit: RawHit; index: number }>,\n topN: number,\n): Map<string, Array<{ hit: RawHit; index: number }>> {\n const cap = Math.min(hitsRanked.length, topN);\n const byFile = new Map<string, Array<{ hit: RawHit; index: number }>>();\n for (let i = 0; i < cap; i++) {\n const entry = hitsRanked[i];\n const list = byFile.get(entry.hit.file) ?? [];\n list.push(entry);\n byFile.set(entry.hit.file, list);\n }\n return byFile;\n}\n\n/**\n * Run the structural-confirmation pass over the top-N ranked hits. Tries the\n * warm worker-thread parse pool first (parallel parses off the main event\n * loop — the measured win for concurrent `code` calls; see\n * `docs/research/tree-sitter-parallelism.md`); on pool unavailability,\n * disablement, or total pool failure it falls back to the in-process path,\n * which is behavior-identical to pre-Lever-2. Both paths produce the SAME\n * confirmed-index set for the same inputs (the shared `confirmDefinitionSites`\n * walk + order-independent Set merge), so the determinism test holds either\n * way.\n */\nasync function runStructuralPass(opts: {\n hitsRanked: Array<{ hit: RawHit; index: number }>;\n workspaceRoot: string;\n topN: number;\n budgetMs: number;\n signal: AbortSignal;\n}): Promise<StructuralPassResult> {\n const result: StructuralPassResult = {\n confirmedHitIndexes: new Set(),\n fallback: null,\n };\n if (opts.hitsRanked.length === 0 || opts.signal.aborted) return result;\n\n const grammars = await getGrammarBundle().ready;\n if (grammars.size === 0) return result;\n\n const byFile = groupHitsByFile(opts.hitsRanked, opts.topN);\n const cap = Math.min(opts.hitsRanked.length, opts.topN);\n const benchOn = _benchStructuralOn();\n if (benchOn) {\n _benchStructural.calls += 1;\n _benchStructural.filesConsidered += byFile.size;\n }\n\n const pool = getTreeSitterPool();\n if (pool) {\n const pooled = await runStructuralPassPooled({\n pool,\n byFile,\n grammars,\n workspaceRoot: opts.workspaceRoot,\n cap,\n budgetMs: opts.budgetMs,\n signal: opts.signal,\n benchOn,\n });\n if (pooled) return pooled;\n // Pool returned null (total failure / unavailable mid-run) → fall through\n // to the in-process path below, which is the always-correct baseline.\n }\n\n return runStructuralPassInProcess({\n byFile,\n grammars,\n workspaceRoot: opts.workspaceRoot,\n cap,\n budgetMs: opts.budgetMs,\n signal: opts.signal,\n benchOn,\n result,\n });\n}\n\n/**\n * Pooled structural pass. Builds one COALESCED job per file (confirm + outline\n * in a single parse), dispatches across the pool under the wall-clock budget,\n * and merges replies order-independently. Returns `null` when the pool produced\n * no usable result (so the caller falls back in-process).\n */\nasync function runStructuralPassPooled(opts: {\n pool: TreeSitterPool;\n byFile: Map<string, Array<{ hit: RawHit; index: number }>>;\n grammars: Map<string, Language>;\n workspaceRoot: string;\n cap: number;\n budgetMs: number;\n signal: AbortSignal;\n benchOn: boolean;\n}): Promise<StructuralPassResult | null> {\n const jobs: Array<PoolJob> = [];\n // Per file: the list of hit indexes in dispatch order, so we can map the\n // worker's returned positions back to original hit indexes.\n const indexMap = new Map<string, Array<number>>();\n for (const [relFile, entries] of opts.byFile) {\n const langKey = getLanguageKeyForPath(relFile);\n if (!langKey || !opts.grammars.has(langKey)) continue;\n const absPath = path.join(opts.workspaceRoot, relFile);\n let mtimeMs: number;\n try {\n const st = statSync(absPath);\n if (st.size > STRUCTURAL_MAX_FILE_BYTES) continue;\n mtimeMs = st.mtimeMs;\n } catch {\n continue;\n }\n const confirmHits: Array<StructuralHit> = entries.map((e) => ({\n line: e.hit.line,\n matchStart: e.hit.match_start,\n matchEnd: e.hit.match_end,\n }));\n indexMap.set(\n relFile,\n entries.map((e) => e.index),\n );\n jobs.push({\n file: relFile,\n absPath,\n language: langKey,\n mtimeMs,\n confirmHits,\n // Coalesce the outline walk so a file used by both the structural pass\n // and the outline summary is parsed exactly once worker-side (the\n // threaded equivalent of Lever 1's in-process tree reuse).\n outline: true,\n });\n }\n\n const run = await opts.pool.parseFiles(jobs, {\n budgetMs: opts.budgetMs,\n signal: opts.signal,\n });\n if (!run) return null; // pool unavailable / total failure → in-process fallback\n\n const confirmedHitIndexes = new Set<number>();\n const outlinesByFile = new Map<string, Array<FileOutlineEntry>>();\n for (const job of jobs) {\n const fileResult = run.byFile.get(job.file);\n if (!fileResult || !fileResult.ok) continue;\n const origIndexes = indexMap.get(job.file) ?? [];\n // Map worker-returned positions (into confirmHits) → original hit indexes.\n for (const pos of fileResult.confirmedHitIndexes) {\n const orig = origIndexes[pos];\n if (orig !== undefined) confirmedHitIndexes.add(orig);\n }\n if (fileResult.outlineEntries) {\n // Key by the normalized (rendered) path so the outline loop's lookup —\n // which iterates rendered result files — matches across OS separators.\n outlinesByFile.set(normalizeRelFile(job.file), fileResult.outlineEntries);\n }\n }\n\n if (opts.benchOn) {\n _benchStructural.filesParsed += run.byFile.size;\n if (run.budgetHit) _benchStructural.budgetHit += 1;\n }\n\n return {\n confirmedHitIndexes,\n fallback: run.budgetHit\n ? `structural budget exceeded after parsing ${run.byFile.size}/${jobs.length} files; ` +\n `retry with structural: \"topN\" or narrow your query`\n : null,\n outlinesByFile,\n };\n}\n\n/**\n * In-process structural pass (the always-correct baseline; identical to\n * pre-Lever-2 behavior). Parses each file synchronously on the main thread,\n * caches the tree in `_treeCache` for the outline loop to reuse (Lever 1), and\n * walks each hit. Wall-clock-bounded — checked between files, not mid-parse\n * (see the note on the top-N pass above: 0.26 has a cancel hook, intentionally\n * unused).\n *\n * Per-file failure modes (file too big, language unsupported, parse error, I/O\n * error) are silent: the file's hits keep the regex `symbol_context` heuristic.\n * Only the wall-clock budget fires the user-visible `fallback` message.\n */\n/**\n * Bounded concurrency for the structural-pass pre-read (Phase 1 below).\n * Disk reads overlap; parses stay serial (single WASM heap). 8 keeps a\n * slow network FS from fanning out unboundedly while still collapsing N\n * serial round-trips into ~one batch on typical top-N sets (≤50 files).\n */\nconst STRUCTURAL_PREREAD_CONCURRENCY = 8;\n\n/** One file's Phase-1 (I/O) outcome, consumed by the serial parse loop. */\ntype StructuralFileInput =\n | { kind: \"skip\" }\n | { kind: \"cached\"; cached: CachedTree }\n | { kind: \"fresh\"; mtimeMs: number; source: string }\n | { kind: \"readfail\"; mtimeMs: number };\n\nasync function runStructuralPassInProcess(opts: {\n byFile: Map<string, Array<{ hit: RawHit; index: number }>>;\n grammars: Map<string, Language>;\n workspaceRoot: string;\n cap: number;\n budgetMs: number;\n signal: AbortSignal;\n benchOn: boolean;\n result: StructuralPassResult;\n}): Promise<StructuralPassResult> {\n const { byFile, grammars, cap, benchOn, result } = opts;\n let filesParsed = 0;\n const parsersUsed = new Map<string, Parser>();\n\n // Phase 1: concurrent stat + read. Parses must serialize (single WASM\n // heap), but the stat/readFile I/O feeding them need not — batch the disk\n // round-trips, then parse serially from memory in Phase 2. The wall-clock\n // budget gates the parse loop only, so a slow batch-read can't silently\n // consume it. Order-preserving: inputs align 1:1 with byFile order, so\n // the parse loop below sees the identical sequence as before.\n const fileList = [...byFile];\n const inputs: Array<StructuralFileInput> = new Array(fileList.length);\n {\n const tasks: Array<() => Promise<StructuralFileInput>> = fileList.map(\n ([relFile]) =>\n async (): Promise<StructuralFileInput> => {\n const langKey = getLanguageKeyForPath(relFile);\n if (!langKey) return { kind: \"skip\" }; // unsupported — silent skip\n if (!grammars.get(langKey)) return { kind: \"skip\" }; // no grammar — silent skip\n const absPath = path.join(opts.workspaceRoot, relFile);\n let mtimeMs: number;\n let size: number;\n try {\n // No signal: stat is metadata-only and fast; the worker-loop\n // abort check above plus the Phase-2 gate cover cancellation.\n const st = await stat(absPath);\n mtimeMs = st.mtimeMs;\n size = st.size;\n } catch (err) {\n if (opts.signal.aborted) return { kind: \"skip\" };\n consola.debug(\n `[code_search] structural skip ${relFile} (stat failed: ${(err as Error).message})`,\n );\n return { kind: \"skip\" };\n }\n if (size > STRUCTURAL_MAX_FILE_BYTES) {\n consola.debug(\n `[code_search] structural skip ${relFile} (${size} bytes > cap)`,\n );\n return { kind: \"skip\" };\n }\n // Cache hit → no read needed; the parse loop reuses the tree.\n const cached = cacheGet(absPath, mtimeMs);\n if (cached) return { kind: \"cached\", cached };\n try {\n const source = await readFile(absPath, {\n encoding: \"utf8\",\n signal: opts.signal,\n });\n return { kind: \"fresh\", mtimeMs, source };\n } catch (err) {\n if (opts.signal.aborted) return { kind: \"skip\" };\n consola.debug(\n `[code_search] structural skip ${relFile} (read failed: ${(err as Error).message})`,\n );\n return { kind: \"readfail\", mtimeMs };\n }\n },\n );\n let next = 0;\n const workers = Array.from(\n { length: Math.min(STRUCTURAL_PREREAD_CONCURRENCY, tasks.length) },\n async () => {\n while (true) {\n if (opts.signal.aborted) break;\n const i = next;\n next += 1;\n if (i >= tasks.length) break;\n inputs[i] = await tasks[i]();\n }\n },\n );\n await Promise.all(workers);\n // Slots never reached after an abort resolve as skips.\n for (let i = 0; i < inputs.length; i++) inputs[i] ??= { kind: \"skip\" };\n }\n\n // Phase 2: serial parse + confirm, budget-gated exactly as before.\n const t0 = Date.now();\n try {\n for (let fi = 0; fi < fileList.length; fi++) {\n if (opts.signal.aborted) break;\n const elapsed = Date.now() - t0;\n if (elapsed >= opts.budgetMs) {\n if (benchOn) _benchStructural.budgetHit += 1;\n result.fallback =\n `structural budget exceeded after parsing ${filesParsed}/${cap} hits; ` +\n `retry with structural: \"topN\" or narrow your query`;\n break;\n }\n\n const [relFile, entries] = fileList[fi];\n const input = inputs[fi];\n if (input.kind === \"skip\") continue;\n\n const langKey = getLanguageKeyForPath(relFile);\n if (!langKey) continue; // unsupported extension — silent skip\n const lang = grammars.get(langKey);\n if (!lang) continue; // grammar failed to load — silent skip\n\n const absPath = path.join(opts.workspaceRoot, relFile);\n\n let cached: CachedTree;\n if (input.kind === \"cached\") {\n cached = input.cached;\n } else if (input.kind === \"readfail\") {\n cachePut(absPath, { mtimeMs: input.mtimeMs, tree: null, source: null });\n continue;\n } else {\n let parser = parsersUsed.get(langKey);\n if (!parser) {\n parser = new Parser();\n parser.setLanguage(lang);\n parsersUsed.set(langKey, parser);\n }\n let tree: Tree | null = null;\n try {\n const pt0 = benchOn ? performance.now() : 0;\n tree = parser.parse(input.source);\n if (benchOn) _benchStructural.parseMsTotal += performance.now() - pt0;\n } catch (err) {\n consola.debug(\n `[code_search] tree-sitter parse failed for ${relFile}: ${(err as Error).message}`,\n );\n }\n cached = {\n mtimeMs: input.mtimeMs,\n tree,\n source: tree ? input.source : null,\n };\n cachePut(absPath, cached);\n filesParsed += 1;\n if (benchOn) _benchStructural.filesParsed += 1;\n }\n\n if (!cached.tree || !cached.source) continue;\n\n // Confirm every hit's matched identifier via the SHARED walk — the same\n // `confirmDefinitionSites` the worker pool runs, so the in-process and\n // pooled paths produce byte-identical confirmed sets (the determinism\n // requirement). Returns positions into `entries`; map back to the\n // original hit indexes.\n const confirmedPositions = confirmDefinitionSites(\n cached.tree,\n cached.source,\n langKey,\n entries.map((e) => ({\n line: e.hit.line,\n matchStart: e.hit.match_start,\n matchEnd: e.hit.match_end,\n })),\n opts.signal,\n );\n for (const pos of confirmedPositions) {\n const entry = entries[pos];\n if (entry) result.confirmedHitIndexes.add(entry.index);\n }\n }\n } finally {\n // Tree-sitter Parser instances are reusable and we don't hold\n // them across calls; freeing keeps native memory clean.\n for (const parser of parsersUsed.values()) {\n try {\n parser.delete();\n } catch {\n // Best effort\n }\n }\n }\n\n return result;\n}\n\ninterface FieldTexts {\n match_line: string;\n context: string;\n file_path: string;\n symbol_context: string;\n}\n\nfunction extractFields(hit: RawHit, astConfirmed: boolean): FieldTexts {\n const ctx = [...hit.context_before, ...hit.context_after].join(\"\\n\");\n let symbolContext: string;\n if (astConfirmed) {\n // Tree-sitter confirmed: this is a real identifier-definition\n // site. Populate `symbol_context` with the matched identifier\n // text so the BM25F field-weight (2.5x) fires for this hit even\n // when the regex heuristic would have left the field empty —\n // the live correctness fix described in the brief.\n const ident = hit.matched_line.slice(hit.match_start, hit.match_end);\n // Guard: rg submatch offsets can be empty / out-of-range for\n // multiline matches — fall back to the matched line so we still\n // get a non-empty field.\n symbolContext = ident.length > 0 ? ident : hit.matched_line;\n } else if (SYMBOL_REGEX.test(hit.matched_line.trimStart())) {\n // Regex heuristic remains in place for hits the AST hasn't\n // confirmed (top-N spillover, unsupported language, parse\n // error, budget overrun). Same field shape as v1.\n symbolContext = hit.matched_line;\n } else {\n symbolContext = \"\";\n }\n return {\n match_line: hit.matched_line,\n context: ctx,\n file_path: hit.file.replace(/[/\\\\]/g, \" \"),\n symbol_context: symbolContext,\n };\n}\n\ninterface ScoredHit {\n hit: RawHit;\n score: number;\n field_contributions: Record<string, number>;\n}\n\n/**\n * BM25F score for the given hit set against the tokenized query.\n *\n * BM25F(q, f) = Σ_t IDF(t) · w_t,f / (w_t,f + k1)\n *\n * w_t,f = Σ_field b_field · tf_t,field,f /\n * ((1 − l_field) + l_field · len_field,f/avglen_field)\n *\n * IDF(t) = log( (M − df(t) + 0.5) / (df(t) + 0.5) )\n *\n * Corpus stats are derived from the rg hit set itself — we have no\n * persistent index. M = number of files in the hit set; df(t) = how\n * many of those files contain token `t` in any field; avglen_f =\n * mean tokenized length of field `f` across those files. This is\n * the \"compute corpus stats per-call\" pattern, which works because\n * M ≤ a few hundred files in practice (sub-second).\n */\nfunction bm25fScore(\n hits: ReadonlyArray<RawHit>,\n queryTokens: ReadonlyArray<string>,\n /**\n * Indexes (into `hits`) for which tree-sitter has confirmed the\n * matched identifier sits at a real definition site. Drives the\n * `extractFields` symbol_context override. Pass `undefined` (or an\n * empty Set) to score with the regex heuristic only — matches the\n * v1 behavior, used as the first pass before structural ranking\n * runs.\n */\n astConfirmedHits?: ReadonlySet<number>,\n): Array<ScoredHit> {\n if (hits.length === 0 || queryTokens.length === 0) {\n return hits.map((h) => ({\n hit: h,\n score: 0,\n field_contributions: {\n match_line: 0,\n symbol_context: 0,\n file_path: 0,\n context: 0,\n },\n }));\n }\n\n // Per-file tokenization (cache by file path to avoid re-tokenizing\n // the same path across multiple hits in one file).\n const fileTokenCache = new Map<string, FieldTexts>();\n const perHitTokens: Array<Record<keyof FieldTexts, Array<string>>> = [];\n for (let i = 0; i < hits.length; i++) {\n const hit = hits[i];\n const confirmed = astConfirmedHits?.has(i) ?? false;\n const fields = extractFields(hit, confirmed);\n fileTokenCache.set(hit.file, fields);\n perHitTokens.push({\n match_line: tokenize(fields.match_line),\n context: tokenize(fields.context),\n file_path: tokenize(fields.file_path),\n symbol_context: tokenize(fields.symbol_context),\n });\n }\n\n // Distinct files for IDF.\n const filesSeen = new Set<string>();\n for (const hit of hits) filesSeen.add(hit.file);\n const M = filesSeen.size;\n\n // df(t) per query token: number of distinct files where ANY field\n // contains t. We compute over the hit set; this is the per-call\n // corpus.\n const df = new Map<string, number>();\n const fileTokensByField: Record<\n keyof FieldTexts,\n Map<string, Set<string>>\n > = {\n match_line: new Map(),\n context: new Map(),\n file_path: new Map(),\n symbol_context: new Map(),\n };\n // First pass: build file → token-set per field, so df is per-file\n // not per-hit (multiple hits in one file shouldn't inflate df).\n for (let i = 0; i < hits.length; i++) {\n const file = hits[i].file;\n const t = perHitTokens[i];\n for (const fname of Object.keys(t) as Array<keyof FieldTexts>) {\n let bucket = fileTokensByField[fname].get(file);\n if (!bucket) {\n bucket = new Set();\n fileTokensByField[fname].set(file, bucket);\n }\n for (const tok of t[fname]) bucket.add(tok);\n }\n }\n // Now compute df: count files containing the query token in any field.\n for (const qt of queryTokens) {\n const files = new Set<string>();\n for (const fname of Object.keys(fileTokensByField) as Array<\n keyof FieldTexts\n >) {\n for (const [file, tokSet] of fileTokensByField[fname]) {\n if (tokSet.has(qt)) files.add(file);\n }\n }\n df.set(qt, files.size);\n }\n\n // avglen per field — across files (one length per file, average them).\n const avglen: Record<keyof FieldTexts, number> = {\n match_line: 0,\n context: 0,\n file_path: 0,\n symbol_context: 0,\n };\n for (const fname of Object.keys(avglen) as Array<keyof FieldTexts>) {\n const lens: Array<number> = [];\n const seen = new Set<string>();\n for (let i = 0; i < hits.length; i++) {\n if (seen.has(hits[i].file)) continue;\n seen.add(hits[i].file);\n lens.push(perHitTokens[i][fname].length);\n }\n avglen[fname] =\n lens.length > 0 ? lens.reduce((a, b) => a + b, 0) / lens.length : 1;\n if (avglen[fname] === 0) avglen[fname] = 1;\n }\n\n // IDF per query token.\n const idf = new Map<string, number>();\n for (const qt of queryTokens) {\n const d = df.get(qt) ?? 0;\n idf.set(qt, Math.log((M - d + 0.5) / (d + 0.5) + 1)); // +1 keeps IDF positive (Lucene convention)\n }\n\n // Score each hit.\n const out: Array<ScoredHit> = [];\n for (let i = 0; i < hits.length; i++) {\n const tokens = perHitTokens[i];\n const contributions: Record<string, number> = {\n match_line: 0,\n symbol_context: 0,\n file_path: 0,\n context: 0,\n };\n for (const qt of queryTokens) {\n // Weighted TF across fields (the BM25F inner sum).\n let w = 0;\n const perField: Record<string, number> = {\n match_line: 0,\n symbol_context: 0,\n file_path: 0,\n context: 0,\n };\n for (const fname of Object.keys(FIELD_BOOSTS) as Array<\n keyof FieldTexts\n >) {\n const tf = tokens[fname].filter((t) => t === qt).length;\n if (tf === 0) continue;\n const len = tokens[fname].length || 1;\n const l = FIELD_LEN_NORMS[fname];\n const norm = 1 - l + l * (len / (avglen[fname] || 1));\n const fieldContrib = FIELD_BOOSTS[fname] * (tf / norm);\n w += fieldContrib;\n perField[fname] = fieldContrib;\n }\n if (w === 0) continue;\n const termScore = (idf.get(qt) ?? 0) * (w / (w + BM25F_K1));\n // Attribute the term's contribution back to fields\n // proportionally to each field's share of w.\n for (const fname of Object.keys(perField)) {\n const share = perField[fname] / w;\n contributions[fname] += termScore * share;\n }\n }\n const total = Object.values(contributions).reduce((a, b) => a + b, 0);\n out.push({\n hit: hits[i],\n score: total,\n field_contributions: contributions,\n });\n }\n\n return out;\n}\n\n// ============================================================\n// Ranking order\n// ============================================================\n\n/**\n * Deterministic ranking order, in place: score desc, then (file, line)\n * ascending as a stable tiebreak.\n *\n * There is NO score-based cut. The floor guarantee (see\n * `docs/code-search-floor.md`) is that ranked mode never drops a hit\n * ripgrep would return — it returns exactly the ripgrep match set,\n * reordered, capped only by the explicit `limit`. An earlier\n * \"shoulder prune\" (drop below 50% of the top score) silently removed\n * real matches a `grep` would surface; it was removed.\n */\nfunction sortByScore(scored: Array<ScoredHit>): void {\n scored.sort((a, b) => {\n if (b.score !== a.score) return b.score - a.score;\n if (a.hit.file !== b.hit.file) return a.hit.file < b.hit.file ? -1 : 1;\n return a.hit.line - b.hit.line;\n });\n}\n\n/**\n * Default-mode precision filter: given a score-sorted array, keep the\n * prefix at or above `SHOULDER_THRESHOLD` × top score. Returns ALL when\n * there is no ranking signal (top score 0). Skipped entirely under\n * `complete: true` — the caller then gets the full ranked set.\n */\nfunction shoulderCut(sorted: Array<ScoredHit>): Array<ScoredHit> {\n if (sorted.length === 0) return sorted;\n const topScore = sorted[0].score;\n if (topScore <= 0) return sorted;\n const threshold = topScore * SHOULDER_THRESHOLD;\n let cut = sorted.length;\n for (let i = 0; i < sorted.length; i++) {\n if (sorted[i].score < threshold) {\n cut = i;\n break;\n }\n }\n return sorted.slice(0, cut);\n}\n\n// ============================================================\n// Snippet rendering\n// ============================================================\n\nfunction renderSnippet(hit: RawHit): string {\n const lines = [...hit.context_before, hit.matched_line, ...hit.context_after];\n let snippet = lines.join(\"\\n\");\n if (Buffer.byteLength(snippet, \"utf8\") > MAX_SNIPPET_BYTES) {\n // Middle-elide. Preserve start and end so context survives.\n const buf = Buffer.from(snippet, \"utf8\");\n const halfCap = Math.floor((MAX_SNIPPET_BYTES - 16) / 2);\n snippet =\n buf.slice(0, halfCap).toString(\"utf8\") +\n \"\\n... [truncated] ...\\n\" +\n buf.slice(buf.length - halfCap).toString(\"utf8\");\n }\n return snippet;\n}\n\n// ============================================================\n// ast-grep (structural pattern match generation)\n// ============================================================\n\n/**\n * Router credentials that must NEVER reach the ast-grep child. Same key\n * set as `dropColgrepSecrets` (colbert/provision.ts) and the worker-bash\n * env allowlist. We keep a LOCAL strip rather than importing\n * `dropColgrepSecrets` to avoid pulling the heavyweight colbert\n * provisioning module into the core code-search import graph. ast-grep is\n * a SHA-pinned local binary, but it is still a child process that could\n * be coaxed (config, network) — no router secret belongs in its env.\n */\nconst AST_GREP_SECRET_ENV_KEYS = [\n \"GITHUB_TOKEN\",\n \"ANTHROPIC_AUTH_TOKEN\",\n \"ANTHROPIC_API_KEY\",\n \"OPENAI_API_KEY\",\n \"COPILOT_TOKEN\",\n];\n\n/**\n * Strip router credentials from a child-env COPY (never the live env).\n * Key matching is case-INSENSITIVE because Windows env names are\n * case-insensitive — `Github_Token` / `openai_api_key` must be dropped\n * too, or a mixed-case shell export would leak into the ast-grep child.\n */\nfunction dropAstGrepSecrets(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n for (const k of Object.keys(env)) {\n const up = k.toUpperCase();\n if (up.startsWith(\"GH_ROUTER_\") || AST_GREP_SECRET_ENV_KEYS.includes(up)) {\n delete env[k];\n }\n }\n return env;\n}\n\n/**\n * Resolve the ast-grep binary. Checks the known router-owned toolbelt paths\n * directly before consulting PATH for the unambiguous `ast-grep` name.\n * Returns an ABSOLUTE path or `null` when neither source has it.\n */\nexport function resolveAstGrep(): string | null {\n const toolbeltDir = PATHS.TOOLBELT_BIN_DIR;\n // Direct lookup is the authoritative toolbelt path. It avoids PATH/PATHEXT\n // runtime differences while keeping bare `sg` confined to OUR directory:\n // on Linux `/usr/bin/sg` is shadow-utils' setgid command, not ast-grep.\n const toolbeltNames =\n process.platform === \"win32\"\n ? [\"sg.exe\", \"ast-grep.exe\", \"sg\", \"ast-grep\"]\n : [\"sg\", \"ast-grep\"];\n for (const name of toolbeltNames) {\n const candidate = path.resolve(toolbeltDir, name);\n if (existsSync(candidate)) return candidate;\n }\n\n // `ast-grep` is unambiguous and safe to resolve from the system PATH.\n return resolveExecutable(\"ast-grep\", { env: process.env });\n}\n\n/**\n * Test-only override for the ast-grep resolver. `undefined` = use the real\n * `resolveAstGrep`. Set to a function (e.g. `() => null` to force the\n * binary-absent path deterministically even on a host that HAS sg) via\n * `__setAstGrepResolverForTest`. Mirrors the `__readBenchStructuralStats`\n * test-export convention already used in this module.\n */\nlet _astGrepResolverOverride: (() => string | null) | undefined;\n\nexport function __setAstGrepResolverForTest(\n fn: (() => string | null) | undefined,\n): void {\n _astGrepResolverOverride = fn;\n}\n\n/** Resolve ast-grep, honoring the test override when set. */\nfunction resolveAstGrepForRun(): string | null {\n return (_astGrepResolverOverride ?? resolveAstGrep)();\n}\n\n/** One `sg run --json=stream` JSON-line shape (only the fields we read). */\ninterface AstGrepMatch {\n text?: string;\n lines?: string;\n file?: string;\n range?: {\n start?: { line?: number; column?: number };\n end?: { line?: number; column?: number };\n };\n}\n\ninterface AstGrepResult {\n /** RawHit set (relative paths, 1-indexed lines). */\n hits: Array<RawHit>;\n /** Non-null when something the model can act on fired (binary missing,\n * truncated, timed out, error) — surfaced as the response `notice`. */\n notice: string | null;\n}\n\n/**\n * Run ast-grep with `pattern` over `workspaceCanonical` and return its\n * matches in `RawHit` shape (relativized, 1-indexed). Read-only,\n * workspace-confined, secret-stripped, stdout-capped, timeout-bounded.\n *\n * Security posture (mirrors `src/lib/colbert/runner.ts`):\n * - `runManagedExeCapture(absExe, argv, {shell:false})` — pattern and\n * workspace are ARGV elements, never a shell string. A workspace path\n * containing `%`, `&`, `|`, quotes, or spaces cannot inject a command\n * on Windows (no cmd.exe in the path; CreateProcess resolves the\n * `.exe` directly).\n * - `dropAstGrepSecrets` strips every `GH_ROUTER_*` + the named\n * credential keys from the child env copy.\n * - workspace is the absolute, realpath-canonicalized directory; the\n * binary's own `.gitignore` handling scopes the file universe (same\n * ignore semantics as ripgrep here).\n */\nasync function runAstGrep(opts: {\n pattern: string;\n lang: string | undefined;\n workspaceCanonical: string;\n limit: number;\n signal: AbortSignal;\n}): Promise<AstGrepResult> {\n const binary = resolveAstGrepForRun();\n if (!binary) {\n return {\n hits: [],\n notice:\n \"ast_pattern requires ast-grep, but no executable was found at \" +\n `${PATHS.TOOLBELT_BIN_DIR} (sg/ast-grep) or on PATH (ast-grep); ` +\n \"install ast-grep or omit ast_pattern\",\n };\n }\n // `--lang` is REQUIRED for correct matching. Without it ast-grep parses\n // the pattern against every language's grammar and emits cross-language\n // false positives (e.g. matching markdown prose). A missing/malformed\n // lang therefore fails closed with an actionable notice rather than\n // returning garbage. The token is validated (ast-grep lang ids are short\n // ascii) before it reaches the argv — though shell:false already makes it\n // non-injectable, this gives a clean notice instead of an sg error.\n if (!opts.lang || !/^[A-Za-z0-9_+-]{1,20}$/.test(opts.lang)) {\n return {\n hits: [],\n notice:\n \"ast_pattern requires ast_lang (the grammar to parse the pattern), \" +\n \"e.g. 'ts' | 'tsx' | 'js' | 'py' | 'rust' | 'go'\",\n };\n }\n\n // `sg run -p <pattern> --lang <lang> --json=stream <workspace>` — VERIFIED\n // on ast-grep 0.43.0. `--json=stream` emits one JSON object per line. The\n // workspace is passed as an absolute positional; sg then reports `file` as\n // an absolute path, which we relativize below.\n const args = [\n \"run\",\n \"-p\",\n opts.pattern,\n \"--lang\",\n opts.lang,\n \"--json=stream\",\n opts.workspaceCanonical,\n ];\n\n let res;\n try {\n res = await runManagedExeCapture(binary, args, {\n cwd: opts.workspaceCanonical,\n env: dropAstGrepSecrets({ ...process.env }),\n timeoutMs: WALL_TIME_MS,\n maxStdoutBytes: MAX_STDOUT_BYTES,\n });\n } catch {\n return {\n hits: [],\n notice: \"ast-grep failed to launch; omit ast_pattern or run it directly\",\n };\n }\n\n if (opts.signal.aborted) {\n return { hits: [], notice: null };\n }\n if (res.timedOut) {\n return {\n hits: [],\n notice: \"ast-grep timed out; narrow the pattern or run it directly\",\n };\n }\n // sg exits 1 on \"no matches\" (not an error). Any other non-zero with no\n // stdout is a real failure (bad pattern, IO). We don't surface raw\n // stderr (it can embed source); a class label is enough.\n if (res.code !== null && res.code !== 0 && res.code !== 1 && !res.stdout) {\n return {\n hits: [],\n notice:\n \"ast-grep returned an error (check the pattern syntax) or omit ast_pattern\",\n };\n }\n\n const hits: Array<RawHit> = [];\n for (const rawLine of res.stdout.split(\"\\n\")) {\n if (hits.length >= opts.limit) break;\n const line = rawLine.trim();\n if (line.length === 0) continue;\n let m: AstGrepMatch;\n try {\n m = JSON.parse(line) as AstGrepMatch;\n } catch {\n continue; // skip a partial/garbage line rather than fail the call\n }\n if (typeof m.file !== \"string\") continue;\n // Confine: drop any path ast-grep reports that resolves OUTSIDE the\n // workspace (e.g. a symlink it traversed). `relativizeToWorkspace`\n // returns null on escape; we skip rather than emit an absolute system\n // path. Then apply the sensitive-path denylist (defense-in-depth, same\n // as the scan path) so a hit never surfaces a credential file.\n const rel = relativizeToWorkspace(m.file, opts.workspaceCanonical);\n if (rel === null) continue;\n const abs = path.join(opts.workspaceCanonical, rel);\n if (isSensitivePath(abs, opts.workspaceCanonical)) continue;\n const startLine = m.range?.start?.line;\n // sg is 0-indexed; our contract is 1-indexed.\n const line1 = typeof startLine === \"number\" ? startLine + 1 : 1;\n const snippetSrc =\n typeof m.text === \"string\" && m.text.length > 0\n ? m.text\n : typeof m.lines === \"string\"\n ? m.lines\n : \"\";\n hits.push({\n file: normalizeRelFile(rel),\n line: line1,\n matched_line: snippetSrc,\n // ast-grep offsets are into the file, not the snippet line; we don't\n // expose a byte range for AST hits, so 0:0 (renderSnippet uses the\n // whole matched_line; the symbol_context slice path is never reached\n // because AST hits render literal, not ranked).\n match_start: 0,\n match_end: 0,\n context_before: [],\n context_after: [],\n });\n }\n\n const truncatedBySize = res.stdoutTruncated || hits.length >= opts.limit;\n return {\n hits,\n notice: truncatedBySize\n ? \"ast-grep results were truncated (size cap or limit reached); \" +\n \"narrow the pattern or raise limit\"\n : null,\n };\n}\n\n/**\n * Relativize an ast-grep-reported file path against the workspace. sg\n * reports absolute paths when handed an absolute positional. Returns the\n * workspace-relative path, or `null` when the path resolves OUTSIDE the\n * workspace (e.g. a traversed symlink) — the caller drops such hits rather\n * than emit an absolute system path. A relative input that stays inside is\n * returned as-is; normalizeRelFile cleans separators afterward.\n */\nfunction relativizeToWorkspace(\n file: string,\n workspaceCanonical: string,\n): string | null {\n try {\n const abs = path.resolve(workspaceCanonical, file);\n const rel = path.relative(workspaceCanonical, abs);\n // Empty rel = the workspace dir itself (not a file hit); \"..\" / absolute\n // = escaped. Either way, not a valid in-workspace file hit.\n if (rel === \"\" || rel.startsWith(\"..\") || path.isAbsolute(rel)) {\n return null;\n }\n return rel;\n } catch {\n return null;\n }\n}\n\n// ============================================================\n// Whole-workspace file enumeration (scan mode)\n// ============================================================\n\n/**\n * Enumerate every non-ignored file in the workspace via `rg --files`\n * (respecting `.gitignore` / `.ignore` exactly like the search path),\n * then drop sensitive-shaped paths (`.env*`, `*.pem`, `id_rsa*`, `.git/`\n * interior, `.ssh/`, …) via the shared worker denylist. Returns paths\n * RELATIVE to the workspace, in rg's enumeration order, capped at\n * `SCAN_MAX_FILES`.\n *\n * `total` is the count of enumerated source files BEFORE the cap (after\n * the sensitive-path filter), so the caller can disclose coverage when\n * the outline set is truncated.\n */\nasync function enumerateWorkspaceFiles(opts: {\n rgPath: string;\n workspaceCanonical: string;\n signal: AbortSignal;\n /** Absolute wall-clock deadline (Date.now() ms) — the search-phase\n * `wallTimer` is already cleared by the time scan runs, so the\n * enumeration self-bounds against this. */\n deadlineMs: number;\n}): Promise<{ files: Array<string>; total: number; capped: boolean }> {\n const files: Array<string> = [];\n let total = 0;\n let capped = false;\n\n if (opts.signal.aborted) return { files, total, capped };\n\n let child: ChildProcess;\n try {\n // `--no-follow`: don't traverse symlinks (matches the search path's\n // scoping; keeps enumeration inside the workspace tree). stderr is\n // IGNORED, not piped: an undrained stderr pipe can fill its OS buffer\n // (e.g. rg \"Permission denied\" spam on Windows) and deadlock the child,\n // which would defeat the deadline check below (it only runs per stdout\n // line). rg's file LIST goes to stdout; stderr is non-essential here.\n child = spawn(opts.rgPath, [\"--files\", \"--no-follow\"], {\n cwd: opts.workspaceCanonical, // kernel-level pin, same as the search path\n shell: false,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n } catch {\n return { files, total, capped };\n }\n\n // Async spawn failures (ENOENT/EACCES) emit an 'error' event rather than\n // throwing; without a listener Node escalates it to an uncaught crash.\n // A no-op listener lets the for-await loop end naturally and we return\n // whatever (nothing) was enumerated.\n child.on(\"error\", () => {});\n\n // Out-of-band kill at the deadline. The per-line deadline check below\n // only fires when rg emits a line; this guarantees termination even if\n // rg stalls before its first line on a pathological tree.\n const deadlineTimer = setTimeout(\n () => killChild(child),\n Math.max(0, opts.deadlineMs - Date.now()),\n );\n deadlineTimer.unref();\n\n const onAbort = (): void => killChild(child);\n opts.signal.addEventListener(\"abort\", onAbort, { once: true });\n\n try {\n if (!child.stdout) return { files, total, capped };\n child.stdout.setEncoding(\"utf8\");\n const rl = createInterface({ input: child.stdout, crlfDelay: Infinity });\n let stdoutBytes = 0;\n for await (const rawLine of rl) {\n if (opts.signal.aborted || Date.now() > opts.deadlineMs) {\n killChild(child);\n break;\n }\n // Byte-accurate cap (multibyte UTF-8 paths must not undercount).\n stdoutBytes += Buffer.byteLength(rawLine, \"utf8\") + 1;\n if (stdoutBytes > MAX_STDOUT_BYTES) {\n killChild(child);\n break;\n }\n const rel = normalizeRelFile(rawLine.trim());\n if (rel.length === 0) continue;\n // Defensive containment re-check: rg --files emits workspace-relative\n // paths, but never trust a subprocess unconditionally — reject any\n // absolute or `..`-escaping path before joining.\n if (path.isAbsolute(rel) || rel.split(\"/\").includes(\"..\")) continue;\n // Skip files whose extension has no tree-sitter grammar — outlining\n // them would just parse-fail. Cheap pre-filter before the cap so the\n // cap counts outlineable files, not READMEs.\n if (!getLanguageKeyForPath(rel)) continue;\n // Drop credential-shaped paths (defense-in-depth — the outline would\n // surface symbol names from a sensitive file).\n const abs = path.join(opts.workspaceCanonical, rel);\n if (isSensitivePath(abs, opts.workspaceCanonical)) continue;\n total += 1;\n if (files.length < SCAN_MAX_FILES) {\n files.push(rel);\n } else {\n capped = true;\n }\n }\n } catch {\n // Best-effort: return whatever we enumerated.\n } finally {\n clearTimeout(deadlineTimer);\n opts.signal.removeEventListener(\"abort\", onAbort);\n if (!child.killed) killChild(child);\n }\n\n return { files, total, capped };\n}\n\n// ============================================================\n// Main entry point\n// ============================================================\n\nexport async function searchCode(\n rawInput: CodeSearchInput,\n externalSignal?: AbortSignal,\n): Promise<CodeSearchResponse> {\n const t0 = Date.now();\n\n const inputErr = validateInputs(rawInput);\n if (inputErr) throw new Error(inputErr);\n\n const ws = validateWorkspace(rawInput.workspace);\n if (!ws.ok || !ws.canonical) {\n throw new Error(ws.error ?? \"workspace validation failed\");\n }\n\n const mode = rawInput.mode ?? \"ranked\";\n const structuralMode = rawInput.structural ?? \"full\";\n const limit = rawInput.limit ?? DEFAULT_LIMIT;\n const contextLines = Math.min(\n rawInput.context_lines ?? DEFAULT_CONTEXT_LINES,\n MAX_CONTEXT_LINES,\n );\n\n // ast_pattern takes PRECEDENCE over the regex query for match\n // generation: when set, matches come from ast-grep, not ripgrep, and\n // are rendered in literal (document-order) shape — BM25F doesn't apply\n // to AST hits. `query` is still required by the schema but unused for\n // matching. The whole-workspace `scan` outline is independent and still\n // runs afterward either way.\n const astPattern =\n typeof rawInput.ast_pattern === \"string\" && rawInput.ast_pattern.length > 0\n ? rawInput.ast_pattern\n : undefined;\n const astLang =\n typeof rawInput.ast_lang === \"string\" && rawInput.ast_lang.length > 0\n ? rawInput.ast_lang\n : undefined;\n // Effective ranking mode: AST hits are never BM25F-scored (there is no\n // text-token relevance signal for a structural match), so force the\n // literal render path for them.\n const effectiveMode = astPattern ? \"literal\" : mode;\n\n // Identifier skeleton-form expansion. When the user's query is a\n // single identifier in any of the five canonical conventions, we\n // expand to all of them and feed rg a regex alternation. This is\n // the live-correctness fix for \"rg getUserName\" not finding\n // get_user_name. Regex mode is excluded — the user is explicit\n // about regex semantics there.\n const expansion =\n astPattern || mode === \"regex\"\n ? null\n : expandIdentifierVariants(rawInput.query);\n const expansionPattern = expansion\n ? buildExpansionPattern(expansion)\n : undefined;\n\n // Local AbortController combines: external signal, wall-time, and\n // any internal short-circuits (stdout cap, global limit). Single\n // place to fire abort from.\n const ac = new AbortController();\n const onExternal = (): void => ac.abort(\"external\");\n if (externalSignal) {\n if (externalSignal.aborted) ac.abort(\"external\");\n else externalSignal.addEventListener(\"abort\", onExternal, { once: true });\n }\n const wallTimer = setTimeout(() => ac.abort(\"timeout\"), WALL_TIME_MS);\n wallTimer.unref();\n\n // Bound active search weight across parallel calls (Phase 1, A8). The\n // slot covers generation + ranking + outlines (the whole CPU-bound body)\n // and releases on every exit path via the trailing finally. Acquired\n // AFTER validation so invalid calls fail fast without holding a slot.\n const slotMode = astPattern\n ? \"ast\"\n : mode === \"ranked\"\n ? \"ranked\"\n : mode === \"literal\"\n ? \"literal\"\n : \"regex\";\n const releaseSlot = await acquireSearchSlot(slotMode, ac.signal);\n try {\n let parseResult: ParseResult;\n let astNotice: string | null = null;\n let rgResolution: RipgrepResolution;\n try {\n rgResolution = resolveRipgrep();\n } catch (err) {\n clearTimeout(wallTimer);\n if (externalSignal)\n externalSignal.removeEventListener(\"abort\", onExternal);\n throw err;\n }\n\n if (astPattern) {\n // ----- ast-grep match generation (precedence over ripgrep) -----\n let astRes: AstGrepResult;\n try {\n astRes = await runAstGrep({\n pattern: astPattern,\n lang: astLang,\n workspaceCanonical: ws.canonical,\n limit,\n signal: ac.signal,\n });\n } finally {\n clearTimeout(wallTimer);\n if (externalSignal) {\n externalSignal.removeEventListener(\"abort\", onExternal);\n }\n }\n if (ac.signal.aborted && astRes.hits.length === 0) {\n const reason = String(ac.signal.reason ?? \"aborted\");\n throw new Error(`code_search aborted (${reason})`);\n }\n astNotice = astRes.notice;\n parseResult = {\n hits: astRes.hits,\n scannedFiles: 0,\n truncated: astRes.hits.length >= limit,\n cancelled: ac.signal.aborted,\n stdoutBytes: 0,\n };\n } else {\n parseResult = await runRipgrep();\n }\n\n // Inlined ripgrep generation: spawn + parse + exit-code error mapping.\n // Hoisted into a closure so the ast_pattern branch above can bypass it\n // cleanly while preserving the exact original control flow (and the\n // load-bearing cancel-race / exit-code handling) on the default path.\n async function runRipgrep(): Promise<ParseResult> {\n const args = buildRgArgs({\n mode,\n fileGlob: rawInput.file_glob,\n contextLines,\n query: rawInput.query,\n expansionPattern,\n complete: rawInput.complete,\n multiline: rawInput.multiline,\n });\n\n let child: ChildProcess;\n try {\n child = spawn(rgResolution.rgPath, args, {\n cwd: ws.canonical, // TOCTOU mitigation: kernel-level pin\n shell: false, // never via shell\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n } catch (err) {\n clearTimeout(wallTimer);\n if (externalSignal) {\n externalSignal.removeEventListener(\"abort\", onExternal);\n }\n throw new Error(`failed to spawn ripgrep: ${(err as Error).message}`, {\n cause: err,\n });\n }\n\n // Capture stderr as text (bounded to 64KB — rg errors are short,\n // but the existing 1MB byte cap stays as a runaway-input guard).\n // We surface stderr on exit code 2 so model gets actionable errors\n // (e.g. regex compile failures) rather than empty results.\n const STDERR_TEXT_CAP = 64 * 1024;\n let stderrBytes = 0;\n let stderrText = \"\";\n if (child.stderr) {\n child.stderr.setEncoding(\"utf8\");\n child.stderr.on(\"data\", (chunk: string) => {\n stderrBytes += chunk.length;\n if (stderrText.length < STDERR_TEXT_CAP) {\n stderrText = (stderrText + chunk).slice(0, STDERR_TEXT_CAP);\n }\n if (stderrBytes > 1024 * 1024) {\n // 1MB stderr is excessive — kill.\n ac.abort(\"stderr_cap\");\n }\n });\n }\n\n // Track rg's exit code so we can distinguish \"no matches\" (code 1)\n // from a real error (code 2: bad regex, IO failure after our\n // workspace validation, etc.) Per `man rg`:\n // 0 = matches found\n // 1 = no matches (not an error)\n // 2 = error (regex, IO, ...)\n let exitCode: number | null = null;\n const exitPromise = new Promise<void>((resolve) => {\n child.on(\"close\", (code) => {\n exitCode = code;\n resolve();\n });\n });\n\n let pr: ParseResult;\n try {\n pr = await parseRgJsonStream(child, {\n limit,\n contextLines,\n signal: ac.signal,\n });\n } finally {\n clearTimeout(wallTimer);\n if (externalSignal) {\n externalSignal.removeEventListener(\"abort\", onExternal);\n }\n if (!child.killed) killChild(child);\n }\n\n // If the abort was due to timeout/cap/external, surface that.\n if (ac.signal.aborted && pr.hits.length === 0) {\n const reason = String(ac.signal.reason ?? \"aborted\");\n throw new Error(`code_search aborted (${reason})`);\n }\n\n // Surface rg errors (regex compile failures, etc.) to the caller.\n // Exit code 2 means \"rg encountered an error\" — typically a malformed\n // regex in mode=\"regex\". Without this, an invalid regex returns\n // empty results with no indication of why; the model can't tell\n // \"no matches\" from \"your pattern is broken.\" We re-check\n // !signal.aborted so timeout/cap-driven aborts (which also produce\n // non-zero exit) keep their existing error path above.\n //\n // Await rg's full exit before reading exitCode — the parseRgJsonStream\n // for-await terminates on stdout EOF, which may slightly precede the\n // child's 'close' event in Node's event-loop ordering.\n if (!ac.signal.aborted) {\n await exitPromise;\n }\n if (\n exitCode !== null &&\n exitCode !== 0 &&\n exitCode !== 1 &&\n !ac.signal.aborted &&\n pr.hits.length === 0\n ) {\n const trimmed = stderrText.trim();\n const detail =\n trimmed.length > 0\n ? trimmed.replace(/^rg:\\s*/i, \"\").slice(0, 600)\n : `ripgrep exited with code ${exitCode}`;\n throw new Error(`code_search: ${detail}`);\n }\n return pr;\n }\n\n // Apply ranking.\n let kept: Array<ScoredHit>;\n // Stable keys (`file:line:byteStart:byteEnd`) of hits the structural\n // pass AST-confirmed as definition sites — used to tag those hits with\n // `role: \"definition\"` at render time. A logical key (not object\n // identity) so a clone/rehydrate in scoring can't silently drop the\n // tag. Only populated in ranked mode (the only mode that runs the\n // structural pass). It NEVER claims \"usage\": absence of the tag is not\n // a claim, since a hit may simply not have been AST-checked.\n let confirmedKeys: Set<string> | undefined;\n let notice: string | null = null;\n // Set when the JIT cross-encoder rerank reordered the head (Phase 3).\n let rerankApplied = false;\n /**\n * Outlines the structural pass already computed (worker-pool path only),\n * keyed by RELATIVE file path. The outline loop reuses these before falling\n * back to `_treeCache` / `outlineFile` — the threaded equivalent of Lever 1's\n * tree reuse (a Tree can't cross threads, so the pool ships outline entries\n * instead). Undefined on the in-process path, where `_treeCache` reuse\n * applies directly.\n */\n let structuralOutlines: Map<string, Array<FileOutlineEntry>> | undefined;\n if (effectiveMode === \"ranked\") {\n const queryTokens = tokenize(rawInput.query);\n // Pass 1: regex-only BM25F. Cheap and gives us a reliable\n // ordering to pick the top-N for structural confirmation.\n const pass1 = bm25fScore(parseResult.hits, queryTokens);\n pass1.sort((a, b) => b.score - a.score);\n const topN =\n structuralMode === \"topN\" ? STRUCTURAL_TOPN_FAST : STRUCTURAL_TOPN_FULL;\n // Build (hit, original-index) entries for the top-N. The index\n // is into `parseResult.hits` so the AST-confirmed set lines up\n // with the pass-2 scoring loop.\n const indexByHit = new Map<RawHit, number>();\n for (let i = 0; i < parseResult.hits.length; i++) {\n indexByHit.set(parseResult.hits[i], i);\n }\n const hitsRanked = pass1\n .slice(0, Math.min(topN, pass1.length))\n .map((sh) => ({ hit: sh.hit, index: indexByHit.get(sh.hit) ?? -1 }))\n .filter((e) => e.index >= 0);\n\n const structural = await runStructuralPass({\n hitsRanked,\n workspaceRoot: ws.canonical,\n topN,\n budgetMs: structuralBudgetMs(),\n signal: ac.signal,\n });\n structuralOutlines = structural.outlinesByFile;\n // Pass 2: re-score with AST confirmation. Corpus stats are\n // re-computed against the structurally-enriched symbol_context\n // fields so token IDFs reflect the new field contents.\n const pass2 = bm25fScore(\n parseResult.hits,\n queryTokens,\n structural.confirmedHitIndexes,\n );\n // Accumulate every actionable notice (structural-budget fallback +\n // the two default-mode precision disclosures) so none silently\n // overwrites another.\n const notices: Array<string> = [];\n if (structural.fallback) notices.push(structural.fallback);\n\n // Floor vs precision. `complete: true` returns the full ranked set\n // (capped only by `limit`). The default applies the precision\n // shoulder cut + per-file cap — but discloses BOTH, so a miss is\n // never silent: the model can always recover the full set with\n // `complete: true`.\n sortByScore(pass2);\n if (rawInput.complete) {\n kept = pass2.slice(0, limit);\n } else {\n const cut = shoulderCut(pass2);\n const hidden = pass2.length - cut.length;\n kept = cut.slice(0, limit);\n if (hidden > 0) {\n notices.push(\n `${hidden} lower-relevance match${hidden === 1 ? \"\" : \"es\"} ` +\n `hidden by precision pruning — pass complete:true for the full set`,\n );\n }\n // Per-file cap disclosure. ripgrep's `--max-count` silently\n // truncates a file at RANKED_MAX_PER_FILE; we can't know the true\n // count, but a file AT the cap was (probably) truncated — disclose\n // it so the cap, like the shoulder cut, is never a silent miss.\n const perFileCounts = new Map<string, number>();\n for (const h of parseResult.hits) {\n perFileCounts.set(h.file, (perFileCounts.get(h.file) ?? 0) + 1);\n }\n let cappedFiles = 0;\n for (const c of perFileCounts.values()) {\n if (c >= RANKED_MAX_PER_FILE) cappedFiles++;\n }\n if (cappedFiles > 0) {\n notices.push(\n `${cappedFiles} file${cappedFiles === 1 ? \"\" : \"s\"} hit the ` +\n `per-file match cap — pass complete:true for every match`,\n );\n }\n }\n notice = notices.length > 0 ? notices.join(\" · \") : null;\n\n // JIT cross-encoder rerank (Phase 3): NL-shaped queries only, never\n // under `complete:true` (exhaustive mode keeps BM25F order). Refines\n // the head (first RERANK_HEAD hits) — beyond that BM25F order stands.\n // Null (disabled/unavailable/over-budget) keeps BM25F order silently;\n // reranking is precision, never correctness.\n if (\n !rawInput.complete &&\n kept.length > 1 &&\n isNaturalLanguageQuery(rawInput.query)\n ) {\n const head = kept.slice(0, RERANK_HEAD)\n const order = await rerankDocuments(\n rawInput.query,\n head.map((sh) => renderSnippet(sh.hit)),\n head.length,\n ac.signal,\n )\n if (order && order.length === head.length) {\n const reordered = order.map((i) => head[i])\n kept = [...reordered, ...kept.slice(head.length)]\n rerankApplied = true\n }\n }\n\n // Confirmed-definition keys (stable file:line:byte-range, NOT object\n // identity) for the render-time `role` tag.\n confirmedKeys = new Set<string>();\n for (const idx of structural.confirmedHitIndexes) {\n const h = parseResult.hits[idx];\n if (h) {\n confirmedKeys.add(\n `${h.file}:${h.line}:${h.match_start}:${h.match_end}`,\n );\n }\n }\n } else {\n // Literal / regex: ripgrep document order, no scoring.\n kept = parseResult.hits.map((h) => ({\n hit: h,\n score: 0,\n field_contributions: {} as Record<string, number>,\n }));\n }\n\n // Render output hits. rg paths are already relative to cwd\n // (we spawned with target \".\") so no extra resolution needed.\n // Strip the leading \"./\" or \".\\\" that rg prepends when target=\".\".\n // Then normalize separators to \"/\" so output is platform-agnostic\n // (Windows rg returns \"src\\foo.ts\"; models and tests expect \"/\").\n const results: Array<CodeSearchHit> = kept.map((sh) => {\n const file = normalizeRelFile(sh.hit.file);\n const baseHit: CodeSearchHit = {\n file,\n line: sh.hit.line,\n snippet: renderSnippet(sh.hit),\n match_byte_range: [sh.hit.match_start, sh.hit.match_end],\n };\n if (effectiveMode === \"ranked\") {\n baseHit.score = round4(sh.score);\n baseHit.field_contributions = {\n match_line: round4(sh.field_contributions.match_line ?? 0),\n symbol_context: round4(sh.field_contributions.symbol_context ?? 0),\n file_path: round4(sh.field_contributions.file_path ?? 0),\n context: round4(sh.field_contributions.context ?? 0),\n };\n } else {\n baseHit.field_contributions = null;\n }\n if (\n confirmedKeys?.has(\n `${sh.hit.file}:${sh.hit.line}:${sh.hit.match_start}:${sh.hit.match_end}`,\n )\n ) {\n baseHit.role = \"definition\";\n }\n return baseHit;\n });\n\n // Structural summary is OPT-IN — outline the distinct files in the\n // result set (capped, in result order) only when the caller passes\n // `summary: true` (saves ~2-5KB tokens per call otherwise). `scan: true`\n // instead outlines the ENTIRE workspace (every non-ignored,\n // non-sensitive source file), up to SCAN_MAX_FILES, so the model gets\n // a whole-tree symbol map in one call.\n // Reuses the shared tree-sitter outliner; each file is bounded by its\n // own 1 MiB parse cap and the outliner never throws. Computed BEFORE\n // `elapsed_ms` so telemetry reflects the real latency. `outline_ms`\n // separately attributes the outline pass in the log line below.\n let outlines:\n Array<{ file: string; outline: Array<FileOutlineEntry> }> | undefined;\n let scanNotice: string | null = null;\n let outline_ms = 0;\n const outlineStartMs = Date.now();\n const wantScan = rawInput.scan === true;\n // A whole-workspace scan (enumerate + outline up to SCAN_MAX_FILES) is\n // the heaviest path and runs AFTER the search-phase wallTimer is torn\n // down, so it self-bounds against this absolute deadline.\n const scanDeadline = Date.now() + WALL_TIME_MS;\n if (rawInput.summary === true || wantScan) {\n let distinct: Array<string>;\n if (wantScan) {\n // Whole-workspace enumeration (respects ignore rules; sensitive\n // paths + non-outlineable extensions filtered). Capped at\n // SCAN_MAX_FILES; coverage disclosed via `scanNotice` on truncation.\n const enumed = await enumerateWorkspaceFiles({\n rgPath: rgResolution.rgPath,\n workspaceCanonical: ws.canonical,\n signal: ac.signal,\n deadlineMs: scanDeadline,\n });\n distinct = enumed.files;\n if (enumed.capped) {\n scanNotice =\n `scan outlined ${enumed.files.length} of ${enumed.total} workspace ` +\n `source files (capped at ${SCAN_MAX_FILES}); narrow with file_glob ` +\n `or inspect a sub-tree for full coverage`;\n }\n } else {\n const seen = new Set<string>();\n distinct = [];\n for (const r of results) {\n if (seen.has(r.file)) continue;\n seen.add(r.file);\n distinct.push(r.file);\n if (distinct.length >= CODE_SUMMARY_MAX_FILES) break;\n }\n }\n outlines = [];\n // A whole-workspace scan shares the single `scanDeadline` across\n // enumeration + outlining; the result-summary path keeps its tight\n // 2s self-bound.\n const outlineDeadline = wantScan ? scanDeadline : Date.now() + 2000;\n for (const file of distinct) {\n // Self-bound: the wall-clock timer + external-signal listener are\n // already torn down by here, so cap the outline pass independently.\n if (ac.signal.aborted || Date.now() > outlineDeadline) break;\n const abs = path.resolve(ws.canonical, file);\n let result: FileOutlineResult | undefined;\n // 1. Reuse the worker-pool's already-computed outline (the threaded\n // equivalent of Lever 1: the pool parsed this file and shipped its\n // outline entries alongside the confirm result). `file` is the\n // normalized result path, matching how the pool keyed its map.\n const pooled = structuralOutlines?.get(file);\n if (pooled) {\n result = { outline: pooled, language: getLanguageKeyForPath(abs) };\n }\n // 2. Else reuse the in-process structural pass's cached tree when it's\n // still fresh — avoids re-reading + re-parsing a file we already\n // parsed this call. `outlineFromTree` is walk-only and does NOT free\n // the tree (the cache owns it). On any miss / mtime change / unknown\n // lang, fall back to a full `outlineFile`.\n if (!result) {\n try {\n const cached = cacheGet(abs, statSync(abs).mtimeMs);\n if (cached?.tree) {\n const lang = getLanguageKeyForPath(abs);\n if (lang) result = outlineFromTree(cached.tree, lang, ac.signal);\n }\n } catch {\n // fall through to a full parse\n }\n }\n const o = result ?? (await outlineFile(abs, ac.signal));\n // Skip files with no recoverable symbols in scan mode so the map\n // stays a list of real symbol-bearing files, not empty noise.\n if (wantScan && o.outline.length === 0) continue;\n outlines.push({\n file,\n outline: o.outline.slice(0, MAX_OUTLINE_ENTRIES_PER_FILE),\n });\n }\n }\n\n // Merge every actionable notice: ast-grep diagnostics + scan coverage +\n // the ranked-mode precision/structural notice. Joined with ` · ` so none\n // overwrites another (same convention as the ranked-mode notice merge).\n const finalNotices: Array<string> = [];\n if (astNotice) finalNotices.push(astNotice);\n if (scanNotice) finalNotices.push(scanNotice);\n if (notice) finalNotices.push(notice);\n const mergedNotice =\n finalNotices.length > 0 ? finalNotices.join(\" · \") : null;\n\n outline_ms = Date.now() - outlineStartMs;\n const elapsed_ms = Date.now() - t0;\n\n // Telemetry breadcrumb. Per LOW-17: don't log raw query or\n // absolute paths unless explicitly enabled.\n const debugLog = process.env.GH_ROUTER_DEBUG_CODE_SEARCH === \"1\";\n consola.info(\n `[code_search] mode=${effectiveMode}${astPattern ? \" ast_pattern\" : \"\"}` +\n `${wantScan ? \" scan\" : \"\"}${rawInput.multiline ? \" multiline\" : \"\"} ` +\n `structural=${structuralMode} ` +\n `expansion=${expansion ? expansion.length : 0} ` +\n `results=${results.length} truncated=${parseResult.truncated} ` +\n `outlines=${outlines ? outlines.length : 0} ` +\n `scanned_files=${parseResult.scannedFiles} elapsed_ms=${elapsed_ms} ` +\n `outline_ms=${outline_ms} ` +\n `rerank=${rerankApplied ? \"yes\" : \"no\"} ` +\n `abort=${parseResult.cancelled} rg=${rgResolution.source} ` +\n `notice=${mergedNotice ? \"yes\" : \"no\"}` +\n (debugLog\n ? ` query=\"${rawInput.query}\" workspace=\"${ws.canonical}\"`\n : \"\"),\n );\n\n const response: CodeSearchResponse = {\n results,\n truncated: parseResult.truncated,\n scanned_files: parseResult.scannedFiles,\n elapsed_ms,\n ranking:\n effectiveMode === \"ranked\"\n ? {\n algorithm: rerankApplied ? \"BM25F+FlashRank\" : \"BM25F\",\n citation: \"Robertson, Zaragoza, Taylor 2004\",\n k1: BM25F_K1,\n }\n : { algorithm: \"ripgrep_document_order\" },\n outlines,\n notice: mergedNotice,\n };\n return response;\n } finally {\n releaseSlot();\n }\n}\n\nfunction round4(x: number): number {\n return Math.round(x * 10000) / 10000;\n}\n","/**\n * ColBERT sidecar manifest: pinned versions, download URLs and SHA256\n * digests for the THREE artifacts the `colgrep` semantic-search sidecar\n * needs — the colgrep binary, the ONNX Runtime dylib, and the ColBERT\n * INT8 model files.\n *\n * The SHA256 values are hardcoded HERE (NOT fetched from the same\n * release at runtime). For colgrep they're read from the published\n * `.sha256` sidecar at manifest-generation time; for ORT and the model\n * they're computed over the bytes we pin. **colgrep itself does ZERO\n * checksum verification** on its own HF-model and ORT downloads\n * (`model.rs` trusts `hf-hub`; `onnx_runtime.rs` `ureq::get(...)` with\n * no digest check), so pre-supplying both SHA-pinned is not just\n * convenience — it closes a supply-chain hole colgrep leaves open.\n *\n * Regenerate with `bun run scripts/gen-colbert-manifest.ts` when\n * re-pinning; the script downloads each asset and recomputes the digest.\n *\n * See docs/research/colbert-sidecar-design.md §3 for the full\n * supply-chain rationale.\n */\n\n/** Archive container of a downloaded artifact. */\nexport type ColbertArchiveKind = \"raw\" | \"zip\" | \"tar.gz\" | \"tar.xz\"\n\nexport interface ColbertAsset {\n url: string\n /** SHA256 of the downloaded archive/file (hex). Verified before extraction. */\n sha256: string\n archive: ColbertArchiveKind\n /**\n * Basename of the member to extract from the archive (no path).\n * Ignored for `raw`. For colgrep this is `colgrep`/`colgrep.exe`; for\n * ORT it's the platform dylib basename.\n */\n member?: string\n}\n\n/** colgrep release version pinned by this manifest. */\nexport const COLGREP_VERSION = \"1.5.2\"\n/** ONNX Runtime version colgrep pins (`onnx_runtime.rs:33`). */\nexport const ORT_VERSION = \"1.23.0\"\n/** ColBERT model HF repo id (`model.rs:5`). */\nexport const MODEL_REPO = \"lightonai/LateOn-Code-edge\"\n/**\n * Pinned model revision (commit SHA). Pins BOTH integrity (per-file SHA)\n * and version (revision) so a model re-publish upstream can't silently\n * change ranking. `--model <local-dir>` short-circuits HF entirely\n * (`model.rs:27-30`), so this revision is only used at provision time.\n */\nexport const MODEL_REVISION = \"07ef20f406c86badca122464808f4cac2f6e4b25\"\n\n/**\n * The 5 required model files (`model.rs:8-14`). We deliberately ship\n * ONLY `model_int8.onnx` (NOT the 68 MB FP32 `model.onnx`): smaller\n * footprint, faster CPU inference, the published-recommended edge\n * config. Since we own the local model dir, omitting `model.onnx`\n * makes INT8 the only option present.\n */\nexport interface ModelFileSpec {\n name: string\n sha256: string\n}\n\n/** colgrep binary, keyed `<platform>-<arch>`. */\nexport const COLGREP_BIN: Record<string, ColbertAsset> = {\n \"win32-x64\": {\n url: \"https://github.com/lightonai/next-plaid/releases/download/v1.5.2/colgrep-x86_64-pc-windows-msvc.zip\",\n sha256: \"5986665a13e50c0c714be45d9f083ac65c243d549f7de52f72d2ecb8ead70c18\",\n archive: \"zip\",\n member: \"colgrep.exe\",\n },\n \"darwin-arm64\": {\n url: \"https://github.com/lightonai/next-plaid/releases/download/v1.5.2/colgrep-aarch64-apple-darwin.tar.xz\",\n sha256: \"28beb4524124681a6b82967d00eea92272ef7ac4cb9b4132bb193d429288ead7\",\n archive: \"tar.xz\",\n member: \"colgrep\",\n },\n \"darwin-x64\": {\n url: \"https://github.com/lightonai/next-plaid/releases/download/v1.5.2/colgrep-x86_64-apple-darwin.tar.xz\",\n sha256: \"763939edb80e93c0c9405b62929d804c0f72ae85a4a73f879ef122839264f557\",\n archive: \"tar.xz\",\n member: \"colgrep\",\n },\n \"linux-x64\": {\n url: \"https://github.com/lightonai/next-plaid/releases/download/v1.5.2/colgrep-x86_64-unknown-linux-gnu.tar.xz\",\n sha256: \"2e736e7abb32a084cfd33f78979fad577e5650e4112b28bef78a438a643f44b5\",\n archive: \"tar.xz\",\n member: \"colgrep\",\n },\n}\n\n/**\n * ONNX Runtime CPU dylib archive, keyed `<platform>-<arch>`. `member`\n * is the VERSIONED dylib basename inside the archive's `lib/` dir. The\n * Windows `.zip` ALSO ships a 377 MB `.pdb` (debug symbols) and `.lib`\n * import libs — we extract ONLY the `.dll`. On POSIX the archive ships\n * the versioned dylib plus an unversioned soname symlink; the\n * provisioner re-creates the soname symlink colgrep's `ORT_LIB_NAME`\n * expects (`libonnxruntime.so` → `…so.1.23.0`,\n * `libonnxruntime.dylib` → `…1.23.0.dylib`).\n */\nexport const ORT_LIB: Record<\n string,\n ColbertAsset & { soname?: string }\n> = {\n \"win32-x64\": {\n url: \"https://github.com/microsoft/onnxruntime/releases/download/v1.23.0/onnxruntime-win-x64-1.23.0.zip\",\n sha256: \"72c23470310ec79a7d42d27fe9d257e6c98540c73fa5a1db1f67f538c6c16f2f\",\n archive: \"zip\",\n member: \"onnxruntime.dll\",\n },\n \"darwin-arm64\": {\n url: \"https://github.com/microsoft/onnxruntime/releases/download/v1.23.0/onnxruntime-osx-arm64-1.23.0.tgz\",\n sha256: \"8182db0ebb5caa21036a3c78178f17fabb98a7916bdab454467c8f4cf34bcfdf\",\n archive: \"tar.gz\",\n member: \"libonnxruntime.1.23.0.dylib\",\n soname: \"libonnxruntime.dylib\",\n },\n \"darwin-x64\": {\n url: \"https://github.com/microsoft/onnxruntime/releases/download/v1.23.0/onnxruntime-osx-x86_64-1.23.0.tgz\",\n sha256: \"a8e43edcaa349cbfc51578a7fc61ea2b88793ccf077b4bc65aca58999d20cf0f\",\n archive: \"tar.gz\",\n member: \"libonnxruntime.1.23.0.dylib\",\n soname: \"libonnxruntime.dylib\",\n },\n \"linux-x64\": {\n url: \"https://github.com/microsoft/onnxruntime/releases/download/v1.23.0/onnxruntime-linux-x64-1.23.0.tgz\",\n sha256: \"b6deea7f2e22c10c043019f294a0ea4d2a6c0ae52a009c34847640db75ec5580\",\n archive: \"tar.gz\",\n member: \"libonnxruntime.so.1.23.0\",\n soname: \"libonnxruntime.so\",\n },\n}\n\n/**\n * The 5 model files, per-file SHA-pinned at `MODEL_REVISION`. Downloaded\n * from `https://huggingface.co/<repo>/resolve/<rev>/<file>`. These are\n * platform-agnostic (the model is the same on every OS).\n */\nexport const MODEL_FILES: ReadonlyArray<ModelFileSpec> = [\n {\n name: \"model_int8.onnx\",\n sha256: \"eac35bdaa862e2762e6455337f7a3e704b05dbc4259f00929fcc8e10207f11c7\",\n },\n {\n name: \"tokenizer.json\",\n sha256: \"a388b94942e98e5c661c6c23f919842285738bfd123a0d148dea0c56287505d0\",\n },\n {\n name: \"config.json\",\n sha256: \"c1413b20ad05927b8226aa2223b3ae104cd04c8541fe1300bdcf455fc8667601\",\n },\n {\n name: \"config_sentence_transformers.json\",\n sha256: \"34942289dec20e285b07132aa1d09980ed776a0bc34e531dd7b49c4701876871\",\n },\n {\n name: \"onnx_config.json\",\n sha256: \"fa4fef89820dcdc33c5504c62c1d5efc19603cfbfebf02368a70d51a4dbe6651\",\n },\n]\n\nexport function platformArchKey(\n platform: NodeJS.Platform = process.platform,\n arch: string = process.arch,\n): string {\n return `${platform}-${arch}`\n}\n\n/** colgrep binary asset for this platform, or undefined if unsupported. */\nexport function colgrepBinAsset(\n platform: NodeJS.Platform = process.platform,\n arch: string = process.arch,\n): ColbertAsset | undefined {\n return COLGREP_BIN[platformArchKey(platform, arch)]\n}\n\n/** ORT dylib asset for this platform, or undefined if unsupported. */\nexport function ortLibAsset(\n platform: NodeJS.Platform = process.platform,\n arch: string = process.arch,\n): (ColbertAsset & { soname?: string }) | undefined {\n return ORT_LIB[platformArchKey(platform, arch)]\n}\n\n/**\n * True iff a prebuilt colgrep + ORT asset exist for this platform-arch.\n * Used by `semanticSearchEnabled()`: the capability is platform-gated on\n * a manifest entry existing, NOT on \"already downloaded\" (gating on\n * download would hide the very tool whose first call triggers\n * provisioning).\n */\nexport function colbertPlatformSupported(\n platform: NodeJS.Platform = process.platform,\n arch: string = process.arch,\n): boolean {\n return (\n colgrepBinAsset(platform, arch) !== undefined &&\n ortLibAsset(platform, arch) !== undefined\n )\n}\n\n/** Model dir basename (the `<rev>` leaf under `models/LateOn-Code-edge/`). */\nexport function modelDirName(): string {\n return MODEL_REVISION\n}\n\n/** Short model id used in the sidecar metadata `model` field. */\nexport const MODEL_ID = \"LateOn-Code-edge\"\n\n/** next-plaid-api release tag these server binaries are promoted from. */\nexport const NEXTPLAID_SERVER_TAG = \"next-plaid-server-v1.7.0\"\n\n/** Compute flavour of a next-plaid-api server binary. */\nexport type NextPlaidServerVariant = \"cpu\" | \"cuda\"\n\nexport interface NextPlaidServerAsset {\n url: string\n /**\n * SHA256 of the downloaded binary (hex). Verified before use.\n * EMPTY means \"not yet promoted\" — the promotion workflow\n * (.github/workflows/promote-next-plaid.yml) fills it from a real\n * build; provisioning treats an empty digest as unavailable\n * (fail closed, never downloads an unverified binary).\n */\n sha256: string\n archive: \"raw\"\n variant: NextPlaidServerVariant\n /** Minimum NVIDIA driver major required (cuda variant only). */\n cudaVersion?: string\n}\n\nfunction nextPlaidServerUrl(asset: string): string {\n return `https://github.com/animeshkundu/github-router/releases/download/${NEXTPLAID_SERVER_TAG}/${asset}`\n}\n\n/**\n * next-plaid-api server binaries, keyed `<platform>-<arch>-<variant>`.\n * Built by .github/workflows/next-plaid-server.yml from the pinned\n * upstream tag: cpu = OpenBLAS-static (Linux/Windows) / Accelerate\n * (macOS); cuda = + CUDA execution provider (Linux/Windows x64 only).\n * macOS has no cuda variant (no NVIDIA target); linux-arm64 and\n * win-arm64 have no entries (unsupported → lexical fallback).\n */\nexport const NEXTPLAID_SERVER: Record<string, NextPlaidServerAsset> = {\n \"linux-x64-cpu\": {\n url: nextPlaidServerUrl(\"next-plaid-api-x86_64-unknown-linux-gnu\"),\n sha256: \"799b69de51c8f9978ea6537315da4ad63f9c2fd6f0b50f3ea8021d7ffdbc0aa3\",\n archive: \"raw\",\n variant: \"cpu\",\n },\n \"linux-x64-cuda\": {\n url: nextPlaidServerUrl(\"next-plaid-api-x86_64-unknown-linux-gnu-cuda\"),\n sha256: \"94adc97569abc4ea58d411cb23e6692c70b23e18eef0071d08fe97bc159a12d6\",\n archive: \"raw\",\n variant: \"cuda\",\n cudaVersion: \"12.8\",\n },\n \"win32-x64-cpu\": {\n url: nextPlaidServerUrl(\"next-plaid-api-x86_64-pc-windows-msvc.exe\"),\n sha256: \"86c243c15f84ff32186f6fe04e98c2d71d922e13a2fdaa9b95da3ac2df8ff7a1\",\n archive: \"raw\",\n variant: \"cpu\",\n },\n \"win32-x64-cuda\": {\n url: nextPlaidServerUrl(\"next-plaid-api-x86_64-pc-windows-msvc-cuda.exe\"),\n sha256: \"f235faf71fbcec0a28024cb416e3060c62f035f446a4eb3a1024220be0666edc\",\n archive: \"raw\",\n variant: \"cuda\",\n cudaVersion: \"12.8\",\n },\n \"darwin-arm64-cpu\": {\n url: nextPlaidServerUrl(\"next-plaid-api-aarch64-apple-darwin\"),\n sha256: \"04d8d8ab6a49617076e1c0f4ff7756a555efd159890d5c3ea1adf54bae0238bb\",\n archive: \"raw\",\n variant: \"cpu\",\n },\n \"darwin-x64-cpu\": {\n url: nextPlaidServerUrl(\"next-plaid-api-x86_64-apple-darwin\"),\n sha256: \"f3bca729db0043c7b609731ea095685fc2a72f0c2f58571b33c4fa52691fbe98\",\n archive: \"raw\",\n variant: \"cpu\",\n },\n}\n\n/** Server asset for this platform-arch-variant, or undefined if unsupported. */\nexport function nextPlaidServerAsset(\n variant: NextPlaidServerVariant,\n platform: NodeJS.Platform = process.platform,\n arch: string = process.arch,\n): NextPlaidServerAsset | undefined {\n return NEXTPLAID_SERVER[`${platformArchKey(platform, arch)}-${variant}`]\n}\n\n/** True iff a promoted (SHA-pinned) server binary exists for this variant. */\nexport function nextPlaidServerPromoted(\n variant: NextPlaidServerVariant,\n platform: NodeJS.Platform = process.platform,\n arch: string = process.arch,\n): boolean {\n const asset = nextPlaidServerAsset(variant, platform, arch)\n return asset !== undefined && asset.sha256.length > 0\n}\n","/**\n * Minimal, dependency-free archive extraction for the toolbelt.\n *\n * We only ever need to pull ONE known binary out of a release archive,\n * so a full archiver dependency is overkill. These parsers find the\n * regular-file member whose basename matches the expected binary and\n * return its bytes — and **reject non-regular entries** (symlinks,\n * hardlinks, devices, directories), closing the malicious-archive\n * entry-type vector that a path-only zip-slip check would miss.\n */\n\nimport { gunzipSync, inflateRawSync } from \"node:zlib\"\n\nfunction baseName(p: string): string {\n const norm = p.replace(/\\\\/g, \"/\")\n const idx = norm.lastIndexOf(\"/\")\n return idx === -1 ? norm : norm.slice(idx + 1)\n}\n\n/**\n * Extract the first regular-file member whose basename equals\n * `wantBasename` from an **xz-compressed tarball** (`.tar.xz`).\n *\n * Node's `zlib` has no xz/lzma decoder and the project carries no xz\n * dependency, so this shells out to the system `tar` (universally\n * present on macOS/Linux, which is the ONLY place a `.tar.xz` is ever\n * fetched — the colgrep Windows asset is a `.zip` handled by\n * `extractZipMember`). The xz path therefore never runs on the Windows\n * primary deployment target.\n *\n * Safety: the archive is extracted into a fresh, caller-provided temp\n * dir (NOT the cwd) and we read back ONLY the named regular-file member.\n * `tar` is invoked with `shell:false` (argv array, no metacharacter\n * surface) and `--no-same-owner` so a hostile archive can't request a\n * uid/gid change. The colgrep tarball nests its binary one dir deep\n * (`colgrep-<triple>/colgrep`), so we search recursively for the\n * basename rather than assuming a flat layout, and never follow\n * symlinks during the walk (closes the escape-the-extract-dir vector).\n *\n * Returns the member bytes, or null if the member is absent or `tar`\n * fails. The provisioner treats null as \"skip / mismatch\".\n */\nexport async function extractTarXzMember(\n buf: Buffer,\n wantBasename: string,\n tmpDir: string,\n): Promise<Buffer | null> {\n const { spawn } = await import(\"node:child_process\")\n const fs = await import(\"node:fs/promises\")\n const path = await import(\"node:path\")\n\n const archivePath = path.join(tmpDir, \"archive.tar.xz\")\n const extractDir = path.join(tmpDir, \"x\")\n try {\n await fs.mkdir(extractDir, { recursive: true })\n await fs.writeFile(archivePath, buf)\n } catch {\n return null\n }\n\n const ok = await new Promise<boolean>((resolve) => {\n let child: ReturnType<typeof spawn>\n try {\n child = spawn(\n \"tar\",\n [\"-xJf\", archivePath, \"-C\", extractDir, \"--no-same-owner\"],\n { stdio: \"ignore\", windowsHide: true },\n )\n } catch {\n resolve(false)\n return\n }\n const timer = setTimeout(() => {\n try {\n child.kill(\"SIGKILL\")\n } catch {\n // already gone\n }\n resolve(false)\n }, 60_000)\n timer.unref?.()\n child.on(\"error\", () => {\n clearTimeout(timer)\n resolve(false)\n })\n child.on(\"close\", (code) => {\n clearTimeout(timer)\n resolve(code === 0)\n })\n })\n if (!ok) return null\n\n const wants = new Set([wantBasename, `${wantBasename}.exe`])\n const found = await findRegularFile(fs, path, extractDir, wants, 6)\n if (!found) return null\n try {\n return await fs.readFile(found)\n } catch {\n return null\n }\n}\n\nasync function findRegularFile(\n fs: typeof import(\"node:fs/promises\"),\n path: typeof import(\"node:path\"),\n dir: string,\n wants: Set<string>,\n depthBudget: number,\n): Promise<string | null> {\n if (depthBudget < 0) return null\n let entries: Array<import(\"node:fs\").Dirent>\n try {\n entries = await fs.readdir(dir, { withFileTypes: true })\n } catch {\n return null\n }\n // Files first (so a matching regular file outranks a same-named dir).\n for (const e of entries) {\n if (e.isFile() && wants.has(e.name)) {\n return path.join(dir, e.name)\n }\n }\n for (const e of entries) {\n // Never follow symlinks during the walk — only descend real dirs.\n if (e.isDirectory()) {\n const hit = await findRegularFile(\n fs,\n path,\n path.join(dir, e.name),\n wants,\n depthBudget - 1,\n )\n if (hit) return hit\n }\n }\n return null\n}\n\n/**\n * Extract the first REGULAR-FILE tar member whose basename equals\n * `wantBasename` (optionally with a `.exe` suffix). Returns its bytes,\n * or null if absent. `buf` is the gzip-compressed tarball.\n */\nexport function extractTarGzMember(\n buf: Buffer,\n wantBasename: string,\n): Buffer | null {\n let tar: Buffer\n try {\n tar = gunzipSync(buf)\n } catch {\n return null\n }\n const wants = new Set([wantBasename, `${wantBasename}.exe`])\n\n let offset = 0\n while (offset + 512 <= tar.length) {\n const header = tar.subarray(offset, offset + 512)\n // Two consecutive zero blocks → end of archive.\n if (header.every((b) => b === 0)) break\n\n const name = readTarString(header, 0, 100)\n const prefix = readTarString(header, 345, 155)\n const fullName = prefix ? `${prefix}/${name}` : name\n const sizeOctal = readTarString(header, 124, 12).trim()\n const size = parseInt(sizeOctal || \"0\", 8)\n const typeflag = String.fromCharCode(header[156])\n\n const dataStart = offset + 512\n // Regular file is typeflag '0' or '\\0'. Anything else (symlink '2',\n // hardlink '1', char '3', block '4', dir '5', fifo '6') is rejected.\n const isRegular = typeflag === \"0\" || typeflag === \"\\0\"\n if (isRegular && wants.has(baseName(fullName))) {\n if (dataStart + size > tar.length) return null\n return Buffer.from(tar.subarray(dataStart, dataStart + size))\n }\n\n // Advance past this entry's data (padded to 512).\n offset = dataStart + Math.ceil(size / 512) * 512\n }\n return null\n}\n\nfunction readTarString(block: Buffer, start: number, len: number): string {\n const slice = block.subarray(start, start + len)\n const nul = slice.indexOf(0)\n return slice.subarray(0, nul === -1 ? len : nul).toString(\"utf8\")\n}\n\n/**\n * Extract the first REGULAR-FILE zip member whose basename equals\n * `wantBasename` (optionally `.exe`). Supports stored (0) and deflate\n * (8) compression. Rejects directories and unix-symlink entries.\n */\nexport function extractZipMember(\n buf: Buffer,\n wantBasename: string,\n): Buffer | null {\n const wants = new Set([wantBasename, `${wantBasename}.exe`])\n\n // Locate End Of Central Directory (signature 0x06054b50). Scan back\n // from the end (no zip comment expected, but allow up to 64KB).\n const EOCD_SIG = 0x06054b50\n let eocd = -1\n const minStart = Math.max(0, buf.length - 65557)\n for (let i = buf.length - 22; i >= minStart; i--) {\n if (buf.readUInt32LE(i) === EOCD_SIG) {\n eocd = i\n break\n }\n }\n if (eocd === -1) return null\n\n const entryCount = buf.readUInt16LE(eocd + 10)\n let cd = buf.readUInt32LE(eocd + 16)\n\n const CEN_SIG = 0x02014b50\n for (let i = 0; i < entryCount; i++) {\n if (cd + 46 > buf.length || buf.readUInt32LE(cd) !== CEN_SIG) return null\n const method = buf.readUInt16LE(cd + 10)\n const compSize = buf.readUInt32LE(cd + 20)\n const nameLen = buf.readUInt16LE(cd + 28)\n const extraLen = buf.readUInt16LE(cd + 30)\n const commentLen = buf.readUInt16LE(cd + 32)\n const externalAttrs = buf.readUInt32LE(cd + 38)\n const localOffset = buf.readUInt32LE(cd + 42)\n const name = buf.subarray(cd + 46, cd + 46 + nameLen).toString(\"utf8\")\n\n const unixMode = (externalAttrs >>> 16) & 0xffff\n const isSymlink = (unixMode & 0xf000) === 0xa000\n const isDir = name.endsWith(\"/\")\n\n if (!isSymlink && !isDir && wants.has(baseName(name))) {\n return readZipLocalEntry(buf, localOffset, method, compSize)\n }\n\n cd += 46 + nameLen + extraLen + commentLen\n }\n return null\n}\n\nfunction readZipLocalEntry(\n buf: Buffer,\n localOffset: number,\n method: number,\n compSize: number,\n): Buffer | null {\n const LOC_SIG = 0x04034b50\n if (localOffset + 30 > buf.length || buf.readUInt32LE(localOffset) !== LOC_SIG) {\n return null\n }\n const nameLen = buf.readUInt16LE(localOffset + 26)\n const extraLen = buf.readUInt16LE(localOffset + 28)\n const dataStart = localOffset + 30 + nameLen + extraLen\n const comp = buf.subarray(dataStart, dataStart + compSize)\n try {\n if (method === 0) return Buffer.from(comp) // stored\n if (method === 8) return inflateRawSync(comp) // deflate\n } catch {\n return null\n }\n return null\n}\n","/**\n * ColBERT sidecar provisioner: download + SHA-verify + extract the three\n * artifacts (`colgrep` binary, ONNX Runtime dylib, ColBERT INT8 model)\n * into the router-owned data dir, then run a smoke test that confirms\n * the ORT dylib actually loads before the capability advertises `ready`.\n *\n * Mirrors `toolbelt/provision.ts`:\n * - **Best-effort.** Every step is timeout-bounded and the public\n * `provisionColbert()` swallows to a structured result; it never\n * throws to the launcher.\n * - **Verified.** Each download's SHA256 must match the hardcoded\n * manifest digest BEFORE it is written into place. This closes the\n * two supply-chain holes colgrep leaves open (it does NO checksum on\n * its own ORT / HF-model downloads).\n * - **Concurrency-safe.** A cross-process `withInstallLock` serializes\n * downloads; partial files land in a temp dir and are atomically\n * renamed into VERSIONED artifact dirs so a failed upgrade never\n * poisons the current install.\n */\n\nimport { createHash, randomBytes } from \"node:crypto\"\nimport { existsSync, readFileSync } from \"node:fs\"\nimport {\n chmod,\n mkdir,\n readFile,\n rename,\n rm,\n symlink,\n writeFile,\n} from \"node:fs/promises\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport consola from \"consola\"\n\nimport { PATHS } from \"../paths\"\nimport { runManagedExeCapture } from \"../exec\"\nimport { withInstallLock } from \"../update-lock\"\nimport { extractTarGzMember, extractTarXzMember, extractZipMember } from \"../toolbelt/extract\"\n\nimport {\n colgrepBinAsset,\n ortLibAsset,\n nextPlaidServerAsset,\n MODEL_FILES,\n MODEL_REPO,\n MODEL_REVISION,\n modelDirName,\n ORT_VERSION,\n type ColbertAsset,\n type NextPlaidServerVariant,\n} from \"./manifest\"\n\n/**\n * Per-download cap. The Windows ORT `.zip` is ~78 MB (it bundles a\n * 377 MB `.pdb` we discard but still transfer), so this is larger than\n * the toolbelt's 64 MB. 256 MB comfortably covers every artifact.\n */\nconst MAX_DOWNLOAD_BYTES = 256 * 1024 * 1024\nconst DOWNLOAD_TIMEOUT_MS = 120_000\nconst SMOKE_TIMEOUT_MS = 30_000\n\nconst EXE_EXT = process.platform === \"win32\" ? \".exe\" : \"\"\n\nexport type ColbertProvisionStatus =\n | \"ready\" // binary + model + ORT present AND smoke test passed\n | \"unsupported\" // no manifest asset for this platform-arch\n | \"incomplete\" // a download/verify/extract step failed\n | \"smoke_failed\" // artifacts present but ORT dlopen / colgrep run failed\n\nexport interface ColbertProvisionResult {\n status: ColbertProvisionStatus\n /** Absolute path to the provisioned colgrep binary (when present). */\n binaryPath?: string\n /** Absolute path to the ORT dylib (ORT_DYLIB_PATH) (when present). */\n ortDylibPath?: string\n /** Absolute path to the local model dir (--model) (when present). */\n modelDir?: string\n /** SHA of the colgrep binary archive (for the rebuild-on-engine-change trigger). */\n binarySha?: string\n /** SHA of the ORT archive. */\n ortSha?: string\n /** Short, non-source-bearing reason when not ready (safe to surface). */\n reason?: string\n}\n\n/** Absolute path the provisioned colgrep binary lives at. */\nexport function colgrepBinaryPath(): string {\n return path.join(PATHS.COLBERT_BIN_DIR, \"colgrep\" + EXE_EXT)\n}\n\n/** Absolute path the provisioned model dir lives at (pinned revision). */\nexport function colbertModelDir(): string {\n return path.join(PATHS.COLBERT_MODELS_DIR, \"LateOn-Code-edge\", modelDirName())\n}\n\n/**\n * Canonical model argument for every colgrep invocation and project lookup.\n * colgrep hashes the raw model string, so slash variants fork one physical\n * index into distinct project keys on Windows.\n */\nexport function canonicalColbertModelDir(): string {\n return path.resolve(colbertModelDir())\n}\n\n/** Absolute path a provisioned next-plaid-api server binary lives at. */\nexport function nextPlaidServerBinaryPath(variant: NextPlaidServerVariant): string {\n const suffix = variant === \"cuda\" ? \"-cuda\" : \"\"\n return path.join(PATHS.COLBERT_BIN_DIR, `next-plaid-api${suffix}${EXE_EXT}`)\n}\n\n/**\n * Provision the next-plaid-api server binary for the requested variant.\n * Lazy and separate from `provisionColbert()` (which owns the\n * colgrep/ORT/model trio): only the service backend calls this, so the\n * default colgrep path never pays for a server download.\n *\n * Fail-closed: unknown platform, unpromoted SHA (empty digest), or any\n * download/verify failure all report `reason` instead of throwing — the\n * caller falls back (cuda → cpu variant → colgrep → lexical).\n */\nexport async function provisionNextPlaidServer(\n variant: NextPlaidServerVariant,\n): Promise<{ path?: string; reason?: string }> {\n const asset = nextPlaidServerAsset(variant)\n if (!asset) return { reason: \"no server asset for this platform\" }\n if (asset.sha256.length === 0) {\n return { reason: \"server binary not yet promoted for this variant\" }\n }\n const dest = nextPlaidServerBinaryPath(variant)\n try {\n await withInstallLock(\"colbert-provision.lock\", async () => {\n await provisionBinary(asset, dest)\n })\n return { path: dest }\n } catch (err) {\n consola.debug(`colbert: server provision failed (${variant}):`, err)\n return { reason: \"server download/verify failed\" }\n }\n}\n\n/** Absolute path the provisioned ORT dylib lives at. */\nexport function colbertOrtDylibPath(): string {\n const asset = ortLibAsset()\n const lib = asset?.member ?? \"libonnxruntime.so\"\n return path.join(PATHS.COLBERT_ORT_DIR, ORT_VERSION, \"cpu\", lib)\n}\n\n/**\n * Cheap on-disk presence check (no download, no smoke). Used by the\n * MCP preflight to decide `provisioning` vs `ready`-eligible. Returns\n * true iff the binary, model dir (with the INT8 onnx), and ORT dylib\n * all exist on disk.\n */\nexport function colbertArtifactsPresent(): boolean {\n return (\n existsSync(colgrepBinaryPath()) &&\n existsSync(path.join(colbertModelDir(), \"model_int8.onnx\")) &&\n existsSync(colbertOrtDylibPath())\n )\n}\n\n/**\n * Router credentials that must NOT reach a colgrep child. colgrep is a\n * SHA-verified local binary, but it makes network calls (model fetch), so\n * no router secret belongs in its environment. Mirrors the credential-drop\n * posture of the worker-bash env (src/lib/worker-agent/bash.ts).\n */\nconst COLGREP_SECRET_ENV_KEYS = [\n \"GITHUB_TOKEN\",\n \"ANTHROPIC_AUTH_TOKEN\",\n \"ANTHROPIC_API_KEY\",\n \"OPENAI_API_KEY\",\n \"COPILOT_TOKEN\",\n]\n\n/**\n * Strip router credentials (the keys above + any `GH_ROUTER_*`) from a\n * child-process env object, in place. Operates on a caller-owned copy of\n * `process.env`, never the live process env.\n */\nexport function dropColgrepSecrets(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n for (const k of Object.keys(env)) {\n if (k.startsWith(\"GH_ROUTER_\") || COLGREP_SECRET_ENV_KEYS.includes(k)) {\n delete env[k]\n }\n }\n return env\n}\n\n/** Marker file written next to the model dir once the smoke test passed. */\nfunction smokeMarkerPath(): string {\n return path.join(PATHS.COLBERT_DIR, \".smoke-ok\")\n}\n\n/**\n * The content written into `.smoke-ok` on a successful smoke test:\n * the SHAs of the binary + ORT archive + model revision the smoke was\n * run against. `colbertSmokeOk()` validates the on-disk marker against\n * the CURRENT manifest values, so a re-pin (new binary/ORT/model)\n * invalidates a stale marker — the capability gate then reads false\n * until the new artifact set is re-provisioned and re-smoked. Without\n * this, a partial provision after a re-pin could leave an old `.smoke-ok`\n * that advertises `ready` for an un-smoke-tested artifact set.\n */\nfunction expectedSmokeMarker(): string {\n const bin = colgrepBinAsset()?.sha256 ?? \"?\"\n const ort = ortLibAsset()?.sha256 ?? \"?\"\n return `colbert-smoke-ok\\nbinary=${bin}\\nort=${ort}\\nmodel=${MODEL_REVISION}\\n`\n}\n\n/**\n * Has the post-provision smoke test passed for the CURRENT artifact set?\n * Validates the marker content against the live manifest SHAs so a\n * re-pin invalidates a stale marker (see `expectedSmokeMarker`).\n */\nexport function colbertSmokeOk(): boolean {\n try {\n return readFileSync(smokeMarkerPath(), \"utf8\") === expectedSmokeMarker()\n } catch {\n return false\n }\n}\n\n/**\n * Provision all three artifacts under a cross-process lock, then smoke\n * test. Idempotent: present + sha-matching artifacts are skipped. Never\n * throws — returns a structured status the caller can act on.\n */\nexport async function provisionColbert(): Promise<ColbertProvisionResult> {\n const binAsset = colgrepBinAsset()\n const ortAsset = ortLibAsset()\n if (!binAsset || !ortAsset) {\n return { status: \"unsupported\", reason: \"no prebuilt asset for this platform\" }\n }\n\n const result: ColbertProvisionResult = {\n status: \"incomplete\",\n binarySha: binAsset.sha256,\n ortSha: ortAsset.sha256,\n }\n\n try {\n await mkdir(PATHS.COLBERT_DIR, { recursive: true })\n } catch (err) {\n consola.debug(\"colbert: cannot create data dir:\", err)\n return { ...result, reason: \"data dir unwritable\" }\n }\n\n await withInstallLock(\"colbert-provision.lock\", async () => {\n // 1. Binary\n const binaryPath = colgrepBinaryPath()\n try {\n await provisionBinary(binAsset, binaryPath)\n result.binaryPath = binaryPath\n } catch (err) {\n consola.debug(\"colbert: binary provision failed:\", err)\n result.reason = \"binary download/verify failed\"\n return\n }\n\n // 2. ORT dylib (+ soname symlink on POSIX)\n const ortDylibPath = colbertOrtDylibPath()\n try {\n await provisionOrt(ortAsset, ortDylibPath)\n result.ortDylibPath = ortDylibPath\n } catch (err) {\n consola.debug(\"colbert: ORT provision failed:\", err)\n result.reason = \"ORT download/verify failed\"\n return\n }\n\n // 3. Model (5 files, per-file SHA)\n const modelDir = colbertModelDir()\n try {\n await provisionModel(modelDir)\n result.modelDir = modelDir\n } catch (err) {\n consola.debug(\"colbert: model provision failed:\", err)\n result.reason = \"model download/verify failed\"\n return\n }\n\n result.status = \"incomplete\" // becomes ready only after smoke\n })\n\n // All three present? Run the smoke test (outside the download lock —\n // it spawns colgrep, which we don't want to hold the download lock for).\n if (result.binaryPath && result.ortDylibPath && result.modelDir) {\n const smoke = await runSmokeTest(result.binaryPath, result.ortDylibPath)\n if (smoke.ok) {\n await writeFile(smokeMarkerPath(), expectedSmokeMarker()).catch(() => {})\n result.status = \"ready\"\n } else {\n await rm(smokeMarkerPath(), { force: true }).catch(() => {})\n result.status = \"smoke_failed\"\n result.reason = smoke.reason\n }\n }\n\n return result\n}\n\nasync function provisionBinary(\n asset: ColbertAsset,\n dest: string,\n): Promise<void> {\n const sidecar = `${dest}.sha256`\n if (await installedArtifactIsIntact(sidecar, dest, asset.sha256)) {\n return // idempotent\n }\n await mkdir(path.dirname(dest), { recursive: true })\n const archive = await download(asset.url)\n verifySha(archive, asset.sha256, \"colgrep binary\")\n const member = await extractMember(asset, archive, \"colgrep\")\n if (!member) throw new Error(\"colgrep binary not found in archive\")\n await atomicWrite(dest, member, /*executable*/ true)\n await writeFile(sidecar, sidecarContent(asset.sha256, member)).catch(() => {})\n}\n\nasync function provisionOrt(\n asset: ColbertAsset & { soname?: string },\n dest: string,\n): Promise<void> {\n const sidecar = `${dest}.sha256`\n if (await installedArtifactIsIntact(sidecar, dest, asset.sha256)) {\n return // idempotent\n }\n await mkdir(path.dirname(dest), { recursive: true })\n const archive = await download(asset.url)\n verifySha(archive, asset.sha256, \"ONNX Runtime\")\n const member = await extractMember(asset, archive, asset.member ?? \"\")\n if (!member) throw new Error(\"ORT dylib not found in archive\")\n await atomicWrite(dest, member, /*executable*/ true)\n await writeFile(sidecar, sidecarContent(asset.sha256, member)).catch(() => {})\n // POSIX: create the unversioned soname symlink colgrep's ORT_LIB_NAME\n // expects (e.g. libonnxruntime.so → libonnxruntime.so.1.23.0). Some\n // loaders dlopen the versioned name directly (we point ORT_DYLIB_PATH\n // at the versioned file), but the symlink is cheap insurance.\n if (process.platform !== \"win32\" && asset.soname) {\n const link = path.join(path.dirname(dest), asset.soname)\n await rm(link, { force: true }).catch(() => {})\n await symlink(path.basename(dest), link).catch((err) =>\n consola.debug(\"colbert: ORT soname symlink skipped:\", err),\n )\n }\n}\n\nasync function provisionModel(modelDir: string): Promise<void> {\n await mkdir(modelDir, { recursive: true })\n for (const file of MODEL_FILES) {\n const dest = path.join(modelDir, file.name)\n if (existsSync(dest)) {\n // Verify existing matches the pinned digest; re-download if not.\n try {\n const have = await readFile(dest)\n if (createHash(\"sha256\").update(have).digest(\"hex\") === file.sha256) {\n continue\n }\n } catch {\n // fall through to re-download\n }\n }\n const url = `https://huggingface.co/${MODEL_REPO}/resolve/${MODEL_REVISION}/${file.name}`\n const bytes = await download(url)\n verifySha(bytes, file.sha256, `model file ${file.name}`)\n await atomicWrite(dest, bytes, /*executable*/ false)\n }\n}\n\nasync function extractMember(\n asset: ColbertAsset,\n archive: Buffer,\n wantBasename: string,\n): Promise<Buffer | null> {\n if (asset.archive === \"raw\") return archive\n if (asset.archive === \"zip\") return extractZipMember(archive, wantBasename)\n if (asset.archive === \"tar.gz\") return extractTarGzMember(archive, wantBasename)\n if (asset.archive === \"tar.xz\") {\n // POSIX-only path (Windows assets are never tar.xz). Needs a temp dir.\n const tmp = path.join(\n PATHS.COLBERT_DIR,\n `xz-tmp-${process.pid}-${randomBytes(4).toString(\"hex\")}`,\n )\n try {\n return await extractTarXzMember(archive, wantBasename, tmp)\n } finally {\n await rm(tmp, { recursive: true, force: true }).catch(() => {})\n }\n }\n return null\n}\n\nfunction verifySha(data: Buffer, expected: string, label: string): void {\n const got = createHash(\"sha256\").update(data).digest(\"hex\")\n if (got !== expected) {\n throw new Error(\n `checksum mismatch for ${label}: expected ${expected}, got ${got}`,\n )\n }\n}\n\nasync function download(url: string): Promise<Buffer> {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), DOWNLOAD_TIMEOUT_MS)\n try {\n const res = await fetch(url, {\n signal: controller.signal,\n redirect: \"follow\",\n headers: { \"User-Agent\": \"github-router-colbert\" },\n })\n if (!res.ok) throw new Error(`download ${url}: HTTP ${res.status}`)\n const buf = Buffer.from(await res.arrayBuffer())\n if (buf.length > MAX_DOWNLOAD_BYTES) {\n throw new Error(`download ${url}: exceeds ${MAX_DOWNLOAD_BYTES} bytes`)\n }\n return buf\n } finally {\n clearTimeout(timer)\n }\n}\n\n/** Write bytes to a unique temp then atomically rename into place. */\nasync function atomicWrite(\n dest: string,\n bytes: Buffer,\n executable: boolean,\n): Promise<void> {\n const tmp = `${dest}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`\n await writeFile(tmp, bytes)\n if (executable && process.platform !== \"win32\") {\n await chmod(tmp, 0o755).catch(() => {})\n }\n try {\n await rename(tmp, dest)\n } catch {\n // Windows: rename won't replace an existing/locked dest. Remove and\n // retry once; if that fails (in-use .exe), leave the existing copy.\n try {\n await rm(dest, { force: true })\n await rename(tmp, dest)\n } catch (err) {\n await rm(tmp, { force: true }).catch(() => {})\n throw err\n }\n }\n}\n\n/**\n * Is the artifact already installed AND still the bytes we installed?\n *\n * Sidecar format is two whitespace-separated hashes: the ARCHIVE sha (which\n * manifest revision this came from) and the INSTALLED-FILE sha (what we wrote\n * to disk). Both are required.\n *\n * The archive hash alone is not enough, and trusting it caused a real outage.\n * `existsSync(dest) && sidecarMatches(archiveSha)` treats any file at the path\n * as good, so when a lane-1 test with a leaked `node:os` mock overwrote the\n * real `colgrep.exe` with a 6-byte stub, provisioning kept short-circuiting on\n * the still-valid sidecar and never re-downloaded. The smoke test then failed\n * every launch, removed `.smoke-ok`, and semantic search reported \"unavailable\n * on this host\" forever. Only manually deleting the binary could recover it.\n *\n * A legacy single-hash sidecar means the installed bytes were never recorded,\n * so their provenance is unknown. That returns false deliberately: one extra\n * download self-heals every install already corrupted by the above, which is\n * the whole point of checking.\n *\n * This matches what the model files already do (they hash installed content\n * before reuse); the binary and ORT were the two that skipped it.\n */\nexport async function installedArtifactIsIntact(\n sidecar: string,\n dest: string,\n archiveSha: string,\n): Promise<boolean> {\n try {\n if (!existsSync(dest)) return false\n const [recordedArchive, recordedInstalled] = (await readFile(sidecar, \"utf8\"))\n .trim()\n .split(/\\s+/)\n // Wrong manifest revision: a re-pin must re-download.\n if (recordedArchive !== archiveSha) return false\n // Legacy sidecar: installed bytes unverifiable, so re-provision.\n if (!recordedInstalled) return false\n const actual = createHash(\"sha256\")\n .update(await readFile(dest))\n .digest(\"hex\")\n return actual === recordedInstalled\n } catch {\n return false\n }\n}\n\n/** Sidecar content pairing the archive revision with the installed bytes. */\nfunction sidecarContent(archiveSha: string, installed: Buffer): string {\n return `${archiveSha}\\n${createHash(\"sha256\").update(installed).digest(\"hex\")}`\n}\n\n/**\n * Post-provision smoke test. Runs ONE cheap colgrep invocation with the\n * EXACT isolating env the runner uses (`COLGREP_DATA_DIR`,\n * `ORT_DYLIB_PATH`, `--model <dir>`, `--force-cpu`) against a tiny\n * one-file fixture, and confirms it exits 0 AND the ORT dylib actually\n * loaded.\n *\n * This is LOAD-BEARING (design Risk #5): the spike proved that an\n * invalid `ORT_DYLIB_PATH` makes colgrep print \"is not a loadable ONNX\n * Runtime dylib; ignoring\" and silently FALL THROUGH to its own\n * unverified GitHub download. So we must verify the handoff actually\n * took before advertising `ready`. We detect the fall-through by\n * scanning stderr for colgrep's exact \"ignoring\" warning — if present,\n * the dylib didn't load and we fail the smoke test even on exit 0.\n */\nasync function runSmokeTest(\n binaryPath: string,\n ortDylibPath: string,\n): Promise<{ ok: boolean; reason?: string }> {\n const tmp = path.join(\n PATHS.COLBERT_DIR,\n `smoke-${process.pid}-${randomBytes(4).toString(\"hex\")}`,\n )\n const fixtureDir = path.join(tmp, \"fixture\")\n const dataDir = path.join(tmp, \"data\")\n try {\n await mkdir(fixtureDir, { recursive: true })\n await mkdir(dataDir, { recursive: true })\n await writeFile(\n path.join(fixtureDir, \"smoke.py\"),\n \"def smoke_test_function():\\n return 1\\n\",\n )\n } catch {\n return { ok: false, reason: \"smoke fixture setup failed\" }\n }\n\n try {\n const env = dropColgrepSecrets({\n ...process.env,\n COLGREP_DATA_DIR: dataDir,\n ORT_DYLIB_PATH: ortDylibPath,\n COLGREP_FORCE_CPU: \"1\",\n // Co-locate ORT dir on PATH so dependent DLLs resolve on Windows.\n PATH: `${path.dirname(ortDylibPath)}${path.delimiter}${process.env.PATH ?? \"\"}`,\n })\n const res = await runManagedExeCapture(\n binaryPath,\n [\n \"search\",\n \"--json\",\n \"--color\",\n \"never\",\n \"--force-cpu\",\n \"--model\",\n canonicalColbertModelDir(),\n \"-y\",\n \"-k\",\n \"1\",\n \"smoke\",\n fixtureDir,\n ],\n { env, timeoutMs: SMOKE_TIMEOUT_MS, maxStdoutBytes: 4 * 1024 * 1024 },\n )\n if (res.timedOut) return { ok: false, reason: \"smoke test timed out\" }\n if (res.code !== 0) {\n return { ok: false, reason: `colgrep exited ${res.code}` }\n }\n // The ORT handoff guard: colgrep prints this EXACT phrase and falls\n // through to its own unverified download when ORT_DYLIB_PATH is bad.\n if (/not a loadable onnx runtime dylib/i.test(res.stderr)) {\n return { ok: false, reason: \"ORT dylib failed to load (ORT_DYLIB_PATH ignored)\" }\n }\n return { ok: true }\n } catch (err) {\n consola.debug(\"colbert: smoke test spawn failed:\", err)\n return { ok: false, reason: \"colgrep failed to launch (AV quarantine / missing runtime?)\" }\n } finally {\n await rm(tmp, { recursive: true, force: true }).catch(() => {})\n }\n}\n","/**\n * ColBERT index store: router-owned sidecar metadata, the per-query\n * freshness verdict (git HEAD / dirty check), the `COLGREP_DATA_DIR`\n * derivation, and the debounce ledger for background `init` builds.\n *\n * colgrep owns the PHYSICAL index dir (keyed by xxh3(path|model) under\n * COLGREP_DATA_DIR) and its own incremental updater. We do NOT key the\n * physical dir by commit — that would force a full rebuild per commit.\n * Instead the router keeps a tiny metadata sidecar per workspace and\n * computes a freshness verdict on each query so we never LABEL a stale\n * result as `ready` (design §4, Risk #3).\n *\n * Staleness model:\n * - `fresh` ⇔ status ready AND HEAD == lastIndexedHead AND tree not\n * dirtier than it was at index time. → serve semantic.\n * - `stale` ⇔ status ready but HEAD moved (branch switch / commits)\n * OR the working tree is dirty since the last index. →\n * honest `stale` notice, NO results (per the dropped-\n * fallback contract — we do NOT silently re-search).\n * - non-git workspace → no lastIndexedHead; freshness falls back to\n * mtime reasoning, which is exactly colgrep's own incremental signal,\n * so a clean ready index is treated as fresh.\n */\n\nimport {\n existsSync,\n readdirSync,\n readFileSync,\n realpathSync,\n statSync,\n} from \"node:fs\"\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport { runManagedExeCapture } from \"../exec\"\nimport { resolveExecutable } from \"../exec\"\nimport { PATHS } from \"../paths\"\n\nimport { colgrepBinAsset, MODEL_ID, ortLibAsset } from \"./manifest\"\nimport { isPidAlive } from \"./lifecycle\"\nimport { canonicalColbertModelDir } from \"./provision\"\n\n/** Sidecar metadata per workspace. Router-owned; colgrep never reads it. */\nexport interface ColbertMeta {\n workspace: string\n model: string\n modelRev: string\n /** Engine-change triggers: a change forces a full rebuild. */\n binarySha?: string\n ortSha?: string\n status: \"absent\" | \"building\" | \"ready\" | \"failed\"\n lastIndexedHead?: string\n lastIndexedDirty?: boolean\n lastIndexedAt?: string\n /** Why the last build failed (drives the self-heal vs operator-actionable\n * decision). `crashed` = the build PID died without writing a result\n * (proxy kill / OOM); `stuck` = the inactivity watchdog killed a hung\n * build; `corrupt` = physical PLAID shards are incoherent;\n * `error` = colgrep non-zero exit; `launch` = spawn threw. */\n failureClass?: \"crashed\" | \"stuck\" | \"corrupt\" | \"error\" | \"launch\"\n /** Consecutive failed build attempts; reset to 0 on a successful build.\n * Caps the self-heal so a persistently-failing workspace stops retrying. */\n failedAttempts?: number\n /**\n * The inputs in effect when the current failure streak was recorded.\n *\n * `failedAttempts` is evidence about a SPECIFIC set of inputs, not a\n * permanent verdict on the workspace. Without this, a streak that reaches\n * the cap is terminal for the life of the process — a build that failed on\n * one bad commit, or under an old colgrep binary, would keep vetoing\n * retries long after the cause was gone. Comparing these against the\n * current state lets `handleFailure` tell \"the same inputs failed again\"\n * from \"the inputs changed, so the streak is stale\".\n *\n * Deliberately separate from `lastIndexedHead` / `lastIndexedDirty`: those\n * mean \"what we successfully indexed\" on the ready path and feed the\n * git-freshness comparison, so reusing them would entangle failure-reset\n * with freshness.\n */\n failedAt?: {\n head?: string\n dirty?: boolean\n binarySha?: string\n ortSha?: string\n modelRev?: string\n }\n /**\n * Which router-bug epoch this entry was last reconciled against. A sidecar\n * behind `WATCHDOG_EPOCH` has its watchdog-attributed failure streak\n * cleared once — see `applyWatchdogEpoch`. Absent on entries written before\n * this field existed, which is exactly the population that needs the reset.\n */\n watchdogEpoch?: number\n /** Owning `init` PID (boot-sweep reclassification). */\n buildPid?: number\n /** Per-proxy-run UUID (ownership disambiguation for the boot sweep). */\n ownerInstanceId?: string\n}\n\nexport type Freshness =\n | \"fresh\"\n | \"stale\"\n | \"absent\"\n | \"building\"\n | \"crashed\"\n | \"corrupt\"\n | \"failed\"\n\nconst GIT_TIMEOUT_MS = 4000\n\n/** Grace window after a `building` write before a workspace with no live\n * build PID is declared `crashed` — covers the cross-process window where\n * one proxy wrote `building` but hasn't yet recorded the colgrep child PID. */\nconst BUILD_SPAWN_GRACE_MS = 30_000\n\n/**\n * Hash a workspace path the same way the metadata sidecar is keyed.\n * NOTE: this is the ROUTER-OWNED meta key, independent of colgrep's\n * internal xxh3 physical-dir key (we never need to predict colgrep's\n * key because we pass the workspace as colgrep's PATH arg and let it\n * route). A stable sha256-prefix of the canonical path is sufficient.\n */\nexport function metaHashForWorkspace(workspace: string): string {\n // ONE identity function for every surface (see `canonicalWorkspace`). This\n // previously resolved+folded WITHOUT realpath, so a workspace reached\n // through a symlink got a different sidecar key than the project-dir\n // lookup derived — two meta files, one physical index, and one of them\n // permanently reporting `absent`. That is the macOS `/var`→`/private/var`\n // shape, and it hits every temp workspace there.\n const canonical = canonicalWorkspace(workspace)\n // Cheap FNV-1a 32-bit → hex; collision risk negligible for the small\n // number of workspaces a single user touches, and the file content\n // also carries the full `workspace` path for disambiguation.\n let h = 0x811c9dc5\n for (let i = 0; i < canonical.length; i++) {\n h ^= canonical.charCodeAt(i)\n h = Math.imul(h, 0x01000193)\n }\n return (h >>> 0).toString(16).padStart(8, \"0\")\n}\n\nfunction metaPath(workspace: string): string {\n return path.join(PATHS.COLBERT_META_DIR, `${metaHashForWorkspace(workspace)}.json`)\n}\n\n/** Read the sidecar metadata for a workspace (null if none yet). */\n/**\n * Bump this when a router-side bug could have written a failure verdict that\n * was never the workspace's fault. A sidecar stamped with an older epoch gets\n * its watchdog-attributed streak cleared ONCE, then is stamped forward.\n *\n * Epoch 1: the fail-safe-probe fix. Before it, `indexDirSignature` could not\n * match colgrep's Windows extended-length `project_path`, so the inactivity\n * watchdog killed healthy builds and recorded `stuck` — which is refused\n * forever at a cap of 2. Those users are still capped after upgrading,\n * because the existing reset triggers on git/model/engine inputs and none of\n * those changed. This is the only thing that un-sticks them.\n * Epoch 2: widened to include `corrupt`, once it became clear the identity\n * bug MANUFACTURED corrupt verdicts (a null project-dir lookup was recorded\n * as corruption).\n *\n * Epoch 3: clearing the streak was not enough — `freshnessVerdict` returns\n * `failed` straight off `meta.status`, before it looks at the disk, so a\n * zeroed counter still short-circuited every query. The reset now drops the\n * status as well.\n *\n * Epoch 4: the shard-tiling validator false-positived on every\n * incrementally-updated index (`embedding_offset` is a write-cursor\n * artifact, never a read invariant — verified against next-plaid v1.7.0\n * source), manufacturing `corrupt` verdicts that quarantine+delete looped\n * deterministically into capped `failed`. Any stored `corrupt` streak may\n * be this bug, so it clears once like the rest.\n */\nconst WATCHDOG_EPOCH = 4\n\n/**\n * Failure classes the router-side bugs could have manufactured.\n *\n * `stuck`/`crashed` came from the blind watchdog. `corrupt` belongs here too,\n * which is not obvious: `repairCorruptIndex` recorded `failureClass:\"corrupt\"`\n * whenever `colbertProjectDir` returned null, and a null lookup is exactly\n * what the identity bug produced for a perfectly healthy index. So a stored\n * `corrupt` is not reliable evidence about the workspace — it may be evidence\n * about us. Observed on the machine where this was diagnosed: a `corrupt`\n * marker sitting next to an index that validates as coherent with 15 shards\n * and 1.24M embeddings.\n *\n * Clearing it is safe because it only resets the STREAK. The next query still\n * re-derives the verdict from the shards on disk, so an index that really is\n * corrupt is re-detected immediately and quarantined as before.\n *\n * `launch` stays excluded: a spawn failure (missing binary, unrunnable ORT)\n * is genuinely about the environment, and the existing engine-sha reset\n * already covers the case where an upgrade fixes it.\n */\nconst EPOCH_CLEARABLE = new Set([\"stuck\", \"crashed\", \"corrupt\"])\n\n/**\n * Clear a stale failure streak that a router-side bug produced.\n *\n * Bounded by construction: it fires only while the stored epoch is behind,\n * and the caller stamps the current epoch on the next write, so it is one\n * reset per epoch bump rather than a reset loop.\n */\nfunction applyWatchdogEpoch(meta: ColbertMeta): ColbertMeta {\n if ((meta.watchdogEpoch ?? 0) >= WATCHDOG_EPOCH) return meta\n const clearable =\n meta.status === \"failed\"\n && meta.failureClass !== undefined\n && EPOCH_CLEARABLE.has(meta.failureClass)\n if (!clearable) return { ...meta, watchdogEpoch: WATCHDOG_EPOCH }\n // Clear the STATUS too, not just the streak. `freshnessVerdict` returns\n // `failed` straight off `meta.status` before it ever looks at the disk, so\n // zeroing the counter alone leaves the workspace exactly as dead — the\n // marker still short-circuits every query. Dropping to `ready` makes the\n // next verdict re-derive from the shards on disk: a genuinely corrupt or\n // missing index is re-detected immediately and re-quarantined, and a\n // healthy one finally becomes visible again.\n return {\n ...meta,\n watchdogEpoch: WATCHDOG_EPOCH,\n status: \"ready\",\n failureClass: undefined,\n failedAttempts: 0,\n failedAt: undefined,\n }\n}\n\nexport async function readColbertMeta(\n workspace: string,\n): Promise<ColbertMeta | null> {\n try {\n const raw = await fs.readFile(metaPath(workspace), \"utf8\")\n const parsed = JSON.parse(raw) as ColbertMeta\n if (parsed && typeof parsed === \"object\" && typeof parsed.status === \"string\") {\n return applyWatchdogEpoch(parsed)\n }\n return null\n } catch {\n return null\n }\n}\n\n/**\n * Per-workspace write serializer. `runInit` issues a pre-spawn\n * `building` write, an `onSpawn` write that patches in the colgrep child\n * PID, and a final `ready`/`failed` write. Chaining them per workspace\n * guarantees the final write lands AFTER the (fire-and-forget) onSpawn\n * write, so a `ready` result is never clobbered back to `building` by a\n * late atomic-rename.\n */\nconst _metaWriteChains = new Map<string, Promise<void>>()\n\n/** Atomically write the sidecar metadata for a workspace (serialized). */\nexport async function writeColbertMeta(meta: ColbertMeta): Promise<void> {\n const key = metaHashForWorkspace(meta.workspace)\n const prev = _metaWriteChains.get(key) ?? Promise.resolve()\n const next = prev.then(() => writeColbertMetaUnchained(meta))\n // Swallow chain-internal errors so one failed write doesn't poison the\n // chain for subsequent callers; each call still sees its own rejection.\n const settled = next.then(\n () => undefined,\n () => undefined,\n )\n _metaWriteChains.set(key, settled)\n // Drop the entry once this write settles AND nothing newer took its place.\n // Without this the map grows one permanent entry per distinct workspace for\n // the life of the process — unbounded under `serve`, which handles many.\n // The identity check is what makes it safe: a newer chain for the same key\n // must not be evicted, or two writers would stop being serialized.\n // (Same pattern as `serializeWrite` in `~/lib/first-mate/durable-store`.)\n void settled.then(() => {\n if (_metaWriteChains.get(key) === settled) _metaWriteChains.delete(key)\n })\n return next\n}\n\nasync function writeColbertMetaUnchained(meta: ColbertMeta): Promise<void> {\n await fs.mkdir(PATHS.COLBERT_META_DIR, { recursive: true })\n const dest = metaPath(meta.workspace)\n // Stamp the current epoch on every write. Without this the read-side reset\n // would re-fire on each read (it would keep seeing a behind-epoch entry),\n // turning a one-shot recovery into an unbounded loop.\n const stamped: ColbertMeta = { ...meta, watchdogEpoch: WATCHDOG_EPOCH }\n const tmp = `${dest}.${process.pid}.${Math.random().toString(16).slice(2, 10)}.tmp`\n try {\n await fs.writeFile(tmp, JSON.stringify(stamped, null, 2))\n await fs.rename(tmp, dest)\n } catch (err) {\n await fs.rm(tmp, { force: true }).catch(() => {})\n throw err\n }\n}\n\n/**\n * Whether a COMPLETED colgrep index exists on disk for this workspace.\n * The preflight uses this to distinguish `building`/`absent` (no\n * completed index → don't spawn a foreground colgrep) from a real\n * index. We scan COLGREP_DATA_DIR for any per-project dir containing a\n * `project.json` whose canonical path matches this workspace AND an\n * `index/metadata.json` marker.\n */\nexport async function colbertProjectDir(workspace: string): Promise<string | null> {\n const indicesDir = PATHS.COLBERT_INDICES_DIR\n let names: Array<string>\n try {\n names = await fs.readdir(indicesDir)\n } catch {\n return null\n }\n const wantCanonical = await realpathForCompare(workspace)\n for (const name of names) {\n if (name === \".gh-router-meta\" || name.includes(\".corrupt-\")) continue\n const dir = path.join(indicesDir, name)\n let proj: { path?: string; project_path?: string; model?: string }\n try {\n proj = JSON.parse(await fs.readFile(path.join(dir, \"project.json\"), \"utf8\"))\n } catch {\n continue\n }\n const projPath = proj.path ?? proj.project_path\n if (!projPath || (await realpathForCompare(projPath)) !== wantCanonical) continue\n // The raw model spelling is part of colgrep's project key. Require the\n // exact proxy spelling so a slash-variant legacy key is never selected.\n if (proj.model !== canonicalColbertModelDir()) {\n continue\n }\n return dir\n }\n return null\n}\n\nexport type IndexIntegrity =\n | { verdict: \"not-built\" }\n | { verdict: \"coherent\"; shardCount: number; embeddingCount: number }\n | { verdict: \"suspect\"; reason: string }\n | { verdict: \"corrupt\"; reason: string }\n\n/**\n * Validate PLAID shard metadata readability — NOT tiling.\n *\n * Deliberately NOT a contiguity check: `embedding_offset` is a write-cursor\n * artifact for incremental appends, never a read invariant. Verified against\n * next-plaid v1.7.0 source: the sole read of `embedding_offset` anywhere\n * (next-plaid `update.rs`, append-to-last cursor) is on the WRITE path;\n * search reads the merged concatenation + SQLite doc mapping, neither of\n * which consults offsets. Incremental updates (and worktree-seed +\n * reconcile) legitimately leave non-tiling layouts — overlapping and\n * gapped intervals on a colgrep-healthy index (observed live: 23 shards,\n * search serving correctly, zero SQLite doc duplicates).\n *\n * The previous tiling check therefore false-positived on every\n * incrementally-updated index, and the quarantine+delete+rebuild response\n * re-seeded into the identical layout deterministically — a self-\n * perpetuating failure loop ending in capped `failed`. Corrupt is now\n * reserved for genuinely unreadable stores (which colgrep itself cannot\n * load either).\n */\nexport function validateIndexIntegrity(projectIndexDir: string): IndexIntegrity {\n let names: Array<string>\n try {\n names = readdirSync(projectIndexDir).filter((name) => /^\\d+\\.metadata\\.json$/.test(name))\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === \"ENOENT\"\n ? { verdict: \"not-built\" }\n : { verdict: \"corrupt\", reason: \"index directory unreadable\" }\n }\n if (names.length === 0) return { verdict: \"not-built\" }\n\n let sum = 0\n for (const name of names) {\n try {\n const parsed = JSON.parse(readFileSync(path.join(projectIndexDir, name), \"utf8\")) as {\n embedding_offset?: unknown\n num_embeddings?: unknown\n }\n const start = parsed.embedding_offset\n const count = parsed.num_embeddings\n if (\n typeof start !== \"number\" ||\n typeof count !== \"number\" ||\n !Number.isSafeInteger(start) ||\n !Number.isSafeInteger(count) ||\n start < 0 ||\n count < 0\n ) {\n return { verdict: \"corrupt\", reason: `invalid shard metadata: ${name}` }\n }\n sum += count\n } catch {\n return { verdict: \"corrupt\", reason: `unreadable shard metadata: ${name}` }\n }\n }\n\n return { verdict: \"coherent\", shardCount: names.length, embeddingCount: sum }\n}\n\nexport async function completedIndexOnDisk(workspace: string): Promise<boolean> {\n const projectDir = await colbertProjectDir(workspace)\n if (!projectDir) return false\n return validateIndexIntegrity(path.join(projectDir, \"index\")).verdict !== \"not-built\"\n}\n\n/**\n * Strip a Windows extended-length prefix.\n *\n * `\\\\?\\Q:\\dir` → `Q:\\dir`, and `\\\\?\\UNC\\server\\share` → `\\\\server\\share`\n * (naively slicing 4 there would yield the relative `UNC\\server\\share`).\n * colgrep stores `project_path` in this form — 50 of 53 dirs on the machine\n * where this was diagnosed — so every comparison against its `project.json`\n * has to account for it.\n */\nfunction stripExtendedPrefix(p: string): string {\n if (p.startsWith(\"\\\\\\\\?\\\\UNC\\\\\")) return `\\\\\\\\${p.slice(8)}`\n if (p.startsWith(\"\\\\\\\\?\\\\\")) return p.slice(4)\n return p\n}\n\n/**\n * Is the volume holding `p` case-insensitive?\n *\n * Probed at runtime rather than inferred from `process.platform`, because\n * the platform is wrong in both directions: APFS can be formatted\n * case-SENSITIVE (folding there merges two genuinely distinct workspaces),\n * and Linux routinely mounts case-INSENSITIVE volumes such as exfat/NTFS\n * (not folding there splits one workspace into two identities).\n *\n * Cheap and memoized per filesystem root: stat the path back through a\n * case-flipped spelling of its own basename. Falls back to the platform\n * default only when the probe itself cannot run.\n */\nconst _caseInsensitiveByRoot = new Map<string, boolean>()\n\nfunction volumeIsCaseInsensitive(p: string): boolean {\n const root = path.parse(path.resolve(p)).root || path.sep\n const cached = _caseInsensitiveByRoot.get(root)\n if (cached !== undefined) return cached\n\n const platformDefault =\n process.platform === \"win32\" || process.platform === \"darwin\"\n let result = platformDefault\n try {\n // Walk up to the nearest existing ancestor so a not-yet-created\n // workspace still probes its real volume.\n let probe = path.resolve(p)\n for (let i = 0; i < 64 && !existsSync(probe); i++) {\n const parent = path.dirname(probe)\n if (parent === probe) break\n probe = parent\n }\n const base = path.basename(probe)\n if (base && /[a-z]/i.test(base)) {\n const flipped =\n base === base.toLowerCase() ? base.toUpperCase() : base.toLowerCase()\n const sibling = path.join(path.dirname(probe), flipped)\n result = existsSync(sibling)\n }\n } catch {\n // Keep the platform default.\n }\n _caseInsensitiveByRoot.set(root, result)\n return result\n}\n\n/** Test-only: clear the memoized per-volume case-sensitivity probe. */\nexport function __resetCaseProbeForTests(): void {\n _caseInsensitiveByRoot.clear()\n}\n\n/**\n * THE canonical identity for a workspace. Every surface that answers \"is this\n * the same workspace?\" — the meta sidecar key, the colgrep project-dir lookup,\n * the watchdog signature, the init/search locks, and the argument handed to\n * colgrep — must go through this and nothing else.\n *\n * They previously disagreed four different ways, and the disagreement is what\n * made a healthy index invisible: colgrep writes `\\\\?\\Q:\\...`, the lookup\n * normalized it to `//?/q:/...`, and nothing ever matched.\n *\n * Order matters: realpath FIRST (it resolves symlinks — the macOS\n * `/var`→`/private/var` and `/tmp`→`/private/tmp` shapes — expands 8.3 short\n * names, and returns the true on-disk casing), THEN strip any extended-length\n * prefix from the *result*. `realpathSync.native` was measured to already\n * return a clean `Q:\\Software\\github-router` for all input spellings, so the\n * strip is belt-and-braces rather than load-bearing; it costs nothing and\n * covers the fallback path where realpath could not run at all.\n */\nexport function canonicalWorkspace(p: string): string {\n let out = stripExtendedPrefix(p)\n try {\n // `.native` (GetFinalPathNameByHandleW / realpath(3)) — NOT the JS\n // variant, which leaves the `\\\\?\\` prefix intact, does not expand 8.3\n // names, and preserves caller casing instead of the on-disk truth.\n out = stripExtendedPrefix(realpathSync.native(out))\n } catch {\n // The leaf is not on disk (a workspace about to be created, deleted, or\n // on an unmounted volume). Resolving the NEAREST EXISTING ANCESTOR and\n // re-appending the remainder keeps the key STABLE across that boundary.\n //\n // Falling back to the raw path instead would make a workspace's identity\n // change the moment it disappears: under a symlinked parent — which is\n // every temp workspace on macOS, where `/var` → `/private/var` — the live\n // key resolves through the link and the post-deletion key does not. The\n // sidecar written while it existed then becomes unfindable, so the boot\n // sweep cannot reap it and a re-created workspace starts from a different\n // key than its own index. Caught by macOS CI on the first run.\n out = resolveThroughExistingAncestor(out)\n }\n out = path.resolve(out)\n if (volumeIsCaseInsensitive(out)) out = out.toLowerCase()\n // Separator-normalize so `Q:\\x` and `Q:/x` are one key. Harmless on POSIX,\n // where backslash is a legal filename character but `path.resolve` has\n // already produced forward slashes.\n return process.platform === \"win32\" ? out.replaceAll(\"\\\\\", \"/\") : out\n}\n\n/**\n * Realpath as much of `p` as exists, then re-append the missing tail. Keeps a\n * not-yet-created or just-deleted path on the same canonical root as its live\n * self.\n */\nfunction resolveThroughExistingAncestor(p: string): string {\n const abs = path.resolve(p)\n const tail: Array<string> = []\n let cur = abs\n for (let i = 0; i < 64; i++) {\n try {\n const real = stripExtendedPrefix(realpathSync.native(cur))\n return tail.length > 0 ? path.join(real, ...tail.reverse()) : real\n } catch {\n const parent = path.dirname(cur)\n if (parent === cur) break // hit the root without finding anything\n tail.push(path.basename(cur))\n cur = parent\n }\n }\n return abs\n}\n\nfunction canonicalForCompare(p: string): string {\n return canonicalWorkspace(p)\n}\n\n/** Sync realpath-aware canonicalization. Retained as a named alias so call\n * sites read intentionally; `canonicalWorkspace` already realpaths. */\nfunction canonicalRealpathSync(p: string): string {\n return canonicalWorkspace(p)\n}\n\n/** Recursive (bytes, fileCount) of a directory; sync + best-effort. A\n * colgrep index is a bounded set of shards so the walk stays small. */\nfunction dirSizeSync(dir: string): [number, number] {\n let bytes = 0\n let count = 0\n let entries: Array<import(\"node:fs\").Dirent>\n try {\n entries = readdirSync(dir, { withFileTypes: true })\n } catch {\n return [0, 0]\n }\n for (const e of entries) {\n const p = path.join(dir, e.name)\n if (e.isDirectory()) {\n const [b, c] = dirSizeSync(p)\n bytes += b\n count += c\n } else {\n try {\n bytes += statSync(p).size\n count += 1\n } catch {\n // vanished mid-walk — skip\n }\n }\n }\n return [bytes, count]\n}\n\n/**\n * (sync) Progress signature of a workspace's colgrep index dir for the init\n * inactivity watchdog: `${totalBytes}:${fileCount}` of the project dir, or\n * `null` if it isn't on disk yet. colgrep is SILENT on a non-TTY pipe\n * during the (potentially multi-hour) encode phase, so output is useless as\n * a progress signal — but it writes index shards incrementally, so a\n * changing signature means \"still progressing\" and a frozen one means\n * \"hung\". Successive signatures drive the watchdog: change ⇒ re-arm, frozen\n * ⇒ kill. Sync because it's called from a `setTimeout` (not awaited).\n */\n/**\n * Result of one progress probe.\n *\n * Three states, not `string | null`. Collapsing them was the fault boundary:\n * `null` meant \"no index yet\" AND \"could not match the dir\" AND \"readdir\n * failed\", and the watchdog read all of them as *no progress* — so a path\n * mismatch (which was permanent on Windows) killed healthy, actively-writing\n * builds and capped the workspace forever. UNKNOWN must never be evidence of\n * a stall; only an OBSERVED signature that stops changing is.\n */\nexport type IndexProgress =\n | { kind: \"observed\"; signature: string }\n | { kind: \"not-created\" }\n | { kind: \"unknown\" }\n\nexport function indexDirSignature(workspace: string): IndexProgress {\n const indicesDir = PATHS.COLBERT_INDICES_DIR\n let names: Array<string>\n try {\n names = readdirSync(indicesDir)\n } catch {\n // The store itself is unreadable — we cannot tell, so say so.\n return { kind: \"unknown\" }\n }\n const want = canonicalRealpathSync(workspace)\n for (const name of names) {\n if (name === \".gh-router-meta\") continue\n // Skip quarantined husks. A `.corrupt-*` dir keeps the original\n // `project.json`, so it still matches this workspace — and its size is\n // frozen. If this probe returned the husk's signature instead of the\n // live build's, the inactivity watchdog would see no growth, judge a\n // healthy rebuild stalled, and kill it — turning a one-off repair into\n // a rebuild death loop. `colbertProjectDir` already skips these; this\n // probe must agree.\n if (name.includes(\".corrupt-\")) continue\n const dir = path.join(indicesDir, name)\n let proj: { path?: string; project_path?: string; model?: string }\n try {\n proj = JSON.parse(readFileSync(path.join(dir, \"project.json\"), \"utf8\"))\n } catch {\n continue\n }\n const projPath = proj.path ?? proj.project_path\n if (!projPath || canonicalRealpathSync(projPath) !== want) continue\n // Same model check as `colbertProjectDir`. Without it the two lookups\n // disagree on a FORKED dir — one written for this workspace under a\n // different `--model` spelling, which colgrep keys separately. The probe\n // would then size a directory the router will never serve, and a fork is\n // frozen (nothing writes to it), so the watchdog would read \"no growth\"\n // during a perfectly healthy build of the canonical index and kill it.\n // That is the exact failure the fail-safe probe exists to prevent,\n // reachable again through the one comparison that was not unified.\n // Observed live: signature `observed` while `colbertProjectDir` returned\n // null, because only the forked dir survived on disk.\n if (proj.model !== canonicalColbertModelDir()) continue\n const [bytes, count] = dirSizeSync(dir)\n return { kind: \"observed\", signature: `${bytes}:${count}` }\n }\n // Scanned the store cleanly and this workspace has no project dir: colgrep\n // has not created one yet. Distinct from `unknown` — a build that has not\n // started writing is normal, and must not be mistaken for a hang.\n return { kind: \"not-created\" }\n}\n\n/**\n * Realpath-aware canonicalization for matching a workspace against\n * colgrep's stored `project_path`. colgrep stores the OS realpath (e.g.\n * macOS `/tmp` → `/private/tmp`, Windows 8.3 short names), so a plain\n * `path.resolve` comparison misses. Falls back to `canonicalForCompare`\n * when realpath fails (path doesn't exist yet).\n */\nasync function realpathForCompare(p: string): Promise<string> {\n // `canonicalWorkspace` is sync but cheap (one realpath + string work), and\n // sharing ONE implementation is the whole point: the async and sync sides\n // disagreeing is what made a healthy index invisible.\n return canonicalWorkspace(p)\n}\n\n/**\n * Compute the freshness verdict for a query against a workspace.\n *\n * Routing (per the dropped-fallback contract):\n * - `failed` — sidecar says failed → caller returns isError.\n * - `building` — a tracked init is live OR no completed index on disk\n * → caller returns building notice (NO results).\n * - `absent` — never indexed → caller kicks a debounced background\n * init, returns absent (isError).\n * - `stale` — ready but HEAD moved / tree dirty since index → caller\n * returns stale notice (NO results, NO re-search).\n * - `fresh` — ready + completed index + HEAD matches + not newly\n * dirty → caller spawns colgrep search.\n */\n/**\n * Why a `stale` verdict lags the index. `content` = the tree moved\n * (HEAD/dirty) while the embedding bits are unchanged — servable with a\n * label when the delta is small. `engine` = the binary/runtime/model bits\n * changed — the embedding space may differ, never servable without a\n * rebuild. `suspect` = shards look structurally odd — never servable.\n */\nexport type StaleKind = \"content\" | \"engine\" | \"suspect\"\n\nexport interface FreshnessResult {\n verdict: Freshness\n meta: ColbertMeta | null\n head?: string\n dirty?: boolean\n /** Present on verdict:\"stale\": why the index lags. */\n staleKind?: StaleKind\n /** Files changed since the index (content-stale only, capped). */\n staleFiles?: Array<string>\n /** True when more files changed than listed. */\n staleTruncated?: boolean\n}\n\n/**\n * Max stale files still servable with a label (serve-while-stale). An LLM\n * editing session typically dirties a handful of files per turn; beyond\n * this the index is too far behind to label honestly and the query falls\n * back to lexical. Override with `GH_ROUTER_SERVE_STALE_MAX_FILES`.\n */\nexport function serveStaleMaxFiles(): number {\n const raw = Number(process.env.GH_ROUTER_SERVE_STALE_MAX_FILES)\n if (Number.isSafeInteger(raw) && raw > 0) return raw\n return 200\n}\n\n/** Cap on delta enumeration (beyond → staleTruncated). */\nconst DELTA_ENUM_CAP = 1000\n\n/**\n * True when semantic results may be served for this verdict: fresh, or\n * stale-by-content with a small, fully-enumerated delta. Engine/suspect\n * stale, failed/crashed/corrupt/building/absent are never servable.\n */\nexport function isServableVerdict(v: FreshnessResult): boolean {\n if (v.verdict === \"fresh\") return true\n if (v.verdict !== \"stale\") return false\n if (v.staleKind !== \"content\") return false\n if (v.staleTruncated) return false\n return (v.staleFiles?.length ?? Number.POSITIVE_INFINITY) <= serveStaleMaxFiles()\n}\n\nexport async function freshnessVerdict(workspace: string): Promise<FreshnessResult> {\n const meta = await readColbertMeta(workspace)\n if (!meta || meta.status === \"absent\") {\n return { verdict: \"absent\", meta }\n }\n if (meta.status === \"failed\") {\n return { verdict: \"failed\", meta }\n }\n if (meta.status === \"building\") {\n // A build is only genuinely \"building\" if THIS proxy has an init in\n // flight for it (covers the brief window between the pre-spawn `building`\n // write and the onSpawn pid write) OR the recorded build PID is alive.\n // Mirror the boot sweep's liveness check per-query so a MID-SESSION crash\n // (proxy-killed / OOM build) is caught on the next query, not only at\n // the next boot. NEVER kill here — a live PID may be a recycled\n // unrelated process; we only reclassify (same discipline as the sweep).\n const pid = typeof meta.buildPid === \"number\" ? meta.buildPid : 0\n if (isInitInFlight(workspace) || (pid > 0 && isPidAlive(pid))) {\n return { verdict: \"building\", meta }\n }\n // No live PID and not in flight in THIS proxy. Another proxy may have\n // just written `building` and not yet recorded the colgrep child PID\n // (cross-process spawn window) — grant a short grace based on the\n // build-start (`lastIndexedAt`) before declaring it crashed.\n const startedMs = meta.lastIndexedAt ? Date.parse(meta.lastIndexedAt) : NaN\n if (\n Number.isFinite(startedMs) &&\n Date.now() - startedMs < BUILD_SPAWN_GRACE_MS\n ) {\n return { verdict: \"building\", meta }\n }\n // Dead/unknown build PID. If a completed index landed on disk, the\n // build finished but the ready-write was lost (crash between done +\n // write) → fall through to the normal ready/git-freshness path below.\n // Otherwise it crashed mid-build with no usable index.\n if (!(await completedIndexOnDisk(workspace))) {\n return { verdict: \"crashed\", meta }\n }\n }\n // status === \"ready\". Confirm a completed index is actually on disk;\n // a meta marker without an index (crash between mark-ready and write)\n // must NOT be served as fresh.\n const projectDir = await colbertProjectDir(workspace)\n if (!projectDir) return { verdict: \"building\", meta }\n const integrity = validateIndexIntegrity(path.join(projectDir, \"index\"))\n if (integrity.verdict === \"not-built\") return { verdict: \"building\", meta }\n if (integrity.verdict === \"corrupt\") return { verdict: \"corrupt\", meta }\n // Suspect: structurally odd but not provably corrupt. Refuse to serve\n // semantic results, but take the NON-destructive route — `stale` keeps the\n // bytes on disk and rebuilds in the background, so if the layout turns out\n // to be legal we have lost nothing but a rebuild.\n if (integrity.verdict === \"suspect\") {\n return { verdict: \"stale\", meta, staleKind: \"suspect\" as const }\n }\n\n // Engine changes require a clean rebuild; an index generated by different\n // binary/runtime bits is not safe to label semantic-ready. This is STALE,\n // not corrupt: the shards are structurally coherent, just built by other\n // bits. `corrupt` would quarantine and DELETE them, which on the first\n // query after any upgrade would destroy a perfectly good index — and a\n // legacy meta predating these fields has `undefined` here, so every\n // existing user would hit it exactly once, at upgrade. `stale` keeps the\n // old index searchable while a background rebuild runs.\n const binarySha = colgrepBinAsset()?.sha256\n const ortSha = ortLibAsset()?.sha256\n if (\n (binarySha && meta.binarySha !== binarySha) ||\n (ortSha && meta.ortSha !== ortSha)\n ) {\n return { verdict: \"stale\", meta, staleKind: \"engine\" as const }\n }\n // Git freshness. Non-git workspace → no head; treat ready as fresh\n // (mtime is colgrep's own incremental signal).\n const git = await gitState(workspace)\n if (!git.isRepo) {\n return { verdict: \"fresh\", meta }\n }\n const headMoved =\n meta.lastIndexedHead !== undefined && git.head !== meta.lastIndexedHead\n // Dirtier than at index time: the working tree is dirty now but the\n // index was taken on a clean tree (or we have no record). A tree that\n // was already dirty at index time and is still dirty is not newly\n // stale by this check alone (colgrep's incremental updater covers the\n // delta), but a clean→dirty transition since indexing IS stale.\n const newlyDirty = git.dirty && meta.lastIndexedDirty !== true\n if (headMoved || newlyDirty) {\n // Content-stale: the embedding bits are unchanged, only the tree moved.\n // Enumerate the delta so callers can serve-while-stale when it is small\n // (an LLM editing session typically dirties a handful of files).\n const delta = await gitDeltaFiles(\n workspace,\n headMoved ? meta.lastIndexedHead : undefined,\n headMoved ? git.head : undefined,\n )\n return {\n verdict: \"stale\",\n meta,\n head: git.head,\n dirty: git.dirty,\n staleKind: \"content\" as const,\n staleFiles: delta.files,\n staleTruncated: delta.truncated,\n }\n }\n return { verdict: \"fresh\", meta, head: git.head, dirty: git.dirty }\n}\n\n/**\n * Files changed since the index: `git diff --name-only` between the indexed\n * and current HEAD (when the head moved) UNION the working-tree porcelain\n * set. Capped at DELTA_ENUM_CAP (beyond → truncated). Fail-closed: any git\n * failure yields truncated (unprovably-small), so servability refuses.\n *\n * Exported for the service backend, which computes its own servability\n * against its own sidecar (it must NOT reuse `freshnessVerdict` — that\n * verdict describes the colgrep sidecar's state, not the service index's).\n */\nexport async function gitDeltaFiles(\n workspace: string,\n baseHead: string | undefined,\n currentHead: string | undefined,\n): Promise<{ files: Array<string>; truncated: boolean }> {\n const files = new Set<string>()\n let truncated = false\n if (baseHead && currentHead && baseHead !== currentHead) {\n const diff = await gitNameOnly(workspace, baseHead, currentHead)\n for (const f of diff.files) files.add(f)\n truncated = truncated || diff.truncated\n if (files.size >= DELTA_ENUM_CAP) {\n return { files: [...files].slice(0, DELTA_ENUM_CAP), truncated: true }\n }\n }\n const porcelain = await gitPorcelainFiles(workspace)\n for (const f of porcelain.files) {\n if (files.size >= DELTA_ENUM_CAP) {\n truncated = true\n break\n }\n files.add(f)\n }\n truncated = truncated || porcelain.truncated\n return { files: [...files], truncated }\n}\n\n/** `git status --porcelain=v1` paths (rename target for `R old -> new`). */\nasync function gitPorcelainFiles(\n workspace: string,\n): Promise<{ files: Array<string>; truncated: boolean }> {\n const git = resolveExecutable(\"git\")\n if (!git) return { files: [], truncated: true }\n try {\n const res = await runManagedExeCapture(\n git,\n [\"-C\", workspace, \"status\", \"--porcelain=v1\", \"--untracked-files=normal\"],\n { timeoutMs: GIT_TIMEOUT_MS, maxStdoutBytes: 1024 * 1024 },\n )\n if (res.code !== 0) return { files: [], truncated: true }\n const files: Array<string> = []\n let truncated = res.stdoutTruncated\n for (const line of res.stdout.split(\"\\n\")) {\n if (files.length >= DELTA_ENUM_CAP) {\n truncated = true\n break\n }\n if (line.length < 4) continue\n const rest = line.slice(3)\n // Rename/copy entries report `old -> new`; the index keys the new path.\n const arrow = rest.indexOf(\" -> \")\n const rel = arrow >= 0 ? rest.slice(arrow + 4) : rest\n // Quoted paths (spaces/specials) arrive `\"...\"`-wrapped; unquote the\n // common case rather than mis-keying the file.\n const unquoted =\n rel.startsWith('\"') && rel.endsWith('\"') && rel.length >= 2\n ? rel.slice(1, -1)\n : rel\n if (unquoted.length > 0) files.push(unquoted)\n }\n return { files, truncated }\n } catch {\n return { files: [], truncated: true }\n }\n}\n\n/** `git diff --name-only <from> <to>`, capped. */\nasync function gitNameOnly(\n workspace: string,\n fromHead: string,\n toHead: string,\n): Promise<{ files: Array<string>; truncated: boolean }> {\n const git = resolveExecutable(\"git\")\n if (!git) return { files: [], truncated: true }\n try {\n // --no-renames: renames report as delete+add, both keyed correctly for\n // a content delta (the old path's units are stale, the new path's are\n // missing — exactly what the label must convey).\n const res = await runManagedExeCapture(\n git,\n [\"-C\", workspace, \"diff\", \"--name-only\", \"--no-renames\", fromHead, toHead],\n { timeoutMs: GIT_TIMEOUT_MS, maxStdoutBytes: 1024 * 1024 },\n )\n if (res.code !== 0) return { files: [], truncated: true }\n const files: Array<string> = []\n let truncated = res.stdoutTruncated\n for (const line of res.stdout.split(\"\\n\")) {\n const rel = line.trim()\n if (rel.length === 0) continue\n if (files.length >= DELTA_ENUM_CAP) {\n truncated = true\n break\n }\n files.push(rel)\n }\n return { files, truncated }\n } catch {\n return { files: [], truncated: true }\n }\n}\n\n/** Cheap, bounded git probe via the native-exe runner. */\nexport async function gitState(\n workspace: string,\n): Promise<{ isRepo: boolean; head?: string; dirty?: boolean }> {\n const git = resolveExecutable(\"git\")\n if (!git) return { isRepo: false }\n try {\n const inside = await runManagedExeCapture(\n git,\n [\"-C\", workspace, \"rev-parse\", \"--is-inside-work-tree\"],\n { timeoutMs: GIT_TIMEOUT_MS, maxStdoutBytes: 64 * 1024 },\n )\n if (inside.code !== 0 || inside.stdout.trim() !== \"true\") {\n return { isRepo: false }\n }\n const head = await runManagedExeCapture(\n git,\n [\"-C\", workspace, \"rev-parse\", \"HEAD\"],\n { timeoutMs: GIT_TIMEOUT_MS, maxStdoutBytes: 64 * 1024 },\n )\n const status = await runManagedExeCapture(\n git,\n [\"-C\", workspace, \"status\", \"--porcelain\"],\n { timeoutMs: GIT_TIMEOUT_MS, maxStdoutBytes: 1024 * 1024 },\n )\n return {\n isRepo: true,\n head: head.code === 0 ? head.stdout.trim() || undefined : undefined,\n dirty: status.code === 0 ? status.stdout.trim().length > 0 : undefined,\n }\n } catch {\n return { isRepo: false }\n }\n}\n\n// ---------------------------------------------------------------------\n// Background-init debounce (per workspace+model)\n// ---------------------------------------------------------------------\n\nconst _initInFlight = new Set<string>()\n\n/** True iff a background init for this workspace is already in flight. */\nexport function isInitInFlight(workspace: string): boolean {\n return _initInFlight.has(initKey(workspace))\n}\n\n/** Mark a background init started (debounce). Returns false if already running. */\nexport function tryClaimInit(workspace: string): boolean {\n const k = initKey(workspace)\n if (_initInFlight.has(k)) return false\n _initInFlight.add(k)\n return true\n}\n\n/** Release the debounce claim (call in the init's finally). */\nexport function releaseInit(workspace: string): void {\n _initInFlight.delete(initKey(workspace))\n}\n\nfunction initKey(workspace: string): string {\n return `${MODEL_ID}::${canonicalForCompare(workspace)}`\n}\n\n/** Test-only: clear the in-flight debounce set. */\nexport function __resetInitDebounceForTests(): void {\n _initInFlight.clear()\n}\n","/**\n * ColBERT sidecar runner: spawn `colgrep search` / `colgrep init` with\n * the isolating env + flags, parse `--json`, trim to the minimal MCP\n * shape, and drive the per-query freshness preflight.\n *\n * Contract (per the coordinator's directive — supersedes the design's\n * lexical-fallback sections): `semantic_search` NEVER runs another\n * search. It returns honest `status` + `notice` and stops:\n * - ready → semantic results, status:\"ready\", source:\"semantic\"\n * - building → status:\"building\" + notice, NO results, NOT isError\n * - stale → status:\"stale\" + notice, NO results, NOT isError\n * - absent → kick a debounced background init, isError \"unavailable\"\n * - failed → isError \"unavailable\" + class\n * Input-shape failures (missing/relative workspace, empty query) → isError.\n *\n * Output handling: colgrep `--json` carries the full source + 5 analysis\n * layers per hit, so we cap the child stdout buffer hard, trim to 6\n * fields, and NEVER log raw stdout/stderr (it embeds source code — a\n * telemetry-leak vector).\n */\n\nimport { randomBytes } from \"node:crypto\"\nimport { existsSync, realpathSync } from \"node:fs\"\nimport fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport consola from \"consola\"\n\nimport { runManagedExeCapture } from \"../exec\"\n\nimport {\n colbertProjectDir,\n completedIndexOnDisk,\n freshnessVerdict,\n gitState,\n indexDirSignature,\n isInitInFlight,\n isServableVerdict,\n readColbertMeta,\n releaseInit,\n tryClaimInit,\n validateIndexIntegrity,\n writeColbertMeta,\n type ColbertMeta,\n} from \"./index-store\"\nimport { getColbertInstanceUuid, trackChild } from \"./lifecycle\"\nimport {\n colgrepBinAsset,\n MODEL_ID,\n MODEL_REVISION,\n ortLibAsset,\n} from \"./manifest\"\nimport {\n canonicalColbertModelDir,\n colbertOrtDylibPath,\n colgrepBinaryPath,\n dropColgrepSecrets,\n} from \"./provision\"\nimport { PATHS } from \"../paths\"\n\n/** Caller responsiveness budget for a search. A warm search is sub-second;\n * if colgrep instead starts a foreground auto-index / reconcile (its index is\n * behind) and hasn't returned results by this point, the search DETACHES —\n * the caller gets a `building` fallback now and the colgrep child finishes\n * the index in the background (never killed mid-write — that would orphan\n * docs and desync the index). The next query is then fast. */\nconst SEARCH_RESPOND_MS = envIntMs(\n \"GH_ROUTER_COLBERT_SEARCH_RESPOND_MS\",\n 20_000,\n)\n/** Inactivity (stall) watchdog for the background init: if the colgrep\n * index dir stops growing for this long, the build is hung → kill it. This\n * is the PRIMARY \"stuck vs slow\" signal — a build that keeps writing shards\n * runs as long as it needs (a 50GB repo can take hours), only a genuinely\n * hung build is killed. colgrep is silent on a non-TTY pipe during the\n * encode, so disk growth (not output) is the progress signal. */\nconst INIT_STALL_MS = envIntMs(\"GH_ROUTER_COLBERT_INIT_STALL_MS\", 5 * 60 * 1000)\n/** Absolute backstop on the background init — a generous ceiling so a truly\n * runaway process can't live forever, NOT the primary mechanism (the stall\n * watchdog is). Raised well above the old 30-min cap so a legitimately huge\n * repo isn't cut off mid-progress. */\nconst INIT_TIMEOUT_MS = envIntMs(\n \"GH_ROUTER_COLBERT_INIT_TIMEOUT_MS\",\n 6 * 60 * 60 * 1000,\n)\n/** After a failed build, don't re-kick a fresh one until this long has\n * elapsed (throttles a fast-failing init; the per-workspace debounce +\n * attempt cap are the other two guards). */\nconst FAILED_RETRY_BACKOFF_MS = 5 * 60 * 1000\n/** Consecutive failed-build attempts before the self-heal gives up and the\n * notice goes operator-actionable. Reset to 0 on a successful build. */\nconst MAX_FAILED_ATTEMPTS = 3\n/** Reuse code-search's stdout cap (10 MiB) for the full-CodeUnit payload. */\nconst MAX_STDOUT_BYTES = 10 * 1024 * 1024\nconst DEFAULT_LIMIT = 15\n\n/** Parse a positive-integer-milliseconds env override, else the default. */\nfunction envIntMs(name: string, fallback: number): number {\n const raw = process.env[name]\n if (raw === undefined) return fallback\n const n = Number(raw)\n return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback\n}\n\n/**\n * A progress probe for the inactivity watchdog: returns `false` (→ kill)\n * only when colgrep's index dir for `workspace` has stopped growing. colgrep\n * is SILENT on a non-TTY pipe during the encode, so disk growth — not output\n * — is the progress signal. `null` (dir not found yet) gets one window of\n * grace, then counts as no-progress (a build/search hung before it ever\n * wrote anything). Shared by BOTH the background init and the foreground\n * search so neither colgrep child is killed mid-write (which orphans docs).\n */\nexport function makeIndexProgressProbe(workspace: string): () => boolean {\n let lastSig: string | undefined\n return () => {\n const p = indexDirSignature(workspace)\n // FAIL-SAFE. Only a signature we actually OBSERVED, twice, unchanged, is\n // evidence of a hang. `unknown` (store unreadable, probe errored) and\n // `not-created` (colgrep has not written a dir yet) are the absence of\n // evidence, and the absence of evidence must never kill a build.\n //\n // The previous version returned `string | null` and treated the second\n // consecutive `null` as no-progress. On Windows the path comparison could\n // never match colgrep's extended-length `project_path`, so the probe\n // returned null on EVERY tick — the watchdog killed healthy,\n // actively-writing builds, classified them `stuck`, and `stuck` is\n // refused forever at a cap of 2. That is the whole outage, and it was\n // reachable from any cause of null, not just the path bug.\n //\n // The absolute `INIT_TIMEOUT_MS` backstop (6h) remains the runaway guard,\n // so a genuinely wedged build that never writes anything still dies.\n if (p.kind !== \"observed\") return true\n const prev = lastSig\n lastSig = p.signature\n // First concrete observation starts the clock — nothing to compare yet.\n if (prev === undefined) return true\n return p.signature !== prev // progressing iff the signature changed\n }\n}\n\n/** Workspaces with a DETACHED indexing search in flight. A new search for\n * such a workspace returns `building` instead of spawning a concurrent\n * colgrep that could collide on the index write — serving the same \"one\n * colgrep writer per workspace\" goal as the init debounce. Cleared when the\n * detached search completes. */\nconst _searchIndexInFlight = new Set<string>()\nconst _initPromises = new Map<string, Promise<void>>()\n/** In-flight quarantine deletions, drained by teardown (Windows EBUSY). */\nconst _quarantineRemovals = new Set<Promise<void>>()\nlet _runManagedExeCapture = runManagedExeCapture\n\n/** Test-only: clear the detached-search in-flight set. */\nexport function __resetSearchInFlightForTests(): void {\n _searchIndexInFlight.clear()\n}\n\n/** Test-only: replace the managed executable runner and observe background init. */\nexport function __setInitRunnerForTests(\n runner: typeof runManagedExeCapture | undefined,\n): void {\n _runManagedExeCapture = runner ?? runManagedExeCapture\n}\n\n/**\n * Await the currently tracked background init for a workspace, if any.\n * Resolves immediately when this process tracks no init (e.g. another\n * proxy owns the build) — callers poll `freshnessVerdict` for progress\n * in that case. Used by the foreground `github-router index` command and\n * by tests (via the alias below).\n */\nexport async function waitForInit(workspace: string): Promise<void> {\n await _initPromises.get(path.resolve(workspace))\n}\n\n/** Test-only: await the currently tracked background init, if any. */\nexport async function __waitForInitForTests(workspace: string): Promise<void> {\n await waitForInit(workspace)\n}\n\n/** Test-only: drain all background init work before removing fixtures. */\nexport async function __waitForAllInitsForTests(): Promise<void> {\n await Promise.all(_initPromises.values())\n await Promise.all(_quarantineRemovals)\n}\n\nexport type SemanticStatus =\n | \"ready\"\n | \"building\"\n | \"stale\"\n | \"unavailable\"\n | \"failed\"\n\nexport interface SemanticResultRow {\n file: string\n line: number\n endLine?: number\n name?: string\n score: number\n snippet: string\n}\n\nexport interface SemanticSearchResult {\n status: SemanticStatus\n results?: Array<SemanticResultRow>\n source?: \"semantic\"\n notice?: string\n /** Set when the outcome is an MCP error envelope (unavailable/failed). */\n isError?: boolean\n /**\n * Freshness of served results (serve-while-stale). `\"fresh\"` = index\n * matches HEAD/tree; `\"stale\"` = served from an index predating a small\n * content delta (see `stale_files`). Absent on non-ready outcomes.\n */\n freshness?: \"fresh\" | \"stale\"\n /** Files changed since the index (present iff freshness is \"stale\"). */\n stale_files?: number\n}\n\n/** colgrep `--json` element shape (only the fields we read). */\ninterface ColgrepHit {\n unit?: {\n name?: string\n file?: string\n line?: number\n end_line?: number\n signature?: string\n code?: string\n docstring?: string | null\n }\n score?: number\n}\n\n/** Build the isolating env for any colgrep child (search or init). */\nfunction colgrepEnv(): NodeJS.ProcessEnv {\n const ortDir = path.dirname(colbertOrtDylibPath())\n return dropColgrepSecrets({\n ...process.env,\n COLGREP_DATA_DIR: PATHS.COLBERT_INDICES_DIR,\n ORT_DYLIB_PATH: colbertOrtDylibPath(),\n COLGREP_FORCE_CPU: \"1\",\n // Co-locate the ORT dir on PATH so Windows resolves dependent DLLs.\n PATH: `${ortDir}${path.delimiter}${process.env.PATH ?? \"\"}`,\n })\n}\n\n/**\n * The high-level entry the MCP handler calls. Runs the deterministic\n * router-side preflight (freshness verdict from on-disk markers + git),\n * and ONLY spawns `colgrep search` when the verdict is `fresh`. Never\n * runs another search engine.\n *\n * The inflight slot is acquired by the MCP handler (BEFORE this call,\n * after the preflight-cheap input validation) — same ordering invariant\n * as the other tools. This function itself does NOT acquire a slot for\n * the search, but it DOES kick background `init` work without a slot\n * (provisioning, not operator traffic).\n */\nexport async function runSemanticSearch(opts: {\n query: string\n workspace: string\n limit?: number\n pattern?: string\n signal?: AbortSignal\n /**\n * Serve-while-stale (Phase 2c): when true and the verdict is\n * stale-by-content with a small, fully-enumerated delta, serve semantic\n * results labeled `freshness:\"stale\"` instead of refusing. The unified\n * `code` tool sets this; direct callers that need the strict\n * refuse-when-stale contract leave it unset.\n */\n serveStale?: boolean\n}): Promise<SemanticSearchResult> {\n const { query, workspace } = opts\n const limit = clampLimit(opts.limit)\n\n const fresh = await freshnessVerdict(workspace)\n\n switch (fresh.verdict) {\n case \"absent\": {\n // Never indexed → kick a debounced background init, tell the model\n // it's not available yet (isError per the contract's defense-in-\n // depth unavailable path — the model picks code_search itself).\n kickBackgroundInit(workspace)\n return {\n status: \"unavailable\",\n isError: true,\n notice:\n \"no semantic index yet — build started; retry mode:\\\"semantic\\\" in minutes or use code_search\",\n }\n }\n case \"failed\":\n return handleFailure(workspace, fresh.meta, false)\n case \"crashed\":\n // A build whose PID died without recording a result (proxy kill / OOM)\n // — detected per-query by the freshness verdict, not yet persisted.\n return handleFailure(workspace, fresh.meta, true)\n case \"corrupt\":\n return repairCorruptIndex(workspace, fresh.meta)\n case \"building\": {\n // A `building` verdict with no live owner and nothing on disk is an\n // INTERRUPTED build, not a running one — and it used to be a silent,\n // permanent dead end: this branch returned a notice and never rebuilt,\n // nothing incremented a failure counter, and the degraded banner only\n // fires on `status:\"failed\"`. A workspace could sit here forever.\n //\n // Schedule ONE debounced recovery rather than kicking unconditionally:\n // `kickBackgroundInit` is single-flight per workspace, and a build that\n // keeps failing lands back in `failed` (capped + backed off), not here,\n // so this cannot become a rebuild storm.\n if (!isInitInFlight(workspace) && !(await completedIndexOnDisk(workspace))) {\n kickBackgroundInit(workspace)\n return {\n status: \"building\",\n notice:\n \"semantic index build interrupted — rebuild started; retry mode:\\\"semantic\\\" in minutes\",\n }\n }\n return {\n status: \"building\",\n notice:\n \"semantic index building; retry mode:\\\"semantic\\\" in minutes or use code_search\",\n }\n }\n case \"stale\": {\n // HEAD moved / tree newly dirty since the index. With serveStale and\n // a small content delta, SERVE the index labeled stale (the LLM-edit\n // fast path: a dirty tree would otherwise make semantic permanently\n // unavailable during active editing) while a background refresh\n // closes the gap. Engine/suspect stale and large deltas still refuse\n // — those can't be labeled honestly.\n if (opts.serveStale && isServableVerdict(fresh)) {\n kickBackgroundInit(workspace)\n return spawnSearch({\n query,\n workspace,\n limit,\n pattern: opts.pattern,\n freshness: \"stale\",\n stale_files: fresh.staleFiles?.length ?? 0,\n })\n }\n kickBackgroundInit(workspace)\n return {\n status: \"stale\",\n notice:\n \"semantic index predates the current HEAD / working tree; results would be outdated, so none are returned — retry shortly after the background re-index, or use code_search\",\n }\n }\n case \"fresh\":\n break\n }\n\n // Fresh + completed index on disk → spawn colgrep search.\n return spawnSearch({\n query,\n workspace,\n limit,\n pattern: opts.pattern,\n freshness: \"fresh\",\n })\n}\n\n/**\n * Decide how to respond to a failed/crashed index and SELF-HEAL when the\n * failure looks transient: re-kick a debounced background re-index when the\n * attempt count is under the per-class cap AND the backoff has elapsed,\n * else return an actionable notice (transient-throttled vs operator-action).\n *\n * A `crashed` verdict is a per-query detection of a build whose PID died\n * without recording a result (proxy kill / OOM); persist it as\n * `failed`+`crashed` (incrementing the attempt counter) before deciding so a\n * later query sees a consistent `failed` state. `stuck` (hung build killed\n * by the inactivity watchdog) retries at most once — re-running a hung build\n * usually hangs again; transient classes retry up to `MAX_FAILED_ATTEMPTS`.\n */\nasync function quarantineProjectDir(projectDir: string): Promise<boolean> {\n const quarantine = `${projectDir}.corrupt-${process.pid}-${randomBytes(4).toString(\"hex\")}`\n try {\n await fs.rename(projectDir, quarantine)\n } catch (err) {\n consola.debug(\"colbert: corrupt index quarantine rename failed:\", err)\n return false\n }\n // The delete runs in the background — the rename already made the corrupt\n // index invisible, so the caller must not wait on a large recursive rm.\n // Track it so teardown can drain it: an in-flight rm walking this tree\n // while something removes an ancestor raises EBUSY/EPERM on Windows.\n const removal = fs\n .rm(quarantine, { recursive: true, force: true })\n .catch((err) => {\n consola.debug(\"colbert: corrupt index quarantine cleanup failed:\", err)\n })\n .finally(() => {\n _quarantineRemovals.delete(removal)\n })\n _quarantineRemovals.add(removal)\n return true\n}\n\nasync function repairCorruptIndex(\n workspace: string,\n meta: ColbertMeta | null,\n): Promise<SemanticSearchResult> {\n const wsKey = path.resolve(workspace)\n const attempts = (meta?.failureClass === \"corrupt\" ? meta.failedAttempts ?? 0 : 0) + 1\n const failedMeta: ColbertMeta = {\n workspace,\n model: meta?.model ?? MODEL_ID,\n modelRev: meta?.modelRev ?? MODEL_REVISION,\n binarySha: colgrepBinAsset()?.sha256,\n ortSha: ortLibAsset()?.sha256,\n status: \"failed\",\n failureClass: \"corrupt\",\n failedAttempts: attempts,\n // Same reason as the other failure writes: a streak with no baseline is\n // never resettable, so a corrupt-index streak would cap permanently even\n // after an engine upgrade or a fresh corpus.\n failedAt: {\n head: meta?.lastIndexedHead,\n dirty: meta?.lastIndexedDirty,\n binarySha: colgrepBinAsset()?.sha256,\n ortSha: ortLibAsset()?.sha256,\n // CURRENT revision, not a copied one — see the note on the launch-path\n // stamp: a stale value never equals MODEL_REVISION and would reset the\n // streak on every query.\n modelRev: MODEL_REVISION,\n },\n lastIndexedAt: new Date().toISOString(),\n lastIndexedHead: meta?.lastIndexedHead,\n lastIndexedDirty: meta?.lastIndexedDirty,\n ownerInstanceId: getColbertInstanceUuid(),\n }\n\n if (_searchIndexInFlight.has(wsKey) || isInitInFlight(workspace)) {\n return {\n status: \"building\",\n notice: \"semantic index corrupt, writer active — results disabled until it exits\",\n }\n }\n\n const projectDir = await colbertProjectDir(workspace)\n if (!projectDir) {\n // No project dir means there is nothing to REPAIR — this workspace has no\n // index, which is `absent`, not corruption. Recording it as `corrupt`\n // burned that class's 2-attempt cap (stricter than the normal 3) on a\n // state that a rebuild fixes, and a stable-HEAD workspace then never\n // reset. That is exactly what a forked or unmatched project key looks\n // like, so this branch was reachable from the identity bug above.\n kickBackgroundInit(workspace)\n return {\n status: \"unavailable\",\n isError: true,\n notice:\n \"no semantic index yet — build started; retry mode:\\\"semantic\\\" in minutes or use code_search\",\n }\n }\n if (!(await quarantineProjectDir(projectDir))) {\n await writeColbertMeta(failedMeta).catch(() => {})\n return {\n status: \"failed\",\n isError: true,\n notice: \"semantic index corrupt, quarantine failed — close active colgrep processes and retry\",\n }\n }\n await writeColbertMeta(failedMeta).catch(() => {})\n\n if (attempts < 2) kickBackgroundInit(workspace)\n return {\n status: \"failed\",\n isError: true,\n notice:\n attempts < 2\n ? 'semantic index corrupt and quarantined — rebuild started; retry mode:\"semantic\" in minutes'\n : 'semantic index repeatedly corrupt — rebuild capped, do NOT retry mode:\"semantic\"; use code_search',\n }\n}\n\n/**\n * True when the inputs that produced the recorded failure streak differ from\n * the inputs in effect now — i.e. the streak is stale evidence and must not\n * veto a fresh attempt.\n *\n * Each signal answers \"could this plausibly have fixed the cause?\":\n * - engine/runtime sha: a colgrep or ONNX-runtime upgrade may fix the exact\n * bug that failed. Precedent: `freshnessVerdict` already forces a rebuild\n * on an engine-sha change for the same reason.\n * - model revision: a different embedding model is a different build.\n * - corpus identity: HEAD moved OR the working tree's dirty-state changed.\n * BOTH are needed — HEAD-only misses the most common local recovery\n * (fixing a malformed file without committing), and dirty-only misses a\n * branch switch.\n *\n * A legacy entry with no `failedAt` (written before this field existed) has no\n * baseline to compare, so it does NOT reset — it keeps today's behavior until\n * its next failure stamps one. That is the conservative direction: a missing\n * baseline must not read as \"everything changed\".\n */\nfunction failureInputsChanged(\n meta: ColbertMeta | null,\n git: { head?: string; dirty?: boolean },\n): boolean {\n const at = meta?.failedAt\n if (!at) return false\n // Every comparison requires BOTH sides to be known. An `undefined` on either\n // side means \"we cannot tell\", and unknown must never read as \"changed\" —\n // otherwise a partially-populated baseline (or a git probe that timed out)\n // would reset the streak on every query, which is the unbounded rebuild loop\n // this whole mechanism has to avoid.\n const binarySha = colgrepBinAsset()?.sha256\n const ortSha = ortLibAsset()?.sha256\n if (\n at.binarySha !== undefined\n && binarySha !== undefined\n && at.binarySha !== binarySha\n ) {\n return true\n }\n if (at.ortSha !== undefined && ortSha !== undefined && at.ortSha !== ortSha) {\n return true\n }\n if (at.modelRev !== undefined && at.modelRev !== MODEL_REVISION) return true\n if (at.head !== undefined && git.head !== undefined && at.head !== git.head) {\n return true\n }\n if (\n at.dirty !== undefined &&\n git.dirty !== undefined &&\n at.dirty !== git.dirty\n ) {\n return true\n }\n return false\n}\n\nasync function handleFailure(\n workspace: string,\n meta: ColbertMeta | null,\n crashedVerdict: boolean,\n): Promise<SemanticSearchResult> {\n const cls: NonNullable<ColbertMeta[\"failureClass\"]> = crashedVerdict\n ? \"crashed\"\n : (meta?.failureClass ?? \"error\")\n\n // Before consulting the cap, check whether the streak still describes the\n // current situation. A cap that only ever counts up is a permanent dead end\n // by construction — which is exactly the bug this fixes. Recovery still goes\n // through a REAL rebuild under the unchanged cap and backoff, so nothing is\n // served that the normal guards wouldn't already serve.\n //\n // The backoff is computed FIRST and applies to the reset kick too. Without\n // it the reset would remove the ceiling along with the dead end: on an\n // actively-developed repo whose build genuinely fails, every commit (head\n // moves) and every clean/dirty toggle would re-zero the counter and kick a\n // fresh full index immediately, forever. Clearing the streak is right;\n // rebuilding without a throttle is not.\n const lastAt = meta?.lastIndexedAt\n // NaN-safe: a missing/corrupt timestamp counts as \"elapsed\" (allow retry)\n // rather than NaN-comparing to false and blocking retries forever.\n const lastMs = lastAt ? Date.parse(lastAt) : NaN\n const backoffElapsed =\n !Number.isFinite(lastMs) || Date.now() - lastMs >= FAILED_RETRY_BACKOFF_MS\n\n // Only probe git when a git-derived baseline field could actually decide the\n // outcome. `gitState` runs up to three git subprocesses with 4s timeouts, and\n // this path is awaited inline before the lexical fallback — so a degraded\n // workspace would pay that on EVERY query. The engine/model comparisons need\n // no subprocess at all.\n const at = meta?.failedAt\n const needsGit = at?.head !== undefined || at?.dirty !== undefined\n const gitNow: { head?: string; dirty?: boolean } =\n needsGit ? await gitState(workspace).catch(() => ({})) : {}\n if (failureInputsChanged(meta, gitNow)) {\n consola.warn(\n `colbert: index inputs changed since the last failure (class=${cls}); ` +\n `clearing the failure streak${backoffElapsed ? \" and retrying\" : \"\"} for ${workspace}`,\n )\n await writeColbertMeta({\n workspace,\n model: meta?.model ?? MODEL_ID,\n modelRev: meta?.modelRev ?? MODEL_REVISION,\n binarySha: meta?.binarySha,\n ortSha: meta?.ortSha,\n status: \"failed\",\n failureClass: meta?.failureClass,\n // Persist the reset BEFORE kicking, so concurrent/back-to-back queries\n // see a cleared streak instead of each re-deciding to reset. The kick\n // itself is deduped by the per-workspace in-flight claim.\n failedAttempts: 0,\n failedAt: undefined,\n lastIndexedAt: meta?.lastIndexedAt,\n lastIndexedHead: meta?.lastIndexedHead,\n lastIndexedDirty: meta?.lastIndexedDirty,\n ownerInstanceId: getColbertInstanceUuid(),\n }).catch(() => {})\n if (backoffElapsed) kickBackgroundInit(workspace)\n return {\n status: \"failed\",\n isError: true,\n notice:\n backoffElapsed ?\n 'semantic index failed (inputs changed) — rebuild started; retry mode:\"semantic\" in minutes'\n : 'semantic index failed — rebuild pending; retry mode:\"semantic\" in minutes',\n }\n }\n\n const attempts = crashedVerdict\n ? (meta?.failedAttempts ?? 0) + 1\n : (meta?.failedAttempts ?? 1)\n\n if (crashedVerdict) {\n // Persist the crash (was a stranded `building` entry). Keep the existing\n // lastIndexedAt (build-start) so the backoff measures from when the\n // build began, not from this detection.\n await writeColbertMeta({\n workspace,\n model: meta?.model ?? MODEL_ID,\n modelRev: meta?.modelRev ?? MODEL_REVISION,\n status: \"failed\",\n failureClass: \"crashed\",\n failedAttempts: attempts,\n // Stamp the baseline so a later input change can clear this streak too\n // — otherwise a 3-crash workspace stays terminal exactly like the bug\n // this fixes.\n failedAt: {\n head: meta?.lastIndexedHead,\n dirty: meta?.lastIndexedDirty,\n binarySha: meta?.binarySha ?? colgrepBinAsset()?.sha256,\n ortSha: meta?.ortSha ?? ortLibAsset()?.sha256,\n // CURRENT revision, not a copied one (see the launch-path note).\n modelRev: MODEL_REVISION,\n },\n lastIndexedAt: lastAt ?? new Date().toISOString(),\n lastIndexedHead: meta?.lastIndexedHead,\n lastIndexedDirty: meta?.lastIndexedDirty,\n ownerInstanceId: getColbertInstanceUuid(),\n }).catch(() => {})\n }\n\n const cap = cls === \"stuck\" || cls === \"corrupt\" ? 2 : MAX_FAILED_ATTEMPTS\n\n if (attempts < cap && backoffElapsed) {\n kickBackgroundInit(workspace)\n consola.debug(\n `colbert: re-kicking index (class=${cls}, attempt=${attempts}/${cap})`,\n )\n return {\n status: \"failed\",\n isError: true,\n notice:\n 'semantic index failed — re-index started; retry mode:\"semantic\" in minutes',\n }\n }\n\n if (attempts < cap) {\n // Under the cap but inside the backoff window — a retry is pending.\n return {\n status: \"failed\",\n isError: true,\n notice:\n 'semantic index unavailable (recent build failure) — retry mode:\"semantic\" in minutes',\n }\n }\n\n // Capped → stop retrying. The env-var tuning advice that used to live in\n // this notice was addressed to the wrong audience: a spawned agent cannot\n // set env vars on the running proxy, so it burned context and could invite\n // a pointless `export`. Operator-facing guidance now lives in the launch\n // banner and the failure line in ERROR_LOG_PATH; the model just needs to\n // know semantic is unavailable and what to use instead.\n consola.warn(\n `colbert: index ${cls}, giving up (attempts=${attempts}) for ${workspace}`,\n )\n return {\n status: \"failed\",\n isError: true,\n notice: `semantic index unavailable (${cls}); use code_search with specific symbol/keyword terms`,\n }\n}\n\nasync function spawnSearch(opts: {\n query: string\n workspace: string\n limit: number\n pattern?: string\n freshness: \"fresh\" | \"stale\"\n stale_files?: number\n}): Promise<SemanticSearchResult> {\n const binary = colgrepBinaryPath()\n if (!existsSync(binary)) {\n return {\n status: \"unavailable\",\n isError: true,\n notice: \"semantic search binary missing; use code_search\",\n }\n }\n // Fail closed if the ORT dylib vanished after the availability gate\n // passed (tiny TOCTOU window): an absent ORT_DYLIB_PATH makes colgrep\n // silently fall through to its own UNVERIFIED ONNX-runtime download.\n // Don't spawn — report unavailable instead.\n if (!existsSync(colbertOrtDylibPath())) {\n return {\n status: \"unavailable\",\n isError: true,\n notice: \"semantic search runtime (ONNX) missing; use code_search\",\n }\n }\n const args = [\n \"search\",\n \"--json\",\n \"--color\",\n \"never\",\n \"--force-cpu\",\n \"--model\",\n canonicalColbertModelDir(),\n \"-y\",\n \"-k\",\n String(opts.limit),\n ]\n if (opts.pattern) args.push(\"-e\", opts.pattern)\n args.push(opts.query, opts.workspace)\n\n const wsKey = path.resolve(opts.workspace)\n if (_searchIndexInFlight.has(wsKey)) {\n // Conservative per-workspace guard: only ONE colgrep search runs per\n // workspace at a time. colgrep auto-indexes/reconciles during a search\n // (no read-only flag), and two concurrent searches that both reconcile\n // would be unsynchronized writers — so we serialize rather than risk it.\n // The lock is held only while the search runs (sub-second for a warm\n // read; until the background index completes for a detached one), so a\n // SEQUENTIAL search pattern never contends — only a simultaneous batch on\n // the same workspace, where the losers get an immediate lexical fallback.\n return {\n status: \"building\",\n notice:\n \"semantic index is busy (another search is running); retry shortly\",\n }\n }\n _searchIndexInFlight.add(wsKey)\n\n // Run colgrep under the GENEROUS (build-grade) watchdog: a search that\n // triggers a foreground auto-index / reconcile is NEVER killed mid-write\n // (that orphans docs and desyncs the index) — only a genuinely hung one is,\n // after INIT_STALL_MS of no progress (no output AND no index-dir growth).\n // INIT_TIMEOUT_MS is a pure runaway backstop. The CALLER doesn't wait this\n // long — see the responsiveness race below.\n let searchPromise: ReturnType<typeof runManagedExeCapture>\n try {\n searchPromise = _runManagedExeCapture(binary, args, {\n env: colgrepEnv(),\n inactivityTimeoutMs: INIT_STALL_MS,\n onInactivityCheck: makeIndexProgressProbe(opts.workspace),\n timeoutMs: INIT_TIMEOUT_MS,\n maxStdoutBytes: MAX_STDOUT_BYTES,\n // Byte-cap TRUNCATES (stops capturing) instead of killing — a huge\n // result must never tree-kill colgrep, which (post-index) is a non-hang\n // kill path that could interrupt a write. The child drains to completion.\n truncateInsteadOfKill: true,\n onSpawn: trackChild,\n })\n } catch {\n // Synchronous failure before a promise existed → release the lock now\n // (the .finally below never got attached).\n _searchIndexInFlight.delete(wsKey)\n consola.debug(\"colbert: search failed to launch\")\n return {\n status: \"failed\",\n isError: true,\n notice: \"semantic search failed to launch; use code_search\",\n }\n }\n // Release the workspace lock when the colgrep child actually exits — covers\n // a fast read (sub-second), a detached background index (much later), AND\n // every async failure path. The lock outlives the responsiveness race below.\n void searchPromise\n .catch(() => undefined)\n .finally(() => _searchIndexInFlight.delete(wsKey))\n\n // A warm search resolves in <1s; only a slow foreground-indexing search hits\n // the responsiveness deadline. The timer is cleared on a fast win so rapid\n // searches don't accumulate live timeouts.\n let respondTimer: ReturnType<typeof setTimeout> | undefined\n const slow = new Promise<{ kind: \"slow\" }>((resolve) => {\n respondTimer = setTimeout(() => resolve({ kind: \"slow\" }), SEARCH_RESPOND_MS)\n respondTimer.unref?.()\n })\n const raced = await Promise.race([\n searchPromise.then(\n (res) => ({ kind: \"done\" as const, res }),\n (err) => ({ kind: \"error\" as const, err }),\n ),\n slow,\n ])\n if (respondTimer) clearTimeout(respondTimer)\n\n if (raced.kind === \"slow\") {\n // colgrep is foreground-indexing / reconciling. DETACH: let it finish in\n // the background (the generous watchdog reaps only a true hang, never a\n // mid-write kill; the workspace lock above stays held until it exits, so\n // no concurrent search collides), and return a fallback now so the caller\n // never hangs. The next query is fast once the index settles.\n consola.debug(`colbert: search detached (indexing) for ${opts.workspace}`)\n return {\n status: \"building\",\n notice:\n 'semantic index updating in background; retry mode:\"semantic\" in minutes',\n }\n }\n\n if (raced.kind === \"error\") {\n consola.debug(\"colbert: search failed to launch\")\n return {\n status: \"failed\",\n isError: true,\n notice: \"semantic search failed to launch; use code_search\",\n }\n }\n\n const res = raced.res\n if (res.timedOut || res.stalled) {\n consola.debug(\n `colbert: search ${res.stalled ? \"stalled (hung, no progress)\" : \"hit the runaway backstop\"}`,\n )\n return {\n status: \"failed\",\n isError: true,\n notice: \"semantic search timed out; use code_search\",\n }\n }\n if (res.stdoutTruncated) {\n return {\n status: \"failed\",\n isError: true,\n notice:\n \"semantic search produced an oversized result; narrow the query or use code_search\",\n }\n }\n if (res.code !== 0) {\n // NEVER surface raw stderr (embeds source). Just a class label.\n consola.debug(`colbert: search exited ${res.code}`)\n return {\n status: \"failed\",\n isError: true,\n notice: \"semantic search returned an error; use code_search\",\n }\n }\n\n const rows = parseAndTrim(res.stdout, opts.workspace)\n if (rows === null) {\n return {\n status: \"failed\",\n isError: true,\n notice: \"semantic search output was unparseable; use code_search\",\n }\n }\n return {\n status: \"ready\",\n source: \"semantic\",\n results: rows,\n freshness: opts.freshness,\n ...(opts.freshness === \"stale\" ? { stale_files: opts.stale_files ?? 0 } : {}),\n }\n}\n\n/**\n * Parse colgrep `--json` and trim each hit to the 6 minimal fields.\n * Returns null on parse failure (caller maps to failed). NEVER includes\n * `unit.code` verbatim — `snippet` is the signature + a few lines.\n */\nfunction parseAndTrim(\n stdout: string,\n workspace: string,\n): Array<SemanticResultRow> | null {\n let parsed: unknown\n try {\n parsed = JSON.parse(stdout)\n } catch {\n return null\n }\n if (!Array.isArray(parsed)) return null\n // colgrep emits OS-realpath'd file paths (macOS /tmp → /private/tmp,\n // Windows 8.3). Resolve the workspace realpath once so relativization\n // produces clean repo-relative paths instead of leaking the absolute.\n const wsReal = realpathSyncSafe(workspace)\n const out: Array<SemanticResultRow> = []\n for (const item of parsed as Array<ColgrepHit>) {\n const unit = item?.unit\n if (!unit || typeof unit.file !== \"string\") continue\n const rel = relativize(unit.file, workspace, wsReal)\n out.push({\n file: rel,\n line: typeof unit.line === \"number\" ? unit.line : 1,\n ...(typeof unit.end_line === \"number\" ? { endLine: unit.end_line } : {}),\n ...(typeof unit.name === \"string\" ? { name: unit.name } : {}),\n score: typeof item.score === \"number\" ? round2(item.score) : 0,\n snippet: buildSnippet(unit),\n })\n }\n return out\n}\n\n/** snippet = signature + first few representative lines (NOT full code). */\nexport function buildSnippet(unit: NonNullable<ColgrepHit[\"unit\"]>): string {\n const sig = typeof unit.signature === \"string\" ? unit.signature.trim() : \"\"\n const code = typeof unit.code === \"string\" ? unit.code : \"\"\n if (!code) return sig\n const lines = code.split(\"\\n\")\n // Up to 5 representative lines after the signature line. Cap total\n // length so a single oversized unit can't blow the response.\n const body = lines.slice(0, 6).join(\"\\n\")\n const firstBodyLine = lines[0]?.trim() ?? \"\"\n const snippet = sig && firstBodyLine !== sig ? `${sig}\\n${body}` : body\n return snippet.length > 600 ? snippet.slice(0, 600) + \"…\" : snippet\n}\n\nfunction stripExtendedPathPrefix(value: string): string {\n if (/^\\\\\\\\\\?\\\\UNC\\\\/i.test(value)) return `\\\\\\\\${value.slice(8)}`\n if (/^\\\\\\\\\\?\\\\[a-z]:\\\\/i.test(value)) return value.slice(4)\n return value\n}\n\nexport function relativize(file: string, workspace: string, workspaceReal: string): string {\n const normalizedFile = stripExtendedPathPrefix(file)\n for (const rawBase of [workspace, workspaceReal]) {\n try {\n const base = stripExtendedPathPrefix(rawBase)\n const flavor = /^[a-z]:[\\\\/]/i.test(base) || base.startsWith(\"\\\\\\\\\")\n ? path.win32\n : path\n const rel = flavor.relative(base, normalizedFile)\n if (rel && !rel.startsWith(\"..\") && !flavor.isAbsolute(rel)) return rel\n } catch {\n // try next base\n }\n }\n return file\n}\n\nfunction realpathSyncSafe(p: string): string {\n try {\n return realpathSync(p)\n } catch {\n return p\n }\n}\n\nfunction round2(n: number): number {\n return Math.round(n * 100) / 100\n}\n\nfunction clampLimit(limit: number | undefined): number {\n if (typeof limit !== \"number\" || !Number.isFinite(limit)) return DEFAULT_LIMIT\n return Math.max(1, Math.min(100, Math.floor(limit)))\n}\n\n// ---------------------------------------------------------------------\n// Background init (provisioning, not operator traffic — no inflight slot)\n// ---------------------------------------------------------------------\n\n/**\n * Kick a background `colgrep init` for a workspace, debounced per\n * (workspace, model). Fire-and-forget; updates the sidecar metadata to\n * `building` (with our PID + instance UUID) on start and `ready`/`failed`\n * on completion. Never throws to the caller.\n */\nexport function kickBackgroundInit(workspace: string): void {\n if (isInitInFlight(workspace)) return\n if (!tryClaimInit(workspace)) return\n const key = path.resolve(workspace)\n const promise = runInit(workspace)\n .catch(async (err) => {\n releaseInit(workspace)\n consola.error(\"colbert: background init failed:\", err)\n const prior = await readColbertMeta(workspace)\n // Read LIVE git state for the baseline rather than copying\n // `prior.lastIndexedHead`. That field records the last SUCCESSFUL index\n // and is empty on a workspace that has never built, so copying it would\n // stamp a headless baseline — and a baseline with no head can never\n // detect a later commit, leaving this failure class unresettable.\n const g = await gitState(workspace).catch(() => ({\n head: undefined,\n dirty: undefined,\n }))\n await writeColbertMeta({\n workspace,\n model: prior?.model ?? MODEL_ID,\n modelRev: prior?.modelRev ?? MODEL_REVISION,\n binarySha: colgrepBinAsset()?.sha256,\n ortSha: ortLibAsset()?.sha256,\n status: \"failed\",\n failureClass: \"launch\",\n failedAttempts: (prior?.failedAttempts ?? 0) + 1,\n // Stamp the baseline here too. Without it a spawn failure — a missing\n // or unrunnable binary, the most likely thing an upgrade FIXES — would\n // accumulate a streak with no `failedAt`, and `failureInputsChanged`\n // treats a missing baseline as \"unknown, do not reset\". That would\n // leave exactly this class of failure permanently capped.\n failedAt: {\n head: g.head,\n dirty: g.dirty,\n binarySha: colgrepBinAsset()?.sha256,\n ortSha: ortLibAsset()?.sha256,\n // The CURRENT revision, not `prior.modelRev`. The baseline records\n // what was in effect for THIS attempt; copying a stale value would\n // make the comparison against MODEL_REVISION permanently unequal and\n // reset the streak on every query — an unbounded rebuild loop.\n modelRev: MODEL_REVISION,\n },\n lastIndexedAt: new Date().toISOString(),\n lastIndexedHead: prior?.lastIndexedHead,\n lastIndexedDirty: prior?.lastIndexedDirty,\n ownerInstanceId: getColbertInstanceUuid(),\n }).catch((writeErr) => {\n consola.error(\"colbert: failed to record background init failure:\", writeErr)\n })\n })\n .finally(() => {\n _initPromises.delete(key)\n })\n _initPromises.set(key, promise)\n}\n\n/**\n * Whether the STARTUP auto-kick should fire for a workspace. Skips a build\n * that's already in a capped/persistent failure state (`failedAttempts >=\n * MAX`) or was killed as `stuck` (hung) — so a restart loop doesn't re-burn\n * a known-bad build on every launch. The per-query self-heal still gives a\n * `stuck` build its one retry and a capped one its post-backoff probe;\n * absent/stale/under-cap/ready all kick normally.\n */\nexport async function startupKickAllowed(workspace: string): Promise<boolean> {\n const meta = await readColbertMeta(workspace)\n if (!meta || meta.status !== \"failed\") return true\n const cap = meta.failureClass === \"stuck\" || meta.failureClass === \"corrupt\"\n ? 2\n : MAX_FAILED_ATTEMPTS\n if ((meta.failedAttempts ?? 0) >= cap) return false\n if (meta.failureClass === \"stuck\") return false\n return true\n}\n\n/**\n * Encoding sessions colgrep may run in parallel: 25% of the machine's\n * threads, never fewer than 2.\n *\n * colgrep defaults this to the FULL CPU count, so a background index build\n * saturates the machine — the exact opposite of what a background build\n * should do during an interactive agent session (the proxy even holds a\n * keep-awake assertion so those sessions run long and unattended). The floor\n * of 2 keeps a 1- to 7-thread box from dropping to a single session and\n * taking proportionally forever.\n *\n * Override with `GH_ROUTER_COLBERT_PARALLEL` (a positive integer).\n */\nexport function colbertParallelSessions(): number {\n const raw = Number(process.env.GH_ROUTER_COLBERT_PARALLEL)\n if (Number.isSafeInteger(raw) && raw > 0) return raw\n const threads = os.availableParallelism?.() ?? os.cpus?.().length ?? 4\n return Math.max(2, Math.floor(threads * 0.25))\n}\n\n/**\n * Persist the parallelism cap into the router-owned colgrep config.\n *\n * `--parallel` exists only on the `settings` subcommand — there is no\n * per-run flag and no env var. It writes `parallel_sessions` to\n * `<COLGREP_DATA_DIR>/../config.json`, which for us is\n * `<APP_DIR>/colbert/config.json`: router-owned, and NOT the user's own\n * colgrep config (verified — after we write ours, a plain `colgrep\n * settings` with no COLGREP_DATA_DIR still reports `auto`).\n *\n * Best-effort: failing here means colgrep encodes at its default (all\n * threads), which is greedy but not incorrect, so it must never block a\n * build.\n */\nasync function applyParallelismCap(binary: string): Promise<void> {\n const sessions = colbertParallelSessions()\n try {\n await _runManagedExeCapture(\n binary,\n [\"settings\", \"--parallel\", String(sessions)],\n { env: colgrepEnv(), timeoutMs: 30_000, maxStdoutBytes: MAX_STDOUT_BYTES },\n )\n } catch (err) {\n consola.debug(\"colbert: could not cap colgrep parallelism:\", err)\n }\n}\n\nasync function runInit(workspace: string): Promise<void> {\n const binary = colgrepBinaryPath()\n if (!existsSync(binary)) {\n throw new Error(\"colgrep binary is missing\")\n }\n // Fail closed if the ORT dylib is missing — otherwise the background\n // init would spawn colgrep, which silently downloads an UNVERIFIED ONNX\n // runtime when ORT_DYLIB_PATH can't be loaded.\n if (!existsSync(colbertOrtDylibPath())) {\n throw new Error(\"ColBERT ONNX runtime is missing\")\n }\n // Cap parallelism before the encode starts. The setting persists in our\n // data dir, so it also governs the reconcile a later `search` may run.\n await applyParallelismCap(binary)\n // Carry the failure streak across the building→done transition so the\n // attempt cap accrues (reset to 0 only on a successful build).\n const prior = await readColbertMeta(workspace)\n const baseMeta: ColbertMeta = {\n workspace,\n model: MODEL_ID,\n modelRev: MODEL_REVISION,\n binarySha: colgrepBinAsset()?.sha256,\n ortSha: ortLibAsset()?.sha256,\n status: \"building\",\n // Placeholder until the colgrep child PID is known (set in onSpawn).\n // The boot sweep reclassifies a `building` entry whose buildPid is\n // DEAD → failed; it MUST be the colgrep CHILD pid, not the proxy\n // pid, or a crashed build with a still-live proxy would stay\n // `building` forever (advisor finding).\n buildPid: undefined,\n ownerInstanceId: getColbertInstanceUuid(),\n lastIndexedAt: new Date().toISOString(),\n // Carry the streak INTO the `building` write so it survives even an\n // ABRUPT crash (OOM / proxy kill) that skips the final write — otherwise\n // the per-query `crashed` reclassification would read a missing counter,\n // reset the streak to 1 every time, and never hit the cap (retry storm).\n failedAttempts: prior?.failedAttempts ?? 0,\n // Carry the BASELINE for the same reason. A meta write replaces the whole\n // record, so dropping `failedAt` here would strip the streak's baseline on\n // every build attempt — and `failureInputsChanged` would then see a\n // partially-populated (or absent) baseline and could clear the streak on\n // the next query, re-kicking forever. The counter and the baseline that\n // scopes it have to survive together or neither is meaningful.\n failedAt: prior?.failedAt,\n }\n // Capture git state at index start so the freshness verdict has a\n // baseline (best-effort; non-git workspaces leave these undefined).\n try {\n const g = await gitState(workspace)\n if (g.isRepo) {\n baseMeta.lastIndexedHead = g.head\n baseMeta.lastIndexedDirty = g.dirty\n }\n } catch {\n // ignore\n }\n await writeColbertMeta(baseMeta).catch(() => {})\n\n const args = [\n \"init\",\n \"-y\",\n \"--color\",\n \"never\",\n \"--force-cpu\",\n \"--model\",\n canonicalColbertModelDir(),\n workspace,\n ]\n\n // Disk-growth progress probe. colgrep is SILENT on a non-TTY pipe during\n // the (possibly multi-hour) encode phase, so output can't signal progress\n // — but it writes index shards incrementally. The probe re-arms the\n // inactivity watchdog while the index dir keeps growing; a frozen\n // signature ⇒ hung ⇒ killed (stalled). `null` (dir not found yet) is\n // inconclusive → don't kill (the absolute timeout backstop covers a build\n // that never writes anything).\n // Disk-growth progress probe (shared with the search path): colgrep is\n // SILENT on a non-TTY pipe during the (possibly multi-hour) encode, so\n // output can't signal progress — but it writes index shards incrementally.\n // The probe re-arms the inactivity watchdog while the index dir grows; a\n // frozen signature ⇒ hung ⇒ killed (stalled).\n const onInactivityCheck = makeIndexProgressProbe(workspace)\n\n const startMs = Date.now()\n let ok: boolean\n let failureClass: NonNullable<ColbertMeta[\"failureClass\"]> | undefined\n try {\n const res = await _runManagedExeCapture(binary, args, {\n env: colgrepEnv(),\n timeoutMs: INIT_TIMEOUT_MS,\n inactivityTimeoutMs: INIT_STALL_MS,\n onInactivityCheck,\n maxStdoutBytes: MAX_STDOUT_BYTES,\n onSpawn: (child) => {\n trackChild(child)\n // Record the colgrep child PID so the boot sweep AND the per-query\n // freshness verdict can detect a crashed build (dead child PID) and\n // reclassify to `failed`.\n if (typeof child.pid === \"number\") {\n void writeColbertMeta({ ...baseMeta, buildPid: child.pid }).catch(\n () => {},\n )\n }\n },\n })\n ok = !res.stalled && !res.timedOut && res.code === 0\n if (ok) {\n const projectDir = await colbertProjectDir(workspace)\n ok =\n projectDir !== null &&\n validateIndexIntegrity(path.join(projectDir, \"index\")).verdict === \"coherent\"\n if (!ok) {\n failureClass = \"corrupt\"\n if (projectDir) await quarantineProjectDir(projectDir)\n }\n } else {\n // stalled (inactivity watchdog) or timedOut (absolute backstop) both\n // mean \"didn't finish, killed\" → `stuck`; a clean non-zero exit is a\n // colgrep `error`. NEVER inspect res.stderr (embeds source).\n failureClass = res.stalled || res.timedOut ? \"stuck\" : \"error\"\n }\n } catch (err) {\n ok = false\n failureClass = \"launch\"\n consola.error(\"colbert: init failed to launch:\", err)\n } finally {\n releaseInit(workspace)\n }\n const elapsedMs = Date.now() - startMs\n\n // Re-read git state at completion so lastIndexedHead reflects the tree\n // we actually indexed.\n const finalMeta: ColbertMeta = { ...baseMeta, buildPid: undefined }\n try {\n const g = await gitState(workspace)\n if (g.isRepo) {\n finalMeta.lastIndexedHead = g.head\n finalMeta.lastIndexedDirty = g.dirty\n }\n } catch {\n // ignore\n }\n finalMeta.status = ok ? \"ready\" : \"failed\"\n finalMeta.lastIndexedAt = new Date().toISOString()\n if (ok) {\n finalMeta.failedAttempts = 0\n finalMeta.failureClass = undefined\n finalMeta.failedAt = undefined\n } else {\n finalMeta.failureClass = failureClass\n finalMeta.failedAttempts = (prior?.failedAttempts ?? 0) + 1\n // Stamp WHAT was being indexed when this failure happened, so a later\n // query can tell \"the same inputs failed again\" from \"the inputs changed,\n // so the old streak is stale evidence\". Kept apart from `lastIndexedHead`,\n // which on the success path means \"what we successfully indexed\" and is\n // read by the git-freshness comparison — overloading it would couple\n // failure-reset to freshness semantics.\n finalMeta.failedAt = {\n head: finalMeta.lastIndexedHead,\n dirty: finalMeta.lastIndexedDirty,\n binarySha: finalMeta.binarySha,\n ortSha: finalMeta.ortSha,\n modelRev: finalMeta.modelRev,\n }\n // WARN, not debug: `enableFileLogging()` installs a reporter that drops\n // everything below `warn` (`file-log-reporter.ts` ALLOWED_TYPES), which is\n // exactly why this diagnostic was invisible — a semantic-search outage ran\n // for weeks with zero colbert lines in a 120KB error.log. At `warn` it\n // reaches PATHS.ERROR_LOG_PATH, already credential-sanitized and capped.\n // Still no raw stderr: colgrep output can embed source, so only the class,\n // the duration and the attempt count are recorded.\n consola.warn(\n `colbert: init ${failureClass} after ${Math.round(elapsedMs / 1000)}s ` +\n `(attempt ${finalMeta.failedAttempts}) for ${workspace}`,\n )\n }\n await writeColbertMeta(finalMeta).catch(() => {})\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,MAAM,gBAAgB;AAEtB,SAAS,SAAS,MAAsB;CACtC,OAAO,KAAK,KAAK,GAAG,QAAQ,GAAG,UAAU,SAAS,iBAAiB,IAAI;AACzE;;;;;;;;;AAUA,eAAsB,gBACpB,MACA,IACkB;CAClB,MAAM,IAAI,SAAS,IAAI;CAEvB,IAAI,SAAS,MAAM,cAAc,CAAC;CAClC,IAAI,CAAC,QAAQ;EAEX,IAAI;EACJ,IAAI;GACF,MAAM,IAAI,MAAM,KAAK,CAAC;GACtB,QAAQ,KAAK,IAAI,IAAI,EAAE,UAAU;EACnC,QAAQ;GAEN,QAAQ;EACV;EACA,IAAI,CAAC,OAAO,OAAO;EACnB,MAAM,GAAG,GAAG,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;EAC3C,SAAS,MAAM,cAAc,CAAC;EAC9B,IAAI,CAAC,QAAQ,OAAO;CACtB;CAEA,IAAI;EACF,MAAM,OAAO,MAAM;EAC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CACP,OAAO;CACP,OAAO;CACP,SAAS;CACT,MAAM;CACN,MAAM;CACN,QAAQ;CACR,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,OAAO;AACT;;;;;;AAOA,MAAa,gBAAgB;;;;;;;;;;;;;AAc7B,MAAa,wBAAuE;CAClF,4BAAY,IAAI,IAAI;EAClB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CACD,qBAAK,IAAI,IAAI;EACX;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CACD,4BAAY,IAAI,IAAI;EAClB;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CACD,wBAAQ,IAAI,IAAI;EACd;EACA;EACA;CACF,CAAC;CACD,oBAAI,IAAI,IAAI;EACV;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CACD,sBAAM,IAAI,IAAI;EACZ;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CACD,sBAAM,IAAI,IAAI;EACZ;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CACD,mBAAG,IAAI,IAAI;EACT;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CACD,qBAAK,IAAI,IAAI;EACX;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CACD,wBAAQ,IAAI,IAAI;EACd;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;AACH;;;;;;;;;;;;;;;;;AAkBA,MAAa,8BAET,EACF,wBAAQ,IAAI,IAAI,CAAC,qBAAqB,yBAAyB,CAAC,EAClE;;;;;;AAOA,MAAa,wCAAwB,IAAI,IAAI;CAC3C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;AAOD,SAAgB,sBAAsB,UAAiC;CACrE,M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