@gmickel/gno 2.15.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/SKILL.md +27 -0
  3. package/assets/skill/cli-reference.md +24 -15
  4. package/assets/spa-production.json.gz +0 -0
  5. package/browser-extension/artifacts/{gno-browser-clipper-v2.15.0.zip → gno-browser-clipper-v2.17.0.zip} +0 -0
  6. package/browser-extension/artifacts/gno-browser-clipper-v2.17.0.zip.sha256 +1 -0
  7. package/browser-extension/dist/manifest.json +1 -1
  8. package/package.json +1 -1
  9. package/spec/cli.md +43 -3
  10. package/spec/db/schema.sql +53 -1
  11. package/spec/mcp.md +9 -3
  12. package/spec/output-schemas/doctor.schema.json +27 -0
  13. package/spec/output-schemas/retrieval-trace-payloads.schema.json +14 -0
  14. package/spec/output-schemas/search-results.schema.json +14 -0
  15. package/spec/output-schemas/status.schema.json +22 -0
  16. package/src/cli/commands/agents/commands.ts +1 -1
  17. package/src/cli/commands/ask.ts +1 -1
  18. package/src/cli/commands/context-build.ts +1 -1
  19. package/src/cli/commands/doctor.ts +101 -29
  20. package/src/cli/commands/embed.ts +2 -2
  21. package/src/cli/commands/links.ts +30 -6
  22. package/src/cli/commands/mcp/install.ts +2 -2
  23. package/src/cli/commands/mcp/status.ts +1 -1
  24. package/src/cli/commands/mcp/uninstall.ts +1 -1
  25. package/src/cli/commands/query.ts +1 -1
  26. package/src/cli/commands/shared.ts +4 -4
  27. package/src/cli/commands/skill/install.ts +1 -1
  28. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  29. package/src/cli/commands/skill/uninstall.ts +1 -1
  30. package/src/cli/commands/status.ts +75 -58
  31. package/src/cli/commands/vec.ts +180 -8
  32. package/src/cli/config-cache.ts +86 -0
  33. package/src/cli/globals.ts +64 -0
  34. package/src/cli/program.ts +63 -36
  35. package/src/cli/run.ts +121 -67
  36. package/src/cli/runtime-health.ts +132 -122
  37. package/src/cli/session-binding.ts +11 -2
  38. package/src/config/saver.ts +8 -0
  39. package/src/config/types.ts +6 -0
  40. package/src/converters/adapters/browser-export/formats.ts +25 -15
  41. package/src/converters/adapters/email/adapter.ts +37 -53
  42. package/src/converters/adapters/email/html.ts +37 -20
  43. package/src/converters/adapters/email/mime.ts +71 -39
  44. package/src/converters/adapters/ical/adapter.ts +20 -12
  45. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  46. package/src/converters/adapters/shared/html-text.ts +55 -37
  47. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  48. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  49. package/src/converters/adapters/transcript/adapter.ts +12 -7
  50. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  51. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  52. package/src/converters/canonicalize.ts +17 -3
  53. package/src/converters/native/markdown.ts +24 -17
  54. package/src/converters/native/plaintext.ts +5 -6
  55. package/src/converters/registry.ts +130 -8
  56. package/src/core/activation-status.ts +4 -8
  57. package/src/core/change-diff.ts +38 -11
  58. package/src/core/context-compiler.ts +17 -18
  59. package/src/core/context-evidence.ts +116 -25
  60. package/src/core/context-verifier.ts +70 -31
  61. package/src/core/file-lock.ts +10 -2
  62. package/src/core/graph-analysis.ts +3 -3
  63. package/src/core/link-inventory-markdown.ts +2 -2
  64. package/src/core/links.ts +20 -87
  65. package/src/core/memory-fence.ts +16 -9
  66. package/src/core/memory-recall.ts +168 -34
  67. package/src/core/path-rules.ts +143 -0
  68. package/src/core/retrieval-trace-session.ts +3 -0
  69. package/src/core/retrieval-trace.ts +9 -0
  70. package/src/core/section-parse.ts +16 -6
  71. package/src/core/typed-metadata.ts +68 -0
  72. package/src/core/vector-partition-status.ts +13 -0
  73. package/src/core/wiki-link-syntax.ts +88 -0
  74. package/src/embed/backlog.ts +142 -60
  75. package/src/embed/retry.ts +39 -33
  76. package/src/embed/variant-backlog.ts +582 -116
  77. package/src/embed/variant-retry.ts +157 -48
  78. package/src/index.ts +3 -3
  79. package/src/ingestion/budget-error-codes.ts +13 -0
  80. package/src/ingestion/chunker.ts +60 -49
  81. package/src/ingestion/compiled-context.ts +4 -5
  82. package/src/ingestion/convert-file.ts +1 -1
  83. package/src/ingestion/document-metadata.ts +16 -9
  84. package/src/ingestion/excluded-ranges.ts +97 -0
  85. package/src/ingestion/file-processor.ts +122 -37
  86. package/src/ingestion/frontmatter.ts +35 -7
  87. package/src/ingestion/graph-reconciliation.ts +187 -51
  88. package/src/ingestion/language.ts +66 -61
  89. package/src/ingestion/position.ts +5 -5
  90. package/src/ingestion/prepare-file.ts +50 -29
  91. package/src/ingestion/record-adapter-canonical.ts +37 -26
  92. package/src/ingestion/record-adapter.ts +46 -26
  93. package/src/ingestion/record-container.ts +121 -53
  94. package/src/ingestion/record-path.ts +5 -2
  95. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  96. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  97. package/src/ingestion/source-availability/readers.ts +51 -0
  98. package/src/ingestion/strip.ts +39 -105
  99. package/src/ingestion/sync.ts +692 -386
  100. package/src/ingestion/typed-metadata.ts +10 -4
  101. package/src/ingestion/walker.ts +485 -158
  102. package/src/llm/cache.ts +128 -84
  103. package/src/llm/http-inference.ts +112 -35
  104. package/src/llm/http-policy.ts +101 -0
  105. package/src/llm/httpEmbedding.ts +8 -1
  106. package/src/llm/httpGeneration.ts +5 -1
  107. package/src/llm/httpRerank.ts +5 -1
  108. package/src/llm/inference-scope.ts +15 -2
  109. package/src/llm/lazy-ports.ts +33 -3
  110. package/src/llm/lockfile.ts +34 -7
  111. package/src/llm/model-cleanup.ts +24 -0
  112. package/src/llm/native-worker/client.ts +23 -12
  113. package/src/llm/native-worker/dispatcher.ts +19 -9
  114. package/src/llm/native-worker/embedding-identity.ts +42 -16
  115. package/src/llm/native-worker/entry.ts +2 -1
  116. package/src/llm/native-worker/owner.ts +1 -0
  117. package/src/llm/native-worker/ports.ts +86 -23
  118. package/src/llm/native-worker/protocol.ts +386 -55
  119. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  120. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  121. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  122. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  123. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  124. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  125. package/src/llm/types.ts +14 -0
  126. package/src/mcp/context.ts +342 -23
  127. package/src/mcp/http-transport.ts +21 -3
  128. package/src/mcp/tool-profile-types.ts +62 -0
  129. package/src/mcp/tool-profile.ts +32 -56
  130. package/src/mcp/tools/context.ts +5 -1
  131. package/src/mcp/tools/index.ts +269 -191
  132. package/src/mcp/tools/links.ts +14 -6
  133. package/src/mcp/tools/query.ts +60 -37
  134. package/src/mcp/tools/vsearch.ts +25 -14
  135. package/src/pipeline/answer.ts +133 -40
  136. package/src/pipeline/claim-verification.ts +293 -189
  137. package/src/pipeline/claim-verifier.ts +6 -7
  138. package/src/pipeline/egress-lineage.ts +37 -26
  139. package/src/pipeline/exclude.ts +34 -11
  140. package/src/pipeline/expansion.ts +233 -19
  141. package/src/pipeline/explain.ts +17 -2
  142. package/src/pipeline/filters.ts +169 -33
  143. package/src/pipeline/graph-retrieval.ts +117 -61
  144. package/src/pipeline/hybrid.ts +626 -330
  145. package/src/pipeline/hydration.ts +86 -24
  146. package/src/pipeline/intent.ts +15 -7
  147. package/src/pipeline/owner-fusion.ts +61 -19
  148. package/src/pipeline/query-language.ts +15 -2
  149. package/src/pipeline/rerank.ts +15 -22
  150. package/src/pipeline/search.ts +193 -72
  151. package/src/pipeline/snippet.ts +15 -2
  152. package/src/pipeline/temporal.ts +51 -10
  153. package/src/pipeline/types.ts +7 -0
  154. package/src/pipeline/vsearch.ts +269 -154
  155. package/src/publish/attachment-raster.ts +2 -16
  156. package/src/publish/encrypted-export.ts +15 -5
  157. package/src/serve/browse-tree.ts +50 -42
  158. package/src/serve/connectors.ts +2 -1
  159. package/src/serve/context.ts +13 -4
  160. package/src/serve/doc-events.ts +3 -0
  161. package/src/serve/public/app.tsx +49 -21
  162. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  163. package/src/serve/public/components/CaptureModal.tsx +14 -10
  164. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  165. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  166. package/src/serve/public/globals.built.css +1 -1
  167. package/src/serve/public/globals.css +19 -0
  168. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  169. package/src/serve/public/lib/metadata-filter.ts +234 -9
  170. package/src/serve/public/pages/Browse.tsx +61 -27
  171. package/src/serve/public/pages/DocView.tsx +44 -25
  172. package/src/serve/public/pages/GraphView.tsx +8 -3
  173. package/src/serve/resident-runtime.ts +199 -48
  174. package/src/serve/routes/api.ts +98 -67
  175. package/src/serve/routes/links.ts +25 -5
  176. package/src/serve/server.ts +1370 -1180
  177. package/src/serve/spa-bundle-source.ts +52 -27
  178. package/src/serve/status.ts +101 -52
  179. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  180. package/src/serve/watch-reconciliation-shared.ts +42 -4
  181. package/src/serve/watch-reconciliation.ts +21 -8
  182. package/src/serve/watch-service-events.ts +7 -1
  183. package/src/serve/watch-service-hosts.ts +3 -1
  184. package/src/serve/watch-service.ts +46 -21
  185. package/src/serve/watch-snapshot-scan.ts +6 -15
  186. package/src/sessions/archive.ts +20 -8
  187. package/src/sessions/sanitize.ts +38 -18
  188. package/src/sessions/service.ts +180 -102
  189. package/src/store/migrations/037-performance-indexes.ts +56 -0
  190. package/src/store/migrations/038-vector-mirror-null-cosine.ts +47 -0
  191. package/src/store/migrations/039-vector-mirror-v2.ts +94 -0
  192. package/src/store/migrations/index.ts +6 -0
  193. package/src/store/sqlite/adapter.ts +1260 -651
  194. package/src/store/sqlite/chunking-policy.ts +15 -1
  195. package/src/store/sqlite/eligibility.ts +110 -70
  196. package/src/store/sqlite/graph-neighbors.ts +71 -46
  197. package/src/store/sqlite/graph-reference-state.ts +27 -3
  198. package/src/store/sqlite/graph-similarity.ts +59 -12
  199. package/src/store/sqlite/metadata-predicate.ts +123 -28
  200. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  201. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  202. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  203. package/src/store/types.ts +32 -0
  204. package/src/store/vector/coarse-router.ts +312 -0
  205. package/src/store/vector/eligibility.ts +39 -0
  206. package/src/store/vector/lazy.ts +17 -0
  207. package/src/store/vector/partition-index.ts +333 -59
  208. package/src/store/vector/proof-cache.ts +209 -0
  209. package/src/store/vector/runtime-compat.ts +6 -0
  210. package/src/store/vector/sqlite-vec.ts +270 -162
  211. package/src/store/vector/stats.ts +37 -73
  212. package/src/store/vector/status.ts +169 -53
  213. package/src/store/vector/stored-vectors.ts +131 -45
  214. package/src/store/vector/types.ts +19 -0
  215. package/src/store/vector/v2-mirror.ts +669 -0
  216. package/src/store/vector/variant-search.ts +1187 -111
  217. package/src/store/vector/variants.ts +964 -160
  218. package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
