@gmickel/gno 2.15.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 (218) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/SKILL.md +27 -0
  3. package/assets/skill/cli-reference.md +24 -15
  4. package/assets/spa-production.json.gz +0 -0
  5. package/browser-extension/artifacts/{gno-browser-clipper-v2.15.0.zip → gno-browser-clipper-v2.17.0.zip} +0 -0
  6. package/browser-extension/artifacts/gno-browser-clipper-v2.17.0.zip.sha256 +1 -0
  7. package/browser-extension/dist/manifest.json +1 -1
  8. package/package.json +1 -1
  9. package/spec/cli.md +43 -3
  10. package/spec/db/schema.sql +53 -1
  11. package/spec/mcp.md +9 -3
  12. package/spec/output-schemas/doctor.schema.json +27 -0
  13. package/spec/output-schemas/retrieval-trace-payloads.schema.json +14 -0
  14. package/spec/output-schemas/search-results.schema.json +14 -0
  15. package/spec/output-schemas/status.schema.json +22 -0
  16. package/src/cli/commands/agents/commands.ts +1 -1
  17. package/src/cli/commands/ask.ts +1 -1
  18. package/src/cli/commands/context-build.ts +1 -1
  19. package/src/cli/commands/doctor.ts +101 -29
  20. package/src/cli/commands/embed.ts +2 -2
  21. package/src/cli/commands/links.ts +30 -6
  22. package/src/cli/commands/mcp/install.ts +2 -2
  23. package/src/cli/commands/mcp/status.ts +1 -1
  24. package/src/cli/commands/mcp/uninstall.ts +1 -1
  25. package/src/cli/commands/query.ts +1 -1
  26. package/src/cli/commands/shared.ts +4 -4
  27. package/src/cli/commands/skill/install.ts +1 -1
  28. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  29. package/src/cli/commands/skill/uninstall.ts +1 -1
  30. package/src/cli/commands/status.ts +75 -58
  31. package/src/cli/commands/vec.ts +180 -8
  32. package/src/cli/config-cache.ts +86 -0
  33. package/src/cli/globals.ts +64 -0
  34. package/src/cli/program.ts +63 -36
  35. package/src/cli/run.ts +121 -67
  36. package/src/cli/runtime-health.ts +132 -122
  37. package/src/cli/session-binding.ts +11 -2
  38. package/src/config/saver.ts +8 -0
  39. package/src/config/types.ts +6 -0
  40. package/src/converters/adapters/browser-export/formats.ts +25 -15
  41. package/src/converters/adapters/email/adapter.ts +37 -53
  42. package/src/converters/adapters/email/html.ts +37 -20
  43. package/src/converters/adapters/email/mime.ts +71 -39
  44. package/src/converters/adapters/ical/adapter.ts +20 -12
  45. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  46. package/src/converters/adapters/shared/html-text.ts +55 -37
  47. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  48. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  49. package/src/converters/adapters/transcript/adapter.ts +12 -7
  50. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  51. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  52. package/src/converters/canonicalize.ts +17 -3
  53. package/src/converters/native/markdown.ts +24 -17
  54. package/src/converters/native/plaintext.ts +5 -6
  55. package/src/converters/registry.ts +130 -8
  56. package/src/core/activation-status.ts +4 -8
  57. package/src/core/change-diff.ts +38 -11
  58. package/src/core/context-compiler.ts +17 -18
  59. package/src/core/context-evidence.ts +116 -25
  60. package/src/core/context-verifier.ts +70 -31
  61. package/src/core/file-lock.ts +10 -2
  62. package/src/core/graph-analysis.ts +3 -3
  63. package/src/core/link-inventory-markdown.ts +2 -2
  64. package/src/core/links.ts +20 -87
  65. package/src/core/memory-fence.ts +16 -9
  66. package/src/core/memory-recall.ts +168 -34
  67. package/src/core/path-rules.ts +143 -0
  68. package/src/core/retrieval-trace-session.ts +3 -0
  69. package/src/core/retrieval-trace.ts +9 -0
  70. package/src/core/section-parse.ts +16 -6
  71. package/src/core/typed-metadata.ts +68 -0
  72. package/src/core/vector-partition-status.ts +13 -0
  73. package/src/core/wiki-link-syntax.ts +88 -0
  74. package/src/embed/backlog.ts +142 -60
  75. package/src/embed/retry.ts +39 -33
  76. package/src/embed/variant-backlog.ts +582 -116
  77. package/src/embed/variant-retry.ts +157 -48
  78. package/src/index.ts +3 -3
  79. package/src/ingestion/budget-error-codes.ts +13 -0
  80. package/src/ingestion/chunker.ts +60 -49
  81. package/src/ingestion/compiled-context.ts +4 -5
  82. package/src/ingestion/convert-file.ts +1 -1
  83. package/src/ingestion/document-metadata.ts +16 -9
  84. package/src/ingestion/excluded-ranges.ts +97 -0
  85. package/src/ingestion/file-processor.ts +122 -37
  86. package/src/ingestion/frontmatter.ts +35 -7
  87. package/src/ingestion/graph-reconciliation.ts +187 -51
  88. package/src/ingestion/language.ts +66 -61
  89. package/src/ingestion/position.ts +5 -5
  90. package/src/ingestion/prepare-file.ts +50 -29
  91. package/src/ingestion/record-adapter-canonical.ts +37 -26
  92. package/src/ingestion/record-adapter.ts +46 -26
  93. package/src/ingestion/record-container.ts +121 -53
  94. package/src/ingestion/record-path.ts +5 -2
  95. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  96. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  97. package/src/ingestion/source-availability/readers.ts +51 -0
  98. package/src/ingestion/strip.ts +39 -105
  99. package/src/ingestion/sync.ts +692 -386
  100. package/src/ingestion/typed-metadata.ts +10 -4
  101. package/src/ingestion/walker.ts +485 -158
  102. package/src/llm/cache.ts +128 -84
  103. package/src/llm/http-inference.ts +112 -35
  104. package/src/llm/http-policy.ts +101 -0
  105. package/src/llm/httpEmbedding.ts +8 -1
  106. package/src/llm/httpGeneration.ts +5 -1
  107. package/src/llm/httpRerank.ts +5 -1
  108. package/src/llm/inference-scope.ts +15 -2
  109. package/src/llm/lazy-ports.ts +33 -3
  110. package/src/llm/lockfile.ts +34 -7
  111. package/src/llm/model-cleanup.ts +24 -0
  112. package/src/llm/native-worker/client.ts +23 -12
  113. package/src/llm/native-worker/dispatcher.ts +19 -9
  114. package/src/llm/native-worker/embedding-identity.ts +42 -16
  115. package/src/llm/native-worker/entry.ts +2 -1
  116. package/src/llm/native-worker/owner.ts +1 -0
  117. package/src/llm/native-worker/ports.ts +86 -23
  118. package/src/llm/native-worker/protocol.ts +386 -55
  119. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  120. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  121. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  122. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  123. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  124. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  125. package/src/llm/types.ts +14 -0
  126. package/src/mcp/context.ts +342 -23
  127. package/src/mcp/http-transport.ts +21 -3
  128. package/src/mcp/tool-profile-types.ts +62 -0
  129. package/src/mcp/tool-profile.ts +32 -56
  130. package/src/mcp/tools/context.ts +5 -1
  131. package/src/mcp/tools/index.ts +269 -191
  132. package/src/mcp/tools/links.ts +14 -6
  133. package/src/mcp/tools/query.ts +60 -37
  134. package/src/mcp/tools/vsearch.ts +25 -14
  135. package/src/pipeline/answer.ts +133 -40
  136. package/src/pipeline/claim-verification.ts +293 -189
  137. package/src/pipeline/claim-verifier.ts +6 -7
  138. package/src/pipeline/egress-lineage.ts +37 -26
  139. package/src/pipeline/exclude.ts +34 -11
  140. package/src/pipeline/expansion.ts +233 -19
  141. package/src/pipeline/explain.ts +17 -2
  142. package/src/pipeline/filters.ts +169 -33
  143. package/src/pipeline/graph-retrieval.ts +117 -61
  144. package/src/pipeline/hybrid.ts +626 -330
  145. package/src/pipeline/hydration.ts +86 -24
  146. package/src/pipeline/intent.ts +15 -7
  147. package/src/pipeline/owner-fusion.ts +61 -19
  148. package/src/pipeline/query-language.ts +15 -2
  149. package/src/pipeline/rerank.ts +15 -22
  150. package/src/pipeline/search.ts +193 -72
  151. package/src/pipeline/snippet.ts +15 -2
  152. package/src/pipeline/temporal.ts +51 -10
  153. package/src/pipeline/types.ts +7 -0
  154. package/src/pipeline/vsearch.ts +269 -154
  155. package/src/publish/attachment-raster.ts +2 -16
  156. package/src/publish/encrypted-export.ts +15 -5
  157. package/src/serve/browse-tree.ts +50 -42
  158. package/src/serve/connectors.ts +2 -1
  159. package/src/serve/context.ts +13 -4
  160. package/src/serve/doc-events.ts +3 -0
  161. package/src/serve/public/app.tsx +49 -21
  162. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  163. package/src/serve/public/components/CaptureModal.tsx +14 -10
  164. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  165. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  166. package/src/serve/public/globals.built.css +1 -1
  167. package/src/serve/public/globals.css +19 -0
  168. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  169. package/src/serve/public/lib/metadata-filter.ts +234 -9
  170. package/src/serve/public/pages/Browse.tsx +61 -27
  171. package/src/serve/public/pages/DocView.tsx +44 -25
  172. package/src/serve/public/pages/GraphView.tsx +8 -3
  173. package/src/serve/resident-runtime.ts +199 -48
  174. package/src/serve/routes/api.ts +98 -67
  175. package/src/serve/routes/links.ts +25 -5
  176. package/src/serve/server.ts +1370 -1180
  177. package/src/serve/spa-bundle-source.ts +52 -27
  178. package/src/serve/status.ts +101 -52
  179. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  180. package/src/serve/watch-reconciliation-shared.ts +42 -4
  181. package/src/serve/watch-reconciliation.ts +21 -8
  182. package/src/serve/watch-service-events.ts +7 -1
  183. package/src/serve/watch-service-hosts.ts +3 -1
  184. package/src/serve/watch-service.ts +46 -21
  185. package/src/serve/watch-snapshot-scan.ts +6 -15
  186. package/src/sessions/archive.ts +20 -8
  187. package/src/sessions/sanitize.ts +38 -18
  188. package/src/sessions/service.ts +180 -102
  189. package/src/store/migrations/037-performance-indexes.ts +56 -0
  190. package/src/store/migrations/038-vector-mirror-null-cosine.ts +47 -0
  191. package/src/store/migrations/039-vector-mirror-v2.ts +94 -0
  192. package/src/store/migrations/index.ts +6 -0
  193. package/src/store/sqlite/adapter.ts +1260 -651
  194. package/src/store/sqlite/chunking-policy.ts +15 -1
  195. package/src/store/sqlite/eligibility.ts +110 -70
  196. package/src/store/sqlite/graph-neighbors.ts +71 -46
  197. package/src/store/sqlite/graph-reference-state.ts +27 -3
  198. package/src/store/sqlite/graph-similarity.ts +59 -12
  199. package/src/store/sqlite/metadata-predicate.ts +123 -28
  200. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  201. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  202. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  203. package/src/store/types.ts +32 -0
  204. package/src/store/vector/coarse-router.ts +312 -0
  205. package/src/store/vector/eligibility.ts +39 -0
  206. package/src/store/vector/lazy.ts +17 -0
  207. package/src/store/vector/partition-index.ts +333 -59
  208. package/src/store/vector/proof-cache.ts +209 -0
  209. package/src/store/vector/runtime-compat.ts +6 -0
  210. package/src/store/vector/sqlite-vec.ts +270 -162
  211. package/src/store/vector/stats.ts +37 -73
  212. package/src/store/vector/status.ts +169 -53
  213. package/src/store/vector/stored-vectors.ts +131 -45
  214. package/src/store/vector/types.ts +19 -0
  215. package/src/store/vector/v2-mirror.ts +669 -0
  216. package/src/store/vector/variant-search.ts +1187 -111
  217. package/src/store/vector/variants.ts +964 -160
  218. package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
