@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
@@ -8,7 +8,7 @@
8
8
  import type { Config } from "../config/types";
9
9
  import type { EmbeddingPort } from "../llm/types";
10
10
  import type { DocumentRow, StorePort } from "../store/types";
11
- import type { VectorIndexPort } from "../store/vector/types";
11
+ import type { VectorIndexPort, VectorRouteInfo } from "../store/vector/types";
12
12
  import type { SearchOptions, SearchResult, SearchResults } from "./types";
13
13
 
14
14
  import { normalizeContentTypes } from "../config/content-types";
@@ -29,13 +29,18 @@ import { createChunkLookup } from "./chunk-lookup";
29
29
  import {
30
30
  applyContentTypeBoost,
31
31
  hasAuxiliaryRanking,
32
+ scoreContentTypeBoost,
32
33
  sortByFinalScoreStable,
33
34
  } from "./content-type-boost";
34
35
  import { formatQueryForEmbedding } from "./contextual";
35
36
  import { attachSearchResultEgressLineage } from "./egress-lineage";
36
- import { matchesExcludedChunks, matchesExcludedText } from "./exclude";
37
+ import {
38
+ compileExcludeTerms,
39
+ matchesExcludedChunks,
40
+ matchesExcludedText,
41
+ } from "./exclude";
37
42
  import { typedMetadataWarnings, typedMetadataFilterReason } from "./filters";
38
- import { selectBestChunkForSteering } from "./intent";
43
+ import { extractSteeringTerms, selectBestChunkForSteering } from "./intent";
39
44
  import { hasProjectAffinity } from "./project-affinity";
40
45
  import { detectQueryLanguage } from "./query-language";
41
46
  import {
@@ -44,13 +49,17 @@ import {
44
49
  } from "./result-context";
45
50
  import { cleanDisplaySnippet } from "./snippet";
46
51
  import {
52
+ compileTemporalRange,
47
53
  resolveRecencyTimestamp,
48
54
  isWithinTemporalRange,
49
55
  resolveTemporalRange,
50
56
  shouldSortByRecency,
51
57
  type TemporalRange,
52
58
  } from "./temporal";
53
- import { attachSearchResultPlannerMetadata } from "./trace-metadata";
59
+ import {
60
+ attachSearchResultPlannerMetadata,
61
+ attachSearchResultsTraceMetadata,
62
+ } from "./trace-metadata";
54
63
  import { SEARCH_RESULT_PLANNER_METADATA } from "./types";
55
64
 
56
65
  // ─────────────────────────────────────────────────────────────────────────────
@@ -140,8 +149,7 @@ async function searchVectorWithEmbeddingOwned(
140
149
  );
141
150
 
142
151
  // Detect query language for metadata (DOES NOT affect retrieval filtering)
143
- const detection = detectQueryLanguage(query);
144
- const queryLanguage = options.lang ?? detection.bcp47;
152
+ const queryLanguage = options.lang ?? detectQueryLanguage(query).bcp47;
145
153
 
146
154
  // Check if vector search is available
147
155
  if (!vectorIndex.searchAvailable) {
@@ -167,6 +175,7 @@ async function searchVectorWithEmbeddingOwned(
167
175
  );
168
176
  }
169
177
  // Search nearest neighbors
178
+ let vectorRoute: VectorRouteInfo | undefined;
170
179
  const searchResult = await vectorIndex.searchNearest(
171
180
  queryEmbedding,
172
181
  retrievalLimit,
@@ -192,6 +201,12 @@ async function searchVectorWithEmbeddingOwned(
192
201
  },
193
202
  minScore: projectAffinityActive ? undefined : minScore,
194
203
  allowedMirrorHashes: options.retrievalScope?.allowedMirrorHashes,
204
+ coarseVectorSearch:
205
+ options.coarseVectorSearch ?? deps.config?.coarseVectorSearch,
206
+ exact: options.exactVectorSearch,
207
+ onRoute: (info) => {
208
+ vectorRoute = info;
209
+ },
195
210
  }
196
211
  );
197
212
 
