@gmickel/gno 2.16.0 → 2.17.0

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 (46) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/SKILL.md +27 -0
  3. package/assets/skill/cli-reference.md +20 -13
  4. package/browser-extension/artifacts/{gno-browser-clipper-v2.16.0.zip → gno-browser-clipper-v2.17.0.zip} +0 -0
  5. package/browser-extension/artifacts/gno-browser-clipper-v2.17.0.zip.sha256 +1 -0
  6. package/browser-extension/dist/manifest.json +1 -1
  7. package/package.json +1 -1
  8. package/spec/cli.md +42 -2
  9. package/spec/db/schema.sql +53 -1
  10. package/spec/mcp.md +9 -3
  11. package/spec/output-schemas/doctor.schema.json +27 -0
  12. package/spec/output-schemas/retrieval-trace-payloads.schema.json +14 -0
  13. package/spec/output-schemas/search-results.schema.json +14 -0
  14. package/spec/output-schemas/status.schema.json +22 -0
  15. package/src/cli/commands/doctor.ts +101 -29
  16. package/src/cli/commands/links.ts +29 -5
  17. package/src/cli/commands/vec.ts +180 -8
  18. package/src/cli/program.ts +43 -0
  19. package/src/config/types.ts +6 -0
  20. package/src/core/retrieval-trace-session.ts +3 -0
  21. package/src/core/retrieval-trace.ts +9 -0
  22. package/src/core/vector-partition-status.ts +13 -0
  23. package/src/embed/variant-backlog.ts +36 -2
  24. package/src/mcp/tools/links.ts +7 -1
  25. package/src/pipeline/explain.ts +17 -2
  26. package/src/pipeline/hybrid.ts +28 -1
  27. package/src/pipeline/types.ts +7 -0
  28. package/src/pipeline/vsearch.ts +19 -2
  29. package/src/serve/public/globals.built.css +1 -1
  30. package/src/serve/routes/links.ts +7 -1
  31. package/src/store/migrations/038-vector-mirror-null-cosine.ts +47 -0
  32. package/src/store/migrations/039-vector-mirror-v2.ts +94 -0
  33. package/src/store/migrations/index.ts +4 -0
  34. package/src/store/sqlite/adapter.ts +117 -74
  35. package/src/store/vector/coarse-router.ts +312 -0
  36. package/src/store/vector/partition-index.ts +309 -18
  37. package/src/store/vector/proof-cache.ts +132 -26
  38. package/src/store/vector/runtime-compat.ts +6 -0
  39. package/src/store/vector/sqlite-vec.ts +43 -26
  40. package/src/store/vector/stats.ts +8 -0
  41. package/src/store/vector/status.ts +18 -1
  42. package/src/store/vector/types.ts +9 -0
  43. package/src/store/vector/v2-mirror.ts +669 -0
  44. package/src/store/vector/variant-search.ts +434 -20
  45. package/src/store/vector/variants.ts +480 -32
  46. package/browser-extension/artifacts/gno-browser-clipper-v2.16.0.zip.sha256 +0 -1
@@ -14,8 +14,9 @@ import {
14
14
  createVectorStatsPort,
15
15
  } from "../../store/vector";
16
16
  import {
17
- rebuildPartitionIndex,
18
- syncPartitionIndex,
17
+ pruneLegacyVectors,
18
+ rebuildPartitionIndexWithDetails,
19
+ syncPartitionIndexWithDetails,
19
20
  } from "../../store/vector/partition-index";
20
21
  import {
21
22
  dropVectorPartition,
@@ -35,11 +36,25 @@ export interface VecOptions {
35
36
  }
36
37
 
37
38
  export type VecSyncResult =
38
- | { success: true; added: number; removed: number; model: string }
39
+ | {
40
+ success: true;
41
+ added: number;
42
+ removed: number;
43
+ v2Added?: number;
44
+ v2Removed?: number;
45
+ checkRecall?: number | null;
46
+ model: string;
47
+ }
39
48
  | { success: false; error: string };
40
49
 
41
50
  export type VecRebuildResult =
42
- | { success: true; count: number; model: string }
51
+ | {
52
+ success: true;
53
+ count: number;
54
+ v2Count?: number;
55
+ checkRecall?: number | null;
56
+ model: string;
57
+ }
43
58
  | { success: false; error: string };
44
59
 
45
60
  // ─────────────────────────────────────────────────────────────────────────────
@@ -130,7 +145,7 @@ export async function vecSync(
130
145
  }
131
146
  return {
132
147
  success: true,
133
- ...syncPartitionIndex(db, partition),
148
+ ...syncPartitionIndexWithDetails(db, partition),
134
149
  model: modelUri,
135
150
  };
136
151
  }
