@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
@@ -4,7 +4,7 @@
4
4
  * @module src/pipeline/filters
5
5
  */
6
6
 
7
- import type { ChunkRow, DocumentRow, StorePort } from "../store/types";
7
+ import type { ChunkRow, DocumentRow, StorePort, TagRow } from "../store/types";
8
8
  import type { HybridSearchOptions } from "./types";
9
9
 
10
10
  import {
@@ -12,14 +12,84 @@ import {
12
12
  TYPED_METADATA_INGEST_VERSION,
13
13
  type MetadataPredicate,
14
14
  } from "../core/typed-metadata";
15
- import { matchesExcludedChunks, matchesExcludedText } from "./exclude";
16
- import { isWithinTemporalRange, resolveTemporalRange } from "./temporal";
15
+ import {
16
+ compileExcludeTerms,
17
+ matchesExcludedChunks,
18
+ matchesExcludedText,
19
+ } from "./exclude";
20
+ import {
21
+ compileTemporalRange,
22
+ isWithinTemporalRange,
23
+ resolveTemporalRange,
24
+ type TemporalRange,
25
+ } from "./temporal";
17
26
 
18
27
  export interface QueryFilterEvaluation {
19
28
  matches: boolean;
20
29
  reasons: string[];
21
30
  }
22
31
 
32
+ export interface CompiledDocumentFilters {
33
+ temporalRange: TemporalRange;
34
+ authorLower?: string;
35
+ allowedCategories?: Set<string>;
36
+ excludeTermsLower?: string[];
37
+ collection?: string;
38
+ collectionsSet?: Set<string>;
39
+ allowedMirrorHashSet?: Set<string>;
40
+ callerCollection?: string;
41
+ callerCollectionsSet?: Set<string>;
42
+ callerAllowedMirrorHashSet?: Set<string>;
43
+ }
44
+
45
+ /** Pre-compile query-invariant filter sets and bounds once per search. */
46
+ export function compileDocumentFilters(
47
+ query: string,
48
+ options: Pick<
49
+ HybridSearchOptions,
50
+ | "since"
51
+ | "until"
52
+ | "author"
53
+ | "categories"
54
+ | "exclude"
55
+ | "collection"
56
+ | "collections"
57
+ | "retrievalScope"
58
+ >,
59
+ callerScope?: Pick<
60
+ HybridSearchOptions,
61
+ "collection" | "collections" | "retrievalScope"
62
+ >,
63
+ preResolvedTemporal?: TemporalRange
64
+ ): CompiledDocumentFilters {
65
+ const temporalRange = compileTemporalRange(
66
+ preResolvedTemporal ??
67
+ resolveTemporalRange(query, options.since, options.until)
68
+ );
69
+ return {
70
+ temporalRange,
71
+ authorLower: options.author ? options.author.toLowerCase() : undefined,
72
+ allowedCategories: options.categories?.length
73
+ ? new Set(options.categories.map((c) => c.toLowerCase()))
74
+ : undefined,
75
+ excludeTermsLower: compileExcludeTerms(options.exclude),
76
+ collection: options.collection,
77
+ collectionsSet: options.collections
78
+ ? new Set(options.collections)
79
+ : undefined,
80
+ allowedMirrorHashSet: options.retrievalScope
81
+ ? new Set(options.retrievalScope.allowedMirrorHashes)
82
+ : undefined,
83
+ callerCollection: callerScope?.collection,
84
+ callerCollectionsSet: callerScope?.collections
85
+ ? new Set(callerScope.collections)
86
+ : undefined,
87
+ callerAllowedMirrorHashSet: callerScope?.retrievalScope
88
+ ? new Set(callerScope.retrievalScope.allowedMirrorHashes)
89
+ : undefined,
90
+ };
91
+ }
92
+
23
93
  /** Internal pre-budget contract. Undefined metadata is a failed lookup, never
24
94
  * an unrestricted candidate. Owners must be evaluated separately; this does
25
95
  * not replace complete ownership lineage or change ranking/deduplication.
@@ -28,9 +98,11 @@ export interface QueryFilterEvaluation {
28
98
  /** True when `collection` falls outside the request's collection scope. */
29
99
  function outsideCollectionScope(
30
100
  scope: Pick<HybridSearchOptions, "collection" | "collections">,
31
- collection: string
101
+ collection: string,
102
+ collectionsSet?: Set<string>
32
103
  ): boolean {
33
104
  if (scope.collection && collection !== scope.collection) return true;
105
+ if (collectionsSet !== undefined) return !collectionsSet.has(collection);
34
106
  return (
35
107
  scope.collections !== undefined && !scope.collections.includes(collection)
36
108
  );
@@ -45,7 +117,9 @@ export async function evaluateRetrievalEligibility(
45
117
  callerScope?: Pick<
46
118
  HybridSearchOptions,
47
119
  "collection" | "collections" | "retrievalScope"
48
- >
120
+ >,
121
+ compiled?: CompiledDocumentFilters,
122
+ prefetchedTags?: ReadonlyMap<number, TagRow[]> | null
49
123
  ): Promise<QueryFilterEvaluation & { chunks: ChunkRow[] }> {
50
124
  if (!doc || !chunks || !doc.mirrorHash) {
51
125
  return { matches: false, reasons: ["metadata"], chunks: [] };
@@ -53,12 +127,39 @@ export async function evaluateRetrievalEligibility(
53
127
  const reasons: string[] = [];
54
128
  if (!doc.active) reasons.push("inactive");
55
129
  const sourcePath = doc.recordSourcePath ?? doc.relPath;
56
- for (const scope of [callerScope, options]) {
57
- if (scope && outsideCollectionScope(scope, doc.collection)) {
130
+ const scopeEntries: Array<{
131
+ scope:
132
+ | Pick<
133
+ HybridSearchOptions,
134
+ "collection" | "collections" | "retrievalScope"
135
+ >
136
+ | undefined;
137
+ collectionsSet?: Set<string>;
138
+ allowedMirrorHashSet?: Set<string>;
139
+ }> = [
140
+ {
141
+ scope: callerScope,
142
+ collectionsSet: compiled?.callerCollectionsSet,
143
+ allowedMirrorHashSet: compiled?.callerAllowedMirrorHashSet,
144
+ },
145
+ {
146
+ scope: options,
147
+ collectionsSet: compiled?.collectionsSet,
148
+ allowedMirrorHashSet: compiled?.allowedMirrorHashSet,
149
+ },
150
+ ];
151
+ for (const { scope, collectionsSet, allowedMirrorHashSet } of scopeEntries) {
152
+ if (
153
+ scope &&
154
+ outsideCollectionScope(scope, doc.collection, collectionsSet)
155
+ ) {
58
156
  reasons.push("collection");
59
157
  }
60
158
  if (scope?.retrievalScope) {
61
- if (!scope.retrievalScope.allowedMirrorHashes.includes(doc.mirrorHash)) {
159
+ const allowed = allowedMirrorHashSet
160
+ ? allowedMirrorHashSet.has(doc.mirrorHash)
161
+ : scope.retrievalScope.allowedMirrorHashes.includes(doc.mirrorHash);
162
+ if (!allowed) {
62
163
  reasons.push("scope");
63
164
  }
64
165
  const prefix = scope.retrievalScope.relPathPrefix;
@@ -80,7 +181,15 @@ export async function evaluateRetrievalEligibility(
80
181
  try {
81
182
  reasons.push(
82
183
  ...(
83
- await evaluateQueryTargetFilters(store, query, doc, chunks, options)
184
+ await evaluateQueryTargetFilters(
185
+ store,
186
+ query,
187
+ doc,
188
+ chunks,
189
+ options,
190
+ compiled,
191
+ prefetchedTags
192
+ )
84
193
  ).reasons
85
194
  );
86
195
  } catch {
@@ -101,36 +210,43 @@ export function evaluateDocumentChunkFilters(
101
210
  query: string,
102
211
  doc: DocumentRow,
103
212
  chunks: ChunkRow[],
104
- options: HybridSearchOptions
213
+ options: HybridSearchOptions,
214
+ compiled?: CompiledDocumentFilters
105
215
  ): QueryFilterEvaluation {
106
216
  const reasons: string[] = [];
107
217
  const metadataReason = typedMetadataFilterReason(doc, options.filter);
108
218
  if (metadataReason) reasons.push(metadataReason);
109
- const temporalRange = resolveTemporalRange(
110
- query,
111
- options.since,
112
- options.until
113
- );
219
+ const temporalRange =
220
+ compiled?.temporalRange ??
221
+ resolveTemporalRange(query, options.since, options.until);
114
222
 
115
- if (outsideCollectionScope(options, doc.collection)) {
223
+ if (
224
+ outsideCollectionScope(options, doc.collection, compiled?.collectionsSet)
225
+ ) {
116
226
  reasons.push("collection");
117
227
  }
118
228
  if (!isWithinTemporalRange(doc.sourceMtime, temporalRange)) {
119
229
  reasons.push("date");
120
230
  }
121
- if (
122
- options.author &&
123
- !doc.author?.toLowerCase().includes(options.author.toLowerCase())
124
- ) {
231
+ const authorLower =
232
+ compiled !== undefined
233
+ ? compiled.authorLower
234
+ : options.author?.toLowerCase();
235
+ if (authorLower && !doc.author?.toLowerCase().includes(authorLower)) {
125
236
  reasons.push("author");
126
237
  }
127
- if (options.categories?.length) {
128
- const allowed = new Set(options.categories.map((c) => c.toLowerCase()));
238
+ const allowedCategories =
239
+ compiled !== undefined
240
+ ? compiled.allowedCategories
241
+ : options.categories?.length
242
+ ? new Set(options.categories.map((c) => c.toLowerCase()))
243
+ : undefined;
244
+ if (allowedCategories) {
129
245
  const contentTypeMatch = doc.contentType
130
- ? allowed.has(doc.contentType.toLowerCase())
246
+ ? allowedCategories.has(doc.contentType.toLowerCase())
131
247
  : false;
132
248
  const categoryMatch = (doc.categories ?? []).some((c) =>
133
- allowed.has(c.toLowerCase())
249
+ allowedCategories.has(c.toLowerCase())
134
250
  );
135
251
  if (!contentTypeMatch && !categoryMatch) {
136
252
  reasons.push("category");
@@ -142,8 +258,12 @@ export function evaluateDocumentChunkFilters(
142
258
  ) {
143
259
  reasons.push("lang");
144
260
  }
261
+ const excludeTerms =
262
+ compiled !== undefined ? compiled.excludeTermsLower : options.exclude;
263
+ const preLowercased = compiled !== undefined;
145
264
  if (
146
- matchesExcludedText(
265
+ excludeTerms?.length &&
266
+ (matchesExcludedText(
147
267
  [
148
268
  doc.title ?? "",
149
269
  doc.recordSourcePath ?? doc.relPath,
@@ -151,9 +271,10 @@ export function evaluateDocumentChunkFilters(
151
271
  doc.contentType ?? "",
152
272
  ...(doc.categories ?? []),
153
273
  ],
154
- options.exclude
274
+ excludeTerms,
275
+ preLowercased
155
276
  ) ||
156
- matchesExcludedChunks(chunks, options.exclude)
277
+ matchesExcludedChunks(chunks, excludeTerms, preLowercased))
157
278
  ) {
158
279
  reasons.push("exclude");
159
280
  }
@@ -169,18 +290,33 @@ export async function evaluateQueryTargetFilters(
169
290
  query: string,
170
291
  doc: DocumentRow,
171
292
  chunks: ChunkRow[],
172
- options: HybridSearchOptions
293
+ options: HybridSearchOptions,
294
+ compiled?: CompiledDocumentFilters,
295
+ prefetchedTags?: ReadonlyMap<number, TagRow[]> | null
173
296
  ): Promise<QueryFilterEvaluation> {
174
297
  const reasons = [
175
- ...evaluateDocumentChunkFilters(query, doc, chunks, options).reasons,
298
+ ...evaluateDocumentChunkFilters(query, doc, chunks, options, compiled)
299
+ .reasons,
176
300
  ];
177
301
 
178
302
  if (options.tagsAll?.length || options.tagsAny?.length) {
179
- const tagsResult = await store.getTagsForDoc(doc.id);
180
- if (!tagsResult.ok) {
181
- reasons.push("tags");
303
+ let docTagRows: TagRow[] | null = null;
304
+ if (prefetchedTags !== undefined) {
305
+ if (prefetchedTags === null) {
306
+ reasons.push("tags");
307
+ } else {
308
+ docTagRows = prefetchedTags.get(doc.id) ?? [];
309
+ }
182
310
  } else {
183
- const docTags = new Set(tagsResult.value.map((tag) => tag.tag));
311
+ const tagsResult = await store.getTagsForDoc(doc.id);
312
+ if (!tagsResult.ok) {
313
+ reasons.push("tags");
314
+ } else {
315
+ docTagRows = tagsResult.value;
316
+ }
317
+ }
318
+ if (docTagRows !== null) {
319
+ const docTags = new Set(docTagRows.map((tag) => tag.tag));
184
320
  if (
185
321
  options.tagsAll?.length &&
186
322
  !options.tagsAll.every((tag) => docTags.has(tag))
@@ -16,7 +16,11 @@ import type {
16
16
  import type { FusionCandidate } from "./types";
17
17
 
18
18
  import { typedMetadataFilterReason } from "./filters";
19
- import { isWithinTemporalRange } from "./temporal";
19
+ import {
20
+ compileTemporalRange,
21
+ isWithinTemporalRange,
22
+ type TemporalRange,
23
+ } from "./temporal";
20
24
 
21
25
  export interface GraphRetrievalMeta {
22
26
  attempted: boolean;
@@ -61,39 +65,33 @@ const confidenceWeight = (confidence: GraphEdgeConfidence): number => {
61
65
  }
62
66
  };
63
67
 
68
+ interface CompiledNeighborFilters {
69
+ temporalRange: TemporalRange;
70
+ authorLower?: string;
71
+ allowedCategories?: Set<string>;
72
+ filter?: MetadataPredicate;
73
+ }
74
+
64
75
  const matchesDocumentFilters = (
65
76
  doc: DocumentRow,
66
- options: {
67
- since?: string;
68
- until?: string;
69
- categories?: string[];
70
- author?: string;
71
- filter?: MetadataPredicate;
72
- relPathPrefix?: string;
73
- }
77
+ compiled: CompiledNeighborFilters
74
78
  ): boolean => {
75
- if (typedMetadataFilterReason(doc, options.filter)) return false;
76
- if (
77
- !isWithinTemporalRange(doc.sourceMtime, {
78
- since: options.since,
79
- until: options.until,
80
- })
81
- ) {
79
+ if (typedMetadataFilterReason(doc, compiled.filter)) return false;
80
+ if (!isWithinTemporalRange(doc.sourceMtime, compiled.temporalRange)) {
82
81
  return false;
83
82
  }
84
83
  if (
85
- options.author &&
86
- !doc.author?.toLowerCase().includes(options.author.toLowerCase())
84
+ compiled.authorLower &&
85
+ !doc.author?.toLowerCase().includes(compiled.authorLower)
87
86
  ) {
88
87
  return false;
89
88
  }
90
- if (options.categories?.length) {
91
- const allowed = new Set(options.categories.map((c) => c.toLowerCase()));
89
+ if (compiled.allowedCategories) {
92
90
  const contentTypeMatch = doc.contentType
93
- ? allowed.has(doc.contentType.toLowerCase())
91
+ ? compiled.allowedCategories.has(doc.contentType.toLowerCase())
94
92
  : false;
95
93
  const categoryMatch = (doc.categories ?? []).some((c) =>
96
- allowed.has(c.toLowerCase())
94
+ compiled.allowedCategories!.has(c.toLowerCase())
97
95
  );
98
96
  if (!contentTypeMatch && !categoryMatch) {
99
97
  return false;
@@ -416,50 +414,112 @@ export async function expandGraphCandidates(
416
414
 
417
415
  // A plural allowlist hydrates across its collections; scope is enforced on
418
416
  // each neighbour's own collection below, never widened past the allowlist.
417
+ // Paginate ranked neighbours in chunks of maxCandidates * 3 so high-degree
418
+ // graphs stop hydrating as soon as maxCandidates survive filters.
419
419
  const plural = options.collections !== undefined;
420
- const docsResult = await store.getDocumentsByDocids(rankedNeighborDocids, {
421
- eligibility:
422
- plural && options.eligibility
423
- ? { ...options.eligibility, collection: undefined }
424
- : options.eligibility,
425
- collection: plural ? undefined : options.collection,
426
- activeOnly: true,
427
- });
428
- if (!docsResult.ok) {
429
- meta.fallbackReasons.push("graph_neighbor_lookup_failed");
430
- return { candidates: [], meta };
420
+ const docEligibility =
421
+ plural && options.eligibility
422
+ ? { ...options.eligibility, collection: undefined }
423
+ : options.eligibility;
424
+ const docCollection = plural ? undefined : options.collection;
425
+ const compiledFilters: CompiledNeighborFilters = {
426
+ temporalRange: compileTemporalRange({
427
+ since: options.since,
428
+ until: options.until,
429
+ }),
430
+ authorLower: options.author ? options.author.toLowerCase() : undefined,
431
+ allowedCategories: options.categories?.length
432
+ ? new Set(options.categories.map((c) => c.toLowerCase()))
433
+ : undefined,
434
+ filter: options.filter,
435
+ };
436
+ const pageSize = Math.max(maxCandidates * 3, 1);
437
+ const rankedDocs: DocumentRow[] = [];
438
+ for (
439
+ let offset = 0;
440
+ offset < rankedNeighborDocids.length && rankedDocs.length < maxCandidates;
441
+ offset += pageSize
442
+ ) {
443
+ const pageDocids = rankedNeighborDocids.slice(offset, offset + pageSize);
444
+ const docsResult = await store.getDocumentsByDocids(pageDocids, {
445
+ eligibility: docEligibility,
446
+ collection: docCollection,
447
+ activeOnly: true,
448
+ });
449
+ if (!docsResult.ok) {
450
+ meta.fallbackReasons.push("graph_neighbor_lookup_failed");
451
+ return { candidates: [], meta };
452
+ }
453
+ const metadataFilteredDocs = docsResult.value.filter(
454
+ (doc) =>
455
+ doc.mirrorHash &&
456
+ (!graphAllowlist || graphAllowlist.has(doc.collection)) &&
457
+ (options.relPathPrefix === undefined ||
458
+ sourceRelPath(doc) === options.relPathPrefix ||
459
+ sourceRelPath(doc).startsWith(`${options.relPathPrefix}/`)) &&
460
+ matchesDocumentFilters(doc, compiledFilters)
461
+ );
462
+ const docs = await filterDocsByTags(store, metadataFilteredDocs, options);
463
+ const docByDocid = new Map(docs.map((doc) => [doc.docid, doc]));
464
+ for (const docid of pageDocids) {
465
+ const doc = docByDocid.get(docid);
466
+ if (doc?.mirrorHash) {
467
+ rankedDocs.push(doc);
468
+ if (rankedDocs.length >= maxCandidates) break;
469
+ }
470
+ }
431
471
  }
432
472
 
433
- const metadataFilteredDocs = docsResult.value.filter(
434
- (doc) =>
435
- doc.mirrorHash &&
436
- (!graphAllowlist || graphAllowlist.has(doc.collection)) &&
437
- (options.relPathPrefix === undefined ||
438
- sourceRelPath(doc) === options.relPathPrefix ||
439
- sourceRelPath(doc).startsWith(`${options.relPathPrefix}/`)) &&
440
- matchesDocumentFilters(doc, options)
441
- );
442
- const docs = await filterDocsByTags(store, metadataFilteredDocs, options);
443
- const docByDocid = new Map(docs.map((doc) => [doc.docid, doc]));
444
- const rankedDocs = rankedNeighborDocids
445
- .map((docid) => docByDocid.get(docid))
446
- .filter((doc): doc is DocumentRow => Boolean(doc?.mirrorHash))
447
- .slice(0, maxCandidates);
448
- const hashes = rankedDocs
449
- .map((doc) => doc.mirrorHash)
450
- .filter((hash): hash is string => Boolean(hash));
451
- const chunksResult = await hydration.getChunksBatch(hashes);
452
- if (!chunksResult.ok) {
453
- meta.fallbackReasons.push("graph_neighbor_chunks_failed");
454
- return { candidates: [], meta };
473
+ const hashes = [
474
+ ...new Set(
475
+ rankedDocs
476
+ .map((doc) => doc.mirrorHash)
477
+ .filter((hash): hash is string => Boolean(hash))
478
+ ),
479
+ ];
480
+ let chunksMap: Map<string, ChunkRow[]>;
481
+ if (!options.lang && typeof store.getChunksBySequenceBatch === "function") {
482
+ const seqRequests = hashes.map((mirrorHash) => ({
483
+ mirrorHash,
484
+ seq: preferredSeqByHash.get(mirrorHash) ?? 0,
485
+ }));
486
+ const seqResult = await store.getChunksBySequenceBatch(seqRequests);
487
+ if (!seqResult.ok) {
488
+ meta.fallbackReasons.push("graph_neighbor_chunks_failed");
489
+ return { candidates: [], meta };
490
+ }
491
+ chunksMap = new Map(seqResult.value);
492
+ const missingHashes = hashes.filter(
493
+ (hash) => (chunksMap.get(hash)?.length ?? 0) === 0
494
+ );
495
+ if (missingHashes.length > 0) {
496
+ const fallbackResult = await hydration.getChunksBatch(missingHashes);
497
+ if (!fallbackResult.ok) {
498
+ meta.fallbackReasons.push("graph_neighbor_chunks_failed");
499
+ return { candidates: [], meta };
500
+ }
501
+ for (const [hash, rows] of fallbackResult.value) {
502
+ chunksMap.set(hash, rows);
503
+ }
504
+ }
505
+ } else {
506
+ const chunksResult = await hydration.getChunksBatch(hashes);
507
+ if (!chunksResult.ok) {
508
+ meta.fallbackReasons.push("graph_neighbor_chunks_failed");
509
+ return { candidates: [], meta };
510
+ }
511
+ chunksMap = chunksResult.value;
455
512
  }
456
513
 
514
+ const hasDocumentIds = fusedCandidates.some(
515
+ (candidate) => candidate.documentId !== undefined
516
+ );
457
517
  const candidates = rankedDocs
458
518
  .map((doc) => {
459
519
  const mirrorHash = doc.mirrorHash as string;
460
520
  const seq = chooseCandidateSeq(
461
521
  doc,
462
- chunksResult.value.get(mirrorHash) ?? [],
522
+ chunksMap.get(mirrorHash) ?? [],
463
523
  preferredSeqByHash,
464
524
  options.lang
465
525
  );
@@ -468,11 +528,7 @@ export async function expandGraphCandidates(
468
528
  : {
469
529
  mirrorHash,
470
530
  seq,
471
- ...(fusedCandidates.some(
472
- (candidate) => candidate.documentId !== undefined
473
- )
474
- ? { sourceDocid: doc.docid }
475
- : {}),
531
+ ...(hasDocumentIds ? { sourceDocid: doc.docid } : {}),
476
532
  };
477
533
  })
478
534
  .filter(