@fgv/ts-agent-memory-sqlite-vec 5.1.0-47 → 5.1.0-49

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/LICENSE +21 -0
  2. package/dist/packlets/sqlite-vec-index/sqliteVecVectorIndex.js +107 -1
  3. package/dist/packlets/sqlite-vec-index/sqliteVecVectorIndex.js.map +1 -1
  4. package/dist/ts-agent-memory-sqlite-vec.d.ts +26 -0
  5. package/lib/packlets/sqlite-vec-index/sqliteVecVectorIndex.d.ts +23 -1
  6. package/lib/packlets/sqlite-vec-index/sqliteVecVectorIndex.d.ts.map +1 -1
  7. package/lib/packlets/sqlite-vec-index/sqliteVecVectorIndex.js +106 -0
  8. package/lib/packlets/sqlite-vec-index/sqliteVecVectorIndex.js.map +1 -1
  9. package/package.json +17 -7
  10. package/.rush/temp/2b1ffec4a34b11a2a7317510ba4142ae814069d2.tar.log +0 -60
  11. package/.rush/temp/chunked-rush-logs/ts-agent-memory-sqlite-vec.build.chunks.jsonl +0 -9
  12. package/.rush/temp/operation/build/all.log +0 -9
  13. package/.rush/temp/operation/build/log-chunks.jsonl +0 -9
  14. package/.rush/temp/operation/build/state.json +0 -3
  15. package/.rush/temp/shrinkwrap-deps.json +0 -720
  16. package/config/api-extractor.json +0 -38
  17. package/config/jest.config.json +0 -13
  18. package/config/rig.json +0 -6
  19. package/dist/test/unit/sqliteVecFragmentIndex.test.js +0 -513
  20. package/dist/test/unit/sqliteVecFragmentIndex.test.js.map +0 -1
  21. package/dist/test/unit/sqliteVecVectorIndex.test.js +0 -199
  22. package/dist/test/unit/sqliteVecVectorIndex.test.js.map +0 -1
  23. package/eslint.config.js +0 -15
  24. package/etc/ts-agent-memory-sqlite-vec.api.md +0 -66
  25. package/lib/test/unit/sqliteVecFragmentIndex.test.d.ts +0 -2
  26. package/lib/test/unit/sqliteVecFragmentIndex.test.d.ts.map +0 -1
  27. package/lib/test/unit/sqliteVecFragmentIndex.test.js +0 -551
  28. package/lib/test/unit/sqliteVecFragmentIndex.test.js.map +0 -1
  29. package/lib/test/unit/sqliteVecVectorIndex.test.d.ts +0 -2
  30. package/lib/test/unit/sqliteVecVectorIndex.test.d.ts.map +0 -1
  31. package/lib/test/unit/sqliteVecVectorIndex.test.js +0 -237
  32. package/lib/test/unit/sqliteVecVectorIndex.test.js.map +0 -1
  33. package/rush-logs/ts-agent-memory-sqlite-vec.build.cache.log +0 -3
  34. package/rush-logs/ts-agent-memory-sqlite-vec.build.log +0 -9
  35. package/src/index.ts +0 -6
  36. package/src/packlets/sqlite-vec-index/index.ts +0 -8
  37. package/src/packlets/sqlite-vec-index/model.ts +0 -56
  38. package/src/packlets/sqlite-vec-index/sqliteVecFragmentIndex.ts +0 -540
  39. package/src/packlets/sqlite-vec-index/sqliteVecVectorIndex.ts +0 -255
  40. package/src/test/unit/sqliteVecFragmentIndex.test.ts +0 -691
  41. package/src/test/unit/sqliteVecVectorIndex.test.ts +0 -253
  42. package/temp/build/lint/_eslint-5eVG3S6w.json +0 -34
  43. package/temp/build/typescript/ts_8nwakTlr.json +0 -1
  44. package/temp/ts-agent-memory-sqlite-vec.api.json +0 -1167
  45. package/temp/ts-agent-memory-sqlite-vec.api.md +0 -66
  46. package/tsconfig.json +0 -8
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Erik Fortune
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -3,8 +3,36 @@
3
3
  * SPDX-License-Identifier: MIT
4
4
  */
5
5
  import { load as loadSqliteVec } from 'sqlite-vec';
6
- import { captureResult, fail, succeed } from '@fgv/ts-utils';
6
+ import { captureAsyncResult, captureResult, fail, succeed } from '@fgv/ts-utils';
7
7
  import { edgeTargetKey } from '@fgv/ts-agent-memory';
8
+ /**
9
+ * Invoke a consumer-supplied hook that already returns a `Result`, converting a
10
+ * synchronous throw or a promise rejection into a `Failure` rather than letting
11
+ * it escape. `captureAsyncResult` wraps the hook's own `Result`, so the outcome
12
+ * is flattened back to one level.
13
+ *
14
+ * @remarks
15
+ * This is `@fgv/ts-utils`' own `_invokeDeferred` shape (see `mapResultsAsync`),
16
+ * which is `@internal` there and so cannot be imported. `@fgv/ts-agent-memory`
17
+ * carries an identical private copy for the in-memory index. Exporting a single
18
+ * `AsyncDeferredResult`-invoking primitive from `ts-utils` is the right home and
19
+ * is recorded in `docs/TECH_DEBT.md`; duplicating three lines twice is the
20
+ * cheaper thing to do from inside this stream than widening it to a foundational
21
+ * library.
22
+ */
23
+ async function invokeHook(hook) {
24
+ return (await captureAsyncResult(hook)).onSuccess((inner) => inner);
25
+ }
26
+ /**
27
+ * Compose the failure that aborted a rebuild with the outcome of the rollback
28
+ * that followed it. A rollback that ALSO fails is worth saying out loud: the
29
+ * `'fail'` path promises an empty index, and a caller that retries against a
30
+ * table which is neither the old index nor empty is working from a state the
31
+ * contract never described.
32
+ */
33
+ function withRollbackNote(error, rollback) {
34
+ return rollback.isFailure() ? `${error} (rollback also failed: ${rollback.message})` : error;
35
+ }
8
36
  /** Default name for the `vec0` virtual table. */
9
37
  const DEFAULT_TABLE_NAME = 'memory_vectors';
10
38
  /** A simple SQL identifier — the only shape allowed for the table name (it is interpolated into DDL). */
@@ -106,6 +134,84 @@ export class SqliteVecVectorIndex {
106
134
  return target;
107
135
  }).withErrorFormat((e) => `vector index: cannot remove '${edgeTargetKey(target)}': ${e}`));
108
136
  }
137
+ /**
138
+ * Re-embed every record from `source` and rebuild the persisted index — see
139
+ * `IVectorIndex.rebuild` for the mode semantics, which this implementation
140
+ * matches exactly.
141
+ *
142
+ * @remarks
143
+ * **Not atomic, and cannot be.** `better-sqlite3` transactions are synchronous,
144
+ * so one cannot span the `await embed(...)` calls this loop makes — unlike
145
+ * {@link SqliteVecVectorIndex.add}, which wraps its delete-then-insert. The
146
+ * `'fail'` / `'skip'` modes therefore cover only failures JavaScript can catch:
147
+ * a process kill mid-rebuild leaves the table holding neither the old index nor
148
+ * the complete new one, and the remedy is to run `rebuild` again.
149
+ */
150
+ async rebuild(source, embed, options) {
151
+ var _a;
152
+ const lenient = ((_a = options === null || options === void 0 ? void 0 : options.onRecordError) !== null && _a !== void 0 ? _a : 'fail') === 'skip';
153
+ // `source` is consumer-supplied, so a throw or rejection becomes a `Failure`
154
+ // here rather than escaping as an exception.
155
+ const listed = await invokeHook(() => source.list());
156
+ if (listed.isFailure()) {
157
+ // Deliberately BEFORE any clear: a failed list is no evidence about the
158
+ // vectors already held, and no re-embedding has been attempted, so there is
159
+ // no half-rebuilt state to protect against. Clearing here would destroy a
160
+ // healthy persisted index over a transient read error.
161
+ return fail(`vector index rebuild: failed to list records: ${listed.message}`);
162
+ }
163
+ const cleared = this._clear();
164
+ if (cleared.isFailure()) {
165
+ return fail(`vector index rebuild: failed to clear the index: ${cleared.message}`);
166
+ }
167
+ let declined = 0;
168
+ const skipped = [];
169
+ for (const scoped of listed.value) {
170
+ // Likewise capture-wrapped: an embedder that throws mid-loop would
171
+ // otherwise escape past the `'fail'` rollback below, leaving this DURABLE
172
+ // table holding a partial index that survives the process.
173
+ const embedded = await invokeHook(() => embed(scoped.record));
174
+ if (embedded.isFailure()) {
175
+ const error = `vector index rebuild: embedding '${edgeTargetKey(scoped.target)}' failed: ${embedded.message}`;
176
+ if (!lenient) {
177
+ return fail(withRollbackNote(error, this._clear()));
178
+ }
179
+ skipped.push({ target: scoped.target, error });
180
+ continue;
181
+ }
182
+ if (embedded.value === undefined) {
183
+ declined++;
184
+ continue;
185
+ }
186
+ const added = await this.add(scoped.target, embedded.value);
187
+ if (added.isFailure()) {
188
+ const error = `vector index rebuild: ${added.message}`;
189
+ if (!lenient) {
190
+ return fail(withRollbackNote(error, this._clear()));
191
+ }
192
+ skipped.push({ target: scoped.target, error });
193
+ }
194
+ }
195
+ return captureResult(() => this.size)
196
+ .withErrorFormat((msg) => `vector index rebuild: failed to count the rebuilt index: ${msg}`)
197
+ .onSuccess((indexed) => succeed({ indexed, declined, skipped }));
198
+ }
199
+ /**
200
+ * Empty the table. Deliberately does NOT drop it or forget the established
201
+ * dimension: the `vec0` table's dimension is fixed at creation and a re-embed at
202
+ * a different dimension needs a drop-and-re-index, which is a consumer decision
203
+ * (see the package README on `vec0` schema changes), not something a rebuild
204
+ * should do silently.
205
+ */
206
+ _clear() {
207
+ if (this._stmts === undefined) {
208
+ return succeed(true);
209
+ }
210
+ // Capture-wrapped like `add` / `remove` / `query`: a closed connection or an
211
+ // I/O error here is a `Failure`, not an exception thrown out of a method
212
+ // whose signature promises a `Result`.
213
+ return captureResult(() => this._db.prepare(`DELETE FROM "${this._table}"`).run()).onSuccess(() => succeed(true));
214
+ }
109
215
  /** {@inheritDoc IVectorIndex.query} */