@@ -223,9 +238,14 @@ export async function vecRebuild(
223
238
  error: "sqlite-vec not available. Cannot rebuild index.",
224
239
  };
225
240
  }
241
+ const rebuilt = rebuildPartitionIndexWithDetails(db, partition);
226
242
  return {
227
243
  success: true,
228
- count: rebuildPartitionIndex(db, partition),
244
+ count: rebuilt.count,
245
+ ...(rebuilt.v2Count !== undefined ? { v2Count: rebuilt.v2Count } : {}),
246
+ ...(rebuilt.checkRecall !== undefined
247
+ ? { checkRecall: rebuilt.checkRecall }
248
+ : {}),
229
249
  model: modelUri,
230
250
  };
231
251
  }
@@ -294,6 +314,13 @@ export function formatVecSync(
294
314
  {
295
315
  added: result.added,
296
316
  removed: result.removed,
317
+ ...(result.v2Added !== undefined ? { v2Added: result.v2Added } : {}),
318
+ ...(result.v2Removed !== undefined
319
+ ? { v2Removed: result.v2Removed }
320
+ : {}),
321
+ ...(result.checkRecall !== undefined
322
+ ? { checkRecall: result.checkRecall }
323
+ : {}),
297
324
  model: result.model,
298
325
  },
299
326
  null,
@@ -301,7 +328,8 @@ export function formatVecSync(
301
328
  );
302
329
  }
303
330
 
