@gmickel/gno 2.16.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 (46) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/SKILL.md +27 -0
  3. package/assets/skill/cli-reference.md +20 -13
  4. package/browser-extension/artifacts/{gno-browser-clipper-v2.16.0.zip → gno-browser-clipper-v2.17.0.zip} +0 -0
  5. package/browser-extension/artifacts/gno-browser-clipper-v2.17.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 +42 -2
  9. package/spec/db/schema.sql +53 -1
  10. package/spec/mcp.md +9 -3
  11. package/spec/output-schemas/doctor.schema.json +27 -0
  12. package/spec/output-schemas/retrieval-trace-payloads.schema.json +14 -0
  13. package/spec/output-schemas/search-results.schema.json +14 -0
  14. package/spec/output-schemas/status.schema.json +22 -0
  15. package/src/cli/commands/doctor.ts +101 -29
  16. package/src/cli/commands/links.ts +29 -5
  17. package/src/cli/commands/vec.ts +180 -8
  18. package/src/cli/program.ts +43 -0
  19. package/src/config/types.ts +6 -0
  20. package/src/core/retrieval-trace-session.ts +3 -0
  21. package/src/core/retrieval-trace.ts +9 -0
  22. package/src/core/vector-partition-status.ts +13 -0
  23. package/src/embed/variant-backlog.ts +36 -2
  24. package/src/mcp/tools/links.ts +7 -1
  25. package/src/pipeline/explain.ts +17 -2
  26. package/src/pipeline/hybrid.ts +28 -1
  27. package/src/pipeline/types.ts +7 -0
  28. package/src/pipeline/vsearch.ts +19 -2
  29. package/src/serve/public/globals.built.css +1 -1
  30. package/src/serve/routes/links.ts +7 -1
  31. package/src/store/migrations/038-vector-mirror-null-cosine.ts +47 -0
  32. package/src/store/migrations/039-vector-mirror-v2.ts +94 -0
  33. package/src/store/migrations/index.ts +4 -0
  34. package/src/store/sqlite/adapter.ts +117 -74
  35. package/src/store/vector/coarse-router.ts +312 -0
  36. package/src/store/vector/partition-index.ts +309 -18
  37. package/src/store/vector/proof-cache.ts +132 -26
  38. package/src/store/vector/runtime-compat.ts +6 -0
  39. package/src/store/vector/sqlite-vec.ts +43 -26
  40. package/src/store/vector/stats.ts +8 -0
  41. package/src/store/vector/status.ts +18 -1
  42. package/src/store/vector/types.ts +9 -0
  43. package/src/store/vector/v2-mirror.ts +669 -0
  44. package/src/store/vector/variant-search.ts +434 -20
  45. package/src/store/vector/variants.ts +480 -32
  46. package/browser-extension/artifacts/gno-browser-clipper-v2.16.0.zip.sha256 +0 -1
@@ -1,5 +1,6 @@
1
1
  /**
2
- * Per-connection input-hash proof cache keyed on `vector_variant_epoch.epoch`.
2
+ * Per-connection input-hash proof cache keyed on `vector_variant_epoch.epoch`,
3
+ * plus O(1) persisted null-cosine state lookup backed by `vector_mirror_state`.
3
4
  *
4
5
  * Every mutation to `documents`, `content_chunks`, `vector_owners`, or
5
6
  * `vector_variants` increments `vector_variant_epoch.epoch` via migration 028
@@ -15,6 +16,11 @@
15
16
  */
16
17
  import type { Database } from "bun:sqlite";
17
18
 
19
+ import {
20
+ hasNullCosineColumn,
21
+ probePartitionNullCosine,
22
+ } from "./partition-index";
23
+
18
24
  const MAX_CACHED_PROOFS = 100_000;
19
25
 
20
26
  const proofCaches = new WeakMap<
@@ -36,28 +42,34 @@ export function vectorProofKey(
36
42
  return `${model}\0${documentId}\0${mirrorHash}\0${seq}\0${inputHash}`;
37
43
  }
38
44
 
