github-router 0.3.330 → 0.3.332

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.
Files changed (128) hide show
  1. package/README.md +4 -2
  2. package/dist/{aic-ledger-CsBx1crE.js → aic-ledger-D4fmThbS.js} +2 -2
  3. package/dist/{aic-ledger-CsBx1crE.js.map → aic-ledger-D4fmThbS.js.map} +1 -1
  4. package/dist/{attribution-settings-DepziZU8.js → attribution-settings-BeO1w_DL.js} +62 -51
  5. package/dist/attribution-settings-BeO1w_DL.js.map +1 -0
  6. package/dist/{auth-xgFZGZbf.js → auth-DjKEIiqG.js} +4 -4
  7. package/dist/{auth-xgFZGZbf.js.map → auth-DjKEIiqG.js.map} +1 -1
  8. package/dist/bluebird-client-DpYl1YmJ.js +1163 -0
  9. package/dist/bluebird-client-DpYl1YmJ.js.map +1 -0
  10. package/dist/bluebird-client-bn9Yv6Cb.js +2 -0
  11. package/dist/browser-ext/manifest.json +1 -1
  12. package/dist/{check-usage-vUDk6oV7.js → check-usage-B7UrDwD8.js} +4 -4
  13. package/dist/{check-usage-vUDk6oV7.js.map → check-usage-B7UrDwD8.js.map} +1 -1
  14. package/dist/{claude-Dw4V8o8l.js → claude-BQQPdXLb.js} +37 -29
  15. package/dist/claude-BQQPdXLb.js.map +1 -0
  16. package/dist/{codex-CXOpv4WP.js → codex-fW-hbxtT.js} +12 -8
  17. package/dist/codex-fW-hbxtT.js.map +1 -0
  18. package/dist/{copilot-discount-0lG67i9O.js → copilot-discount-BcUa3f-k.js} +2 -2
  19. package/dist/{copilot-discount-0lG67i9O.js.map → copilot-discount-BcUa3f-k.js.map} +1 -1
  20. package/dist/{debug-a737qcCC.js → debug-CigFsS-h.js} +2 -2
  21. package/dist/{debug-a737qcCC.js.map → debug-CigFsS-h.js.map} +1 -1
  22. package/dist/engine-E4WJGSeg.js +2 -0
  23. package/dist/{exec-COUT4QsS.js → exec-MCU1H-KZ.js} +63 -13
  24. package/dist/exec-MCU1H-KZ.js.map +1 -0
  25. package/dist/{gate-discovery-BGqS7R2g.js → gate-discovery-DbwVeERm.js} +6 -6
  26. package/dist/{gate-discovery-BGqS7R2g.js.map → gate-discovery-DbwVeERm.js.map} +1 -1
  27. package/dist/{get-copilot-usage-VKU2IvuE.js → get-copilot-usage-CGaV01dC.js} +4 -3
  28. package/dist/{get-copilot-usage-VKU2IvuE.js.map → get-copilot-usage-CGaV01dC.js.map} +1 -1
  29. package/dist/hooks.mjs +90 -27
  30. package/dist/hooks.sha256 +1 -1
  31. package/dist/index-cmd-DXYWgKS6.js +330 -0
  32. package/dist/index-cmd-DXYWgKS6.js.map +1 -0
  33. package/dist/{internal-aic-status-Cfl5HiAN.js → internal-aic-status-Bma0r0ZS.js} +6 -5
  34. package/dist/internal-aic-status-Bma0r0ZS.js.map +1 -0
  35. package/dist/{internal-artifact-open-CX2fRP_D.js → internal-artifact-open-lta2UPnE.js} +2 -2
  36. package/dist/{internal-artifact-open-CX2fRP_D.js.map → internal-artifact-open-lta2UPnE.js.map} +1 -1
  37. package/dist/{internal-fast-dispatch-guard-Cxattkm4.js → internal-fast-dispatch-guard-DPR16qUE.js} +1 -1
  38. package/dist/{internal-fast-dispatch-guard-BoTxjO6b.js → internal-fast-dispatch-guard-DoXO3X7P.js} +2 -2
  39. package/dist/{internal-fast-dispatch-guard-BoTxjO6b.js.map → internal-fast-dispatch-guard-DoXO3X7P.js.map} +1 -1
  40. package/dist/{internal-first-mate-guard-D_JFcrl_.js → internal-first-mate-guard-BEwDjHfX.js} +3 -3
  41. package/dist/{internal-first-mate-guard-D_JFcrl_.js.map → internal-first-mate-guard-BEwDjHfX.js.map} +1 -1
  42. package/dist/{internal-first-mate-guard-97qsseTP.js → internal-first-mate-guard-CAefr6Ce.js} +1 -1
  43. package/dist/{internal-max-dispatch-guard-DQMyOds8.js → internal-max-dispatch-guard-6ZCEanI6.js} +1 -1
  44. package/dist/{internal-max-dispatch-guard-Cxe8h12x.js → internal-max-dispatch-guard-CtIO7pm1.js} +3 -3
  45. package/dist/{internal-max-dispatch-guard-Cxe8h12x.js.map → internal-max-dispatch-guard-CtIO7pm1.js.map} +1 -1
  46. package/dist/{internal-plan-review-O2dwnQv3.js → internal-plan-review-jIts3KYd.js} +3 -3
  47. package/dist/{internal-plan-review-O2dwnQv3.js.map → internal-plan-review-jIts3KYd.js.map} +1 -1
  48. package/dist/{internal-prompt-submit-CD0UFkT-.js → internal-prompt-submit-BfoWVyzs.js} +10 -7
  49. package/dist/internal-prompt-submit-BfoWVyzs.js.map +1 -0
  50. package/dist/{internal-session-bind-CHIOd5ys.js → internal-session-bind-IpZ5hJzR.js} +2 -2
  51. package/dist/{internal-session-bind-CHIOd5ys.js.map → internal-session-bind-IpZ5hJzR.js.map} +1 -1
  52. package/dist/{internal-stop-hook-CH9SKjZ9.js → internal-stop-hook-DO8RKfKB.js} +6 -6
  53. package/dist/{internal-stop-hook-CH9SKjZ9.js.map → internal-stop-hook-DO8RKfKB.js.map} +1 -1
  54. package/dist/{internal-stop-review-a3rpzzhd.js → internal-stop-review-BtGDVrv-.js} +2 -2
  55. package/dist/{internal-stop-review-a3rpzzhd.js.map → internal-stop-review-BtGDVrv-.js.map} +1 -1
  56. package/dist/{internal-worker-guard-BY5seBqp.js → internal-worker-guard-C0FJ4b29.js} +2 -2
  57. package/dist/{internal-worker-guard-BY5seBqp.js.map → internal-worker-guard-C0FJ4b29.js.map} +1 -1
  58. package/dist/{internal-workspace-header-CPZNphnk.js → internal-workspace-header-tvJVAXpv.js} +2 -2
  59. package/dist/{internal-workspace-header-CPZNphnk.js.map → internal-workspace-header-tvJVAXpv.js.map} +1 -1
  60. package/dist/{lifecycle-D8vQXfeC.js → lifecycle-BqWTXaeC.js} +3 -3
  61. package/dist/{lifecycle-D8vQXfeC.js.map → lifecycle-BqWTXaeC.js.map} +1 -1
  62. package/dist/lifecycle-DMRZswwc.js +2 -0
  63. package/dist/lifecycle-FT75ohVw.js +2 -0
  64. package/dist/{lifecycle-MmpJWRcl.js → lifecycle-kpLzHUgD.js} +2 -2
  65. package/dist/{lifecycle-MmpJWRcl.js.map → lifecycle-kpLzHUgD.js.map} +1 -1
  66. package/dist/main.js +21 -21
  67. package/dist/{max-profile-contract-Bl7I_EOC.js → max-profile-contract-MJJt0zm-.js} +2 -2
  68. package/dist/{max-profile-contract-Bl7I_EOC.js.map → max-profile-contract-MJJt0zm-.js.map} +1 -1
  69. package/dist/{mcp-workspace-header-DX_mD0JT.js → mcp-workspace-header-B77WqVFw.js} +2 -2
  70. package/dist/{mcp-workspace-header-DX_mD0JT.js.map → mcp-workspace-header-B77WqVFw.js.map} +1 -1
  71. package/dist/{models-BjCRO0AC.js → models-68HDOEPK.js} +3 -3
  72. package/dist/{models-BjCRO0AC.js.map → models-68HDOEPK.js.map} +1 -1
  73. package/dist/{orchestration-Dn5v8c0a.js → orchestration-Ccmfslh4.js} +3 -3
  74. package/dist/{orchestration-Dn5v8c0a.js.map → orchestration-Ccmfslh4.js.map} +1 -1
  75. package/dist/{paths-P5ajjpzU.js → paths-CpbTHKeP.js} +3 -3
  76. package/dist/{paths-P5ajjpzU.js.map → paths-CpbTHKeP.js.map} +1 -1
  77. package/dist/paths-Dfivvq21.js +2 -0
  78. package/dist/{peer-mcp-personas-CnYMTizo.js → peer-mcp-personas-CeB2Kcn2.js} +184 -76
  79. package/dist/peer-mcp-personas-CeB2Kcn2.js.map +1 -0
  80. package/dist/{plan-review-hook-CfZBvsHd.js → plan-review-hook-ciat1jgZ.js} +4 -4
  81. package/dist/{plan-review-hook-CfZBvsHd.js.map → plan-review-hook-ciat1jgZ.js.map} +1 -1
  82. package/dist/{prompt-submit-hook-CRH6m7Vz.js → prompt-submit-hook-C8q_hDOv.js} +21 -17
  83. package/dist/prompt-submit-hook-C8q_hDOv.js.map +1 -0
  84. package/dist/{provision-D5KOOw6n.js → provision-DZLsyRYh.js} +7 -6
  85. package/dist/provision-DZLsyRYh.js.map +1 -0
  86. package/dist/{self-invocation-DBWyjvGm.js → self-invocation-DIUyoRgL.js} +2 -2
  87. package/dist/{self-invocation-DBWyjvGm.js.map → self-invocation-DIUyoRgL.js.map} +1 -1
  88. package/dist/{serve-fJWhiivo.js → serve-ik_96Q2Z.js} +33 -21
  89. package/dist/serve-ik_96Q2Z.js.map +1 -0
  90. package/dist/{server-setup-DHMPOXKT.js → server-setup-CK3O_Hwf.js} +37 -13
  91. package/dist/{server-setup-DHMPOXKT.js.map → server-setup-CK3O_Hwf.js.map} +1 -1
  92. package/dist/{service-backend-DYEPoszR.js → service-backend-7SPDLUB9.js} +411 -25
  93. package/dist/service-backend-7SPDLUB9.js.map +1 -0
  94. package/dist/{start-Gs4jAwUR.js → start-DPOJJSvp.js} +4 -4
  95. package/dist/{start-Gs4jAwUR.js.map → start-DPOJJSvp.js.map} +1 -1
  96. package/dist/{state-BlMpEFAt.js → state-CVp30CBF.js} +7 -1
  97. package/dist/state-CVp30CBF.js.map +1 -0
  98. package/dist/{stop-gate-hook-BACb8dlj.js → stop-gate-hook-DZVfKoSh.js} +4 -4
  99. package/dist/{stop-gate-hook-BACb8dlj.js.map → stop-gate-hook-DZVfKoSh.js.map} +1 -1
  100. package/dist/{stop-gate-policy-D6jIeOXB.js → stop-gate-policy-Gd_cNT9-.js} +3 -3
  101. package/dist/{stop-gate-policy-D6jIeOXB.js.map → stop-gate-policy-Gd_cNT9-.js.map} +1 -1
  102. package/dist/{token-Dlb_84hW.js → token-DATA_OQK.js} +5 -383
  103. package/dist/token-DATA_OQK.js.map +1 -0
  104. package/dist/upstream-retry-i1k1Xai2.js +383 -0
  105. package/dist/upstream-retry-i1k1Xai2.js.map +1 -0
  106. package/dist/{worker-dispatch-DtjQchvM.js → worker-dispatch-lRhno09M.js} +2 -2
  107. package/dist/{worker-dispatch-DtjQchvM.js.map → worker-dispatch-lRhno09M.js.map} +1 -1
  108. package/docs/bluebird-search.md +338 -0
  109. package/package.json +3 -2
  110. package/dist/attribution-settings-DepziZU8.js.map +0 -1
  111. package/dist/claude-Dw4V8o8l.js.map +0 -1
  112. package/dist/codex-CXOpv4WP.js.map +0 -1
  113. package/dist/engine-CYba_zi7.js +0 -2
  114. package/dist/exec-COUT4QsS.js.map +0 -1
  115. package/dist/index-cmd-DUjQs9zw.js +0 -182
  116. package/dist/index-cmd-DUjQs9zw.js.map +0 -1
  117. package/dist/internal-aic-status-Cfl5HiAN.js.map +0 -1
  118. package/dist/internal-prompt-submit-CD0UFkT-.js.map +0 -1
  119. package/dist/lifecycle-B2eB8nRg.js +0 -2
  120. package/dist/lifecycle-Dz-Rq8pD.js +0 -2
  121. package/dist/paths-DVXBtLyo.js +0 -2
  122. package/dist/peer-mcp-personas-CnYMTizo.js.map +0 -1
  123. package/dist/prompt-submit-hook-CRH6m7Vz.js.map +0 -1
  124. package/dist/provision-D5KOOw6n.js.map +0 -1
  125. package/dist/serve-fJWhiivo.js.map +0 -1
  126. package/dist/service-backend-DYEPoszR.js.map +0 -1
  127. package/dist/state-BlMpEFAt.js.map +0 -1
  128. package/dist/token-Dlb_84hW.js.map +0 -1
