github-router 0.3.327 → 0.3.329
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-FdE6tYAl.js → attribution-settings-B7ShuykF.js} +10 -10
- package/dist/attribution-settings-B7ShuykF.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-C6Ddvt8L.js → claude-mRxETPzg.js} +21 -21
- package/dist/{claude-C6Ddvt8L.js.map → claude-mRxETPzg.js.map} +1 -1
- package/dist/{codex-DikHPpLj.js → codex-DFw8NKp1.js} +6 -6
- package/dist/{codex-DikHPpLj.js.map → codex-DFw8NKp1.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-Y2BmXHF9.js +2 -0
- package/dist/{gate-discovery-CBna9eP-.js → gate-discovery-Dkmfcujh.js} +5 -5
- package/dist/{gate-discovery-CBna9eP-.js.map → gate-discovery-Dkmfcujh.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-BnIqDmBT.js → index-cmd-DUjQs9zw.js} +18 -8
- package/dist/index-cmd-DUjQs9zw.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-DNfS5cxB.js → internal-stop-hook-D0m7aRJ4.js} +5 -5
- package/dist/{internal-stop-hook-DNfS5cxB.js.map → internal-stop-hook-D0m7aRJ4.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/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 -21
- 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-Cs7qXWA7.js → peer-mcp-personas-C5WQdw7V.js} +49 -21
- package/dist/peer-mcp-personas-C5WQdw7V.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-5FSlDXXk.js → provision-B96yW3ax.js} +5 -5
- package/dist/{provision-5FSlDXXk.js.map → provision-B96yW3ax.js.map} +1 -1
- 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-DPeyTjn0.js → serve-BOqxpa24.js} +13 -13
- package/dist/{serve-DPeyTjn0.js.map → serve-BOqxpa24.js.map} +1 -1
- package/dist/{server-setup-Bymo8rfd.js → server-setup-DCp30g9w.js} +8 -8
- package/dist/{server-setup-Bymo8rfd.js.map → server-setup-DCp30g9w.js.map} +1 -1
- package/dist/{runner-CFR2seH4.js → service-backend-DYEPoszR.js} +1068 -18
- package/dist/service-backend-DYEPoszR.js.map +1 -0
- package/dist/{start-RwIzqSUq.js → start-CQduw8RP.js} +4 -4
- package/dist/{start-RwIzqSUq.js.map → start-CQduw8RP.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 +1 -1
- package/dist/attribution-settings-FdE6tYAl.js.map +0 -1
- package/dist/engine-CNDZ4OP_.js +0 -2
- package/dist/index-cmd-BnIqDmBT.js.map +0 -1
- 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-Cs7qXWA7.js.map +0 -1
- package/dist/runner-CFR2seH4.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as PATHS } from "./paths-
|
|
1
|
+
import { t as PATHS } from "./paths-P5ajjpzU.js";
|
|
2
2
|
import { l as runManagedExeCapture, o as resolveExecutable, u as spawnTaskkillBestEffort } from "./exec-COUT4QsS.js";
|
|
3
|
-
import { n as isPidAlive, s as trackChild, t as getColbertInstanceUuid } from "./lifecycle-
|
|
3
|
+
import { c as untrackChild, n as isPidAlive, s as trackChild, t as getColbertInstanceUuid } from "./lifecycle-D8vQXfeC.js";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
5
|
import consola from "consola";
|
|
6
6
|
import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
@@ -18,6 +18,7 @@ import { createInterface } from "node:readline";
|
|
|
18
18
|
import { Language, Parser } from "web-tree-sitter";
|
|
19
19
|
import { Worker } from "node:worker_threads";
|
|
20
20
|
import { gunzipSync, inflateRawSync } from "node:zlib";
|
|
21
|
+
import * as net from "node:net";
|
|
21
22
|
//#region \0rolldown/runtime.js
|
|
22
23
|
var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
|
|
23
24
|
//#endregion
|
|
@@ -3344,7 +3345,7 @@ async function searchCode(rawInput, externalSignal) {
|
|
|
3344
3345
|
const outlineStartMs = Date.now();
|
|
3345
3346
|
const wantScan = rawInput.scan === true;
|
|
3346
3347
|
const scanDeadline = Date.now() + WALL_TIME_MS;
|
|
3347
|
-
if (rawInput.summary
|
|
3348
|
+
if (rawInput.summary === true || wantScan) {
|
|
3348
3349
|
let distinct;
|
|
3349
3350
|
if (wantScan) {
|
|
3350
3351
|
const enumed = await enumerateWorkspaceFiles({
|
|
@@ -3543,6 +3544,68 @@ function modelDirName() {
|
|
|
3543
3544
|
}
|
|
3544
3545
|
/** Short model id used in the sidecar metadata `model` field. */
|
|
3545
3546
|
const MODEL_ID = "LateOn-Code-edge";
|
|
3547
|
+
/** next-plaid-api release tag these server binaries are promoted from. */
|
|
3548
|
+
const NEXTPLAID_SERVER_TAG = "next-plaid-server-v1.7.0";
|
|
3549
|
+
function nextPlaidServerUrl(asset) {
|
|
3550
|
+
return `https://github.com/animeshkundu/github-router/releases/download/${NEXTPLAID_SERVER_TAG}/${asset}`;
|
|
3551
|
+
}
|
|
3552
|
+
/**
|
|
3553
|
+
* next-plaid-api server binaries, keyed `<platform>-<arch>-<variant>`.
|
|
3554
|
+
* Built by .github/workflows/next-plaid-server.yml from the pinned
|
|
3555
|
+
* upstream tag: cpu = OpenBLAS-static (Linux/Windows) / Accelerate
|
|
3556
|
+
* (macOS); cuda = + CUDA execution provider (Linux/Windows x64 only).
|
|
3557
|
+
* macOS has no cuda variant (no NVIDIA target); linux-arm64 and
|
|
3558
|
+
* win-arm64 have no entries (unsupported → lexical fallback).
|
|
3559
|
+
*/
|
|
3560
|
+
const NEXTPLAID_SERVER = {
|
|
3561
|
+
"linux-x64-cpu": {
|
|
3562
|
+
url: nextPlaidServerUrl("next-plaid-api-x86_64-unknown-linux-gnu"),
|
|
3563
|
+
sha256: "799b69de51c8f9978ea6537315da4ad63f9c2fd6f0b50f3ea8021d7ffdbc0aa3",
|
|
3564
|
+
archive: "raw",
|
|
3565
|
+
variant: "cpu"
|
|
3566
|
+
},
|
|
3567
|
+
"linux-x64-cuda": {
|
|
3568
|
+
url: nextPlaidServerUrl("next-plaid-api-x86_64-unknown-linux-gnu-cuda"),
|
|
3569
|
+
sha256: "94adc97569abc4ea58d411cb23e6692c70b23e18eef0071d08fe97bc159a12d6",
|
|
3570
|
+
archive: "raw",
|
|
3571
|
+
variant: "cuda",
|
|
3572
|
+
cudaVersion: "12.8"
|
|
3573
|
+
},
|
|
3574
|
+
"win32-x64-cpu": {
|
|
3575
|
+
url: nextPlaidServerUrl("next-plaid-api-x86_64-pc-windows-msvc.exe"),
|
|
3576
|
+
sha256: "86c243c15f84ff32186f6fe04e98c2d71d922e13a2fdaa9b95da3ac2df8ff7a1",
|
|
3577
|
+
archive: "raw",
|
|
3578
|
+
variant: "cpu"
|
|
3579
|
+
},
|
|
3580
|
+
"win32-x64-cuda": {
|
|
3581
|
+
url: nextPlaidServerUrl("next-plaid-api-x86_64-pc-windows-msvc-cuda.exe"),
|
|
3582
|
+
sha256: "f235faf71fbcec0a28024cb416e3060c62f035f446a4eb3a1024220be0666edc",
|
|
3583
|
+
archive: "raw",
|
|
3584
|
+
variant: "cuda",
|
|
3585
|
+
cudaVersion: "12.8"
|
|
3586
|
+
},
|
|
3587
|
+
"darwin-arm64-cpu": {
|
|
3588
|
+
url: nextPlaidServerUrl("next-plaid-api-aarch64-apple-darwin"),
|
|
3589
|
+
sha256: "04d8d8ab6a49617076e1c0f4ff7756a555efd159890d5c3ea1adf54bae0238bb",
|
|
3590
|
+
archive: "raw",
|
|
3591
|
+
variant: "cpu"
|
|
3592
|
+
},
|
|
3593
|
+
"darwin-x64-cpu": {
|
|
3594
|
+
url: nextPlaidServerUrl("next-plaid-api-x86_64-apple-darwin"),
|
|
3595
|
+
sha256: "f3bca729db0043c7b609731ea095685fc2a72f0c2f58571b33c4fa52691fbe98",
|
|
3596
|
+
archive: "raw",
|
|
3597
|
+
variant: "cpu"
|
|
3598
|
+
}
|
|
3599
|
+
};
|
|
3600
|
+
/** Server asset for this platform-arch-variant, or undefined if unsupported. */
|
|
3601
|
+
function nextPlaidServerAsset(variant, platform = process.platform, arch = process.arch) {
|
|
3602
|
+
return NEXTPLAID_SERVER[`${platformArchKey(platform, arch)}-${variant}`];
|
|
3603
|
+
}
|
|
3604
|
+
/** True iff a promoted (SHA-pinned) server binary exists for this variant. */
|
|
3605
|
+
function nextPlaidServerPromoted(variant, platform = process.platform, arch = process.arch) {
|
|
3606
|
+
const asset = nextPlaidServerAsset(variant, platform, arch);
|
|
3607
|
+
return asset !== void 0 && asset.sha256.length > 0;
|
|
3608
|
+
}
|
|
3546
3609
|
//#endregion
|
|
3547
3610
|
//#region src/lib/toolbelt/extract.ts
|
|
3548
3611
|
/**
|
|
@@ -3783,6 +3846,36 @@ function colbertModelDir() {
|
|
|
3783
3846
|
function canonicalColbertModelDir() {
|
|
3784
3847
|
return path.resolve(colbertModelDir());
|
|
3785
3848
|
}
|
|
3849
|
+
/** Absolute path a provisioned next-plaid-api server binary lives at. */
|
|
3850
|
+
function nextPlaidServerBinaryPath(variant) {
|
|
3851
|
+
const suffix = variant === "cuda" ? "-cuda" : "";
|
|
3852
|
+
return path.join(PATHS.COLBERT_BIN_DIR, `next-plaid-api${suffix}${EXE_EXT}`);
|
|
3853
|
+
}
|
|
3854
|
+
/**
|
|
3855
|
+
* Provision the next-plaid-api server binary for the requested variant.
|
|
3856
|
+
* Lazy and separate from `provisionColbert()` (which owns the
|
|
3857
|
+
* colgrep/ORT/model trio): only the service backend calls this, so the
|
|
3858
|
+
* default colgrep path never pays for a server download.
|
|
3859
|
+
*
|
|
3860
|
+
* Fail-closed: unknown platform, unpromoted SHA (empty digest), or any
|
|
3861
|
+
* download/verify failure all report `reason` instead of throwing — the
|
|
3862
|
+
* caller falls back (cuda → cpu variant → colgrep → lexical).
|
|
3863
|
+
*/
|
|
3864
|
+
async function provisionNextPlaidServer(variant) {
|
|
3865
|
+
const asset = nextPlaidServerAsset(variant);
|
|
3866
|
+
if (!asset) return { reason: "no server asset for this platform" };
|
|
3867
|
+
if (asset.sha256.length === 0) return { reason: "server binary not yet promoted for this variant" };
|
|
3868
|
+
const dest = nextPlaidServerBinaryPath(variant);
|
|
3869
|
+
try {
|
|
3870
|
+
await withInstallLock("colbert-provision.lock", async () => {
|
|
3871
|
+
await provisionBinary(asset, dest);
|
|
3872
|
+
});
|
|
3873
|
+
return { path: dest };
|
|
3874
|
+
} catch (err) {
|
|
3875
|
+
consola.debug(`colbert: server provision failed (${variant}):`, err);
|
|
3876
|
+
return { reason: "server download/verify failed" };
|
|
3877
|
+
}
|
|
3878
|
+
}
|
|
3786
3879
|
/** Absolute path the provisioned ORT dylib lives at. */
|
|
3787
3880
|
function colbertOrtDylibPath() {
|
|
3788
3881
|
const lib = ortLibAsset()?.member ?? "libonnxruntime.so";
|
|
@@ -4672,6 +4765,10 @@ async function freshnessVerdict(workspace) {
|
|
|
4672
4765
|
* and current HEAD (when the head moved) UNION the working-tree porcelain
|
|
4673
4766
|
* set. Capped at DELTA_ENUM_CAP (beyond → truncated). Fail-closed: any git
|
|
4674
4767
|
* failure yields truncated (unprovably-small), so servability refuses.
|
|
4768
|
+
*
|
|
4769
|
+
* Exported for the service backend, which computes its own servability
|
|
4770
|
+
* against its own sidecar (it must NOT reuse `freshnessVerdict` — that
|
|
4771
|
+
* verdict describes the colgrep sidecar's state, not the service index's).
|
|
4675
4772
|
*/
|
|
4676
4773
|
async function gitDeltaFiles(workspace, baseHead, currentHead) {
|
|
4677
4774
|
const files = /* @__PURE__ */ new Set();
|
|
@@ -4984,7 +5081,7 @@ async function runSemanticSearch(opts) {
|
|
|
4984
5081
|
return {
|
|
4985
5082
|
status: "unavailable",
|
|
4986
5083
|
isError: true,
|
|
4987
|
-
notice: "no semantic index
|
|
5084
|
+
notice: "no semantic index yet — build started; retry mode:\"semantic\" in minutes or use code_search"
|
|
4988
5085
|
};
|
|
4989
5086
|
case "failed": return handleFailure(workspace, fresh.meta, false);
|
|
4990
5087
|
case "crashed": return handleFailure(workspace, fresh.meta, true);
|
|
@@ -4994,12 +5091,12 @@ async function runSemanticSearch(opts) {
|
|
|
4994
5091
|
kickBackgroundInit(workspace);
|
|
4995
5092
|
return {
|
|
4996
5093
|
status: "building",
|
|
4997
|
-
notice: "semantic index build
|
|
5094
|
+
notice: "semantic index build interrupted — rebuild started; retry mode:\"semantic\" in minutes"
|
|
4998
5095
|
};
|
|
4999
5096
|
}
|
|
5000
5097
|
return {
|
|
5001
5098
|
status: "building",
|
|
5002
|
-
notice: "semantic index
|
|
5099
|
+
notice: "semantic index building; retry mode:\"semantic\" in minutes or use code_search"
|
|
5003
5100
|
};
|
|
5004
5101
|
case "stale":
|
|
5005
5102
|
if (opts.serveStale && isServableVerdict(fresh)) {
|
|
@@ -5085,7 +5182,7 @@ async function repairCorruptIndex(workspace, meta) {
|
|
|
5085
5182
|
};
|
|
5086
5183
|
if (_searchIndexInFlight.has(wsKey) || isInitInFlight(workspace)) return {
|
|
5087
5184
|
status: "building",
|
|
5088
|
-
notice: "semantic index
|
|
5185
|
+
notice: "semantic index corrupt, writer active — results disabled until it exits"
|
|
5089
5186
|
};
|
|
5090
5187
|
const projectDir = await colbertProjectDir(workspace);
|
|
5091
5188
|
if (!projectDir) {
|
|
@@ -5093,7 +5190,7 @@ async function repairCorruptIndex(workspace, meta) {
|
|
|
5093
5190
|
return {
|
|
5094
5191
|
status: "unavailable",
|
|
5095
5192
|
isError: true,
|
|
5096
|
-
notice: "no semantic index
|
|
5193
|
+
notice: "no semantic index yet — build started; retry mode:\"semantic\" in minutes or use code_search"
|
|
5097
5194
|
};
|
|
5098
5195
|
}
|
|
5099
5196
|
if (!await quarantineProjectDir(projectDir)) {
|
|
@@ -5101,7 +5198,7 @@ async function repairCorruptIndex(workspace, meta) {
|
|
|
5101
5198
|
return {
|
|
5102
5199
|
status: "failed",
|
|
5103
5200
|
isError: true,
|
|
5104
|
-
notice: "semantic index
|
|
5201
|
+
notice: "semantic index corrupt, quarantine failed — close active colgrep processes and retry"
|
|
5105
5202
|
};
|
|
5106
5203
|
}
|
|
5107
5204
|
await writeColbertMeta(failedMeta).catch(() => {});
|
|
@@ -5109,7 +5206,7 @@ async function repairCorruptIndex(workspace, meta) {
|
|
|
5109
5206
|
return {
|
|
5110
5207
|
status: "failed",
|
|
5111
5208
|
isError: true,
|
|
5112
|
-
notice: attempts < 2 ? "semantic index
|
|
5209
|
+
notice: attempts < 2 ? "semantic index corrupt and quarantined — rebuild started; retry mode:\"semantic\" in minutes" : "semantic index repeatedly corrupt — rebuild capped, do NOT retry mode:\"semantic\"; use code_search"
|
|
5113
5210
|
};
|
|
5114
5211
|
}
|
|
5115
5212
|
/**
|
|
@@ -5171,7 +5268,7 @@ async function handleFailure(workspace, meta, crashedVerdict) {
|
|
|
5171
5268
|
return {
|
|
5172
5269
|
status: "failed",
|
|
5173
5270
|
isError: true,
|
|
5174
|
-
notice: backoffElapsed ? "semantic index
|
|
5271
|
+
notice: backoffElapsed ? "semantic index failed (inputs changed) — rebuild started; retry mode:\"semantic\" in minutes" : "semantic index failed — rebuild pending; retry mode:\"semantic\" in minutes"
|
|
5175
5272
|
};
|
|
5176
5273
|
}
|
|
5177
5274
|
const attempts = crashedVerdict ? (meta?.failedAttempts ?? 0) + 1 : meta?.failedAttempts ?? 1;
|
|
@@ -5201,13 +5298,13 @@ async function handleFailure(workspace, meta, crashedVerdict) {
|
|
|
5201
5298
|
return {
|
|
5202
5299
|
status: "failed",
|
|
5203
5300
|
isError: true,
|
|
5204
|
-
notice: "semantic index
|
|
5301
|
+
notice: "semantic index failed — re-index started; retry mode:\"semantic\" in minutes"
|
|
5205
5302
|
};
|
|
5206
5303
|
}
|
|
5207
5304
|
if (attempts < cap) return {
|
|
5208
5305
|
status: "failed",
|
|
5209
5306
|
isError: true,
|
|
5210
|
-
notice: "semantic index unavailable (recent build failure)
|
|
5307
|
+
notice: "semantic index unavailable (recent build failure) — retry mode:\"semantic\" in minutes"
|
|
5211
5308
|
};
|
|
5212
5309
|
consola.warn(`colbert: index ${cls}, giving up (attempts=${attempts}) for ${workspace}`);
|
|
5213
5310
|
return {
|
|
@@ -5286,7 +5383,7 @@ async function spawnSearch(opts) {
|
|
|
5286
5383
|
consola.debug(`colbert: search detached (indexing) for ${opts.workspace}`);
|
|
5287
5384
|
return {
|
|
5288
5385
|
status: "building",
|
|
5289
|
-
notice: "semantic index
|
|
5386
|
+
notice: "semantic index updating in background; retry mode:\"semantic\" in minutes"
|
|
5290
5387
|
};
|
|
5291
5388
|
}
|
|
5292
5389
|
if (raced.kind === "error") {
|
|
@@ -5358,13 +5455,13 @@ function parseAndTrim(stdout, workspace) {
|
|
|
5358
5455
|
...typeof unit.end_line === "number" ? { endLine: unit.end_line } : {},
|
|
5359
5456
|
...typeof unit.name === "string" ? { name: unit.name } : {},
|
|
5360
5457
|
score: typeof item.score === "number" ? round2(item.score) : 0,
|
|
5361
|
-
snippet: buildSnippet(unit)
|
|
5458
|
+
snippet: buildSnippet$1(unit)
|
|
5362
5459
|
});
|
|
5363
5460
|
}
|
|
5364
5461
|
return out;
|
|
5365
5462
|
}
|
|
5366
5463
|
/** snippet = signature + first few representative lines (NOT full code). */
|
|
5367
|
-
function buildSnippet(unit) {
|
|
5464
|
+
function buildSnippet$1(unit) {
|
|
5368
5465
|
const sig = typeof unit.signature === "string" ? unit.signature.trim() : "";
|
|
5369
5466
|
const code = typeof unit.code === "string" ? unit.code : "";
|
|
5370
5467
|
if (!code) return sig;
|
|
@@ -5619,6 +5716,959 @@ async function runInit(workspace) {
|
|
|
5619
5716
|
await writeColbertMeta(finalMeta).catch(() => {});
|
|
5620
5717
|
}
|
|
5621
5718
|
//#endregion
|
|
5622
|
-
|
|
5719
|
+
//#region src/lib/colbert/service.ts
|
|
5720
|
+
/**
|
|
5721
|
+
* next-plaid-api service client + managed lifecycle (Phase 2e).
|
|
5722
|
+
*
|
|
5723
|
+
* The semantic backend moves from colgrep CLI-per-invocation (every query
|
|
5724
|
+
* re-loads ORT + model + index) to a persistent `next-plaid-api` server
|
|
5725
|
+
* (model warm, PLAID mmap'd, lock-free reads, batched async writes).
|
|
5726
|
+
* This module owns the HTTP protocol and the child-process lifecycle;
|
|
5727
|
+
* the query-path switch (runner → service) lands separately once a
|
|
5728
|
+
* provisioned binary exists (see the CI build workflow).
|
|
5729
|
+
*
|
|
5730
|
+
* API surface (next-plaid-api v1.7.0, verified from upstream README):
|
|
5731
|
+
* GET /health → system + per-index summaries
|
|
5732
|
+
* POST /indices {name, config} → declare index (409 taken)
|
|
5733
|
+
* POST /indices/{name}/update_with_encoding → 202 (async batch)
|
|
5734
|
+
* DELETE /indices/{name}/documents {condition, parameters} → 202
|
|
5735
|
+
* POST /indices/{name}/search_with_encoding → ranked hits + metadata
|
|
5736
|
+
*
|
|
5737
|
+
* Conventions shared with the colbert sidecar: never log response bodies
|
|
5738
|
+
* (they embed source code), bound every request with a timeout, fail
|
|
5739
|
+
* closed (throw → caller falls back to lexical).
|
|
5740
|
+
*/
|
|
5741
|
+
const DEFAULT_TIMEOUT_MS = 3e4;
|
|
5742
|
+
async function fetchJson(url, init, timeoutMs) {
|
|
5743
|
+
const ac = new AbortController();
|
|
5744
|
+
const timer = setTimeout(() => ac.abort(/* @__PURE__ */ new Error("service request timeout")), timeoutMs);
|
|
5745
|
+
timer.unref?.();
|
|
5746
|
+
try {
|
|
5747
|
+
const res = await fetch(url, {
|
|
5748
|
+
...init,
|
|
5749
|
+
signal: ac.signal
|
|
5750
|
+
});
|
|
5751
|
+
const text = await res.text();
|
|
5752
|
+
let body = null;
|
|
5753
|
+
try {
|
|
5754
|
+
body = text.length > 0 ? JSON.parse(text) : null;
|
|
5755
|
+
} catch {
|
|
5756
|
+
body = null;
|
|
5757
|
+
}
|
|
5758
|
+
return {
|
|
5759
|
+
status: res.status,
|
|
5760
|
+
body
|
|
5761
|
+
};
|
|
5762
|
+
} finally {
|
|
5763
|
+
clearTimeout(timer);
|
|
5764
|
+
}
|
|
5765
|
+
}
|
|
5766
|
+
/**
|
|
5767
|
+
* Thin HTTP client over a running next-plaid-api server. Construct with
|
|
5768
|
+
* the base URL (`http://127.0.0.1:PORT`); use `startManagedServer` below
|
|
5769
|
+
* for process lifecycle, or point at an externally managed server.
|
|
5770
|
+
*/
|
|
5771
|
+
var NextPlaidClient = class {
|
|
5772
|
+
baseUrl;
|
|
5773
|
+
timeoutMs;
|
|
5774
|
+
constructor(baseUrl, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
5775
|
+
this.baseUrl = baseUrl.replace(/\/+$/, "");
|
|
5776
|
+
this.timeoutMs = timeoutMs;
|
|
5777
|
+
}
|
|
5778
|
+
async health() {
|
|
5779
|
+
const { status, body } = await fetchJson(`${this.baseUrl}/health`, {}, this.timeoutMs);
|
|
5780
|
+
if (status !== 200 || typeof body !== "object" || body === null) return {
|
|
5781
|
+
ok: false,
|
|
5782
|
+
indices: []
|
|
5783
|
+
};
|
|
5784
|
+
const b = body;
|
|
5785
|
+
return {
|
|
5786
|
+
ok: b.status === "healthy",
|
|
5787
|
+
indices: (b.indices ?? []).map((i) => ({
|
|
5788
|
+
name: typeof i.name === "string" ? i.name : "",
|
|
5789
|
+
num_documents: typeof i.num_documents === "number" ? i.num_documents : 0,
|
|
5790
|
+
num_embeddings: typeof i.num_embeddings === "number" ? i.num_embeddings : 0,
|
|
5791
|
+
dimension: typeof i.dimension === "number" ? i.dimension : 0
|
|
5792
|
+
})),
|
|
5793
|
+
model: b.model?.name
|
|
5794
|
+
};
|
|
5795
|
+
}
|
|
5796
|
+
/** Declare an index (idempotent: 409 taken is success). */
|
|
5797
|
+
async ensureIndex(name, config = {}) {
|
|
5798
|
+
const { status, body } = await fetchJson(`${this.baseUrl}/indices`, {
|
|
5799
|
+
method: "POST",
|
|
5800
|
+
headers: { "content-type": "application/json" },
|
|
5801
|
+
body: JSON.stringify({
|
|
5802
|
+
name,
|
|
5803
|
+
config: {
|
|
5804
|
+
nbits: config.nbits ?? 4,
|
|
5805
|
+
...config.pool_factor !== void 0 ? { pool_factor: config.pool_factor } : {},
|
|
5806
|
+
...config.start_from_scratch !== void 0 ? { start_from_scratch: config.start_from_scratch } : {}
|
|
5807
|
+
}
|
|
5808
|
+
})
|
|
5809
|
+
}, this.timeoutMs);
|
|
5810
|
+
if (status === 200 || status === 201 || status === 409) return;
|
|
5811
|
+
throw new Error(`ensureIndex ${name} failed: HTTP ${status} (${describeError(body)})`);
|
|
5812
|
+
}
|
|
5813
|
+
/**
|
|
5814
|
+
* Add/update documents (server encodes text). 202 = accepted into the
|
|
5815
|
+
* async batch queue (NOT yet searchable — the server merges within
|
|
5816
|
+
* ~100ms/300 docs). Never throws for queue-full: maps 503 to a typed
|
|
5817
|
+
* error the caller retries after backoff.
|
|
5818
|
+
*/
|
|
5819
|
+
async updateDocuments(index, documents, metadata, poolFactor = 2) {
|
|
5820
|
+
const { status, body } = await fetchJson(`${this.baseUrl}/indices/${encodeURIComponent(index)}/update_with_encoding`, {
|
|
5821
|
+
method: "POST",
|
|
5822
|
+
headers: { "content-type": "application/json" },
|
|
5823
|
+
body: JSON.stringify({
|
|
5824
|
+
documents,
|
|
5825
|
+
metadata,
|
|
5826
|
+
pool_factor: poolFactor
|
|
5827
|
+
})
|
|
5828
|
+
}, this.timeoutMs);
|
|
5829
|
+
if (status === 202) return;
|
|
5830
|
+
if (status === 503) throw new ServiceBusyError(index);
|
|
5831
|
+
throw new Error(`update ${index} failed: HTTP ${status} (${describeError(body)})`);
|
|
5832
|
+
}
|
|
5833
|
+
/** Delete by SQL predicate (batched server-side, 202 accepted). */
|
|
5834
|
+
async deleteDocuments(index, condition, parameters = []) {
|
|
5835
|
+
const { status, body } = await fetchJson(`${this.baseUrl}/indices/${encodeURIComponent(index)}/documents`, {
|
|
5836
|
+
method: "DELETE",
|
|
5837
|
+
headers: { "content-type": "application/json" },
|
|
5838
|
+
body: JSON.stringify({
|
|
5839
|
+
condition,
|
|
5840
|
+
parameters
|
|
5841
|
+
})
|
|
5842
|
+
}, this.timeoutMs);
|
|
5843
|
+
if (status === 202) return;
|
|
5844
|
+
if (status === 404) return;
|
|
5845
|
+
if (status === 503) throw new ServiceBusyError(index);
|
|
5846
|
+
throw new Error(`delete ${index} failed: HTTP ${status} (${describeError(body)})`);
|
|
5847
|
+
}
|
|
5848
|
+
/**
|
|
5849
|
+
* Hybrid search (semantic + FTS5 keyword, server-side RRF fusion).
|
|
5850
|
+
* `fileGlob` scopes via metadata filter when provided (the indexer
|
|
5851
|
+
* stores `file` per doc). Returns hits in ranked order.
|
|
5852
|
+
*/
|
|
5853
|
+
async search(index, query, opts = {}) {
|
|
5854
|
+
const top_k = Math.max(1, Math.floor(opts.topK ?? 15));
|
|
5855
|
+
const body = {
|
|
5856
|
+
queries: [query],
|
|
5857
|
+
params: {
|
|
5858
|
+
top_k,
|
|
5859
|
+
...opts.nIvfProbe !== void 0 ? { n_ivf_probe: opts.nIvfProbe } : {}
|
|
5860
|
+
}
|
|
5861
|
+
};
|
|
5862
|
+
if (opts.textQuery) {
|
|
5863
|
+
body.text_query = [opts.textQuery];
|
|
5864
|
+
body.alpha = opts.alpha ?? .75;
|
|
5865
|
+
body.fusion = "relative_score";
|
|
5866
|
+
}
|
|
5867
|
+
if (opts.fileGlob) {
|
|
5868
|
+
body.filter_condition = "file GLOB ?";
|
|
5869
|
+
body.filter_parameters = [opts.fileGlob];
|
|
5870
|
+
}
|
|
5871
|
+
const { status, body: res } = await fetchJson(`${this.baseUrl}/indices/${encodeURIComponent(index)}/search_with_encoding`, {
|
|
5872
|
+
method: "POST",
|
|
5873
|
+
headers: { "content-type": "application/json" },
|
|
5874
|
+
body: JSON.stringify(body)
|
|
5875
|
+
}, this.timeoutMs);
|
|
5876
|
+
if (status === 404) return [];
|
|
5877
|
+
if (status === 503) throw new ServiceBusyError(index);
|
|
5878
|
+
if (status !== 200) throw new Error(`search ${index} failed: HTTP ${status} (${describeError(res)})`);
|
|
5879
|
+
return toHits(res);
|
|
5880
|
+
}
|
|
5881
|
+
};
|
|
5882
|
+
/** Queue-full signal: retry after backoff, never fatal. */
|
|
5883
|
+
var ServiceBusyError = class extends Error {
|
|
5884
|
+
index;
|
|
5885
|
+
constructor(index) {
|
|
5886
|
+
super(`next-plaid index ${index} busy (queue full); retry after backoff`);
|
|
5887
|
+
this.name = "ServiceBusyError";
|
|
5888
|
+
this.index = index;
|
|
5889
|
+
}
|
|
5890
|
+
};
|
|
5891
|
+
function describeError(body) {
|
|
5892
|
+
if (typeof body === "object" && body !== null) {
|
|
5893
|
+
const b = body;
|
|
5894
|
+
const code = typeof b.code === "string" ? b.code : "?";
|
|
5895
|
+
const message = typeof b.message === "string" ? b.message : "";
|
|
5896
|
+
return `${code}${message ? `: ${message.slice(0, 200)}` : ""}`;
|
|
5897
|
+
}
|
|
5898
|
+
return "unparseable response";
|
|
5899
|
+
}
|
|
5900
|
+
/**
|
|
5901
|
+
* Map the API search response to file-anchored hits. Metadata carries the
|
|
5902
|
+
* unit fields the indexer stored (file/line/end_line/name/signature);
|
|
5903
|
+
* rows missing a file are dropped (never surface an unanchored hit).
|
|
5904
|
+
*/
|
|
5905
|
+
function toHits(res) {
|
|
5906
|
+
const out = [];
|
|
5907
|
+
for (const r of res.results ?? []) {
|
|
5908
|
+
const ids = r.document_ids ?? [];
|
|
5909
|
+
const scores = r.scores ?? [];
|
|
5910
|
+
const metas = r.metadata ?? [];
|
|
5911
|
+
for (let i = 0; i < ids.length; i++) {
|
|
5912
|
+
const meta = metas[i] ?? {};
|
|
5913
|
+
const file = meta.file;
|
|
5914
|
+
if (typeof file !== "string" || file.length === 0) continue;
|
|
5915
|
+
const line = meta.line;
|
|
5916
|
+
out.push({
|
|
5917
|
+
file,
|
|
5918
|
+
line: typeof line === "number" ? line : 1,
|
|
5919
|
+
...typeof meta.end_line === "number" ? { end_line: meta.end_line } : {},
|
|
5920
|
+
...typeof meta.name === "string" ? { name: meta.name } : {},
|
|
5921
|
+
score: typeof scores[i] === "number" ? scores[i] : 0,
|
|
5922
|
+
metadata: meta
|
|
5923
|
+
});
|
|
5924
|
+
}
|
|
5925
|
+
}
|
|
5926
|
+
return out;
|
|
5927
|
+
}
|
|
5928
|
+
/** Find a free loopback port (TOCTOU-racy by nature; retry on collision). */
|
|
5929
|
+
async function freePort() {
|
|
5930
|
+
return new Promise((resolve, reject) => {
|
|
5931
|
+
const s = net.createServer();
|
|
5932
|
+
s.on("error", reject);
|
|
5933
|
+
s.listen(0, "127.0.0.1", () => {
|
|
5934
|
+
const addr = s.address();
|
|
5935
|
+
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
|
5936
|
+
s.close((err) => err ? reject(err) : resolve(port));
|
|
5937
|
+
});
|
|
5938
|
+
});
|
|
5939
|
+
}
|
|
5940
|
+
/**
|
|
5941
|
+
* Spawn the server, wait for `/health`, return a managed handle. Throws
|
|
5942
|
+
* when the binary is missing, the port never becomes healthy, or the
|
|
5943
|
+
* child exits early (stderr is captured, truncated, never logged raw —
|
|
5944
|
+
* it can embed paths, not source, but the discipline is cheap).
|
|
5945
|
+
*/
|
|
5946
|
+
/**
|
|
5947
|
+
* Build the next-plaid-api argv (exported for unit tests; production
|
|
5948
|
+
* goes through `startManagedServer`). `--int8`/`--cuda` both require
|
|
5949
|
+
* `--model` (upstream CLI contract) and are never passed alone.
|
|
5950
|
+
*/
|
|
5951
|
+
function serverArgv(opts, port) {
|
|
5952
|
+
return [
|
|
5953
|
+
"--host",
|
|
5954
|
+
"127.0.0.1",
|
|
5955
|
+
"--port",
|
|
5956
|
+
String(port),
|
|
5957
|
+
"--index-dir",
|
|
5958
|
+
opts.indexDir,
|
|
5959
|
+
...opts.modelDir ? ["--model", opts.modelDir] : [],
|
|
5960
|
+
...opts.modelDir && opts.int8 !== false ? ["--int8"] : [],
|
|
5961
|
+
...opts.modelDir && opts.cuda === true ? ["--cuda"] : [],
|
|
5962
|
+
"--parallel",
|
|
5963
|
+
String(Math.max(1, Math.floor(opts.parallel ?? 1)))
|
|
5964
|
+
];
|
|
5965
|
+
}
|
|
5966
|
+
async function startManagedServer(opts) {
|
|
5967
|
+
const port = opts.port ?? await freePort();
|
|
5968
|
+
const args = opts.argv ?? serverArgv(opts, port);
|
|
5969
|
+
let child;
|
|
5970
|
+
try {
|
|
5971
|
+
child = spawn(opts.binaryPath, args, {
|
|
5972
|
+
env: {
|
|
5973
|
+
...process$1.env,
|
|
5974
|
+
...opts.env
|
|
5975
|
+
},
|
|
5976
|
+
stdio: [
|
|
5977
|
+
"ignore",
|
|
5978
|
+
"pipe",
|
|
5979
|
+
"pipe"
|
|
5980
|
+
],
|
|
5981
|
+
windowsHide: true
|
|
5982
|
+
});
|
|
5983
|
+
} catch (err) {
|
|
5984
|
+
throw new Error(`next-plaid server failed to spawn: ${err.message}`, { cause: err });
|
|
5985
|
+
}
|
|
5986
|
+
trackChild(child);
|
|
5987
|
+
child.on("error", () => {
|
|
5988
|
+
untrackChild(child);
|
|
5989
|
+
});
|
|
5990
|
+
let stderrTail = "";
|
|
5991
|
+
child.stderr?.setEncoding("utf8");
|
|
5992
|
+
child.stderr?.on("data", (chunk) => {
|
|
5993
|
+
stderrTail = (stderrTail + chunk).slice(-4096);
|
|
5994
|
+
});
|
|
5995
|
+
const url = `http://127.0.0.1:${port}`;
|
|
5996
|
+
const client = new NextPlaidClient(url);
|
|
5997
|
+
const deadline = Date.now() + (opts.startupTimeoutMs ?? 6e4);
|
|
5998
|
+
let exited = null;
|
|
5999
|
+
let spawnFailed = false;
|
|
6000
|
+
child.on("exit", (code) => {
|
|
6001
|
+
exited = code;
|
|
6002
|
+
});
|
|
6003
|
+
child.on("error", () => {
|
|
6004
|
+
spawnFailed = true;
|
|
6005
|
+
});
|
|
6006
|
+
child.on("close", () => {
|
|
6007
|
+
if (exited === null) spawnFailed = true;
|
|
6008
|
+
});
|
|
6009
|
+
try {
|
|
6010
|
+
for (;;) {
|
|
6011
|
+
if (exited !== null || spawnFailed) throw new Error(`next-plaid server exited during startup${exited !== null ? ` (code ${exited})` : ""}: ${stderrTail.slice(-500)}`);
|
|
6012
|
+
try {
|
|
6013
|
+
if ((await client.health()).ok) return {
|
|
6014
|
+
url,
|
|
6015
|
+
client,
|
|
6016
|
+
stop: () => stopServer(child)
|
|
6017
|
+
};
|
|
6018
|
+
} catch {}
|
|
6019
|
+
if (Date.now() > deadline) throw new Error(`next-plaid server not healthy after startup budget: ${stderrTail.slice(-500)}`);
|
|
6020
|
+
await new Promise((r) => {
|
|
6021
|
+
setTimeout(() => r(), 250).unref?.();
|
|
6022
|
+
});
|
|
6023
|
+
}
|
|
6024
|
+
} catch (err) {
|
|
6025
|
+
await stopServer(child).catch(() => {});
|
|
6026
|
+
throw err;
|
|
6027
|
+
}
|
|
6028
|
+
}
|
|
6029
|
+
async function stopServer(child) {
|
|
6030
|
+
try {
|
|
6031
|
+
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
6032
|
+
if (child.pid === void 0) return;
|
|
6033
|
+
let finished = false;
|
|
6034
|
+
let doneResolve = () => {};
|
|
6035
|
+
const done = new Promise((resolve) => {
|
|
6036
|
+
doneResolve = resolve;
|
|
6037
|
+
});
|
|
6038
|
+
const finish = () => {
|
|
6039
|
+
if (finished) return;
|
|
6040
|
+
finished = true;
|
|
6041
|
+
clearTimeout(escalation);
|
|
6042
|
+
clearTimeout(backstop);
|
|
6043
|
+
doneResolve();
|
|
6044
|
+
};
|
|
6045
|
+
child.once("exit", finish);
|
|
6046
|
+
child.once("close", finish);
|
|
6047
|
+
const escalation = setTimeout(() => {
|
|
6048
|
+
try {
|
|
6049
|
+
child.kill("SIGKILL");
|
|
6050
|
+
} catch {}
|
|
6051
|
+
}, 5e3);
|
|
6052
|
+
escalation.unref?.();
|
|
6053
|
+
const backstop = setTimeout(finish, 15e3);
|
|
6054
|
+
backstop.unref?.();
|
|
6055
|
+
try {
|
|
6056
|
+
child.kill("SIGTERM");
|
|
6057
|
+
} catch {
|
|
6058
|
+
finish();
|
|
6059
|
+
return;
|
|
6060
|
+
}
|
|
6061
|
+
if (process$1.platform === "win32") try {
|
|
6062
|
+
const { spawnSync } = await import("node:child_process");
|
|
6063
|
+
if (child.pid) spawnSync("taskkill", [
|
|
6064
|
+
"/T",
|
|
6065
|
+
"/F",
|
|
6066
|
+
"/PID",
|
|
6067
|
+
String(child.pid)
|
|
6068
|
+
], {
|
|
6069
|
+
stdio: "ignore",
|
|
6070
|
+
windowsHide: true
|
|
6071
|
+
});
|
|
6072
|
+
} catch {}
|
|
6073
|
+
await done;
|
|
6074
|
+
} finally {
|
|
6075
|
+
untrackChild(child);
|
|
6076
|
+
}
|
|
6077
|
+
}
|
|
6078
|
+
/** CPU-aware default parallelism for the managed server. */
|
|
6079
|
+
function serverParallelSessions() {
|
|
6080
|
+
const raw = Number(process$1.env.GH_ROUTER_NP_PARALLEL);
|
|
6081
|
+
if (Number.isSafeInteger(raw) && raw > 0) return raw;
|
|
6082
|
+
let cpus = 4;
|
|
6083
|
+
try {
|
|
6084
|
+
cpus = os$1.cpus().length;
|
|
6085
|
+
} catch {}
|
|
6086
|
+
return Math.max(1, Math.floor(cpus * .25));
|
|
6087
|
+
}
|
|
6088
|
+
/** Per-workspace index name: stable hash of the canonical workspace path. */
|
|
6089
|
+
function indexNameForWorkspace(canonicalWorkspace) {
|
|
6090
|
+
let h = 2166136261;
|
|
6091
|
+
for (let i = 0; i < canonicalWorkspace.length; i++) {
|
|
6092
|
+
h ^= canonicalWorkspace.charCodeAt(i);
|
|
6093
|
+
h = Math.imul(h, 16777619);
|
|
6094
|
+
}
|
|
6095
|
+
return `ws-${(h >>> 0).toString(16).padStart(8, "0")}`;
|
|
6096
|
+
}
|
|
6097
|
+
//#endregion
|
|
6098
|
+
//#region src/lib/colbert/units.ts
|
|
6099
|
+
/**
|
|
6100
|
+
* Semantic code-unit extraction (Phase 2b).
|
|
6101
|
+
*
|
|
6102
|
+
* The next-plaid service is a generic multi-vector document store — unlike
|
|
6103
|
+
* colgrep it does NOT parse code. This module owns the code-aware half:
|
|
6104
|
+
* tree-sitter parsing (reusing the warm grammar bundle + definition tables
|
|
6105
|
+
* from `~/lib/tree-sitter-grammars`), unit scoping (top-level + class-like
|
|
6106
|
+
* members — the same navigable scope as outlines), and structured-text
|
|
6107
|
+
* construction for embedding.
|
|
6108
|
+
*
|
|
6109
|
+
* Unit text mirrors colgrep's high-signal layers with the cheap subset:
|
|
6110
|
+
* name, signature (first line), leading doc comment, normalized file path,
|
|
6111
|
+
* and capped body. Call-graph / data-flow layers are deliberately omitted
|
|
6112
|
+
* in v1 (that analysis is computed by colgrep but never returned in our
|
|
6113
|
+
* responses today — see the Phase 2 plan — so nothing observable is lost).
|
|
6114
|
+
*
|
|
6115
|
+
* Pure file-level functions (no index state here): the service owns
|
|
6116
|
+
* storage/incremental logic; the freshness sidecar owns per-file hashes.
|
|
6117
|
+
* `extractUnits` never throws — per-file failures surface as `notice`.
|
|
6118
|
+
*/
|
|
6119
|
+
/** Max unit body chars embedded (~500 tokens). Longer bodies truncate. */
|
|
6120
|
+
const UNIT_MAX_BODY_CHARS = 2e3;
|
|
6121
|
+
/** Max signature chars (first line(s) of the unit). */
|
|
6122
|
+
const UNIT_MAX_SIGNATURE_CHARS = 300;
|
|
6123
|
+
/**
|
|
6124
|
+
* Normalize a file path for embedding: separators → spaces, snake_case /
|
|
6125
|
+
* CamelCase split (mirrors colgrep's path normalization AND the BM25F
|
|
6126
|
+
* `file_path` field, so lexical and semantic agree on path tokens).
|
|
6127
|
+
* `src/utils/HttpClient.ts` → `src utils Http Client ts`.
|
|
6128
|
+
*/
|
|
6129
|
+
function normalizePathForEmbedding(relPath) {
|
|
6130
|
+
return relPath.replace(/[/\\]/g, " ").replace(/\.[A-Za-z0-9]+$/, " $&").split(/[^A-Za-z0-9]+/).filter(Boolean).flatMap((piece) => {
|
|
6131
|
+
return piece.match(/[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+[0-9]*|[A-Z]+[0-9]*|[0-9]+/g) ?? [piece];
|
|
6132
|
+
}).join(" ");
|
|
6133
|
+
}
|
|
6134
|
+
/**
|
|
6135
|
+
* Leading doc comment for the unit starting at 1-indexed `startLine`:
|
|
6136
|
+
* consecutive comment-ish lines directly above (//, #, *, <!--, """, ''',
|
|
6137
|
+
* ///), blank-line-terminated. Language-agnostic and AST-free — runs on
|
|
6138
|
+
* raw source lines so it needs no per-language comment grammar.
|
|
6139
|
+
*/
|
|
6140
|
+
function leadingDocComment(sourceLines, startLine1) {
|
|
6141
|
+
const out = [];
|
|
6142
|
+
for (let i = startLine1 - 2; i >= 0; i--) {
|
|
6143
|
+
const line = sourceLines[i].trim();
|
|
6144
|
+
if (line.length === 0) break;
|
|
6145
|
+
if (line.startsWith("//") || line.startsWith("#") || line.startsWith("*") || line.startsWith("<!--") || line.startsWith("\"\"\"") || line.startsWith("'''")) {
|
|
6146
|
+
out.unshift(sourceLines[i].trim());
|
|
6147
|
+
if (out.length >= 10) break;
|
|
6148
|
+
} else break;
|
|
6149
|
+
}
|
|
6150
|
+
return out.length > 0 ? out.join("\n") : void 0;
|
|
6151
|
+
}
|
|
6152
|
+
/**
|
|
6153
|
+
* Structured text for one unit — what gets embedded. Field order mirrors
|
|
6154
|
+
* colgrep's (name → signature → description → path → code) so ranking
|
|
6155
|
+
* behavior stays close to the ColBERT sidecar it replaces.
|
|
6156
|
+
*/
|
|
6157
|
+
function buildUnitText(unit, relPath) {
|
|
6158
|
+
const parts = [`${labelForKind(unit.kind)}: ${unit.name}`];
|
|
6159
|
+
if (unit.signature && unit.signature !== unit.name) parts.push(`Signature: ${unit.signature}`);
|
|
6160
|
+
if (unit.docstring) parts.push(`Description: ${unit.docstring}`);
|
|
6161
|
+
parts.push(`File: ${normalizePathForEmbedding(relPath)}`);
|
|
6162
|
+
parts.push(`Code:\n${unit.code}`);
|
|
6163
|
+
return parts.join("\n");
|
|
6164
|
+
}
|
|
6165
|
+
function labelForKind(kind) {
|
|
6166
|
+
if (kind.includes("class")) return "Class";
|
|
6167
|
+
if (kind.includes("interface")) return "Interface";
|
|
6168
|
+
if (kind.includes("struct")) return "Struct";
|
|
6169
|
+
if (kind.includes("enum")) return "Enum";
|
|
6170
|
+
if (kind.includes("namespace") || kind.includes("module")) return "Namespace";
|
|
6171
|
+
if (kind.includes("method") || kind.includes("function")) return "Function";
|
|
6172
|
+
if (kind.includes("property")) return "Property";
|
|
6173
|
+
if (kind.includes("field")) return "Field";
|
|
6174
|
+
return "Symbol";
|
|
6175
|
+
}
|
|
6176
|
+
/**
|
|
6177
|
+
* Extract indexable units from one file. Read + parse + walk; frees the
|
|
6178
|
+
* tree before returning (units carry plain strings, never live nodes).
|
|
6179
|
+
* Never throws — failures surface as `notice` with empty `units`.
|
|
6180
|
+
*/
|
|
6181
|
+
async function extractUnits(absPath, relPath, signal) {
|
|
6182
|
+
if (signal?.aborted) return {
|
|
6183
|
+
units: [],
|
|
6184
|
+
language: null
|
|
6185
|
+
};
|
|
6186
|
+
const language = getLanguageKeyForPath(absPath);
|
|
6187
|
+
if (!language) return {
|
|
6188
|
+
units: [],
|
|
6189
|
+
language: null,
|
|
6190
|
+
notice: "no grammar for this file type"
|
|
6191
|
+
};
|
|
6192
|
+
let size;
|
|
6193
|
+
try {
|
|
6194
|
+
size = statSync(absPath).size;
|
|
6195
|
+
} catch {
|
|
6196
|
+
return {
|
|
6197
|
+
units: [],
|
|
6198
|
+
language,
|
|
6199
|
+
notice: "unreadable file"
|
|
6200
|
+
};
|
|
6201
|
+
}
|
|
6202
|
+
if (size > 1048576) return {
|
|
6203
|
+
units: [],
|
|
6204
|
+
language,
|
|
6205
|
+
notice: "file too large"
|
|
6206
|
+
};
|
|
6207
|
+
const grammars = await getGrammarBundle().ready;
|
|
6208
|
+
if (signal?.aborted) return {
|
|
6209
|
+
units: [],
|
|
6210
|
+
language
|
|
6211
|
+
};
|
|
6212
|
+
const lang = grammars.get(language);
|
|
6213
|
+
const defTypes = DEFINITION_NODE_TYPES[language];
|
|
6214
|
+
if (!lang || !defTypes) return {
|
|
6215
|
+
units: [],
|
|
6216
|
+
language,
|
|
6217
|
+
notice: "grammar unavailable"
|
|
6218
|
+
};
|
|
6219
|
+
let source;
|
|
6220
|
+
try {
|
|
6221
|
+
source = await readFile(absPath, "utf8");
|
|
6222
|
+
} catch {
|
|
6223
|
+
return {
|
|
6224
|
+
units: [],
|
|
6225
|
+
language,
|
|
6226
|
+
notice: "unreadable file"
|
|
6227
|
+
};
|
|
6228
|
+
}
|
|
6229
|
+
if (signal?.aborted) return {
|
|
6230
|
+
units: [],
|
|
6231
|
+
language
|
|
6232
|
+
};
|
|
6233
|
+
let parser = null;
|
|
6234
|
+
let tree = null;
|
|
6235
|
+
try {
|
|
6236
|
+
parser = new Parser();
|
|
6237
|
+
parser.setLanguage(lang);
|
|
6238
|
+
tree = parser.parse(source);
|
|
6239
|
+
if (!tree) return {
|
|
6240
|
+
units: [],
|
|
6241
|
+
language,
|
|
6242
|
+
notice: "parse failed"
|
|
6243
|
+
};
|
|
6244
|
+
const sourceLines = source.split("\n");
|
|
6245
|
+
const slashRel = relPath.replace(/\\/g, "/");
|
|
6246
|
+
const units = [];
|
|
6247
|
+
for (const u of collectUnitNodes(tree.rootNode, defTypes, signal)) {
|
|
6248
|
+
if (signal?.aborted) break;
|
|
6249
|
+
const line = u.node.startPosition.row + 1;
|
|
6250
|
+
const endLine = u.node.endPosition.row + 1;
|
|
6251
|
+
const firstLine = (sourceLines[line - 1] ?? "").trim().slice(0, UNIT_MAX_SIGNATURE_CHARS);
|
|
6252
|
+
const body = u.node.text.length > 2e3 ? u.node.text.slice(0, UNIT_MAX_BODY_CHARS) + "\n…[truncated]" : u.node.text;
|
|
6253
|
+
units.push({
|
|
6254
|
+
unit_id: `${slashRel}:${line}:${u.name}`,
|
|
6255
|
+
file: slashRel,
|
|
6256
|
+
name: u.name,
|
|
6257
|
+
kind: u.kind,
|
|
6258
|
+
line,
|
|
6259
|
+
end_line: endLine,
|
|
6260
|
+
signature: firstLine,
|
|
6261
|
+
code: body,
|
|
6262
|
+
...leadingDocComment(sourceLines, line) !== void 0 ? { docstring: leadingDocComment(sourceLines, line) } : {}
|
|
6263
|
+
});
|
|
6264
|
+
}
|
|
6265
|
+
units.sort((a, b) => a.line - b.line);
|
|
6266
|
+
return {
|
|
6267
|
+
units,
|
|
6268
|
+
language
|
|
6269
|
+
};
|
|
6270
|
+
} catch {
|
|
6271
|
+
return {
|
|
6272
|
+
units: [],
|
|
6273
|
+
language,
|
|
6274
|
+
notice: "parse failed"
|
|
6275
|
+
};
|
|
6276
|
+
} finally {
|
|
6277
|
+
if (tree) try {
|
|
6278
|
+
tree.delete();
|
|
6279
|
+
} catch {}
|
|
6280
|
+
if (parser) try {
|
|
6281
|
+
parser.delete();
|
|
6282
|
+
} catch {}
|
|
6283
|
+
}
|
|
6284
|
+
}
|
|
6285
|
+
//#endregion
|
|
6286
|
+
//#region src/lib/colbert/service-backend.ts
|
|
6287
|
+
/**
|
|
6288
|
+
* Service-backed semantic search orchestration (Phase 2e query path).
|
|
6289
|
+
*
|
|
6290
|
+
* Selects between the legacy colgrep CLI backend and the persistent
|
|
6291
|
+
* next-plaid-api server via `GH_ROUTER_SEMANTIC_BACKEND` (`colgrep` default,
|
|
6292
|
+
* `service` opt-in). The service path owns its own per-workspace state
|
|
6293
|
+
* (`svc-<hash>.json` sidecars — never touches the colgrep sidecar, so
|
|
6294
|
+
* flipping the flag back and forth loses nothing) and degrades to the
|
|
6295
|
+
* colgrep path on ANY service failure (missing binary, unhealthy server,
|
|
6296
|
+
* unknown index, busy queue).
|
|
6297
|
+
*
|
|
6298
|
+
* Indexing model: on-demand background populate. First query for a
|
|
6299
|
+
* workspace kicks `populateWorkspace` (enumerate → extractUnits →
|
|
6300
|
+
* batched updateDocuments) and returns `unavailable` meanwhile — the same
|
|
6301
|
+
* transparent-fallback contract as the CLI backend. Watcher-driven
|
|
6302
|
+
* proactive refresh lands separately (Phase 2d wiring).
|
|
6303
|
+
*
|
|
6304
|
+
* Binary resolution (no provisioner yet — CI artifacts pending):
|
|
6305
|
+
* 1. `GH_ROUTER_NEXTPLAID_BIN` explicit path
|
|
6306
|
+
* 2. Router-owned `<APP_DIR>/colbert/bin/next-plaid-api[.exe]`
|
|
6307
|
+
* 3. `next-plaid-api` on PATH
|
|
6308
|
+
* Model + ORT reuse the colbert provision (LateOn-Code-edge INT8 dir);
|
|
6309
|
+
* absent model ⇒ backend unavailable ⇒ colgrep fallback.
|
|
6310
|
+
*/
|
|
6311
|
+
/** Backend selection. Default `colgrep`; opt in with `=service`. */
|
|
6312
|
+
function semanticBackend() {
|
|
6313
|
+
return process.env.GH_ROUTER_SEMANTIC_BACKEND === "service" ? "service" : "colgrep";
|
|
6314
|
+
}
|
|
6315
|
+
/** True when the service backend is selected AND actionable. */
|
|
6316
|
+
function serviceBackendEnabled() {
|
|
6317
|
+
if (semanticBackend() !== "service") return false;
|
|
6318
|
+
if (resolveServiceBinary() === null && !nextPlaidServerPromoted("cpu") && !nextPlaidServerPromoted("cuda")) return false;
|
|
6319
|
+
if (!existsSync(canonicalColbertModelDir())) return false;
|
|
6320
|
+
return true;
|
|
6321
|
+
}
|
|
6322
|
+
/** Locate the server binary (env → router-owned → PATH). */
|
|
6323
|
+
function resolveServiceBinary() {
|
|
6324
|
+
const explicit = process.env.GH_ROUTER_NEXTPLAID_BIN;
|
|
6325
|
+
if (explicit && explicit.length > 0 && existsSync(explicit)) return explicit;
|
|
6326
|
+
for (const variant of ["cpu", "cuda"]) {
|
|
6327
|
+
const owned = nextPlaidServerBinaryPath(variant);
|
|
6328
|
+
if (existsSync(owned)) return owned;
|
|
6329
|
+
}
|
|
6330
|
+
return resolveExecutable("next-plaid-api");
|
|
6331
|
+
}
|
|
6332
|
+
/**
|
|
6333
|
+
* True when an NVIDIA GPU is visible (`nvidia-smi -L` exits 0). Never
|
|
6334
|
+
* throws; absent tool/driver ⇒ false ⇒ cpu variant. Bounded (~8s) so a
|
|
6335
|
+
* wedged driver can't stall startup.
|
|
6336
|
+
*/
|
|
6337
|
+
async function hasCudaGpu() {
|
|
6338
|
+
try {
|
|
6339
|
+
const smi = resolveExecutable("nvidia-smi");
|
|
6340
|
+
if (!smi) return false;
|
|
6341
|
+
const res = await runManagedExeCapture(smi, ["-L"], {
|
|
6342
|
+
timeoutMs: 8e3,
|
|
6343
|
+
maxStdoutBytes: 65536
|
|
6344
|
+
});
|
|
6345
|
+
return res.code === 0 && !res.timedOut;
|
|
6346
|
+
} catch {
|
|
6347
|
+
return false;
|
|
6348
|
+
}
|
|
6349
|
+
}
|
|
6350
|
+
/**
|
|
6351
|
+
* Pick the server compute variant. Explicit `GH_ROUTER_NEXTPLAID_VARIANT`
|
|
6352
|
+
* (`cpu`|`cuda`) wins (operator/test seam); otherwise cuda iff a GPU is
|
|
6353
|
+
* visible. Callers still fall back across variants when the preferred
|
|
6354
|
+
* binary can't be provisioned — selection is a preference, not a gate.
|
|
6355
|
+
*/
|
|
6356
|
+
async function selectServerVariant() {
|
|
6357
|
+
const override = process.env.GH_ROUTER_NEXTPLAID_VARIANT;
|
|
6358
|
+
if (override === "cpu" || override === "cuda") return override;
|
|
6359
|
+
return await hasCudaGpu() ? "cuda" : "cpu";
|
|
6360
|
+
}
|
|
6361
|
+
/**
|
|
6362
|
+
* Resolve the server binary + flags, provisioning on demand. Order:
|
|
6363
|
+
* explicit env (as-is; `--cuda` only via GH_ROUTER_NEXTPLAID_CUDA=1) →
|
|
6364
|
+
* preferred variant (provision, else on-disk) → cpu fallback (provision,
|
|
6365
|
+
* else on-disk) → PATH (cpu only). Null when nothing is usable.
|
|
6366
|
+
*/
|
|
6367
|
+
async function resolveServerBinaryWithVariant(variant) {
|
|
6368
|
+
const explicit = process.env.GH_ROUTER_NEXTPLAID_BIN;
|
|
6369
|
+
if (explicit && explicit.length > 0 && existsSync(explicit)) return {
|
|
6370
|
+
binary: explicit,
|
|
6371
|
+
cuda: process.env.GH_ROUTER_NEXTPLAID_CUDA === "1"
|
|
6372
|
+
};
|
|
6373
|
+
const ordered = variant === "cuda" ? ["cuda", "cpu"] : ["cpu"];
|
|
6374
|
+
for (const v of ordered) {
|
|
6375
|
+
const provisioned = await provisionNextPlaidServer(v);
|
|
6376
|
+
if (provisioned.path) return {
|
|
6377
|
+
binary: provisioned.path,
|
|
6378
|
+
cuda: v === "cuda"
|
|
6379
|
+
};
|
|
6380
|
+
const owned = nextPlaidServerBinaryPath(v);
|
|
6381
|
+
if (existsSync(owned)) return {
|
|
6382
|
+
binary: owned,
|
|
6383
|
+
cuda: v === "cuda"
|
|
6384
|
+
};
|
|
6385
|
+
}
|
|
6386
|
+
const onPath = resolveExecutable("next-plaid-api");
|
|
6387
|
+
if (onPath) return {
|
|
6388
|
+
binary: onPath,
|
|
6389
|
+
cuda: false
|
|
6390
|
+
};
|
|
6391
|
+
return null;
|
|
6392
|
+
}
|
|
6393
|
+
let _server = null;
|
|
6394
|
+
let _starting = null;
|
|
6395
|
+
/** Start (once) and health-check the server; null when unavailable. */
|
|
6396
|
+
async function ensureServer() {
|
|
6397
|
+
if (_server) {
|
|
6398
|
+
try {
|
|
6399
|
+
if ((await _server.client.health()).ok) return _server;
|
|
6400
|
+
} catch {}
|
|
6401
|
+
try {
|
|
6402
|
+
await _server.stop();
|
|
6403
|
+
} catch {}
|
|
6404
|
+
_server = null;
|
|
6405
|
+
}
|
|
6406
|
+
if (_starting) return _starting.catch(() => null);
|
|
6407
|
+
const resolved = await resolveServerBinaryWithVariant(await selectServerVariant());
|
|
6408
|
+
if (!resolved) return null;
|
|
6409
|
+
_starting = (async () => {
|
|
6410
|
+
const ortDir = path.dirname(colbertOrtDylibPath());
|
|
6411
|
+
const svc = await startManagedServer({
|
|
6412
|
+
binaryPath: resolved.binary,
|
|
6413
|
+
modelDir: canonicalColbertModelDir(),
|
|
6414
|
+
indexDir: PATHS.COLBERT_INDICES_DIR,
|
|
6415
|
+
parallel: serverParallelSessions(),
|
|
6416
|
+
cuda: resolved.cuda,
|
|
6417
|
+
env: {
|
|
6418
|
+
ORT_DYLIB_PATH: colbertOrtDylibPath(),
|
|
6419
|
+
PATH: `${ortDir}${path.delimiter}${process.env.PATH ?? ""}`
|
|
6420
|
+
},
|
|
6421
|
+
startupTimeoutMs: 12e4
|
|
6422
|
+
});
|
|
6423
|
+
_server = svc;
|
|
6424
|
+
return svc;
|
|
6425
|
+
})();
|
|
6426
|
+
try {
|
|
6427
|
+
return await _starting;
|
|
6428
|
+
} catch (err) {
|
|
6429
|
+
consola.debug(`service-backend: server start failed: ${err.message}`);
|
|
6430
|
+
return null;
|
|
6431
|
+
} finally {
|
|
6432
|
+
_starting = null;
|
|
6433
|
+
}
|
|
6434
|
+
}
|
|
6435
|
+
function serviceMetaPath(workspace) {
|
|
6436
|
+
return path.join(PATHS.COLBERT_META_DIR, `svc-${metaHash(workspace)}.json`);
|
|
6437
|
+
}
|
|
6438
|
+
function metaHash(workspace) {
|
|
6439
|
+
const canonical = canonicalWorkspace(workspace);
|
|
6440
|
+
let h = 2166136261;
|
|
6441
|
+
for (let i = 0; i < canonical.length; i++) {
|
|
6442
|
+
h ^= canonical.charCodeAt(i);
|
|
6443
|
+
h = Math.imul(h, 16777619);
|
|
6444
|
+
}
|
|
6445
|
+
return (h >>> 0).toString(16).padStart(8, "0");
|
|
6446
|
+
}
|
|
6447
|
+
async function readServiceMeta(workspace) {
|
|
6448
|
+
try {
|
|
6449
|
+
const raw = await fs$1.readFile(serviceMetaPath(workspace), "utf8");
|
|
6450
|
+
const parsed = JSON.parse(raw);
|
|
6451
|
+
if (parsed && typeof parsed === "object") return parsed;
|
|
6452
|
+
return null;
|
|
6453
|
+
} catch {
|
|
6454
|
+
return null;
|
|
6455
|
+
}
|
|
6456
|
+
}
|
|
6457
|
+
async function writeServiceMeta(meta) {
|
|
6458
|
+
await fs$1.mkdir(PATHS.COLBERT_META_DIR, { recursive: true });
|
|
6459
|
+
const dest = serviceMetaPath(meta.workspace);
|
|
6460
|
+
const tmp = `${dest}.${process.pid}.tmp`;
|
|
6461
|
+
try {
|
|
6462
|
+
await fs$1.writeFile(tmp, JSON.stringify(meta, null, 2));
|
|
6463
|
+
await fs$1.rename(tmp, dest);
|
|
6464
|
+
} catch {
|
|
6465
|
+
await fs$1.rm(tmp, { force: true }).catch(() => {});
|
|
6466
|
+
}
|
|
6467
|
+
}
|
|
6468
|
+
const _populateInFlight = /* @__PURE__ */ new Set();
|
|
6469
|
+
/** Fire-and-forget per-workspace populate (single-flight). Never throws. */
|
|
6470
|
+
function kickServiceIndex(workspace) {
|
|
6471
|
+
const key = path.resolve(workspace);
|
|
6472
|
+
if (_populateInFlight.has(key)) return;
|
|
6473
|
+
_populateInFlight.add(key);
|
|
6474
|
+
populateWorkspace(workspace).catch((err) => {
|
|
6475
|
+
consola.debug(`service-backend: populate failed for ${workspace}: ${err.message}`);
|
|
6476
|
+
}).finally(() => {
|
|
6477
|
+
_populateInFlight.delete(key);
|
|
6478
|
+
});
|
|
6479
|
+
}
|
|
6480
|
+
/** Max files enumerated per populate (whole-repo cap for v1). */
|
|
6481
|
+
const POPULATE_MAX_FILES = 2e4;
|
|
6482
|
+
/** Units per updateDocuments batch (server batches internally too). */
|
|
6483
|
+
const POPULATE_BATCH_UNITS = 100;
|
|
6484
|
+
/** Max concurrent file parses. */
|
|
6485
|
+
const POPULATE_PARSE_CONCURRENCY = 4;
|
|
6486
|
+
async function enumerateSourceFiles(rgPath, workspace, signal) {
|
|
6487
|
+
return new Promise((resolve) => {
|
|
6488
|
+
let child;
|
|
6489
|
+
try {
|
|
6490
|
+
child = spawn(rgPath, [
|
|
6491
|
+
"--files",
|
|
6492
|
+
"--no-follow",
|
|
6493
|
+
"-0"
|
|
6494
|
+
], {
|
|
6495
|
+
cwd: workspace,
|
|
6496
|
+
shell: false,
|
|
6497
|
+
stdio: [
|
|
6498
|
+
"ignore",
|
|
6499
|
+
"pipe",
|
|
6500
|
+
"ignore"
|
|
6501
|
+
]
|
|
6502
|
+
});
|
|
6503
|
+
} catch {
|
|
6504
|
+
resolve([]);
|
|
6505
|
+
return;
|
|
6506
|
+
}
|
|
6507
|
+
let buf = Buffer.alloc(0);
|
|
6508
|
+
const files = [];
|
|
6509
|
+
let done = false;
|
|
6510
|
+
const finish = (out) => {
|
|
6511
|
+
if (done) return;
|
|
6512
|
+
done = true;
|
|
6513
|
+
try {
|
|
6514
|
+
child.kill("SIGKILL");
|
|
6515
|
+
} catch {}
|
|
6516
|
+
resolve(out);
|
|
6517
|
+
};
|
|
6518
|
+
signal.addEventListener("abort", () => finish(files), { once: true });
|
|
6519
|
+
child.on("error", () => finish(files));
|
|
6520
|
+
child.stdout?.on("data", (chunk) => {
|
|
6521
|
+
buf = Buffer.concat([buf, chunk]);
|
|
6522
|
+
let idx;
|
|
6523
|
+
while ((idx = buf.indexOf(0)) >= 0 && files.length < POPULATE_MAX_FILES) {
|
|
6524
|
+
const rel = buf.subarray(0, idx).toString("utf8");
|
|
6525
|
+
buf = buf.subarray(idx + 1);
|
|
6526
|
+
if (rel.length > 0 && !path.isAbsolute(rel)) files.push(rel.replace(/\\/g, "/"));
|
|
6527
|
+
}
|
|
6528
|
+
if (files.length >= POPULATE_MAX_FILES) finish(files);
|
|
6529
|
+
});
|
|
6530
|
+
child.on("close", () => finish(files));
|
|
6531
|
+
});
|
|
6532
|
+
}
|
|
6533
|
+
function resolveRipgrepBin() {
|
|
6534
|
+
try {
|
|
6535
|
+
return resolveRipgrep().rgPath;
|
|
6536
|
+
} catch {
|
|
6537
|
+
return "rg";
|
|
6538
|
+
}
|
|
6539
|
+
}
|
|
6540
|
+
async function populateWorkspace(workspace) {
|
|
6541
|
+
const svc = await ensureServer();
|
|
6542
|
+
if (!svc) return;
|
|
6543
|
+
const canonical = canonicalWorkspace(workspace);
|
|
6544
|
+
const index = indexNameForWorkspace(canonical);
|
|
6545
|
+
await svc.client.ensureIndex(index, { nbits: 4 });
|
|
6546
|
+
const rgPath = resolveRipgrepBin();
|
|
6547
|
+
const ac = new AbortController();
|
|
6548
|
+
const timeout = setTimeout(() => ac.abort(), 18e5);
|
|
6549
|
+
timeout.unref?.();
|
|
6550
|
+
try {
|
|
6551
|
+
const parseable = (await enumerateSourceFiles(rgPath, canonical, ac.signal)).filter((f) => getLanguageKeyForPath(f) !== null);
|
|
6552
|
+
let units = [];
|
|
6553
|
+
let unitTotal = 0;
|
|
6554
|
+
const flush = async () => {
|
|
6555
|
+
if (units.length === 0) return;
|
|
6556
|
+
const batch = units;
|
|
6557
|
+
units = [];
|
|
6558
|
+
await svc.client.updateDocuments(index, batch.map((u) => u.text), batch.map((u) => u.metadata));
|
|
6559
|
+
unitTotal += batch.length;
|
|
6560
|
+
};
|
|
6561
|
+
let next = 0;
|
|
6562
|
+
const workers = Array.from({ length: Math.min(POPULATE_PARSE_CONCURRENCY, parseable.length) }, async () => {
|
|
6563
|
+
while (!ac.signal.aborted) {
|
|
6564
|
+
const i = next;
|
|
6565
|
+
next += 1;
|
|
6566
|
+
if (i >= parseable.length) break;
|
|
6567
|
+
const rel = parseable[i];
|
|
6568
|
+
try {
|
|
6569
|
+
const r = await extractUnits(path.join(canonical, rel), rel, ac.signal);
|
|
6570
|
+
for (const u of r.units) {
|
|
6571
|
+
units.push({
|
|
6572
|
+
text: buildUnitText(u, rel),
|
|
6573
|
+
metadata: {
|
|
6574
|
+
file: u.file,
|
|
6575
|
+
line: u.line,
|
|
6576
|
+
end_line: u.end_line,
|
|
6577
|
+
name: u.name,
|
|
6578
|
+
signature: u.signature,
|
|
6579
|
+
kind: u.kind,
|
|
6580
|
+
unit_id: u.unit_id
|
|
6581
|
+
}
|
|
6582
|
+
});
|
|
6583
|
+
if (units.length >= POPULATE_BATCH_UNITS) await flush();
|
|
6584
|
+
}
|
|
6585
|
+
} catch {}
|
|
6586
|
+
}
|
|
6587
|
+
});
|
|
6588
|
+
await Promise.all(workers);
|
|
6589
|
+
await flush();
|
|
6590
|
+
const g = await gitState(canonical).catch(() => ({ isRepo: false }));
|
|
6591
|
+
await writeServiceMeta({
|
|
6592
|
+
workspace: canonical,
|
|
6593
|
+
index,
|
|
6594
|
+
...g.isRepo ? {
|
|
6595
|
+
head: g.head,
|
|
6596
|
+
dirty: g.dirty ?? false
|
|
6597
|
+
} : {},
|
|
6598
|
+
indexedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
6599
|
+
docCount: unitTotal
|
|
6600
|
+
});
|
|
6601
|
+
consola.debug(`service-backend: indexed ${unitTotal} units in ${canonical}`);
|
|
6602
|
+
} finally {
|
|
6603
|
+
clearTimeout(timeout);
|
|
6604
|
+
}
|
|
6605
|
+
}
|
|
6606
|
+
/**
|
|
6607
|
+
* Search via the service backend. Returns `unavailable` (caller falls back
|
|
6608
|
+
* to colgrep/lexical) when the server, model, or index isn't ready; `failed`
|
|
6609
|
+
* only on unexpected errors. Served rows carry freshness labels per the
|
|
6610
|
+
* serve-while-stale policy.
|
|
6611
|
+
*/
|
|
6612
|
+
async function runServiceSearch(opts) {
|
|
6613
|
+
const { query, workspace } = opts;
|
|
6614
|
+
const limit = Math.max(1, Math.min(100, Math.floor(opts.limit ?? 15)));
|
|
6615
|
+
const canonical = canonicalWorkspace(workspace);
|
|
6616
|
+
const meta = await readServiceMeta(canonical);
|
|
6617
|
+
if (!meta) {
|
|
6618
|
+
kickServiceIndex(canonical);
|
|
6619
|
+
return { status: "unavailable" };
|
|
6620
|
+
}
|
|
6621
|
+
const svc = await ensureServer();
|
|
6622
|
+
if (!svc) return { status: "unavailable" };
|
|
6623
|
+
const index = indexNameForWorkspace(canonical);
|
|
6624
|
+
const g = await gitState(canonical).catch(() => ({ isRepo: false }));
|
|
6625
|
+
let freshness = "fresh";
|
|
6626
|
+
let staleFiles = 0;
|
|
6627
|
+
if (g.isRepo) {
|
|
6628
|
+
const headMoved = meta.head !== void 0 && g.head !== meta.head;
|
|
6629
|
+
const newlyDirty = g.dirty === true && meta.dirty !== true;
|
|
6630
|
+
if (headMoved || newlyDirty) {
|
|
6631
|
+
freshness = "stale";
|
|
6632
|
+
kickServiceIndex(canonical);
|
|
6633
|
+
try {
|
|
6634
|
+
const delta = await gitDeltaFiles(canonical, headMoved ? meta.head : void 0, headMoved ? g.head : void 0);
|
|
6635
|
+
if (delta.truncated || delta.files.length > serveStaleMaxFiles()) return { status: "unavailable" };
|
|
6636
|
+
staleFiles = delta.files.length;
|
|
6637
|
+
} catch {
|
|
6638
|
+
return { status: "unavailable" };
|
|
6639
|
+
}
|
|
6640
|
+
}
|
|
6641
|
+
}
|
|
6642
|
+
try {
|
|
6643
|
+
return {
|
|
6644
|
+
status: "ready",
|
|
6645
|
+
results: (await svc.client.search(index, query, {
|
|
6646
|
+
topK: limit,
|
|
6647
|
+
textQuery: query,
|
|
6648
|
+
alpha: .75
|
|
6649
|
+
})).map((h) => ({
|
|
6650
|
+
file: h.file,
|
|
6651
|
+
line: h.line,
|
|
6652
|
+
snippet: buildSnippet(h),
|
|
6653
|
+
...h.end_line !== void 0 ? { endLine: h.end_line } : {},
|
|
6654
|
+
...h.name !== void 0 ? { name: h.name } : {},
|
|
6655
|
+
score: h.score
|
|
6656
|
+
})),
|
|
6657
|
+
freshness,
|
|
6658
|
+
...freshness === "stale" ? { stale_files: staleFiles } : {}
|
|
6659
|
+
};
|
|
6660
|
+
} catch (err) {
|
|
6661
|
+
if (err instanceof ServiceBusyError) return { status: "unavailable" };
|
|
6662
|
+
consola.debug(`service-backend: search failed: ${err.message}`);
|
|
6663
|
+
return { status: "failed" };
|
|
6664
|
+
}
|
|
6665
|
+
}
|
|
6666
|
+
function buildSnippet(h) {
|
|
6667
|
+
const meta = h.metadata ?? {};
|
|
6668
|
+
const sig = typeof meta.signature === "string" ? meta.signature : "";
|
|
6669
|
+
return sig.length > 0 ? `${sig}\n${h.file}:${h.line}` : `${h.file}:${h.line}`;
|
|
6670
|
+
}
|
|
6671
|
+
//#endregion
|
|
6672
|
+
export { provisionTreeSitterAssets as A, searchCode as C, recommendedRgThreads as D, isSensitivePath as E, warmTreeSitterPool as O, resolveRipgrep as S, confineToWorkspaceResult as T, colbertSmokeOk as _, kickBackgroundInit as a, extractTarGzMember as b, waitForInit as c, freshnessVerdict as d, gitState as f, colbertArtifactsPresent as g, validateIndexIntegrity as h, serviceBackendEnabled as i, withInstallLock as j, outlineFile as k, colbertProjectDir as l, readColbertMeta as m, selectServerVariant as n, runSemanticSearch as o, indexDirSignature as p, semanticBackend as r, startupKickAllowed as s, runServiceSearch as t, completedIndexOnDisk as u, provisionColbert as v, validateWorkspace as w, extractZipMember as x, provisionNextPlaidServer as y };
|
|
5623
6673
|
|
|
5624
|
-
//# sourceMappingURL=
|
|
6674
|
+
//# sourceMappingURL=service-backend-DYEPoszR.js.map
|