@gmickel/gno 2.15.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 (198) 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.15.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 +1 -1
  9. package/src/cli/commands/agents/commands.ts +1 -1
  10. package/src/cli/commands/ask.ts +1 -1
  11. package/src/cli/commands/context-build.ts +1 -1
  12. package/src/cli/commands/embed.ts +2 -2
  13. package/src/cli/commands/links.ts +1 -1
  14. package/src/cli/commands/mcp/install.ts +2 -2
  15. package/src/cli/commands/mcp/status.ts +1 -1
  16. package/src/cli/commands/mcp/uninstall.ts +1 -1
  17. package/src/cli/commands/query.ts +1 -1
  18. package/src/cli/commands/shared.ts +4 -4
  19. package/src/cli/commands/skill/install.ts +1 -1
  20. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  21. package/src/cli/commands/skill/uninstall.ts +1 -1
  22. package/src/cli/commands/status.ts +75 -58
  23. package/src/cli/config-cache.ts +86 -0
  24. package/src/cli/globals.ts +64 -0
  25. package/src/cli/program.ts +20 -36
  26. package/src/cli/run.ts +121 -67
  27. package/src/cli/runtime-health.ts +132 -122
  28. package/src/cli/session-binding.ts +11 -2
  29. package/src/config/saver.ts +8 -0
  30. package/src/converters/adapters/browser-export/formats.ts +25 -15
  31. package/src/converters/adapters/email/adapter.ts +37 -53
  32. package/src/converters/adapters/email/html.ts +37 -20
  33. package/src/converters/adapters/email/mime.ts +71 -39
  34. package/src/converters/adapters/ical/adapter.ts +20 -12
  35. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  36. package/src/converters/adapters/shared/html-text.ts +55 -37
  37. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  38. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  39. package/src/converters/adapters/transcript/adapter.ts +12 -7
  40. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  41. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  42. package/src/converters/canonicalize.ts +17 -3
  43. package/src/converters/native/markdown.ts +24 -17
  44. package/src/converters/native/plaintext.ts +5 -6
  45. package/src/converters/registry.ts +130 -8
  46. package/src/core/activation-status.ts +4 -8
  47. package/src/core/change-diff.ts +38 -11
  48. package/src/core/context-compiler.ts +17 -18
  49. package/src/core/context-evidence.ts +116 -25
  50. package/src/core/context-verifier.ts +70 -31
  51. package/src/core/file-lock.ts +10 -2
  52. package/src/core/graph-analysis.ts +3 -3
  53. package/src/core/link-inventory-markdown.ts +2 -2
  54. package/src/core/links.ts +20 -87
  55. package/src/core/memory-fence.ts +16 -9
  56. package/src/core/memory-recall.ts +168 -34
  57. package/src/core/path-rules.ts +143 -0
  58. package/src/core/section-parse.ts +16 -6
  59. package/src/core/typed-metadata.ts +68 -0
  60. package/src/core/wiki-link-syntax.ts +88 -0
  61. package/src/embed/backlog.ts +142 -60
  62. package/src/embed/retry.ts +39 -33
  63. package/src/embed/variant-backlog.ts +546 -114
  64. package/src/embed/variant-retry.ts +157 -48
  65. package/src/index.ts +3 -3
  66. package/src/ingestion/budget-error-codes.ts +13 -0
  67. package/src/ingestion/chunker.ts +60 -49
  68. package/src/ingestion/compiled-context.ts +4 -5
  69. package/src/ingestion/convert-file.ts +1 -1
  70. package/src/ingestion/document-metadata.ts +16 -9
  71. package/src/ingestion/excluded-ranges.ts +97 -0
  72. package/src/ingestion/file-processor.ts +122 -37
  73. package/src/ingestion/frontmatter.ts +35 -7
  74. package/src/ingestion/graph-reconciliation.ts +187 -51
  75. package/src/ingestion/language.ts +66 -61
  76. package/src/ingestion/position.ts +5 -5
  77. package/src/ingestion/prepare-file.ts +50 -29
  78. package/src/ingestion/record-adapter-canonical.ts +37 -26
  79. package/src/ingestion/record-adapter.ts +46 -26
  80. package/src/ingestion/record-container.ts +121 -53
  81. package/src/ingestion/record-path.ts +5 -2
  82. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  83. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  84. package/src/ingestion/source-availability/readers.ts +51 -0
  85. package/src/ingestion/strip.ts +39 -105
  86. package/src/ingestion/sync.ts +692 -386
  87. package/src/ingestion/typed-metadata.ts +10 -4
  88. package/src/ingestion/walker.ts +485 -158
  89. package/src/llm/cache.ts +128 -84
  90. package/src/llm/http-inference.ts +112 -35
  91. package/src/llm/http-policy.ts +101 -0
  92. package/src/llm/httpEmbedding.ts +8 -1
  93. package/src/llm/httpGeneration.ts +5 -1
  94. package/src/llm/httpRerank.ts +5 -1
  95. package/src/llm/inference-scope.ts +15 -2
  96. package/src/llm/lazy-ports.ts +33 -3
  97. package/src/llm/lockfile.ts +34 -7
  98. package/src/llm/model-cleanup.ts +24 -0
  99. package/src/llm/native-worker/client.ts +23 -12
  100. package/src/llm/native-worker/dispatcher.ts +19 -9
  101. package/src/llm/native-worker/embedding-identity.ts +42 -16
  102. package/src/llm/native-worker/entry.ts +2 -1
  103. package/src/llm/native-worker/owner.ts +1 -0
  104. package/src/llm/native-worker/ports.ts +86 -23
  105. package/src/llm/native-worker/protocol.ts +386 -55
  106. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  107. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  108. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  109. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  110. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  111. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  112. package/src/llm/types.ts +14 -0
  113. package/src/mcp/context.ts +342 -23
  114. package/src/mcp/http-transport.ts +21 -3
  115. package/src/mcp/tool-profile-types.ts +62 -0
  116. package/src/mcp/tool-profile.ts +32 -56
  117. package/src/mcp/tools/context.ts +5 -1
  118. package/src/mcp/tools/index.ts +269 -191
  119. package/src/mcp/tools/links.ts +7 -5
  120. package/src/mcp/tools/query.ts +60 -37
  121. package/src/mcp/tools/vsearch.ts +25 -14
  122. package/src/pipeline/answer.ts +133 -40
  123. package/src/pipeline/claim-verification.ts +293 -189
  124. package/src/pipeline/claim-verifier.ts +6 -7
  125. package/src/pipeline/egress-lineage.ts +37 -26
  126. package/src/pipeline/exclude.ts +34 -11
  127. package/src/pipeline/expansion.ts +233 -19
  128. package/src/pipeline/filters.ts +169 -33
  129. package/src/pipeline/graph-retrieval.ts +117 -61
  130. package/src/pipeline/hybrid.ts +598 -329
  131. package/src/pipeline/hydration.ts +86 -24
  132. package/src/pipeline/intent.ts +15 -7
  133. package/src/pipeline/owner-fusion.ts +61 -19
  134. package/src/pipeline/query-language.ts +15 -2
  135. package/src/pipeline/rerank.ts +15 -22
  136. package/src/pipeline/search.ts +193 -72
  137. package/src/pipeline/snippet.ts +15 -2
  138. package/src/pipeline/temporal.ts +51 -10
  139. package/src/pipeline/vsearch.ts +250 -152
  140. package/src/publish/attachment-raster.ts +2 -16
  141. package/src/publish/encrypted-export.ts +15 -5
  142. package/src/serve/browse-tree.ts +50 -42
  143. package/src/serve/connectors.ts +2 -1
  144. package/src/serve/context.ts +13 -4
  145. package/src/serve/doc-events.ts +3 -0
  146. package/src/serve/public/app.tsx +49 -21
  147. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  148. package/src/serve/public/components/CaptureModal.tsx +14 -10
  149. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  150. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  151. package/src/serve/public/globals.built.css +1 -1
  152. package/src/serve/public/globals.css +19 -0
  153. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  154. package/src/serve/public/lib/metadata-filter.ts +234 -9
  155. package/src/serve/public/pages/Browse.tsx +61 -27
  156. package/src/serve/public/pages/DocView.tsx +44 -25
  157. package/src/serve/public/pages/GraphView.tsx +8 -3
  158. package/src/serve/resident-runtime.ts +199 -48
  159. package/src/serve/routes/api.ts +98 -67
  160. package/src/serve/routes/links.ts +18 -4
  161. package/src/serve/server.ts +1370 -1180
  162. package/src/serve/spa-bundle-source.ts +52 -27
  163. package/src/serve/status.ts +101 -52
  164. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  165. package/src/serve/watch-reconciliation-shared.ts +42 -4
  166. package/src/serve/watch-reconciliation.ts +21 -8
  167. package/src/serve/watch-service-events.ts +7 -1
  168. package/src/serve/watch-service-hosts.ts +3 -1
  169. package/src/serve/watch-service.ts +46 -21
  170. package/src/serve/watch-snapshot-scan.ts +6 -15
  171. package/src/sessions/archive.ts +20 -8
  172. package/src/sessions/sanitize.ts +38 -18
  173. package/src/sessions/service.ts +180 -102
  174. package/src/store/migrations/037-performance-indexes.ts +56 -0
  175. package/src/store/migrations/index.ts +2 -0
  176. package/src/store/sqlite/adapter.ts +1217 -651
  177. package/src/store/sqlite/chunking-policy.ts +15 -1
  178. package/src/store/sqlite/eligibility.ts +110 -70
  179. package/src/store/sqlite/graph-neighbors.ts +71 -46
  180. package/src/store/sqlite/graph-reference-state.ts +27 -3
  181. package/src/store/sqlite/graph-similarity.ts +59 -12
  182. package/src/store/sqlite/metadata-predicate.ts +123 -28
  183. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  184. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  185. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  186. package/src/store/types.ts +32 -0
  187. package/src/store/vector/eligibility.ts +39 -0
  188. package/src/store/vector/lazy.ts +17 -0
  189. package/src/store/vector/partition-index.ts +28 -45
  190. package/src/store/vector/proof-cache.ts +103 -0
  191. package/src/store/vector/sqlite-vec.ts +230 -139
  192. package/src/store/vector/stats.ts +29 -73
  193. package/src/store/vector/status.ts +151 -52
  194. package/src/store/vector/stored-vectors.ts +131 -45
  195. package/src/store/vector/types.ts +10 -0
  196. package/src/store/vector/variant-search.ts +771 -109
  197. package/src/store/vector/variants.ts +495 -139
  198. package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