package/src/core/links.ts CHANGED
@@ -10,16 +10,31 @@
10
10
  // node:path/posix for POSIX paths (relPaths are always POSIX in gno)
11
11
  import { posix as pathPosix } from "node:path";
12
12
 
13
- import type { ExcludedRange } from "../ingestion/strip";
13
+ import type { ExcludedRange } from "../ingestion/excluded-ranges";
14
14
 
15
+ import { rangeIntersectsExcluded } from "../ingestion/excluded-ranges";
15
16
  import { buildLineOffsets, offsetToPosition } from "../ingestion/position";
16
- import { rangeIntersectsExcluded } from "../ingestion/strip";
17
17
  import {
18
18
  isBackslashEscaped,
19
19
  parseParenthesizedDestination,
20
20
  stripAngleBracketDestination,
21
21
  unescapeCommonMarkDestination,
22
22
  } from "./link-destination-parse";
23
+ import {
24
+ type TargetParts,
25
+ normalizeWikiName,
26
+ parseTargetParts,
27
+ splitWikiLinkContent,
28
+ stripWikiMdExt,
29
+ } from "./wiki-link-syntax";
30
+
31
+ export {
32
+ type TargetParts,
33
+ normalizeWikiName,
34
+ parseTargetParts,
35
+ splitWikiLinkContent,
36
+ stripWikiMdExt,
37
+ };
23
38
 
