@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
@@ -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.
@@ -66,19 +66,24 @@ export function slugifySectionTitle(title: string): string {
66
66
 
67
67
  export const lineStartOffsets = (content: string): number[] => {
68
68
  const offsets = [0];
69
- for (let index = 0; index < content.length; index += 1) {
70
- if (content[index] === "\n") offsets.push(index + 1);
69
+ let pos = content.indexOf("\n");
70
+ while (pos !== -1) {
71
+ offsets.push(pos + 1);
72
+ pos = content.indexOf("\n", pos + 1);
71
73
  }
72
74
  return offsets;
73
75
  };
74
76
 
75
77
  /** Extract structural section records (no quote evidence). */
76
- export function extractSectionRecords(content: string): SectionRecord[] {
78
+ export function extractSectionRecords(
79
+ content: string,
80
+ precomputedStarts?: readonly number[]
81
+ ): SectionRecord[] {
77
82
  const records: SectionRecord[] = [];
78
83
  const counts = new Map<string, number>();
79
84
  const pathCounts = new Map<string, number>();
80
85
  const lines = content.split("\n");
81
- const starts = lineStartOffsets(content);
86
+ const starts = precomputedStarts ?? lineStartOffsets(content);
82
87
  let openFence: OpenFence | null = null;
83
88
  const stack: { level: number; title: string }[] = [];
84
89
 
@@ -149,8 +154,13 @@ export function extractSectionRecords(content: string): SectionRecord[] {
149
154
  return records;
150
155
  }
151
156
 
152
- export function extractSections(content: string): DocumentSection[] {
153
- return extractSectionRecords(content).map((record) => record.section);
157
+ export function extractSections(
158
+ content: string,
159
+ precomputedStarts?: readonly number[]
160
+ ): DocumentSection[] {
161
+ return extractSectionRecords(content, precomputedStarts).map(
162
+ (record) => record.section
163
+ );
154
164
  }
155
165
 
156
166
  /** Extract one inclusive, 1-based line range without normalizing source bytes. */
@@ -70,6 +70,74 @@ export const typedMetadataSchema = z
70
70
  )
71
71
  );
72
72
 
73
+ function isValidScalar(value: unknown): value is MetadataScalar {
74
+ if (typeof value === "string") {
75
+ return value.length <= METADATA_LIMITS.stringLength;
76
+ }
77
+ if (typeof value === "number") {
78
+ return Number.isFinite(value);
79
+ }
80
+ return typeof value === "boolean";
81
+ }
82
+
83
+ /**
84
+ * Direct validator for stored `documents.typed_metadata` JSON strings.
85
+ * Avoids `JSON.stringify` + `TextEncoder` when raw UTF-8 length plus the
86
+ * worst-case numeric re-serialization bound (24 bytes per finite JS number)
87
+ * proves the canonical JSON fits within 64 KiB; otherwise checks exact
88
+ * canonical `JSON.stringify(parsed)` byte length.
89
+ */
90
+ const MAX_JSON_NUMBER_BYTES = 24;
91
+
92
+ export function parseStoredTypedMetadata(raw: string): TypedMetadata {
93
+ const parsed: unknown = JSON.parse(raw);
94
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
95
+ throw new Error("Invalid typed metadata: expected object");
96
+ }
97
+ const entries = Object.entries(parsed);
98
+ if (entries.length > METADATA_LIMITS.keys) {
99
+ throw new Error("Too many metadata keys");
100
+ }
101
+ let numberCount = 0;
102
+ for (const [key, value] of entries) {
103
+ if (key.length < 1 || key.length > METADATA_LIMITS.keyLength) {
104
+ throw new Error("Invalid metadata key length");
105
+ }
106
+ if (reserved.has(key)) {
107
+ throw new Error("Reserved metadata key");
108
+ }
109
+ if (Array.isArray(value)) {
110
+ if (value.length > METADATA_LIMITS.members) {
111
+ throw new Error("Too many metadata array members");
112
+ }
113
+ const firstType = value.length > 0 ? typeof value[0] : null;
114
+ for (const member of value) {
115
+ if (!isValidScalar(member)) {
116
+ throw new Error("Invalid metadata array member");
117
+ }
118
+ if (typeof member !== firstType) {
119
+ throw new Error("Array members must have one scalar type");
120
+ }
121
+ if (typeof member === "number") {
122
+ numberCount++;
123
+ }
124
+ }
125
+ } else if (!isValidScalar(value)) {
126
+ throw new Error("Invalid metadata value");
127
+ } else if (typeof value === "number") {
128
+ numberCount++;
129
+ }
130
+ }
131
+ const rawBytes = Buffer.byteLength(raw, "utf8");
132
+ if (
133
+ rawBytes + numberCount * MAX_JSON_NUMBER_BYTES > METADATA_LIMITS.bytes &&
134
+ Buffer.byteLength(JSON.stringify(parsed), "utf8") > METADATA_LIMITS.bytes
135
+ ) {
136
+ throw new Error("Metadata exceeds 64 KiB");
137
+ }
138
+ return parsed as TypedMetadata;
139
+ }
140
+
73
141
  const leafSchemas = [
74
142
  z
75
143
  .object({ op: z.enum(["eq", "ne"]), key: keySchema, value: scalarSchema })
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Zero-dependency pure wiki-link string helpers.
3
+ * Extracted from src/core/links so browser bundles (MarkdownPreview) and
4
+ * lightweight callers do not pull in node:path or markdown parsing modules.
5
+ *
6
+ * @module src/core/wiki-link-syntax
7
+ */
8
+
9
+ export interface TargetParts {
10
+ /** Reference (name or path) without anchor */
11
+ ref: string;
12
+ /** Anchor/fragment without # */
13
+ anchor?: string;
14
+ /** Collection prefix */
15
+ collection?: string;
16
+ }
17
+
18
+ /** Collection prefix pattern: collection:rest */
19
+ const COLLECTION_PREFIX_REGEX = /^([a-z0-9_-]+):(.+)$/i;
20
+
21
+ /**
22
+ * Normalize wiki name: NFC + lowercase + trim.
23
+ * Used for matching wiki links to document titles.
24
+ */
25
+ export function normalizeWikiName(name: string): string {
26
+ return name.normalize("NFC").toLowerCase().trim();
27
+ }
28
+
29
+ /**
30
+ * Strip a trailing .md extension (case-insensitive) without lowercasing.
31
+ */
32
+ export function stripWikiMdExt(ref: string): string {
33
+ const lower = ref.toLowerCase();
34
+ return lower.endsWith(".md") ? ref.slice(0, -3) : ref;
35
+ }
36
+
37
+ /**
38
+ * Split the content of a wiki link into target and alias. Obsidian also reads
39
+ * `\|` (the pipe escaped inside a Markdown table) as the alias separator,
40
+ * so `[[Note\|Alias]]` targets `Note`, not `Note\`.
41
+ */
42
+ export function splitWikiLinkContent(content: string): {
43
+ target: string;
44
+ alias?: string;
45
+ } {
46
+ const pipeIndex = content.indexOf("|");
47
+ if (pipeIndex < 0) {
48
+ return { target: content };
49
+ }
50
+ const escaped = pipeIndex > 0 && content[pipeIndex - 1] === "\\";
51
+ return {
52
+ target: content.slice(0, escaped ? pipeIndex - 1 : pipeIndex),
53
+ alias: content.slice(pipeIndex + 1),
54
+ };
55
+ }
56
+
57
+ /**
58
+ * Parse target into ref, anchor, and optional collection prefix.
59
+ * Handles: "Note", "Note#Section", "collection:Note#Section"
60
+ */
61
+ export function parseTargetParts(target: string): TargetParts {
62
+ let remaining = target.trim();
63
+ let collection: string | undefined;
64
+
65
+ // Check for collection prefix (before any #)
66
+ const hashIndex = remaining.indexOf("#");
67
+ const textBeforeHash =
68
+ hashIndex >= 0 ? remaining.slice(0, hashIndex) : remaining;
69
+
70
+ const prefixMatch = COLLECTION_PREFIX_REGEX.exec(textBeforeHash);
71
+ if (prefixMatch?.[1] && prefixMatch[2]) {
72
+ collection = prefixMatch[1].toLowerCase(); // Normalize to lowercase for consistency
73
+ // Reconstruct remaining without the collection prefix
74
+ remaining =
75
+ prefixMatch[2] + (hashIndex >= 0 ? remaining.slice(hashIndex) : "");
76
+ }
77
+
78
+ // Split on # for anchor
79
+ const parts = remaining.split("#");
80
+ const ref = (parts[0] ?? "").trim();
81
+ const anchor = parts[1]?.trim();
82
+
83
+ return {
84
+ ref,
85
+ anchor: anchor && anchor.length > 0 ? anchor : undefined,
86
+ collection,
87
+ };
88
+ }