@gmickel/gno 2.15.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/SKILL.md +27 -0
  3. package/assets/skill/cli-reference.md +24 -15
  4. package/assets/spa-production.json.gz +0 -0
  5. package/browser-extension/artifacts/{gno-browser-clipper-v2.15.0.zip → gno-browser-clipper-v2.17.0.zip} +0 -0
  6. package/browser-extension/artifacts/gno-browser-clipper-v2.17.0.zip.sha256 +1 -0
  7. package/browser-extension/dist/manifest.json +1 -1
  8. package/package.json +1 -1
  9. package/spec/cli.md +43 -3
  10. package/spec/db/schema.sql +53 -1
  11. package/spec/mcp.md +9 -3
  12. package/spec/output-schemas/doctor.schema.json +27 -0
  13. package/spec/output-schemas/retrieval-trace-payloads.schema.json +14 -0
  14. package/spec/output-schemas/search-results.schema.json +14 -0
  15. package/spec/output-schemas/status.schema.json +22 -0
  16. package/src/cli/commands/agents/commands.ts +1 -1
  17. package/src/cli/commands/ask.ts +1 -1
  18. package/src/cli/commands/context-build.ts +1 -1
  19. package/src/cli/commands/doctor.ts +101 -29
  20. package/src/cli/commands/embed.ts +2 -2
  21. package/src/cli/commands/links.ts +30 -6
  22. package/src/cli/commands/mcp/install.ts +2 -2
  23. package/src/cli/commands/mcp/status.ts +1 -1
  24. package/src/cli/commands/mcp/uninstall.ts +1 -1
  25. package/src/cli/commands/query.ts +1 -1
  26. package/src/cli/commands/shared.ts +4 -4
  27. package/src/cli/commands/skill/install.ts +1 -1
  28. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  29. package/src/cli/commands/skill/uninstall.ts +1 -1
  30. package/src/cli/commands/status.ts +75 -58
  31. package/src/cli/commands/vec.ts +180 -8
  32. package/src/cli/config-cache.ts +86 -0
  33. package/src/cli/globals.ts +64 -0
  34. package/src/cli/program.ts +63 -36
  35. package/src/cli/run.ts +121 -67
  36. package/src/cli/runtime-health.ts +132 -122
  37. package/src/cli/session-binding.ts +11 -2
  38. package/src/config/saver.ts +8 -0
  39. package/src/config/types.ts +6 -0
  40. package/src/converters/adapters/browser-export/formats.ts +25 -15
  41. package/src/converters/adapters/email/adapter.ts +37 -53
  42. package/src/converters/adapters/email/html.ts +37 -20
  43. package/src/converters/adapters/email/mime.ts +71 -39
  44. package/src/converters/adapters/ical/adapter.ts +20 -12
  45. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  46. package/src/converters/adapters/shared/html-text.ts +55 -37
  47. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  48. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  49. package/src/converters/adapters/transcript/adapter.ts +12 -7
  50. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  51. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  52. package/src/converters/canonicalize.ts +17 -3
  53. package/src/converters/native/markdown.ts +24 -17
  54. package/src/converters/native/plaintext.ts +5 -6
  55. package/src/converters/registry.ts +130 -8
  56. package/src/core/activation-status.ts +4 -8
  57. package/src/core/change-diff.ts +38 -11
  58. package/src/core/context-compiler.ts +17 -18
  59. package/src/core/context-evidence.ts +116 -25
  60. package/src/core/context-verifier.ts +70 -31
  61. package/src/core/file-lock.ts +10 -2
  62. package/src/core/graph-analysis.ts +3 -3
  63. package/src/core/link-inventory-markdown.ts +2 -2
  64. package/src/core/links.ts +20 -87
  65. package/src/core/memory-fence.ts +16 -9
  66. package/src/core/memory-recall.ts +168 -34
  67. package/src/core/path-rules.ts +143 -0
  68. package/src/core/retrieval-trace-session.ts +3 -0
  69. package/src/core/retrieval-trace.ts +9 -0
  70. package/src/core/section-parse.ts +16 -6
  71. package/src/core/typed-metadata.ts +68 -0
  72. package/src/core/vector-partition-status.ts +13 -0
  73. package/src/core/wiki-link-syntax.ts +88 -0
  74. package/src/embed/backlog.ts +142 -60
  75. package/src/embed/retry.ts +39 -33
  76. package/src/embed/variant-backlog.ts +582 -116
  77. package/src/embed/variant-retry.ts +157 -48
  78. package/src/index.ts +3 -3
  79. package/src/ingestion/budget-error-codes.ts +13 -0
  80. package/src/ingestion/chunker.ts +60 -49
  81. package/src/ingestion/compiled-context.ts +4 -5
  82. package/src/ingestion/convert-file.ts +1 -1
  83. package/src/ingestion/document-metadata.ts +16 -9
  84. package/src/ingestion/excluded-ranges.ts +97 -0
  85. package/src/ingestion/file-processor.ts +122 -37
  86. package/src/ingestion/frontmatter.ts +35 -7
  87. package/src/ingestion/graph-reconciliation.ts +187 -51
  88. package/src/ingestion/language.ts +66 -61
  89. package/src/ingestion/position.ts +5 -5
  90. package/src/ingestion/prepare-file.ts +50 -29
  91. package/src/ingestion/record-adapter-canonical.ts +37 -26
  92. package/src/ingestion/record-adapter.ts +46 -26
  93. package/src/ingestion/record-container.ts +121 -53
  94. package/src/ingestion/record-path.ts +5 -2
  95. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  96. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  97. package/src/ingestion/source-availability/readers.ts +51 -0
  98. package/src/ingestion/strip.ts +39 -105
  99. package/src/ingestion/sync.ts +692 -386
  100. package/src/ingestion/typed-metadata.ts +10 -4
  101. package/src/ingestion/walker.ts +485 -158
  102. package/src/llm/cache.ts +128 -84
  103. package/src/llm/http-inference.ts +112 -35
  104. package/src/llm/http-policy.ts +101 -0
  105. package/src/llm/httpEmbedding.ts +8 -1
  106. package/src/llm/httpGeneration.ts +5 -1
  107. package/src/llm/httpRerank.ts +5 -1
  108. package/src/llm/inference-scope.ts +15 -2
  109. package/src/llm/lazy-ports.ts +33 -3
  110. package/src/llm/lockfile.ts +34 -7
  111. package/src/llm/model-cleanup.ts +24 -0
  112. package/src/llm/native-worker/client.ts +23 -12
  113. package/src/llm/native-worker/dispatcher.ts +19 -9
  114. package/src/llm/native-worker/embedding-identity.ts +42 -16
  115. package/src/llm/native-worker/entry.ts +2 -1
  116. package/src/llm/native-worker/owner.ts +1 -0
  117. package/src/llm/native-worker/ports.ts +86 -23
  118. package/src/llm/native-worker/protocol.ts +386 -55
  119. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  120. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  121. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  122. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  123. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  124. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  125. package/src/llm/types.ts +14 -0
  126. package/src/mcp/context.ts +342 -23
  127. package/src/mcp/http-transport.ts +21 -3
  128. package/src/mcp/tool-profile-types.ts +62 -0
  129. package/src/mcp/tool-profile.ts +32 -56
  130. package/src/mcp/tools/context.ts +5 -1
  131. package/src/mcp/tools/index.ts +269 -191
  132. package/src/mcp/tools/links.ts +14 -6
  133. package/src/mcp/tools/query.ts +60 -37
  134. package/src/mcp/tools/vsearch.ts +25 -14
  135. package/src/pipeline/answer.ts +133 -40
  136. package/src/pipeline/claim-verification.ts +293 -189
  137. package/src/pipeline/claim-verifier.ts +6 -7
  138. package/src/pipeline/egress-lineage.ts +37 -26
  139. package/src/pipeline/exclude.ts +34 -11
  140. package/src/pipeline/expansion.ts +233 -19
  141. package/src/pipeline/explain.ts +17 -2
  142. package/src/pipeline/filters.ts +169 -33
  143. package/src/pipeline/graph-retrieval.ts +117 -61
  144. package/src/pipeline/hybrid.ts +626 -330
  145. package/src/pipeline/hydration.ts +86 -24
  146. package/src/pipeline/intent.ts +15 -7
  147. package/src/pipeline/owner-fusion.ts +61 -19
  148. package/src/pipeline/query-language.ts +15 -2
  149. package/src/pipeline/rerank.ts +15 -22
  150. package/src/pipeline/search.ts +193 -72
  151. package/src/pipeline/snippet.ts +15 -2
  152. package/src/pipeline/temporal.ts +51 -10
  153. package/src/pipeline/types.ts +7 -0
  154. package/src/pipeline/vsearch.ts +269 -154
  155. package/src/publish/attachment-raster.ts +2 -16
  156. package/src/publish/encrypted-export.ts +15 -5
  157. package/src/serve/browse-tree.ts +50 -42
  158. package/src/serve/connectors.ts +2 -1
  159. package/src/serve/context.ts +13 -4
  160. package/src/serve/doc-events.ts +3 -0
  161. package/src/serve/public/app.tsx +49 -21
  162. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  163. package/src/serve/public/components/CaptureModal.tsx +14 -10
  164. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  165. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  166. package/src/serve/public/globals.built.css +1 -1
  167. package/src/serve/public/globals.css +19 -0
  168. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  169. package/src/serve/public/lib/metadata-filter.ts +234 -9
  170. package/src/serve/public/pages/Browse.tsx +61 -27
  171. package/src/serve/public/pages/DocView.tsx +44 -25
  172. package/src/serve/public/pages/GraphView.tsx +8 -3
  173. package/src/serve/resident-runtime.ts +199 -48
  174. package/src/serve/routes/api.ts +98 -67
  175. package/src/serve/routes/links.ts +25 -5
  176. package/src/serve/server.ts +1370 -1180
  177. package/src/serve/spa-bundle-source.ts +52 -27
  178. package/src/serve/status.ts +101 -52
  179. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  180. package/src/serve/watch-reconciliation-shared.ts +42 -4
  181. package/src/serve/watch-reconciliation.ts +21 -8
  182. package/src/serve/watch-service-events.ts +7 -1
  183. package/src/serve/watch-service-hosts.ts +3 -1
  184. package/src/serve/watch-service.ts +46 -21
  185. package/src/serve/watch-snapshot-scan.ts +6 -15
  186. package/src/sessions/archive.ts +20 -8
  187. package/src/sessions/sanitize.ts +38 -18
  188. package/src/sessions/service.ts +180 -102
  189. package/src/store/migrations/037-performance-indexes.ts +56 -0
  190. package/src/store/migrations/038-vector-mirror-null-cosine.ts +47 -0
  191. package/src/store/migrations/039-vector-mirror-v2.ts +94 -0
  192. package/src/store/migrations/index.ts +6 -0
  193. package/src/store/sqlite/adapter.ts +1260 -651
  194. package/src/store/sqlite/chunking-policy.ts +15 -1
  195. package/src/store/sqlite/eligibility.ts +110 -70
  196. package/src/store/sqlite/graph-neighbors.ts +71 -46
  197. package/src/store/sqlite/graph-reference-state.ts +27 -3
  198. package/src/store/sqlite/graph-similarity.ts +59 -12
  199. package/src/store/sqlite/metadata-predicate.ts +123 -28
  200. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  201. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  202. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  203. package/src/store/types.ts +32 -0
  204. package/src/store/vector/coarse-router.ts +312 -0
  205. package/src/store/vector/eligibility.ts +39 -0
  206. package/src/store/vector/lazy.ts +17 -0
  207. package/src/store/vector/partition-index.ts +333 -59
  208. package/src/store/vector/proof-cache.ts +209 -0
  209. package/src/store/vector/runtime-compat.ts +6 -0
  210. package/src/store/vector/sqlite-vec.ts +270 -162
  211. package/src/store/vector/stats.ts +37 -73
  212. package/src/store/vector/status.ts +169 -53
  213. package/src/store/vector/stored-vectors.ts +131 -45
  214. package/src/store/vector/types.ts +19 -0
  215. package/src/store/vector/v2-mirror.ts +669 -0
  216. package/src/store/vector/variant-search.ts +1187 -111
  217. package/src/store/vector/variants.ts +964 -160
  218. package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