@@ -1,6 +1,6 @@
1
- import { t as PATHS } from "./paths-P5ajjpzU.js";
2
- import { l as runManagedExeCapture, o as resolveExecutable, u as spawnTaskkillBestEffort } from "./exec-COUT4QsS.js";
3
- import { c as untrackChild, n as isPidAlive, s as trackChild, t as getColbertInstanceUuid } from "./lifecycle-D8vQXfeC.js";
1
+ import { t as PATHS } from "./paths-CpbTHKeP.js";
2
+ import { l as runManagedExeCapture, o as resolveExecutable, u as spawnTaskkillBestEffort } from "./exec-MCU1H-KZ.js";
3
+ import { c as untrackChild, n as isPidAlive, s as trackChild, t as getColbertInstanceUuid } from "./lifecycle-BqWTXaeC.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";
@@ -1880,8 +1880,8 @@ const MAX_GLOB_LEN = 512;
1880
1880
  const DEFAULT_LIMIT$1 = 200;
1881
1881
  const MAX_CONTEXT_LINES = 10;
1882
1882
  /**
1883
- * `summary: true` outlines at most this many distinct result files (in
1884
- * result order) — a structural map of where the matches live, bounded
1883
+ * The default structural summary outlines at most this many distinct result
1884
+ * files (in result order) — a map of where the matches live, bounded
1885
1885
  * so a broad query doesn't trigger hundreds of tree-sitter parses.
1886
1886
  */
