@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
@@ -673,6 +673,11 @@ export interface GraphReferenceDocument {
673
673
  contentType: string | null;
674
674
  }
675
675
 
676
+ /** Lean scalar document identity for graph reconciliation (avoids SELECT * JSON parsing). */
677
+ export interface GraphDocumentIdentity extends GraphReferenceDocument {
678
+ active: boolean;
679
+ }
680
+
676
681
  export interface GraphFrontmatterReference {
677
682
  edgeType: string;
678
683
  target: string;
@@ -700,6 +705,8 @@ export interface GraphReferenceStore {
700
705
  readInventory(): GraphReferenceInventory[];
701
706
  /** Active parsed-link sources matching any old/new target candidate. */
702
707
  incomingLinkSources(identities: GraphReferenceDocument[]): number[];
708
+ /** Frontmatter-relation sources targeting any of the given `#docid` strings. */
709
+ docidReferenceSources?(docids: readonly string[]): number[];
703
710
  writeInventory(inventory: GraphReferenceInventory): void;
704
711
  complete(expectedEpoch: number): void;
705
712
  }
@@ -774,6 +781,8 @@ export interface MemoryEligibleDocumentsOptions {
774
781
  /** Normalized scopes; any-intersection semantics. */
775
782
  scopes: string[];
776
783
  excludeSuperseded?: boolean;
784
+ /** Optional positive row cap (e.g. `1` for existence probes). */
785
+ limit?: number;
777
786
  }
778
787
 
779
788
  /** Minimal identity of a memory record eligible for managed recall. */
@@ -2337,6 +2346,9 @@ export interface StorePort {
2337
2346
  /** Missing capability or stale state requires full graph reconciliation. */
2338
2347
  graphReferenceStore?(): GraphReferenceStore;
2339
2348
 
2349
+ /** Lean scalar document identities for graph reconciliation (avoids SELECT * JSON parsing). */
2350
+ listGraphDocumentIdentities?(): Promise<StoreResult<GraphDocumentIdentity[]>>;
2351
+
2340
2352
  /**
2341
2353
  * Get backlinks pointing to a document.
2342
2354
  * Uses target_ref_norm for matching (wiki=normalized title with path fallbacks, markdown=rel_path).
@@ -2492,4 +2504,24 @@ export interface StorePort {
2492
2504
  collection: string,
2493
2505
  options: { mode: "stale" | "all"; activeModel?: string }
2494
2506
  ): Promise<StoreResult<EmbeddingCleanupStats>>;
2507
+
2508
+ // ─────────────────────────────────────────────────────────────────────────
2509
+ // LLM Cache (optional)
2510
+ // ─────────────────────────────────────────────────────────────────────────
2511
+
2512
+ /**
2513
+ * Read a non-expired value from the persistent `llm_cache` table.
2514
+ * Optional: mocks or read-only custom stores may omit this method.
2515
+ */
2516
+ getLlmCache?(key: string): Promise<StoreResult<string | null>>;
2517
+
2518
+ /**
2519
+ * Write a value to the persistent `llm_cache` table.
2520
+ * Read-only connections and write-lock contention should no-op cleanly.
2521
+ */
2522
+ setLlmCache?(
2523
+ key: string,
2524
+ value: string,
2525
+ expiresAt?: string
2526
+ ): Promise<StoreResult<void>>;
2495
2527
  }
@@ -34,3 +34,42 @@ export function buildEligibleVectorQuery(
34
34
  params,
35
35
  };
36
36
  }