@@ -2,6 +2,7 @@
2
2
  import type {
3
3
  DocEdgeInput,
4
4
  DocumentRow,
5
+ GraphDocumentIdentity,
5
6
  GraphReferenceDocument,
6
7
  GraphReferenceInventory,
7
8
  StorePort,
@@ -35,7 +36,7 @@ const EDGE_TYPE = /^[a-z][a-z0-9_]*$/;
35
36
  const RELATIVE_REF = /^\.\.?\//;
36
37
  type ProjectionError = { relPath: string; code: string; message: string };
37
38
 
38
- function identity(doc: DocumentRow): GraphReferenceDocument {
39
+ function identity(doc: DocumentRow): GraphDocumentIdentity {
39
40
  return {
40
41
  documentId: doc.id,
41
42
  collection: doc.collection,
@@ -46,9 +47,60 @@ function identity(doc: DocumentRow): GraphReferenceDocument {
46
47
  mirrorHash: doc.mirrorHash,
47
48
  sourceHash: doc.sourceHash,
48
49
  contentType: doc.contentType ?? null,
50
+ active: doc.active,
49
51
  };
50
52
  }
51
53
 
54
+ function toReferenceDocument(
55
+ doc: GraphDocumentIdentity
56
+ ): GraphReferenceDocument {
57
+ return {
58
+ documentId: doc.documentId,
59
+ collection: doc.collection,
60
+ relPath: doc.relPath,
61
+ docid: doc.docid,
62
+ uri: doc.uri,
63
+ title: doc.title,
64
+ mirrorHash: doc.mirrorHash,
65
+ sourceHash: doc.sourceHash,
66
+ contentType: doc.contentType,
67
+ };
68
+ }
69
+
70
+ function sameIdentity(
71
+ a: GraphReferenceDocument,
72
+ b: GraphReferenceDocument
73
+ ): boolean {
74
+ return (
75
+ a.documentId === b.documentId &&
76
+ a.collection === b.collection &&
77
+ a.relPath === b.relPath &&
78
+ a.docid === b.docid &&
79
+ a.uri === b.uri &&
80
+ a.title === b.title &&
81
+ a.mirrorHash === b.mirrorHash &&
82
+ a.sourceHash === b.sourceHash &&
83
+ a.contentType === b.contentType
84
+ );
85
+ }
86
+
87
+ /**
88
+ * Whether fields that parsed wiki/markdown links can address are unchanged.
89
+ * `incomingLinkSources` only matches `(collection, relPath, title)`; body-only
90
+ * edits mutate `sourceHash`, `mirrorHash`, and content-derived `docid` without
91
+ * changing how parsed links resolve.
92
+ */
93
+ function sameLinkAddressableIdentity(
94
+ a: GraphReferenceDocument,
95
+ b: GraphReferenceDocument
96
+ ): boolean {
97
+ return (
98
+ a.collection === b.collection &&
99
+ a.relPath === b.relPath &&
100
+ a.title === b.title
101
+ );
102
+ }
103
+
52
104
  /**
53
105
  * Insert once in catalog order: preserves legacy Array.find ambiguity precedence.
54
106
  * Plain wiki-style targets from a document inside a link workspace use the
@@ -179,11 +231,36 @@ export async function projectGraph(
179
231
  }
180
232
  const state = graph?.state(VERSION, fingerprint);
181
233
  if (!forceFull && state?.complete) return [];
182
- const documents = await store.listDocuments();
183
- if (!documents.ok) throw new Error(documents.error.message);
184
- const activeDocs = documents.value.filter((doc) => doc.active);
185
- const current = activeDocs.map(identity);
186
- const currentById = new Map(current.map((doc) => [doc.documentId, doc]));
234
+ let allDocs: GraphDocumentIdentity[];
235
+ if (typeof store.listGraphDocumentIdentities === "function") {
236
+ const identitiesResult = await store.listGraphDocumentIdentities();
237
+ if (!identitiesResult.ok) throw new Error(identitiesResult.error.message);
238
+ allDocs = identitiesResult.value;
239
+ } else {
240
+ const documents = await store.listDocuments();
241
+ if (!documents.ok) throw new Error(documents.error.message);
242
+ allDocs = documents.value.map(identity);
243
+ }
244
+ const current: GraphReferenceDocument[] = [];
245
+ const currentById = new Map<number, GraphReferenceDocument>();
246
+ for (const doc of allDocs) {
247
+ if (!doc.active) continue;
248
+ const refDoc = toReferenceDocument(doc);
249
+ current.push(refDoc);
250
+ currentById.set(refDoc.documentId, refDoc);
251
+ }
252
+ // Pre-index content-type graph hints once; record the FIRST occurrence of
253
+ // every rule ID (including null when its hint is absent/invalid) so later
254
+ // duplicate IDs never override the first rule's precedence.
255
+ const graphHintsByContentType = new Map<string, string | null>();
256
+ for (const rule of options.contentTypeRules ?? []) {
257
+ if (graphHintsByContentType.has(rule.id)) continue;
258
+ const hint = rule.graphHints?.[0];
259
+ graphHintsByContentType.set(
260
+ rule.id,
261
+ hint && EDGE_TYPE.test(hint) ? hint : null
262
+ );
263
+ }
187
264
  // Read before begin: a new version/config deliberately resets the old inventory.
188
265
  const previous = graph?.readInventory() ?? [];
189
266
  const previousById = new Map(
@@ -208,49 +285,106 @@ export async function projectGraph(
208
285
  let selected: Set<number> | undefined;
209
286
  if (!full && graph) {
210
287
  selected = new Set(requestedSources);
211
- const changed = new Map<number, GraphReferenceDocument[]>();
288
+ let anyChanged = false;
289
+ const linkAddressableIdentities: GraphReferenceDocument[] = [];
290
+ let uriOrLinkTargetChanged = false;
291
+ const changedDocids = new Set<string>();
212
292
  for (const doc of current) {
213
293
  const old = previousById.get(doc.documentId)?.document;
214
- if (!old || JSON.stringify(old) !== JSON.stringify(doc)) {
215
- changed.set(doc.documentId, old ? [old, doc] : [doc]);
294
+ if (!old || !sameIdentity(old, doc)) {
295
+ anyChanged = true;
216
296
  selected.add(doc.documentId);
297
+ if (!old) {
298
+ linkAddressableIdentities.push(doc);
299
+ uriOrLinkTargetChanged = true;
300
+ } else {
301
+ if (!sameLinkAddressableIdentity(old, doc)) {
302
+ linkAddressableIdentities.push(old, doc);
303
+ uriOrLinkTargetChanged = true;
304
+ }
305
+ if (old.uri !== doc.uri) {
306
+ uriOrLinkTargetChanged = true;
307
+ }
308
+ if (old.docid !== doc.docid) {
309
+ changedDocids.add(old.docid);
310
+ changedDocids.add(doc.docid);
311
+ }
312
+ }
217
313
  }
218
314
  }
219
315
  for (const row of previous) {
220
316
  if (!currentById.has(row.document.documentId)) {
221
- changed.set(row.document.documentId, [row.document]);
317
+ anyChanged = true;
318
+ linkAddressableIdentities.push(row.document);
319
+ uriOrLinkTargetChanged = true;
222
320
  selected.add(row.document.documentId);
223
321
  }
224
322
  }
225
323
  // Input mutation without a changed identity can be a direct parsed-link edit.
226
324
  // No durable per-source link journal exists; conservatively rebuild in that case.
227
- if (changed.size === 0 && state.dirty) selected = undefined;
325
+ if (!anyChanged && state.dirty) selected = undefined;
228
326
  else {
229
- // One statement over every changed identity scales with links x
230
- // targets and cannot yield; chunk it so the event loop gets turns.
231
- const identities = [...changed.values()].flat();
232
- for (let i = 0; i < identities.length; i += INCOMING_LINK_CHUNK) {
233
- await slicer.maybeYield();
234
- for (const id of graph.incomingLinkSources(
235
- identities.slice(i, i + INCOMING_LINK_CHUNK)
236
- ))
237
- selected.add(id);
327
+ if (linkAddressableIdentities.length > 0) {
328
+ // One statement over every changed link-addressable identity scales
329
+ // with links x targets and cannot yield; chunk it for event-loop turns.
330
+ for (
331
+ let i = 0;
332
+ i < linkAddressableIdentities.length;
333
+ i += INCOMING_LINK_CHUNK
334
+ ) {
335
+ await slicer.maybeYield();
336
+ for (const id of graph.incomingLinkSources(
337
+ linkAddressableIdentities.slice(i, i + INCOMING_LINK_CHUNK)
338
+ ))
339
+ selected.add(id);
340
+ }
238
341
  }
239
- const resolveOld = relationResolver(
240
- previous.map((row) => row.document),
241
- memberships
242
- );
243
- for (const row of previous) {
244
- const source = currentById.get(row.document.documentId);
245
- if (!source || selected.has(source.documentId)) continue;
246
- if (
247
- row.references.some(
248
- (ref) =>
249
- resolveOld(row.document, ref.target)?.documentId !==
250
- resolve(source, ref.target)?.documentId
342
+ if (uriOrLinkTargetChanged) {
343
+ const resolveOld = relationResolver(
344
+ previous.map((row) => row.document),
345
+ memberships
346
+ );
347
+ for (const row of previous) {
348
+ const source = currentById.get(row.document.documentId);
349
+ if (!source || selected.has(source.documentId)) continue;
350
+ if (
351
+ row.references.some(
352
+ (ref) =>
353
+ resolveOld(row.document, ref.target)?.documentId !==
354
+ resolve(source, ref.target)?.documentId
355
+ )
251
356
  )
252
- )
253
- selected.add(source.documentId);
357
+ selected.add(source.documentId);
358
+ }
359
+ } else if (changedDocids.size > 0) {
360
+ // Body-only edits change content-derived docid without altering
361
+ // collection/relPath/uri/title; only explicit `#docid` frontmatter
362
+ // relations can be affected. Query those directly without scanning
363
+ // every prior inventory row or rebuilding resolveOld.
364
+ if (typeof graph.docidReferenceSources === "function") {
365
+ for (const sourceId of graph.docidReferenceSources([
366
+ ...changedDocids,
367
+ ])) {
368
+ if (currentById.has(sourceId)) {
369
+ selected.add(sourceId);
370
+ }
371
+ }
372
+ } else {
373
+ for (const row of previous) {
374
+ if (row.references.length === 0) continue;
375
+ const source = currentById.get(row.document.documentId);
376
+ if (!source || selected.has(source.documentId)) continue;
377
+ if (
378
+ row.references.some(
379
+ (ref) =>
380
+ ref.target.includes("#") &&
381
+ changedDocids.has(normalizeRelationTarget(ref.target))
382
+ )
383
+ ) {
384
+ selected.add(source.documentId);
385
+ }
386
+ }
387
+ }
254
388
  }
255
389
  }
256
390
  }
@@ -260,18 +394,19 @@ export async function projectGraph(
260
394
  throw new Error("Graph inputs changed while computing affected sources");
261
395
  const work = async () => {
262
396
  const targets = selected
263
- ? documents.value.filter((doc) => selected.has(doc.id))
264
- : documents.value;
397
+ ? allDocs.filter((doc) => selected.has(doc.documentId))
398
+ : allDocs;
265
399
  // Configured sources get their final sets below. Applying defaults first
266
400
  // would delete/recreate an unchanged configured edge on every repair pass.
267
401
  const defaults = targets.filter((doc) => {
268
- const hint = options.contentTypeRules?.find(
269
- (rule) => rule.id === doc.contentType
270
- )?.graphHints?.[0];
271
- return !doc.active || !hint || !EDGE_TYPE.test(hint);
402
+ if (!doc.active) return true;
403
+ return !(
404
+ doc.contentType !== null &&
405
+ graphHintsByContentType.get(doc.contentType)
406
+ );
272
407
  });
273
408
  const backfill = await store.backfillDocEdges(
274
- defaults.map((doc) => doc.id)
409
+ defaults.map((doc) => doc.documentId)
275
410
  );
276
411
  if (!backfill.ok) throw new Error(backfill.error.message);
277
412
  for (const [index, doc] of targets.entries()) {
@@ -281,7 +416,7 @@ export async function projectGraph(
281
416
  else await slicer.maybeYield();
282
417
  if (!doc.active) {
283
418
  const cleared = await store.setDocEdges(
284
- doc.id,
419
+ doc.documentId,
285
420
  [],
286
421
  "frontmatter-relation"
287
422
  );
@@ -289,8 +424,8 @@ export async function projectGraph(
289
424
  errors.push({ relPath: doc.relPath, ...cleared.error });
290
425
  continue;
291
426
  }
292
- const snapshot = currentById.get(doc.id)!;
293
- const cached = selected ? previousById.get(doc.id) : undefined;
427
+ const snapshot = currentById.get(doc.documentId)!;
428
+ const cached = selected ? previousById.get(doc.documentId) : undefined;
294
429
  let references: GraphReferenceInventory["references"];
295
430
  if (
296
431
  cached &&
@@ -336,18 +471,19 @@ export async function projectGraph(
336
471
  });
337
472
  }
338
473
  const relationsResult = await store.setDocEdges(
339
- doc.id,
474
+ doc.documentId,
340
475
  relationEdges,
341
476
  "frontmatter-relation"
342
477
  );
343
478
  if (!relationsResult.ok)
344
479
  errors.push({ relPath: doc.relPath, ...relationsResult.error });
345
480
  graph?.writeInventory({ document: snapshot, references });
346
- const hint = options.contentTypeRules?.find(
347
- (rule) => rule.id === doc.contentType
348
- )?.graphHints?.[0];
349
- if (!hint || !EDGE_TYPE.test(hint)) continue;
350
- const links = await store.getLinksForDoc(doc.id);
481
+ const hint =
482
+ doc.contentType !== null
483
+ ? (graphHintsByContentType.get(doc.contentType) ?? undefined)
484
+ : undefined;
485
+ if (!hint) continue;
486
+ const links = await store.getLinksForDoc(doc.documentId);
351
487
  if (!links.ok) {
352
488
  errors.push({ relPath: doc.relPath, ...links.error });
353
489
  continue;
@@ -377,7 +513,7 @@ export async function projectGraph(
377
513
  ["wikilink", wikiEdges],
378
514
  ["markdown-link", markdownEdges],
379
515
  ] as const) {
380
- const result = await store.setDocEdges(doc.id, edges, source);
516
+ const result = await store.setDocEdges(doc.documentId, edges, source);
381
517
  if (!result.ok)
382
518
  errors.push({ relPath: doc.relPath, ...result.error });
383
519
  }
@@ -10,27 +10,16 @@ import type { LanguageDetectorPort } from "./types";
10
10
  /** Regex to split on whitespace and punctuation */
11
11
  const WORD_SPLIT_REGEX = /[\s\p{P}]+/u;
12
12
 
13
- /** Hiragana range */
14
- const HIRAGANA_MIN = 0x30_40;
13
+ /** Hiragana upper bound (lower bound is 0x3040 fast-skip threshold) */
15
14
  const HIRAGANA_MAX = 0x30_9f;
16
15
 
17
- /** Katakana range */
18
- const KATAKANA_MIN = 0x30_a0;
16
+ /** Katakana upper bound */
19
17
  const KATAKANA_MAX = 0x30_ff;
20
18
 
21
19
  /** Hangul range */
22
20
  const HANGUL_MIN = 0xac_00;
23
21
  const HANGUL_MAX = 0xd7_af;
24
22
 
25
- /** CJK ranges for quick codepoint checking */
26
- const CJK_RANGES = [
27
- [0x4e_00, 0x9f_ff], // CJK Unified Ideographs
28
- [0x34_00, 0x4d_bf], // CJK Unified Ideographs Extension A
29
- [0x30_40, 0x30_9f], // Hiragana
30
- [0x30_a0, 0x30_ff], // Katakana
31
- [0xac_00, 0xd7_af], // Hangul
32
- ] as const;
33
-
34
23
  /**
35
24
  * Character frequency thresholds for CJK detection.
36
25
  */
@@ -108,16 +97,17 @@ const LANGUAGE_MARKER_SETS: Record<string, Set<string>> = {
108
97
  ]),
109
98
  };
110
99
 
111
- /**
112
- * Check if a codepoint is CJK.
113
- */
114
- function isCjkCodepoint(cp: number): boolean {
115
- for (const [min, max] of CJK_RANGES) {
116
- if (cp >= min && cp <= max) {
117
- return true;
118
- }
100
+ /** Single-pass bitmask map for European language markers (preserves en, de, fr, it order). */
101
+ const EUROPEAN_LANGS = ["en", "de", "fr", "it"] as const;
102
+ const MARKER_BITMASK = new Map<string, number>();
103
+ for (let langIndex = 0; langIndex < EUROPEAN_LANGS.length; langIndex += 1) {
104
+ const lang = EUROPEAN_LANGS[langIndex];
105
+ const markerSet = lang ? LANGUAGE_MARKER_SETS[lang] : undefined;
106
+ if (!markerSet) continue;
107
+ const bit = 1 << langIndex;
108
+ for (const word of markerSet) {
109
+ MARKER_BITMASK.set(word, (MARKER_BITMASK.get(word) ?? 0) | bit);
119
110
  }
120
- return false;
121
111
  }
122
112
 
123
113
  /**
@@ -148,7 +138,7 @@ function extractWords(text: string): string[] {
148
138
 
149
139
  /**
150
140
  * Detect if text is primarily CJK (Chinese, Japanese, Korean).
151
- * Single-pass counting for efficiency.
141
+ * Single-pass counting using charCodeAt with fast ASCII/Latin skip.
152
142
  */
153
143
  // oxlint-disable-next-line max-lines-per-function -- Unicode range detection with multiple heuristics
154
144
  function detectCjk(text: string): "zh" | "ja" | "ko" | null {
@@ -158,30 +148,40 @@ function detectCjk(text: string): "zh" | "ja" | "ko" | null {
158
148
  let hasKatakana = false;
159
149
  let hasHangul = false;
160
150
 
161
- // Single pass through the string
162
- for (const char of text) {
163
- const cp = char.codePointAt(0);
164
- if (cp === undefined) {
151
+ const len = text.length;
152
+ for (let i = 0; i < len; i += 1) {
153
+ const cp = text.charCodeAt(i);
154
+ // Preserve codepoint counting for UTF-16 surrogate pairs
155
+ if (cp >= 0xd8_00 && cp <= 0xdb_ff && i + 1 < len) {
156
+ const low = text.charCodeAt(i + 1);
157
+ if (low >= 0xdc_00 && low <= 0xdf_ff) {
158
+ i += 1;
159
+ totalChars += 1;
160
+ continue;
161
+ }
162
+ }
163
+ if (cp < 0x30_40) {
164
+ if (!isWhitespace(cp)) {
165
+ totalChars += 1;
166
+ }
165
167
  continue;
166
168
  }
167
169
 
168
- // Skip whitespace for total count
169
- if (!isWhitespace(cp)) {
170
- totalChars += 1;
171
-
172
- // Check CJK ranges
173
- if (isCjkCodepoint(cp)) {
174
- cjkCount += 1;
175
-
176
- // Also check for script-specific markers
177
- if (cp >= HIRAGANA_MIN && cp <= HIRAGANA_MAX) {
178
- hasHiragana = true;
179
- } else if (cp >= KATAKANA_MIN && cp <= KATAKANA_MAX) {
180
- hasKatakana = true;
181
- } else if (cp >= HANGUL_MIN && cp <= HANGUL_MAX) {
182
- hasHangul = true;
183
- }
184
- }
170
+ totalChars += 1;
171
+ if (cp <= HIRAGANA_MAX) {
172
+ cjkCount += 1;
173
+ hasHiragana = true;
174
+ } else if (cp <= KATAKANA_MAX) {
175
+ cjkCount += 1;
176
+ hasKatakana = true;
177
+ } else if (
178
+ (cp >= 0x4e_00 && cp <= 0x9f_ff) ||
179
+ (cp >= 0x34_00 && cp <= 0x4d_bf)
180
+ ) {
181
+ cjkCount += 1;
182
+ } else if (cp >= HANGUL_MIN && cp <= HANGUL_MAX) {
183
+ cjkCount += 1;
184
+ hasHangul = true;
185
185
  }
186
186
  }
187
187
 
@@ -209,36 +209,41 @@ function detectCjk(text: string): "zh" | "ja" | "ko" | null {
209
209
 
210
210
  /**
211
211
  * Detect European language by word frequency.
212
- * Uses pre-built Sets for O(1) marker lookup.
212
+ * Single pass over words using a pre-built bitmask map.
213
213
  */
214
214
  function detectEuropean(words: string[]): string | null {
215
- if (words.length < 10) {
215
+ const count = words.length;
216
+ if (count < 10) {
216
217
  return null;
217
218
  }
218
219
 
219
- const scores: Record<string, number> = {};
220
-
221
- for (const [lang, markerSet] of Object.entries(LANGUAGE_MARKER_SETS)) {
222
- let matches = 0;
223
-
224
- for (const word of words) {
225
- if (markerSet.has(word)) {
226
- matches += 1;
227
- }
228
- }
229
-
230
- scores[lang] = matches / words.length;
220
+ let en = 0;
221
+ let de = 0;
222
+ let fr = 0;
223
+ let it = 0;
224
+
225
+ for (let i = 0; i < count; i += 1) {
226
+ const word = words[i];
227
+ if (word === undefined) continue;
228
+ const mask = MARKER_BITMASK.get(word);
229
+ if (mask === undefined) continue;
230
+ if (mask & 1) en += 1;
231
+ if (mask & 2) de += 1;
232
+ if (mask & 4) fr += 1;
233
+ if (mask & 8) it += 1;
231
234
  }
232
235
 
233
- // Find language with highest score (must exceed threshold)
236
+ // Find language with highest score (must exceed threshold; preserve en, de, fr, it tie order)
234
237
  const threshold = 0.02; // 2% of words must be markers
235
238
  let bestLang: string | null = null;
236
239
  let bestScore = threshold;
240
+ const counts = [en, de, fr, it] as const;
237
241
 
238
- for (const [lang, score] of Object.entries(scores)) {
242
+ for (let i = 0; i < EUROPEAN_LANGS.length; i += 1) {
243
+ const score = (counts[i] ?? 0) / count;
239
244
  if (score > bestScore) {
240
245
  bestScore = score;
241
- bestLang = lang;
246
+ bestLang = EUROPEAN_LANGS[i] ?? null;
242
247
  }
243
248
  }
244
249
 
@@ -38,11 +38,11 @@ export interface Position {
38
38
  export function buildLineOffsets(content: string): number[] {
39
39
  const offsets: number[] = [0]; // Line 1 starts at offset 0
40
40
 
41
- for (let i = 0; i < content.length; i++) {
42
- if (content[i] === "\n") {
43
- // Next line starts after the newline
44
- offsets.push(i + 1);
45
- }
41
+ let pos = content.indexOf("\n");
42
+ while (pos !== -1) {
43
+ // Next line starts after the newline
44
+ offsets.push(pos + 1);
45
+ pos = content.indexOf("\n", pos + 1);
46
46
  }
47
47
 
48
48
  return offsets;
@@ -28,10 +28,13 @@ import { extractDocumentStructure } from "../core/change-diff";
28
28
  import {
29
29
  normalizeMarkdownPath,
30
30
  normalizeWikiName,
31
+ type ParsedLink,
31
32
  parseLinks,
32
33
  } from "../core/links";
33
34
  import { validateMemoryRecord } from "../core/memory-record";
35
+ import { MarkdownChunker } from "./chunker";
34
36
  import { extractDocumentMetadata, extractTags } from "./document-metadata";
37
+ import { parseFrontmatterDetails } from "./frontmatter";
35
38
  import { buildLineOffsets } from "./position";
36
39
  import { type ExcludedRange, getExcludedRanges } from "./strip";
37
40
 
@@ -107,19 +110,14 @@ export interface PrepareHooks {
107
110
  }
108
111
 
109
112
  const toLinkInputs = (
110
- markdown: string,
111
- relPath: string,
112
- excludedRanges: ExcludedRange[] | null
113
+ parsedLinks: readonly ParsedLink[] | null,
114
+ relPath: string
113
115
  ): DocLinkInput[] => {
114
116
  // Only Markdown sources carry links, as in Obsidian: link-shaped text in
115
117
  // code, plain text or converted documents stays searchable prose.
116
- if (!excludedRanges) return [];
118
+ if (!parsedLinks) return [];
117
119
  const linkInputs: DocLinkInput[] = [];
118
- for (const link of parseLinks(
119
- markdown,
120
- buildLineOffsets(markdown),
121
- excludedRanges
122
- )) {
120
+ for (const link of parsedLinks) {
123
121
  let targetRefNorm: string;
124
122
  if (link.kind === "wiki") {
125
123
  targetRefNorm = normalizeWikiName(link.targetRef);
@@ -198,13 +196,15 @@ export async function prepareFile(
198
196
  if (stopAfterConversion) return { ok: false, error: stopAfterConversion };
199
197
 
200
198
  hooks.onPhase("metadata extraction");
199
+ const frontmatter = parseFrontmatterDetails(markdown);
201
200
  const metadata = extractDocumentMetadata(
202
201
  markdown,
203
202
  relPath,
204
203
  request.metadataExt,
205
- request.contentTypeRules
204
+ request.contentTypeRules,
205
+ frontmatter
206
206
  );
207
- const tags = extractTags(markdown);
207
+ const tags = extractTags(markdown, frontmatter);
208
208
  let memoryScopes: string[] | null = null;
209
209
  if (request.memoryManaged) {
210
210
  const memoryRecord = validateMemoryRecord(markdown);
@@ -233,37 +233,58 @@ export async function prepareFile(
233
233
  if (stopAfterRanges) return { ok: false, error: stopAfterRanges };
234
234
 
235
235
  hooks.onPhase("change-journal structure");
236
+ const lineOffsets = buildLineOffsets(markdown);
237
+ const parsedLinks =
238
+ markdownSource && excludedRanges
239
+ ? parseLinks(markdown, lineOffsets, excludedRanges)
240
+ : null;
236
241
  const nextStructure = extractDocumentStructure(
237
242
  markdown,
238
243
  relPath,
239
244
  metadata.dateFields,
240
- { markdownSource, excludedRanges: excludedRanges ?? undefined }
245
+ {
246
+ markdownSource,
247
+ excludedRanges: excludedRanges ?? undefined,
248
+ lineOffsets,
249
+ parsedLinks: parsedLinks ?? undefined,
250
+ frontmatter,
251
+ }
241
252
  );
242
253
  const stopAfterStructure = step("change-journal structure");
243
254
  if (stopAfterStructure) return { ok: false, error: stopAfterStructure };
244
255
 
245
256
  hooks.onPhase("chunking");
246
- const chunkInputs: ChunkInput[] = hooks.chunker
247
- .chunk(
248
- markdown,
249
- request.chunkParams,
250
- artifact.languageHint ?? request.collectionLanguageHint,
251
- relPath
252
- )
253
- .map((c) => ({
254
- seq: c.seq,
255
- pos: c.pos,
256
- text: c.text,
257
- startLine: c.startLine,
258
- endLine: c.endLine,
259
- language: c.language ?? undefined,
260
- tokenCount: c.tokenCount ?? undefined,
261
- }));
257
+ const chunkLanguageHint =
258
+ artifact.languageHint ?? request.collectionLanguageHint;
259
+ const rawChunks =
260
+ hooks.chunker instanceof MarkdownChunker
261
+ ? hooks.chunker.chunk(
262
+ markdown,
263
+ request.chunkParams,
264
+ chunkLanguageHint,
265
+ relPath,
266
+ lineOffsets
267
+ )
268
+ : hooks.chunker.chunk(
269
+ markdown,
270
+ request.chunkParams,
271
+ chunkLanguageHint,
272
+ relPath
273
+ );
274
+ const chunkInputs: ChunkInput[] = rawChunks.map((c) => ({
275
+ seq: c.seq,
276
+ pos: c.pos,
277
+ text: c.text,
278
+ startLine: c.startLine,
279
+ endLine: c.endLine,
280
+ language: c.language ?? undefined,
281
+ tokenCount: c.tokenCount ?? undefined,
282
+ }));
262
283
  const stopAfterChunking = step("chunking");
263
284
  if (stopAfterChunking) return { ok: false, error: stopAfterChunking };
264
285
 
265
286
  hooks.onPhase("link extraction");
266
- const linkInputs = toLinkInputs(markdown, relPath, excludedRanges);
287
+ const linkInputs = toLinkInputs(parsedLinks, relPath);
267
288
  const stopAfterLinks = step("link extraction");
268
289
  if (stopAfterLinks) return { ok: false, error: stopAfterLinks };
269
290