304
- if (result.added === 0 && result.removed === 0) {
331
+ const v2Changed = (result.v2Added ?? 0) > 0 || (result.v2Removed ?? 0) > 0;
332
+ if (result.added === 0 && result.removed === 0 && !v2Changed) {
305
333
  return "Vec index already in sync.";
306
334
  }
307
335
 
@@ -312,6 +340,15 @@ export function formatVecSync(
312
340
  if (result.removed > 0) {
313
341
  parts.push(`-${result.removed} removed`);
314
342
  }
343
+ if (v2Changed) {
344
+ const v2Parts: string[] = [];
345
+ if ((result.v2Added ?? 0) > 0) v2Parts.push(`+${result.v2Added}`);
346
+ if ((result.v2Removed ?? 0) > 0) v2Parts.push(`-${result.v2Removed}`);
347
+ parts.push(`coarse mirror ${v2Parts.join("/")}`);
348
+ }
349
+ if (result.checkRecall !== undefined && result.checkRecall !== null) {
350
+ parts.push(`recall@10=${(result.checkRecall * 100).toFixed(1)}%`);
351
+ }
315
352
  return `Vec index synced: ${parts.join(", ")}`;
316
353
  }
317
354
 
@@ -329,6 +366,10 @@ export function formatVecRebuild(
329
366
  return JSON.stringify(
330
367
  {
331
368
  count: result.count,
369
+ ...(result.v2Count !== undefined ? { v2Count: result.v2Count } : {}),
370
+ ...(result.checkRecall !== undefined
371
+ ? { checkRecall: result.checkRecall }
372
+ : {}),
332
373
  model: result.model,
333
374
  },
334
375
  null,
@@ -336,7 +377,15 @@ export function formatVecRebuild(
336
377
  );
337
378
  }
338
379
 
339
- return `Vec index rebuilt: ${result.count.toLocaleString()} vectors`;
380
+ const extras: string[] = [];
381
+ if (result.v2Count !== undefined) {
382
+ extras.push(`coarse mirror ${result.v2Count.toLocaleString()} rows`);
383
+ }
384
+ if (result.checkRecall !== undefined && result.checkRecall !== null) {
385
+ extras.push(`recall@10=${(result.checkRecall * 100).toFixed(1)}%`);
386
+ }
387
+ const suffix = extras.length > 0 ? ` (${extras.join(", ")})` : "";
388
+ return `Vec index rebuilt: ${result.count.toLocaleString()} vectors${suffix}`;
340
389
  }
341
390
 
342
391
  export type VecDropResult =
@@ -388,3 +437,126 @@ export function formatVecDrop(
388
437
  ? JSON.stringify({ dropped: partition }, null, 2)
389
438
  : `Dropped ${partition.state} partition ${partition.id.slice(0, 12)} (${partition.provenance}, ${partition.owners} chunks)`;
390
439
  }
440
+
441
+ export interface VecPruneOptions extends VecOptions {
442
+ /** Run SQLite VACUUM after pruning to reclaim disk space in-place. */
443
+ vacuum?: boolean;
444
+ }
445
+
446
+ export type VecPruneResult =
447
+ | {
448
+ success: true;
449
+ droppedTables: string[];
450
+ removedRows: number;
451
+ vacuumed: boolean;
452
+ }
453
+ | { success: false; error: string };
454
+
455
+ /**
456
+ * Drop superseded legacy `vec_<hash>` tables and delete legacy `content_vectors`
457
+ * rows for models that already have an activated v1 partition, plus any
458
+ * orphaned `vec_v1_*` tables absent from `vector_partitions`.
459
+ */
460
+ export async function vecPrune(
461
+ options: VecPruneOptions = {}
462
+ ): Promise<VecPruneResult> {
463
+ if (!(await isInitialized(options.configPath))) {
464
+ return { success: false, error: "GNO not initialized. Run: gno init" };
465
+ }
466
+ const configResult = await loadConfig(options.configPath);
467
+ if (!configResult.ok) {
468
+ return { success: false, error: configResult.error.message };
469
+ }
470
+ const config = configResult.value;
471
+
472
+ const store = new SqliteAdapter();
473
+ const dbPath = getIndexDbPath(options.indexName);
474
+ const paths = getConfigPaths();
475
+ store.setConfigPath(paths.configFile);
476
+
477
+ const openResult = await store.open(
478
+ dbPath,
479
+ config.ftsTokenizer,
480
+ config.busyTimeoutMs
481
+ );
482
+ if (!openResult.ok) {
483
+ return { success: false, error: openResult.error.message };
484
+ }
485
+
486
+ try {
487
+ const db = store.getRawDb();
488
+ const pruned = await pruneLegacyVectors(db);
489
+ if (!pruned.ok) {
490
+ return { success: false, error: pruned.error };
491
+ }
492
+ if (options.vacuum) {
493
+ try {
494
+ db.exec("VACUUM");
495
+ } catch (vacuumCause) {
496
+ const vacuumMsg =
497
+ vacuumCause instanceof Error
498
+ ? vacuumCause.message
499
+ : String(vacuumCause);
500
+ return {
501
+ success: false,
502
+ error: `Pruned ${pruned.droppedTables.length} legacy table(s) and ${pruned.removedRows.toLocaleString()} legacy row(s), but VACUUM failed: ${vacuumMsg}. The prune already committed; reclaim disk space with VACUUM INTO or retry gno vec prune --vacuum.`,
503
+ };
504
+ }
505
+ }
506
+ return {
507
+ success: true,
508
+ droppedTables: pruned.droppedTables,
509
+ removedRows: pruned.removedRows,
510
+ vacuumed: Boolean(options.vacuum),
511
+ };
512
+ } catch (cause) {
513
+ return {
514
+ success: false,
515
+ error:
516
+ cause instanceof Error
517
+ ? cause.message
518
+ : "Failed to prune legacy vector tables",
519
+ };
520
+ } finally {
521
+ await store.close();
522
+ }
523
+ }
524
+
525
+ export function formatVecPrune(
526
+ result: VecPruneResult,
527
+ options: { json?: boolean }
528
+ ): string {
529
+ if (!result.success) {
530
+ return options.json
531
+ ? JSON.stringify({ error: { code: "RUNTIME", message: result.error } })
532
+ : `Error: ${result.error}`;
533
+ }
534
+ if (options.json) {
535
+ return JSON.stringify(
536
+ {
537
+ droppedTables: result.droppedTables,
538
+ removedRows: result.removedRows,
539
+ vacuumed: result.vacuumed,
540
+ },
541
+ null,
542
+ 2
543
+ );
544
+ }
545
+ if (result.droppedTables.length === 0 && result.removedRows === 0) {
546
+ return result.vacuumed
547
+ ? "No legacy vector tables or rows to prune. Database vacuumed."
548
+ : "No legacy vector tables or rows to prune.";
549
+ }
550
+ const lines = [
551
+ `Pruned ${result.droppedTables.length} legacy table(s) and ${result.removedRows.toLocaleString()} legacy row(s)${result.vacuumed ? "; database vacuumed." : "."}`,
552
+ ];
553
+ if (result.droppedTables.length > 0) {
554
+ lines.push(`Dropped tables: ${result.droppedTables.join(", ")}`);
555
+ }
556
+ if (!result.vacuumed) {
557
+ lines.push(
558
+ "Disk space is reclaimed only after vacuuming (for large indexes, run SQLite VACUUM INTO a new file and swap it in, or rerun with --vacuum)."
559
+ );
560
+ }
561
+ return lines.join("\n");
562
+ }
@@ -3908,6 +3908,49 @@ function wireVecCommands(program: Command): void {
3908
3908
  `${formatVecRebuild(result, { json: format === "json" })}\n`
3909
3909
  );
3910
3910
  });
