@gmickel/gno 2.14.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 (205) 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.14.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 +88 -45
  9. package/spec/db/schema.sql +45 -0
  10. package/spec/output-schemas/embed-receipt.schema.json +89 -0
  11. package/src/cli/commands/agents/commands.ts +1 -1
  12. package/src/cli/commands/ask.ts +1 -1
  13. package/src/cli/commands/context-build.ts +1 -1
  14. package/src/cli/commands/embed.ts +341 -20
  15. package/src/cli/commands/links.ts +1 -1
  16. package/src/cli/commands/mcp/install.ts +2 -2
  17. package/src/cli/commands/mcp/status.ts +1 -1
  18. package/src/cli/commands/mcp/uninstall.ts +1 -1
  19. package/src/cli/commands/query.ts +1 -1
  20. package/src/cli/commands/shared.ts +4 -4
  21. package/src/cli/commands/skill/install.ts +1 -1
  22. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  23. package/src/cli/commands/skill/uninstall.ts +1 -1
  24. package/src/cli/commands/status.ts +75 -58
  25. package/src/cli/config-cache.ts +86 -0
  26. package/src/cli/globals.ts +64 -0
  27. package/src/cli/options.ts +23 -0
  28. package/src/cli/program.ts +44 -37
  29. package/src/cli/run.ts +121 -67
  30. package/src/cli/runtime-health.ts +132 -122
  31. package/src/cli/session-binding.ts +11 -2
  32. package/src/config/saver.ts +8 -0
  33. package/src/converters/adapters/browser-export/formats.ts +25 -15
  34. package/src/converters/adapters/email/adapter.ts +37 -53
  35. package/src/converters/adapters/email/html.ts +37 -20
  36. package/src/converters/adapters/email/mime.ts +71 -39
  37. package/src/converters/adapters/ical/adapter.ts +20 -12
  38. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  39. package/src/converters/adapters/shared/html-text.ts +55 -37
  40. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  41. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  42. package/src/converters/adapters/transcript/adapter.ts +12 -7
  43. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  44. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  45. package/src/converters/canonicalize.ts +17 -3
  46. package/src/converters/native/markdown.ts +24 -17
  47. package/src/converters/native/plaintext.ts +5 -6
  48. package/src/converters/registry.ts +130 -8
  49. package/src/core/activation-status.ts +4 -8
  50. package/src/core/change-diff.ts +38 -11
  51. package/src/core/context-compiler.ts +17 -18
  52. package/src/core/context-evidence.ts +116 -25
  53. package/src/core/context-verifier.ts +70 -31
  54. package/src/core/file-lock.ts +10 -2
  55. package/src/core/graph-analysis.ts +3 -3
  56. package/src/core/link-inventory-markdown.ts +2 -2
  57. package/src/core/links.ts +20 -87
  58. package/src/core/memory-fence.ts +16 -9
  59. package/src/core/memory-recall.ts +168 -34
  60. package/src/core/path-rules.ts +143 -0
  61. package/src/core/section-parse.ts +16 -6
  62. package/src/core/typed-metadata.ts +68 -0
  63. package/src/core/wiki-link-syntax.ts +88 -0
  64. package/src/embed/backlog.ts +173 -60
  65. package/src/embed/batch.ts +83 -12
  66. package/src/embed/resume-cursor.ts +103 -0
  67. package/src/embed/retry.ts +41 -32
  68. package/src/embed/variant-backlog.ts +697 -63
  69. package/src/embed/variant-plan.ts +41 -45
  70. package/src/embed/variant-retry.ts +157 -44
  71. package/src/index.ts +3 -3
  72. package/src/ingestion/budget-error-codes.ts +13 -0
  73. package/src/ingestion/chunker.ts +60 -49
  74. package/src/ingestion/compiled-context.ts +4 -5
  75. package/src/ingestion/convert-file.ts +1 -1
  76. package/src/ingestion/document-metadata.ts +16 -9
  77. package/src/ingestion/excluded-ranges.ts +97 -0
  78. package/src/ingestion/file-processor.ts +122 -37
  79. package/src/ingestion/frontmatter.ts +35 -7
  80. package/src/ingestion/graph-reconciliation.ts +187 -51
  81. package/src/ingestion/language.ts +66 -61
  82. package/src/ingestion/position.ts +5 -5
  83. package/src/ingestion/prepare-file.ts +50 -29
  84. package/src/ingestion/record-adapter-canonical.ts +37 -26
  85. package/src/ingestion/record-adapter.ts +46 -26
  86. package/src/ingestion/record-container.ts +121 -53
  87. package/src/ingestion/record-path.ts +5 -2
  88. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  89. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  90. package/src/ingestion/source-availability/readers.ts +51 -0
  91. package/src/ingestion/strip.ts +39 -105
  92. package/src/ingestion/sync.ts +692 -386
  93. package/src/ingestion/typed-metadata.ts +10 -4
  94. package/src/ingestion/walker.ts +485 -158
  95. package/src/llm/cache.ts +128 -84
  96. package/src/llm/http-inference.ts +112 -35
  97. package/src/llm/http-policy.ts +101 -0
  98. package/src/llm/httpEmbedding.ts +8 -1
  99. package/src/llm/httpGeneration.ts +5 -1
  100. package/src/llm/httpRerank.ts +5 -1
  101. package/src/llm/inference-scope.ts +15 -2
  102. package/src/llm/lazy-ports.ts +33 -3
  103. package/src/llm/lockfile.ts +34 -7
  104. package/src/llm/model-cleanup.ts +24 -0
  105. package/src/llm/native-worker/client.ts +23 -12
  106. package/src/llm/native-worker/dispatcher.ts +19 -9
  107. package/src/llm/native-worker/embedding-identity.ts +42 -16
  108. package/src/llm/native-worker/entry.ts +2 -1
  109. package/src/llm/native-worker/owner.ts +1 -0
  110. package/src/llm/native-worker/ports.ts +86 -23
  111. package/src/llm/native-worker/protocol.ts +386 -55
  112. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  113. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  114. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  115. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  116. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  117. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  118. package/src/llm/types.ts +14 -0
  119. package/src/mcp/context.ts +342 -23
  120. package/src/mcp/http-transport.ts +21 -3
  121. package/src/mcp/tool-profile-types.ts +62 -0
  122. package/src/mcp/tool-profile.ts +32 -56
  123. package/src/mcp/tools/context.ts +5 -1
  124. package/src/mcp/tools/index.ts +269 -191
  125. package/src/mcp/tools/links.ts +7 -5
  126. package/src/mcp/tools/query.ts +60 -37
  127. package/src/mcp/tools/vsearch.ts +25 -14
  128. package/src/pipeline/answer.ts +133 -40
  129. package/src/pipeline/claim-verification.ts +293 -189
  130. package/src/pipeline/claim-verifier.ts +6 -7
  131. package/src/pipeline/egress-lineage.ts +37 -26
  132. package/src/pipeline/exclude.ts +34 -11
  133. package/src/pipeline/expansion.ts +233 -19
  134. package/src/pipeline/filters.ts +169 -33
  135. package/src/pipeline/graph-retrieval.ts +117 -61
  136. package/src/pipeline/hybrid.ts +598 -329
  137. package/src/pipeline/hydration.ts +86 -24
  138. package/src/pipeline/intent.ts +15 -7
  139. package/src/pipeline/owner-fusion.ts +61 -19
  140. package/src/pipeline/query-language.ts +15 -2
  141. package/src/pipeline/rerank.ts +15 -22
  142. package/src/pipeline/search.ts +193 -72
  143. package/src/pipeline/snippet.ts +15 -2
  144. package/src/pipeline/temporal.ts +51 -10
  145. package/src/pipeline/vsearch.ts +250 -152
  146. package/src/publish/attachment-raster.ts +2 -16
  147. package/src/publish/encrypted-export.ts +15 -5
  148. package/src/serve/browse-tree.ts +50 -42
  149. package/src/serve/connectors.ts +2 -1
  150. package/src/serve/context.ts +13 -4
  151. package/src/serve/doc-events.ts +3 -0
  152. package/src/serve/public/app.tsx +49 -21
  153. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  154. package/src/serve/public/components/CaptureModal.tsx +14 -10
  155. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  156. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  157. package/src/serve/public/globals.built.css +1 -1
  158. package/src/serve/public/globals.css +19 -0
  159. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  160. package/src/serve/public/lib/metadata-filter.ts +234 -9
  161. package/src/serve/public/pages/Browse.tsx +61 -27
  162. package/src/serve/public/pages/DocView.tsx +44 -25
  163. package/src/serve/public/pages/GraphView.tsx +8 -3
  164. package/src/serve/resident-runtime.ts +199 -48
  165. package/src/serve/routes/api.ts +98 -67
  166. package/src/serve/routes/links.ts +18 -4
  167. package/src/serve/server.ts +1370 -1180
  168. package/src/serve/spa-bundle-source.ts +52 -27
  169. package/src/serve/status.ts +101 -52
  170. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  171. package/src/serve/watch-reconciliation-shared.ts +42 -4
  172. package/src/serve/watch-reconciliation.ts +21 -8
  173. package/src/serve/watch-service-events.ts +7 -1
  174. package/src/serve/watch-service-hosts.ts +3 -1
  175. package/src/serve/watch-service.ts +46 -21
  176. package/src/serve/watch-snapshot-scan.ts +6 -15
  177. package/src/sessions/archive.ts +20 -8
  178. package/src/sessions/sanitize.ts +38 -18
  179. package/src/sessions/service.ts +180 -102
  180. package/src/store/migrations/036-vector-mirror-state.ts +83 -0
  181. package/src/store/migrations/037-performance-indexes.ts +56 -0
  182. package/src/store/migrations/index.ts +4 -0
  183. package/src/store/sqlite/adapter.ts +1217 -651
  184. package/src/store/sqlite/chunking-policy.ts +15 -1
  185. package/src/store/sqlite/eligibility.ts +110 -70
  186. package/src/store/sqlite/graph-neighbors.ts +71 -46
  187. package/src/store/sqlite/graph-reference-state.ts +27 -3
  188. package/src/store/sqlite/graph-similarity.ts +59 -12
  189. package/src/store/sqlite/metadata-predicate.ts +123 -28
  190. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  191. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  192. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  193. package/src/store/types.ts +32 -0
  194. package/src/store/vector/eligibility.ts +39 -0
  195. package/src/store/vector/lazy.ts +17 -0
  196. package/src/store/vector/partition-index.ts +49 -47
  197. package/src/store/vector/proof-cache.ts +103 -0
  198. package/src/store/vector/sqlite-vec.ts +230 -139
  199. package/src/store/vector/stats.ts +29 -73
  200. package/src/store/vector/status.ts +151 -52
  201. package/src/store/vector/stored-vectors.ts +131 -45
  202. package/src/store/vector/types.ts +10 -0
  203. package/src/store/vector/variant-search.ts +771 -109
  204. package/src/store/vector/variants.ts +785 -144
  205. package/browser-extension/artifacts/gno-browser-clipper-v2.14.0.zip.sha256 +0 -1