@@ -10,10 +10,18 @@ import type {
10
10
  DocumentChangeSet,
11
11
  } from "../store/types";
12
12
 
13
- import { parseFrontmatter } from "../ingestion/frontmatter";
13
+ import {
14
+ type FrontmatterResult,
15
+ parseFrontmatter,
16
+ } from "../ingestion/frontmatter";
14
17
  import { buildLineOffsets } from "../ingestion/position";
15
18
  import { type ExcludedRange, getExcludedRanges } from "../ingestion/strip";
16
- import { normalizeMarkdownPath, normalizeWikiName, parseLinks } from "./links";
19
+ import {
20
+ normalizeMarkdownPath,
21
+ normalizeWikiName,
22
+ type ParsedLink,
23
+ parseLinks,
24
+ } from "./links";
17
25
  import { extractSections } from "./sections";
18
26
 
19
27
  export type RelationMap = Record<string, string[]>;
@@ -86,8 +94,12 @@ const linkSummary = (
86
94
  return target ? `markdown:${target}${anchor}` : null;
87
95
  };
88
96
 
89
- const extractTypedEdges = (markdown: string): string[] => {
90
- const relations = parseFrontmatter(markdown).metadata.relations;
97
+ const extractTypedEdges = (
98
+ markdown: string,
99
+ frontmatter?: FrontmatterResult
100
+ ): string[] => {
101
+ const relations = (frontmatter ?? parseFrontmatter(markdown)).metadata
102
+ .relations;
91
103
  if (!isRelationMap(relations)) return [];
92
104
 
93
105
  const values: string[] = [];
@@ -108,19 +120,34 @@ export interface DocumentStructureOptions {
108
120
  /** Only Markdown sources carry links (matches link extraction at sync). */
109
121
  markdownSource: boolean;
110
122
  excludedRanges?: ExcludedRange[];
123
+ /** Optional precomputed line offsets (avoids recomputing buildLineOffsets). */
124
+ lineOffsets?: number[];
125
+ /** Optional precomputed parsed links (avoids running parseLinks twice). */
126
+ parsedLinks?: readonly ParsedLink[];
127
+ /** Optional pre-parsed frontmatter (avoids re-running parseFrontmatter). */
128
+ frontmatter?: FrontmatterResult;
111
129
  }
112
130
 
113
131
  export const extractDocumentStructure = (
114
132
  markdown: string,
115
133
  relPath: string,
116
134
  dateFields: Readonly<Record<string, string>> | null | undefined,
117
- { markdownSource, excludedRanges }: DocumentStructureOptions
135
+ {
136
+ markdownSource,
137
+ excludedRanges,
138
+ lineOffsets,
139
+ parsedLinks,
140
+ frontmatter,
141
+ }: DocumentStructureOptions
118
142
  ): DocumentStructureSnapshot => {
119
143
  const links = markdownSource
120
- ? parseLinks(
121
- markdown,
122
- buildLineOffsets(markdown),
123
- excludedRanges ?? getExcludedRanges(markdown)
144
+ ? (
145
+ parsedLinks ??
146
+ parseLinks(
147
+ markdown,
148
+ lineOffsets ?? buildLineOffsets(markdown),
149
+ excludedRanges ?? getExcludedRanges(markdown)
150
+ )
124
151
  )
125
152
  .map((link) => linkSummary(link, relPath))
126
153
  .filter((value): value is string => value !== null)
@@ -128,12 +155,12 @@ export const extractDocumentStructure = (
128
155
 
129
156
  return {
130
157
  headings: withOccurrences(
131
- extractSections(markdown).map(
158
+ extractSections(markdown, lineOffsets).map(
132
159
  ({ level, title }) => `${"#".repeat(level)} ${title.normalize("NFC")}`
133
160
  )
134
161
  ),
135
162
  links: withOccurrences(links),
136
- typedEdges: extractTypedEdges(markdown),
163
+ typedEdges: extractTypedEdges(markdown, frontmatter),
137
164
  dates: { ...dateFields },
138
165
  };
139
166
  };
@@ -338,21 +338,20 @@ export const planContextEvidence = async <T, P>(
338
338
  const indexName = canonicalizeIndexName(input.indexName);
339
339
  const collectionRequests = collections.length > 0 ? collections : [undefined];
340
340
  const requestCount = collectionRequests.length;
341
- const responses: SearchResults[] = [];
342
- for (const [requestIndex, collection] of collectionRequests.entries()) {
343
- const resultLimit = distributedLimit(
344
- input.limit,
345
- requestIndex,
346
- requestCount
347
- );
348
- const rerankLimit = distributedLimit(
349
- input.candidateLimit,
350
- requestIndex,
351
- requestCount
352
- );
353
- const hasRerankBudget = rerankLimit === undefined || rerankLimit > 0;
354
- responses.push(
355
- await deps.retrieve({
341
+ const responses: SearchResults[] = await Promise.all(
342
+ collectionRequests.map((collection, requestIndex) => {
343
+ const resultLimit = distributedLimit(
344
+ input.limit,
345
+ requestIndex,
346
+ requestCount
347
+ );
348
+ const rerankLimit = distributedLimit(
349
+ input.candidateLimit,
350
+ requestIndex,
351
+ requestCount
352
+ );
353
+ const hasRerankBudget = rerankLimit === undefined || rerankLimit > 0;
354
+ return deps.retrieve({
356
355
  query,
357
356
  collection,
358
357
  // The primary search is partitioned per collection; graph expansion
@@ -377,9 +376,9 @@ export const planContextEvidence = async <T, P>(
377
376
  candidateLimit:
378
377
  rerankLimit === undefined ? undefined : Math.max(1, rerankLimit),
379
378
  explain: input.explain,
380
- })
381
- );
382
- }
379
+ });
380
+ })
381
+ );
383
382
  const decoratedResults = responses
384
383
  .flatMap((response) => response.results)
385
384
  .map((result) => {
@@ -300,16 +300,12 @@ export const captureContextEvidenceSnapshot = async (
300
300
  };
301
301
 
302
302
  const referenceDocument = (
303
- documents: DocumentRow[],
304
- candidate: ContextRetrievalCandidate,
305
- indexName: string
303
+ documentsByKey: ReadonlyMap<string, DocumentRow[]>,
304
+ derivedDocidCache: Map<string, string>,
305
+ candidate: ContextRetrievalCandidate
306
306
  ): DocumentRow => {
307
307
  const result = candidate.result;
308
- const matches = documents.filter(
309
- (document) =>
310
- document.docid === result.docid &&
311
- decorateUriForIndex(document.uri, indexName) === result.uri
312
- );
308
+ const matches = documentsByKey.get(`${result.docid}\0${result.uri}`) ?? [];
313
309
  if (matches.length !== 1) {
314
310
  throw new ContextEvidenceError(
315
311
  "stored_provenance_mismatch",
@@ -320,6 +316,13 @@ const referenceDocument = (
320
316
  const parsedUri = parseUri(result.uri);
321
317
  const sourceHash = result.source.sourceHash;
322
318
  const mirrorHash = result.conversion?.mirrorHash;
319
+ let derivedDocid = document
320
+ ? derivedDocidCache.get(document.sourceHash)
321
+ : undefined;
322
+ if (document && derivedDocid === undefined) {
323
+ derivedDocid = deriveDocid(document.sourceHash);
324
+ derivedDocidCache.set(document.sourceHash, derivedDocid);
325
+ }
323
326
  if (
324
327
  !document ||
325
328
  !document.active ||
@@ -328,7 +331,7 @@ const referenceDocument = (
328
331
  result.source.relPath !== (document.recordSourcePath ?? document.relPath) ||
329
332
  sourceHash !== document.sourceHash ||
330
333
  mirrorHash !== document.mirrorHash ||
331
- deriveDocid(document.sourceHash) !== document.docid
334
+ derivedDocid !== document.docid
332
335
  ) {
333
336
  throw new ContextEvidenceError(
334
337
  "stored_provenance_mismatch",
@@ -368,8 +371,16 @@ export const materializeContextEvidenceCandidates = async (
368
371
  },
369
372
  ])
370
373
  );
374
+ const documentsByKey = new Map<string, DocumentRow[]>();
375
+ for (const document of documents) {
376
+ const key = `${document.docid}\0${decorateUriForIndex(document.uri, indexName)}`;
377
+ const list = documentsByKey.get(key);
378
+ if (list) list.push(document);
379
+ else documentsByKey.set(key, [document]);
380
+ }
381
+ const derivedDocidCache = new Map<string, string>();
371
382
  const alignedDocuments = candidates.map((candidate) =>
372
- referenceDocument(documents, candidate, indexName)
383
+ referenceDocument(documentsByKey, derivedDocidCache, candidate)
373
384
  );
374
385
  const mirrorHashes = [
375
386
  ...new Set(
@@ -509,11 +520,85 @@ export const materializeContextEvidenceCandidates = async (
509
520
  });
510
521
  };
511
522
 
523
+ interface SqliteMutationWatermark {
524
+ db: unknown;
525
+ dataVersion: number;
526
+ totalChanges: number;
527
+ contextGeneration: number;
528
+ }
529
+
530
+ interface SqliteMutationProbeStore {
531
+ getRawDb?: () => {
532
+ inTransaction?: boolean;
533
+ query: <R>(sql: string) => { get: () => R | null };
534
+ };
535
+ getContextGeneration?: () => number;
536
+ }
537
+
538
+ /**
539
+ * Capture a SQLite zero-mutation watermark when `store` is an unpatched
540
+ * SqliteAdapter not currently inside a transaction. Returns null for custom
541
+ * or monkey-patched stores so callers always run the full post-compile snapshot.
542
+ */
543
+ function captureSqliteMutationWatermark(
544
+ store: ContextEvidenceStore
545
+ ): SqliteMutationWatermark | null {
546
+ const probe = store as ContextEvidenceStore & SqliteMutationProbeStore;
547
+ if (
548
+ typeof probe.getRawDb !== "function" ||
549
+ typeof probe.getContextGeneration !== "function" ||
550
+ store.constructor?.name !== "SqliteAdapter" ||
551
+ Object.hasOwn(store, "getActivationIndexSnapshot") ||
552
+ Object.hasOwn(store, "getContexts") ||
553
+ Object.hasOwn(store, "getCollections")
554
+ ) {
555
+ return null;
556
+ }
557
+ try {
558
+ const db = probe.getRawDb();
559
+ if (!db || db.inTransaction) return null;
560
+ const dataVersionRow = db
561
+ .query<{ data_version: number }>("PRAGMA data_version")
562
+ .get();
563
+ const totalChangesRow = db
564
+ .query<{ total_changes: number }>(
565
+ "SELECT total_changes() AS total_changes"
566
+ )
567
+ .get();
568
+ if (!dataVersionRow || !totalChangesRow) return null;
569
+ return {
570
+ db,
571
+ dataVersion: dataVersionRow.data_version,
572
+ totalChanges: totalChangesRow.total_changes,
573
+ contextGeneration: probe.getContextGeneration(),
574
+ };
575
+ } catch {
576
+ return null;
577
+ }
578
+ }
579
+
580
+ function sameSqliteMutationWatermark(
581
+ before: SqliteMutationWatermark | null,
582
+ after: SqliteMutationWatermark | null
583
+ ): boolean {
584
+ return (
585
+ before !== null &&
586
+ after !== null &&
587
+ before.db === after.db &&
588
+ before.dataVersion === after.dataVersion &&
589
+ before.totalChanges === after.totalChanges &&
590
+ before.contextGeneration === after.contextGeneration
591
+ );
592
+ }
593
+
512
594
  /** Compile one evidence plan and discard it if either source snapshot drifted. */
513
595
  export const compileContextEvidence = async <P>(
514
596
  input: ContextEvidenceCompilerInput,
515
597
  deps: ContextEvidenceCompilerDeps<P>
516
598
  ): Promise<CompiledContextEvidence<P>> => {
599
+ // Capture the SQLite watermark BEFORE any initial snapshot read so a write
600
+ // landing mid-snapshot invalidates the zero-mutation fast path.
601
+ const watermarkBefore = captureSqliteMutationWatermark(deps.store);
517
602
  const before = await captureContextEvidenceSnapshot(
518
603
  deps.store,
519
604
  input.indexName,
@@ -538,22 +623,28 @@ export const compileContextEvidence = async <P>(
538
623
  projectCanonical: (draft) => deps.projectCanonical(draft, fingerprints),
539
624
  }
540
625
  );
541
- const after = await captureContextEvidenceSnapshot(
542
- deps.store,
543
- input.indexName,
544
- input.collections
545
- );
546
- if (before.indexFingerprint !== after.indexFingerprint) {
547
- throw new ContextEvidenceError(
548
- "index_changed_during_compile",
549
- "Index changed while Context evidence was being compiled"
550
- );
551
- }
552
- if (before.contextFingerprint !== after.contextFingerprint) {
553
- throw new ContextEvidenceError(
554
- "context_changed_during_compile",
555
- "Configured contexts changed while Context evidence was being compiled"
626
+ const watermarkAfter =
627
+ watermarkBefore !== null
628
+ ? captureSqliteMutationWatermark(deps.store)
629
+ : null;
630
+ if (!sameSqliteMutationWatermark(watermarkBefore, watermarkAfter)) {
631
+ const after = await captureContextEvidenceSnapshot(
632
+ deps.store,
633
+ input.indexName,
634
+ input.collections
556
635
  );
636
+ if (before.indexFingerprint !== after.indexFingerprint) {
637
+ throw new ContextEvidenceError(
638
+ "index_changed_during_compile",
639
+ "Index changed while Context evidence was being compiled"
640
+ );
641
+ }
642
+ if (before.contextFingerprint !== after.contextFingerprint) {
643
+ throw new ContextEvidenceError(
644
+ "context_changed_during_compile",
645
+ "Configured contexts changed while Context evidence was being compiled"
646
+ );
647
+ }
557
648
  }
558
649
  return { ...plan, snapshot: fingerprints };
559
650
  };
@@ -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,