110
216
  query(vector, topK) {
111
217
  if (topK <= 0 || this._stmts === undefined) {
@@ -1 +1 @@
1
- {"version":3,"file":"sqliteVecVectorIndex.js","sourceRoot":"","sources":["../../../src/packlets/sqlite-vec-index/sqlite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from 'better-sqlite3';\nimport { load as loadSqliteVec } from 'sqlite-vec';\nimport { Result, captureResult, fail, succeed } from '@fgv/ts-utils';\nimport {\n IEdgeTarget,\n IVectorIndex,\n IVectorQueryHit,\n MemoryId,\n MemoryScopeKey,\n edgeTargetKey\n} from '@fgv/ts-agent-memory';\nimport { ISqliteVecVectorIndexCreateParams } from './model';\n\n/** Default name for the `vec0` virtual table. */\nconst DEFAULT_TABLE_NAME: string = 'memory_vectors';\n\n/** A simple SQL identifier — the only shape allowed for the table name (it is interpolated into DDL). */\nconst IDENTIFIER_RE: RegExp = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** One KNN row as returned by the `vec0` MATCH query. */\ninterface IKnnRow {\n readonly target_key: string;\n readonly distance: number;\n}\n\n/**\n * A persistent, `sqlite-vec`-backed `IVectorIndex` for `@fgv/ts-agent-memory`.\n *\n * @remarks\n * This is the **durable** counterpart to the in-memory `InMemoryCosineIndex`:\n * embeddings live in a `sqlite-vec` `vec0` virtual table inside a `better-sqlite3`\n * database, so they survive a process restart. A consumer that wires this index\n * into `FileTreeMemoryStore` (instead of the in-memory index) opens an existing\n * vault **without re-embedding it** — the vectors are already on disk. New writes\n * still flow through the store's incremental embed-on-write path; there is no core\n * store change.\n *\n * The index is keyed by the canonical `edgeTargetKey` of each record's\n * scope-qualified `(scope, id)` address (a `TEXT PRIMARY KEY` on the `vec0` table),\n * so two records that share a filename stem across scopes never collide. The\n * dimension is established by the first `add` (the `vec0` column is fixed-width) and\n * recovered from the table schema when a persistent file is reopened; every later\n * `add`/`query` must match it or fail loudly, exactly as the in-memory index does.\n * Similarity is cosine (`distance_metric=cosine`): the returned `score` is\n * `1 - cosineDistance`, i.e. cosine similarity in `[-1, 1]`, higher = more similar —\n * byte-for-byte the same scoring contract as `InMemoryCosineIndex`.\n *\n * Query is a brute-force `vec0` KNN scan (not an ANN structure): correct and\n * durable, appropriate for the same \"thousands of records\" regime the in-memory\n * index targets. Large-N ANN indexing is explicitly out of scope — see the README.\n *\n * The `better-sqlite3` `Database` is consumer-owned (bring-your-own): this index\n * loads the `sqlite-vec` extension onto it and reads/writes the table, but never\n * opens or closes the connection.\n * @public\n */\nexport class SqliteVecVectorIndex implements IVectorIndex {\n private readonly _db: BetterSqlite3.Database;\n private readonly _table: string;\n /** The dimension of every stored vector; `undefined` until the table exists (first `add` or a reopened non-empty file). */\n private _dimension: number | undefined;\n /** Prepared statements; created once the table exists (established or recovered). */\n private _stmts: ISqliteVecStatements | undefined;\n\n private constructor(db: BetterSqlite3.Database, table: string, dimension: number | undefined) {\n this._db = db;\n this._table = table;\n this._dimension = dimension;\n this._stmts = dimension === undefined ? undefined : this._prepare();\n }\n\n /** The number of vectors currently held. Zero before the first `add`. */\n public get size(): number {\n if (this._stmts === undefined) {\n return 0;\n }\n return (this._stmts.count.get() as { c: number }).c;\n }\n\n /**\n * Family-convention factory. Loads the `sqlite-vec` extension onto the supplied\n * `better-sqlite3` connection and, if the vector table already exists (a reopened\n * persistent file), recovers its established dimension so no re-embedding is\n * needed on open.\n *\n * @param params - See {@link ISqliteVecVectorIndexCreateParams}.\n * @returns `Success` with the index, or `Failure` if the table name is not a\n * simple identifier or the extension fails to load.\n */\n public static create(params: ISqliteVecVectorIndexCreateParams): Promise<Result<SqliteVecVectorIndex>> {\n const table: string = params.tableName ?? DEFAULT_TABLE_NAME;\n if (!IDENTIFIER_RE.test(table)) {\n return Promise.resolve(fail(`sqlite-vec index: table name '${table}' is not a simple SQL identifier`));\n }\n return Promise.resolve(\n captureResult(() => {\n loadSqliteVec(params.database);\n const dimension: number | undefined = SqliteVecVectorIndex._readExistingDimension(\n params.database,\n table\n );\n return new SqliteVecVectorIndex(params.database, table, dimension);\n }).withErrorFormat((e) => `sqlite-vec index: failed to initialize: ${e}`)\n );\n }\n\n /** {@inheritDoc IVectorIndex.add} */\n public add(target: IEdgeTarget, vector: Float32Array): Promise<Result<string>> {\n const key: string = edgeTargetKey(target);\n if (vector.length === 0) {\n return Promise.resolve(fail(`vector index: cannot add '${key}': empty vector`));\n }\n if (this._dimension !== undefined && vector.length !== this._dimension) {\n return Promise.resolve(\n fail(\n `vector index: cannot add '${key}': dimension ${vector.length} does not match index dimension ${this._dimension}`\n )\n );\n }\n return Promise.resolve(\n captureResult(() => {\n if (this._stmts === undefined) {\n this._createTable(vector.length);\n this._dimension = vector.length;\n this._stmts = this._prepare();\n }\n this._stmts.replace(key, SqliteVecVectorIndex._toBlob(vector));\n return key;\n }).withErrorFormat((e) => `vector index: cannot add '${key}': ${e}`)\n );\n }\n\n /** {@inheritDoc IVectorIndex.remove} */\n public remove(target: IEdgeTarget): Promise<Result<IEdgeTarget>> {\n return Promise.resolve(\n captureResult(() => {\n // Idempotent: removing a target with no embedding (or before any `add`\n // created the table) still succeeds.\n if (this._stmts !== undefined) {\n this._stmts.delete.run(edgeTargetKey(target));\n }\n return target;\n }).withErrorFormat((e) => `vector index: cannot remove '${edgeTargetKey(target)}': ${e}`)\n );\n }\n\n /** {@inheritDoc IVectorIndex.query} */\n public query(vector: Float32Array, topK: number): Promise<Result<ReadonlyArray<IVectorQueryHit>>> {\n if (topK <= 0 || this._stmts === undefined) {\n return Promise.resolve(succeed([]));\n }\n if (vector.length !== this._dimension) {\n return Promise.resolve(\n fail(\n `vector index: query dimension ${vector.length} does not match index dimension ${this._dimension}`\n )\n );\n }\n return Promise.resolve(\n captureResult<ReadonlyArray<IVectorQueryHit>>(() => {\n const rows: ReadonlyArray<IKnnRow> = this._stmts!.query.all(\n SqliteVecVectorIndex._toBlob(vector),\n topK\n ) as ReadonlyArray<IKnnRow>;\n // sqlite-vec returns rows in ascending distance (nearest first); score is\n // `1 - cosineDistance` = cosine similarity, so descending score is preserved.\n return rows.map((row) => ({\n target: SqliteVecVectorIndex._parseKey(row.target_key),\n score: 1 - row.distance\n }));\n }).withErrorFormat((e) => `vector index: query failed: ${e}`)\n );\n }\n\n /** Create the `vec0` virtual table with the established dimension. */\n private _createTable(dimension: number): void {\n this._db.exec(\n `CREATE VIRTUAL TABLE IF NOT EXISTS \"${this._table}\" USING vec0(` +\n `target_key TEXT PRIMARY KEY, embedding float[${dimension}] distance_metric=cosine)`\n );\n }\n\n /** Prepare the statements the index reuses. Requires the table to exist. */\n private _prepare(): ISqliteVecStatements {\n const del: BetterSqlite3.Statement = this._db.prepare(\n `DELETE FROM \"${this._table}\" WHERE target_key = ?`\n );\n const ins: BetterSqlite3.Statement = this._db.prepare(\n `INSERT INTO \"${this._table}\"(target_key, embedding) VALUES (?, ?)`\n );\n // vec0 rejects INSERT OR REPLACE on a TEXT primary key, so replace is a\n // delete-then-insert inside a single transaction.\n const replaceTxn: BetterSqlite3.Transaction<(key: string, blob: Uint8Array) => void> =\n this._db.transaction((key: string, blob: Uint8Array) => {\n del.run(key);\n ins.run(key, blob);\n });\n return {\n delete: del,\n replace: (key: string, blob: Uint8Array): void => {\n replaceTxn(key, blob);\n },\n query: this._db.prepare(\n `SELECT target_key, distance FROM \"${this._table}\" WHERE embedding MATCH ? AND k = ?`\n ),\n count: this._db.prepare(`SELECT count(*) AS c FROM \"${this._table}\"`)\n };\n }\n\n /**\n * Recover the established dimension of an existing `vec0` table from its stored\n * `CREATE VIRTUAL TABLE` SQL (`float[<n>]`). Returns `undefined` when the table\n * does not exist yet (a fresh database — dimension is set by the first `add`).\n */\n private static _readExistingDimension(db: BetterSqlite3.Database, table: string): number | undefined {\n const row: { sql: string } | undefined = db\n .prepare(\"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\")\n .get(table) as { sql: string } | undefined;\n if (row === undefined) {\n return undefined;\n }\n const match: RegExpMatchArray | null = row.sql.match(/float\\[(\\d+)\\]/);\n return match === null ? undefined : Number(match[1]);\n }\n\n /** Pack a `Float32Array` as the little-endian byte blob `vec0` stores. Copies, so the caller may reuse its buffer. */\n private static _toBlob(vector: Float32Array): Uint8Array {\n return new Uint8Array(Float32Array.from(vector).buffer);\n }\n\n /**\n * Reverse `edgeTargetKey` — the canonical key is `scope\\0id` with NUL\n * excluded from both components, so the first NUL splits it unambiguously.\n */\n private static _parseKey(key: string): IEdgeTarget {\n const nul: number = key.indexOf('\\0');\n return {\n scope: key.slice(0, nul) as unknown as MemoryScopeKey,\n id: key.slice(nul + 1) as unknown as MemoryId\n };\n }\n}\n\n/** The prepared statements / helpers the index reuses once its table exists. */\ninterface ISqliteVecStatements {\n readonly delete: BetterSqlite3.Statement;\n readonly replace: (key: string, blob: Uint8Array) => void;\n readonly query: BetterSqlite3.Statement;\n readonly count: BetterSqlite3.Statement;\n}\n"]}
1
+ {"version":3,"file":"sqliteVecVectorIndex.js","sourceRoot":"","sources":["../../../src/packlets/sqlite-vec-index/sqliteVecVectorIndex.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,IAAI,IAAI,aAAa,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAU,kBAAkB,EAAE,aAAa,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACzF,OAAO,EAYL,aAAa,EACd,MAAM,sBAAsB,CAAC;AAG9B;;;;;;;;;;;;;;GAcG;AACH,KAAK,UAAU,UAAU,CAAI,IAA8B;IACzD,OAAO,CAAC,MAAM,kBAAkB,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC;AACtE,CAAC;AAED;;;;;;GAMG;AACH,SAAS,gBAAgB,CAAC,KAAa,EAAE,QAAsB;IAC7D,OAAO,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,GAAG,KAAK,2BAA2B,QAAQ,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC;AAC/F,CAAC;AAED,iDAAiD;AACjD,MAAM,kBAAkB,GAAW,gBAAgB,CAAC;AAEpD,yGAAyG;AACzG,MAAM,aAAa,GAAW,0BAA0B,CAAC;AAQzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAM,OAAO,oBA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8BAA8B,IAAI,CAAC,MAAM,GAAG,CAAC;SACtE,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACK,MAAM,CAAC,sBAAsB,CAAC,EAA0B,EAAE,KAAa;QAC7E,MAAM,GAAG,GAAgC,EAAE;aACxC,OAAO,CAAC,iEAAiE,CAAC;aAC1E,GAAG,CAAC,KAAK,CAAgC,CAAC;QAC7C,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;YACtB,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,MAAM,KAAK,GAA4B,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;QACvE,OAAO,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,CAAC;IAED,sHAAsH;IAC9G,MAAM,CAAC,OAAO,CAAC,MAAoB;QACzC,OAAO,IAAI,UAAU,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC;IAC1D,CAAC;IAED;;;OAGG;IACK,MAAM,CAAC,SAAS,CAAC,GAAW;QAClC,MAAM,GAAG,GAAW,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACtC,OAAO;YACL,KAAK,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAA8B;YACrD,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,CAAwB;SAC9C,CAAC;IACJ,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport type BetterSqlite3 from 'better-sqlite3';\nimport { load as loadSqliteVec } from 'sqlite-vec';\nimport { Result, captureAsyncResult, captureResult, fail, succeed } from '@fgv/ts-utils';\nimport {\n IEdgeTarget,\n IMemoryRecordSource,\n IScopedMemoryRecord,\n ISkippedVectorRecord,\n IVectorIndex,\n IVectorQueryHit,\n IVectorRebuildOptions,\n IVectorRebuildReport,\n MemoryEmbedder,\n MemoryId,\n MemoryScopeKey,\n edgeTargetKey\n} from '@fgv/ts-agent-memory';\nimport { ISqliteVecVectorIndexCreateParams } from './model';\n\n/**\n * Invoke a consumer-supplied hook that already returns a `Result`, converting a\n * synchronous throw or a promise rejection into a `Failure` rather than letting\n * it escape. `captureAsyncResult` wraps the hook's own `Result`, so the outcome\n * is flattened back to one level.\n *\n * @remarks\n * This is `@fgv/ts-utils`' own `_invokeDeferred` shape (see `mapResultsAsync`),\n * which is `@internal` there and so cannot be imported. `@fgv/ts-agent-memory`\n * carries an identical private copy for the in-memory index. Exporting a single\n * `AsyncDeferredResult`-invoking primitive from `ts-utils` is the right home and\n * is recorded in `docs/TECH_DEBT.md`; duplicating three lines twice is the\n * cheaper thing to do from inside this stream than widening it to a foundational\n * library.\n */\nasync function invokeHook<T>(hook: () => Promise<Result<T>>): Promise<Result<T>> {\n return (await captureAsyncResult(hook)).onSuccess((inner) => inner);\n}\n\n/**\n * Compose the failure that aborted a rebuild with the outcome of the rollback\n * that followed it. A rollback that ALSO fails is worth saying out loud: the\n * `'fail'` path promises an empty index, and a caller that retries against a\n * table which is neither the old index nor empty is working from a state the\n * contract never described.\n */\nfunction withRollbackNote(error: string, rollback: Result<true>): string {\n return rollback.isFailure() ? `${error} (rollback also failed: ${rollback.message})` : error;\n}\n\n/** Default name for the `vec0` virtual table. */\nconst DEFAULT_TABLE_NAME: string = 'memory_vectors';\n\n/** A simple SQL identifier — the only shape allowed for the table name (it is interpolated into DDL). */\nconst IDENTIFIER_RE: RegExp = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** One KNN row as returned by the `vec0` MATCH query. */\ninterface IKnnRow {\n readonly target_key: string;\n readonly distance: number;\n}\n\n/**\n * A persistent, `sqlite-vec`-backed `IVectorIndex` for `@fgv/ts-agent-memory`.\n *\n * @remarks\n * This is the **durable** counterpart to the in-memory `InMemoryCosineIndex`:\n * embeddings live in a `sqlite-vec` `vec0` virtual table inside a `better-sqlite3`\n * database, so they survive a process restart. A consumer that wires this index\n * into `FileTreeMemoryStore` (instead of the in-memory index) opens an existing\n * vault **without re-embedding it** — the vectors are already on disk. New writes\n * still flow through the store's incremental embed-on-write path; there is no core\n * store change.\n *\n * The index is keyed by the canonical `edgeTargetKey` of each record's\n * scope-qualified `(scope, id)` address (a `TEXT PRIMARY KEY` on the `vec0` table),\n * so two records that share a filename stem across scopes never collide. The\n * dimension is established by the first `add` (the `vec0` column is fixed-width) and\n * recovered from the table schema when a persistent file is reopened; every later\n * `add`/`query` must match it or fail loudly, exactly as the in-memory index does.\n * Similarity is cosine (`distance_metric=cosine`): the returned `score` is\n * `1 - cosineDistance`, i.e. cosine similarity in `[-1, 1]`, higher = more similar —\n * byte-for-byte the same scoring contract as `InMemoryCosineIndex`.\n *\n * Query is a brute-force `vec0` KNN scan (not an ANN structure): correct and\n * durable, appropriate for the same \"thousands of records\" regime the in-memory\n * index targets. Large-N ANN indexing is explicitly out of scope — see the README.\n *\n * The `better-sqlite3` `Database` is consumer-owned (bring-your-own): this index\n * loads the `sqlite-vec` extension onto it and reads/writes the table, but never\n * opens or closes the connection.\n * @public\n */\nexport class SqliteVecVectorIndex implements IVectorIndex {\n private readonly _db: BetterSqlite3.Database;\n private readonly _table: string;\n /** The dimension of every stored vector; `undefined` until the table exists (first `add` or a reopened non-empty file). */\n private _dimension: number | undefined;\n /** Prepared statements; created once the table exists (established or recovered). */\n private _stmts: ISqliteVecStatements | undefined;\n\n private constructor(db: BetterSqlite3.Database, table: string, dimension: number | undefined) {\n this._db = db;\n this._table = table;\n this._dimension = dimension;\n this._stmts = dimension === undefined ? undefined : this._prepare();\n }\n\n /** The number of vectors currently held. Zero before the first `add`. */\n public get size(): number {\n if (this._stmts === undefined) {\n return 0;\n }\n return (this._stmts.count.get() as { c: number }).c;\n }\n\n /**\n * Family-convention factory. Loads the `sqlite-vec` extension onto the supplied\n * `better-sqlite3` connection and, if the vector table already exists (a reopened\n * persistent file), recovers its established dimension so no re-embedding is\n * needed on open.\n *\n * @param params - See {@link ISqliteVecVectorIndexCreateParams}.\n * @returns `Success` with the index, or `Failure` if the table name is not a\n * simple identifier or the extension fails to load.\n */\n public static create(params: ISqliteVecVectorIndexCreateParams): Promise<Result<SqliteVecVectorIndex>> {\n const table: string = params.tableName ?? DEFAULT_TABLE_NAME;\n if (!IDENTIFIER_RE.test(table)) {\n return Promise.resolve(fail(`sqlite-vec index: table name '${table}' is not a simple SQL identifier`));\n }\n return Promise.resolve(\n captureResult(() => {\n loadSqliteVec(params.database);\n const dimension: number | undefined = SqliteVecVectorIndex._readExistingDimension(\n params.database,\n table\n );\n return new SqliteVecVectorIndex(params.database, table, dimension);\n }).withErrorFormat((e) => `sqlite-vec index: failed to initialize: ${e}`)\n );\n }\n\n /** {@inheritDoc IVectorIndex.add} */\n public add(target: IEdgeTarget, vector: Float32Array): Promise<Result<string>> {\n const key: string = edgeTargetKey(target);\n if (vector.length === 0) {\n return Promise.resolve(fail(`vector index: cannot add '${key}': empty vector`));\n }\n if (this._dimension !== undefined && vector.length !== this._dimension) {\n return Promise.resolve(\n fail(\n `vector index: cannot add '${key}': dimension ${vector.length} does not match index dimension ${this._dimension}`\n )\n );\n }\n return Promise.resolve(\n captureResult(() => {\n if (this._stmts === undefined) {\n this._createTable(vector.length);\n this._dimension = vector.length;\n this._stmts = this._prepare();\n }\n this._stmts.replace(key, SqliteVecVectorIndex._toBlob(vector));\n return key;\n }).withErrorFormat((e) => `vector index: cannot add '${key}': ${e}`)\n );\n }\n\n /** {@inheritDoc IVectorIndex.remove} */\n public remove(target: IEdgeTarget): Promise<Result<IEdgeTarget>> {\n return Promise.resolve(\n captureResult(() => {\n // Idempotent: removing a target with no embedding (or before any `add`\n // created the table) still succeeds.\n if (this._stmts !== undefined) {\n this._stmts.delete.run(edgeTargetKey(target));\n }\n return target;\n }).withErrorFormat((e) => `vector index: cannot remove '${edgeTargetKey(target)}': ${e}`)\n );\n }\n\n /**\n * Re-embed every record from `source` and rebuild the persisted index — see\n * `IVectorIndex.rebuild` for the mode semantics, which this implementation\n * matches exactly.\n *\n * @remarks\n * **Not atomic, and cannot be.** `better-sqlite3` transactions are synchronous,\n * so one cannot span the `await embed(...)` calls this loop makes — unlike\n * {@link SqliteVecVectorIndex.add}, which wraps its delete-then-insert. The\n * `'fail'` / `'skip'` modes therefore cover only failures JavaScript can catch:\n * a process kill mid-rebuild leaves the table holding neither the old index nor\n * the complete new one, and the remedy is to run `rebuild` again.\n */\n public async rebuild(\n source: IMemoryRecordSource,\n embed: MemoryEmbedder,\n options?: IVectorRebuildOptions\n ): Promise<Result<IVectorRebuildReport>> {\n const lenient: boolean = (options?.onRecordError ?? 'fail') === 'skip';\n // `source` is consumer-supplied, so a throw or rejection becomes a `Failure`\n // here rather than escaping as an exception.\n const listed: Result<ReadonlyArray<IScopedMemoryRecord>> = await invokeHook(() => source.list());\n if (listed.isFailure()) {\n // Deliberately BEFORE any clear: a failed list is no evidence about the\n // vectors already held, and no re-embedding has been attempted, so there is\n // no half-rebuilt state to protect against. Clearing here would destroy a\n // healthy persisted index over a transient read error.\n return fail(`vector index rebuild: failed to list records: ${listed.message}`);\n }\n const cleared: Result<true> = this._clear();\n if (cleared.isFailure()) {\n return fail(`vector index rebuild: failed to clear the index: ${cleared.message}`);\n }\n let declined: number = 0;\n const skipped: ISkippedVectorRecord[] = [];\n for (const scoped of listed.value) {\n // Likewise capture-wrapped: an embedder that throws mid-loop would\n // otherwise escape past the `'fail'` rollback below, leaving this DURABLE\n // table holding a partial index that survives the process.\n const embedded: Result<Float32Array | undefined> = await invokeHook(() => embed(scoped.record));\n if (embedded.isFailure()) {\n const error: string = `vector index rebuild: embedding '${edgeTargetKey(scoped.target)}' failed: ${\n embedded.message\n }`;\n if (!lenient) {\n return fail(withRollbackNote(error, this._clear()));\n }\n skipped.push({ target: scoped.target, error });\n continue;\n }\n if (embedded.value === undefined) {\n declined++;\n continue;\n }\n const added: Result<string> = await this.add(scoped.target, embedded.value);\n if (added.isFailure()) {\n const error: string = `vector index rebuild: ${added.message}`;\n if (!lenient) {\n return fail(withRollbackNote(error, this._clear()));\n }\n skipped.push({ target: scoped.target, error });\n }\n }\n return captureResult(() => this.size)\n .withErrorFormat((msg) => `vector index rebuild: failed to count the rebuilt index: ${msg}`)\n .onSuccess((indexed) => succeed({ indexed, declined, skipped }));\n }\n\n /**\n * Empty the table. Deliberately does NOT drop it or forget the established\n * dimension: the `vec0` table's dimension is fixed at creation and a re-embed at\n * a different dimension needs a drop-and-re-index, which is a consumer decision\n * (see the package README on `vec0` schema changes), not something a rebuild\n * should do silently.\n */\n private _clear(): Result<true> {\n if (this._stmts === undefined) {\n return succeed(true);\n }\n // Capture-wrapped like `add` / `remove` / `query`: a closed connection or an\n // I/O error here is a `Failure`, not an exception thrown out of a method\n // whose signature promises a `Result`.\n return captureResult(() => this._db.prepare(`DELETE FROM \"${this._table}\"`).run()).onSuccess(() =>\n succeed(true)\n );\n }\n\n /** {@inheritDoc IVectorIndex.query} */\n public query(vector: Float32Array, topK: number): Promise<Result<ReadonlyArray<IVectorQueryHit>>> {\n if (topK <= 0 || this._stmts === undefined) {\n return Promise.resolve(succeed([]));\n }\n if (vector.length !== this._dimension) {\n return Promise.resolve(\n fail(\n `vector index: query dimension ${vector.length} does not match index dimension ${this._dimension}`\n )\n );\n }\n return Promise.resolve(\n captureResult<ReadonlyArray<IVectorQueryHit>>(() => {\n const rows: ReadonlyArray<IKnnRow> = this._stmts!.query.all(\n SqliteVecVectorIndex._toBlob(vector),\n topK\n ) as ReadonlyArray<IKnnRow>;\n // sqlite-vec returns rows in ascending distance (nearest first); score is\n // `1 - cosineDistance` = cosine similarity, so descending score is preserved.\n return rows.map((row) => ({\n target: SqliteVecVectorIndex._parseKey(row.target_key),\n score: 1 - row.distance\n }));\n }).withErrorFormat((e) => `vector index: query failed: ${e}`)\n );\n }\n\n /** Create the `vec0` virtual table with the established dimension. */\n private _createTable(dimension: number): void {\n this._db.exec(\n `CREATE VIRTUAL TABLE IF NOT EXISTS \"${this._table}\" USING vec0(` +\n `target_key TEXT PRIMARY KEY, embedding float[${dimension}] distance_metric=cosine)`\n );\n }\n\n /** Prepare the statements the index reuses. Requires the table to exist. */\n private _prepare(): ISqliteVecStatements {\n const del: BetterSqlite3.Statement = this._db.prepare(\n `DELETE FROM \"${this._table}\" WHERE target_key = ?`\n );\n const ins: BetterSqlite3.Statement = this._db.prepare(\n `INSERT INTO \"${this._table}\"(target_key, embedding) VALUES (?, ?)`\n );\n // vec0 rejects INSERT OR REPLACE on a TEXT primary key, so replace is a\n // delete-then-insert inside a single transaction.\n const replaceTxn: BetterSqlite3.Transaction<(key: string, blob: Uint8Array) => void> =\n this._db.transaction((key: string, blob: Uint8Array) => {\n del.run(key);\n ins.run(key, blob);\n });\n return {\n delete: del,\n replace: (key: string, blob: Uint8Array): void => {\n replaceTxn(key, blob);\n },\n query: this._db.prepare(\n `SELECT target_key, distance FROM \"${this._table}\" WHERE embedding MATCH ? AND k = ?`\n ),\n count: this._db.prepare(`SELECT count(*) AS c FROM \"${this._table}\"`)\n };\n }\n\n /**\n * Recover the established dimension of an existing `vec0` table from its stored\n * `CREATE VIRTUAL TABLE` SQL (`float[<n>]`). Returns `undefined` when the table\n * does not exist yet (a fresh database — dimension is set by the first `add`).\n */\n private static _readExistingDimension(db: BetterSqlite3.Database, table: string): number | undefined {\n const row: { sql: string } | undefined = db\n .prepare(\"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\")\n .get(table) as { sql: string } | undefined;\n if (row === undefined) {\n return undefined;\n }\n const match: RegExpMatchArray | null = row.sql.match(/float\\[(\\d+)\\]/);\n return match === null ? undefined : Number(match[1]);\n }\n\n /** Pack a `Float32Array` as the little-endian byte blob `vec0` stores. Copies, so the caller may reuse its buffer. */\n private static _toBlob(vector: Float32Array): Uint8Array {\n return new Uint8Array(Float32Array.from(vector).buffer);\n }\n\n /**\n * Reverse `edgeTargetKey` — the canonical key is `scope\\0id` with NUL\n * excluded from both components, so the first NUL splits it unambiguously.\n */\n private static _parseKey(key: string): IEdgeTarget {\n const nul: number = key.indexOf('\\0');\n return {\n scope: key.slice(0, nul) as unknown as MemoryScopeKey,\n id: key.slice(nul + 1) as unknown as MemoryId\n };\n }\n}\n\n/** The prepared statements / helpers the index reuses once its table exists. */\ninterface ISqliteVecStatements {\n readonly delete: BetterSqlite3.Statement;\n readonly replace: (key: string, blob: Uint8Array) => void;\n readonly query: BetterSqlite3.Statement;\n readonly count: BetterSqlite3.Statement;\n}\n"]}
@@ -2,8 +2,12 @@ import type BetterSqlite3 from 'better-sqlite3';
2
2
  import { IEdgeTarget } from '@fgv/ts-agent-memory';
3
3
  import { IEmbeddedFragment } from '@fgv/ts-agent-memory';
4
4
  import { IFragmentVectorIndex } from '@fgv/ts-agent-memory';
5
+ import { IMemoryRecordSource } from '@fgv/ts-agent-memory';
5
6
  import { IVectorIndex } from '@fgv/ts-agent-memory';
6
7
  import { IVectorQueryHit } from '@fgv/ts-agent-memory';
8
+ import { IVectorRebuildOptions } from '@fgv/ts-agent-memory';
9
+ import { IVectorRebuildReport } from '@fgv/ts-agent-memory';
10
+ import { MemoryEmbedder } from '@fgv/ts-agent-memory';
7
11
  import { Result } from '@fgv/ts-utils';
8
12
 
9
13
  /**
@@ -258,6 +262,28 @@ export declare class SqliteVecVectorIndex implements IVectorIndex {
258
262
  add(target: IEdgeTarget, vector: Float32Array): Promise<Result<string>>;
259
263
  /** {@inheritDoc IVectorIndex.remove} */
260
264
  remove(target: IEdgeTarget): Promise<Result<IEdgeTarget>>;
265
+ /**
266
+ * Re-embed every record from `source` and rebuild the persisted index — see
267
+ * `IVectorIndex.rebuild` for the mode semantics, which this implementation
268
+ * matches exactly.
269
+ *
270
+ * @remarks
271
+ * **Not atomic, and cannot be.** `better-sqlite3` transactions are synchronous,
272
+ * so one cannot span the `await embed(...)` calls this loop makes — unlike
273
+ * {@link SqliteVecVectorIndex.add}, which wraps its delete-then-insert. The
274
+ * `'fail'` / `'skip'` modes therefore cover only failures JavaScript can catch:
275
+ * a process kill mid-rebuild leaves the table holding neither the old index nor
276
+ * the complete new one, and the remedy is to run `rebuild` again.
277
+ */
278
+ rebuild(source: IMemoryRecordSource, embed: MemoryEmbedder, options?: IVectorRebuildOptions): Promise<Result<IVectorRebuildReport>>;
279
+ /**
280
+ * Empty the table. Deliberately does NOT drop it or forget the established
281
+ * dimension: the `vec0` table's dimension is fixed at creation and a re-embed at
282
+ * a different dimension needs a drop-and-re-index, which is a consumer decision
283
+ * (see the package README on `vec0` schema changes), not something a rebuild
284
+ * should do silently.
285
+ */
286
+ private _clear;
261
287
  /** {@inheritDoc IVectorIndex.query} */
262
288
  query(vector: Float32Array, topK: number): Promise<Result<ReadonlyArray<IVectorQueryHit>>>;
263
289
  /** Create the `vec0` virtual table with the established dimension. */
@@ -1,5 +1,5 @@
1
1
  import { Result } from '@fgv/ts-utils';
2
- import { IEdgeTarget, IVectorIndex, IVectorQueryHit } from '@fgv/ts-agent-memory';
2
+ import { IEdgeTarget, IMemoryRecordSource, IVectorIndex, IVectorQueryHit, IVectorRebuildOptions, IVectorRebuildReport, MemoryEmbedder } from '@fgv/ts-agent-memory';
3
3
  import { ISqliteVecVectorIndexCreateParams } from './model';
4
4
  /**
5
5
  * A persistent, `sqlite-vec`-backed `IVectorIndex` for `@fgv/ts-agent-memory`.
@@ -57,6 +57,28 @@ export declare class SqliteVecVectorIndex implements IVectorIndex {
57
57
  add(target: IEdgeTarget, vector: Float32Array): Promise<Result<string>>;
58
58
  /** {@inheritDoc IVectorIndex.remove} */
59
59
  remove(target: IEdgeTarget): Promise<Result<IEdgeTarget>>;
60
+ /**
61
+ * Re-embed every record from `source` and rebuild the persisted index — see
62
+ * `IVectorIndex.rebuild` for the mode semantics, which this implementation
63
+ * matches exactly.
64
+ *
65
+ * @remarks
66
+ * **Not atomic, and cannot be.** `better-sqlite3` transactions are synchronous,
67
+ * so one cannot span the `await embed(...)` calls this loop makes — unlike
68
+ * {@link SqliteVecVectorIndex.add}, which wraps its delete-then-insert. The
69
+ * `'fail'` / `'skip'` modes therefore cover only failures JavaScript can catch:
70
+ * a process kill mid-rebuild leaves the table holding neither the old index nor
71
+ * the complete new one, and the remedy is to run `rebuild` again.
72
+ */
73
+ rebuild(source: IMemoryRecordSource, embed: MemoryEmbedder, options?: IVectorRebuildOptions): Promise<Result<IVectorRebuildReport>>;
74
+ /**
75
+ * Empty the table. Deliberately does NOT drop it or forget the established
76
+ * dimension: the `vec0` table's dimension is fixed at creation and a re-embed at
77
+ * a different dimension needs a drop-and-re-index, which is a consumer decision
78
+ * (see the package README on `vec0` schema changes), not something a rebuild
79
+ * should do silently.
80
+ */
81
+ private _clear;
60
82
  /** {@inheritDoc IVectorIndex.query} */
61
83
  query(vector: Float32Array, topK: number): Promise<Result<ReadonlyArray<IVectorQueryHit>>>;
62
84
  /** Create the `vec0` virtual table with the established dimension. */
@@ -1 +1 @@
1
- {"version":3,"file":"sqliteVecVectorIndex.d.ts","sourceRoot":"","sources":["../../../src/packlets/sqlite-vec-index/sqliteVecVectorIndex.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,MAAM,EAAgC,MAAM,eAAe,CAAC;AACrE,OAAO,EACL,WAAW,EACX,YAAY,EACZ,eAAe,EAIhB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,iCAAiC,EAAE,MAAM,SAAS,CAAC;AAc5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,qBAAa,oBAAqB,YAAW,YAAY;IACvD,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAyB;IAC7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,2HAA2H;IAC3H,OAAO,CAAC,UAAU,CAAqB;IACvC,qFAAqF;IACrF,OAAO,CAAC,MAAM,CAAmC;IAEjD,OAAO;IAOP,yEAAyE;IACzE,IAAW,IAAI,IAAI,MAAM,CAKxB;IAED;;;;;;;;;OASG;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AC3H,OAAO,CAAC,UAAU,CAAqB;IACvC,qFAAqF;IACrF,OAAO,CAAC,MAAM,CAAmC;IAEjD,OAAO;IAOP,yEAAyE;IACzE,IAAW,IAAI,IAAI,MAAM,CAKxB;IAED;;;;;;;;;OASG;WACW,MAAM,CAAC,MAAM,EAAE,iCAAiC,GAAG,OAAO,CAAC,MAAM,CAAC,oBAAoB,CAAC,CAAC;IAiBtG,qCAAqC;IAC9B,GAAG,CAAC,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAyB9E,wCAAwC;IACjC,MAAM,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAahE;;;;;;;;;;;;OAYG;IACU,OAAO,CAClB,MAAM,EAAE,mBAAmB,EAC3B,KAAK,EAAE,cAAc,EACrB,OAAO,CAAC,EAAE,qBAAqB,GAC9B,OAAO,CAAC,MAAM,CAAC,oBAAoB,CAAC,CAAC;IAmDxC;;;;;;OAMG;IACH,OAAO,CAAC,MAAM;IAYd,uCAAuC;IAChC,KAAK,CAAC,MAAM,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,eAAe,CAAC,CAAC,CAAC;IA2BjG,sEAAsE;IACtE,OAAO,CAAC,YAAY;IAOpB,4EAA4E;IAC5E,OAAO,CAAC,QAAQ;IA0BhB;;;;OAIG;IACH,OAAO,CAAC,MAAM,CAAC,sBAAsB;IAWrC,sHAAsH;IACtH,OAAO,CAAC,MAAM,CAAC,OAAO;IAItB;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,SAAS;CAOzB"}
@@ -8,6 +8,34 @@ exports.SqliteVecVectorIndex = void 0;
8
8
  const sqlite_vec_1 = require("sqlite-vec");
9
9
  const ts_utils_1 = require("@fgv/ts-utils");
10
10
  const ts_agent_memory_1 = require("@fgv/ts-agent-memory");
11
+ /**
12
+ * Invoke a consumer-supplied hook that already returns a `Result`, converting a
13
+ * synchronous throw or a promise rejection into a `Failure` rather than letting
14
+ * it escape. `captureAsyncResult` wraps the hook's own `Result`, so the outcome
15
+ * is flattened back to one level.
16
+ *
17
+ * @remarks
18
+ * This is `@fgv/ts-utils`' own `_invokeDeferred` shape (see `mapResultsAsync`),
19
+ * which is `@internal` there and so cannot be imported. `@fgv/ts-agent-memory`
20
+ * carries an identical private copy for the in-memory index. Exporting a single
21
+ * `AsyncDeferredResult`-invoking primitive from `ts-utils` is the right home and
22
+ * is recorded in `docs/TECH_DEBT.md`; duplicating three lines twice is the
23
+ * cheaper thing to do from inside this stream than widening it to a foundational
24
+ * library.
25
+ */
26
+ async function invokeHook(hook) {
27
+ return (await (0, ts_utils_1.captureAsyncResult)(hook)).onSuccess((inner) => inner);
28
+ }
29
+ /**
30
+ * Compose the failure that aborted a rebuild with the outcome of the rollback
31
+ * that followed it. A rollback that ALSO fails is worth saying out loud: the
32
+ * `'fail'` path promises an empty index, and a caller that retries against a
33
+ * table which is neither the old index nor empty is working from a state the
34
+ * contract never described.
35
+ */
36
+ function withRollbackNote(error, rollback) {
37
+ return rollback.isFailure() ? `${error} (rollback also failed: ${rollback.message})` : error;
38
+ }
11
39
  /** Default name for the `vec0` virtual table. */
12
40
  const DEFAULT_TABLE_NAME = 'memory_vectors';
13
41
  /** A simple SQL identifier — the only shape allowed for the table name (it is interpolated into DDL). */
@@ -109,6 +137,84 @@ class SqliteVecVectorIndex {
109
137
  return target;
110
138
  }).withErrorFormat((e) => `vector index: cannot remove '${(0, ts_agent_memory_1.edgeTargetKey)(target)}': ${e}`));
111
139
  }
