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