@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
@@ -0,0 +1,312 @@
1
+ /**
2
+ * Cost-based vector search router and centralized constants (fn-235).
3
+ *
4
+ * Every path returns exact float32 cosine distances. Small scopes and every
5
+ * filtered search stay on existing exact paths; large unfiltered or
6
+ * collection-scoped searches route to the two-stage bit coarse mirror when
7
+ * enabled, clean, and self-checked above the recall floor.
8
+ *
9
+ * @module src/store/vector/coarse-router
10
+ */
11
+ import type { Database } from "bun:sqlite";
12
+
13
+ import type { VectorSearchOptions } from "./types";
14
+
15
+ /**
16
+ * Single source of truth for fn-235 router and self-check constants.
17
+ * Enabled by default per owner decision (2026-11-23), gated by the per-index
18
+ * build-time recall self-check (floor 0.95) and controllable via
19
+ * `coarseVectorSearch: false`.
20
+ */
21
+ export const COARSE_ROUTER_DEFAULTS = {
22
+ /** Default config switch (ON; set `coarseVectorSearch: false` to disable). */
23
+ enabledByDefault: true,
24
+ /** Exact-cost budget in microseconds (100 ms). */
25
+ exactBudgetUs: 100_000,
26
+ /** Exact SQL scan per-vector fixed overhead (µs). */
27
+ exactFixedUsPerVec: 1.05,
28
+ /** Exact SQL scan per-vector per-query cosine cost (µs). */
29
+ exactQueryUsPerVec: 0.82,
30
+ /** Oversample factor: coarseK = clamp(oversampleFactor * k, minCoarseK, maxCoarseK). */
31
+ oversampleFactor: 25,
32
+ minCoarseK: 200,
33
+ maxCoarseK: 500,
34
+ /** Maximum query k eligible for two-stage routing. */
35
+ maxCoarseQueryK: 40,
36
+ /** Maximum combined stage-1 candidates across multiple collections. */
37
+ maxMultiCollectionCandidates: 2000,
38
+ /** Build-time recall self-check constants. */
39
+ selfCheckQueries: 16,
40
+ selfCheckTopK: 10,
41
+ selfCheckCoarseK: 200,
42
+ selfCheckRecallFloor: 0.95,
43
+ } as const;
44
+
45
+ export type VectorRouteKind = "exact-sql" | "exact-vec0" | "coarse-bit";
46
+
47
+ export interface VectorRouteInfo {
48
+ route: VectorRouteKind;
49
+ /** Number of mirror rows in scope (or total partition variants when unavailable). */
50
+ mirrorRows: number;
51
+ /** Stage-1 coarse candidate count (coarse-bit only). */
52
+ coarseK?: number;
53
+ /** Distinct variants rescored in stage 2 (coarse-bit only). */
54
+ rescored?: number;
55
+ }
56
+
57
+ export function isV2CompatibleDimensions(dimensions: number): boolean {
58
+ return Number.isInteger(dimensions) && dimensions > 0 && dimensions % 8 === 0;
59
+ }
60
+
61
+ export function v2TableName(partitionId: string): string {
62
+ return `vec_v2_${partitionId}`;
63
+ }
64
+
65
+ export function computeCoarseK(k: number): number {
66
+ return Math.max(
67
+ COARSE_ROUTER_DEFAULTS.minCoarseK,
68
+ Math.min(
69
+ COARSE_ROUTER_DEFAULTS.maxCoarseK,
70
+ COARSE_ROUTER_DEFAULTS.oversampleFactor * k
71
+ )
72
+ );
73
+ }
74
+
75
+ export function estimateExactCostUs(
76
+ mirrorRows: number,
77
+ queryCount: number
78
+ ): number {
79
+ return (
80
+ mirrorRows *
81
+ (COARSE_ROUTER_DEFAULTS.exactFixedUsPerVec +
82
+ COARSE_ROUTER_DEFAULTS.exactQueryUsPerVec * Math.max(1, queryCount))
83
+ );
84
+ }
85
+
86
+ export function isPartitionAboveBudget(
87
+ mirrorRows: number,
88
+ queryCount = 1
89
+ ): boolean {
90
+ return (
91
+ estimateExactCostUs(mirrorRows, queryCount) >
92
+ COARSE_ROUTER_DEFAULTS.exactBudgetUs
93
+ );
94
+ }
95
+
96
+ /**
97
+ * Extract the collection scope requested by `options.eligibility`, or `[]` when
98
+ * unscoped. Deduplicates preserving order.
99
+ */
100
+ export function extractRequestedCollections(
101
+ options: VectorSearchOptions
102
+ ): string[] {
103
+ const e = options.eligibility;
104
+ if (!e) return [];
105
+ const raw = e.collections?.length
106
+ ? e.collections
107
+ : e.collection
108
+ ? [e.collection]
109
+ : [];
110
+ return [...new Set(raw)];
111
+ }
112
+
113
+ /**
114
+ * Rule 1 predicate: true when ANY filter beyond `collection` / `collections` is
115
+ * present. Matches `hasSelectiveEligibility` plus `eligibility.language` with
116
+ * `collection`/`collections` removed, ignoring `excludeMetadata` and
117
+ * `semanticMetadata` mode flags.
118
+ */
119
+ export function hasNonCollectionFilter(options: VectorSearchOptions): boolean {
120
+ if (options.allowedMirrorHashes !== undefined) return true;
121
+ const e = options.eligibility;
122
+ if (!e) return false;
123
+ return Boolean(
124
+ e.language ||
125
+ e.memoryScopesAny?.length ||
126
+ e.excludeSuperseded ||
127
+ e.relPathPrefix ||
128
+ e.tagsAll?.length ||
129
+ e.tagsAny?.length ||
130
+ e.since ||
131
+ e.until ||
132
+ e.categories?.length ||
133
+ e.author ||
134
+ e.filter ||
135
+ e.exclude?.length
136
+ );
137
+ }
138
+
139
+ // Per-connection epoch-keyed cache for indexed `vector_partition_rows` counts.
140
+ const mirrorCountCaches = new WeakMap<
141
+ Database,
142
+ { epoch: number; counts: Map<string, number> }
143
+ >();
144
+
145
+ function readVariantEpoch(db: Database): number | null {
146
+ try {
147
+ const row = db
148
+ .query<{ epoch: number }, []>(
149
+ "SELECT epoch FROM vector_variant_epoch WHERE id = 1"
150
+ )
151
+ .get();
152
+ return row ? row.epoch : null;
153
+ } catch {
154
+ return null;
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Indexed row count `N` in `vector_partition_rows` for the scanned scope
160
+ * (unscoped, single collection, or multiple collections), cached per connection
161
+ * on `vector_variant_epoch.epoch` when not inside an uncommitted outer tx.
162
+ * Falls back to `vector_variants` count when `vector_partition_rows` is absent.
163
+ */
164
+ export function countScopeMirrorRows(
165
+ db: Database,
166
+ partitionId: string,
167
+ collections: readonly string[],
168
+ hasV2Tables: boolean,
169
+ inOuterTransaction: boolean
170
+ ): number {
171
+ const cacheKey = `${partitionId}\0${hasV2Tables ? "v2" : "v1"}\0${[...collections].sort().join("\0")}`;
172
+ let cache: { epoch: number; counts: Map<string, number> } | undefined;
173
+ if (!inOuterTransaction) {
174
+ const epoch = readVariantEpoch(db);
175
+ if (epoch !== null) {
176
+ cache = mirrorCountCaches.get(db);
177
+ if (cache?.epoch !== epoch || cache.counts.size > 4096) {
178
+ cache = { epoch, counts: new Map() };
179
+ mirrorCountCaches.set(db, cache);
180
+ }
181
+ const hit = cache.counts.get(cacheKey);
182
+ if (hit !== undefined) return hit;
183
+ }
184
+ }
185
+
186
+ let count = 0;
187
+ if (hasV2Tables) {
188
+ if (collections.length === 0) {
189
+ count =
190
+ db
191
+ .query<{ n: number }, [string]>(
192
+ "SELECT COUNT(*) AS n FROM vector_partition_rows WHERE partition_id = ?"
193
+ )
194
+ .get(partitionId)?.n ?? 0;
195
+ } else if (collections.length === 1) {
196
+ count =
197
+ db
198
+ .query<{ n: number }, [string, string]>(
199
+ "SELECT COUNT(*) AS n FROM vector_partition_rows WHERE partition_id = ? AND collection = ?"
200
+ )
201
+ .get(partitionId, collections[0]!)?.n ?? 0;
202
+ } else {
203
+ count =
204
+ db
205
+ .query<{ n: number }, [string, string]>(
206
+ `SELECT COUNT(*) AS n FROM vector_partition_rows
207
+ WHERE partition_id = ?
208
+ AND collection IN (SELECT value FROM json_each(?))`
209
+ )
210
+ .get(partitionId, JSON.stringify(collections))?.n ?? 0;
211
+ }
212
+ } else {
213
+ count =
214
+ db
215
+ .query<{ n: number }, [string]>(
216
+ "SELECT COUNT(*) AS n FROM vector_variants WHERE partition_id = ?"
217
+ )
218
+ .get(partitionId)?.n ?? 0;
219
+ }
220
+
221
+ cache?.counts.set(cacheKey, count);
222
+ return count;
223
+ }
224
+
225
+ export interface RouteDecisionInput {
226
+ options: VectorSearchOptions;
227
+ dimensions: number;
228
+ queryCount: number;
229
+ maxK: number;
230
+ collections: readonly string[];
231
+ mirrorRows: number;
232
+ /** Whether the v2 bit mirror exists and is clean (`dirty = 0`). */
233
+ v2MirrorClean: boolean;
234
+ /** Stored self-check recall, or null when unchecked. */
235
+ v2CheckRecall: number | null;
236
+ /** Persisted null_cosine flag (0 = known none, 1 = has null, null = unknown). */
237
+ nullCosineFlag: 0 | 1 | null;
238
+ /** Whether existing unscoped v1 exact-vec0 fast path is eligible. */
239
+ canUseV1ExactVec0: boolean;
240
+ }
241
+
242
+ export interface RouteDecision {
243
+ route: VectorRouteKind;
244
+ coarseK?: number;
245
+ reason: string;
246
+ }
247
+
248
+ /**
249
+ * Evaluate fn-235 router Rules 1–5 deterministically for a single or batched search.
250
+ */
251
+ export function resolveVectorRoute(input: RouteDecisionInput): RouteDecision {
252
+ const exactRoute: VectorRouteKind = input.canUseV1ExactVec0
253
+ ? "exact-vec0"
254
+ : "exact-sql";
255
+
256
+ // Rule 1: any filter beyond collection/collections -> exact SQL scan
257
+ if (hasNonCollectionFilter(input.options)) {
258
+ return { route: "exact-sql", reason: "filtered" };
259
+ }
260
+
261
+ // Rule 2: explicit exact override, switch off, unsupported dims, missing/dirty/unchecked/below-floor v2, or null_cosine !== 0
262
+ if (input.options.exact === true) {
263
+ return { route: exactRoute, reason: "exact-override" };
264
+ }
265
+ const coarseEnabled =
266
+ input.options.coarseVectorSearch ?? COARSE_ROUTER_DEFAULTS.enabledByDefault;
267
+ if (!coarseEnabled) {
268
+ return { route: exactRoute, reason: "coarse-disabled" };
269
+ }
270
+ if (!isV2CompatibleDimensions(input.dimensions)) {
271
+ return { route: exactRoute, reason: "unsupported-dimensions" };
272
+ }
273
+ if (!input.v2MirrorClean) {
274
+ return { route: exactRoute, reason: "v2-mirror-unavailable" };
275
+ }
276
+ if (
277
+ input.v2CheckRecall === null ||
278
+ input.v2CheckRecall < COARSE_ROUTER_DEFAULTS.selfCheckRecallFloor
279
+ ) {
280
+ return { route: exactRoute, reason: "v2-self-check-not-passed" };
281
+ }
282
+ if (input.nullCosineFlag !== 0) {
283
+ return { route: exactRoute, reason: "null-cosine-not-zero" };
284
+ }
285
+
286
+ // Rule 3: estimated exact cost within 100 ms budget -> existing exact paths
287
+ if (
288
+ estimateExactCostUs(input.mirrorRows, input.queryCount) <=
289
+ COARSE_ROUTER_DEFAULTS.exactBudgetUs
290
+ ) {
291
+ return { route: exactRoute, reason: "within-exact-budget" };
292
+ }
293
+
294
+ // Rule 4: k > maxCoarseQueryK (40) -> existing exact paths
295
+ if (input.maxK > COARSE_ROUTER_DEFAULTS.maxCoarseQueryK) {
296
+ return { route: exactRoute, reason: "k-above-max-coarse" };
297
+ }
298
+
299
+ const coarseK = computeCoarseK(input.maxK);
300
+
301
+ // Multi-collection candidate cap: collections.length * coarseK > 2000 -> exact
302
+ if (
303
+ input.collections.length > 1 &&
304
+ input.collections.length * coarseK >
305
+ COARSE_ROUTER_DEFAULTS.maxMultiCollectionCandidates
306
+ ) {
307
+ return { route: exactRoute, reason: "multi-collection-cap" };
308
+ }
309
+
310
+ // Rule 5: two-stage bit coarse + exact float32 rescore
311
+ return { route: "coarse-bit", coarseK, reason: "coarse-bit" };
312
+ }
@@ -1,34 +1,101 @@
1
1
  /**
2
2
  * Maintenance of an activated vector partition's vec0 index
3
3
  * (`vec_v1_<partition>`), which mirrors the partition's `vector_variants`.
4
- * `gno vec sync` and `gno vec rebuild` use it on indexes embedded since 2.7.
5
- * Neither changes authority, owners or variants, so the variant epoch stays.
4
+ * `gno vec sync`, `gno vec rebuild`, and `gno vec prune` use it on indexes
5
+ * embedded since 2.7. Sync/rebuild never change authority, owners, or variants,
6
+ * so the variant epoch stays.
6
7
  *
7
8
  * @module src/store/vector/partition-index
8
9
  */
9
10
  import type { Database } from "bun:sqlite";
10
11
 
12
+ import { modelTableName } from "./sqlite-vec";
13
+ import {
14
+ rebuildV2PartitionMirrorInTx,
15
+ runV2RecallSelfCheck,
16
+ syncV2PartitionMirrorInTx,
17
+ } from "./v2-mirror";
18
+
11
19
  export interface StoredPartition {
12
20
  partitionId: string;
13
21
  dimensions: number;
14
22
  }
15
23
 
24
+ export type NullCosineMark = 0 | 1 | null;
25
+
26
+ /** True when migration 038's `null_cosine` column is present on `vector_mirror_state`. */
27
+ export function hasNullCosineColumn(db: Database): boolean {
28
+ return Boolean(
29
+ db
30
+ .query<{ name: string }, []>(
31
+ "SELECT name FROM pragma_table_info('vector_mirror_state') WHERE name = 'null_cosine'"
32
+ )
33
+ .get()
34
+ );
35
+ }
36
+
37
+ /**
38
+ * Exact SQLite null-cosine check for one embedding BLOB. Uses sqlite-vec's own
39
+ * float32 cosine distance so underflow/overflow vectors (e.g. components of
40
+ * 1e-30 or 1e30) match SQLite's `vec_distance_cosine` behavior identically.
41
+ */
42
+ export function isNullCosineEmbedding(db: Database, blob: Uint8Array): boolean {
43
+ const row = db
44
+ .query<{ is_null: number }, [Uint8Array]>(
45
+ "SELECT vec_distance_cosine(?1, ?1) IS NULL AS is_null"
46
+ )
47
+ .get(blob);
48
+ return row?.is_null === 1;
49
+ }
50
+
51
+ /**
52
+ * Probe whether `partitionId` contains any variant whose cosine distance can
53
+ * be NULL (zero or float32-norm underflow/overflow). Requires sqlite-vec.
54
+ */
55
+ export function probePartitionNullCosine(
56
+ db: Database,
57
+ partitionId: string
58
+ ): boolean {
59
+ return Boolean(
60
+ db
61
+ .query<unknown, [string]>(
62
+ `SELECT 1 FROM vector_variants
63
+ WHERE partition_id = ?
64
+ AND vec_distance_cosine(embedding, embedding) IS NULL
65
+ LIMIT 1`
66
+ )
67
+ .get(partitionId)
68
+ );
69
+ }
70
+
16
71
  /**
17
72
  * Records that the partition's vec0 mirror matches its stored variants
18
- * (migration 036). A no-op on databases without mirror tracking. Callers run
19
- * it inside the transaction that made the mirror current.
73
+ * (migration 036) and optionally persists its `null_cosine` state (migration
74
+ * 038). A no-op on databases without mirror tracking. Callers run it inside
75
+ * the transaction that made the mirror current.
20
76
  */
21
- export function markMirrorClean(db: Database, partitionId: string): void {
77
+ export function markMirrorClean(
78
+ db: Database,
79
+ partitionId: string,
80
+ nullCosine: NullCosineMark = null
81
+ ): void {
22
82
  if (
23
83
  !db
24
84
  .query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?")
25
85
  .get("vector_mirror_state")
26
86
  )
27
87
  return;
28
- db.run(
29
- "INSERT OR REPLACE INTO vector_mirror_state (partition_id, dirty) VALUES (?, 0)",
30
- [partitionId]
31
- );
88
+ if (hasNullCosineColumn(db)) {
89
+ db.run(
90
+ "INSERT OR REPLACE INTO vector_mirror_state (partition_id, dirty, null_cosine) VALUES (?, 0, ?)",
91
+ [partitionId, nullCosine]
92
+ );
93
+ } else {
94
+ db.run(
95
+ "INSERT OR REPLACE INTO vector_mirror_state (partition_id, dirty) VALUES (?, 0)",
96
+ [partitionId]
97
+ );
98
+ }
32
99
  }
33
100
 
34
101
  const tableName = (partition: StoredPartition): string =>
@@ -49,10 +116,16 @@ const logicalChanges = (db: Database): number =>
49
116
  * Remove index rows without a matching variant (orphans and stale
50
117
  * embeddings), then add the variants the index lacks. Requires sqlite-vec.
51
118
  */
52
- export function syncPartitionIndex(
119
+ export function syncPartitionIndexWithDetails(
53
120
  db: Database,
54
121
  partition: StoredPartition
55
- ): { added: number; removed: number } {
122
+ ): {
123
+ added: number;
124
+ removed: number;
125
+ v2Added?: number;
126
+ v2Removed?: number;
127
+ checkRecall?: number | null;
128
+ } {
56
129
  const table = tableName(partition);
57
130
  return db
58
131
  .transaction(() => {
@@ -74,17 +147,46 @@ export function syncPartitionIndex(
74
147
  WHERE v.partition_id = ? AND x.variant_id IS NULL`
75
148
  ).run(partition.partitionId);
76
149
  const added = logicalChanges(db);
77
- markMirrorClean(db, partition.partitionId);
78
- return { added, removed };
150
+ const nullCosine: 0 | 1 = probePartitionNullCosine(
151
+ db,
152
+ partition.partitionId
153
+ )
154
+ ? 1
155
+ : 0;
156
+ markMirrorClean(db, partition.partitionId, nullCosine);
157
+ const v2 = syncV2PartitionMirrorInTx(
158
+ db,
159
+ partition.partitionId,
160
+ partition.dimensions
161
+ );
162
+ if (v2.skipped) {
163
+ return { added, removed };
164
+ }
165
+ const check = runV2RecallSelfCheck(db, partition);
166
+ return {
167
+ added,
168
+ removed,
169
+ v2Added: v2.added,
170
+ v2Removed: v2.removed,
171
+ checkRecall: check.recall,
172
+ };
79
173
  })
80
174
  .immediate();
81
175
  }
82
176
 
83
- /** Drop and repopulate the index from the partition's variants. */
84
- export function rebuildPartitionIndex(
177
+ export function syncPartitionIndex(
85
178
  db: Database,
86
179
  partition: StoredPartition
87
- ): number {
180
+ ): { added: number; removed: number } {
181
+ const { added, removed } = syncPartitionIndexWithDetails(db, partition);
182
+ return { added, removed };
183
+ }
184
+
185
+ /** Drop and repopulate the v1 and v2 mirrors from the partition's variants. */
186
+ export function rebuildPartitionIndexWithDetails(
187
+ db: Database,
188
+ partition: StoredPartition
189
+ ): { count: number; v2Count?: number; checkRecall?: number | null } {
88
190
  const table = tableName(partition);
89
191
  return db
90
192
  .transaction(() => {
@@ -95,8 +197,197 @@ export function rebuildPartitionIndex(
95
197
  SELECT variant_id, embedding FROM vector_variants WHERE partition_id = ?`
96
198
  ).run(partition.partitionId);
97
199
  const inserted = logicalChanges(db);
98
- markMirrorClean(db, partition.partitionId);
99
- return inserted;
200
+ const nullCosine: 0 | 1 = probePartitionNullCosine(
201
+ db,
202
+ partition.partitionId
203
+ )
204
+ ? 1
205
+ : 0;
206
+ markMirrorClean(db, partition.partitionId, nullCosine);
207
+ if (partition.dimensions % 8 !== 0) {
208
+ return { count: inserted };
209
+ }
210
+ const v2Count = rebuildV2PartitionMirrorInTx(
211
+ db,
212
+ partition.partitionId,
213
+ partition.dimensions
214
+ );
215
+ const check = runV2RecallSelfCheck(db, partition);
216
+ return { count: inserted, v2Count, checkRecall: check.recall };
100
217
  })
101
218
  .immediate();
102
219
  }
220
+
221
+ /** Drop and repopulate the index from the partition's variants. */
222
+ export function rebuildPartitionIndex(
223
+ db: Database,
224
+ partition: StoredPartition
225
+ ): number {
226
+ return rebuildPartitionIndexWithDetails(db, partition).count;
227
+ }
228
+
229
+ export type PruneLegacyVectorsResult =
230
+ | {
231
+ ok: true;
232
+ droppedTables: string[];
233
+ removedRows: number;
234
+ activatedModels: string[];
235
+ }
236
+ | { ok: false; error: string };
237
+
238
+ const VEC_V1_TABLE_PATTERN = /^vec_v1_([0-9a-f]{64})$/;
239
+ const VEC_V2_TABLE_PATTERN = /^vec_v2_([0-9a-f]{64})$/;
240
+
241
+ /**
242
+ * Safely prune superseded legacy vector tables (`vec_<hash>`), legacy
243
+ * `content_vectors` rows for models with an activated v1 partition, and
244
+ * orphaned `vec_v1_<partition>` tables absent from `vector_partitions`.
245
+ *
246
+ * Requires sqlite-vec (DROP TABLE on a vec0 virtual table fails with
247
+ * `no such module: vec0` without the extension) and a writable connection.
248
+ */
249
+ export async function pruneLegacyVectors(
250
+ db: Database,
251
+ options: { loadSqliteVec?: (db: Database) => Promise<boolean> } = {}
252
+ ): Promise<PruneLegacyVectorsResult> {
253
+ const queryOnly =
254
+ db.query<{ query_only: number }, []>("PRAGMA query_only").get()
255
+ ?.query_only === 1;
256
+ if (queryOnly) {
257
+ return {
258
+ ok: false,
259
+ error: "Cannot prune legacy vectors on a read-only database.",
260
+ };
261
+ }
262
+
263
+ let sqliteVecLoaded = false;
264
+ if (options.loadSqliteVec) {
265
+ sqliteVecLoaded = await options.loadSqliteVec(db);
266
+ } else {
267
+ try {
268
+ const sqliteVec = await import("sqlite-vec");
269
+ sqliteVec.load(db);
270
+ sqliteVecLoaded = true;
271
+ } catch {
272
+ sqliteVecLoaded = false;
273
+ }
274
+ }
275
+ if (!sqliteVecLoaded) {
276
+ return {
277
+ ok: false,
278
+ error:
279
+ "sqlite-vec is unavailable; cannot drop legacy or orphaned vector tables.",
280
+ };
281
+ }
282
+
283
+ try {
284
+ return db
285
+ .transaction((): PruneLegacyVectorsResult => {
286
+ const hasPartitionsTable = Boolean(
287
+ db
288
+ .query(
289
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'vector_partitions'"
290
+ )
291
+ .get()
292
+ );
293
+ if (!hasPartitionsTable) {
294
+ return {
295
+ ok: true,
296
+ droppedTables: [],
297
+ removedRows: 0,
298
+ activatedModels: [],
299
+ };
300
+ }
301
+
302
+ const activatedModels = db
303
+ .query<{ model: string }, []>(
304
+ `SELECT DISTINCT model
305
+ FROM vector_partitions
306
+ WHERE state = 'active' AND activated_epoch IS NOT NULL
307
+ ORDER BY model`
308
+ )
309
+ .all()
310
+ .map((row) => row.model);
311
+
312
+ const knownPartitionIds = new Set(
313
+ db
314
+ .query<{ partition_id: string }, []>(
315
+ "SELECT partition_id FROM vector_partitions"
316
+ )
317
+ .all()
318
+ .map((row) => row.partition_id)
319
+ );
320
+
321
+ const allTables = db
322
+ .query<{ name: string }, []>(
323
+ "SELECT name FROM sqlite_master WHERE type = 'table'"
324
+ )
325
+ .all()
326
+ .map((row) => row.name);
327
+ const tableSet = new Set(allTables);
328
+
329
+ const droppedTables: string[] = [];
330
+ let removedRows = 0;
331
+
332
+ // 1. Drop legacy per-model vec_<hash> tables and delete legacy
333
+ // content_vectors rows ONLY for models with an activated partition.
334
+ for (const model of activatedModels) {
335
+ const legacyTable = modelTableName(model);
336
+ if (tableSet.has(legacyTable)) {
337
+ db.exec(`DROP TABLE IF EXISTS "${legacyTable}"`);
338
+ droppedTables.push(legacyTable);
339
+ }
340
+ if (tableSet.has("content_vectors")) {
341
+ db.query("DELETE FROM content_vectors WHERE model = ?").run(model);
342
+ removedRows += logicalChanges(db);
343
+ }
344
+ }
345
+
346
+ // 2. Drop orphaned vec_v1_<partition> and vec_v2_<partition> tables absent from vector_partitions.
347
+ for (const name of allTables) {
348
+ const match =
349
+ VEC_V1_TABLE_PATTERN.exec(name) ?? VEC_V2_TABLE_PATTERN.exec(name);
350
+ if (!match) continue;
351
+ const partitionId = match[1]!;
352
+ if (!knownPartitionIds.has(partitionId)) {
353
+ db.exec(`DROP TABLE IF EXISTS "${name}"`);
354
+ droppedTables.push(name);
355
+ }
356
+ }
357
+
358
+ // 3. Remove orphaned rows from vector_mirror_state, vector_mirror_v2_state,
359
+ // and vector_partition_rows if present.
360
+ if (tableSet.has("vector_mirror_state")) {
361
+ db.run(
362
+ `DELETE FROM vector_mirror_state
363
+ WHERE partition_id NOT IN (SELECT partition_id FROM vector_partitions)`
364
+ );
365
+ }
366
+ if (tableSet.has("vector_mirror_v2_state")) {
367
+ db.run(
368
+ `DELETE FROM vector_mirror_v2_state
369
+ WHERE partition_id NOT IN (SELECT partition_id FROM vector_partitions)`
370
+ );
371
+ }
372
+ if (tableSet.has("vector_partition_rows")) {
373
+ db.run(
374
+ `DELETE FROM vector_partition_rows
375
+ WHERE partition_id NOT IN (SELECT partition_id FROM vector_partitions)`
376
+ );
377
+ }
378
+
379
+ return {
380
+ ok: true,
381
+ droppedTables,
382
+ removedRows,
383
+ activatedModels,
384
+ };
385
+ })
386
+ .immediate();
387
+ } catch (cause) {
388
+ return {
389
+ ok: false,
390
+ error: `Vector prune failed: ${cause instanceof Error ? cause.message : String(cause)}`,
391
+ };
392
+ }
393
+ }