45
+ function readVariantEpoch(db: Database): number | null {
46
+ const row = db
47
+ .query<{ epoch: number }, []>(
48
+ "SELECT epoch FROM vector_variant_epoch WHERE id = 1"
49
+ )
50
+ .get();
51
+ return row ? row.epoch : null;
52
+ }
53
+
39
54
  function getEpochCache(
40
55
  db: Database,
41
56
  inOuterTransaction: boolean
42
57
  ): {
58
+ epoch: number;
43
59
  proofs: Map<string, boolean>;
44
60
  nullCosinePartitions: Map<string, boolean>;
45
61
  } | null {
46
62
  if (inOuterTransaction) {
47
63
  return null;
48
64
  }
49
- const row = db
50
- .query<{ epoch: number }, []>(
51
- "SELECT epoch FROM vector_variant_epoch WHERE id = 1"
52
- )
53
- .get();
54
- if (!row) {
65
+ const epoch = readVariantEpoch(db);
66
+ if (epoch === null) {
55
67
  return null;
56
68
  }
57
69
  let cache = proofCaches.get(db);
58
- if (cache?.epoch !== row.epoch || cache.proofs.size > MAX_CACHED_PROOFS) {
70
+ if (cache?.epoch !== epoch || cache.proofs.size > MAX_CACHED_PROOFS) {
59
71
  cache = {
60
- epoch: row.epoch,
72
+ epoch,
61
73
  proofs: new Map(),
62
74
  nullCosinePartitions: new Map(),
63
75
  };
@@ -73,31 +85,125 @@ export function provenOwners(
73
85
  return getEpochCache(db, inOuterTransaction)?.proofs ?? new Map();
74
86
  }
75
87
 
88
+ export interface NullCosineCheckResult {
89
+ found: boolean;
90
+ /**
91
+ * Non-null when this call had to scan `vector_variants` because
92
+ * `vector_mirror_state.null_cosine` was NULL, carrying the variant epoch
93
+ * observed inside the read snapshot for a guarded post-snapshot persist.
94
+ */
95
+ persistAfterSnapshot?: {
96
+ partitionId: string;
97
+ value: 0 | 1;
98
+ epoch: number;
99
+ };
100
+ }
101
+
76
102
  /**
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.
103
+ * Inspect whether `partitionId` contains any null-cosine variant.
104
+ *
105
+ * Checks persisted `vector_mirror_state.null_cosine` first (O(1) PK lookup,
106
+ * surviving cold CLI starts and unrelated document/chunk edits), then the
107
+ * connection-local epoch cache, and only falls back to the `LIMIT 1` probe
108
+ * when unknown (`NULL`). Never writes inside the read snapshot.
80
109
  */
81
- export function hasNullCosineVariant(
110
+ export function checkNullCosineVariant(
82
111
  db: Database,
83
112
  partitionId: string,
84
113
  inOuterTransaction: boolean
85
- ): boolean {
114
+ ): NullCosineCheckResult {
115
+ let mirrorCleanWithUnknown = false;
116
+ if (hasNullCosineColumn(db)) {
117
+ const persisted = db
118
+ .query<{ dirty: number; null_cosine: number | null }, [string]>(
119
+ "SELECT dirty, null_cosine FROM vector_mirror_state WHERE partition_id = ?"
120
+ )
121
+ .get(partitionId);
122
+ if (persisted?.dirty === 0) {
123
+ if (persisted.null_cosine === 0 || persisted.null_cosine === 1) {
124
+ return { found: persisted.null_cosine === 1 };
125
+ }
126
+ mirrorCleanWithUnknown = true;
127
+ }
128
+ }
129
+
86
130
  const cache = getEpochCache(db, inOuterTransaction);
87
131
  const cached = cache?.nullCosinePartitions.get(partitionId);
88
132
  if (cached !== undefined) {
89
- return cached;
133
+ return {
134
+ found: cached,
135
+ ...(mirrorCleanWithUnknown && cache
136
+ ? {
137
+ persistAfterSnapshot: {
138
+ partitionId,
139
+ value: cached ? 1 : 0,
140
+ epoch: cache.epoch,
141
+ },
142
+ }
143
+ : {}),
144
+ };
90
145
  }
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
- );
146
+
147
+ const found = probePartitionNullCosine(db, partitionId);
101
148
  cache?.nullCosinePartitions.set(partitionId, found);
102
- return found;
149
+ const epoch = cache?.epoch ?? readVariantEpoch(db);
150
+ return {
151
+ found,
152
+ ...(mirrorCleanWithUnknown && !inOuterTransaction && epoch !== null
153
+ ? {
154
+ persistAfterSnapshot: {
155
+ partitionId,
156
+ value: found ? 1 : 0,
157
+ epoch,
158
+ },
159
+ }
160
+ : {}),
161
+ };
162
+ }
163
+
164
+ /**
165
+ * True if the partition contains any variant whose cosine distance can be NULL
166
+ * (e.g. an all-zero vector or float32 norm underflow/overflow).
167
+ */
168
+ export function hasNullCosineVariant(
169
+ db: Database,
170
+ partitionId: string,
171
+ inOuterTransaction: boolean
172
+ ): boolean {
173
+ return checkNullCosineVariant(db, partitionId, inOuterTransaction).found;
174
+ }
175
+
176
+ /**
177
+ * Best-effort guarded persist of a probed `null_cosine` flag after the search's
178
+ * read snapshot closes. Skips on query-only connections, active transactions,
179
+ * changed variant epoch, dirty mirrors, or lock contention.
180
+ */
181
+ export function persistNullCosineAfterSnapshot(
182
+ writerDb: Database,
183
+ pending: NonNullable<NullCosineCheckResult["persistAfterSnapshot"]>
184
+ ): boolean {
185
+ if (writerDb.inTransaction) return false;
186
+ try {
187
+ const queryOnly =
188
+ writerDb.query<{ query_only: number }, []>("PRAGMA query_only").get()
189
+ ?.query_only === 1;
190
+ if (queryOnly) return false;
191
+ if (!hasNullCosineColumn(writerDb)) return false;
192
+ writerDb.run(
193
+ `UPDATE vector_mirror_state
194
+ SET null_cosine = ?
195
+ WHERE partition_id = ?
196
+ AND dirty = 0
197
+ AND null_cosine IS NULL
198
+ AND (SELECT epoch FROM vector_variant_epoch WHERE id = 1) = ?`,
199
+ [pending.value, pending.partitionId, pending.epoch]
200
+ );
201
+ return (
202
+ (writerDb.query<{ c: number }, []>("SELECT changes() AS c").get()?.c ??
203
+ 0) > 0
204
+ );
205
+ } catch {
206
+ // Busy/locked writer or read-only file: skip silently, probe cache stays valid.
207
+ return false;
208
+ }
103
209
  }
@@ -18,6 +18,10 @@ import { getVariantModelFingerprint } from "../../embed/fingerprint";
18
18
  import { runtimeCallerKey } from "../../llm/native-worker/embedding-identity";
19
19
  import { formatDocForEmbedding } from "../../pipeline/contextual";
20
20
  import { decodeEmbedding } from "./sqlite-vec";
21
+ import {
22
+ dropV2PartitionMirrorInTx,
23
+ rebuildV2PartitionMirrorInTx,
24
+ } from "./v2-mirror";
21
25
  import {
22
26
  embeddingInputHash,
23
27
  loadSqliteVec,
@@ -373,6 +377,8 @@ async function rekeyLegacy(
373
377
  [newId]
374
378
  );
375
379
  db.exec(`DROP TABLE IF EXISTS vec_v1_${oldId}`);
380
+ dropV2PartitionMirrorInTx(db, oldId);
381
+ rebuildV2PartitionMirrorInTx(db, newId, primary.dimensions);
376
382
  }).immediate();
377
383
  return { kind: "rekeyed", msPerChunk };
378
384
  }
@@ -167,6 +167,8 @@ export async function createVectorIndexPort(
167
167
 
168
168
  // A query-only (read) connection cannot create the table. A missing table
169
169
  // there means no vectors were ever stored for this model: search is empty.
170
+ // Once a v1 partition is active for this model, never create an unused legacy
171
+ // vec_<hash> table; variant search runs through vec_v1_<partition> instead.
170
172
  const tableExists =
171
173
  db
172
174
  .query<{ found: number }, [string]>(
@@ -176,11 +178,24 @@ export async function createVectorIndexPort(
176
178
  const queryOnly =
177
179
  db.query<{ query_only: number }, []>("PRAGMA query_only").get()
178
180
  ?.query_only === 1;
181
+ const hasActivatedPartition =
182
+ db
183
+ .query<{ found: number }, []>(
184
+ "SELECT 1 AS found FROM sqlite_master WHERE type = 'table' AND name = 'vector_partitions'"
185
+ )
186
+ .get() !== null &&
187
+ db
188
+ .query<{ found: number }, [string]>(
189
+ "SELECT 1 AS found FROM vector_partitions WHERE model = ? AND state = 'active' AND activated_epoch IS NOT NULL LIMIT 1"
190
+ )
191
+ .get(model) !== null;
179
192
  const noVectorsYet = searchAvailable && !tableExists && queryOnly;
193
+ const partitionActiveNoLegacy =
194
+ searchAvailable && !tableExists && hasActivatedPartition;
180
195
 
181
- // Create per-model vec0 table if extension available
196
+ // Create per-model vec0 table if extension available and no v1 partition is active
182
197
  // Graceful degradation: if table creation fails, storage still works
183
- if (searchAvailable && !tableExists && !queryOnly) {
198
+ if (searchAvailable && !tableExists && !queryOnly && !hasActivatedPartition) {
184
199
  try {
185
200
  db.exec(`
186
201
  CREATE VIRTUAL TABLE IF NOT EXISTS ${tableName} USING vec0(
@@ -207,33 +222,29 @@ export async function createVectorIndexPort(
207
222
  DELETE FROM content_vectors WHERE mirror_hash = ? AND model = ?
208
223
  `);
209
224
 
210
- // Prepared statements for vec0 table (if available)
211
- const deleteVecChunkStmt =
212
- searchAvailable && !noVectorsYet
213
- ? db.prepare(`DELETE FROM ${tableName} WHERE chunk_id = ?`)
214
- : null;
225
+ // Prepared statements for vec0 table (if available and legacy table exists)
226
+ const hasLegacyVecTable =
227
+ searchAvailable && !noVectorsYet && !partitionActiveNoLegacy;
228
+ const deleteVecChunkStmt = hasLegacyVecTable
229
+ ? db.prepare(`DELETE FROM ${tableName} WHERE chunk_id = ?`)
230
+ : null;
215
231
 
216
- const insertVecStmt =
217
- searchAvailable && !noVectorsYet
218
- ? db.prepare(
219
- `INSERT INTO ${tableName} (chunk_id, embedding) VALUES (?, ?)`
220
- )
221
- : null;
232
+ const insertVecStmt = hasLegacyVecTable
233
+ ? db.prepare(`INSERT INTO ${tableName} (chunk_id, embedding) VALUES (?, ?)`)
234
+ : null;
222
235
 
223
- const searchStmt =
224
- searchAvailable && !noVectorsYet
225
- ? db.prepare(`
236
+ const searchStmt = hasLegacyVecTable
237
+ ? db.prepare(`
226
238
  SELECT chunk_id, distance
227
239
  FROM ${tableName}
228
240
  WHERE embedding MATCH ?
229
241
  AND k = ?
230
242
  `)
231
- : null;
243
+ : null;
232
244
 
233
- const deleteVecStmt =
234
- searchAvailable && !noVectorsYet
235
- ? db.prepare(`DELETE FROM ${tableName} WHERE chunk_id LIKE ? || ':%'`)
236
- : null;
245
+ const deleteVecStmt = hasLegacyVecTable
246
+ ? db.prepare(`DELETE FROM ${tableName} WHERE chunk_id LIKE ? || ':%'`)
247
+ : null;
237
248
 
238
249
  // Track if vec0 writes failed this session (needs sync)
239
250
  let vecDirty = false;
@@ -357,7 +368,10 @@ export async function createVectorIndexPort(
357
368
  k: number,
358
369
  searchOptions?: VectorSearchOptions
359
370
  ): Promise<StoreResult<VectorSearchResult[]>> {
360
- if (!searchAvailable || !(searchStmt || noVectorsYet)) {
371
+ if (
372
+ !searchAvailable ||
373
+ !(searchStmt || noVectorsYet || partitionActiveNoLegacy)
374
+ ) {
361
375
  return Promise.resolve(
362
376
  err("VEC_SEARCH_UNAVAILABLE", formatUnavailableMessage(loadError))
363
377
  );
@@ -549,7 +563,10 @@ export async function createVectorIndexPort(
549
563
  limits: number[],
550
564
  searchOptions?: VectorSearchOptions
551
565
  ): Promise<StoreResult<VectorSearchResult[][]>> {
552
- if (!searchAvailable || !(searchStmt || noVectorsYet)) {
566
+ if (
567
+ !searchAvailable ||
568
+ !(searchStmt || noVectorsYet || partitionActiveNoLegacy)
569
+ ) {
553
570
  return err(
554
571
  "VEC_SEARCH_UNAVAILABLE",
555
572
  formatUnavailableMessage(loadError)
@@ -612,8 +629,8 @@ export async function createVectorIndexPort(
612
629
  },
613
630
 
614
631
  rebuildVecIndex(): Promise<StoreResult<void>> {
615
- if (!searchAvailable) {
616
- return Promise.resolve(ok(undefined)); // No-op if no vec support
632
+ if (!searchAvailable || partitionActiveNoLegacy) {
633
+ return Promise.resolve(ok(undefined)); // No-op if no vec support or v1 active without legacy table
617
634
  }
618
635
 
619
636
  try {
@@ -646,7 +663,7 @@ export async function createVectorIndexPort(
646
663
  },
647
664
 
648
665
  syncVecIndex(): Promise<StoreResult<{ added: number; removed: number }>> {
649
- if (!searchAvailable) {
666
+ if (!searchAvailable || partitionActiveNoLegacy) {
650
667
  return Promise.resolve(ok({ added: 0, removed: 0 }));
651
668
  }
652
669
 
@@ -11,6 +11,8 @@ import type { StoreResult } from "../types";
11
11
  import type { BacklogItem, VectorStatsPort } from "./types";
12
12
 
13
13
  import { err, ok } from "../types";
14
+ import { currentOwnerCount } from "./runtime-compat";
15
+ import { storedVectorPartition } from "./status";
14
16
 
15
17
  const statsDatabases = new WeakMap<VectorStatsPort, Database>();
16
18
 
@@ -56,6 +58,12 @@ export function createVectorStatsPort(db: Database): VectorStatsPort {
56
58
  const port: VectorStatsPort = {
57
59
  countVectors(model: string): Promise<StoreResult<number>> {
58
60
  try {
61
+ const partition = storedVectorPartition(db, model);
62
+ if (partition) {
63
+ return Promise.resolve(
64
+ ok(currentOwnerCount(db, partition.partitionId))
65
+ );
66
+ }
59
67
  const result = db
60
68
  .query<{ count: number }, [string]>(
61
69
  "SELECT COUNT(*) as count FROM content_vectors WHERE model = ?"
@@ -11,6 +11,12 @@ import {
11
11
  retrievalUse,
12
12
  selectRuntimePartition,
13
13
  } from "./runtime-compat";
14
+ import {
15
+ dropV2PartitionMirrorInTx,
16
+ getV2MirrorStatus,
17
+ hasV2MirrorTables,
18
+ type V2MirrorStatusInfo,
19
+ } from "./v2-mirror";
14
20
  import {
15
21
  embeddingInputHash,
16
22
  loadSqliteVec,
@@ -52,6 +58,8 @@ export interface VectorPartitionStatus {
52
58
  compatibleRuntimes: string[];
53
59
  /** Runtimes measured incompatible; they need another partition or lexical. */
54
60
  incompatibleRuntimes: string[];
61
+ /** Bit coarse vec0 mirror status (fn-235); omitted on pre-v39 schemas. */
62
+ coarseMirror?: V2MirrorStatusInfo;
55
63
  }
56
64
 
57
65
  /** The calling process's runtime, resolved exactly as its queries resolve it. */
@@ -225,6 +233,7 @@ export function listVectorPartitions(
225
233
  const runtimes = db.prepare<{ label: string }, [string, string]>(
226
234
  "SELECT DISTINCT label FROM vector_runtime_verdicts WHERE partition_id = ? AND verdict = ? ORDER BY label"
227
235
  );
236
+ const trackV2 = hasV2MirrorTables(db);
228
237
  return partitions.map(
229
238
  (p): VectorPartitionStatus => ({
230
239
  id: p.partition_id,
@@ -247,6 +256,11 @@ export function listVectorPartitions(
247
256
  incompatibleRuntimes: runtimes
248
257
  .all(p.partition_id, "incompatible")
249
258
  .map((row) => row.label),
259
+ ...(trackV2
260
+ ? {
261
+ coarseMirror: getV2MirrorStatus(db, p.partition_id, p.dimensions),
262
+ }
263
+ : {}),
250
264
  })
251
265
  );
252
266
  })();
@@ -539,9 +553,11 @@ export async function dropVectorPartition(
539
553
  : `Refusing to drop active partition ${partition.id.slice(0, 12)}: other runtimes may read it, or it awaits its one-time re-key`,
540
554
  };
541
555
  const table = `vec_v1_${partition.id}`;
556
+ const v2Table = `vec_v2_${partition.id}`;
542
557
  if (
543
558
  !vecLoaded &&
544
- db.query("SELECT 1 FROM sqlite_master WHERE name = ?").get(table)
559
+ (db.query("SELECT 1 FROM sqlite_master WHERE name = ?").get(table) ||
560
+ db.query("SELECT 1 FROM sqlite_master WHERE name = ?").get(v2Table))
545
561
  )
546
562
  return {
547
563
  ok: false,
@@ -557,6 +573,7 @@ export async function dropVectorPartition(
557
573
  ])
558
574
  db.run(statement, [partition.id]);
559
575
  db.exec(`DROP TABLE IF EXISTS ${table}`);
576
+ dropV2PartitionMirrorInTx(db, partition.id);
560
577
  return { ok: true, partition };
561
578
  })
562
579
  .immediate();
@@ -6,6 +6,9 @@
6
6
  */
7
7
 
8
8
  import type { DocumentEligibilityOptions, StoreResult } from "../types";
9
+ import type { VectorRouteInfo } from "./coarse-router";
10
+
11
+ export type { VectorRouteInfo, VectorRouteKind } from "./coarse-router";
9
12
 
10
13
  /** Full effective embedding identity, including truncation/runtime policy. */
11
14
  export interface VectorVariantIdentity {
@@ -53,6 +56,12 @@ export interface VectorSearchOptions {
53
56
  allowedMirrorHashes?: string[];
54
57
  /** Exact active owner/chunk domain, applied before the nearest-neighbor budget. */
55
58
  eligibility?: DocumentEligibilityOptions & { language?: string };
59
+ /** Force exact search even when coarse bit mirror routing is enabled (self-check/evals/benchmarks). */
60
+ exact?: boolean;
61
+ /** Enable cost-routed coarse two-stage bit vec0 search (default false per fn-235 R1). */
62
+ coarseVectorSearch?: boolean;
63
+ /** Optional observer invoked with the chosen vector route metadata for --explain and traces. */
64
+ onRoute?: (info: VectorRouteInfo) => void;
56
65
  }
57
66
 
58
67
  /** Vector search result */