@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
@@ -21,6 +21,7 @@ import {
21
21
  import {
22
22
  captureContextEvidenceSnapshot,
23
23
  type ContextEvidenceSnapshot,
24
+ type ContextEvidenceSnapshotDocument,
24
25
  } from "./context-evidence";
25
26
  import { canonicalVerifierJson } from "./context-verifier-canonical";
26
27
  import {
@@ -94,21 +95,31 @@ const unwrapStore = <T>(
94
95
  };
95
96
 
96
97
  const matchingDocument = (
97
- documents: readonly DocumentRow[],
98
+ documentsByKey: ReadonlyMap<string, DocumentRow[]>,
99
+ derivedDocidCache: Map<string, string>,
98
100
  uri: string,
99
101
  sourceHash: string,
100
- mirrorHash: string,
101
- indexName: string
102
+ mirrorHash: string
102
103
  ): DocumentRow | null => {
103
- const matches = documents.filter(
104
- (document) =>
104
+ let docid = derivedDocidCache.get(sourceHash);
105
+ if (docid === undefined) {
106
+ docid = deriveDocid(sourceHash);
107
+ derivedDocidCache.set(sourceHash, docid);
108
+ }
109
+ const candidates = documentsByKey.get(`${docid}\0${uri}`);
110
+ if (!candidates) return null;
111
+ let matched: DocumentRow | null = null;
112
+ for (const document of candidates) {
113
+ if (
105
114
  document.active &&
106
- document.docid === deriveDocid(sourceHash) &&
107
115
  document.sourceHash === sourceHash &&
108
- document.mirrorHash === mirrorHash &&
109
- decorateUriForIndex(document.uri, indexName) === uri
110
- );
111
- return matches.length === 1 ? (matches[0] ?? null) : null;
116
+ document.mirrorHash === mirrorHash
117
+ ) {
118
+ if (matched !== null) return null;
119
+ matched = document;
120
+ }
121
+ }
122
+ return matched;
112
123
  };
113
124
 
114
125
  const rawInclusiveLines = (
@@ -127,7 +138,10 @@ type EvidenceReceipt = ContextCapsuleVerification["evidence"][number];
127
138
  interface LoadedEvidence {
128
139
  contentByHash: Map<string, string>;
129
140
  chunksByHash: Map<string, ChunkRow[]>;
130
- documents: DocumentRow[];
141
+ documentsByKey: Map<string, DocumentRow[]>;
142
+ snapshotDocsByUri: Map<string, ContextEvidenceSnapshotDocument[]>;
143
+ derivedDocidCache: Map<string, string>;
144
+ mirrorSha256ByHash: Map<string, string>;
131
145
  snapshot: ContextEvidenceSnapshot;
132
146
  /** Current successor URI of evidence whose memory fact was superseded. */
133
147
  successors: ReadonlyMap<string, string>;
@@ -165,23 +179,20 @@ const missingMirrorReceipt = (
165
179
 
166
180
  const verifyContent = (
167
181
  evidence: Evidence,
168
- loaded: LoadedEvidence,
169
- indexName: string
182
+ loaded: LoadedEvidence
170
183
  ): EvidenceReceipt => {
171
- const identities = loaded.snapshot.documents.filter(
172
- (document) => document.uri === evidence.uri
173
- );
184
+ const identities = loaded.snapshotDocsByUri.get(evidence.uri) ?? [];
174
185
  const identity = identities.length === 1 ? identities[0] : undefined;
175
186
  if (!identity) return missingReceipt(evidence);
176
187
  if (!identity.mirrorHash) {
177
188
  return missingMirrorReceipt(evidence, identity.sourceHash, null);
178
189
  }
179
190
  const document = matchingDocument(
180
- loaded.documents,
191
+ loaded.documentsByKey,
192
+ loaded.derivedDocidCache,
181
193
  evidence.uri,
182
194
  identity.sourceHash,
183
- identity.mirrorHash,
184
- indexName
195
+ identity.mirrorHash
185
196
  );
186
197
  const currentSourceHash = document?.sourceHash ?? identity.sourceHash;
187
198
  const registeredMirrorHash = document?.mirrorHash ?? identity.mirrorHash;
@@ -194,7 +205,11 @@ const verifyContent = (
194
205
  );
195
206
  }
196
207
 
197
- const currentMirrorHash = sha256Text(content);
208
+ let currentMirrorHash = loaded.mirrorSha256ByHash.get(registeredMirrorHash);
209
+ if (currentMirrorHash === undefined) {
210
+ currentMirrorHash = sha256Text(content);
211
+ loaded.mirrorSha256ByHash.set(registeredMirrorHash, currentMirrorHash);
212
+ }
198
213
  const exactPassage = extractInclusiveLines(
199
214
  content,
200
215
  evidence.startLine,
@@ -368,9 +383,26 @@ export const verifyContextCapsule = async (
368
383
  const referencedDocuments = before.documents.filter((document) =>
369
384
  evidenceUris.has(document.uri)
370
385
  );
386
+ const snapshotDocsByUri = new Map<
387
+ string,
388
+ ContextEvidenceSnapshotDocument[]
389
+ >();
390
+ for (const doc of before.documents) {
391
+ const list = snapshotDocsByUri.get(doc.uri);
392
+ if (list) list.push(doc);
393
+ else snapshotDocsByUri.set(doc.uri, [doc]);
394
+ }
395
+ const derivedDocidCache = new Map<string, string>();
371
396
  const docids = [
372
397
  ...new Set(
373
- referencedDocuments.map((document) => deriveDocid(document.sourceHash))
398
+ referencedDocuments.map((document) => {
399
+ let docid = derivedDocidCache.get(document.sourceHash);
400
+ if (docid === undefined) {
401
+ docid = deriveDocid(document.sourceHash);
402
+ derivedDocidCache.set(document.sourceHash, docid);
403
+ }
404
+ return docid;
405
+ })
374
406
  ),
375
407
  ];
376
408
  const mirrorHashes = [
@@ -390,18 +422,29 @@ export const verifyContextCapsule = async (
390
422
  deps.store.getSupersedingUris?.([...evidenceUris]) ??
391
423
  Promise.resolve(ok(new Map<string, string>())),
392
424
  ]);
425
+ const loadedDocuments = unwrapStore(
426
+ documentResult,
427
+ "document_load_failed",
428
+ "Failed to batch-load verification documents"
429
+ );
430
+ const documentsByKey = new Map<string, DocumentRow[]>();
431
+ for (const doc of loadedDocuments) {
432
+ const key = `${doc.docid}\0${decorateUriForIndex(doc.uri, capsule.scope.indexName)}`;
433
+ const list = documentsByKey.get(key);
434
+ if (list) list.push(doc);
435
+ else documentsByKey.set(key, [doc]);
436
+ }
393
437
  const loaded: LoadedEvidence = {
394
438
  snapshot: before,
439
+ snapshotDocsByUri,
440
+ documentsByKey,
441
+ derivedDocidCache,
442
+ mirrorSha256ByHash: new Map<string, string>(),
395
443
  successors: unwrapStore(
396
444
  successors,
397
445
  "document_load_failed",
398
446
  "Failed to load supersession of verification evidence"
399
447
  ),
400
- documents: unwrapStore(
401
- documentResult,
402
- "document_load_failed",
403
- "Failed to batch-load verification documents"
404
- ),
405
448
  contentByHash: unwrapStore(
406
449
  contentResult,
407
450
  "content_load_failed",
@@ -439,11 +482,7 @@ export const verifyContextCapsule = async (
439
482
  }
440
483
 
441
484
  const evidence = capsule.evidence.map((item) =>
442
- applyRanking(
443
- verifyContent(item, loaded, capsule.scope.indexName),
444
- item,
445
- rankResult
446
- )
485
+ applyRanking(verifyContent(item, loaded), item, rankResult)
447
486
  );
448
487
  return aggregateReceipt(
449
488
  capsule,
@@ -29,10 +29,15 @@ interface LockCommand {
29
29
  ) => string[];
30
30
  }
31
31
 
32
+ let resolvedLockCommand: LockCommand | null | undefined;
33
+
32
34
  function resolveLockCommand(): LockCommand | null {
35
+ if (resolvedLockCommand !== undefined) {
36
+ return resolvedLockCommand;
37
+ }
33
38
  const lockfPath = Bun.which("lockf");
34
39
  if (lockfPath) {
35
- return {
40
+ resolvedLockCommand = {
36
41
  path: lockfPath,
37
42
  args: (lockPath, timeoutSeconds, holdCommand) => [
38
43
  "-k",
@@ -44,11 +49,12 @@ function resolveLockCommand(): LockCommand | null {
44
49
  holdCommand,
45
50
  ],
46
51
  };
52
+ return resolvedLockCommand;
47
53
  }
48
54
 
49
55
  const flockPath = Bun.which("flock");
50
56
  if (flockPath) {
51
- return {
57
+ resolvedLockCommand = {
52
58
  path: flockPath,
53
59
  args: (lockPath, timeoutSeconds, holdCommand) => [
54
60
  "--no-fork",
@@ -60,8 +66,10 @@ function resolveLockCommand(): LockCommand | null {
60
66
  holdCommand,
61
67
  ],
62
68
  };
69
+ return resolvedLockCommand;
63
70
  }
64
71
 
72
+ resolvedLockCommand = null;
65
73
  return null;
66
74
  }
67
75
 
@@ -112,9 +112,9 @@ export function analyzeGraphCommunities(
112
112
  const currentLabel = labels.get(node.id) ?? node.id;
113
113
  let bestLabel = currentLabel;
114
114
  let bestScore = scores.get(currentLabel) ?? 0;
115
- for (const [candidate, score] of [...scores.entries()].sort((a, b) =>
116
- a[0].localeCompare(b[0])
117
- )) {
115
+ // Tie-break (score > bestScore || (score === bestScore && candidate < bestLabel))
116
+ // is a strict total order, so iteration order over `scores` does not matter.
117
+ for (const [candidate, score] of scores) {
118
118
  if (
119
119
  score > bestScore ||
120
120
  (score === bestScore && candidate < bestLabel)
@@ -4,11 +4,11 @@
4
4
  * @module src/core/link-inventory-markdown
5
5
  */
6
6
 
7
- import type { ExcludedRange } from "../ingestion/strip";
7
+ import type { ExcludedRange } from "../ingestion/excluded-ranges";
8
8
  import type { LinkInventoryToken } from "./link-inventory-types";
9
9
 
10
+ import { rangeIntersectsExcluded } from "../ingestion/excluded-ranges";
10
11
  import { offsetToPosition } from "../ingestion/position";
11
- import { rangeIntersectsExcluded } from "../ingestion/strip";
12
12
  import {
13
13
  detectEncodingStyle,
14
14
  isBackslashEscaped,
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
+ }