@@ -245,6 +260,15 @@ async function searchVectorWithEmbeddingOwned(
245
260
 
246
261
  // Build search results
247
262
  const results: SearchResult[] = [];
263
+ const deferredChunkTextByResult = new WeakMap<SearchResult, string>();
264
+ const excludeTermsLower = compileExcludeTerms(options.exclude);
265
+ const excludedMirrorCache = excludeTermsLower
266
+ ? new Map<string, boolean>()
267
+ : undefined;
268
+ const queryTerms = options.intent ? extractSteeringTerms(query) : undefined;
269
+ const intentTerms = options.intent
270
+ ? extractSteeringTerms(options.intent)
271
+ : undefined;
248
272
 
249
273
  // For --full, track best score per docid to de-dupe
250
274
  const bestByDocid = new Map<
@@ -277,6 +301,8 @@ async function searchVectorWithEmbeddingOwned(
277
301
  {
278
302
  preferredSeq: rawChunk?.seq ?? vec.seq,
279
303
  intentWeight: 0.3,
304
+ queryTerms,
305
+ intentTerms,
280
306
  }
281
307
  ) ?? rawChunk)
282
308
  : rawChunk;
@@ -303,11 +329,26 @@ async function searchVectorWithEmbeddingOwned(
303
329
  auxiliaryRankingActive || vec.documentIds !== undefined
304
330
  ? matchingDocs
305
331
  : [matchingDocs.at(-1)!];
332
+ let chunksExcluded = false;
333
+ if (excludeTermsLower) {
334
+ const cached = excludedMirrorCache!.get(vec.mirrorHash);
335
+ if (cached !== undefined) {
336
+ chunksExcluded = cached;
337
+ } else {
338
+ chunksExcluded = matchesExcludedChunks(
339
+ chunksMap.get(vec.mirrorHash) ?? [],
340
+ excludeTermsLower,
341
+ true
342
+ );
343
+ excludedMirrorCache!.set(vec.mirrorHash, chunksExcluded);
344
+ }
345
+ if (chunksExcluded) continue;
346
+ }
306
347
  for (const doc of docs) {
307
348
  assertInferenceActive();
308
- const collectionPath = collectionPaths.get(doc.collection);
309
349
  const sourceRelPath = doc.recordSourcePath ?? doc.relPath;
310
- const excluded =
350
+ if (
351
+ excludeTermsLower &&
311
352
  matchesExcludedText(
312
353
  [
313
354
  doc.title ?? "",
@@ -316,66 +357,31 @@ async function searchVectorWithEmbeddingOwned(
316
357
  doc.contentType ?? "",
317
358
  ...(doc.categories ?? []),
318
359
  ],
319
- options.exclude
320
- ) ||
321
- matchesExcludedChunks(
322
- chunksMap.get(vec.mirrorHash) ?? [],
323
- options.exclude
324
- );
325
- if (excluded) {
360
+ excludeTermsLower,
361
+ true
362
+ )
363
+ ) {
326
364
  continue;
327
365
  }
328
366
 
329
- const cleanedSnippet = cleanDisplaySnippet(chunk.text, chunk.text);
330
- const snippetStartLine = chunk.startLine + cleanedSnippet.startLineOffset;
331
- const scoredResult = applyContentTypeBoost(
332
- {
333
- docid: doc.docid,
334
- score: baseScore,
335
- uri: doc.uri,
336
- title: doc.title ?? undefined,
337
- contentType: doc.contentType ?? undefined,
338
- categories: doc.categories ?? undefined,
339
- line: snippetStartLine,
340
- snippet: cleanedSnippet.text,
341
- snippetLanguage: chunk.language ?? undefined,
342
- snippetRange: {
343
- startLine: snippetStartLine,
344
- endLine: chunk.endLine,
345
- },
346
- source: {
347
- relPath: sourceRelPath,
348
- absPath: collectionPath
349
- ? `${collectionPath}/${sourceRelPath}`
350
- : undefined,
351
- mime: doc.sourceMime,
352
- ext: doc.sourceExt,
353
- modifiedAt: doc.sourceMtime,
354
- documentDate: doc.frontmatterDate ?? undefined,
355
- sizeBytes: doc.sourceSize,
356
- sourceHash: doc.sourceHash,
357
- },
358
- conversion: doc.mirrorHash
359
- ? {
360
- mirrorHash: doc.mirrorHash,
361
- converterId: doc.converterId ?? undefined,
362
- converterVersion: doc.converterVersion ?? undefined,
363
- }
364
- : undefined,
365
- record: projectRecordEvidenceMetadata(doc),
366
- },
367
- doc.collection,
368
- contentTypeRules,
369
- options.projectAffinity,
370
- doc.contentTypeSource,
371
- { kind: "vector_distance", score: vec.distance }
372
- );
373
- if (scoredResult.score < minScore) continue;
374
-
375
- // For --full, de-dupe by docid (keep best scoring chunk per doc)
367
+ // For --full, avoid throwaway snippet cleaning / SearchResult construction;
368
+ // compute only the final score needed for dedupe/filtering/ranking.
376
369
  if (options.full) {
370
+ const rankingScore = auxiliaryRankingActive
371
+ ? scoreContentTypeBoost(
372
+ baseScore,
373
+ doc.contentType ?? undefined,
374
+ doc.contentTypeSource,
375
+ sourceRelPath,
376
+ doc.collection,
377
+ contentTypeRules,
378
+ options.projectAffinity,
379
+ { kind: "vector_distance", score: vec.distance }
380
+ ).projectAffinity.finalScore
381
+ : baseScore;
382
+ if (rankingScore < minScore) continue;
377
383
  const existing = bestByDocid.get(doc.docid);
378
- if (!existing || scoredResult.score > existing.rankingScore) {
384
+ if (!existing || rankingScore > existing.rankingScore) {
379
385
  bestByDocid.set(doc.docid, {
380
386
  doc,
381
387
  chunk: {
@@ -385,7 +391,7 @@ async function searchVectorWithEmbeddingOwned(
385
391
  endLine: chunk.endLine,
386
392
  seq: chunk.seq,
387
393
  },
388
- rankingScore: scoredResult.score,
394
+ rankingScore,
389
395
  rawDistance: vec.distance,
390
396
  score: baseScore,
391
397
  });
@@ -393,28 +399,106 @@ async function searchVectorWithEmbeddingOwned(
393
399
  continue;
394
400
  }
395
401
 
396
- results.push(
397
- attachSearchResultPlannerMetadata(scoredResult, {
398
- retrievalRank: 0,
399
- mirrorHash: vec.mirrorHash,
400
- seq: chunk.seq,
401
- sources: ["vector"],
402
- graphExpanded: false,
403
- startLine: chunk.startLine,
402
+ const collectionPath = collectionPaths.get(doc.collection);
403
+ const cleanedSnippet = cleanDisplaySnippet(chunk.text, chunk.text);
404
+ const snippetStartLine = chunk.startLine + cleanedSnippet.startLineOffset;
405
+ const baseResult: SearchResult = {
406
+ docid: doc.docid,
407
+ score: baseScore,
408
+ uri: doc.uri,
409
+ title: doc.title ?? undefined,
410
+ contentType: doc.contentType ?? undefined,
411
+ categories: doc.categories ?? undefined,
412
+ line: snippetStartLine,
413
+ snippet: cleanedSnippet.text,
414
+ snippetLanguage: chunk.language ?? undefined,
415
+ snippetRange: {
416
+ startLine: snippetStartLine,
404
417
  endLine: chunk.endLine,
405
- passageHash: new Bun.CryptoHasher("sha256")
406
- .update(chunk.text)
407
- .digest("hex"),
408
- })
409
- );
418
+ },
419
+ source: {
420
+ relPath: sourceRelPath,
421
+ absPath: collectionPath
422
+ ? `${collectionPath}/${sourceRelPath}`
423
+ : undefined,
424
+ mime: doc.sourceMime,
425
+ ext: doc.sourceExt,
426
+ modifiedAt: doc.sourceMtime,
427
+ documentDate: doc.frontmatterDate ?? undefined,
428
+ sizeBytes: doc.sourceSize,
429
+ sourceHash: doc.sourceHash,
430
+ },
431
+ conversion: doc.mirrorHash
432
+ ? {
433
+ mirrorHash: doc.mirrorHash,
434
+ converterId: doc.converterId ?? undefined,
435
+ converterVersion: doc.converterVersion ?? undefined,
436
+ }
437
+ : undefined,
438
+ record: projectRecordEvidenceMetadata(doc),
439
+ };
440
+ const scoredResult = auxiliaryRankingActive
441
+ ? applyContentTypeBoost(
442
+ baseResult,
443
+ doc.collection,
444
+ contentTypeRules,
445
+ options.projectAffinity,
446
+ doc.contentTypeSource,
447
+ { kind: "vector_distance", score: vec.distance }
448
+ )
449
+ : baseResult;
450
+ if (scoredResult.score < minScore) continue;
451
+
452
+ const attached = attachSearchResultPlannerMetadata(scoredResult, {
453
+ retrievalRank: 0,
454
+ mirrorHash: vec.mirrorHash,
455
+ seq: chunk.seq,
456
+ sources: ["vector"],
457
+ graphExpanded: false,
458
+ startLine: chunk.startLine,
459
+ endLine: chunk.endLine,
460
+ passageHash: "",
461
+ });
462
+ deferredChunkTextByResult.set(attached, chunk.text);
463
+ results.push(attached);
410
464
  }
411
465
  }
412
466
 
413
- // For --full, fetch full content and build results
467
+ let finalResults: SearchResult[];
468
+ // For --full, sort and slice BEFORE fetching full content via getContentBatch
414
469
  if (options.full) {
470
+ const entries = [...bestByDocid.values()];
471
+ if (recencySort) {
472
+ const recencyTs = new Map<(typeof entries)[number], number>();
473
+ for (const entry of entries) {
474
+ recencyTs.set(
475
+ entry,
476
+ resolveRecencyTimestamp(
477
+ entry.doc.frontmatterDate,
478
+ entry.doc.sourceMtime
479
+ )
480
+ );
481
+ }
482
+ entries.sort((a, b) => {
483
+ const aTs = recencyTs.get(a) ?? 0;
484
+ const bTs = recencyTs.get(b) ?? 0;
485
+ if (aTs !== bTs) return bTs - aTs;
486
+ return b.rankingScore - a.rankingScore;
487
+ });
488
+ } else if (auxiliaryRankingActive) {
489
+ const originalRank = new Map(
490
+ entries.map((entry, idx) => [entry, idx] as const)
491
+ );
492
+ entries.sort(
493
+ (left, right) =>
494
+ right.rankingScore - left.rankingScore ||
495
+ (originalRank.get(left) ?? 0) - (originalRank.get(right) ?? 0)
496
+ );
497
+ }
498
+ const survivingEntries = entries.slice(0, limit);
415
499
  const fullContentResult = await getContentBatch(
416
500
  store,
417
- [...bestByDocid.values()]
501
+ survivingEntries
418
502
  .map(({ doc }) => doc.mirrorHash)
419
503
  .filter((mirrorHash): mirrorHash is string => Boolean(mirrorHash))
420
504
  );
@@ -423,7 +507,8 @@ async function searchVectorWithEmbeddingOwned(
423
507
  }
424
508
  const fullContentByHash = fullContentResult.value;
425
509
 
426
- for (const { doc, chunk, rawDistance, score } of bestByDocid.values()) {
510
+ finalResults = [];
511
+ for (const { doc, chunk, rawDistance, score } of survivingEntries) {
427
512
  assertInferenceActive();
428
513
  const fullContent = doc.mirrorHash
429
514
  ? fullContentByHash.get(doc.mirrorHash)
@@ -438,49 +523,52 @@ async function searchVectorWithEmbeddingOwned(
438
523
  ? chunk.startLine + cleanedChunk.startLineOffset
439
524
  : chunk.startLine;
440
525
 
441
- const result = applyContentTypeBoost(
442
- {
443
- docid: doc.docid,
444
- score,
445
- uri: doc.uri,
446
- title: doc.title ?? undefined,
447
- contentType: doc.contentType ?? undefined,
448
- categories: doc.categories ?? undefined,
449
- line: snippetStartLine,
450
- snippet: fullContent ?? cleanedChunk?.text ?? chunk.text,
451
- snippetLanguage: chunk.language ?? undefined,
452
- // --full: no snippetRange (full doc content)
453
- snippetRange: fullContent
454
- ? undefined
455
- : { startLine: snippetStartLine, endLine: chunk.endLine },
456
- source: {
457
- relPath: sourceRelPath,
458
- absPath: collectionPath
459
- ? `${collectionPath}/${sourceRelPath}`
460
- : undefined,
461
- mime: doc.sourceMime,
462
- ext: doc.sourceExt,
463
- modifiedAt: doc.sourceMtime,
464
- documentDate: doc.frontmatterDate ?? undefined,
465
- sizeBytes: doc.sourceSize,
466
- sourceHash: doc.sourceHash,
467
- },
468
- conversion: doc.mirrorHash
469
- ? {
470
- mirrorHash: doc.mirrorHash,
471
- converterId: doc.converterId ?? undefined,
472
- converterVersion: doc.converterVersion ?? undefined,
473
- }
526
+ const baseResult: SearchResult = {
527
+ docid: doc.docid,
528
+ score,
529
+ uri: doc.uri,
530
+ title: doc.title ?? undefined,
531
+ contentType: doc.contentType ?? undefined,
532
+ categories: doc.categories ?? undefined,
533
+ line: snippetStartLine,
534
+ snippet: fullContent ?? cleanedChunk?.text ?? chunk.text,
535
+ snippetLanguage: chunk.language ?? undefined,
536
+ // --full: no snippetRange (full doc content)
537
+ snippetRange: fullContent
538
+ ? undefined
539
+ : { startLine: snippetStartLine, endLine: chunk.endLine },
540
+ source: {
541
+ relPath: sourceRelPath,
542
+ absPath: collectionPath
543
+ ? `${collectionPath}/${sourceRelPath}`
474
544
  : undefined,
475
- record: projectRecordEvidenceMetadata(doc),
545
+ mime: doc.sourceMime,
546
+ ext: doc.sourceExt,
547
+ modifiedAt: doc.sourceMtime,
548
+ documentDate: doc.frontmatterDate ?? undefined,
549
+ sizeBytes: doc.sourceSize,
550
+ sourceHash: doc.sourceHash,
476
551
  },
477
- doc.collection,
478
- contentTypeRules,
479
- options.projectAffinity,
480
- doc.contentTypeSource,
481
- { kind: "vector_distance", score: rawDistance }
482
- );
483
- results.push(
552
+ conversion: doc.mirrorHash
553
+ ? {
554
+ mirrorHash: doc.mirrorHash,
555
+ converterId: doc.converterId ?? undefined,
556
+ converterVersion: doc.converterVersion ?? undefined,
557
+ }
558
+ : undefined,
559
+ record: projectRecordEvidenceMetadata(doc),
560
+ };
561
+ const result = auxiliaryRankingActive
562
+ ? applyContentTypeBoost(
563
+ baseResult,
564
+ doc.collection,
565
+ contentTypeRules,
566
+ options.projectAffinity,
567
+ doc.contentTypeSource,
568
+ { kind: "vector_distance", score: rawDistance }
569
+ )
570
+ : baseResult;
571
+ finalResults.push(
484
572
  doc.mirrorHash
485
573
  ? attachSearchResultPlannerMetadata(result, {
486
574
  retrievalRank: 0,
@@ -497,40 +585,58 @@ async function searchVectorWithEmbeddingOwned(
497
585
  : result
498
586
  );
499
587
  }
500
- }
501
-
502
- if (recencySort) {
503
- results.sort((a, b) => {
504
- const aTs = resolveRecencyTimestamp(
505
- a.source.documentDate,
506
- a.source.modifiedAt
507
- );
508
- const bTs = resolveRecencyTimestamp(
509
- b.source.documentDate,
510
- b.source.modifiedAt
511
- );
512
- if (aTs !== bTs) {
513
- return bTs - aTs;
588
+ } else {
589
+ if (recencySort) {
590
+ const recencyTs = new Map<SearchResult, number>();
591
+ for (const r of results) {
592
+ recencyTs.set(
593
+ r,
594
+ resolveRecencyTimestamp(r.source.documentDate, r.source.modifiedAt)
595
+ );
514
596
  }
515
- return b.score - a.score;
516
- });
517
- } else if (auxiliaryRankingActive) {
518
- sortByFinalScoreStable(results);
597
+ results.sort((a, b) => {
598
+ const aTs = recencyTs.get(a) ?? 0;
599
+ const bTs = recencyTs.get(b) ?? 0;
600
+ if (aTs !== bTs) {
601
+ return bTs - aTs;
602
+ }
603
+ return b.score - a.score;
604
+ });
605
+ } else if (auxiliaryRankingActive) {
606
+ sortByFinalScoreStable(results);
607
+ }
608
+ finalResults = results.slice(0, limit);
519
609
  }
520
610
 
521
- const finalResults = results.slice(0, limit);
522
611
  for (const [index, result] of finalResults.entries()) {
523
612
  assertInferenceActive();
524
613
  const metadata = result[SEARCH_RESULT_PLANNER_METADATA];
525
- if (metadata) metadata.retrievalRank = index + 1;
614
+ if (metadata) {
615
+ metadata.retrievalRank = index + 1;
616
+ if (!metadata.passageHash) {
617
+ const text = deferredChunkTextByResult.get(result);
618
+ if (text !== undefined) {
619
+ metadata.passageHash = new Bun.CryptoHasher("sha256")
620
+ .update(text)
621
+ .digest("hex");
622
+ }
623
+ }
624
+ }
526
625
  }
527
626
  await attachSearchResultContexts(store, finalResults);
528
627
  await attachSupersession(store, finalResults);
628
+ const finalHashes = [
629
+ ...new Set(
630
+ finalResults
631
+ .map((r) => r.conversion?.mirrorHash)
632
+ .filter((hash): hash is string => Boolean(hash))
633
+ ),
634
+ ];
529
635
  const lineageResult = await attachSearchResultEgressLineage(
530
636
  store,
531
637
  finalResults,
532
638
  {
533
- ownershipHashes: uniqueHashes,
639
+ ownershipHashes: finalHashes,
534
640
  ownershipDocuments,
535
641
  collections: collectionsResult.ok ? collectionsResult.value : undefined,
536
642
  }
@@ -561,6 +667,13 @@ async function searchVectorWithEmbeddingOwned(
561
667
  queryLanguage,
562
668
  },
563
669
  };
670
+ if (vectorRoute) {
671
+ attachSearchResultsTraceMetadata(output, {
672
+ capabilityOutcomes: [{ capability: "semantic_search", status: "used" }],
673
+ fallbackCodes: [],
674
+ vectorRoute,
675
+ });
676
+ }
564
677
  const traceResult = await options.traceSession?.recordRetrieval(
565
678
  output,
566
679
  performance.now() - traceStartedAt
@@ -683,16 +796,17 @@ interface DocumentMapOptions {
683
796
 
684
797
  function matchesCategoryFilter(
685
798
  doc: { contentType?: string | null; categories?: string[] | null },
686
- categories?: string[]
799
+ allowedCategories?: Set<string>
687
800
  ): boolean {
688
- if (!categories || categories.length === 0) {
801
+ if (!allowedCategories || allowedCategories.size === 0) {
689
802
  return true;
690
803
  }
691
- const allowed = new Set(categories.map((c) => c.toLowerCase()));
692
- if (doc.contentType && allowed.has(doc.contentType.toLowerCase())) {
804
+ if (doc.contentType && allowedCategories.has(doc.contentType.toLowerCase())) {
693
805
  return true;
694
806
  }
695
- return (doc.categories ?? []).some((c) => allowed.has(c.toLowerCase()));
807
+ return (doc.categories ?? []).some((c) =>
808
+ allowedCategories.has(c.toLowerCase())
809
+ );
696
810
  }
697
811
 
698
812
  async function buildDocumentMap(
@@ -728,10 +842,14 @@ async function buildDocumentMap(
728
842
  (options.collections === undefined ||
729
843
  options.collections.includes(document.collection))
730
844
  );
731
- const temporalRange: TemporalRange = {
845
+ const temporalRange: TemporalRange = compileTemporalRange({
732
846
  since: options.since,
733
847
  until: options.until,
734
- };
848
+ });
849
+ const allowedCategories = options.categories?.length
850
+ ? new Set(options.categories.map((c) => c.toLowerCase()))
851
+ : undefined;
852
+ const authorLower = options.author ? options.author.toLowerCase() : undefined;
735
853
 
736
854
  // Apply tag filters if specified (batch fetch to avoid N+1)
737
855
  const needsTagFilter = options.tagsAll?.length || options.tagsAny?.length;
@@ -783,13 +901,10 @@ async function buildDocumentMap(
783
901
  if (!isWithinTemporalRange(doc.sourceMtime, temporalRange)) {
784
902
  continue;
785
903
  }
786
- if (!matchesCategoryFilter(doc, options.categories)) {
904
+ if (!matchesCategoryFilter(doc, allowedCategories)) {
787
905
  continue;
788
906
  }
789
- if (
790
- options.author &&
791
- !doc.author?.toLowerCase().includes(options.author.toLowerCase())
792
- ) {
907
+ if (authorLower && !doc.author?.toLowerCase().includes(authorLower)) {
793
908
  continue;
794
909
  }
795
910
 
@@ -71,22 +71,8 @@ const readU32LE = (bytes: Uint8Array, offset: number): number =>
71
71
  (bytes[offset] ?? 0)) >>>
72
72
  0;
73
73
 
74
- const CRC32_TABLE = Uint32Array.from({ length: 256 }, (_, value) => {
75
- let crc = value;
76
- for (let bit = 0; bit < 8; bit += 1) {
77
- crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0);
78
- }
79
- return crc >>> 0;
80
- });
81
-
82
- const crc32 = (bytes: Uint8Array, start: number, end: number): number => {
83
- let crc = 0xffffffff;
84
- for (let index = start; index < end; index += 1) {
85
- const tableIndex = (crc ^ (bytes[index] ?? 0)) & 0xff;
86
- crc = (crc >>> 8) ^ (CRC32_TABLE[tableIndex] ?? 0);
87
- }
88
- return (crc ^ 0xffffffff) >>> 0;
89
- };
74
+ const crc32 = (bytes: Uint8Array, start: number, end: number): number =>
75
+ Bun.hash.crc32(bytes.subarray(start, end)) >>> 0;
90
76
 
91
77
  const validateDimensions = (
92
78
  width: number,
@@ -95,13 +95,23 @@ export type EncryptedReaderSpaceData = {
95
95
 
96
96
  const toBase64 = (value: Uint8Array): string => encodeBytesToBase64(value);
97
97
 
98
+ const BASE64_WHITESPACE = /[\t\n\f\r ]+/g;
99
+ const BASE64_STRICT = /^[A-Za-z0-9+/]*={0,2}$/;
100
+
98
101
  const fromBase64 = (value: string): Uint8Array => {
99
- const binary = atob(value);
100
- const bytes = new Uint8Array(binary.length);
101
- for (let i = 0; i < binary.length; i += 1) {
102
- bytes[i] = binary.charCodeAt(i);
102
+ const cleaned = value.replace(BASE64_WHITESPACE, "");
103
+ if (
104
+ cleaned.length % 4 === 1 ||
105
+ !BASE64_STRICT.test(cleaned) ||
106
+ (cleaned.includes("=") && cleaned.length % 4 !== 0)
107
+ ) {
108
+ throw new DOMException(
109
+ "The string to be decoded is not correctly encoded.",
110
+ "InvalidCharacterError"
111
+ );
103
112
  }
104
- return bytes;
113
+ const buf = Buffer.from(cleaned, "base64");
114
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
105
115
  };
106
116
 
107
117
  const randomBytes = (size: number): Uint8Array => {