140
+ /**
141
+ * Re-embed every record from `source` and rebuild the persisted index — see
142
+ * `IVectorIndex.rebuild` for the mode semantics, which this implementation
143
+ * matches exactly.
144
+ *
145
+ * @remarks
146
+ * **Not atomic, and cannot be.** `better-sqlite3` transactions are synchronous,
147
+ * so one cannot span the `await embed(...)` calls this loop makes — unlike
148
+ * {@link SqliteVecVectorIndex.add}, which wraps its delete-then-insert. The
149
+ * `'fail'` / `'skip'` modes therefore cover only failures JavaScript can catch:
150
+ * a process kill mid-rebuild leaves the table holding neither the old index nor
151
+ * the complete new one, and the remedy is to run `rebuild` again.
152
+ */
153
+ async rebuild(source, embed, options) {
154
+ var _a;
155
+ const lenient = ((_a = options === null || options === void 0 ? void 0 : options.onRecordError) !== null && _a !== void 0 ? _a : 'fail') === 'skip';
156
+ // `source` is consumer-supplied, so a throw or rejection becomes a `Failure`
157
+ // here rather than escaping as an exception.
158
+ const listed = await invokeHook(() => source.list());
159
+ if (listed.isFailure()) {
160
+ // Deliberately BEFORE any clear: a failed list is no evidence about the
161
+ // vectors already held, and no re-embedding has been attempted, so there is
162
+ // no half-rebuilt state to protect against. Clearing here would destroy a
163
+ // healthy persisted index over a transient read error.
164
+ return (0, ts_utils_1.fail)(`vector index rebuild: failed to list records: ${listed.message}`);
165
+ }
166
+ const cleared = this._clear();
167
+ if (cleared.isFailure()) {
168
+ return (0, ts_utils_1.fail)(`vector index rebuild: failed to clear the index: ${cleared.message}`);
169
+ }
170
+ let declined = 0;
171
+ const skipped = [];
172
+ for (const scoped of listed.value) {
173
+ // Likewise capture-wrapped: an embedder that throws mid-loop would
174
+ // otherwise escape past the `'fail'` rollback below, leaving this DURABLE
175
+ // table holding a partial index that survives the process.
176
+ const embedded = await invokeHook(() => embed(scoped.record));
177
+ if (embedded.isFailure()) {
178
+ const error = `vector index rebuild: embedding '${(0, ts_agent_memory_1.edgeTargetKey)(scoped.target)}' failed: ${embedded.message}`;
179
+ if (!lenient) {
180
+ return (0, ts_utils_1.fail)(withRollbackNote(error, this._clear()));
181
+ }
182
+ skipped.push({ target: scoped.target, error });
183
+ continue;
184
+ }
185
+ if (embedded.value === undefined) {
186
+ declined++;
187
+ continue;
188
+ }
189
+ const added = await this.add(scoped.target, embedded.value);
190
+ if (added.isFailure()) {
191
+ const error = `vector index rebuild: ${added.message}`;
192
+ if (!lenient) {
193
+ return (0, ts_utils_1.fail)(withRollbackNote(error, this._clear()));
194
+ }
195
+ skipped.push({ target: scoped.target, error });
196
+ }
197
+ }
198
+ return (0, ts_utils_1.captureResult)(() => this.size)
199
+ .withErrorFormat((msg) => `vector index rebuild: failed to count the rebuilt index: ${msg}`)
200
+ .onSuccess((indexed) => (0, ts_utils_1.succeed)({ indexed, declined, skipped }));
201
+ }
202
+ /**
203
+ * Empty the table. Deliberately does NOT drop it or forget the established
204
+ * dimension: the `vec0` table's dimension is fixed at creation and a re-embed at
205
+ * a different dimension needs a drop-and-re-index, which is a consumer decision
206
+ * (see the package README on `vec0` schema changes), not something a rebuild
207
+ * should do silently.
208
+ */
209
+ _clear() {
210
+ if (this._stmts === undefined) {
211
+ return (0, ts_utils_1.succeed)(true);
212
+ }
213
+ // Capture-wrapped like `add` / `remove` / `query`: a closed connection or an
214
+ // I/O error here is a `Failure`, not an exception thrown out of a method
215
+ // whose signature promises a `Result`.
216
+ return (0, ts_utils_1.captureResult)(() => this._db.prepare(`DELETE FROM "${this._table}"`).run()).onSuccess(() => (0, ts_utils_1.succeed)(true));
217
+ }
112
218
  /** {@inheritDoc IVectorIndex.query} */