3911
+
3912
+ // vec prune
3913
+ addWriteLeaseFlags(
3914
+ vecCmd
3915
+ .command("prune")
3916
+ .description(
3917
+ "Remove superseded legacy vector tables and orphaned vec_v1 mirrors"
3918
+ )
3919
+ .option(
3920
+ "--vacuum",
3921
+ "Run SQLite VACUUM after pruning to reclaim disk space"
3922
+ )
3923
+ .option("--json", "JSON output")
3924
+ ).action(async (cmdOpts: Record<string, unknown>) => {
3925
+ const format = getFormat(cmdOpts);
3926
+ const globals = getGlobals();
3927
+
3928
+ const { vecPrune, formatVecPrune } = await import("./commands/vec");
3929
+ const lease = parseWriteLeaseFlags(cmdOpts);
3930
+ const result = await withCliWriteLease(
3931
+ {
3932
+ indexName: globals.index,
3933
+ lockWaitMs: lease.lockWaitMs,
3934
+ noWait: lease.noWait,
3935
+ },
3936
+ () =>
3937
+ vecPrune({
3938
+ configPath: globals.config,
3939
+ indexName: globals.index,
3940
+ vacuum: Boolean(cmdOpts.vacuum),
3941
+ json: format === "json",
3942
+ })
3943
+ );
3944
+ throwIfWriteLeaseBusy(result, format === "json");
3945
+
3946
+ if (!result.success) {
3947
+ throw new CliError("RUNTIME", result.error);
3948
+ }
3949
+
3950
+ process.stdout.write(
3951
+ `${formatVecPrune(result, { json: format === "json" })}\n`
3952
+ );
3953
+ });
3911
3954
  }
3912
3955
 