24
39
  // ─────────────────────────────────────────────────────────────────────────────
25
40
  // Types
@@ -50,15 +65,6 @@ export interface ParsedLink {
50
65
  endCol: number;
51
66
  }
52
67
 
53
- export interface TargetParts {
54
- /** Reference (name or path) without anchor */
55
- ref: string;
56
- /** Anchor/fragment without # */
57
- anchor?: string;
58
- /** Collection prefix */
59
- collection?: string;
60
- }
61
-
62
68
  // ─────────────────────────────────────────────────────────────────────────────
63
69
  // Constants
64
70
  // ─────────────────────────────────────────────────────────────────────────────
@@ -158,9 +164,6 @@ const BRACKET_IN_DESTINATION_REGEX = /[[\]]/;
158
164
  /** External URL pattern (http:// https:// mailto: etc.) */
159
165
  const EXTERNAL_URL_REGEX = /^[a-z][a-z0-9+.-]*:/i;
160
166
 
161
- /** Collection prefix pattern: collection:rest */
162
- const COLLECTION_PREFIX_REGEX = /^([a-z0-9_-]+):(.+)$/i;
163
-
164
167
  // ─────────────────────────────────────────────────────────────────────────────
165
168
  // Unicode Text Utilities
166
169
  // ─────────────────────────────────────────────────────────────────────────────
@@ -170,6 +173,9 @@ const COLLECTION_PREFIX_REGEX = /^([a-z0-9_-]+):(.+)$/i;
170
173
  * Uses Array.from for proper Unicode segmentation.
171
174
  */