1887
1887
  const CODE_SUMMARY_MAX_FILES = 10;
@@ -3345,7 +3345,7 @@ async function searchCode(rawInput, externalSignal) {
3345
3345
  const outlineStartMs = Date.now();
3346
3346
  const wantScan = rawInput.scan === true;
3347
3347
  const scanDeadline = Date.now() + WALL_TIME_MS;
3348
- if (rawInput.summary === true || wantScan) {
3348
+ if (rawInput.summary !== false || wantScan) {
3349
3349
  let distinct;
3350
3350
  if (wantScan) {
3351
3351
  const enumed = await enumerateWorkspaceFiles({
@@ -5779,7 +5779,8 @@ var NextPlaidClient = class {
5779
5779
  const { status, body } = await fetchJson(`${this.baseUrl}/health`, {}, this.timeoutMs);
5780
5780
  if (status !== 200 || typeof body !== "object" || body === null) return {
5781
5781
  ok: false,
5782
- indices: []
5782
+ indices: [],
5783
+ updates: []
5783
5784
  };
5784
5785
  const b = body;
5785
5786
  return {
@@ -5790,7 +5791,11 @@ var NextPlaidClient = class {
5790
5791
  num_embeddings: typeof i.num_embeddings === "number" ? i.num_embeddings : 0,
5791
5792
  dimension: typeof i.dimension === "number" ? i.dimension : 0
5792
5793
  })),
5793
- model: b.model?.name
5794
+ model: b.model?.name,
5795
+ updates: (b.updates ?? []).map((u) => ({
5796
+ index: typeof u.index === "string" ? u.index : typeof u.name === "string" ? u.name : "",
5797
+ status: typeof u.status === "string" ? u.status : ""
5798
+ }))
5794
5799
  };
5795
5800
  }
5796
5801
  /** Declare an index (idempotent: 409 taken is success). */
@@ -5830,6 +5835,18 @@ var NextPlaidClient = class {
5830
5835
  if (status === 503) throw new ServiceBusyError(index);
5831
5836
  throw new Error(`update ${index} failed: HTTP ${status} (${describeError(body)})`);
5832
5837
  }
5838
+ /**
5839
+ * Drop an entire index. Returns true when the index is guaranteed absent
5840
+ * afterwards (dropped, or never existed). Returns false when the server
5841
+ * does not support the operation (405/501) or reports an error — the
5842
+ * caller falls back to per-file deletes. Verified against v1.7.0:
5843
+ * `{"deleted":true}` with HTTP 200.
5844
+ */
5845
+ async dropIndex(name) {
5846
+ const { status } = await fetchJson(`${this.baseUrl}/indices/${encodeURIComponent(name)}`, { method: "DELETE" }, this.timeoutMs);
5847
+ if (status === 200 || status === 201 || status === 204 || status === 404) return true;
5848
+ return false;
5849
+ }
5833
5850
  /** Delete by SQL predicate (batched server-side, 202 accepted). */
5834
5851
  async deleteDocuments(index, condition, parameters = []) {
5835
5852
  const { status, body } = await fetchJson(`${this.baseUrl}/indices/${encodeURIComponent(index)}/documents`, {
@@ -6076,13 +6093,14 @@ async function stopServer(child) {
6076
6093
  }
6077
6094
  }
6078
6095
  /** CPU-aware default parallelism for the managed server. */
6079
- function serverParallelSessions() {
6096
+ function serverParallelSessions(foreground = false) {
6080
6097
  const raw = Number(process$1.env.GH_ROUTER_NP_PARALLEL);
6081
6098
  if (Number.isSafeInteger(raw) && raw > 0) return raw;
6082
6099
  let cpus = 4;
6083
6100
  try {
6084
6101
  cpus = os$1.cpus().length;
6085
6102
  } catch {}
6103
+ if (foreground) return Math.max(1, cpus);
6086
6104
  return Math.max(1, Math.floor(cpus * .25));
6087
6105
  }
6088
6106
  /** Per-workspace index name: stable hash of the canonical workspace path. */
@@ -6315,6 +6333,16 @@ function semanticBackend() {
6315
6333
  /** True when the service backend is selected AND actionable. */
6316
6334
  function serviceBackendEnabled() {
6317
6335
  if (semanticBackend() !== "service") return false;
6336
+ return serviceBackendProvisionable();
6337
+ }
6338
+ /**
6339
+ * True when the service backend COULD run here (binary on disk or promoted
6340
+ * download + model present), regardless of the `GH_ROUTER_SEMANTIC_BACKEND`
6341
+ * opt-in. The `index` command's `auto` backend uses this: an explicit
6342
+ * `index` invocation is its own opt-in, while the query path stays gated
6343
+ * on the env var via `serviceBackendEnabled`.
6344
+ */
6345
+ function serviceBackendProvisionable() {
6318
6346
  if (resolveServiceBinary() === null && !nextPlaidServerPromoted("cpu") && !nextPlaidServerPromoted("cuda")) return false;
6319
6347
  if (!existsSync(canonicalColbertModelDir())) return false;
6320
6348
  return true;
@@ -6393,7 +6421,7 @@ async function resolveServerBinaryWithVariant(variant) {
6393
6421
  let _server = null;
6394
6422
  let _starting = null;
6395
6423
  /** Start (once) and health-check the server; null when unavailable. */
6396
- async function ensureServer() {
6424
+ async function ensureServer(opts = {}) {
6397
6425
  if (_server) {
6398
6426
  try {
6399
6427
  if ((await _server.client.health()).ok) return _server;
@@ -6412,7 +6440,7 @@ async function ensureServer() {
6412
6440
  binaryPath: resolved.binary,
6413
6441
  modelDir: canonicalColbertModelDir(),
6414
6442
  indexDir: PATHS.COLBERT_INDICES_DIR,
6415
- parallel: serverParallelSessions(),
6443
+ parallel: serverParallelSessions(opts.foreground === true),
6416
6444
  cuda: resolved.cuda,
6417
6445
  env: {
6418
6446
  ORT_DYLIB_PATH: colbertOrtDylibPath(),
@@ -6466,16 +6494,120 @@ async function writeServiceMeta(meta) {
6466
6494
  }
6467
6495
  }
6468
6496
  const _populateInFlight = /* @__PURE__ */ new Set();
6497
+ /** Background populate promises, drained by tests. */
6498
+ const _populatePromises = /* @__PURE__ */ new Set();
6499
+ /** Start the server with foreground (all-core) parallelism for `index`. */
6500
+ async function ensureServerForeground() {
6501
+ return ensureServer({ foreground: true });
6502
+ }
6503
+ /**
6504
+ * Stop the managed server and clear the singleton. The `index` command
6505
+ * must call this before returning: unlike short-lived colgrep children,
6506
+ * the persistent server holds the event loop open forever, so a
6507
+ * foreground build that never stops it never exits (orphaning the
6508
+ * server on every invocation).
6509
+ */
6510
+ async function stopServiceServer() {
6511
+ try {
6512
+ await _starting?.catch(() => null);
6513
+ } catch {}
6514
+ _starting = null;
6515
+ const svc = _server;
6516
+ _server = null;
6517
+ if (svc) try {
6518
+ await svc.stop();
6519
+ } catch {}
6520
+ }
6521
+ /**
6522
+ * Freshness of the SERVICE index for a workspace (own sidecar — never the
6523
+ * colgrep verdict, which describes a different index). `stale` covers both
6524
+ * content drift (HEAD moved / newly dirty) and engine drift (model
6525
+ * revision changed). Callers rebuild (delta or full); `fresh` needs nothing.
6526
+ */
6527
+ async function serviceFreshness(workspace) {
6528
+ const canonical = canonicalWorkspace(workspace);
6529
+ const meta = await readServiceMeta(canonical);
6530
+ if (!meta) return {
6531
+ verdict: "absent",
6532
+ meta
6533
+ };
6534
+ if (!existsSync(canonicalColbertModelDir())) return {
6535
+ verdict: "absent",
6536
+ meta
6537
+ };
6538
+ if (meta.modelRev !== void 0 && meta.modelRev !== "07ef20f406c86badca122464808f4cac2f6e4b25") return {
6539
+ verdict: "stale",
6540
+ meta
6541
+ };
6542
+ const g = await gitState(canonical).catch(() => ({ isRepo: false }));
6543
+ if (g.isRepo) {
6544
+ const headMoved = meta.head !== void 0 && g.head !== meta.head;
6545
+ const newlyDirty = g.dirty === true && meta.dirty !== true;
6546
+ if (headMoved || newlyDirty) return {
6547
+ verdict: "stale",
6548
+ meta,
6549
+ head: g.head,
6550
+ dirty: g.dirty ?? false
6551
+ };
6552
+ return {
6553
+ verdict: "fresh",
6554
+ meta,
6555
+ head: g.head,
6556
+ dirty: g.dirty ?? false
6557
+ };
6558
+ }
6559
+ return {
6560
+ verdict: "fresh",
6561
+ meta
6562
+ };
6563
+ }
6564
+ /** sha256 hex of a file's bytes; undefined when unreadable. */
6565
+ async function hashFile(absPath) {
6566
+ try {
6567
+ const bytes = await fs$1.readFile(absPath);
6568
+ return createHash("sha256").update(bytes).digest("hex");
6569
+ } catch {
6570
+ return;
6571
+ }
6572
+ }
6573
+ /** Hash many files with a bounded worker pool (IO-bound, cheap per file). */
6574
+ async function hashFilesParallel(relPaths, workspace, signal, onProgress) {
6575
+ let cpus = 4;
6576
+ try {
6577
+ cpus = os.cpus().length;
6578
+ } catch {}
6579
+ const concurrency = Math.max(1, Math.min(16, cpus, relPaths.length));
6580
+ const out = {};
6581
+ let next = 0;
6582
+ let scanned = 0;
6583
+ const workers = Array.from({ length: concurrency }, async () => {
6584
+ for (;;) {
6585
+ if (signal?.aborted) break;
6586
+ const i = next;
6587
+ next += 1;
6588
+ if (i >= relPaths.length) break;
6589
+ const rel = relPaths[i];
6590
+ const hash = await hashFile(path.join(workspace, rel));
6591
+ if (hash !== void 0) out[rel] = hash;
6592
+ scanned += 1;
6593
+ onProgress?.(scanned, relPaths.length);
6594
+ }
6595
+ });
6596
+ await Promise.all(workers);
6597
+ return out;
6598
+ }
6469
6599
  /** Fire-and-forget per-workspace populate (single-flight). Never throws. */
6470
6600
  function kickServiceIndex(workspace) {
6471
6601
  const key = path.resolve(workspace);
6472
6602
  if (_populateInFlight.has(key)) return;
6473
6603
  _populateInFlight.add(key);
6474
- populateWorkspace(workspace).catch((err) => {
6604
+ const p = populateWorkspace(workspace).catch((err) => {
6475
6605
  consola.debug(`service-backend: populate failed for ${workspace}: ${err.message}`);
6476
6606
  }).finally(() => {
6477
6607
  _populateInFlight.delete(key);
6608
+ _populatePromises.delete(p);
6478
6609
  });
6610
+ _populatePromises.add(p);
6479
6611
  }
6480
6612
  /** Max files enumerated per populate (whole-repo cap for v1). */
6481
6613
  const POPULATE_MAX_FILES = 2e4;
@@ -6537,36 +6669,245 @@ function resolveRipgrepBin() {
6537
6669
  return "rg";
6538
6670
  }
6539
6671
  }
6540
- async function populateWorkspace(workspace) {
6541
- const svc = await ensureServer();
6542
- if (!svc) return;
6672
+ /**
6673
+ * Wait for delete batches to merge: the doc count must fall to the
6674
+ * expected post-delete level. Deletes rebuild PLAID partitions (seconds),
6675
+ * far slower than update merges — sending updates first risks a late
6676
+ * delete wiping the new units, which is unrecoverable data loss (the
6677
+ * file predicate cannot tell old units from new ones).
6678
+ *
6679
+ * Throws on timeout WITHOUT writing the sidecar, so a later run retries
6680
+ * the same classification instead of recording a lie. Callers must only
6681
+ * invoke this when at least one counted delete was issued; a fully
6682
+ * unknown drop has no observable target (see the unknown-file handling
6683
+ * at the call site).
6684
+ */
6685
+ async function waitForDocCountDrop(client, index, target, opts = {}, signal) {
6686
+ const timeoutMs = opts.timeoutMs ?? 12e4;
6687
+ const pollMs = opts.pollMs ?? 250;
6688
+ const start = Date.now();
6689
+ let last = Number.POSITIVE_INFINITY;
6690
+ for (;;) {
6691
+ if (signal?.aborted) throw new Error("populate aborted");
6692
+ const count = await client.health().then((h) => h.indices.find((i) => i.name === index)?.num_documents).catch(() => void 0);
6693
+ if (count !== void 0) {
6694
+ last = count;
6695
+ if (count <= target) return count;
6696
+ }
6697
+ if (Date.now() - start >= timeoutMs) throw new Error(`delete batches for ${index} did not merge within ${Math.round(timeoutMs / 1e3)}s (docs=${Number.isFinite(last) ? last : "unknown"}, target<=${target})`);
6698
+ await new Promise((r) => {
6699
+ setTimeout(r, pollMs).unref?.();
6700
+ });
6701
+ }
6702
+ }
6703
+ /**
6704
+ * Wait for the server's async write queue to settle after a populate.
6705
+ *
6706
+ * `updateDocuments`/`deleteDocuments` return 202 on ACCEPT, not on merge —
6707
+ * reporting ready (or reading `docCount`) immediately would observe the
6708
+ * pre-merge state: searches miss new units, and the unchanged fast-path
6709
+ * anchor (`num_documents > 0`) never fires. Update batches are visible in
6710
+ * `/health.updates[]` (`running` → `complete`); delete batches are NOT, so
6711
+ * count stability is the second signal and `waitForDocCountDrop` (above)
6712
+ * gates the delete phase separately.
6713
+ */
6714
+ async function waitForIndexSettled(client, index, expectDocs, opts = {}, signal) {
6715
+ const minWaitMs = opts.minWaitMs ?? 2e3;
6716
+ const timeoutMs = opts.timeoutMs ?? 6e4;
6717
+ const pollMs = opts.pollMs ?? 250;
6718
+ const start = Date.now();
6719
+ let prev;
6720
+ for (;;) {
6721
+ if (signal?.aborted) return prev;
6722
+ const h = await client.health().catch(() => void 0);
6723
+ const count = h?.indices.find((i) => i.name === index)?.num_documents;
6724
+ const running = h?.updates?.some((u) => u.index === index && u.status !== "complete") ?? false;
6725
+ const elapsed = Date.now() - start;
6726
+ if (count !== void 0) {
6727
+ if (elapsed >= minWaitMs && prev !== void 0 && prev === count && !running && (!expectDocs || count > 0)) return count;
6728
+ prev = count;
6729
+ }
6730
+ if (elapsed >= timeoutMs) return prev;
6731
+ await new Promise((r) => {
6732
+ setTimeout(r, pollMs).unref?.();
6733
+ });
6734
+ }
6735
+ }
6736
+ /**
6737
+ * Populate (or refresh) a workspace's service index with TRUE DELTA
6738
+ * semantics: only files whose content hash changed since the last
6739
+ * successful populate are re-extracted and re-encoded; unchanged files are
6740
+ * never re-embedded; removed files have their documents deleted.
6741
+ *
6742
+ * The sidecar is written ONLY on success, so a failed/interrupted run
6743
+ * retries cleanly (stale hashes ⇒ same classification next time).
6744
+ */
6745
+ async function populateWorkspace(workspace, opts = {}) {
6543
6746
  const canonical = canonicalWorkspace(workspace);
6544
6747
  const index = indexNameForWorkspace(canonical);
6545
- await svc.client.ensureIndex(index, { nbits: 4 });
6748
+ const prev = await readServiceMeta(canonical);
6749
+ const prevHashes = prev?.fileHashes ?? {};
6750
+ const prevUnits = prev?.fileUnits ?? {};
6751
+ const hasBaseline = prev !== null && prev.fileHashes !== void 0 && prev.fileUnits !== void 0 && !opts.full;
6546
6752
  const rgPath = resolveRipgrepBin();
6547
6753
  const ac = new AbortController();
6548
6754
  const timeout = setTimeout(() => ac.abort(), 18e5);
6549
6755
  timeout.unref?.();
6756
+ const signal = opts.signal ? anySignal([opts.signal, ac.signal]) : ac.signal;
6550
6757
  try {
6551
- const parseable = (await enumerateSourceFiles(rgPath, canonical, ac.signal)).filter((f) => getLanguageKeyForPath(f) !== null);
6758
+ const parseable = (await enumerateSourceFiles(rgPath, canonical, signal)).filter((f) => getLanguageKeyForPath(f) !== null);
6759
+ opts.onProgress?.({
6760
+ phase: "enumerate",
6761
+ scanned: 0,
6762
+ total: parseable.length,
6763
+ unchanged: 0,
6764
+ updatedFiles: 0,
6765
+ removedFiles: 0,
6766
+ units: 0
6767
+ });
6768
+ const currentHashes = await hashFilesParallel(parseable, canonical, signal, (scanned, total) => {
6769
+ opts.onProgress?.({
6770
+ phase: "hash",
6771
+ scanned,
6772
+ total,
6773
+ unchanged: 0,
6774
+ updatedFiles: 0,
6775
+ removedFiles: 0,
6776
+ units: 0
6777
+ });
6778
+ });
6779
+ if (signal.aborted) throw new Error("populate aborted");
6780
+ const changed = [];
6781
+ let unchanged = 0;
6782
+ for (const rel of parseable) {
6783
+ const current = currentHashes[rel];
6784
+ if (current === void 0) continue;
6785
+ if (hasBaseline && prevHashes[rel] === current) unchanged += 1;
6786
+ else changed.push(rel);
6787
+ }
6788
+ const currentSet = new Set(parseable);
6789
+ const removed = hasBaseline ? Object.keys(prevHashes).filter((rel) => !currentSet.has(rel)) : [];
6790
+ if (opts.dryRun) return {
6791
+ status: "dry-run",
6792
+ scanned: parseable.length,
6793
+ unchanged,
6794
+ updatedFiles: changed.length,
6795
+ removedFiles: removed.length,
6796
+ units: 0
6797
+ };
6798
+ const svc = await ensureServer(opts.foreground === true ? { foreground: true } : void 0);
6799
+ if (!svc) throw new Error("service server unavailable");
6800
+ await svc.client.ensureIndex(index, { nbits: 4 });
6801
+ if (hasBaseline && changed.length === 0 && removed.length === 0) {
6802
+ const known = await svc.client.health().then((h) => h.indices.find((i) => i.name === index)).catch(() => void 0);
6803
+ if (known && known.num_documents > 0) {
6804
+ const g = await gitState(canonical).catch(() => ({ isRepo: false }));
6805
+ const carriedHashes = { ...currentHashes };
6806
+ const carriedUnits = {};
6807
+ for (const rel of parseable) if (currentHashes[rel] !== void 0) carriedUnits[rel] = prevUnits[rel] ?? 0;
6808
+ else {
6809
+ if (prevHashes[rel] !== void 0) carriedHashes[rel] = prevHashes[rel];
6810
+ if (prevUnits[rel] !== void 0) carriedUnits[rel] = prevUnits[rel];
6811
+ }
6812
+ await writeServiceMeta({
6813
+ workspace: canonical,
6814
+ index,
6815
+ ...g.isRepo ? {
6816
+ head: g.head,
6817
+ dirty: g.dirty ?? false
6818
+ } : {},
6819
+ indexedAt: (/* @__PURE__ */ new Date()).toISOString(),
6820
+ docCount: known.num_documents,
6821
+ fileHashes: carriedHashes,
6822
+ fileUnits: carriedUnits,
6823
+ modelRev: MODEL_REVISION
6824
+ });
6825
+ opts.onProgress?.({
6826
+ phase: "done",
6827
+ scanned: parseable.length,
6828
+ total: parseable.length,
6829
+ unchanged,
6830
+ updatedFiles: 0,
6831
+ removedFiles: 0,
6832
+ units: 0
6833
+ });
6834
+ return {
6835
+ status: "unchanged",
6836
+ scanned: parseable.length,
6837
+ unchanged,
6838
+ updatedFiles: 0,
6839
+ removedFiles: 0,
6840
+ units: 0,
6841
+ docCount: known.num_documents
6842
+ };
6843
+ }
6844
+ changed.push(...parseable.filter((rel) => currentHashes[rel] !== void 0));
6845
+ unchanged = 0;
6846
+ }
6847
+ if (!hasBaseline) {
6848
+ if ((await svc.client.health().then((h) => h.indices.find((i) => i.name === index)?.num_documents).catch(() => void 0) ?? 0) > 0) if (await svc.client.dropIndex(index).catch(() => false)) await svc.client.ensureIndex(index, { nbits: 4 });
6849
+ else {
6850
+ consola.warn(`service-backend: index drop unsupported, per-file reset for ${canonical}`);
6851
+ for (const rel of changed) {
6852
+ if (signal.aborted) throw new Error("populate aborted");
6853
+ await svc.client.deleteDocuments(index, "file = ?", [rel]);
6854
+ }
6855
+ await waitForIndexSettled(svc.client, index, false, {
6856
+ minWaitMs: 5e3,
6857
+ ...opts.settle ?? {}
6858
+ }, signal);
6859
+ }
6860
+ if (signal.aborted) throw new Error("populate aborted");
6861
+ } else {
6862
+ const deleteTargets = [...changed, ...removed].filter((rel) => (prevUnits[rel] ?? 0) > 0);
6863
+ const expectedDrop = deleteTargets.reduce((sum, rel) => sum + (prevUnits[rel] ?? 0), 0);
6864
+ if (deleteTargets.length > 0) {
6865
+ const before = await svc.client.health().then((h) => h.indices.find((i) => i.name === index)?.num_documents).catch(() => void 0);
6866
+ for (const rel of deleteTargets) {
6867
+ if (signal.aborted) throw new Error("populate aborted");
6868
+ await svc.client.deleteDocuments(index, "file = ?", [rel]);
6869
+ }
6870
+ if (expectedDrop > 0 && before !== void 0) await waitForDocCountDrop(svc.client, index, before - expectedDrop, {
6871
+ timeoutMs: 12e4,
6872
+ ...opts.settle ?? {}
6873
+ }, signal);
6874
+ if (signal.aborted) throw new Error("populate aborted");
6875
+ }
6876
+ }
6877
+ let cpus = 4;
6878
+ try {
6879
+ cpus = os.cpus().length;
6880
+ } catch {}
6881
+ const parseConcurrency = opts.foreground === true ? Math.max(4, Math.min(16, cpus)) : POPULATE_PARSE_CONCURRENCY;
6552
6882
  let units = [];
6553
6883
  let unitTotal = 0;
6884
+ const fileUnitCounts = {};
6554
6885
  const flush = async () => {
6555
6886
  if (units.length === 0) return;
6556
6887
  const batch = units;
6557
6888
  units = [];
6558
6889
  await svc.client.updateDocuments(index, batch.map((u) => u.text), batch.map((u) => u.metadata));
6559
6890
  unitTotal += batch.length;
6891
+ opts.onProgress?.({
6892
+ phase: "encode",
6893
+ scanned: parseable.length,
6894
+ total: parseable.length,
6895
+ unchanged,
6896
+ updatedFiles: changed.length,
6897
+ removedFiles: removed.length,
6898
+ units: unitTotal
6899
+ });
6560
6900
  };
6561
6901
  let next = 0;
6562
- const workers = Array.from({ length: Math.min(POPULATE_PARSE_CONCURRENCY, parseable.length) }, async () => {
6563
- while (!ac.signal.aborted) {
6902
+ const workers = Array.from({ length: Math.min(parseConcurrency, Math.max(changed.length, 1)) }, async () => {
6903
+ while (!signal.aborted) {
6564
6904
  const i = next;
6565
6905
  next += 1;
6566
- if (i >= parseable.length) break;
6567
- const rel = parseable[i];
6906
+ if (i >= changed.length) break;
6907
+ const rel = changed[i];
6568
6908
  try {
6569
- const r = await extractUnits(path.join(canonical, rel), rel, ac.signal);
6909
+ const r = await extractUnits(path.join(canonical, rel), rel, signal);
6910
+ fileUnitCounts[rel] = r.units.length;
6570
6911
  for (const u of r.units) {
6571
6912
  units.push({
6572
6913
  text: buildUnitText(u, rel),
@@ -6587,6 +6928,17 @@ async function populateWorkspace(workspace) {
6587
6928
  });
6588
6929
  await Promise.all(workers);
6589
6930
  await flush();
6931
+ if (signal.aborted) throw new Error("populate aborted");
6932
+ const docCount = await waitForIndexSettled(svc.client, index, unitTotal > 0, opts.settle ?? {}, signal);
6933
+ if (signal.aborted) throw new Error("populate aborted");
6934
+ const mergedHashes = { ...currentHashes };
6935
+ const mergedUnits = {};
6936
+ for (const rel of parseable) if (currentHashes[rel] === void 0) {
6937
+ if (prevHashes[rel] !== void 0) mergedHashes[rel] = prevHashes[rel];
6938
+ if (prevUnits[rel] !== void 0) mergedUnits[rel] = prevUnits[rel];
6939
+ } else if (hasBaseline && prevHashes[rel] === currentHashes[rel]) mergedUnits[rel] = prevUnits[rel] ?? 0;
6940
+ else if (fileUnitCounts[rel] !== void 0) mergedUnits[rel] = fileUnitCounts[rel];
6941
+ else delete mergedHashes[rel];
6590
6942
  const g = await gitState(canonical).catch(() => ({ isRepo: false }));
6591
6943
  await writeServiceMeta({
6592
6944
  workspace: canonical,
@@ -6596,13 +6948,47 @@ async function populateWorkspace(workspace) {
6596
6948
  dirty: g.dirty ?? false
6597
6949
  } : {},
6598
6950
  indexedAt: (/* @__PURE__ */ new Date()).toISOString(),
6599
- docCount: unitTotal
6951
+ docCount,
6952
+ fileHashes: mergedHashes,
6953
+ fileUnits: mergedUnits,
6954
+ modelRev: MODEL_REVISION
6600
6955
  });
6601
6956
  consola.debug(`service-backend: indexed ${unitTotal} units in ${canonical}`);
6957
+ opts.onProgress?.({
6958
+ phase: "done",
6959
+ scanned: parseable.length,
6960
+ total: parseable.length,
6961
+ unchanged,
6962
+ updatedFiles: changed.length,
6963
+ removedFiles: removed.length,
6964
+ units: unitTotal
6965
+ });
6966
+ return {
6967
+ status: "ready",
6968
+ scanned: parseable.length,
6969
+ unchanged,
6970
+ updatedFiles: changed.length,
6971
+ removedFiles: removed.length,
6972
+ units: unitTotal,
6973
+ docCount
6974
+ };
6602
6975
  } finally {
6603
6976
  clearTimeout(timeout);
6604
6977
  }
6605
6978
  }
6979
+ /** Combine abort signals (cleanup listeners once settled). */
6980
+ function anySignal(signals) {
6981
+ const ac = new AbortController();
6982
+ const onAbort = () => ac.abort();
6983
+ for (const s of signals) {
6984
+ if (s.aborted) {
6985
+ ac.abort();
6986
+ break;
6987
+ }
6988
+ s.addEventListener("abort", onAbort, { once: true });
6989
+ }
6990
+ return ac.signal;
6991
+ }
6606
6992
  /**
6607
6993
  * Search via the service backend. Returns `unavailable` (caller falls back
6608
6994
  * to colgrep/lexical) when the server, model, or index isn't ready; `failed`
@@ -6669,6 +7055,6 @@ function buildSnippet(h) {
6669
7055
  return sig.length > 0 ? `${sig}\n${h.file}:${h.line}` : `${h.file}:${h.line}`;
6670
7056
  }
6671
7057
  //#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 };
7058
+ export { confineToWorkspaceResult as A, provisionColbert as C, resolveRipgrep as D, extractZipMember as E, provisionTreeSitterAssets as F, withInstallLock as I, recommendedRgThreads as M, warmTreeSitterPool as N, searchCode as O, outlineFile as P, colbertSmokeOk as S, extractTarGzMember as T, gitState as _, semanticBackend as a, validateIndexIntegrity as b, serviceFreshness as c, runSemanticSearch as d, startupKickAllowed as f, freshnessVerdict as g, completedIndexOnDisk as h, selectServerVariant as i, isSensitivePath as j, validateWorkspace as k, stopServiceServer as l, colbertProjectDir as m, populateWorkspace as n, serviceBackendEnabled as o, waitForInit as p, runServiceSearch as r, serviceBackendProvisionable as s, ensureServerForeground as t, kickBackgroundInit as u, indexDirSignature as v, provisionNextPlaidServer as w, colbertArtifactsPresent as x, readColbertMeta as y };
6673
7059
 
6674
- //# sourceMappingURL=service-backend-DYEPoszR.js.map
7060
+ //# sourceMappingURL=service-backend-7SPDLUB9.js.map