@@ -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,6 +49,7 @@ 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,
@@ -140,8 +146,7 @@ async function searchVectorWithEmbeddingOwned(
140
146
  );
141
147
 
142
148
  // Detect query language for metadata (DOES NOT affect retrieval filtering)
143
- const detection = detectQueryLanguage(query);
144
- const queryLanguage = options.lang ?? detection.bcp47;
149
+ const queryLanguage = options.lang ?? detectQueryLanguage(query).bcp47;
145
150
 
146
151
  // Check if vector search is available
147
152
  if (!vectorIndex.searchAvailable) {
@@ -245,6 +250,15 @@ async function searchVectorWithEmbeddingOwned(
245
250
 
246
251
  // Build search results
247
252
  const results: SearchResult[] = [];
253
+ const deferredChunkTextByResult = new WeakMap<SearchResult, string>();
254
+ const excludeTermsLower = compileExcludeTerms(options.exclude);
255
+ const excludedMirrorCache = excludeTermsLower
256
+ ? new Map<string, boolean>()
257
+ : undefined;
258
+ const queryTerms = options.intent ? extractSteeringTerms(query) : undefined;
259
+ const intentTerms = options.intent
260
+ ? extractSteeringTerms(options.intent)
261
+ : undefined;
248
262
 
249
263
  // For --full, track best score per docid to de-dupe
250
264
  const bestByDocid = new Map<
@@ -277,6 +291,8 @@ async function searchVectorWithEmbeddingOwned(
277
291
  {
278
292
  preferredSeq: rawChunk?.seq ?? vec.seq,
279
293
  intentWeight: 0.3,
294
+ queryTerms,
295
+ intentTerms,
280
296
  }
281
297
  ) ?? rawChunk)
282
298
  : rawChunk;
@@ -303,11 +319,26 @@ async function searchVectorWithEmbeddingOwned(
303
319
  auxiliaryRankingActive || vec.documentIds !== undefined
304
320
  ? matchingDocs
305
321
  : [matchingDocs.at(-1)!];
322
+ let chunksExcluded = false;
323
+ if (excludeTermsLower) {
324
+ const cached = excludedMirrorCache!.get(vec.mirrorHash);
325
+ if (cached !== undefined) {
326
+ chunksExcluded = cached;
327
+ } else {
328
+ chunksExcluded = matchesExcludedChunks(
329
+ chunksMap.get(vec.mirrorHash) ?? [],
330
+ excludeTermsLower,
331
+ true
332
+ );
333
+ excludedMirrorCache!.set(vec.mirrorHash, chunksExcluded);
334
+ }
335
+ if (chunksExcluded) continue;
336
+ }
306
337
  for (const doc of docs) {
307
338
  assertInferenceActive();
308
- const collectionPath = collectionPaths.get(doc.collection);
309
339
  const sourceRelPath = doc.recordSourcePath ?? doc.relPath;
310
- const excluded =
340
+ if (
341
+ excludeTermsLower &&
311
342
  matchesExcludedText(
312
343
  [
313
344
  doc.title ?? "",
@@ -316,66 +347,31 @@ async function searchVectorWithEmbeddingOwned(
316
347
  doc.contentType ?? "",
317
348
  ...(doc.categories ?? []),
318
349
  ],
319
- options.exclude
320
- ) ||
321
- matchesExcludedChunks(
322
- chunksMap.get(vec.mirrorHash) ?? [],
323
- options.exclude
324
- );
325
- if (excluded) {
350
+ excludeTermsLower,
351
+ true
352
+ )
353
+ ) {
326
354
  continue;
327
355
  }
328
356
 
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)
357
+ // For --full, avoid throwaway snippet cleaning / SearchResult construction;
358
+ // compute only the final score needed for dedupe/filtering/ranking.
376
359
  if (options.full) {
360
+ const rankingScore = auxiliaryRankingActive
361
+ ? scoreContentTypeBoost(
362
+ baseScore,
363
+ doc.contentType ?? undefined,
364
+ doc.contentTypeSource,
365
+ sourceRelPath,
366
+ doc.collection,
367
+ contentTypeRules,
368
+ options.projectAffinity,
369
+ { kind: "vector_distance", score: vec.distance }
370
+ ).projectAffinity.finalScore
371
+ : baseScore;
372
+ if (rankingScore < minScore) continue;
377
373
  const existing = bestByDocid.get(doc.docid);
378
- if (!existing || scoredResult.score > existing.rankingScore) {
374
+ if (!existing || rankingScore > existing.rankingScore) {
379
375
  bestByDocid.set(doc.docid, {
380
376
  doc,
381
377
  chunk: {
@@ -385,7 +381,7 @@ async function searchVectorWithEmbeddingOwned(
385
381
  endLine: chunk.endLine,
386
382
  seq: chunk.seq,
387
383
  },
388
- rankingScore: scoredResult.score,
384
+ rankingScore,
389
385
  rawDistance: vec.distance,
390
386
  score: baseScore,
391
387
  });
@@ -393,28 +389,106 @@ async function searchVectorWithEmbeddingOwned(
393
389
  continue;
394
390
  }
395
391
 
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,
392
+ const collectionPath = collectionPaths.get(doc.collection);
393
+ const cleanedSnippet = cleanDisplaySnippet(chunk.text, chunk.text);
394
+ const snippetStartLine = chunk.startLine + cleanedSnippet.startLineOffset;
395
+ const baseResult: SearchResult = {
396
+ docid: doc.docid,
397
+ score: baseScore,
398
+ uri: doc.uri,
399
+ title: doc.title ?? undefined,
400
+ contentType: doc.contentType ?? undefined,
401
+ categories: doc.categories ?? undefined,
402
+ line: snippetStartLine,
403
+ snippet: cleanedSnippet.text,
404
+ snippetLanguage: chunk.language ?? undefined,
405
+ snippetRange: {
406
+ startLine: snippetStartLine,
404
407
  endLine: chunk.endLine,
405
- passageHash: new Bun.CryptoHasher("sha256")
406
- .update(chunk.text)
407
- .digest("hex"),
408
- })
409
- );
408
+ },
409
+ source: {
410
+ relPath: sourceRelPath,
411
+ absPath: collectionPath
412
+ ? `${collectionPath}/${sourceRelPath}`
413
+ : undefined,
414
+ mime: doc.sourceMime,
415
+ ext: doc.sourceExt,
416
+ modifiedAt: doc.sourceMtime,
417
+ documentDate: doc.frontmatterDate ?? undefined,
418
+ sizeBytes: doc.sourceSize,
419
+ sourceHash: doc.sourceHash,
420
+ },
421
+ conversion: doc.mirrorHash
422
+ ? {
423
+ mirrorHash: doc.mirrorHash,
424
+ converterId: doc.converterId ?? undefined,
425
+ converterVersion: doc.converterVersion ?? undefined,
426
+ }
427
+ : undefined,
428
+ record: projectRecordEvidenceMetadata(doc),
429
+ };
430
+ const scoredResult = auxiliaryRankingActive
431
+ ? applyContentTypeBoost(
432
+ baseResult,
433
+ doc.collection,
434
+ contentTypeRules,
435
+ options.projectAffinity,
436
+ doc.contentTypeSource,
437
+ { kind: "vector_distance", score: vec.distance }
438
+ )
439
+ : baseResult;
440
+ if (scoredResult.score < minScore) continue;
441
+
442
+ const attached = attachSearchResultPlannerMetadata(scoredResult, {
443
+ retrievalRank: 0,
444
+ mirrorHash: vec.mirrorHash,
445
+ seq: chunk.seq,
446
+ sources: ["vector"],
447
+ graphExpanded: false,
448
+ startLine: chunk.startLine,
449
+ endLine: chunk.endLine,
450
+ passageHash: "",
451
+ });
452
+ deferredChunkTextByResult.set(attached, chunk.text);
453
+ results.push(attached);
410
454
  }
411
455
  }
412
456
 
413
- // For --full, fetch full content and build results
457
+ let finalResults: SearchResult[];
458
+ // For --full, sort and slice BEFORE fetching full content via getContentBatch
414
459
  if (options.full) {
460
+ const entries = [...bestByDocid.values()];
461
+ if (recencySort) {
462
+ const recencyTs = new Map<(typeof entries)[number], number>();
463
+ for (const entry of entries) {
464
+ recencyTs.set(
465
+ entry,
466
+ resolveRecencyTimestamp(
467
+ entry.doc.frontmatterDate,
468
+ entry.doc.sourceMtime
469
+ )
470
+ );
471
+ }
472
+ entries.sort((a, b) => {
473
+ const aTs = recencyTs.get(a) ?? 0;
474
+ const bTs = recencyTs.get(b) ?? 0;
475
+ if (aTs !== bTs) return bTs - aTs;
476
+ return b.rankingScore - a.rankingScore;
477
+ });
478
+ } else if (auxiliaryRankingActive) {
479
+ const originalRank = new Map(
480
+ entries.map((entry, idx) => [entry, idx] as const)
481
+ );
482
+ entries.sort(
483
+ (left, right) =>
484
+ right.rankingScore - left.rankingScore ||
485
+ (originalRank.get(left) ?? 0) - (originalRank.get(right) ?? 0)
486
+ );
487
+ }
488
+ const survivingEntries = entries.slice(0, limit);
415
489
  const fullContentResult = await getContentBatch(
416
490
  store,
417
- [...bestByDocid.values()]
491
+ survivingEntries
418
492
  .map(({ doc }) => doc.mirrorHash)
419
493
  .filter((mirrorHash): mirrorHash is string => Boolean(mirrorHash))
420
494
  );
@@ -423,7 +497,8 @@ async function searchVectorWithEmbeddingOwned(
423
497
  }
424
498
  const fullContentByHash = fullContentResult.value;
425
499
 
426
- for (const { doc, chunk, rawDistance, score } of bestByDocid.values()) {
500
+ finalResults = [];
501
+ for (const { doc, chunk, rawDistance, score } of survivingEntries) {
427
502
  assertInferenceActive();
428
503
  const fullContent = doc.mirrorHash
429
504
  ? fullContentByHash.get(doc.mirrorHash)
@@ -438,49 +513,52 @@ async function searchVectorWithEmbeddingOwned(
438
513
  ? chunk.startLine + cleanedChunk.startLineOffset
439
514
  : chunk.startLine;
440
515
 
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
- }
516
+ const baseResult: SearchResult = {
517
+ docid: doc.docid,
518
+ score,
519
+ uri: doc.uri,
520
+ title: doc.title ?? undefined,
521
+ contentType: doc.contentType ?? undefined,
522
+ categories: doc.categories ?? undefined,
523
+ line: snippetStartLine,
524
+ snippet: fullContent ?? cleanedChunk?.text ?? chunk.text,
525
+ snippetLanguage: chunk.language ?? undefined,
526
+ // --full: no snippetRange (full doc content)
527
+ snippetRange: fullContent
528
+ ? undefined
529
+ : { startLine: snippetStartLine, endLine: chunk.endLine },
530
+ source: {
531
+ relPath: sourceRelPath,
532
+ absPath: collectionPath
533
+ ? `${collectionPath}/${sourceRelPath}`
474
534
  : undefined,
475
- record: projectRecordEvidenceMetadata(doc),
535
+ mime: doc.sourceMime,
536
+ ext: doc.sourceExt,
537
+ modifiedAt: doc.sourceMtime,
538
+ documentDate: doc.frontmatterDate ?? undefined,
539
+ sizeBytes: doc.sourceSize,
540
+ sourceHash: doc.sourceHash,
476
541
  },
477
- doc.collection,
478
- contentTypeRules,
479
- options.projectAffinity,
480
- doc.contentTypeSource,
481
- { kind: "vector_distance", score: rawDistance }
482
- );
483
- results.push(
542
+ conversion: doc.mirrorHash
543
+ ? {
544
+ mirrorHash: doc.mirrorHash,
545
+ converterId: doc.converterId ?? undefined,
546
+ converterVersion: doc.converterVersion ?? undefined,
547
+ }
548
+ : undefined,
549
+ record: projectRecordEvidenceMetadata(doc),
550
+ };
551
+ const result = auxiliaryRankingActive
552
+ ? applyContentTypeBoost(
553
+ baseResult,
554
+ doc.collection,
555
+ contentTypeRules,
556
+ options.projectAffinity,
557
+ doc.contentTypeSource,
558
+ { kind: "vector_distance", score: rawDistance }
559
+ )
560
+ : baseResult;
561
+ finalResults.push(
484
562
  doc.mirrorHash
485
563
  ? attachSearchResultPlannerMetadata(result, {
486
564
  retrievalRank: 0,
@@ -497,40 +575,58 @@ async function searchVectorWithEmbeddingOwned(
497
575
  : result
498
576
  );
499
577
  }
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;
578
+ } else {
579
+ if (recencySort) {
580
+ const recencyTs = new Map<SearchResult, number>();
581
+ for (const r of results) {
582
+ recencyTs.set(
583
+ r,
584
+ resolveRecencyTimestamp(r.source.documentDate, r.source.modifiedAt)
585
+ );
514
586
  }
515
- return b.score - a.score;
516
- });
517
- } else if (auxiliaryRankingActive) {
518
- sortByFinalScoreStable(results);
587
+ results.sort((a, b) => {
588
+ const aTs = recencyTs.get(a) ?? 0;
589
+ const bTs = recencyTs.get(b) ?? 0;
590
+ if (aTs !== bTs) {
591
+ return bTs - aTs;
592
+ }
593
+ return b.score - a.score;
594
+ });
595
+ } else if (auxiliaryRankingActive) {
596
+ sortByFinalScoreStable(results);
597
+ }
598
+ finalResults = results.slice(0, limit);
519
599
  }
520
600
 
521
- const finalResults = results.slice(0, limit);
522
601
  for (const [index, result] of finalResults.entries()) {
523
602
  assertInferenceActive();
524
603
  const metadata = result[SEARCH_RESULT_PLANNER_METADATA];
525
- if (metadata) metadata.retrievalRank = index + 1;
604
+ if (metadata) {
605
+ metadata.retrievalRank = index + 1;
606
+ if (!metadata.passageHash) {
607
+ const text = deferredChunkTextByResult.get(result);
608
+ if (text !== undefined) {
609
+ metadata.passageHash = new Bun.CryptoHasher("sha256")
610
+ .update(text)
611
+ .digest("hex");
612
+ }
613
+ }
614
+ }
526
615
  }
527
616
  await attachSearchResultContexts(store, finalResults);
528
617
  await attachSupersession(store, finalResults);
618
+ const finalHashes = [
619
+ ...new Set(
620
+ finalResults
621
+ .map((r) => r.conversion?.mirrorHash)
622
+ .filter((hash): hash is string => Boolean(hash))
623
+ ),
624
+ ];
529
625
  const lineageResult = await attachSearchResultEgressLineage(
530
626
  store,
531
627
  finalResults,
532
628
  {
533
- ownershipHashes: uniqueHashes,
629
+ ownershipHashes: finalHashes,
534
630
  ownershipDocuments,
535
631
  collections: collectionsResult.ok ? collectionsResult.value : undefined,
536
632
  }
@@ -683,16 +779,17 @@ interface DocumentMapOptions {
683
779
 
684
780
  function matchesCategoryFilter(
685
781
  doc: { contentType?: string | null; categories?: string[] | null },
686
- categories?: string[]
782
+ allowedCategories?: Set<string>
687
783
  ): boolean {
688
- if (!categories || categories.length === 0) {
784
+ if (!allowedCategories || allowedCategories.size === 0) {
689
785
  return true;
690
786
  }
691
- const allowed = new Set(categories.map((c) => c.toLowerCase()));
692
- if (doc.contentType && allowed.has(doc.contentType.toLowerCase())) {
787
+ if (doc.contentType && allowedCategories.has(doc.contentType.toLowerCase())) {
693
788
  return true;
694
789
  }
695
- return (doc.categories ?? []).some((c) => allowed.has(c.toLowerCase()));
790
+ return (doc.categories ?? []).some((c) =>
791
+ allowedCategories.has(c.toLowerCase())
792
+ );
696
793
  }
697
794
 
698
795
  async function buildDocumentMap(
@@ -728,10 +825,14 @@ async function buildDocumentMap(
728
825
  (options.collections === undefined ||
729
826
  options.collections.includes(document.collection))
730
827
  );
731
- const temporalRange: TemporalRange = {
828
+ const temporalRange: TemporalRange = compileTemporalRange({
732
829
  since: options.since,
733
830
  until: options.until,
734
- };
831
+ });
832
+ const allowedCategories = options.categories?.length
833
+ ? new Set(options.categories.map((c) => c.toLowerCase()))
834
+ : undefined;
835
+ const authorLower = options.author ? options.author.toLowerCase() : undefined;
735
836
 
736
837
  // Apply tag filters if specified (batch fetch to avoid N+1)
737
838
  const needsTagFilter = options.tagsAll?.length || options.tagsAny?.length;
@@ -783,13 +884,10 @@ async function buildDocumentMap(
783
884
  if (!isWithinTemporalRange(doc.sourceMtime, temporalRange)) {
784
885
  continue;
785
886
  }
786
- if (!matchesCategoryFilter(doc, options.categories)) {
887
+ if (!matchesCategoryFilter(doc, allowedCategories)) {
787
888
  continue;
788
889
  }
789
- if (
790
- options.author &&
791
- !doc.author?.toLowerCase().includes(options.author.toLowerCase())
792
- ) {
890
+ if (authorLower && !doc.author?.toLowerCase().includes(authorLower)) {
793
891
  continue;
794
892
  }
795
893
 
@@ -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 => {