172
175
  export function truncateText(text: string, maxGraphemes: number): string {
176
+ if (text.length <= maxGraphemes) {
177
+ return text;
178
+ }
173
179
  const graphemes = Array.from(text);
174
180
  if (graphemes.length <= maxGraphemes) {
175
181
  return text;
@@ -177,22 +183,6 @@ export function truncateText(text: string, maxGraphemes: number): string {
177
183
  return graphemes.slice(0, maxGraphemes).join("");
178
184
  }
179
185
 
180
- /**
181
- * Normalize wiki name: NFC + lowercase + trim.
182
- * Used for matching wiki links to document titles.
183
- */
184
- export function normalizeWikiName(name: string): string {
185
- return name.normalize("NFC").toLowerCase().trim();
186
- }
187
-
188
- /**
189
- * Strip a trailing .md extension (case-insensitive) without lowercasing.
190
- */
191
- export function stripWikiMdExt(ref: string): string {
192
- const lower = ref.toLowerCase();
193
- return lower.endsWith(".md") ? ref.slice(0, -3) : ref;
194
- }
195
-
196
186
  /**
197
187
  * Extract basename from a wiki ref.
198
188
  * Strips path segments and a trailing .md extension (no normalization).
@@ -202,26 +192,6 @@ export function extractWikiBasename(ref: string): string {
202
192
  return stripWikiMdExt(base);
203
193
  }
204
194
 
205
- /**
206
- * Split the content of a wiki link into target and alias. Obsidian also reads
207
- * `\|` (the pipe escaped inside a Markdown table) as the alias separator,
208
- * so `[[Note\|Alias]]` targets `Note`, not `Note\`.
209
- */
210
- export function splitWikiLinkContent(content: string): {
211
- target: string;
212
- alias?: string;
213
- } {
214
- const pipeIndex = content.indexOf("|");
215
- if (pipeIndex < 0) {
216
- return { target: content };
217
- }
218
- const escaped = pipeIndex > 0 && content[pipeIndex - 1] === "\\";
219
- return {
220
- target: content.slice(0, escaped ? pipeIndex - 1 : pipeIndex),
221
- alias: content.slice(pipeIndex + 1),
222
- };
223
- }
224
-
225
195
  // ─────────────────────────────────────────────────────────────────────────────
226
196
  // Path Normalization
227
197
  // ─────────────────────────────────────────────────────────────────────────────
@@ -299,43 +269,6 @@ export function normalizeMarkdownPath(
299
269
  return resolved;
300
270
  }
301
271
 
302
- // ─────────────────────────────────────────────────────────────────────────────
303
- // Target Parsing
304
- // ─────────────────────────────────────────────────────────────────────────────
305
-
306
- /**
307
- * Parse target into ref, anchor, and optional collection prefix.
308
- * Handles: "Note", "Note#Section", "collection:Note#Section"
309
- */
310
- export function parseTargetParts(target: string): TargetParts {
311
- let remaining = target.trim();
312
- let collection: string | undefined;
313
-
314
- // Check for collection prefix (before any #)
315
- const hashIndex = remaining.indexOf("#");
316
- const textBeforeHash =
317
- hashIndex >= 0 ? remaining.slice(0, hashIndex) : remaining;
318
-
319
- const prefixMatch = COLLECTION_PREFIX_REGEX.exec(textBeforeHash);
320
- if (prefixMatch?.[1] && prefixMatch[2]) {
321
- collection = prefixMatch[1].toLowerCase(); // Normalize to lowercase for consistency
322
- // Reconstruct remaining without the collection prefix
323
- remaining =
324
- prefixMatch[2] + (hashIndex >= 0 ? remaining.slice(hashIndex) : "");
325
- }
326
-
327
- // Split on # for anchor
328
- const parts = remaining.split("#");
329
- const ref = (parts[0] ?? "").trim();
330
- const anchor = parts[1]?.trim();
331
-
332
- return {
333
- ref,
334
- anchor: anchor && anchor.length > 0 ? anchor : undefined,
335
- collection,
336
- };
337
- }
338
-
339
272
  // ─────────────────────────────────────────────────────────────────────────────
340
273
  // Link Parsing
341
274
  // ─────────────────────────────────────────────────────────────────────────────
@@ -48,7 +48,7 @@ export function memoryLockWaitMs(deps: MemoryServiceDeps): number {
48
48
  }
49
49
 
50
50
  export function utf8Bytes(text: string): number {
51
- return new TextEncoder().encode(text).byteLength;
51
+ return Buffer.byteLength(text, "utf8");
52
52
  }
53
53
 
54
54
  export function estimateTokens(text: string): number {
@@ -213,14 +213,11 @@ export function buildRecallReceipt(input: {
213
213
  // Record materialization
214
214
  // ─────────────────────────────────────────────────────────────────────────────
215
215
 
216
- export async function readFact(
217
- store: StorePort,
218
- doc: Pick<DocumentRow, "uri" | "docid" | "mirrorHash">
219
- ): Promise<MemoryFact | null> {
220
- if (!doc.mirrorHash) return null;
221
- const content = await store.getContent(doc.mirrorHash);
222
- if (!content.ok || content.value === null) return null;
223
- const validation = validateMemoryRecord(content.value);
216
+ export function parseFactFromContent(
217
+ doc: Pick<DocumentRow, "uri" | "docid" | "mirrorHash">,
218
+ content: string
219
+ ): MemoryFact | null {
220
+ const validation = validateMemoryRecord(content);
224
221
  if (!validation.ok) return null;
225
222
  const { frontmatter, supersedes, text } = validation.record;
226
223
  return {
@@ -237,3 +234,13 @@ export async function readFact(
237
234
  ...(frontmatter.source ? { source: frontmatter.source } : {}),
238
235
  };
239
236
  }
237
+
238
+ export async function readFact(
239
+ store: StorePort,
240
+ doc: Pick<DocumentRow, "uri" | "docid" | "mirrorHash">
241
+ ): Promise<MemoryFact | null> {
242
+ if (!doc.mirrorHash) return null;
243
+ const content = await store.getContent(doc.mirrorHash);
244
+ if (!content.ok || content.value === null) return null;
245
+ return parseFactFromContent(doc, content.value);
246
+ }
@@ -15,6 +15,7 @@ import type {
15
15
 
16
16
  import { searchBm25 } from "../pipeline/search";
17
17
  import { searchVectorWithEmbedding } from "../pipeline/vsearch";
18
+ import { getContentBatch } from "../store/content-batch";
18
19
  import { selectContextEvidence } from "./context-budget";
19
20
  import { mergeEgressLineages } from "./egress-provenance";
20
21
  import {
@@ -22,7 +23,7 @@ import {
22
23
  compareCodeUnits,
23
24
  estimateTokens,
24
25
  memoryNow,
25
- readFact,
26
+ parseFactFromContent,
26
27
  requireIdentity,
27
28
  requireManagedCollection,
28
29
  requireScopes,
@@ -257,8 +258,9 @@ async function searchLexical(
257
258
 
258
259
  /**
259
260
  * Retrieval legs: BM25 always; vectors when an embedding port and a searchable
260
- * vector index are present. The eligible set is one unbounded in-query
261
- * scope+supersession filter; the vector leg only ever ranks inside it.
261
+ * vector index are present. The vector leg applies the native in-query
262
+ * memoryFilter (scopes + excludeSuperseded) directly and overlaps query
263
+ * embedding with lexical search.
262
264
  */
263
265
  async function retrieveLegs(
264
266
  deps: MemoryServiceDeps,
@@ -267,41 +269,62 @@ async function retrieveLegs(
267
269
  const { store, config } = deps;
268
270
  const { query, collection, scopes } = input;
269
271
  const legs: RetrievalLeg[] = [];
270
- const lexical = await searchLexical(deps, input);
271
- if (lexical) {
272
- legs.push({ source: "bm25", results: lexical });
273
- }
274
-
275
272
  const retrieval: RecallResult["retrieval"] = { mode: "lexical" };
276
273
  const embedPort = deps.embedPort ?? null;
277
274
  const vectorIndex = deps.vectorIndex ?? null;
275
+
278
276
  if (!embedPort || !vectorIndex?.searchAvailable) {
277
+ const lexical = await searchLexical(deps, input);
278
+ if (lexical) {
279
+ legs.push({ source: "bm25", results: lexical });
280
+ }
279
281
  retrieval.semanticUnavailable = embedPort
280
282
  ? "vector index unavailable"
281
283
  : "no embedding model available";
282
284
  return { legs, retrieval };
283
285
  }
284
286
 
285
- const eligible = await store.listMemoryEligibleDocuments({
287
+ // Start lexical search immediately and observe its outcome right away so a
288
+ // lexical rejection can never become an unhandled rejection while the probe
289
+ // is still pending.
290
+ const lexicalOutcome = searchLexical(deps, input).then(
291
+ (value) => ({ ok: true as const, value }),
292
+ (error: unknown) => ({ ok: false as const, error })
293
+ );
294
+ const probe = await store.listMemoryEligibleDocuments({
286
295
  collection,
287
296
  scopes,
288
297
  excludeSuperseded: true,
298
+ limit: 1,
289
299
  });
290
- if (!eligible.ok) {
291
- throw new MemoryError("MEMORY_QUERY_FAILED", eligible.error.message);
300
+ if (!probe.ok) {
301
+ await lexicalOutcome;
302
+ throw new MemoryError("MEMORY_QUERY_FAILED", probe.error.message);
292
303
  }
293
- const allowedMirrorHashes = [
294
- ...new Set(eligible.value.map((row) => row.mirrorHash)),
295
- ];
296
- if (allowedMirrorHashes.length === 0) {
304
+ if (probe.value.length === 0) {
305
+ const lexicalResult = await lexicalOutcome;
306
+ if (!lexicalResult.ok) throw lexicalResult.error;
307
+ if (lexicalResult.value) {
308
+ legs.push({ source: "bm25", results: lexicalResult.value });
309
+ }
297
310
  retrieval.mode = "hybrid";
298
311
  return { legs, retrieval };
299
312
  }
300
- const embedded = await embedPort.embed(query);
313
+
314
+ // Overlap query embedding with BM25 lexical retrieval.
315
+ const [lexicalResult, embedded] = await Promise.all([
316
+ lexicalOutcome,
317
+ embedPort.embed(query),
318
+ ]);
319
+ if (!lexicalResult.ok) throw lexicalResult.error;
320
+ if (lexicalResult.value) {
321
+ legs.push({ source: "bm25", results: lexicalResult.value });
322
+ }
301
323
  if (!embedded.ok) {
302
324
  retrieval.semanticUnavailable = embedded.error.message;
303
325
  return { legs, retrieval };
304
326
  }
327
+
305
328
  const vector = await searchVectorWithEmbedding(
306
329
  { store, vectorIndex, embedPort, config },
307
330
  query,
@@ -309,7 +332,7 @@ async function retrieveLegs(
309
332
  {
310
333
  collection,
311
334
  limit: MEMORY_RECALL_RETRIEVAL_LIMIT,
312
- retrievalScope: { allowedMirrorHashes },
335
+ memoryFilter: { scopes, excludeSuperseded: true },
313
336
  }
314
337
  );
315
338
  if (vector.ok) {
@@ -344,22 +367,59 @@ async function materializeFacts(
344
367
  deps: MemoryServiceDeps,
345
368
  ranked: SearchResult[]
346
369
  ): Promise<Array<{ fact: RecalledFact; rank: number }>> {
370
+ const eligible = ranked
371
+ .map((result, index) => ({ result, rank: index + 1 }))
372
+ .filter(
373
+ ({ result }) =>
374
+ Boolean(result.conversion?.mirrorHash) && Boolean(result.egressLineage)
375
+ );
376
+ if (eligible.length === 0) return [];
377
+
378
+ const hashes = [
379
+ ...new Set(eligible.map(({ result }) => result.conversion!.mirrorHash!)),
380
+ ];
381
+ let contentByHash: Map<string, string>;
382
+ const contentBatch = await getContentBatch(deps.store, hashes);
383
+ if (contentBatch.ok) {
384
+ contentByHash = contentBatch.value;
385
+ } else {
386
+ // Fall back to independent per-hash reads so a single unreadable mirror
387
+ // never drops other healthy facts.
388
+ contentByHash = new Map<string, string>();
389
+ const perHash = await Promise.all(
390
+ hashes.map(async (hash) => ({
391
+ hash,
392
+ res: await deps.store.getContent(hash),
393
+ }))
394
+ );
395
+ for (const { hash, res } of perHash) {
396
+ if (res.ok && res.value !== null) {
397
+ contentByHash.set(hash, res.value);
398
+ }
399
+ }
400
+ }
401
+
347
402
  const materialized: Array<{ fact: RecalledFact; rank: number }> = [];
348
- for (const [index, result] of ranked.entries()) {
349
- if (!result.conversion?.mirrorHash || !result.egressLineage) continue;
350
- const fact = await readFact(deps.store, {
351
- uri: result.uri,
352
- docid: result.docid,
353
- mirrorHash: result.conversion.mirrorHash,
354
- });
403
+ for (const { result, rank } of eligible) {
404
+ const mirrorHash = result.conversion!.mirrorHash!;
405
+ const raw = contentByHash.get(mirrorHash);
406
+ if (raw === undefined) continue;
407
+ const fact = parseFactFromContent(
408
+ {
409
+ uri: result.uri,
410
+ docid: result.docid,
411
+ mirrorHash,
412
+ },
413
+ raw
414
+ );
355
415
  if (!fact) continue;
356
416
  materialized.push({
357
- rank: index + 1,
417
+ rank,
358
418
  fact: {
359
419
  ...fact,
360
420
  score: result.score,
361
421
  spanHash: fact.contentHash,
362
- egressLineage: result.egressLineage,
422
+ egressLineage: result.egressLineage!,
363
423
  },
364
424
  });
365
425
  }
@@ -370,14 +430,36 @@ async function materializeFacts(
370
430
  * Token budget via the shared context-evidence selector, then the fact cap.
371
431
  * Facts carry no facets, so the selector fills the budget in retrieval-rank
372
432
  * order (per-fact facets would make it prefer the shortest facts).
433
+ * Precomputes per-fact (bytes, tokens) once via Buffer.byteLength and tracks
434
+ * the accepted prefix separately from proposed tails so both accepted and
435
+ * rejected proposals run in O(1) (strictly O(K) total).
373
436
  */
374
437
  function selectWithinBudget(
375
438
  materialized: Array<{ fact: RecalledFact; rank: number }>,
376
439
  maxFacts: number,
377
440
  maxTokens: number
378
441
  ): RecalledFact[] {
442
+ const measured = materialized.map(({ fact, rank }) => {
443
+ const bytes = utf8Bytes(fact.text);
444
+ const tokens = Math.ceil(bytes / MEMORY_TOKEN_BYTES_ESTIMATE);
445
+ return { fact, rank, bytes, tokens };
446
+ });
447
+
448
+ // Accepted prefix (confirmed across subsequent proposals) kept separate from
449
+ // the last proposed tail so consecutive rejections never invalidate the prefix.
450
+ let prefixLength = 0;
451
+ let prefixTailId: string | null = null;
452
+ let prefixBytes = 0;
453
+ let prefixTokens = 0;
454
+ let lastProposal: {
455
+ length: number;
456
+ tailId: string;
457
+ bytes: number;
458
+ tokens: number;
459
+ } | null = null;
460
+
379
461
  const selection = selectContextEvidence({
380
- candidates: materialized.map(({ fact, rank }) => ({
462
+ candidates: measured.map(({ fact, rank, bytes, tokens }) => ({
381
463
  candidateId: fact.uri,
382
464
  uri: fact.uri,
383
465
  docid: fact.docid,
@@ -389,7 +471,7 @@ function selectWithinBudget(
389
471
  text: fact.text,
390
472
  facets: [],
391
473
  retrievalRank: rank,
392
- value: fact,
474
+ value: { fact, bytes, tokens },
393
475
  })),
394
476
  requestedFacets: [],
395
477
  limits: {
@@ -401,15 +483,67 @@ function selectWithinBudget(
401
483
  documentShareDenominator: 1,
402
484
  },
403
485
  projectCanonical: (state) => {
404
- const texts = state.selected.map((item) => item.value.text);
405
- return {
406
- value: texts,
407
- usedBytes: texts.reduce((sum, item) => sum + utf8Bytes(item), 0),
408
- usedTokens: texts.reduce((sum, item) => sum + estimateTokens(item), 0),
486
+ const selected = state.selected;
487
+ const len = selected.length;
488
+ if (len === 0) {
489
+ prefixLength = 0;
490
+ prefixTailId = null;
491
+ prefixBytes = 0;
492
+ prefixTokens = 0;
493
+ lastProposal = null;
494
+ return { value: selected, usedBytes: 0, usedTokens: 0 };
495
+ }
496
+ const tail = selected[len - 1]!;
497
+ let usedBytes: number;
498
+ let usedTokens: number;
499
+
500
+ if (
501
+ lastProposal !== null &&
502
+ len === lastProposal.length + 1 &&
503
+ selected[lastProposal.length - 1]?.candidateId === lastProposal.tailId
504
+ ) {
505
+ // The previous proposal was accepted by the selector: promote it into
506
+ // the stable prefix in O(1), then add the new proposed tail.
507
+ prefixLength = lastProposal.length;
508
+ prefixTailId = lastProposal.tailId;
509
+ prefixBytes = lastProposal.bytes;
510
+ prefixTokens = lastProposal.tokens;
511
+ usedBytes = prefixBytes + tail.value.bytes;
512
+ usedTokens = prefixTokens + tail.value.tokens;
513
+ } else if (
514
+ len === prefixLength + 1 &&
515
+ (prefixLength === 0 ||
516
+ selected[prefixLength - 1]?.candidateId === prefixTailId)
517
+ ) {
518
+ // The previous proposal was rejected; the accepted prefix is unchanged
519
+ // and we only add the new proposed candidate's precomputed cost in O(1).
520
+ usedBytes = prefixBytes + tail.value.bytes;
521
+ usedTokens = prefixTokens + tail.value.tokens;
522
+ } else {
523
+ // Fallback for non-incremental jumps: recompute stable prefix 0..len-2.
524
+ prefixBytes = 0;
525
+ prefixTokens = 0;
526
+ for (let i = 0; i < len - 1; i += 1) {
527
+ prefixBytes += selected[i]!.value.bytes;
528
+ prefixTokens += selected[i]!.value.tokens;
529
+ }
530
+ prefixLength = len - 1;
531
+ prefixTailId =
532
+ prefixLength > 0 ? selected[prefixLength - 1]!.candidateId : null;
533
+ usedBytes = prefixBytes + tail.value.bytes;
534
+ usedTokens = prefixTokens + tail.value.tokens;
535
+ }
536
+
537
+ lastProposal = {
538
+ length: len,
539
+ tailId: tail.candidateId,
540
+ bytes: usedBytes,
541
+ tokens: usedTokens,
409
542
  };
543
+ return { value: selected, usedBytes, usedTokens };
410
544
  },
411
545
  });
412
- return selection.selected.slice(0, maxFacts).map((item) => item.value);
546
+ return selection.selected.slice(0, maxFacts).map((item) => item.value.fact);
413
547
  }
414
548
 
415
549
  /**
@@ -24,6 +24,149 @@ export function hasGlobMeta(pattern: string): boolean {
24
24
  return GLOB_META_PATTERN.test(pattern);
25
25
  }
26
26
 
27
+ export type CompiledGlobMatcher = (normalizedPath: string) => boolean;
28
+
29
+ function compileGlobMatcher(pattern: string): CompiledGlobMatcher {
30
+ const glob = new Bun.Glob(pattern);
31
+ // Pre-bind Bun.Glob.prototype.match so callers invoke a typed predicate
32
+ // rather than a polymorphic `.match(path)` call (which CodeQL misclassifies
33
+ // as String.prototype.match(RegExp)).
34
+ return glob.match.bind(glob);
35
+ }
36
+
37
+ export interface CompiledCollectionExclusions {
38
+ /** Single-component literal exclusions (no `/` and no glob metacharacters). */
39
+ bareComponents: ReadonlySet<string>;
40
+ /** Multi-component literal path/prefix exclusions (contain `/`, no glob metacharacters). */
41
+ literalPrefixes: readonly string[];
42
+ /** Glob exclusions compiled once. */
43
+ globs: readonly CompiledGlobMatcher[];
44
+ /** True when `"**"` excludes every subtree. */
45
+ excludesAllSubtrees: boolean;
46
+ /** Compiled root patterns from trailing `/**` exclusions. */
47
+ subtreeGlobs: readonly CompiledGlobMatcher[];
48
+ }
49
+
50
+ /** Pre-compile collection exclusion patterns once per walk. */
51
+ export function compileCollectionExclusions(
52
+ excludes: readonly string[]
53
+ ): CompiledCollectionExclusions {
54
+ const bareComponents = new Set<string>();
55
+ const literalPrefixes: string[] = [];
56
+ const globs: CompiledGlobMatcher[] = [];
57
+ const subtreeGlobs: CompiledGlobMatcher[] = [];
58
+ let excludesAllSubtrees = false;
59
+
60
+ for (const rawPattern of excludes) {
61
+ const pattern = rawPattern.replaceAll("\\", "/");
62
+ if (pattern === "**") {
63
+ excludesAllSubtrees = true;
64
+ }
65
+ if (pattern.endsWith("/**")) {
66
+ const subtreeRootPattern = pattern.slice(0, -3);
67
+ if (subtreeRootPattern.length > 0) {
68
+ subtreeGlobs.push(compileGlobMatcher(subtreeRootPattern));
69
+ }
70
+ }
71
+ if (hasGlobMeta(pattern)) {
72
+ globs.push(compileGlobMatcher(pattern));
73
+ } else if (pattern.includes("/")) {
74
+ literalPrefixes.push(pattern);
75
+ } else {
76
+ bareComponents.add(pattern);
77
+ }
78
+ }
79
+
80
+ return {
81
+ bareComponents,
82
+ literalPrefixes,
83
+ globs,
84
+ excludesAllSubtrees,
85
+ subtreeGlobs,
86
+ };
87
+ }
88
+
89
+ /** Check a POSIX-normalized relative path against pre-compiled exclusions. */
90
+ export function matchesCompiledExclusion(
91
+ normalizedPath: string,
92
+ compiled: CompiledCollectionExclusions
93
+ ): boolean {
94
+ if (compiled.bareComponents.size > 0) {
95
+ let start = 0;
96
+ while (start <= normalizedPath.length) {
97
+ const slash = normalizedPath.indexOf("/", start);
98
+ const part =
99
+ slash === -1
100
+ ? normalizedPath.slice(start)
101
+ : normalizedPath.slice(start, slash);
102
+ if (compiled.bareComponents.has(part)) return true;
103
+ if (slash === -1) break;
104
+ start = slash + 1;
105
+ }
106
+ }
107
+ for (const prefix of compiled.literalPrefixes) {
108
+ if (normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`)) {
109
+ return true;
110
+ }
111
+ }
112
+ for (const matchGlob of compiled.globs) {
113
+ if (matchGlob(normalizedPath)) return true;
114
+ }
115
+ return false;
116
+ }
117
+
118
+ /**
119
+ * Check whether a POSIX-normalized directory path is strictly a fully excluded
120
+ * subtree (every descendant is guaranteed excluded: `**`, bare component,
121
+ * literal prefix, or trailing `/**` glob). Partial non-recursive globs such as
122
+ * `docs/*` or `src/converters*` are NOT matched here so `walkAny` still visits
123
+ * their eligible descendants.
124
+ */
125
+ export function matchesCompiledStrictSubtreeExclusion(
126
+ normalizedPath: string,
127
+ compiled: CompiledCollectionExclusions
128
+ ): boolean {
129
+ if (compiled.excludesAllSubtrees) return true;
130
+ if (compiled.bareComponents.size > 0) {
131
+ let start = 0;
132
+ while (start <= normalizedPath.length) {
133
+ const slash = normalizedPath.indexOf("/", start);
134
+ const part =
135
+ slash === -1
136
+ ? normalizedPath.slice(start)
137
+ : normalizedPath.slice(start, slash);
138
+ if (compiled.bareComponents.has(part)) return true;
139
+ if (slash === -1) break;
140
+ start = slash + 1;
141
+ }
142
+ }
143
+ for (const prefix of compiled.literalPrefixes) {
144
+ if (normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`)) {
145
+ return true;
146
+ }
147
+ }
148
+ for (const matchGlob of compiled.subtreeGlobs) {
149
+ if (matchGlob(normalizedPath)) return true;
150
+ }
151
+ return false;
152
+ }
153
+
154
+ /**
155
+ * Compiled equivalent of `matchesCollectionSubtreeExclusion` (used by `walkLocal`
156
+ * to preserve exact local-mode directory exclusion semantics).
157
+ */
158
+ export function matchesCompiledSubtreeExclusion(
159
+ normalizedPath: string,
160
+ compiled: CompiledCollectionExclusions
161
+ ): boolean {
162
+ if (compiled.excludesAllSubtrees) return true;
163
+ if (matchesCompiledExclusion(normalizedPath, compiled)) return true;
164
+ for (const matchGlob of compiled.subtreeGlobs) {
165
+ if (matchGlob(normalizedPath)) return true;
166
+ }
167
+ return false;
168
+ }
169
+
27
170
  /**
28
171
  * Bare values preserve historical component/prefix semantics. Values with
29
172
  * glob metacharacters match the complete normalized relative path.
@@ -347,6 +347,9 @@ export class RetrievalTraceSession {
347
347
  capabilities,
348
348
  fallbackCodes,
349
349
  ...(latencyMs === undefined ? {} : { latencyMs }),
350
+ ...(traceMetadata?.vectorRoute === undefined
351
+ ? {}
352
+ : { vectorRoute: traceMetadata.vectorRoute }),
350
353
  };
351
354
  const runId = this.nextId("retrieval-run");
352
355
  const run = await this.recorder.appendRun({
@@ -143,12 +143,21 @@ const evidencePayloadSchema = z
143
143
  latencyMs: z.number().finite().nonnegative().optional(),
144
144
  })
145
145
  .strict();
146
+ const vectorRouteSchema = z
147
+ .object({
148
+ route: z.enum(["exact-sql", "exact-vec0", "coarse-bit"]),
149
+ mirrorRows: z.number().int().nonnegative(),
150
+ coarseK: z.number().int().positive().optional(),
151
+ rescored: z.number().int().nonnegative().optional(),
152
+ })
153
+ .strict();
146
154
  const retrievalPayloadSchema = z
147
155
  .object({
148
156
  ranked: z.array(evidenceRefSchema).max(10_000),
149
157
  latencyMs: z.number().finite().nonnegative().optional(),
150
158
  capabilities: z.array(z.string().min(1).max(128)).max(100).optional(),
151
159
  fallbackCodes: z.array(z.string().min(1).max(128)).max(100).optional(),
160
+ vectorRoute: vectorRouteSchema.optional(),
152
161
  })
153
162
  .strict();
154
163
  const contextPayloadSchema = evidencePayloadSchema.extend({