3913
3956
  function wirePublishCommand(program: Command): void {
@@ -683,6 +683,12 @@ export const ConfigSchema = z.object({
683
683
  )
684
684
  .default(DEFAULT_BUSY_TIMEOUT_MS),
685
685
 
686
+ /**
687
+ * Toggle cost-routed two-stage bit coarse vec0 mirror routing for large vector scopes.
688
+ * Defaults to true; set to false to keep all searches on the exact paths.
689
+ */
690
+ coarseVectorSearch: z.boolean().optional(),
691
+
686
692
  /** Optional terminal hyperlink editor URI template */
687
693
  editorUriTemplate: z.string().min(1).optional(),
688
694
 
@@ -347,6 +347,9 @@ export class RetrievalTraceSession {
347
347
  capabilities,
348
348
  fallbackCodes,
349
349
  ...(latencyMs === undefined ? {} : { latencyMs }),
350
+ ...(traceMetadata?.vectorRoute === undefined
351
+ ? {}
352
+ : { vectorRoute: traceMetadata.vectorRoute }),
350
353
  };
351
354
  const runId = this.nextId("retrieval-run");
352
355
  const run = await this.recorder.appendRun({
@@ -143,12 +143,21 @@ const evidencePayloadSchema = z
143
143
  latencyMs: z.number().finite().nonnegative().optional(),
144
144
  })
145
145
  .strict();
146
+ const vectorRouteSchema = z
147
+ .object({
148
+ route: z.enum(["exact-sql", "exact-vec0", "coarse-bit"]),
149
+ mirrorRows: z.number().int().nonnegative(),
150
+ coarseK: z.number().int().positive().optional(),
151
+ rescored: z.number().int().nonnegative().optional(),
152
+ })
153
+ .strict();
146
154
  const retrievalPayloadSchema = z
147
155
  .object({
148
156
  ranked: z.array(evidenceRefSchema).max(10_000),
149
157
  latencyMs: z.number().finite().nonnegative().optional(),
150
158
  capabilities: z.array(z.string().min(1).max(128)).max(100).optional(),
151
159
  fallbackCodes: z.array(z.string().min(1).max(128)).max(100).optional(),
160
+ vectorRoute: vectorRouteSchema.optional(),
152
161
  })
153
162
  .strict();
154
163
  const contextPayloadSchema = evidencePayloadSchema.extend({
@@ -47,6 +47,19 @@ export function formatVectorPartitionLines(
47
47
  lines.push(` read by: ${p.compatibleRuntimes.join("; ")}`);
48
48
  if (p.incompatibleRuntimes.length)
49
49
  lines.push(` incompatible: ${p.incompatibleRuntimes.join("; ")}`);
50
+ if (p.coarseMirror && p.coarseMirror.state !== "unsupported") {
51
+ const recallPart =
52
+ p.coarseMirror.checkRecall !== null
53
+ ? `, recall@10=${(p.coarseMirror.checkRecall * 100).toFixed(1)}% (${p.coarseMirror.checkQueries ?? 0}q, coarseK=${p.coarseMirror.checkCoarseK ?? 200})${p.coarseMirror.belowFloor ? " [below 95% floor]" : ""}`
54
+ : ", self-check=not run";
55
+ const repairHint =
56
+ p.coarseMirror.state === "dirty" || p.coarseMirror.state === "missing"
57
+ ? " (repair with: gno vec sync)"
58
+ : "";
59
+ lines.push(
60
+ ` coarse mirror: ${p.coarseMirror.state}${recallPart}${repairHint}`
61
+ );
62
+ }
50
63
  }
51
64
  return lines;
52
65
  }
@@ -719,7 +719,38 @@ export async function embedVariantBacklog(
719
719
  // sqlite-vec, keep the full check below.
720
720
  if (identityStillCurrent() && store.hasActivated()) {
721
721
  const mirror = store.mirrorState();
722
- if (mirror === "clean") {
722
+ const v2Mirror = store.v2MirrorState();
723
+ const needsV2Repair = v2Mirror === "dirty" || v2Mirror === "missing";
724
+ if (mirror === "clean" && !needsV2Repair) {
725
+ if (v2Mirror === "clean") {
726
+ const checkTurn = await inWriteTurn(
727
+ deps.acquireWriteTurn,
728
+ async () => {
729
+ try {
730
+ store.ensureV2RecallSelfCheck();
731
+ return undefined;
732
+ } catch (cause) {
733
+ return cause instanceof Error ? cause.message : String(cause);
734
+ }
735
+ }
736
+ );
737
+ if (checkTurn.deferred) return ok({ ...total, deferred: true });
738
+ }
739
+ assertInferenceActive();
740
+ return ok(total);
741
+ }
742
+ if (mirror === "clean" && needsV2Repair) {
743
+ const turn = await inWriteTurn(deps.acquireWriteTurn, async () => {
744
+ try {
745
+ store.syncV2Index();
746
+ return undefined;
747
+ } catch (cause) {
748
+ return cause instanceof Error ? cause.message : String(cause);
749
+ }
750
+ });
751
+ if (turn.deferred) return ok({ ...total, deferred: true });
752
+ if (turn.value !== undefined)
753
+ return ok({ ...total, syncError: turn.value });
723
754
  assertInferenceActive();
724
755
  return ok(total);
725
756
  }
@@ -748,7 +779,10 @@ export async function embedVariantBacklog(
748
779
  const turn = await inWriteTurn(deps.acquireWriteTurn, async () => {
749
780
  try {
750
781
  if (!store.isActive()) store.syncIndex();
751
- if (identityStillCurrent()) store.activate(epoch);
782
+ if (identityStillCurrent()) {
783
+ store.activate(epoch);
784
+ store.ensureV2RecallSelfCheck();
785
+ }
752
786
  return undefined;
753
787
  } catch (cause) {
754
788
  return cause instanceof Error ? cause.message : String(cause);
@@ -472,7 +472,13 @@ export function handleSimilar(
472
472
  const searchResult = await vectorIndex.searchNearest(
473
473
  embedding,
474
474
  candidateLimit,
475
- storedVectorSearchOptions(source)
475
+ {
476
+ ...storedVectorSearchOptions(source),
477
+ coarseVectorSearch: ctx.config.coarseVectorSearch,
478
+ ...(!crossCollection
479
+ ? { eligibility: { collection: doc.collection } }
480
+ : {}),
481
+ }
476
482
  );
477
483
 
478
484
  if (!searchResult.ok) {
@@ -5,6 +5,7 @@
5
5
  * @module src/pipeline/explain
6
6
  */
7
7
 
8
+ import type { VectorRouteInfo } from "../store/vector/types";
8
9
  import type {
9
10
  ExpansionResult,
10
11
  ExplainLine,
@@ -145,7 +146,8 @@ export function explainVector(
145
146
  count: number,
146
147
  available: boolean,
147
148
  unavailableReason?: string,
148
- guidance?: string
149
+ guidance?: string,
150
+ route?: VectorRouteInfo
149
151
  ): ExplainLine {
150
152
  if (!available) {
151
153
  const detail = unavailableReason ? `: ${unavailableReason}` : "";
@@ -155,7 +157,20 @@ export function explainVector(
155
157
  message: `unavailable (sqlite-vec not loaded${detail})${hint}`,
156
158
  };
157
159
  }
158
- return { stage: "vector", message: `${count} candidates` };
160
+ if (!route) {
161
+ return { stage: "vector", message: `${count} candidates` };
162
+ }
163
+ const routeParts = [`route=${route.route}`, `N=${route.mirrorRows}`];
164
+ if (route.coarseK !== undefined) {
165
+ routeParts.push(`coarseK=${route.coarseK}`);
166
+ }
167
+ if (route.rescored !== undefined) {
168
+ routeParts.push(`rescored=${route.rescored}`);
169
+ }
170
+ return {
171
+ stage: "vector",
172
+ message: `${count} candidates (${routeParts.join(", ")})`,
173
+ };
159
174
  }
160
175
 
161
176
  export function explainFusion(k: number, uniqueCount: number): ExplainLine {
@@ -10,6 +10,7 @@ import type { EmbeddingPort, GenerationPort, RerankPort } from "../llm/types";
10
10
  import type { DocumentRow, StorePort } from "../store/types";
11
11
  import type {
12
12
  VectorIndexPort,
13
+ VectorRouteInfo,
13
14
  VectorSearchOptions,
14
15
  } from "../store/vector/types";
15
16
  import type {
@@ -257,6 +258,9 @@ async function searchVectorChunks(
257
258
  minScore?: number;
258
259
  allowedMirrorHashes?: string[];
259
260
  eligibility?: VectorSearchOptions["eligibility"];
261
+ coarseVectorSearch?: boolean;
262
+ exact?: boolean;
263
+ onRoute?: (info: VectorRouteInfo) => void;
260
264
  }
261
265
  ): Promise<
262
266
  | { ok: true; chunks: ChunkId[] }
@@ -291,6 +295,9 @@ async function searchVectorChunks(
291
295
  minScore: options.minScore,
292
296
  allowedMirrorHashes: options.allowedMirrorHashes,
293
297
  eligibility: options.eligibility,
298
+ coarseVectorSearch: options.coarseVectorSearch,
299
+ exact: options.exact,
300
+ onRoute: options.onRoute,
294
301
  }
295
302
  );
296
303
 
@@ -639,6 +646,7 @@ async function searchHybridWithHydration(
639
646
  vecCount: number;
640
647
  vectorsUsed: boolean;
641
648
  vectorNotice?: string;
649
+ vectorRoute?: VectorRouteInfo;
642
650
  fallbacks: string[];
643
651
  durationMs: number;
644
652
  }> => {
@@ -661,6 +669,7 @@ async function searchHybridWithHydration(
661
669
  let localVecCount = 0;
662
670
  let localVectorsUsed = false;
663
671
  let localNotice: string | undefined;
672
+ let localVectorRoute: VectorRouteInfo | undefined;
664
673
 
665
674
  const vectorVariantQueries = [
666
675
  ...(expansion?.vectorQueries?.map((q) => ({
@@ -681,6 +690,12 @@ async function searchHybridWithHydration(
681
690
  limit: limit * 2 * retrievalMultiplier,
682
691
  allowedMirrorHashes: options.retrievalScope?.allowedMirrorHashes,
683
692
  eligibility: vectorEligibility,
693
+ coarseVectorSearch:
694
+ options.coarseVectorSearch ?? deps.config.coarseVectorSearch,
695
+ exact: options.exactVectorSearch,
696
+ onRoute: (info) => {
697
+ localVectorRoute = info;
698
+ },
684
699
  }
685
700
  );
686
701
 
@@ -755,6 +770,12 @@ async function searchHybridWithHydration(
755
770
  embeddingIdentity: partition?.identity,
756
771
  allowedMirrorHashes: options.retrievalScope?.allowedMirrorHashes,
757
772
  eligibility: vectorEligibility,
773
+ coarseVectorSearch:
774
+ options.coarseVectorSearch ?? deps.config.coarseVectorSearch,
775
+ exact: options.exactVectorSearch,
776
+ onRoute: (info) => {
777
+ localVectorRoute = info;
778
+ },
758
779
  };
759
780
  const uniqueResults = new Map<number, ChunkId[]>();
760
781
  const uniqueFailed = new Set<number>();
@@ -854,6 +875,7 @@ async function searchHybridWithHydration(
854
875
  vecCount: localVecCount,
855
876
  vectorsUsed: localVectorsUsed,
856
877
  vectorNotice: localNotice,
878
+ vectorRoute: localVectorRoute,
857
879
  fallbacks,
858
880
  durationMs: performance.now() - started,
859
881
  };
@@ -894,7 +916,8 @@ async function searchHybridWithHydration(
894
916
  vecCount,
895
917
  vectorAvailable,
896
918
  vectorIndex?.loadError,
897
- vectorIndex?.guidance
919
+ vectorIndex?.guidance,
920
+ vecOutcome.vectorRoute
898
921
  )
899
922
  );
900
923
 
@@ -1636,6 +1659,9 @@ async function searchHybridWithHydration(
1636
1659
  results: auxiliaryRankingActive
1637
1660
  ? buildExplainResults(filteredCandidates, docidMap, finalResults)
1638
1661
  : buildExplainResults(filteredCandidates.slice(0, limit), docidMap),
1662
+ ...(vecOutcome.vectorRoute
1663
+ ? { vectorRoute: vecOutcome.vectorRoute }
1664
+ : {}),
1639
1665
  }
1640
1666
  : undefined;
1641
1667
  await attachSearchResultContexts(store, finalResults);
@@ -1764,6 +1790,7 @@ async function searchHybridWithHydration(
1764
1790
  attachSearchResultsTraceMetadata(output, {
1765
1791
  capabilityOutcomes,
1766
1792
  fallbackCodes,
1793
+ ...(vecOutcome.vectorRoute ? { vectorRoute: vecOutcome.vectorRoute } : {}),
1767
1794
  });
1768
1795
  const traceResult = await options.traceSession?.recordRetrieval(
1769
1796
  output,
@@ -16,6 +16,7 @@ import type { RetrievalTraceSession } from "../core/retrieval-trace-session";
16
16
  import type { MetadataPredicate } from "../core/typed-metadata";
17
17
  import type { InferenceOptions } from "../llm/types";
18
18
  import type { StoreResult } from "../store/types";
19
+ import type { VectorRouteInfo } from "../store/vector/types";
19
20
  import type { ClaimVerificationResult } from "./claim-verification";
20
21
  import type { SemanticVerificationCapability } from "./claim-verifier";
21
22
  import type { ContentTypeBoostScoreMetadata } from "./content-type-boost";
@@ -166,6 +167,7 @@ export interface SearchCapabilityOutcome {
166
167
  export interface SearchResultsTraceMetadata {
167
168
  capabilityOutcomes: SearchCapabilityOutcome[];
168
169
  fallbackCodes: string[];
170
+ vectorRoute?: VectorRouteInfo;
169
171
  }
170
172
 
171
173
  /** Complete search results wrapper */
@@ -245,6 +247,10 @@ export interface SearchOptions extends InferenceOptions {
245
247
  anyTerm?: boolean;
246
248
  /** Internal: drop hits below this fraction of the best raw BM25 score. */
247
249
  minRelativeScore?: number;
250
+ /** Internal: force exact vector search even when coarse routing is enabled. */
251
+ exactVectorSearch?: boolean;
252
+ /** Optional override for config.coarseVectorSearch. */
253
+ coarseVectorSearch?: boolean;
248
254
  }
249
255
 
250
256
  /** Structured query mode identifier */
@@ -594,4 +600,5 @@ export interface ExplainResult {
594
600
  export interface SearchExplain {
595
601
  lines: ExplainLine[];
596
602
  results: ExplainResult[];
603
+ vectorRoute?: VectorRouteInfo;
597
604
  }
@@ -8,7 +8,7 @@
8
8
  import type { Config } from "../config/types";
9
9
  import type { EmbeddingPort } from "../llm/types";
10
10
  import type { DocumentRow, StorePort } from "../store/types";
11
- import type { VectorIndexPort } from "../store/vector/types";
11
+ import type { VectorIndexPort, VectorRouteInfo } from "../store/vector/types";
12
12
  import type { SearchOptions, SearchResult, SearchResults } from "./types";
13
13
 
14
14
  import { normalizeContentTypes } from "../config/content-types";
@@ -56,7 +56,10 @@ import {
56
56
  shouldSortByRecency,
57
57
  type TemporalRange,
58
58
  } from "./temporal";
59
- import { attachSearchResultPlannerMetadata } from "./trace-metadata";
59
+ import {
60
+ attachSearchResultPlannerMetadata,
61
+ attachSearchResultsTraceMetadata,
62
+ } from "./trace-metadata";
60
63
  import { SEARCH_RESULT_PLANNER_METADATA } from "./types";
61
64
 
62
65
  // ─────────────────────────────────────────────────────────────────────────────
@@ -172,6 +175,7 @@ async function searchVectorWithEmbeddingOwned(
172
175
  );
173
176
  }
174
177
  // Search nearest neighbors
178
+ let vectorRoute: VectorRouteInfo | undefined;
175
179
  const searchResult = await vectorIndex.searchNearest(
176
180
  queryEmbedding,
177
181
  retrievalLimit,
@@ -197,6 +201,12 @@ async function searchVectorWithEmbeddingOwned(
197
201
  },
198
202
  minScore: projectAffinityActive ? undefined : minScore,
199
203
  allowedMirrorHashes: options.retrievalScope?.allowedMirrorHashes,
204
+ coarseVectorSearch:
205
+ options.coarseVectorSearch ?? deps.config?.coarseVectorSearch,
206
+ exact: options.exactVectorSearch,
207
+ onRoute: (info) => {
208
+ vectorRoute = info;
209
+ },
200
210
  }
201
211
  );
202
212
 
@@ -657,6 +667,13 @@ async function searchVectorWithEmbeddingOwned(
657
667
  queryLanguage,
658
668
  },
659
669
  };
670
+ if (vectorRoute) {
671
+ attachSearchResultsTraceMetadata(output, {
672
+ capabilityOutcomes: [{ capability: "semantic_search", status: "used" }],
673
+ fallbackCodes: [],
674
+ vectorRoute,
675
+ });
676
+ }
660
677
  const traceResult = await options.traceSession?.recordRetrieval(
661
678
  output,
662
679
  performance.now() - traceStartedAt