113
219
  query(vector, topK) {
114
220
  if (topK <= 0 || this._stmts === undefined) {
@@ -1 +1 @@
1
- {"version":3,"file":"sqliteVecVectorIndex.js","sourceRoot":"","sources":["../../../src/packlets/sqlite-vec-index/sqliteVecVectorIndex.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAGH,2CAAmD;AACnD,4CAAqE;AACrE,0DAO8B;AAG9B,iDAAiD;AACjD,MAAM,kBAAkB,GAAW,gBAAgB,CAAC;AAEpD,yGAAyG;AACzG,MAAM,aAAa,GAAW,0BAA0B,CAAC;AAQzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAa,oBAAoB;IAQ/B,YAAoB,EAA0B,EAAE,KAAa,EAAE,SAA6B;QAC1F,IAAI,CAAC,GAAG,GAAG,EA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AgC,CAAC;QAC7C,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;YACtB,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,MAAM,KAAK,GAA4B,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;QACvE,OAAO,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,CAAC;IAED,sHAAsH;IAC9G,MAAM,CAAC,OAAO,CAAC,MAAoB;QACzC,OAAO,IAAI,UAAU,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC;IAC1D,CAAC;IAED;;;OAGG;IACK,MAAM,CAAC,SAAS,CAAC,GAAW;QAClC,MAAM,GAAG,GAAW,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACtC,OAAO;YACL,KAAK,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAA8B;YACrD,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,CAAwB;SAC9C,CAAC;IACJ,CAAC;CACF;AAzLD,oDAyLC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport type BetterSqlite3 from 'better-sqlite3';\nimport { load as loadSqliteVec } from 'sqlite-vec';\nimport { Result, captureResult, fail, succeed } from '@fgv/ts-utils';\nimport {\n IEdgeTarget,\n IVectorIndex,\n IVectorQueryHit,\n MemoryId,\n MemoryScopeKey,\n edgeTargetKey\n} from '@fgv/ts-agent-memory';\nimport { ISqliteVecVectorIndexCreateParams } from './model';\n\n/** Default name for the `vec0` virtual table. */\nconst DEFAULT_TABLE_NAME: string = 'memory_vectors';\n\n/** A simple SQL identifier — the only shape allowed for the table name (it is interpolated into DDL). */\nconst IDENTIFIER_RE: RegExp = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** One KNN row as returned by the `vec0` MATCH query. */\ninterface IKnnRow {\n readonly target_key: string;\n readonly distance: number;\n}\n\n/**\n * A persistent, `sqlite-vec`-backed `IVectorIndex` for `@fgv/ts-agent-memory`.\n *\n * @remarks\n * This is the **durable** counterpart to the in-memory `InMemoryCosineIndex`:\n * embeddings live in a `sqlite-vec` `vec0` virtual table inside a `better-sqlite3`\n * database, so they survive a process restart. A consumer that wires this index\n * into `FileTreeMemoryStore` (instead of the in-memory index) opens an existing\n * vault **without re-embedding it** — the vectors are already on disk. New writes\n * still flow through the store's incremental embed-on-write path; there is no core\n * store change.\n *\n * The index is keyed by the canonical `edgeTargetKey` of each record's\n * scope-qualified `(scope, id)` address (a `TEXT PRIMARY KEY` on the `vec0` table),\n * so two records that share a filename stem across scopes never collide. The\n * dimension is established by the first `add` (the `vec0` column is fixed-width) and\n * recovered from the table schema when a persistent file is reopened; every later\n * `add`/`query` must match it or fail loudly, exactly as the in-memory index does.\n * Similarity is cosine (`distance_metric=cosine`): the returned `score` is\n * `1 - cosineDistance`, i.e. cosine similarity in `[-1, 1]`, higher = more similar —\n * byte-for-byte the same scoring contract as `InMemoryCosineIndex`.\n *\n * Query is a brute-force `vec0` KNN scan (not an ANN structure): correct and\n * durable, appropriate for the same \"thousands of records\" regime the in-memory\n * index targets. Large-N ANN indexing is explicitly out of scope — see the README.\n *\n * The `better-sqlite3` `Database` is consumer-owned (bring-your-own): this index\n * loads the `sqlite-vec` extension onto it and reads/writes the table, but never\n * opens or closes the connection.\n * @public\n */\nexport class SqliteVecVectorIndex implements IVectorIndex {\n private readonly _db: BetterSqlite3.Database;\n private readonly _table: string;\n /** The dimension of every stored vector; `undefined` until the table exists (first `add` or a reopened non-empty file). */\n private _dimension: number | undefined;\n /** Prepared statements; created once the table exists (established or recovered). */\n private _stmts: ISqliteVecStatements | undefined;\n\n private constructor(db: BetterSqlite3.Database, table: string, dimension: number | undefined) {\n this._db = db;\n this._table = table;\n this._dimension = dimension;\n this._stmts = dimension === undefined ? undefined : this._prepare();\n }\n\n /** The number of vectors currently held. Zero before the first `add`. */\n public get size(): number {\n if (this._stmts === undefined) {\n return 0;\n }\n return (this._stmts.count.get() as { c: number }).c;\n }\n\n /**\n * Family-convention factory. Loads the `sqlite-vec` extension onto the supplied\n * `better-sqlite3` connection and, if the vector table already exists (a reopened\n * persistent file), recovers its established dimension so no re-embedding is\n * needed on open.\n *\n * @param params - See {@link ISqliteVecVectorIndexCreateParams}.\n * @returns `Success` with the index, or `Failure` if the table name is not a\n * simple identifier or the extension fails to load.\n */\n public static create(params: ISqliteVecVectorIndexCreateParams): Promise<Result<SqliteVecVectorIndex>> {\n const table: string = params.tableName ?? DEFAULT_TABLE_NAME;\n if (!IDENTIFIER_RE.test(table)) {\n return Promise.resolve(fail(`sqlite-vec index: table name '${table}' is not a simple SQL identifier`));\n }\n return Promise.resolve(\n captureResult(() => {\n loadSqliteVec(params.database);\n const dimension: number | undefined = SqliteVecVectorIndex._readExistingDimension(\n params.database,\n table\n );\n return new SqliteVecVectorIndex(params.database, table, dimension);\n }).withErrorFormat((e) => `sqlite-vec index: failed to initialize: ${e}`)\n );\n }\n\n /** {@inheritDoc IVectorIndex.add} */\n public add(target: IEdgeTarget, vector: Float32Array): Promise<Result<string>> {\n const key: string = edgeTargetKey(target);\n if (vector.length === 0) {\n return Promise.resolve(fail(`vector index: cannot add '${key}': empty vector`));\n }\n if (this._dimension !== undefined && vector.length !== this._dimension) {\n return Promise.resolve(\n fail(\n `vector index: cannot add '${key}': dimension ${vector.length} does not match index dimension ${this._dimension}`\n )\n );\n }\n return Promise.resolve(\n captureResult(() => {\n if (this._stmts === undefined) {\n this._createTable(vector.length);\n this._dimension = vector.length;\n this._stmts = this._prepare();\n }\n this._stmts.replace(key, SqliteVecVectorIndex._toBlob(vector));\n return key;\n }).withErrorFormat((e) => `vector index: cannot add '${key}': ${e}`)\n );\n }\n\n /** {@inheritDoc IVectorIndex.remove} */\n public remove(target: IEdgeTarget): Promise<Result<IEdgeTarget>> {\n return Promise.resolve(\n captureResult(() => {\n // Idempotent: removing a target with no embedding (or before any `add`\n // created the table) still succeeds.\n if (this._stmts !== undefined) {\n this._stmts.delete.run(edgeTargetKey(target));\n }\n return target;\n }).withErrorFormat((e) => `vector index: cannot remove '${edgeTargetKey(target)}': ${e}`)\n );\n }\n\n /** {@inheritDoc IVectorIndex.query} */\n public query(vector: Float32Array, topK: number): Promise<Result<ReadonlyArray<IVectorQueryHit>>> {\n if (topK <= 0 || this._stmts === undefined) {\n return Promise.resolve(succeed([]));\n }\n if (vector.length !== this._dimension) {\n return Promise.resolve(\n fail(\n `vector index: query dimension ${vector.length} does not match index dimension ${this._dimension}`\n )\n );\n }\n return Promise.resolve(\n captureResult<ReadonlyArray<IVectorQueryHit>>(() => {\n const rows: ReadonlyArray<IKnnRow> = this._stmts!.query.all(\n SqliteVecVectorIndex._toBlob(vector),\n topK\n ) as ReadonlyArray<IKnnRow>;\n // sqlite-vec returns rows in ascending distance (nearest first); score is\n // `1 - cosineDistance` = cosine similarity, so descending score is preserved.\n return rows.map((row) => ({\n target: SqliteVecVectorIndex._parseKey(row.target_key),\n score: 1 - row.distance\n }));\n }).withErrorFormat((e) => `vector index: query failed: ${e}`)\n );\n }\n\n /** Create the `vec0` virtual table with the established dimension. */\n private _createTable(dimension: number): void {\n this._db.exec(\n `CREATE VIRTUAL TABLE IF NOT EXISTS \"${this._table}\" USING vec0(` +\n `target_key TEXT PRIMARY KEY, embedding float[${dimension}] distance_metric=cosine)`\n );\n }\n\n /** Prepare the statements the index reuses. Requires the table to exist. */\n private _prepare(): ISqliteVecStatements {\n const del: BetterSqlite3.Statement = this._db.prepare(\n `DELETE FROM \"${this._table}\" WHERE target_key = ?`\n );\n const ins: BetterSqlite3.Statement = this._db.prepare(\n `INSERT INTO \"${this._table}\"(target_key, embedding) VALUES (?, ?)`\n );\n // vec0 rejects INSERT OR REPLACE on a TEXT primary key, so replace is a\n // delete-then-insert inside a single transaction.\n const replaceTxn: BetterSqlite3.Transaction<(key: string, blob: Uint8Array) => void> =\n this._db.transaction((key: string, blob: Uint8Array) => {\n del.run(key);\n ins.run(key, blob);\n });\n return {\n delete: del,\n replace: (key: string, blob: Uint8Array): void => {\n replaceTxn(key, blob);\n },\n query: this._db.prepare(\n `SELECT target_key, distance FROM \"${this._table}\" WHERE embedding MATCH ? AND k = ?`\n ),\n count: this._db.prepare(`SELECT count(*) AS c FROM \"${this._table}\"`)\n };\n }\n\n /**\n * Recover the established dimension of an existing `vec0` table from its stored\n * `CREATE VIRTUAL TABLE` SQL (`float[<n>]`). Returns `undefined` when the table\n * does not exist yet (a fresh database — dimension is set by the first `add`).\n */\n private static _readExistingDimension(db: BetterSqlite3.Database, table: string): number | undefined {\n const row: { sql: string } | undefined = db\n .prepare(\"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\")\n .get(table) as { sql: string } | undefined;\n if (row === undefined) {\n return undefined;\n }\n const match: RegExpMatchArray | null = row.sql.match(/float\\[(\\d+)\\]/);\n return match === null ? undefined : Number(match[1]);\n }\n\n /** Pack a `Float32Array` as the little-endian byte blob `vec0` stores. Copies, so the caller may reuse its buffer. */\n private static _toBlob(vector: Float32Array): Uint8Array {\n return new Uint8Array(Float32Array.from(vector).buffer);\n }\n\n /**\n * Reverse `edgeTargetKey` — the canonical key is `scope\\0id` with NUL\n * excluded from both components, so the first NUL splits it unambiguously.\n */\n private static _parseKey(key: string): IEdgeTarget {\n const nul: number = key.indexOf('\\0');\n return {\n scope: key.slice(0, nul) as unknown as MemoryScopeKey,\n id: key.slice(nul + 1) as unknown as MemoryId\n };\n }\n}\n\n/** The prepared statements / helpers the index reuses once its table exists. */\ninterface ISqliteVecStatements {\n readonly delete: BetterSqlite3.Statement;\n readonly replace: (key: string, blob: Uint8Array) => void;\n readonly query: BetterSqlite3.Statement;\n readonly count: BetterSqlite3.Statement;\n}\n"]}
1
+ {"version":3,"file":"sqliteVecVectorIndex.js","sourceRoot":"","sources":["../../../src/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AAC,CAAC;QACvE,OAAO,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,CAAC;IAED,sHAAsH;IAC9G,MAAM,CAAC,OAAO,CAAC,MAAoB;QACzC,OAAO,IAAI,UAAU,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC;IAC1D,CAAC;IAED;;;OAGG;IACK,MAAM,CAAC,SAAS,CAAC,GAAW;QAClC,MAAM,GAAG,GAAW,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACtC,OAAO;YACL,KAAK,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAA8B;YACrD,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,CAAwB;SAC9C,CAAC;IACJ,CAAC;CACF;AAhRD,oDAgRC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport type BetterSqlite3 from 'better-sqlite3';\nimport { load as loadSqliteVec } from 'sqlite-vec';\nimport { Result, captureAsyncResult, captureResult, fail, succeed } from '@fgv/ts-utils';\nimport {\n IEdgeTarget,\n IMemoryRecordSource,\n IScopedMemoryRecord,\n ISkippedVectorRecord,\n IVectorIndex,\n IVectorQueryHit,\n IVectorRebuildOptions,\n IVectorRebuildReport,\n MemoryEmbedder,\n MemoryId,\n MemoryScopeKey,\n edgeTargetKey\n} from '@fgv/ts-agent-memory';\nimport { ISqliteVecVectorIndexCreateParams } from './model';\n\n/**\n * Invoke a consumer-supplied hook that already returns a `Result`, converting a\n * synchronous throw or a promise rejection into a `Failure` rather than letting\n * it escape. `captureAsyncResult` wraps the hook's own `Result`, so the outcome\n * is flattened back to one level.\n *\n * @remarks\n * This is `@fgv/ts-utils`' own `_invokeDeferred` shape (see `mapResultsAsync`),\n * which is `@internal` there and so cannot be imported. `@fgv/ts-agent-memory`\n * carries an identical private copy for the in-memory index. Exporting a single\n * `AsyncDeferredResult`-invoking primitive from `ts-utils` is the right home and\n * is recorded in `docs/TECH_DEBT.md`; duplicating three lines twice is the\n * cheaper thing to do from inside this stream than widening it to a foundational\n * library.\n */\nasync function invokeHook<T>(hook: () => Promise<Result<T>>): Promise<Result<T>> {\n return (await captureAsyncResult(hook)).onSuccess((inner) => inner);\n}\n\n/**\n * Compose the failure that aborted a rebuild with the outcome of the rollback\n * that followed it. A rollback that ALSO fails is worth saying out loud: the\n * `'fail'` path promises an empty index, and a caller that retries against a\n * table which is neither the old index nor empty is working from a state the\n * contract never described.\n */\nfunction withRollbackNote(error: string, rollback: Result<true>): string {\n return rollback.isFailure() ? `${error} (rollback also failed: ${rollback.message})` : error;\n}\n\n/** Default name for the `vec0` virtual table. */\nconst DEFAULT_TABLE_NAME: string = 'memory_vectors';\n\n/** A simple SQL identifier — the only shape allowed for the table name (it is interpolated into DDL). */\nconst IDENTIFIER_RE: RegExp = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** One KNN row as returned by the `vec0` MATCH query. */\ninterface IKnnRow {\n readonly target_key: string;\n readonly distance: number;\n}\n\n/**\n * A persistent, `sqlite-vec`-backed `IVectorIndex` for `@fgv/ts-agent-memory`.\n *\n * @remarks\n * This is the **durable** counterpart to the in-memory `InMemoryCosineIndex`:\n * embeddings live in a `sqlite-vec` `vec0` virtual table inside a `better-sqlite3`\n * database, so they survive a process restart. A consumer that wires this index\n * into `FileTreeMemoryStore` (instead of the in-memory index) opens an existing\n * vault **without re-embedding it** — the vectors are already on disk. New writes\n * still flow through the store's incremental embed-on-write path; there is no core\n * store change.\n *\n * The index is keyed by the canonical `edgeTargetKey` of each record's\n * scope-qualified `(scope, id)` address (a `TEXT PRIMARY KEY` on the `vec0` table),\n * so two records that share a filename stem across scopes never collide. The\n * dimension is established by the first `add` (the `vec0` column is fixed-width) and\n * recovered from the table schema when a persistent file is reopened; every later\n * `add`/`query` must match it or fail loudly, exactly as the in-memory index does.\n * Similarity is cosine (`distance_metric=cosine`): the returned `score` is\n * `1 - cosineDistance`, i.e. cosine similarity in `[-1, 1]`, higher = more similar —\n * byte-for-byte the same scoring contract as `InMemoryCosineIndex`.\n *\n * Query is a brute-force `vec0` KNN scan (not an ANN structure): correct and\n * durable, appropriate for the same \"thousands of records\" regime the in-memory\n * index targets. Large-N ANN indexing is explicitly out of scope — see the README.\n *\n * The `better-sqlite3` `Database` is consumer-owned (bring-your-own): this index\n * loads the `sqlite-vec` extension onto it and reads/writes the table, but never\n * opens or closes the connection.\n * @public\n */\nexport class SqliteVecVectorIndex implements IVectorIndex {\n private readonly _db: BetterSqlite3.Database;\n private readonly _table: string;\n /** The dimension of every stored vector; `undefined` until the table exists (first `add` or a reopened non-empty file). */\n private _dimension: number | undefined;\n /** Prepared statements; created once the table exists (established or recovered). */\n private _stmts: ISqliteVecStatements | undefined;\n\n private constructor(db: BetterSqlite3.Database, table: string, dimension: number | undefined) {\n this._db = db;\n this._table = table;\n this._dimension = dimension;\n this._stmts = dimension === undefined ? undefined : this._prepare();\n }\n\n /** The number of vectors currently held. Zero before the first `add`. */\n public get size(): number {\n if (this._stmts === undefined) {\n return 0;\n }\n return (this._stmts.count.get() as { c: number }).c;\n }\n\n /**\n * Family-convention factory. Loads the `sqlite-vec` extension onto the supplied\n * `better-sqlite3` connection and, if the vector table already exists (a reopened\n * persistent file), recovers its established dimension so no re-embedding is\n * needed on open.\n *\n * @param params - See {@link ISqliteVecVectorIndexCreateParams}.\n * @returns `Success` with the index, or `Failure` if the table name is not a\n * simple identifier or the extension fails to load.\n */\n public static create(params: ISqliteVecVectorIndexCreateParams): Promise<Result<SqliteVecVectorIndex>> {\n const table: string = params.tableName ?? DEFAULT_TABLE_NAME;\n if (!IDENTIFIER_RE.test(table)) {\n return Promise.resolve(fail(`sqlite-vec index: table name '${table}' is not a simple SQL identifier`));\n }\n return Promise.resolve(\n captureResult(() => {\n loadSqliteVec(params.database);\n const dimension: number | undefined = SqliteVecVectorIndex._readExistingDimension(\n params.database,\n table\n );\n return new SqliteVecVectorIndex(params.database, table, dimension);\n }).withErrorFormat((e) => `sqlite-vec index: failed to initialize: ${e}`)\n );\n }\n\n /** {@inheritDoc IVectorIndex.add} */\n public add(target: IEdgeTarget, vector: Float32Array): Promise<Result<string>> {\n const key: string = edgeTargetKey(target);\n if (vector.length === 0) {\n return Promise.resolve(fail(`vector index: cannot add '${key}': empty vector`));\n }\n if (this._dimension !== undefined && vector.length !== this._dimension) {\n return Promise.resolve(\n fail(\n `vector index: cannot add '${key}': dimension ${vector.length} does not match index dimension ${this._dimension}`\n )\n );\n }\n return Promise.resolve(\n captureResult(() => {\n if (this._stmts === undefined) {\n this._createTable(vector.length);\n this._dimension = vector.length;\n this._stmts = this._prepare();\n }\n this._stmts.replace(key, SqliteVecVectorIndex._toBlob(vector));\n return key;\n }).withErrorFormat((e) => `vector index: cannot add '${key}': ${e}`)\n );\n }\n\n /** {@inheritDoc IVectorIndex.remove} */\n public remove(target: IEdgeTarget): Promise<Result<IEdgeTarget>> {\n return Promise.resolve(\n captureResult(() => {\n // Idempotent: removing a target with no embedding (or before any `add`\n // created the table) still succeeds.\n if (this._stmts !== undefined) {\n this._stmts.delete.run(edgeTargetKey(target));\n }\n return target;\n }).withErrorFormat((e) => `vector index: cannot remove '${edgeTargetKey(target)}': ${e}`)\n );\n }\n\n /**\n * Re-embed every record from `source` and rebuild the persisted index — see\n * `IVectorIndex.rebuild` for the mode semantics, which this implementation\n * matches exactly.\n *\n * @remarks\n * **Not atomic, and cannot be.** `better-sqlite3` transactions are synchronous,\n * so one cannot span the `await embed(...)` calls this loop makes — unlike\n * {@link SqliteVecVectorIndex.add}, which wraps its delete-then-insert. The\n * `'fail'` / `'skip'` modes therefore cover only failures JavaScript can catch:\n * a process kill mid-rebuild leaves the table holding neither the old index nor\n * the complete new one, and the remedy is to run `rebuild` again.\n */\n public async rebuild(\n source: IMemoryRecordSource,\n embed: MemoryEmbedder,\n options?: IVectorRebuildOptions\n ): Promise<Result<IVectorRebuildReport>> {\n const lenient: boolean = (options?.onRecordError ?? 'fail') === 'skip';\n // `source` is consumer-supplied, so a throw or rejection becomes a `Failure`\n // here rather than escaping as an exception.\n const listed: Result<ReadonlyArray<IScopedMemoryRecord>> = await invokeHook(() => source.list());\n if (listed.isFailure()) {\n // Deliberately BEFORE any clear: a failed list is no evidence about the\n // vectors already held, and no re-embedding has been attempted, so there is\n // no half-rebuilt state to protect against. Clearing here would destroy a\n // healthy persisted index over a transient read error.\n return fail(`vector index rebuild: failed to list records: ${listed.message}`);\n }\n const cleared: Result<true> = this._clear();\n if (cleared.isFailure()) {\n return fail(`vector index rebuild: failed to clear the index: ${cleared.message}`);\n }\n let declined: number = 0;\n const skipped: ISkippedVectorRecord[] = [];\n for (const scoped of listed.value) {\n // Likewise capture-wrapped: an embedder that throws mid-loop would\n // otherwise escape past the `'fail'` rollback below, leaving this DURABLE\n // table holding a partial index that survives the process.\n const embedded: Result<Float32Array | undefined> = await invokeHook(() => embed(scoped.record));\n if (embedded.isFailure()) {\n const error: string = `vector index rebuild: embedding '${edgeTargetKey(scoped.target)}' failed: ${\n embedded.message\n }`;\n if (!lenient) {\n return fail(withRollbackNote(error, this._clear()));\n }\n skipped.push({ target: scoped.target, error });\n continue;\n }\n if (embedded.value === undefined) {\n declined++;\n continue;\n }\n const added: Result<string> = await this.add(scoped.target, embedded.value);\n if (added.isFailure()) {\n const error: string = `vector index rebuild: ${added.message}`;\n if (!lenient) {\n return fail(withRollbackNote(error, this._clear()));\n }\n skipped.push({ target: scoped.target, error });\n }\n }\n return captureResult(() => this.size)\n .withErrorFormat((msg) => `vector index rebuild: failed to count the rebuilt index: ${msg}`)\n .onSuccess((indexed) => succeed({ indexed, declined, skipped }));\n }\n\n /**\n * Empty the table. Deliberately does NOT drop it or forget the established\n * dimension: the `vec0` table's dimension is fixed at creation and a re-embed at\n * a different dimension needs a drop-and-re-index, which is a consumer decision\n * (see the package README on `vec0` schema changes), not something a rebuild\n * should do silently.\n */\n private _clear(): Result<true> {\n if (this._stmts === undefined) {\n return succeed(true);\n }\n // Capture-wrapped like `add` / `remove` / `query`: a closed connection or an\n // I/O error here is a `Failure`, not an exception thrown out of a method\n // whose signature promises a `Result`.\n return captureResult(() => this._db.prepare(`DELETE FROM \"${this._table}\"`).run()).onSuccess(() =>\n succeed(true)\n );\n }\n\n /** {@inheritDoc IVectorIndex.query} */\n public query(vector: Float32Array, topK: number): Promise<Result<ReadonlyArray<IVectorQueryHit>>> {\n if (topK <= 0 || this._stmts === undefined) {\n return Promise.resolve(succeed([]));\n }\n if (vector.length !== this._dimension) {\n return Promise.resolve(\n fail(\n `vector index: query dimension ${vector.length} does not match index dimension ${this._dimension}`\n )\n );\n }\n return Promise.resolve(\n captureResult<ReadonlyArray<IVectorQueryHit>>(() => {\n const rows: ReadonlyArray<IKnnRow> = this._stmts!.query.all(\n SqliteVecVectorIndex._toBlob(vector),\n topK\n ) as ReadonlyArray<IKnnRow>;\n // sqlite-vec returns rows in ascending distance (nearest first); score is\n // `1 - cosineDistance` = cosine similarity, so descending score is preserved.\n return rows.map((row) => ({\n target: SqliteVecVectorIndex._parseKey(row.target_key),\n score: 1 - row.distance\n }));\n }).withErrorFormat((e) => `vector index: query failed: ${e}`)\n );\n }\n\n /** Create the `vec0` virtual table with the established dimension. */\n private _createTable(dimension: number): void {\n this._db.exec(\n `CREATE VIRTUAL TABLE IF NOT EXISTS \"${this._table}\" USING vec0(` +\n `target_key TEXT PRIMARY KEY, embedding float[${dimension}] distance_metric=cosine)`\n );\n }\n\n /** Prepare the statements the index reuses. Requires the table to exist. */\n private _prepare(): ISqliteVecStatements {\n const del: BetterSqlite3.Statement = this._db.prepare(\n `DELETE FROM \"${this._table}\" WHERE target_key = ?`\n );\n const ins: BetterSqlite3.Statement = this._db.prepare(\n `INSERT INTO \"${this._table}\"(target_key, embedding) VALUES (?, ?)`\n );\n // vec0 rejects INSERT OR REPLACE on a TEXT primary key, so replace is a\n // delete-then-insert inside a single transaction.\n const replaceTxn: BetterSqlite3.Transaction<(key: string, blob: Uint8Array) => void> =\n this._db.transaction((key: string, blob: Uint8Array) => {\n del.run(key);\n ins.run(key, blob);\n });\n return {\n delete: del,\n replace: (key: string, blob: Uint8Array): void => {\n replaceTxn(key, blob);\n },\n query: this._db.prepare(\n `SELECT target_key, distance FROM \"${this._table}\" WHERE embedding MATCH ? AND k = ?`\n ),\n count: this._db.prepare(`SELECT count(*) AS c FROM \"${this._table}\"`)\n };\n }\n\n /**\n * Recover the established dimension of an existing `vec0` table from its stored\n * `CREATE VIRTUAL TABLE` SQL (`float[<n>]`). Returns `undefined` when the table\n * does not exist yet (a fresh database — dimension is set by the first `add`).\n */\n private static _readExistingDimension(db: BetterSqlite3.Database, table: string): number | undefined {\n const row: { sql: string } | undefined = db\n .prepare(\"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\")\n .get(table) as { sql: string } | undefined;\n if (row === undefined) {\n return undefined;\n }\n const match: RegExpMatchArray | null = row.sql.match(/float\\[(\\d+)\\]/);\n return match === null ? undefined : Number(match[1]);\n }\n\n /** Pack a `Float32Array` as the little-endian byte blob `vec0` stores. Copies, so the caller may reuse its buffer. */\n private static _toBlob(vector: Float32Array): Uint8Array {\n return new Uint8Array(Float32Array.from(vector).buffer);\n }\n\n /**\n * Reverse `edgeTargetKey` — the canonical key is `scope\\0id` with NUL\n * excluded from both components, so the first NUL splits it unambiguously.\n */\n private static _parseKey(key: string): IEdgeTarget {\n const nul: number = key.indexOf('\\0');\n return {\n scope: key.slice(0, nul) as unknown as MemoryScopeKey,\n id: key.slice(nul + 1) as unknown as MemoryId\n };\n }\n}\n\n/** The prepared statements / helpers the index reuses once its table exists. */\ninterface ISqliteVecStatements {\n readonly delete: BetterSqlite3.Statement;\n readonly replace: (key: string, blob: Uint8Array) => void;\n readonly query: BetterSqlite3.Statement;\n readonly count: BetterSqlite3.Statement;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fgv/ts-agent-memory-sqlite-vec",
3
- "version": "5.1.0-47",
3
+ "version": "5.1.0-49",
4
4
  "description": "Result-integration boundary providing a persistent, sqlite-vec-backed IVectorIndex for @fgv/ts-agent-memory (survives restarts — no re-embed on open)",
5
5
  "main": "lib/index.js",
6
6
  "types": "dist/ts-agent-memory-sqlite-vec.d.ts",
@@ -17,6 +17,16 @@
17
17
  "types": "./dist/ts-agent-memory-sqlite-vec.d.ts"
18
18
  }
19
19
  },
20
+ "files": [
21
+ "lib",
22
+ "dist",
23
+ "CHANGELOG.json",
24
+ "README.md",
25
+ "LICENSE",
26
+ "!lib/test",
27
+ "!dist/test",
28
+ "!**/*.test.*"
29
+ ],
20
30
  "keywords": [
21
31
  "typescript",
22
32
  "sqlite-vec",
@@ -62,16 +72,16 @@
62
72
  "ts-jest": "^29.4.6",
63
73
  "ts-node": "^10.9.2",
64
74
  "typescript": "5.9.3",
65
- "@fgv/heft-dual-rig": "5.1.0-47",
66
- "@fgv/ts-utils": "5.1.0-47",
67
- "@fgv/ts-agent-memory": "5.1.0-47",
68
- "@fgv/ts-utils-jest": "5.1.0-47"
75
+ "@fgv/heft-dual-rig": "5.1.0-49",
76
+ "@fgv/ts-utils": "5.1.0-49",
77
+ "@fgv/ts-agent-memory": "5.1.0-49",
78
+ "@fgv/ts-utils-jest": "5.1.0-49"
69
79
  },
70
80
  "peerDependencies": {
71
81
  "better-sqlite3": "^12.0.0",
72
82
  "sqlite-vec": "^0.1.9",
73
- "@fgv/ts-utils": "5.1.0-47",
74
- "@fgv/ts-agent-memory": "5.1.0-47"
83
+ "@fgv/ts-utils": "5.1.0-49",
84
+ "@fgv/ts-agent-memory": "5.1.0-49"
75
85
  },
76
86
  "scripts": {
77
87
  "build": "heft build --clean",