@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
@@ -27,9 +27,13 @@ import {
27
27
  sortByFinalScoreStable,
28
28
  } from "./content-type-boost";
29
29
  import { attachSearchResultEgressLineage } from "./egress-lineage";
30
- import { matchesExcludedChunks, matchesExcludedText } from "./exclude";
30
+ import {
31
+ compileExcludeTerms,
32
+ matchesExcludedChunks,
33
+ matchesExcludedText,
34
+ } from "./exclude";
31
35
  import { typedMetadataWarnings } from "./filters";
32
- import { selectBestChunkForSteering } from "./intent";
36
+ import { extractSteeringTerms, selectBestChunkForSteering } from "./intent";
33
37
  import { hasProjectAffinity } from "./project-affinity";
34
38
  import { detectQueryLanguage } from "./query-language";
35
39
  import {
@@ -100,11 +104,19 @@ interface BuildResultContext {
100
104
  collectionPath?: string;
101
105
  options?: SearchOptions;
102
106
  fullContent?: string;
107
+ deferPassageHash?: boolean;
103
108
  }
104
109
 
105
110
  /** Build SearchResult from FtsResult and related data */
106
111
  function buildSearchResult(ctx: BuildResultContext): SearchResult {
107
- const { fts, chunk, collectionPath, options, fullContent } = ctx;
112
+ const {
113
+ fts,
114
+ chunk,
115
+ collectionPath,
116
+ options,
117
+ fullContent,
118
+ deferPassageHash = false,
119
+ } = ctx;
108
120
  const sourceRelPath = fts.recordSourcePath ?? fts.relPath ?? "";
109
121
  const source: SearchResultSource = {
110
122
  relPath: sourceRelPath,
@@ -135,17 +147,16 @@ function buildSearchResult(ctx: BuildResultContext): SearchResult {
135
147
  // --line-numbers: use raw chunk text (not FTS snippet with markers)
136
148
  snippet = chunk.text;
137
149
  snippetRange = { startLine: chunk.startLine, endLine: chunk.endLine };
138
- } else {
150
+ } else if (chunk) {
139
151
  // Default: chunk text until attachChunkSnippets replaces it for the final
140
152
  // rows, with leading frontmatter stripped
141
- const cleaned = cleanDisplaySnippet(chunk?.text ?? "", chunk?.text);
153
+ const cleaned = cleanDisplaySnippet(chunk.text, chunk.text);
142
154
  snippet = cleaned.text;
143
- if (chunk) {
144
- line = chunk.startLine + cleaned.startLineOffset;
145
- snippetRange = { startLine: line, endLine: chunk.endLine };
146
- } else {
147
- snippetRange = undefined;
148
- }
155
+ line = chunk.startLine + cleaned.startLineOffset;
156
+ snippetRange = { startLine: line, endLine: chunk.endLine };
157
+ } else {
158
+ snippet = "";
159
+ snippetRange = undefined;
149
160
  }
150
161
 
151
162
  const result: SearchResult = {
@@ -172,7 +183,7 @@ function buildSearchResult(ctx: BuildResultContext): SearchResult {
172
183
  graphExpanded: false,
173
184
  startLine: chunk.startLine,
174
185
  endLine: chunk.endLine,
175
- passageHash: passageHash(chunk.text),
186
+ passageHash: deferPassageHash ? "" : passageHash(chunk.text),
176
187
  });
177
188
  }
178
189
 
@@ -255,10 +266,10 @@ async function attachChunkSnippets(
255
266
  });
256
267
  let chunks = read.chunks;
257
268
  if (!chunks) {
269
+ const chosenKeys = chosen.filter((key) => key !== undefined);
270
+ if (chosenKeys.length === 0) return;
258
271
  const fetched = store.getChunksBySequenceBatch
259
- ? await store.getChunksBySequenceBatch(
260
- chosen.filter((key) => key !== undefined)
261
- )
272
+ ? await store.getChunksBySequenceBatch(chosenKeys)
262
273
  : await store.getChunksBatch(hashes);
263
274
  if (!fetched.ok) return;
264
275
  chunks = fetched.value;
@@ -334,8 +345,7 @@ export async function searchBm25(
334
345
  );
335
346
 
336
347
  // Detect query language for metadata (DOES NOT affect retrieval filtering)
337
- const detection = detectQueryLanguage(query);
338
- const queryLanguage = options.lang ?? detection.bcp47;
348
+ const queryLanguage = options.lang ?? detectQueryLanguage(query).bcp47;
339
349
 
340
350
  // Run FTS search (ranking only; snippets come from chunks of the final rows)
341
351
  const ftsResult = await store.searchFts(query, {
@@ -389,27 +399,44 @@ export async function searchBm25(
389
399
  >();
390
400
 
391
401
  // Exact sequences suffice unless selection needs whole-document evidence.
402
+ // In default mode (no --full, --line-numbers, --intent, or --exclude), defer
403
+ // chunk loading, display-snippet cleaning, and passage hashing until after
404
+ // slicing to the final `limit` rows.
392
405
  const uniqueHashes = [
393
406
  ...new Set(
394
407
  ftsResult.value.map((f) => f.mirrorHash).filter((h): h is string => !!h)
395
408
  ),
396
409
  ];
397
410
  const needsAllChunks = Boolean(options.intent || options.exclude?.length);
398
- const chunksMapResult =
399
- store.getChunksBySequenceBatch && !needsAllChunks
400
- ? await store.getChunksBySequenceBatch(
401
- ftsResult.value
402
- .filter((row) => !!row.mirrorHash)
403
- .map((row) => ({ mirrorHash: row.mirrorHash!, seq: row.seq }))
404
- )
405
- : await store.getChunksBatch(uniqueHashes);
406
- const getChunk = chunksMapResult.ok
411
+ const deferDefaultChunks =
412
+ !options.full && !options.lineNumbers && !needsAllChunks;
413
+ let chunksMapResult:
414
+ | Awaited<ReturnType<StorePort["getChunksBatch"]>>
415
+ | undefined;
416
+ if (!deferDefaultChunks) {
417
+ chunksMapResult =
418
+ store.getChunksBySequenceBatch && !needsAllChunks
419
+ ? await store.getChunksBySequenceBatch(
420
+ ftsResult.value
421
+ .filter((row) => !!row.mirrorHash)
422
+ .map((row) => ({ mirrorHash: row.mirrorHash!, seq: row.seq }))
423
+ )
424
+ : await store.getChunksBatch(uniqueHashes);
425
+ }
426
+ const getChunk = chunksMapResult?.ok
407
427
  ? createChunkLookup(chunksMapResult.value)
408
428
  : () => undefined;
409
429
  const allChunks =
410
- chunksMapResult.ok && (needsAllChunks || !store.getChunksBySequenceBatch)
430
+ chunksMapResult?.ok && (needsAllChunks || !store.getChunksBySequenceBatch)
411
431
  ? chunksMapResult.value
412
432
  : undefined;
433
+ const excludeTermsLower = compileExcludeTerms(options.exclude);
434
+ const queryTerms = options.intent ? extractSteeringTerms(query) : undefined;
435
+ const intentTerms = options.intent
436
+ ? extractSteeringTerms(options.intent)
437
+ : undefined;
438
+ const deferredChunkByResult = new WeakMap<SearchResult, ChunkRow>();
439
+ const deferredFtsByResult = new WeakMap<SearchResult, FtsResult>();
413
440
 
414
441
  // Dedup: multiple docs can share mirror_hash (content-addressed storage)
415
442
  // Track seen uri+seq to eliminate duplicate rows from join fan-out
@@ -437,14 +464,15 @@ export async function searchBm25(
437
464
  }
438
465
  seenUriSeq.add(uriSeqKey);
439
466
 
440
- // Get chunk via O(1) lookup
441
- const rawChunk = fts.mirrorHash
442
- ? (getChunk(fts.mirrorHash, fts.seq) ?? null)
443
- : null;
467
+ // Get chunk via O(1) lookup (skipped when deferring default-mode chunks)
468
+ const rawChunk =
469
+ !deferDefaultChunks && fts.mirrorHash
470
+ ? (getChunk(fts.mirrorHash, fts.seq) ?? null)
471
+ : null;
444
472
  const chunk =
445
473
  options.intent && fts.mirrorHash
446
474
  ? (selectBestChunkForSteering(
447
- chunksMapResult.ok
475
+ chunksMapResult?.ok
448
476
  ? (chunksMapResult.value.get(fts.mirrorHash) ?? [])
449
477
  : [],
450
478
  query,
@@ -452,23 +480,29 @@ export async function searchBm25(
452
480
  {
453
481
  preferredSeq: rawChunk?.seq ?? fts.seq,
454
482
  intentWeight: 0.3,
483
+ queryTerms,
484
+ intentTerms,
455
485
  }
456
486
  ) ?? rawChunk)
457
487
  : rawChunk;
458
488
 
459
- const excluded =
460
- matchesExcludedText(
461
- [fts.title ?? "", fts.recordSourcePath ?? fts.relPath ?? ""],
462
- options.exclude
463
- ) ||
464
- matchesExcludedChunks(
465
- chunksMapResult.ok && fts.mirrorHash
466
- ? (chunksMapResult.value.get(fts.mirrorHash) ?? [])
467
- : [],
468
- options.exclude
469
- );
470
- if (excluded) {
471
- continue;
489
+ if (excludeTermsLower) {
490
+ const excluded =
491
+ matchesExcludedText(
492
+ [fts.title ?? "", fts.recordSourcePath ?? fts.relPath ?? ""],
493
+ excludeTermsLower,
494
+ true
495
+ ) ||
496
+ matchesExcludedChunks(
497
+ chunksMapResult?.ok && fts.mirrorHash
498
+ ? (chunksMapResult.value.get(fts.mirrorHash) ?? [])
499
+ : [],
500
+ excludeTermsLower,
501
+ true
502
+ );
503
+ if (excluded) {
504
+ continue;
505
+ }
472
506
  }
473
507
 
474
508
  // For --full, de-dupe by docid (keep best scoring chunk per doc)
@@ -489,7 +523,15 @@ export async function searchBm25(
489
523
  const collectionPath = fts.collection
490
524
  ? collectionPaths.get(fts.collection)
491
525
  : undefined;
492
- const result = buildSearchResult({ fts, chunk, collectionPath, options });
526
+ const result = buildSearchResult({
527
+ fts,
528
+ chunk,
529
+ collectionPath,
530
+ options,
531
+ deferPassageHash: true,
532
+ });
533
+ if (chunk) deferredChunkByResult.set(result, chunk);
534
+ if (deferDefaultChunks) deferredFtsByResult.set(result, fts);
493
535
  if (fts.collection) {
494
536
  scoringByResult.set(result, {
495
537
  collection: fts.collection,
@@ -500,27 +542,14 @@ export async function searchBm25(
500
542
  results.push(result);
501
543
  }
502
544
 
503
- // For --full, fetch full content and build results
545
+ // For --full, defer full content fetch until after filtering, sorting, and slicing to `limit`
504
546
  if (options.full) {
505
547
  // Sort by raw BM25 score (smaller = better) before building results
506
548
  const sortedEntries = (
507
549
  auxiliaryRankingActive ? fullAffinityEntries : [...bestByDocid.values()]
508
550
  ).sort((a, b) => a.score - b.score);
509
- const fullContentResult = await getContentBatch(
510
- store,
511
- sortedEntries
512
- .map(({ fts }) => fts.mirrorHash)
513
- .filter((mirrorHash): mirrorHash is string => Boolean(mirrorHash))
514
- );
515
- if (!fullContentResult.ok) {
516
- return err("QUERY_FAILED", fullContentResult.error.message);
517
- }
518
- const fullContentByHash = fullContentResult.value;
519
551
 
520
552
  for (const { fts, chunk } of sortedEntries) {
521
- const fullContent = fts.mirrorHash
522
- ? fullContentByHash.get(fts.mirrorHash)
523
- : undefined;
524
553
  const collectionPath = fts.collection
525
554
  ? collectionPaths.get(fts.collection)
526
555
  : undefined;
@@ -529,8 +558,9 @@ export async function searchBm25(
529
558
  chunk,
530
559
  collectionPath,
531
560
  options,
532
- fullContent,
561
+ deferPassageHash: true,
533
562
  });
563
+ if (chunk) deferredChunkByResult.set(result, chunk);
534
564
  if (fts.collection) {
535
565
  scoringByResult.set(result, {
536
566
  collection: fts.collection,
@@ -573,15 +603,16 @@ export async function searchBm25(
573
603
  : dedupedResults;
574
604
 
575
605
  if (recencySort) {
576
- filteredResults.sort((a, b) => {
577
- const aTs = resolveRecencyTimestamp(
578
- a.source.documentDate,
579
- a.source.modifiedAt
580
- );
581
- const bTs = resolveRecencyTimestamp(
582
- b.source.documentDate,
583
- b.source.modifiedAt
606
+ const recencyTs = new Map<SearchResult, number>();
607
+ for (const r of filteredResults) {
608
+ recencyTs.set(
609
+ r,
610
+ resolveRecencyTimestamp(r.source.documentDate, r.source.modifiedAt)
584
611
  );
612
+ }
613
+ filteredResults.sort((a, b) => {
614
+ const aTs = recencyTs.get(a) ?? 0;
615
+ const bTs = recencyTs.get(b) ?? 0;
585
616
  if (aTs !== bTs) {
586
617
  return bTs - aTs;
587
618
  }
@@ -592,20 +623,110 @@ export async function searchBm25(
592
623
  }
593
624
 
594
625
  const finalResults = filteredResults.slice(0, limit);
595
- if (!(options.full || options.lineNumbers)) {
626
+ if (options.full && finalResults.length > 0) {
627
+ const fullHashes = [
628
+ ...new Set(
629
+ finalResults
630
+ .map((r) => r.conversion?.mirrorHash)
631
+ .filter((mirrorHash): mirrorHash is string => Boolean(mirrorHash))
632
+ ),
633
+ ];
634
+ if (fullHashes.length > 0) {
635
+ const fullContentResult = await getContentBatch(store, fullHashes);
636
+ if (!fullContentResult.ok) {
637
+ return err("QUERY_FAILED", fullContentResult.error.message);
638
+ }
639
+ for (const result of finalResults) {
640
+ const hash = result.conversion?.mirrorHash;
641
+ const fullContent = hash
642
+ ? fullContentResult.value.get(hash)
643
+ : undefined;
644
+ if (fullContent) {
645
+ result.snippet = fullContent;
646
+ result.snippetRange = undefined;
647
+ const originalChunk = deferredChunkByResult.get(result);
648
+ if (originalChunk) {
649
+ result.line = originalChunk.startLine;
650
+ }
651
+ }
652
+ }
653
+ }
654
+ } else if (!(options.full || options.lineNumbers)) {
596
655
  await attachChunkSnippets(store, finalResults, query, options, allChunks);
656
+ if (deferDefaultChunks) {
657
+ const missingFallback: Array<{ result: SearchResult; fts: FtsResult }> =
658
+ [];
659
+ for (const result of finalResults) {
660
+ if (result[SEARCH_RESULT_PLANNER_METADATA]) continue;
661
+ const fts = deferredFtsByResult.get(result);
662
+ if (fts?.mirrorHash) {
663
+ missingFallback.push({ result, fts });
664
+ }
665
+ }
666
+ if (missingFallback.length > 0) {
667
+ const fallbackHashes = [
668
+ ...new Set(missingFallback.map(({ fts }) => fts.mirrorHash!)),
669
+ ];
670
+ const fallbackRes = store.getChunksBySequenceBatch
671
+ ? await store.getChunksBySequenceBatch(
672
+ missingFallback.map(({ fts }) => ({
673
+ mirrorHash: fts.mirrorHash!,
674
+ seq: fts.seq,
675
+ }))
676
+ )
677
+ : await store.getChunksBatch(fallbackHashes);
678
+ if (fallbackRes.ok) {
679
+ const getFallbackChunk = createChunkLookup(fallbackRes.value);
680
+ for (const { result, fts } of missingFallback) {
681
+ const chunk = getFallbackChunk(fts.mirrorHash!, fts.seq);
682
+ if (!chunk) continue;
683
+ const cleaned = cleanDisplaySnippet(chunk.text, chunk.text);
684
+ result.snippet = cleaned.text;
685
+ result.line = chunk.startLine + cleaned.startLineOffset;
686
+ result.snippetLanguage = chunk.language ?? undefined;
687
+ result.snippetRange = {
688
+ startLine: result.line,
689
+ endLine: chunk.endLine,
690
+ };
691
+ attachSearchResultPlannerMetadata(result, {
692
+ retrievalRank: 0,
693
+ mirrorHash: fts.mirrorHash!,
694
+ seq: chunk.seq,
695
+ sources: ["bm25"],
696
+ graphExpanded: false,
697
+ startLine: chunk.startLine,
698
+ endLine: chunk.endLine,
699
+ passageHash: passageHash(chunk.text),
700
+ });
701
+ }
702
+ }
703
+ }
704
+ }
597
705
  }
598
706
  for (const [index, result] of finalResults.entries()) {
599
707
  const metadata = result[SEARCH_RESULT_PLANNER_METADATA];
600
- if (metadata) metadata.retrievalRank = index + 1;
708
+ if (metadata) {
709
+ metadata.retrievalRank = index + 1;
710
+ if (!metadata.passageHash) {
711
+ const chunk = deferredChunkByResult.get(result);
712
+ if (chunk) metadata.passageHash = passageHash(chunk.text);
713
+ }
714
+ }
601
715
  }
602
716
  await attachSearchResultContexts(store, finalResults);
603
717
  await attachSupersession(store, finalResults);
718
+ const finalHashes = [
719
+ ...new Set(
720
+ finalResults
721
+ .map((r) => r.conversion?.mirrorHash)
722
+ .filter((hash): hash is string => Boolean(hash))
723
+ ),
724
+ ];
604
725
  const lineageResult = await attachSearchResultEgressLineage(
605
726
  store,
606
727
  finalResults,
607
728
  {
608
- ownershipHashes: uniqueHashes,
729
+ ownershipHashes: finalHashes,
609
730
  collections: collectionsResult.ok ? collectionsResult.value : undefined,
610
731
  }
611
732
  );
@@ -65,7 +65,7 @@ export function cleanDisplaySnippet(
65
65
  const canFallback =
66
66
  chunkText !== undefined &&
67
67
  chunkText !== snippet &&
68
- isFrontmatterDominatedSnippet(snippet);
68
+ isFrontmatterDominatedSnippetInner(snippet, true);
69
69
  if (canFallback) {
70
70
  const cleanedChunk = stripLeadingFrontmatterBlock(chunkText);
71
71
  if (cleanedChunk.text.length > 0) {
@@ -86,6 +86,13 @@ export function cleanDisplaySnippet(
86
86
 
87
87
  /** True for FTS-style snippets that are only (or start as) YAML frontmatter. */
88
88
  export function isFrontmatterDominatedSnippet(text: string): boolean {
89
+ return isFrontmatterDominatedSnippetInner(text, false);
90
+ }
91
+
92
+ function isFrontmatterDominatedSnippetInner(
93
+ text: string,
94
+ skipEmbeddedFenceCheck: boolean
95
+ ): boolean {
89
96
  const unmarked = text.replace(MARK_TAG_REGEX, "");
90
97
  const trimmed = unmarked.trimStart();
91
98
  const withoutLeadingEllipsis = trimmed.startsWith("...")
@@ -105,7 +112,10 @@ export function isFrontmatterDominatedSnippet(text: string): boolean {
105
112
  if (contentLines.every(isYamlFrontmatterLine)) {
106
113
  return true;
107
114
  }
108
- return proseAfterEmbeddedFrontmatterFence(text) !== undefined;
115
+ return (
116
+ !skipEmbeddedFenceCheck &&
117
+ proseAfterEmbeddedFrontmatterFence(text) !== undefined
118
+ );
109
119
  }
110
120
 
111
121
  /**
@@ -113,6 +123,9 @@ export function isFrontmatterDominatedSnippet(text: string): boolean {
113
123
  * Keep the prose after that fence when the prefix looks like YAML.
114
124
  */
115
125
  function proseAfterEmbeddedFrontmatterFence(text: string): string | undefined {
126
+ if (!text.includes("-")) {
127
+ return undefined;
128
+ }
116
129
  const lines = text.split(/\r?\n/);
117
130
  for (let i = 1; i < lines.length; i++) {
118
131
  const line = lines[i];
@@ -11,6 +11,8 @@ const RECENCY_SORT_RE =
11
11
  export interface TemporalRange {
12
12
  since?: string;
13
13
  until?: string;
14
+ sinceMs?: number;
15
+ untilMs?: number;
14
16
  }
15
17
 
16
18
  type BoundKind = "since" | "until";
@@ -197,6 +199,31 @@ export function resolveTemporalRange(
197
199
  return inferFromQuery(query, now);
198
200
  }
199
201
 
202
+ /** Pre-parse temporal range ISO bounds once per query to avoid per-doc Date parsing. */
203
+ export function compileTemporalRange(range: TemporalRange): TemporalRange {
204
+ if (!range.since && !range.until) return range;
205
+ const sinceMs =
206
+ range.sinceMs !== undefined
207
+ ? range.sinceMs
208
+ : range.since
209
+ ? new Date(range.since).getTime()
210
+ : undefined;
211
+ const untilMs =
212
+ range.untilMs !== undefined
213
+ ? range.untilMs
214
+ : range.until
215
+ ? new Date(range.until).getTime()
216
+ : undefined;
217
+ return {
218
+ since: range.since,
219
+ until: range.until,
220
+ sinceMs:
221
+ sinceMs !== undefined && !Number.isNaN(sinceMs) ? sinceMs : undefined,
222
+ untilMs:
223
+ untilMs !== undefined && !Number.isNaN(untilMs) ? untilMs : undefined,
224
+ };
225
+ }
226
+
200
227
  /**
201
228
  * Return true when timestamp falls inside optional range.
202
229
  */
@@ -204,6 +231,14 @@ export function isWithinTemporalRange(
204
231
  timestamp: string | undefined,
205
232
  range: TemporalRange
206
233
  ): boolean {
234
+ if (
235
+ !range.since &&
236
+ !range.until &&
237
+ range.sinceMs === undefined &&
238
+ range.untilMs === undefined
239
+ ) {
240
+ return true;
241
+ }
207
242
  if (!timestamp) {
208
243
  return true;
209
244
  }
@@ -211,17 +246,23 @@ export function isWithinTemporalRange(
211
246
  if (Number.isNaN(t)) {
212
247
  return true;
213
248
  }
214
- if (range.since) {
215
- const since = new Date(range.since).getTime();
216
- if (!Number.isNaN(since) && t < since) {
217
- return false;
218
- }
249
+ const since =
250
+ range.sinceMs !== undefined
251
+ ? range.sinceMs
252
+ : range.since
253
+ ? new Date(range.since).getTime()
254
+ : Number.NaN;
255
+ if (!Number.isNaN(since) && t < since) {
256
+ return false;
219
257
  }
220
- if (range.until) {
221
- const until = new Date(range.until).getTime();
222
- if (!Number.isNaN(until) && t > until) {
223
- return false;
224
- }
258
+ const until =
259
+ range.untilMs !== undefined
260
+ ? range.untilMs
261
+ : range.until
262
+ ? new Date(range.until).getTime()
263
+ : Number.NaN;
264
+ if (!Number.isNaN(until) && t > until) {
265
+ return false;
225
266
  }
226
267
  return true;
227
268
  }