@@ -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 {
@@ -47,7 +48,8 @@ import {
47
48
  } from "./content-type-boost";
48
49
  import { formatQueryForEmbedding } from "./contextual";
49
50
  import { attachSearchResultEgressLineage } from "./egress-lineage";
50
- import { expandQuery } from "./expansion";
51
+ import { matchesExcludedChunks, matchesExcludedText } from "./exclude";
52
+ import { expandQuery, expandQueryCached } from "./expansion";
51
53
  import {
52
54
  buildExplainResults,
53
55
  type ExpansionStatus,
@@ -60,11 +62,15 @@ import {
60
62
  explainTimings,
61
63
  explainVector,
62
64
  } from "./explain";
63
- import { evaluateDocumentChunkFilters, typedMetadataWarnings } from "./filters";
65
+ import {
66
+ compileDocumentFilters,
67
+ typedMetadataFilterReason,
68
+ typedMetadataWarnings,
69
+ } from "./filters";
64
70
  import { type RankedInput, rrfFuse, toRankedInput } from "./fusion";
65
71
  import { expandGraphCandidates } from "./graph-retrieval";
66
72
  import { RequestHydration } from "./hydration";
67
- import { selectBestChunkForSteering } from "./intent";
73
+ import { extractSteeringTerms, selectBestChunkForSteering } from "./intent";
68
74
  import { OwnerMetadataError, resolveFusionOwners } from "./owner-fusion";
69
75
  import { hasProjectAffinity } from "./project-affinity";
70
76
  import { detectQueryLanguage } from "./query-language";
@@ -79,6 +85,7 @@ import {
79
85
  } from "./result-context";
80
86
  import { cleanDisplaySnippet } from "./snippet";
81
87
  import {
88
+ compileTemporalRange,
82
89
  isWithinTemporalRange,
83
90
  resolveRecencyTimestamp,
84
91
  resolveTemporalRange,
@@ -141,60 +148,17 @@ const STRONG_TOP_SCORE = 0.84; // ~84th percentile confidence
141
148
  const STRONG_GAP = 0.14; // Clear separation from #2
142
149
 
143
150
  /**
144
- * Check if BM25 results are strong enough to skip expansion.
151
+ * Compute whether top-5 BM25 results are strong enough to skip expansion.
145
152
  * Returns true if top result is both confident AND clearly separated.
146
- * This prevents skipping on weak-but-separated results.
147
153
  */
148
- async function checkBm25Strength(
149
- store: StorePort,
150
- query: string,
151
- options?: {
152
- collection?: string;
153
- collections?: string[];
154
- lang?: string;
155
- tagsAll?: string[];
156
- tagsAny?: string[];
157
- since?: string;
158
- until?: string;
159
- categories?: string[];
160
- author?: string;
161
- filter?: HybridSearchOptions["filter"];
162
- relPathPrefix?: string;
163
- allowedMirrorHashes?: string[];
164
- exclude?: string[];
165
- memoryScopesAny?: string[];
166
- excludeSuperseded?: boolean;
167
- }
168
- ): Promise<boolean> {
169
- const result = await store.searchFts(query, {
170
- limit: 5,
171
- collection: options?.collection,
172
- collections: options?.collections,
173
- relPathPrefix: options?.relPathPrefix,
174
- language: options?.lang,
175
- chunkLanguage: options?.lang,
176
- allowedMirrorHashes: options?.allowedMirrorHashes,
177
- exclude: options?.exclude,
178
- excludeMetadata: true,
179
- semanticMetadata: true,
180
- memoryScopesAny: options?.memoryScopesAny,
181
- excludeSuperseded: options?.excludeSuperseded,
182
- tagsAll: options?.tagsAll,
183
- tagsAny: options?.tagsAny,
184
- since: options?.since,
185
- until: options?.until,
186
- categories: options?.categories,
187
- author: options?.author,
188
- filter: options?.filter,
189
- });
190
-
191
- if (!result.ok || result.value.length === 0) {
154
+ function hasStrongBm25Signal(chunks: readonly ChunkId[]): boolean {
155
+ if (chunks.length === 0) {
192
156
  return false;
193
157
  }
194
158
 
195
- // Normalize scores (higher = better)
196
- const scores = result.value
197
- .map((r) => normalizeBm25Score(r.score))
159
+ const scores = chunks
160
+ .slice(0, 5)
161
+ .map((r) => normalizeBm25Score(r.score ?? 0))
198
162
  .sort((a, b) => b - a); // Descending
199
163
 
200
164
  const topScore = scores[0] ?? 0;
@@ -294,6 +258,9 @@ async function searchVectorChunks(
294
258
  minScore?: number;
295
259
  allowedMirrorHashes?: string[];
296
260
  eligibility?: VectorSearchOptions["eligibility"];
261
+ coarseVectorSearch?: boolean;
262
+ exact?: boolean;
263
+ onRoute?: (info: VectorRouteInfo) => void;
297
264
  }
298
265
  ): Promise<
299
266
  | { ok: true; chunks: ChunkId[] }
@@ -328,6 +295,9 @@ async function searchVectorChunks(
328
295
  minScore: options.minScore,
329
296
  allowedMirrorHashes: options.allowedMirrorHashes,
330
297
  eligibility: options.eligibility,
298
+ coarseVectorSearch: options.coarseVectorSearch,
299
+ exact: options.exact,
300
+ onRoute: options.onRoute,
331
301
  }
332
302
  );
333
303
 
@@ -465,18 +435,17 @@ async function searchHybridWithHydration(
465
435
  // Priority: queryLanguageHint (MCP) > lang (CLI) > detection
466
436
  // ─────────────────────────────────────────────────────────────────────────
467
437
  const langStartedAt = performance.now();
468
- const detection = detectQueryLanguage(query);
469
- // Use explicit hint > lang filter > detected language
470
- const queryLanguage =
471
- options.queryLanguageHint ?? options.lang ?? detection.bcp47;
472
-
473
- // Build explain message for language detection
438
+ let queryLanguage: string;
474
439
  let langMessage: string;
475
440
  if (options.queryLanguageHint) {
441
+ queryLanguage = options.queryLanguageHint;
476
442
  langMessage = `queryLanguage=${queryLanguage} (hint)`;
477
443
  } else if (options.lang) {
444
+ queryLanguage = options.lang;
478
445
  langMessage = `queryLanguage=${queryLanguage} (explicit)`;
479
446
  } else {
447
+ const detection = detectQueryLanguage(query);
448
+ queryLanguage = detection.bcp47;
480
449
  const confidence = detection.confident ? "" : ", low confidence";
481
450
  langMessage = `queryLanguage=${queryLanguage} (detected${confidence})`;
482
451
  }
@@ -484,9 +453,8 @@ async function searchHybridWithHydration(
484
453
  timings.langMs = performance.now() - langStartedAt;
485
454
 
486
455
  // ─────────────────────────────────────────────────────────────────────────
487
- // 1. Check if expansion needed
456
+ // 1. Original BM25 query (once; fail-fast on INVALID_INPUT) + expansion
488
457
  // ─────────────────────────────────────────────────────────────────────────
489
- const expansionStartedAt = performance.now();
490
458
  const shouldExpand = !options.noExpand && expandPort !== null;
491
459
  let expansionStatus: ExpansionStatus = "disabled";
492
460
  let queryModeSummary: ReturnType<typeof summarizeQueryModes> | undefined =
@@ -499,38 +467,84 @@ async function searchHybridWithHydration(
499
467
  expansionStatus = "provided";
500
468
  }
501
469
 
470
+ const bm25BaseOptions = {
471
+ collection: options.collection,
472
+ collections: options.collections,
473
+ lang: options.lang,
474
+ memoryScopesAny: options.memoryFilter?.scopes,
475
+ excludeSuperseded: options.memoryFilter?.excludeSuperseded,
476
+ exclude: options.exclude,
477
+ allowedMirrorHashes: options.retrievalScope?.allowedMirrorHashes,
478
+ tagsAll: options.tagsAll,
479
+ tagsAny: options.tagsAny,
480
+ since: temporalRange.since,
481
+ until: temporalRange.until,
482
+ categories: options.categories,
483
+ author: options.author,
484
+ filter: options.filter,
485
+ relPathPrefix: options.retrievalScope?.relPathPrefix,
486
+ };
487
+ const needsStrengthCheck =
488
+ expansionStatus !== "provided" && shouldExpand && !options.intent?.trim();
489
+ const originalBm25TargetLimit = limit * 2 * retrievalMultiplier;
490
+ const bm25InitialStartedAt = performance.now();
491
+ const bm25Result = await searchFtsChunks(store, query, {
492
+ ...bm25BaseOptions,
493
+ limit: needsStrengthCheck
494
+ ? Math.max(5, originalBm25TargetLimit)
495
+ : originalBm25TargetLimit,
496
+ });
497
+ timings.bm25Ms = performance.now() - bm25InitialStartedAt;
498
+
499
+ // Propagate FTS syntax errors as INVALID_INPUT before invoking LLM expansion
500
+ if (!bm25Result.ok && bm25Result.code === "INVALID_INPUT") {
501
+ return err("INVALID_INPUT", `Invalid search query: ${bm25Result.message}`);
502
+ }
503
+ const bm25AllChunks = bm25Result.ok ? bm25Result.chunks : [];
504
+ const bm25Chunks = bm25AllChunks.slice(0, originalBm25TargetLimit);
505
+ const bm25Count = bm25Chunks.length;
506
+
507
+ const expansionStartedAt = performance.now();
502
508
  if (expansionStatus !== "provided" && shouldExpand) {
503
509
  const hasStrongSignal = options.intent?.trim()
504
510
  ? false
505
- : await checkBm25Strength(store, query, {
506
- collection: options.collection,
507
- collections: options.collections,
508
- lang: options.lang,
509
- memoryScopesAny: options.memoryFilter?.scopes,
510
- excludeSuperseded: options.memoryFilter?.excludeSuperseded,
511
- exclude: options.exclude,
512
- allowedMirrorHashes: options.retrievalScope?.allowedMirrorHashes,
513
- tagsAll: options.tagsAll,
514
- tagsAny: options.tagsAny,
515
- since: temporalRange.since,
516
- until: temporalRange.until,
517
- categories: options.categories,
518
- author: options.author,
519
- filter: options.filter,
520
- relPathPrefix: options.retrievalScope?.relPathPrefix,
521
- });
511
+ : hasStrongBm25Signal(bm25AllChunks);
522
512
 
523
513
  if (hasStrongSignal) {
524
514
  expansionStatus = "skipped_strong";
525
515
  counters.fallbackEvents.push("expansion_skipped_strong");
526
516
  } else {
527
517
  expansionStatus = "attempted";
528
- const expandResult = await expandQuery(expandPort, query, {
518
+ const expandOptions = {
529
519
  // Use queryLanguage for prompt selection, NOT options.lang (retrieval filter)
530
520
  lang: queryLanguage,
531
521
  intent: options.intent,
532
522
  contextSize: deps.config.models?.expandContextSize,
533
- });
523
+ };
524
+ const expandResult =
525
+ typeof store.getLlmCache === "function" &&
526
+ typeof store.setLlmCache === "function"
527
+ ? await expandQueryCached(
528
+ {
529
+ genPort: expandPort,
530
+ getCache: async (key) => {
531
+ const res = await store.getLlmCache!(key);
532
+ return res.ok ? res.value : null;
533
+ },
534
+ setCache: async (key, value) => {
535
+ await store.setLlmCache!(key, value);
536
+ },
537
+ onCacheLookup: () => {
538
+ counters.expansionCacheLookups += 1;
539
+ },
540
+ onCacheHit: () => {
541
+ counters.expansionCacheHits += 1;
542
+ },
543
+ },
544
+ query,
545
+ expandOptions
546
+ )
547
+ : await expandQuery(expandPort, query, expandOptions);
534
548
  if (expandResult.ok) {
535
549
  expansion = expandResult.value;
536
550
  } else {
@@ -546,7 +560,7 @@ async function searchHybridWithHydration(
546
560
  timings.expansionMs = performance.now() - expansionStartedAt;
547
561
 
548
562
  // ─────────────────────────────────────────────────────────────────────────
549
- // 2. Parallel retrieval using raw store/vector APIs for correct seq tracking
563
+ // 2. Concurrent retrieval: lexical variants + vector leg
550
564
  // ─────────────────────────────────────────────────────────────────────────
551
565
  const rankedInputs: RankedInput[] = [];
552
566
  const diagnoseTrace: QueryDiagnoseTrace | undefined = options.diagnoseTrace
@@ -571,36 +585,7 @@ async function searchHybridWithHydration(
571
585
  semanticMetadata: true,
572
586
  language: options.lang,
573
587
  };
574
- const bm25StartedAt = performance.now();
575
588
 
576
- // BM25: original query
577
- const bm25Result = await searchFtsChunks(store, query, {
578
- limit: limit * 2 * retrievalMultiplier,
579
- memoryScopesAny: options.memoryFilter?.scopes,
580
- excludeSuperseded: options.memoryFilter?.excludeSuperseded,
581
- exclude: options.exclude,
582
- allowedMirrorHashes: options.retrievalScope?.allowedMirrorHashes,
583
- collection: options.collection,
584
- collections: options.collections,
585
- lang: options.lang,
586
- tagsAll: options.tagsAll,
587
- tagsAny: options.tagsAny,
588
- since: temporalRange.since,
589
- until: temporalRange.until,
590
- categories: options.categories,
591
- author: options.author,
592
- filter: options.filter,
593
- relPathPrefix: options.retrievalScope?.relPathPrefix,
594
- });
595
-
596
- // Propagate FTS syntax errors as INVALID_INPUT
597
- if (!bm25Result.ok && bm25Result.code === "INVALID_INPUT") {
598
- return err("INVALID_INPUT", `Invalid search query: ${bm25Result.message}`);
599
- }
600
- // Other errors: continue with empty BM25 results
601
-
602
- const bm25Chunks = bm25Result.ok ? bm25Result.chunks : [];
603
- const bm25Count = bm25Chunks.length;
604
589
  diagnoseTrace?.stages.push({
605
590
  id: "bm25",
606
591
  status: "active",
@@ -611,64 +596,85 @@ async function searchHybridWithHydration(
611
596
  rankedInputs.push(toRankedInput("bm25", bm25Chunks));
612
597
  }
613
598
 
614
- // BM25: lexical variants (optional; run in parallel and ignore failures)
615
- if (expansion?.lexicalQueries?.length) {
616
- const lexicalVariantResults = await Promise.allSettled(
617
- expansion.lexicalQueries.map((variant) =>
618
- searchFtsChunks(store, variant, {
619
- limit: limit * retrievalMultiplier,
620
- memoryScopesAny: options.memoryFilter?.scopes,
621
- excludeSuperseded: options.memoryFilter?.excludeSuperseded,
622
- exclude: options.exclude,
623
- allowedMirrorHashes: options.retrievalScope?.allowedMirrorHashes,
624
- collection: options.collection,
625
- collections: options.collections,
626
- lang: options.lang,
627
- tagsAll: options.tagsAll,
628
- tagsAny: options.tagsAny,
629
- since: temporalRange.since,
630
- until: temporalRange.until,
631
- categories: options.categories,
632
- author: options.author,
633
- filter: options.filter,
634
- relPathPrefix: options.retrievalScope?.relPathPrefix,
635
- })
636
- )
637
- );
599
+ const vectorAvailable =
600
+ (vectorIndex?.searchAvailable && embedPort !== null) ?? false;
638
601
 
639
- for (const settled of lexicalVariantResults) {
602
+ const runLexicalVariants = async (): Promise<{
603
+ inputs: RankedInput[];
604
+ durationMs: number;
605
+ }> => {
606
+ const lexicalQueries = expansion?.lexicalQueries;
607
+ if (!lexicalQueries?.length) {
608
+ return { inputs: [], durationMs: 0 };
609
+ }
610
+ const started = performance.now();
611
+ const trimmedQuery = query.trim();
612
+ const variantLimit = limit * retrievalMultiplier;
613
+ const settledResults = await Promise.allSettled(
614
+ lexicalQueries.map((variant) => {
615
+ if (variant.trim() === trimmedQuery) {
616
+ return Promise.resolve<FtsChunksResult>(
617
+ bm25Result.ok
618
+ ? {
619
+ ok: true,
620
+ chunks: bm25AllChunks.slice(0, variantLimit),
621
+ }
622
+ : bm25Result
623
+ );
624
+ }
625
+ return searchFtsChunks(store, variant, {
626
+ ...bm25BaseOptions,
627
+ limit: variantLimit,
628
+ });
629
+ })
630
+ );
631
+ const inputs: RankedInput[] = [];
632
+ for (const settled of settledResults) {
640
633
  assertInferenceActive();
641
- if (settled.status !== "fulfilled") {
642
- continue;
643
- }
634
+ if (settled.status !== "fulfilled") continue;
644
635
  const variantResult = settled.value;
645
636
  if (variantResult.ok && variantResult.chunks.length > 0) {
646
- rankedInputs.push(toRankedInput("bm25_variant", variantResult.chunks));
637
+ inputs.push(toRankedInput("bm25_variant", variantResult.chunks));
647
638
  }
648
639
  }
649
- }
650
- timings.bm25Ms = performance.now() - bm25StartedAt;
651
-
652
- explainLines.push(explainBm25(bm25Count));
640
+ return { inputs, durationMs: performance.now() - started };
641
+ };
653
642
 
654
- // Vector search
655
- let vecCount = 0;
656
- let vectorsUsed = false;
657
- let vectorNotice: string | undefined;
658
- const vectorAvailable =
659
- (vectorIndex?.searchAvailable && embedPort !== null) ?? false;
660
- if (!vectorAvailable) {
661
- counters.fallbackEvents.push("vector_unavailable");
662
- }
643
+ const runVectorLeg = async (): Promise<{
644
+ inputs: RankedInput[];
645
+ traceChunks: ChunkId[];
646
+ vecCount: number;
647
+ vectorsUsed: boolean;
648
+ vectorNotice?: string;
649
+ vectorRoute?: VectorRouteInfo;
650
+ fallbacks: string[];
651
+ durationMs: number;
652
+ }> => {
653
+ const fallbacks: string[] = [];
654
+ if (!vectorAvailable || !vectorIndex || !embedPort) {
655
+ fallbacks.push("vector_unavailable");
656
+ return {
657
+ inputs: [],
658
+ traceChunks: [],
659
+ vecCount: 0,
660
+ vectorsUsed: false,
661
+ fallbacks,
662
+ durationMs: 0,
663
+ };
664
+ }
663
665
 
664
- const vectorStartedAt = performance.now();
665
- const vectorTraceChunks: ChunkId[] = [];
666
+ const started = performance.now();
667
+ const inputs: RankedInput[] = [];
668
+ const traceChunks: ChunkId[] = [];
669
+ let localVecCount = 0;
670
+ let localVectorsUsed = false;
671
+ let localNotice: string | undefined;
672
+ let localVectorRoute: VectorRouteInfo | undefined;
666
673
 
667
- if (vectorAvailable && vectorIndex && embedPort) {
668
674
  const vectorVariantQueries = [
669
- ...(expansion?.vectorQueries?.map((query) => ({
675
+ ...(expansion?.vectorQueries?.map((q) => ({
670
676
  source: "vector_variant" as const,
671
- query,
677
+ query: q,
672
678
  })) ?? []),
673
679
  ...(expansion?.hyde
674
680
  ? [{ source: "hyde" as const, query: expansion.hyde }]
@@ -684,18 +690,26 @@ async function searchHybridWithHydration(
684
690
  limit: limit * 2 * retrievalMultiplier,
685
691
  allowedMirrorHashes: options.retrievalScope?.allowedMirrorHashes,
686
692
  eligibility: vectorEligibility,
693
+ coarseVectorSearch:
694
+ options.coarseVectorSearch ?? deps.config.coarseVectorSearch,
695
+ exact: options.exactVectorSearch,
696
+ onRoute: (info) => {
697
+ localVectorRoute = info;
698
+ },
687
699
  }
688
700
  );
689
701
 
690
702
  if (!vectorResult.ok) {
691
- counters.fallbackEvents.push(vectorResult.reason);
692
- vectorNotice = vectorResult.notice;
693
- } else vectorsUsed = true;
703
+ fallbacks.push(vectorResult.reason);
704
+ localNotice = vectorResult.notice;
705
+ } else {
706
+ localVectorsUsed = true;
707
+ }
694
708
  const vecChunks = vectorResult.ok ? vectorResult.chunks : [];
695
- vecCount = vecChunks.length;
696
- vectorTraceChunks.push(...vecChunks);
697
- if (vecCount > 0) {
698
- rankedInputs.push(toRankedInput("vector", vecChunks));
709
+ localVecCount = vecChunks.length;
710
+ traceChunks.push(...vecChunks);
711
+ if (localVecCount > 0) {
712
+ inputs.push(toRankedInput("vector", vecChunks));
699
713
  }
700
714
  } else {
701
715
  const batchedQueries = [
@@ -710,11 +724,32 @@ async function searchHybridWithHydration(
710
724
  })),
711
725
  ];
712
726
 
727
+ // Deduplicate identical formatted query strings before embedding & searching,
728
+ // retaining every variant's RRF input contribution via per-variant slicing.
729
+ const uniqueFormatted: string[] = [];
730
+ const uniqueMaxLimits: number[] = [];
731
+ const formattedToUniqueIdx = new Map<string, number>();
732
+ const variantToUniqueIdx: number[] = [];
733
+ for (const variant of batchedQueries) {
734
+ const formatted = formatQueryForEmbedding(
735
+ variant.query,
736
+ embedPort.modelUri
737
+ );
738
+ let uIdx = formattedToUniqueIdx.get(formatted);
739
+ if (uIdx === undefined) {
740
+ uIdx = uniqueFormatted.length;
741
+ formattedToUniqueIdx.set(formatted, uIdx);
742
+ uniqueFormatted.push(formatted);
743
+ uniqueMaxLimits.push(variant.limit);
744
+ } else if (variant.limit > uniqueMaxLimits[uIdx]!) {
745
+ uniqueMaxLimits[uIdx] = variant.limit;
746
+ }
747
+ variantToUniqueIdx.push(uIdx);
748
+ }
749
+
713
750
  const embedResult = await embedTextsWithRecovery(
714
751
  embedPort,
715
- batchedQueries.map((variant) =>
716
- formatQueryForEmbedding(variant.query, embedPort.modelUri)
717
- )
752
+ uniqueFormatted
718
753
  );
719
754
 
720
755
  assertInferenceResult(embedResult);
@@ -722,63 +757,158 @@ async function searchHybridWithHydration(
722
757
  ? await resolveVectorSearchIdentity(embedPort, vectorIndex)
723
758
  : undefined;
724
759
  if (!embedResult.ok) {
725
- counters.fallbackEvents.push("vector_embed_error");
760
+ fallbacks.push("vector_embed_error");
726
761
  } else if (partition?.unavailable) {
727
- counters.fallbackEvents.push(VECTOR_RUNTIME_INCOMPATIBLE);
728
- vectorNotice = lexicalFallbackNotice(partition.unavailable);
762
+ fallbacks.push(VECTOR_RUNTIME_INCOMPATIBLE);
763
+ localNotice = lexicalFallbackNotice(partition.unavailable);
729
764
  } else {
730
765
  if (embedResult.value.batchFailed) {
731
- counters.fallbackEvents.push("vector_embed_batch_fallback");
766
+ fallbacks.push("vector_embed_batch_fallback");
732
767
  }
733
768
 
734
- for (const [index, variant] of batchedQueries.entries()) {
735
- assertInferenceActive();
736
- const embedding = embedResult.value.vectors[index];
737
- if (!embedding || !variant) {
738
- continue;
739
- }
769
+ const searchOpts: VectorSearchOptions = {
770
+ embeddingIdentity: partition?.identity,
771
+ allowedMirrorHashes: options.retrievalScope?.allowedMirrorHashes,
772
+ eligibility: vectorEligibility,
773
+ coarseVectorSearch:
774
+ options.coarseVectorSearch ?? deps.config.coarseVectorSearch,
775
+ exact: options.exactVectorSearch,
776
+ onRoute: (info) => {
777
+ localVectorRoute = info;
778
+ },
779
+ };
780
+ const uniqueResults = new Map<number, ChunkId[]>();
781
+ const uniqueFailed = new Set<number>();
782
+
783
+ const validUniqueIndices: number[] = [];
784
+ const validEmbeddings: Float32Array[] = [];
785
+ const validLimits: number[] = [];
786
+ for (let uIdx = 0; uIdx < uniqueFormatted.length; uIdx++) {
787
+ const emb = embedResult.value.vectors[uIdx];
788
+ if (!emb) continue;
789
+ validUniqueIndices.push(uIdx);
790
+ validEmbeddings.push(new Float32Array(emb));
791
+ validLimits.push(uniqueMaxLimits[uIdx]!);
792
+ }
740
793
 
741
- const searchResult = await vectorIndex.searchNearest(
742
- new Float32Array(embedding),
743
- variant.limit,
744
- {
745
- embeddingIdentity: partition?.identity,
746
- allowedMirrorHashes: options.retrievalScope?.allowedMirrorHashes,
747
- eligibility: vectorEligibility,
794
+ const runIndividualSearches = async (): Promise<void> => {
795
+ for (let i = 0; i < validUniqueIndices.length; i++) {
796
+ assertInferenceActive();
797
+ const uIdx = validUniqueIndices[i]!;
798
+ const searchResult = await vectorIndex.searchNearest(
799
+ validEmbeddings[i]!,
800
+ validLimits[i]!,
801
+ searchOpts
802
+ );
803
+ if (!searchResult.ok) {
804
+ uniqueFailed.add(uIdx);
805
+ continue;
748
806
  }
807
+ localVectorsUsed = true;
808
+ uniqueResults.set(
809
+ uIdx,
810
+ searchResult.value.map((item) => ({
811
+ documentIds: item.documentIds,
812
+ mirrorHash: item.mirrorHash,
813
+ seq: item.seq,
814
+ }))
815
+ );
816
+ }
817
+ };
818
+
819
+ if (
820
+ typeof vectorIndex.searchNearestBatch === "function" &&
821
+ validEmbeddings.length > 1
822
+ ) {
823
+ assertInferenceActive();
824
+ const batchRes = await vectorIndex.searchNearestBatch(
825
+ validEmbeddings,
826
+ validLimits,
827
+ searchOpts
749
828
  );
750
- if (!searchResult.ok) {
751
- counters.fallbackEvents.push("vector_search_error");
829
+ if (batchRes.ok) {
830
+ localVectorsUsed = true;
831
+ for (let i = 0; i < validUniqueIndices.length; i++) {
832
+ const uIdx = validUniqueIndices[i]!;
833
+ const hits = batchRes.value[i] ?? [];
834
+ uniqueResults.set(
835
+ uIdx,
836
+ hits.map((item) => ({
837
+ documentIds: item.documentIds,
838
+ mirrorHash: item.mirrorHash,
839
+ seq: item.seq,
840
+ }))
841
+ );
842
+ }
843
+ } else {
844
+ // Preserve per-query isolation: retry unique embeddings individually so
845
+ // one bad variant cannot discard healthy vector legs.
846
+ await runIndividualSearches();
847
+ }
848
+ } else {
849
+ await runIndividualSearches();
850
+ }
851
+
852
+ for (const [index, variant] of batchedQueries.entries()) {
853
+ assertInferenceActive();
854
+ const uIdx = variantToUniqueIdx[index]!;
855
+ if (uniqueFailed.has(uIdx)) {
856
+ fallbacks.push("vector_search_error");
752
857
  continue;
753
858
  }
754
- vectorsUsed = true;
755
- if (searchResult.value.length === 0) continue;
756
-
757
- const chunks = searchResult.value.map((item) => ({
758
- documentIds: item.documentIds,
759
- mirrorHash: item.mirrorHash,
760
- seq: item.seq,
761
- }));
859
+ const fullChunks = uniqueResults.get(uIdx);
860
+ if (!fullChunks || fullChunks.length === 0) continue;
861
+ const chunks = fullChunks.slice(0, variant.limit);
762
862
  if (variant.source === "vector") {
763
- vecCount = chunks.length;
764
- }
765
- vectorTraceChunks.push(...chunks);
766
- if (chunks.length === 0) {
767
- continue;
863
+ localVecCount = chunks.length;
768
864
  }
769
- rankedInputs.push(toRankedInput(variant.source, chunks));
865
+ traceChunks.push(...chunks);
866
+ if (chunks.length === 0) continue;
867
+ inputs.push(toRankedInput(variant.source, chunks));
770
868
  }
771
869
  }
772
870
  }
773
- }
774
- timings.vectorMs = performance.now() - vectorStartedAt;
871
+
872
+ return {
873
+ inputs,
874
+ traceChunks,
875
+ vecCount: localVecCount,
876
+ vectorsUsed: localVectorsUsed,
877
+ vectorNotice: localNotice,
878
+ vectorRoute: localVectorRoute,
879
+ fallbacks,
880
+ durationMs: performance.now() - started,
881
+ };
882
+ };
883
+
884
+ // Run lexical expansion variants concurrently with out-of-process vector leg;
885
+ // Promise.allSettled guarantees no unhandled rejections on abort/timeout.
886
+ const [lexSettled, vecSettled] = await Promise.allSettled([
887
+ runLexicalVariants(),
888
+ runVectorLeg(),
889
+ ]);
890
+ if (lexSettled.status === "rejected") throw lexSettled.reason;
891
+ if (vecSettled.status === "rejected") throw vecSettled.reason;
892
+
893
+ const lexOutcome = lexSettled.value;
894
+ const vecOutcome = vecSettled.value;
895
+ rankedInputs.push(...lexOutcome.inputs);
896
+ timings.bm25Ms += lexOutcome.durationMs;
897
+ explainLines.push(explainBm25(bm25Count));
898
+
899
+ const vecCount = vecOutcome.vecCount;
900
+ const vectorsUsed = vecOutcome.vectorsUsed;
901
+ const vectorNotice = vecOutcome.vectorNotice;
902
+ counters.fallbackEvents.push(...vecOutcome.fallbacks);
903
+ rankedInputs.push(...vecOutcome.inputs);
904
+ timings.vectorMs = vecOutcome.durationMs;
775
905
 
776
906
  diagnoseTrace?.stages.push({
777
907
  id: "vector",
778
908
  status: vectorAvailable ? "active" : "skipped",
779
909
  reason: vectorAvailable ? undefined : "vector_unavailable",
780
910
  sourceCount: vectorAvailable ? 1 : 0,
781
- candidates: toTraceCandidates(vectorTraceChunks),
911
+ candidates: toTraceCandidates(vecOutcome.traceChunks),
782
912
  });
783
913
 
784
914
  explainLines.push(
@@ -786,7 +916,8 @@ async function searchHybridWithHydration(
786
916
  vecCount,
787
917
  vectorAvailable,
788
918
  vectorIndex?.loadError,
789
- vectorIndex?.guidance
919
+ vectorIndex?.guidance,
920
+ vecOutcome.vectorRoute
790
921
  )
791
922
  );
792
923
 
@@ -796,10 +927,17 @@ async function searchHybridWithHydration(
796
927
  const fusionStartedAt = performance.now();
797
928
  const candidateLimit =
798
929
  options.candidateLimit ?? pipelineConfig.rerankCandidates;
799
- let fusedCandidates = rrfFuse(
800
- await resolveFusionOwners(rankedInputs, store, hydration, query, options),
801
- pipelineConfig.rrf
930
+ const hasVariantOwners = rankedInputs.some((input) =>
931
+ input.results.some((result) => result.documentId !== undefined)
932
+ );
933
+ const resolvedInputs = await resolveFusionOwners(
934
+ rankedInputs,
935
+ store,
936
+ hydration,
937
+ query,
938
+ options
802
939
  );
940
+ let fusedCandidates = rrfFuse(resolvedInputs, pipelineConfig.rrf);
803
941
  diagnoseTrace?.stages.push({
804
942
  id: "fusion",
805
943
  status: "active",
@@ -835,11 +973,19 @@ async function searchHybridWithHydration(
835
973
  timings.graphMs = performance.now() - graphStartedAt;
836
974
  if (graphExpansion.candidates.length > 0) {
837
975
  const graphFusionStartedAt = performance.now();
838
- rankedInputs.push(toRankedInput("graph", graphExpansion.candidates));
839
- fusedCandidates = rrfFuse(
840
- await resolveFusionOwners(rankedInputs, store, hydration, query, options),
841
- pipelineConfig.rrf
842
- );
976
+ const graphInput = toRankedInput("graph", graphExpansion.candidates);
977
+ const resolvedGraph = hasVariantOwners
978
+ ? await resolveFusionOwners(
979
+ [graphInput],
980
+ store,
981
+ hydration,
982
+ query,
983
+ options,
984
+ true
985
+ )
986
+ : [graphInput];
987
+ const finalResolvedInputs = [...resolvedInputs, ...resolvedGraph];
988
+ fusedCandidates = rrfFuse(finalResolvedInputs, pipelineConfig.rrf);
843
989
  timings.fusionMs += performance.now() - graphFusionStartedAt;
844
990
  }
845
991
  diagnoseTrace?.stages.push({
@@ -1011,7 +1157,13 @@ async function searchHybridWithHydration(
1011
1157
  }
1012
1158
  const collectionsResult = await store.getCollections();
1013
1159
 
1014
- // Build lookup maps.
1160
+ // Build lookup maps with pre-compiled query-invariant filters.
1161
+ const compiledFilters = compileDocumentFilters(
1162
+ query,
1163
+ options,
1164
+ undefined,
1165
+ compileTemporalRange(temporalRange)
1166
+ );
1015
1167
  const docsByMirrorHash = new Map<string, DocumentRow[]>();
1016
1168
  const addDocument = (doc: DocumentRow): void => {
1017
1169
  if (!doc.mirrorHash) return;
@@ -1020,6 +1172,9 @@ async function searchHybridWithHydration(
1020
1172
  docsByMirrorHash.set(doc.mirrorHash, docs);
1021
1173
  };
1022
1174
  const matchesMetadataFilters = (doc: DocumentRow): boolean => {
1175
+ if (typedMetadataFilterReason(doc, options.filter)) {
1176
+ return false;
1177
+ }
1023
1178
  const relPathPrefix = options.retrievalScope?.relPathPrefix;
1024
1179
  const sourceRelPath = doc.recordSourcePath ?? doc.relPath;
1025
1180
  if (
@@ -1029,22 +1184,23 @@ async function searchHybridWithHydration(
1029
1184
  ) {
1030
1185
  return false;
1031
1186
  }
1032
- if (!isWithinTemporalRange(doc.sourceMtime, temporalRange)) {
1187
+ if (
1188
+ !isWithinTemporalRange(doc.sourceMtime, compiledFilters.temporalRange)
1189
+ ) {
1033
1190
  return false;
1034
1191
  }
1035
1192
  if (
1036
- options.author &&
1037
- !doc.author?.toLowerCase().includes(options.author.toLowerCase())
1193
+ compiledFilters.authorLower &&
1194
+ !doc.author?.toLowerCase().includes(compiledFilters.authorLower)
1038
1195
  ) {
1039
1196
  return false;
1040
1197
  }
1041
- if (options.categories?.length) {
1042
- const allowed = new Set(options.categories.map((c) => c.toLowerCase()));
1198
+ if (compiledFilters.allowedCategories) {
1043
1199
  const contentTypeMatch = doc.contentType
1044
- ? allowed.has(doc.contentType.toLowerCase())
1200
+ ? compiledFilters.allowedCategories.has(doc.contentType.toLowerCase())
1045
1201
  : false;
1046
1202
  const categoryMatch = (doc.categories ?? []).some((c) =>
1047
- allowed.has(c.toLowerCase())
1203
+ compiledFilters.allowedCategories!.has(c.toLowerCase())
1048
1204
  );
1049
1205
  if (!contentTypeMatch && !categoryMatch) {
1050
1206
  return false;
@@ -1063,13 +1219,14 @@ async function searchHybridWithHydration(
1063
1219
  if (!doc.mirrorHash) {
1064
1220
  continue;
1065
1221
  }
1222
+ if (!matchesMetadataFilters(doc)) {
1223
+ continue;
1224
+ }
1066
1225
  if (needsTagFilter) {
1067
1226
  docIdsForTagCheck.push(doc.id);
1068
1227
  candidateDocs.push(doc);
1069
1228
  } else {
1070
- if (matchesMetadataFilters(doc)) {
1071
- addDocument(doc);
1072
- }
1229
+ addDocument(doc);
1073
1230
  }
1074
1231
  }
1075
1232
 
@@ -1096,9 +1253,7 @@ async function searchHybridWithHydration(
1096
1253
  if (!hasAny) continue;
1097
1254
  }
1098
1255
 
1099
- if (doc.mirrorHash && matchesMetadataFilters(doc)) {
1100
- addDocument(doc);
1101
- }
1256
+ addDocument(doc);
1102
1257
  }
1103
1258
  }
1104
1259
  }
@@ -1120,21 +1275,92 @@ async function searchHybridWithHydration(
1120
1275
  }
1121
1276
  }
1122
1277
 
1123
- // Pre-fetch all chunks in one batch query (eliminates N+1)
1124
- const chunksMapResult = await hydration.getChunksBatch([...neededHashes]);
1125
- if (!chunksMapResult.ok) {
1126
- return err("QUERY_FAILED", chunksMapResult.error.message);
1278
+ // Pre-fetch chunks: use sequence-scoped loading when neither intent nor
1279
+ // exclude needs full chunk sets, reusing already-hydrated hashes when warm.
1280
+ const needsAllChunksForAssembly = Boolean(
1281
+ options.intent?.trim() || options.exclude?.length
1282
+ );
1283
+ let chunksMap: Map<string, import("../store/types").ChunkRow[]>;
1284
+ if (
1285
+ !needsAllChunksForAssembly &&
1286
+ typeof store.getChunksBySequenceBatch === "function"
1287
+ ) {
1288
+ const cachedHashes: string[] = [];
1289
+ const uncachedSeqRequests: Array<{ mirrorHash: string; seq: number }> = [];
1290
+ const seenReq = new Set<string>();
1291
+ for (const candidate of filteredCandidates) {
1292
+ if (hydration.hasChunks(candidate.mirrorHash)) {
1293
+ cachedHashes.push(candidate.mirrorHash);
1294
+ } else {
1295
+ const reqKey = `${candidate.mirrorHash}:${candidate.seq}`;
1296
+ if (!seenReq.has(reqKey)) {
1297
+ seenReq.add(reqKey);
1298
+ uncachedSeqRequests.push({
1299
+ mirrorHash: candidate.mirrorHash,
1300
+ seq: candidate.seq,
1301
+ });
1302
+ }
1303
+ }
1304
+ }
1305
+ const [cachedRes, seqRes] = await Promise.all([
1306
+ cachedHashes.length > 0
1307
+ ? hydration.getChunksBatch(cachedHashes)
1308
+ : Promise.resolve(
1309
+ ok(new Map<string, import("../store/types").ChunkRow[]>())
1310
+ ),
1311
+ uncachedSeqRequests.length > 0
1312
+ ? store.getChunksBySequenceBatch(uncachedSeqRequests)
1313
+ : Promise.resolve(
1314
+ ok(new Map<string, import("../store/types").ChunkRow[]>())
1315
+ ),
1316
+ ]);
1317
+ if (!cachedRes.ok) {
1318
+ return err("QUERY_FAILED", cachedRes.error.message);
1319
+ }
1320
+ if (!seqRes.ok) {
1321
+ return err("QUERY_FAILED", seqRes.error.message);
1322
+ }
1323
+ chunksMap = new Map(cachedRes.value);
1324
+ for (const [hash, rows] of seqRes.value) {
1325
+ chunksMap.set(hash, rows);
1326
+ }
1327
+ // For doc-level FTS (seq=0) missing seq=0, fall back to full batch for only those hashes.
1328
+ const missingSeqZeroHashes: string[] = [];
1329
+ for (const req of uncachedSeqRequests) {
1330
+ if (req.seq === 0 && (chunksMap.get(req.mirrorHash)?.length ?? 0) === 0) {
1331
+ missingSeqZeroHashes.push(req.mirrorHash);
1332
+ }
1333
+ }
1334
+ if (missingSeqZeroHashes.length > 0) {
1335
+ const fallbackRes = await hydration.getChunksBatch(missingSeqZeroHashes);
1336
+ if (!fallbackRes.ok) {
1337
+ return err("QUERY_FAILED", fallbackRes.error.message);
1338
+ }
1339
+ for (const [hash, rows] of fallbackRes.value) {
1340
+ chunksMap.set(hash, rows);
1341
+ }
1342
+ }
1343
+ } else {
1344
+ const chunksMapResult = await hydration.getChunksBatch([...neededHashes]);
1345
+ if (!chunksMapResult.ok) {
1346
+ return err("QUERY_FAILED", chunksMapResult.error.message);
1347
+ }
1348
+ chunksMap = chunksMapResult.value;
1127
1349
  }
1128
- const chunksMap = chunksMapResult.value;
1129
1350
  const getChunk = createChunkLookup(chunksMap);
1130
-
1131
- // Cache full content by mirrorHash for --full mode
1132
- const contentCache = new Map<
1133
- string,
1134
- Awaited<ReturnType<typeof store.getContent>>
1135
- >();
1351
+ const excludeTermsLower = compiledFilters.excludeTermsLower;
1352
+ const excludedChunksCache = excludeTermsLower
1353
+ ? new Map<string, boolean>()
1354
+ : undefined;
1355
+ const queryTerms = options.intent?.trim()
1356
+ ? extractSteeringTerms(query)
1357
+ : undefined;
1358
+ const intentTerms = options.intent?.trim()
1359
+ ? extractSteeringTerms(options.intent)
1360
+ : undefined;
1136
1361
 
1137
1362
  const results: SearchResult[] = [];
1363
+ const deferredChunkTextByResult = new WeakMap<SearchResult, string>();
1138
1364
  const assemblyLimit = recencySort ? limit * 3 : limit;
1139
1365
  const docidMap = new Map<string, string>();
1140
1366
  // Track seen docids for --full de-duplication
@@ -1149,13 +1375,13 @@ async function searchHybridWithHydration(
1149
1375
  }
1150
1376
 
1151
1377
  // Find document from pre-fetched map
1152
- const candidateDocs = (
1378
+ const candidateDocsForHit = (
1153
1379
  docsByMirrorHash.get(candidate.mirrorHash) ?? []
1154
1380
  ).filter(
1155
1381
  (doc) =>
1156
1382
  candidate.documentId === undefined || candidate.documentId === doc.id
1157
1383
  );
1158
- if (candidateDocs.length === 0) {
1384
+ if (candidateDocsForHit.length === 0) {
1159
1385
  continue;
1160
1386
  }
1161
1387
 
@@ -1165,8 +1391,7 @@ async function searchHybridWithHydration(
1165
1391
  let chunk = getChunk(candidate.mirrorHash, candidate.seq);
1166
1392
  if (!chunk && candidate.seq === 0) {
1167
1393
  // Doc-level FTS uses seq=0 as placeholder - try first chunk
1168
- const docChunks = chunksMap.get(candidate.mirrorHash);
1169
- chunk = docChunks?.[0];
1394
+ chunk = docChunks[0];
1170
1395
  }
1171
1396
  if (!chunk) {
1172
1397
  continue;
@@ -1177,19 +1402,33 @@ async function searchHybridWithHydration(
1177
1402
  continue;
1178
1403
  }
1179
1404
 
1180
- // For --full mode, fetch full mirror content
1405
+ if (excludeTermsLower) {
1406
+ let chunksExcluded = excludedChunksCache!.get(candidate.mirrorHash);
1407
+ if (chunksExcluded === undefined) {
1408
+ chunksExcluded = matchesExcludedChunks(
1409
+ docChunks,
1410
+ excludeTermsLower,
1411
+ true
1412
+ );
1413
+ excludedChunksCache!.set(candidate.mirrorHash, chunksExcluded);
1414
+ }
1415
+ if (chunksExcluded) continue;
1416
+ }
1417
+
1181
1418
  const snippetChunk =
1182
1419
  options.full || !options.intent?.trim()
1183
1420
  ? chunk
1184
1421
  : (selectBestChunkForSteering(
1185
- (chunksMap.get(candidate.mirrorHash) ?? []).filter(
1186
- (chunk) => !options.lang || chunk.language === options.lang
1422
+ docChunks.filter(
1423
+ (c) => !options.lang || c.language === options.lang
1187
1424
  ),
1188
1425
  query,
1189
1426
  options.intent,
1190
1427
  {
1191
1428
  preferredSeq: chunk.seq,
1192
1429
  intentWeight: 0.3,
1430
+ queryTerms,
1431
+ intentTerms,
1193
1432
  }
1194
1433
  ) ?? chunk);
1195
1434
 
@@ -1200,20 +1439,7 @@ async function searchHybridWithHydration(
1200
1439
  endLine: snippetChunk.endLine,
1201
1440
  };
1202
1441
 
1203
- if (options.full) {
1204
- // Get or fetch full content for this mirrorHash
1205
- let contentResult = contentCache.get(candidate.mirrorHash);
1206
- if (!contentResult) {
1207
- contentResult = await hydration.getContent(candidate.mirrorHash);
1208
- contentCache.set(candidate.mirrorHash, contentResult);
1209
- }
1210
-
1211
- if (contentResult.ok && contentResult.value) {
1212
- snippet = contentResult.value;
1213
- snippetRange = undefined; // Full content has no range
1214
- }
1215
- // Fallback to chunk text if content unavailable
1216
- } else {
1442
+ if (!options.full) {
1217
1443
  const cleanedSnippet = cleanDisplaySnippet(
1218
1444
  snippetChunk.text,
1219
1445
  snippetChunk.text
@@ -1227,18 +1453,29 @@ async function searchHybridWithHydration(
1227
1453
  };
1228
1454
  }
1229
1455
 
1230
- for (const doc of candidateDocs) {
1456
+ for (const doc of candidateDocsForHit) {
1231
1457
  assertInferenceActive();
1232
1458
  if (!auxiliaryRankingActive && results.length >= assemblyLimit) break;
1233
- const filterEval = evaluateDocumentChunkFilters(
1234
- query,
1235
- doc,
1236
- docChunks,
1237
- options
1238
- );
1239
1459
  if (
1240
- !filterEval.matches ||
1241
- (options.full && !auxiliaryRankingActive && seenDocids.has(doc.docid))
1460
+ excludeTermsLower &&
1461
+ matchesExcludedText(
1462
+ [
1463
+ doc.title ?? "",
1464
+ doc.recordSourcePath ?? doc.relPath,
1465
+ doc.author ?? "",
1466
+ doc.contentType ?? "",
1467
+ ...(doc.categories ?? []),
1468
+ ],
1469
+ excludeTermsLower,
1470
+ true
1471
+ )
1472
+ ) {
1473
+ continue;
1474
+ }
1475
+ if (
1476
+ options.full &&
1477
+ !auxiliaryRankingActive &&
1478
+ seenDocids.has(doc.docid)
1242
1479
  ) {
1243
1480
  continue;
1244
1481
  }
@@ -1278,65 +1515,57 @@ async function searchHybridWithHydration(
1278
1515
  },
1279
1516
  record: projectRecordEvidenceMetadata(doc),
1280
1517
  };
1281
- const auxiliaryBaseScore =
1282
- auxiliaryBaseScores.get(
1283
- `${candidate.mirrorHash}:${candidate.seq}:${candidate.documentId ?? ""}`
1284
- ) ?? candidate.blendedScore;
1285
- const candidateKey = `${candidate.mirrorHash}:${candidate.seq}:${candidate.documentId ?? ""}`;
1286
- const composedBeforeRerank =
1287
- preRerankAdjustedCandidates.has(candidateKey);
1288
- const scoringBaseScore =
1289
- rerankResult.reranked && !composedBeforeRerank
1290
- ? candidate.blendedScore
1291
- : auxiliaryBaseScore;
1292
- const scored = scoreContentTypeBoost(
1293
- scoringBaseScore,
1294
- doc.contentType ?? undefined,
1295
- doc.contentTypeSource,
1296
- doc.relPath,
1297
- doc.collection,
1298
- contentTypeRules,
1299
- options.projectAffinity,
1300
- { kind: "hybrid_blended", score: scoringBaseScore }
1301
- );
1302
- const scoredResult = attachAuxiliaryScoreMetadata(
1303
- baseResult,
1304
- scored,
1305
- rerankResult.reranked && composedBeforeRerank
1306
- ? candidate.blendedScore
1307
- : scored.projectAffinity.finalScore,
1308
- hasProjectAffinity(options.projectAffinity)
1309
- );
1518
+ let scoredResult = baseResult;
1519
+ if (auxiliaryRankingActive) {
1520
+ const candidateKey = `${candidate.mirrorHash}:${candidate.seq}:${candidate.documentId ?? ""}`;
1521
+ const auxiliaryBaseScore =
1522
+ auxiliaryBaseScores.get(candidateKey) ?? candidate.blendedScore;
1523
+ const composedBeforeRerank =
1524
+ preRerankAdjustedCandidates.has(candidateKey);
1525
+ const scoringBaseScore =
1526
+ rerankResult.reranked && !composedBeforeRerank
1527
+ ? candidate.blendedScore
1528
+ : auxiliaryBaseScore;
1529
+ const scored = scoreContentTypeBoost(
1530
+ scoringBaseScore,
1531
+ doc.contentType ?? undefined,
1532
+ doc.contentTypeSource,
1533
+ doc.relPath,
1534
+ doc.collection,
1535
+ contentTypeRules,
1536
+ options.projectAffinity,
1537
+ { kind: "hybrid_blended", score: scoringBaseScore }
1538
+ );
1539
+ scoredResult = attachAuxiliaryScoreMetadata(
1540
+ baseResult,
1541
+ scored,
1542
+ rerankResult.reranked && composedBeforeRerank
1543
+ ? candidate.blendedScore
1544
+ : scored.projectAffinity.finalScore,
1545
+ hasProjectAffinity(options.projectAffinity)
1546
+ );
1547
+ }
1310
1548
  if (scoredResult.score < minScore) continue;
1311
- results.push(
1312
- attachSearchResultPlannerMetadata(scoredResult, {
1313
- retrievalRank: candidateIndex + 1,
1314
- mirrorHash: candidate.mirrorHash,
1315
- seq: snippetChunk.seq,
1316
- ...(auxiliaryRankingActive && snippetChunk.seq !== candidate.seq
1317
- ? { retrievalSeq: candidate.seq }
1318
- : {}),
1319
- sources: [...candidate.sources].sort(),
1320
- graphExpanded: candidate.sources.includes("graph"),
1321
- startLine: snippetChunk.startLine,
1322
- endLine: snippetChunk.endLine,
1323
- passageHash: new Bun.CryptoHasher("sha256")
1324
- .update(snippetChunk.text)
1325
- .digest("hex"),
1326
- })
1327
- );
1549
+ const attached = attachSearchResultPlannerMetadata(scoredResult, {
1550
+ retrievalRank: candidateIndex + 1,
1551
+ mirrorHash: candidate.mirrorHash,
1552
+ seq: snippetChunk.seq,
1553
+ ...(auxiliaryRankingActive && snippetChunk.seq !== candidate.seq
1554
+ ? { retrievalSeq: candidate.seq }
1555
+ : {}),
1556
+ sources: [...candidate.sources].sort(),
1557
+ graphExpanded: candidate.sources.includes("graph"),
1558
+ startLine: snippetChunk.startLine,
1559
+ endLine: snippetChunk.endLine,
1560
+ passageHash: "",
1561
+ });
1562
+ deferredChunkTextByResult.set(attached, snippetChunk.text);
1563
+ results.push(attached);
1328
1564
  }
1329
1565
  }
1330
- timings.assemblyMs = performance.now() - assemblyStartedAt;
1331
- timings.totalMs = performance.now() - runStartedAt;
1332
- explainLines.push(explainTimings(timings));
1333
- explainLines.push(explainCounters(counters));
1334
1566
 
1335
1567
  // ─────────────────────────────────────────────────────────────────────────
1336
- // 6. Build explain data (if requested)
1337
- // ─────────────────────────────────────────────────────────────────────────
1338
- // ─────────────────────────────────────────────────────────────────────────
1339
- // 7. Return results
1568
+ // 6. Sort, slice, hydrate deferred --full content and passage hashes
1340
1569
  // ─────────────────────────────────────────────────────────────────────────
1341
1570
  const dedupedResults =
1342
1571
  options.full && auxiliaryRankingActive
@@ -1344,15 +1573,16 @@ async function searchHybridWithHydration(
1344
1573
  : results;
1345
1574
 
1346
1575
  if (recencySort) {
1347
- dedupedResults.sort((a, b) => {
1348
- const aTs = resolveRecencyTimestamp(
1349
- a.source.documentDate,
1350
- a.source.modifiedAt
1351
- );
1352
- const bTs = resolveRecencyTimestamp(
1353
- b.source.documentDate,
1354
- b.source.modifiedAt
1576
+ const recencyTs = new Map<SearchResult, number>();
1577
+ for (const r of dedupedResults) {
1578
+ recencyTs.set(
1579
+ r,
1580
+ resolveRecencyTimestamp(r.source.documentDate, r.source.modifiedAt)
1355
1581
  );
1582
+ }
1583
+ dedupedResults.sort((a, b) => {
1584
+ const aTs = recencyTs.get(a) ?? 0;
1585
+ const bTs = recencyTs.get(b) ?? 0;
1356
1586
  if (aTs !== bTs) {
1357
1587
  return bTs - aTs;
1358
1588
  }
@@ -1363,26 +1593,91 @@ async function searchHybridWithHydration(
1363
1593
  }
1364
1594
 
1365
1595
  const finalResults = dedupedResults.slice(0, limit);
1596
+ if (options.full && finalResults.length > 0) {
1597
+ const fullHashes = [
1598
+ ...new Set(
1599
+ finalResults
1600
+ .map((r) => r.conversion?.mirrorHash)
1601
+ .filter((hash): hash is string => Boolean(hash))
1602
+ ),
1603
+ ];
1604
+ if (fullHashes.length > 0) {
1605
+ let fullContentByHash: Map<string, string> | undefined;
1606
+ const contentBatch = await hydration.getContentBatch(fullHashes);
1607
+ if (contentBatch.ok) {
1608
+ fullContentByHash = contentBatch.value;
1609
+ } else {
1610
+ // Recover per hash on batch error so healthy results retain full content.
1611
+ const recovered = new Map<string, string>();
1612
+ const individual = await Promise.all(
1613
+ fullHashes.map(async (hash) => ({
1614
+ hash,
1615
+ res: await hydration.getContent(hash),
1616
+ }))
1617
+ );
1618
+ for (const { hash, res } of individual) {
1619
+ if (res.ok && res.value) {
1620
+ recovered.set(hash, res.value);
1621
+ }
1622
+ }
1623
+ fullContentByHash = recovered;
1624
+ }
1625
+ for (const result of finalResults) {
1626
+ const hash = result.conversion?.mirrorHash;
1627
+ const fullContent = hash ? fullContentByHash.get(hash) : undefined;
1628
+ if (fullContent) {
1629
+ result.snippet = fullContent;
1630
+ result.snippetRange = undefined;
1631
+ }
1632
+ }
1633
+ }
1634
+ }
1366
1635
  for (const [index, result] of finalResults.entries()) {
1367
1636
  assertInferenceActive();
1368
1637
  const metadata = result[SEARCH_RESULT_PLANNER_METADATA];
1369
- if (metadata) metadata.retrievalRank = index + 1;
1638
+ if (metadata) {
1639
+ metadata.retrievalRank = index + 1;
1640
+ if (!metadata.passageHash) {
1641
+ const text = deferredChunkTextByResult.get(result);
1642
+ if (text !== undefined) {
1643
+ metadata.passageHash = new Bun.CryptoHasher("sha256")
1644
+ .update(text)
1645
+ .digest("hex");
1646
+ }
1647
+ }
1648
+ }
1370
1649
  }
1650
+
1651
+ timings.assemblyMs = performance.now() - assemblyStartedAt;
1652
+ timings.totalMs = performance.now() - runStartedAt;
1653
+ explainLines.push(explainTimings(timings));
1654
+ explainLines.push(explainCounters(counters));
1655
+
1371
1656
  const explainData = options.explain
1372
1657
  ? {
1373
1658
  lines: explainLines,
1374
1659
  results: auxiliaryRankingActive
1375
1660
  ? buildExplainResults(filteredCandidates, docidMap, finalResults)
1376
1661
  : buildExplainResults(filteredCandidates.slice(0, limit), docidMap),
1662
+ ...(vecOutcome.vectorRoute
1663
+ ? { vectorRoute: vecOutcome.vectorRoute }
1664
+ : {}),
1377
1665
  }
1378
1666
  : undefined;
1379
1667
  await attachSearchResultContexts(store, finalResults);
1380
1668
  await attachSupersession(store, finalResults);
1669
+ const finalHashes = [
1670
+ ...new Set(
1671
+ finalResults
1672
+ .map((r) => r.conversion?.mirrorHash)
1673
+ .filter((hash): hash is string => Boolean(hash))
1674
+ ),
1675
+ ];
1381
1676
  const lineageResult = await attachSearchResultEgressLineage(
1382
1677
  store,
1383
1678
  finalResults,
1384
1679
  {
1385
- ownershipHashes: [...neededHashes],
1680
+ ownershipHashes: finalHashes,
1386
1681
  ownershipDocuments:
1387
1682
  options.collection === undefined && options.collections === undefined
1388
1683
  ? documents
@@ -1495,6 +1790,7 @@ async function searchHybridWithHydration(
1495
1790
  attachSearchResultsTraceMetadata(output, {
1496
1791
  capabilityOutcomes,
1497
1792
  fallbackCodes,
1793
+ ...(vecOutcome.vectorRoute ? { vectorRoute: vecOutcome.vectorRoute } : {}),
1498
1794
  });
1499
1795
  const traceResult = await options.traceSession?.recordRetrieval(
1500
1796
  output,