37
+
38
+ /**
39
+ * Set-driven eligible `(mirror_hash, seq)` domain for legacy vector search:
40
+ * deduplicates eligible `mirror_hash`es first and joins into `content_chunks`
41
+ * and `content_vectors` by key instead of scanning every vector row.
42
+ */
43
+ export function buildEligibleVectorChunksQuery(
44
+ db: Database,
45
+ options: VectorSearchOptions
46
+ ): { sql: string; params: (string | number)[] } {
47
+ const eligibility = options.eligibility ?? {};
48
+ const owners = buildEligibleDocumentQuery(
49
+ { ...eligibility, semanticMetadata: true },
50
+ db
51
+ );
52
+ const mirrorConditions: string[] = [];
53
+ const params: (string | number)[] = [...owners.params];
54
+ if (options.allowedMirrorHashes !== undefined) {
55
+ mirrorConditions.push("em.mirror_hash IN (SELECT value FROM json_each(?))");
56
+ params.push(JSON.stringify(options.allowedMirrorHashes));
57
+ }
58
+ const chunkConditions: string[] = [];
59
+ if (eligibility.language) {
60
+ chunkConditions.push("cc.language = ?");
61
+ params.push(eligibility.language);
62
+ }
63
+ const mirrorFilter = mirrorConditions.length
64
+ ? ` AND ${mirrorConditions.join(" AND ")}`
65
+ : "";
66
+ const chunkWhere = chunkConditions.length
67
+ ? ` WHERE ${chunkConditions.join(" AND ")}`
68
+ : "";
69
+ return {
70
+ sql: `SELECT cc.mirror_hash, cc.seq
71
+ FROM (SELECT DISTINCT mirror_hash FROM (${owners.sql})) em
72
+ JOIN content_chunks cc ON cc.mirror_hash = em.mirror_hash${mirrorFilter}${chunkWhere}`,
73
+ params,
74
+ };
75
+ }
@@ -72,6 +72,23 @@ export async function createLazyVectorIndex(
72
72
  async searchNearest(embedding, k, options) {
73
73
  return (await get()).searchNearest(embedding, k, options);
74
74
  },
75
+ async searchNearestBatch(embeddings, limits, options) {
76
+ const port = await get();
77
+ if (port.searchNearestBatch) {
78
+ return port.searchNearestBatch(embeddings, limits, options);
79
+ }
80
+ const results = [];
81
+ for (let i = 0; i < embeddings.length; i++) {
82
+ const res = await port.searchNearest(
83
+ embeddings[i]!,
84
+ limits[i]!,
85
+ options
86
+ );
87
+ if (!res.ok) return res;
88
+ results.push(res.value);
89
+ }
90
+ return { ok: true as const, value: results };
91
+ },
75
92
  async rebuildVecIndex() {
76
93
  return (await get()).rebuildVecIndex();
77
94
  },
@@ -41,21 +41,9 @@ const createTable = (db: Database, partition: StoredPartition): void => {
41
41
  )`);
42
42
  };
43
43
 
44
- const insertVariants = (
45
- db: Database,
46
- partition: StoredPartition,
47
- rows: Iterable<{ variantId: number; embedding: Uint8Array }>
48
- ): number => {
49
- let inserted = 0;
50
- for (const row of rows) {
51
- db.run(
52
- `INSERT INTO ${tableName(partition)}(variant_id, embedding) VALUES (?, ?)`,
53
- [row.variantId, row.embedding]
54
- );
55
- inserted += 1;
56
- }
57
- return inserted;
58
- };
44
+ const logicalChanges = (db: Database): number =>
45
+ db.query<{ changes: number }, []>("SELECT changes() AS changes").get()
46
+ ?.changes ?? 0;
59
47
 
60
48
  /**
61
49
  * Remove index rows without a matching variant (orphans and stale
@@ -69,27 +57,25 @@ export function syncPartitionIndex(
69
57
  return db
70
58
  .transaction(() => {
71
59
  createTable(db, partition);
72
- const stale = db
73
- .query<{ variantId: number }, [string]>(`
74
- SELECT x.variant_id AS variantId FROM ${table} x
75
- LEFT JOIN vector_variants v ON v.variant_id = x.variant_id
76
- AND v.partition_id = ?
77
- WHERE v.variant_id IS NULL OR x.embedding != v.embedding
78
- `)
79
- .all(partition.partitionId);
80
- for (const { variantId } of stale) {
81
- db.run(`DELETE FROM ${table} WHERE variant_id = ?`, [variantId]);
82
- }
83
- const missing = db
84
- .query<{ variantId: number; embedding: Uint8Array }, [string]>(`
85
- SELECT v.variant_id AS variantId, v.embedding FROM vector_variants v
86
- LEFT JOIN ${table} x ON x.variant_id = v.variant_id
87
- WHERE v.partition_id = ? AND x.variant_id IS NULL
88
- `)
89
- .all(partition.partitionId);
90
- const added = insertVariants(db, partition, missing);
60
+ db.query(
61
+ `DELETE FROM ${table}
62
+ WHERE variant_id IN (
63
+ SELECT x.variant_id FROM ${table} x
64
+ LEFT JOIN vector_variants v ON v.variant_id = x.variant_id
65
+ AND v.partition_id = ?
66
+ WHERE v.variant_id IS NULL OR x.embedding != v.embedding
67
+ )`
68
+ ).run(partition.partitionId);
69
+ const removed = logicalChanges(db);
70
+ db.query(
71
+ `INSERT INTO ${table}(variant_id, embedding)
72
+ SELECT v.variant_id, v.embedding FROM vector_variants v
73
+ LEFT JOIN ${table} x ON x.variant_id = v.variant_id
74
+ WHERE v.partition_id = ? AND x.variant_id IS NULL`
75
+ ).run(partition.partitionId);
76
+ const added = logicalChanges(db);
91
77
  markMirrorClean(db, partition.partitionId);
92
- return { added, removed: stale.length };
78
+ return { added, removed };
93
79
  })
94
80
  .immediate();
95
81
  }
@@ -99,19 +85,16 @@ export function rebuildPartitionIndex(
99
85
  db: Database,
100
86
  partition: StoredPartition
101
87
  ): number {
88
+ const table = tableName(partition);
102
89
  return db
103
90
  .transaction(() => {
104
- db.exec(`DROP TABLE IF EXISTS ${tableName(partition)}`);
91
+ db.exec(`DROP TABLE IF EXISTS ${table}`);
105
92
  createTable(db, partition);
106
- const inserted = insertVariants(
107
- db,
108
- partition,
109
- db
110
- .query<{ variantId: number; embedding: Uint8Array }, [string]>(
111
- "SELECT variant_id AS variantId, embedding FROM vector_variants WHERE partition_id = ?"
112
- )
113
- .iterate(partition.partitionId)
114
- );
93
+ db.query(
94
+ `INSERT INTO ${table}(variant_id, embedding)
95
+ SELECT variant_id, embedding FROM vector_variants WHERE partition_id = ?`
96
+ ).run(partition.partitionId);
97
+ const inserted = logicalChanges(db);
115
98
  markMirrorClean(db, partition.partitionId);
116
99
  return inserted;
117
100
  })
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Per-connection input-hash proof cache keyed on `vector_variant_epoch.epoch`.
3
+ *
4
+ * Every mutation to `documents`, `content_chunks`, `vector_owners`, or
5
+ * `vector_variants` increments `vector_variant_epoch.epoch` via migration 028
6
+ * triggers, so proofs survive unrelated writes (`retrieval_traces`,
7
+ * `llm_cache`, `egress_audit_receipts`, `vector_runtime_callers`) while still
8
+ * invalidating across connections whenever document titles or chunk text change.
9
+ *
10
+ * When a caller is already inside an uncommitted outer transaction
11
+ * (`inOuterTransaction === true`), a call-local Map is returned so a later
12
+ * `ROLLBACK` can never poison the connection-shared cache.
13
+ *
14
+ * @module src/store/vector/proof-cache
15
+ */
16
+ import type { Database } from "bun:sqlite";
17
+
18
+ const MAX_CACHED_PROOFS = 100_000;
19
+
20
+ const proofCaches = new WeakMap<
21
+ Database,
22
+ {
23
+ epoch: number;
24
+ proofs: Map<string, boolean>;
25
+ nullCosinePartitions: Map<string, boolean>;
26
+ }
27
+ >();
28
+
29
+ export function vectorProofKey(
30
+ model: string,
31
+ documentId: number,
32
+ mirrorHash: string,
33
+ seq: number,
34
+ inputHash: string
35
+ ): string {
36
+ return `${model}\0${documentId}\0${mirrorHash}\0${seq}\0${inputHash}`;
37
+ }
38
+
39
+ function getEpochCache(
40
+ db: Database,
41
+ inOuterTransaction: boolean
42
+ ): {
43
+ proofs: Map<string, boolean>;
44
+ nullCosinePartitions: Map<string, boolean>;
45
+ } | null {
46
+ if (inOuterTransaction) {
47
+ return null;
48
+ }
49
+ const row = db
50
+ .query<{ epoch: number }, []>(
51
+ "SELECT epoch FROM vector_variant_epoch WHERE id = 1"
52
+ )
53
+ .get();
54
+ if (!row) {
55
+ return null;
56
+ }
57
+ let cache = proofCaches.get(db);
58
+ if (cache?.epoch !== row.epoch || cache.proofs.size > MAX_CACHED_PROOFS) {
59
+ cache = {
60
+ epoch: row.epoch,
61
+ proofs: new Map(),
62
+ nullCosinePartitions: new Map(),
63
+ };
64
+ proofCaches.set(db, cache);
65
+ }
66
+ return cache;
67
+ }
68
+
69
+ export function provenOwners(
70
+ db: Database,
71
+ inOuterTransaction: boolean
72
+ ): Map<string, boolean> {
73
+ return getEpochCache(db, inOuterTransaction)?.proofs ?? new Map();
74
+ }
75
+
76
+ /**
77
+ * True if the partition contains any variant whose cosine distance can be NULL
78
+ * (e.g. an all-zero vector). Cached per (db, partitionId, epoch) so the vec0
79
+ * fast path stays O(1) while preserving exact SQLite NULLS FIRST parity.
80
+ */
81
+ export function hasNullCosineVariant(
82
+ db: Database,
83
+ partitionId: string,
84
+ inOuterTransaction: boolean
85
+ ): boolean {
86
+ const cache = getEpochCache(db, inOuterTransaction);
87
+ const cached = cache?.nullCosinePartitions.get(partitionId);
88
+ if (cached !== undefined) {
89
+ return cached;
90
+ }
91
+ const found = Boolean(
92
+ db
93
+ .query<unknown, [string]>(
94
+ `SELECT 1 FROM vector_variants
95
+ WHERE partition_id = ?
96
+ AND vec_distance_cosine(embedding, embedding) IS NULL
97
+ LIMIT 1`
98
+ )
99
+ .get(partitionId)
100
+ );
101
+ cache?.nullCosinePartitions.set(partitionId, found);
102
+ return found;
103
+ }