@theokit/sdk-memory 0.6.1 → 0.6.2

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.
package/dist/index.cjs CHANGED
@@ -8,11 +8,7 @@ var persistence = require('@theokit/sdk/persistence');
8
8
  var memoryAdapters = require('@theokit/sdk/internal/memory-adapters');
9
9
  var errors = require('@theokit/sdk/errors');
10
10
  var pathSafety = require('@theokit/sdk/path-safety');
11
- var crypto = require('crypto');
12
- var fs = require('fs');
13
- var module$1 = require('module');
14
11
 
15
- var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
16
12
  // src/in-memory-provider.ts
17
13
  var ADAPTER_ID = "in-memory-md";
18
14
  var IN_MEMORY_REMEDY = "merge or delete facts with the adapter's delete(id), or raise maxFacts";
@@ -1083,220 +1079,17 @@ ${bullet}
1083
1079
  return `${raw.slice(0, insertAt)}
1084
1080
  ${bullet}${raw.slice(insertAt)}`;
1085
1081
  }
1086
- function requireLance() {
1087
- try {
1088
- const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
1089
- return r("@lancedb/lancedb");
1090
- } catch (cause) {
1091
- throw new errors.ConfigurationError(
1092
- 'Lance backend selected but `@lancedb/lancedb` is not installed. Install with: `pnpm add @lancedb/lancedb`. SQLite remains available as the default (omit `backend: "lance"`).',
1093
- { code: "lance_backend_unavailable", cause }
1094
- );
1095
- }
1096
- }
1097
- var LanceIndex = class _LanceIndex {
1098
- constructor(table, embedding, embeddingDim) {
1099
- this.table = table;
1100
- this.embedding = embedding;
1101
- this.embeddingDim = embeddingDim;
1102
- }
1103
- table;
1104
- embedding;
1105
- embeddingDim;
1106
- static async open(opts) {
1107
- const lance = requireLance();
1108
- const storagePath = opts.storagePath ?? memoryStore.lanceStoragePath(opts.memoryRoot ?? memoryStore.resolveMemoryRoot(opts.cwd));
1109
- fs.mkdirSync(storagePath, { recursive: true });
1110
- const conn = await lance.connect(storagePath);
1111
- const dim = opts.embedding.dimension;
1112
- const tableName = "facts";
1113
- const existing = await conn.tableNames();
1114
- let table;
1115
- if (existing.includes(tableName)) {
1116
- table = await conn.openTable(tableName);
1117
- const schema = await table.schema();
1118
- const embField = schema.fields.find((f) => f.name === "embedding");
1119
- const existingDim = embField?.type?.listSize ?? embField?.type?.fixedSize;
1120
- if (typeof existingDim === "number" && existingDim !== dim) {
1121
- throw new errors.ConfigurationError(
1122
- `Embedding dimension mismatch in Lance index: storage has ${existingDim}-dim vectors, current provider yields ${dim}-dim. Re-embed with \`migrateSqliteToLance\` after switching providers, or use a different storagePath.`,
1123
- { code: "embedding_dimension_mismatch" }
1124
- );
1125
- }
1126
- } else {
1127
- const bootstrap = {
1128
- id: "__bootstrap__",
1129
- text: "",
1130
- source: "memory",
1131
- embedding: new Array(dim).fill(0),
1132
- namespace: "__bootstrap__",
1133
- scope: "__bootstrap__",
1134
- user_id: "__bootstrap__",
1135
- timestamp: 0
1136
- };
1137
- table = await conn.createTable(tableName, [bootstrap]);
1138
- await table.delete("namespace = '__bootstrap__'");
1139
- }
1140
- return new _LanceIndex(table, opts.embedding, dim);
1141
- }
1142
- async addFacts(facts) {
1143
- if (facts.length === 0) return;
1144
- const texts = facts.map((f) => f.text);
1145
- const embeddings = await this.embedding.embed(texts);
1146
- const rows = facts.map((f, i) => ({
1147
- ...f,
1148
- embedding: embeddings[i] ?? new Array(this.embeddingDim).fill(0)
1149
- }));
1150
- await this.table.add(rows);
1151
- }
1152
- /**
1153
- * Search facts by semantic similarity. EC-1: filters use Lance's
1154
- * SQL string predicate with `'` → `''` escape — bind parameters are
1155
- * not supported by Lance 0.30.
1156
- */
1157
- async search(query, opts) {
1158
- const [embedding] = await this.embedding.embed([query]);
1159
- if (embedding === void 0) return [];
1160
- const predicates = [`namespace = '${escapeSqlValue(opts.namespace)}'`];
1161
- if (opts.scope !== void 0) {
1162
- predicates.push(`scope = '${escapeSqlValue(opts.scope)}'`);
1163
- }
1164
- let q = this.table.search(embedding).where(predicates.join(" AND "));
1165
- if (opts.limit !== void 0) q = q.limit(opts.limit);
1166
- const results = await q.toArray();
1167
- return results.filter((r) => opts.sources === void 0 || opts.sources.includes(r.source)).map((r) => ({
1168
- id: r.id,
1169
- text: r.text,
1170
- source: r.source,
1171
- namespace: r.namespace,
1172
- scope: r.scope,
1173
- userId: r.user_id,
1174
- // Lower _distance = better match; normalize to 0..1 (1=best).
1175
- score: 1 / (1 + (r._distance ?? 1))
1176
- }));
1177
- }
1178
- async countFacts(namespace) {
1179
- return this.table.countRows();
1180
- }
1181
- async removeFacts(ids) {
1182
- if (ids.length === 0) return;
1183
- const escaped = ids.map((id) => `'${id.replace(/'/g, "''")}'`).join(", ");
1184
- await this.table.delete(`id IN (${escaped})`);
1185
- }
1186
- async close() {
1187
- }
1188
- };
1189
- function escapeSqlValue(value) {
1190
- for (let i = 0; i < value.length; i++) {
1191
- const code = value.charCodeAt(i);
1192
- if (code === 0 || code >= 1 && code <= 31 || code === 127) {
1193
- throw new errors.ConfigurationError(
1194
- `SQL filter value contains control character at position ${i} (0x${code.toString(16)}). This may indicate an injection attempt.`,
1195
- { code: "sql_injection_blocked" }
1196
- );
1197
- }
1198
- }
1199
- return value.replace(/\\/g, "\\\\").replace(/'/g, "''");
1200
- }
1201
- function isLanceAvailable() {
1202
- try {
1203
- const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
1204
- r("@lancedb/lancedb");
1205
- return true;
1206
- } catch {
1207
- return false;
1208
- }
1209
- }
1210
-
1211
- // src/internal/index/lance-memory-adapter.ts
1212
- var DEFAULT_NAMESPACE = "default";
1213
- var EMPTY_SYNC_RESULT = Object.freeze({
1214
- filesScanned: 0,
1215
- filesUpdated: 0,
1216
- chunksWritten: 0,
1217
- chunksEmbedded: 0
1218
- });
1219
- var LanceMemoryAdapter = class {
1082
+ var LanceMemoryAdapter = class extends memoryStore.LanceMemoryAdapter {
1083
+ #lance;
1220
1084
  constructor(inner) {
1221
- this.inner = inner;
1085
+ super(inner);
1086
+ this.#lance = inner;
1222
1087
  }
1223
- inner;
1224
- /**
1225
- * No-op for Lance — see file header. Returns zero counts so callers'
1226
- * existing logging (`filesScanned: X`) does not break.
1227
- */
1228
- async sync() {
1229
- return EMPTY_SYNC_RESULT;
1230
- }
1231
- // jscpd:ignore-start — search signature + early-out is idiomatic
1232
- // overlap with IndexManager.search; further factoring would hurt
1233
- // readability (the bodies diverge sharply right after).
1234
- async search(query, options = {}) {
1235
- if (query.trim().length === 0) return [];
1236
- const { maxResults, minScore } = memoryStore.parseSearchOptions(options);
1237
- const lanceHits = await this.inner.search(query, {
1238
- namespace: DEFAULT_NAMESPACE,
1239
- limit: maxResults * 2,
1240
- ...options.sources !== void 0 ? { sources: options.sources } : {}
1241
- });
1242
- return lanceHits.filter((h) => h.score >= minScore).slice(0, maxResults).map((h) => translateLanceHit(h));
1243
- }
1244
- status() {
1245
- return {
1246
- backend: "hybrid",
1247
- filesIndexed: 0,
1248
- chunksIndexed: 0
1249
- };
1250
- }
1251
- async close() {
1252
- await this.inner.close();
1253
- }
1254
- /**
1255
- * Escape hatch for advanced callers (migration tool, benchmark script)
1256
- * that need direct access to addFacts/countFacts/removeFacts.
1257
- */
1088
+ /** The wrapped `LanceIndex`, for `addFacts`, `countFacts` and `removeFacts`. */
1258
1089
  unwrap() {
1259
- return this.inner;
1090
+ return this.#lance;
1260
1091
  }
1261
1092
  };
1262
- function translateLanceHit(hit) {
1263
- return {
1264
- path: hit.id,
1265
- startLine: 0,
1266
- endLine: 0,
1267
- score: hit.score,
1268
- textScore: 0,
1269
- vectorScore: hit.score,
1270
- snippet: hit.text.slice(0, 200),
1271
- source: hit.source,
1272
- citation: hit.id
1273
- };
1274
- }
1275
-
1276
- // src/internal/index/index-manager-dispatch.ts
1277
- var VALID_BACKENDS = ["sqlite-vec", "lance"];
1278
- function assertValidBackend(backend) {
1279
- if (!VALID_BACKENDS.includes(backend)) {
1280
- throw new errors.ConfigurationError(
1281
- `Invalid memory backend "${backend}". Valid values: ${VALID_BACKENDS.join(", ")}.`,
1282
- { code: "invalid_memory_backend" }
1283
- );
1284
- }
1285
- }
1286
- async function openLanceIndex(opts) {
1287
- if (opts.embedding === void 0) {
1288
- throw new errors.ConfigurationError(
1289
- "Lance backend requires an embedding runtime. Pass `embedding: { provider, model, apiKey }` in Memory.create options (or omit `backend` to use SQLite default).",
1290
- { code: "lance_requires_embedding" }
1291
- );
1292
- }
1293
- const lance = await LanceIndex.open({
1294
- cwd: opts.cwd,
1295
- embedding: opts.embedding,
1296
- ...opts.filePath !== void 0 ? { storagePath: opts.filePath } : {}
1297
- });
1298
- return new LanceMemoryAdapter(lance);
1299
- }
1300
1093
  function isSqliteVecLoaded(db) {
1301
1094
  try {
1302
1095
  const row = db.prepare("SELECT vec_version() as v").get();
@@ -1305,434 +1098,6 @@ function isSqliteVecLoaded(db) {
1305
1098
  return false;
1306
1099
  }
1307
1100
  }
1308
-
1309
- // src/internal/index/index-manager.ts
1310
- var IndexManager = class _IndexManager {
1311
- constructor(memoryRoot, db, embedding) {
1312
- this.memoryRoot = memoryRoot;
1313
- this.db = db;
1314
- this.embedding = embedding;
1315
- }
1316
- memoryRoot;
1317
- db;
1318
- embedding;
1319
- lastSyncMs;
1320
- vectorReady = false;
1321
- static async open(opts) {
1322
- const backend = opts.backend ?? "sqlite-vec";
1323
- assertValidBackend(backend);
1324
- if (backend === "lance") return await openLanceIndex(opts);
1325
- return await _IndexManager.openSqliteInternal(opts);
1326
- }
1327
- /** Internal SQLite-path open. Renamed from previous public `open`. */
1328
- static async openSqliteInternal(opts) {
1329
- const memoryRoot = opts.memoryRoot ?? memoryStore.resolveMemoryRoot(opts.cwd);
1330
- const filePath = opts.filePath ?? memoryStore.defaultIndexPath(memoryStore.projectMemoryDir(opts.cwd));
1331
- const db = await memoryStore.openMemoryDb({ filePath });
1332
- const manager = new _IndexManager(memoryRoot, db, opts.embedding);
1333
- if (opts.embedding !== void 0) await manager.initVectorBackend(opts.embedding);
1334
- return manager;
1335
- }
1336
- async initVectorBackend(runtime) {
1337
- await memoryStore.loadSqliteVecExtension(this.db);
1338
- const currentIdentity = {
1339
- providerId: runtime.id,
1340
- model: runtime.model,
1341
- dimension: runtime.dimension
1342
- };
1343
- const persisted = memoryStore.readEmbeddingIdentity(this.db);
1344
- if (persisted !== void 0 && !memoryStore.identityMatches(persisted, currentIdentity)) {
1345
- memoryStore.dropVectorIndex(this.db);
1346
- }
1347
- memoryStore.createVectorIndex(this.db, runtime.dimension);
1348
- memoryStore.writeEmbeddingIdentity(this.db, currentIdentity);
1349
- this.vectorReady = true;
1350
- }
1351
- /** Walk the memory corpus + (re)index changed files. */
1352
- async sync() {
1353
- const files = await memoryStore.collectMarkdownFiles(this.memoryRoot);
1354
- let filesUpdated = 0;
1355
- let chunksWritten = 0;
1356
- const existingByPath = this.loadFilesIndex();
1357
- for (const entry of files) {
1358
- const raw = await promises.readFile(entry.absolutePath, "utf8");
1359
- const hash = sha256(raw);
1360
- const existing = existingByPath.get(entry.absolutePath);
1361
- if (existing !== void 0 && existing.hash === hash) continue;
1362
- const stats = await promises.stat(entry.absolutePath);
1363
- const fileId = this.upsertFile(
1364
- entry.absolutePath,
1365
- entry.relPath,
1366
- hash,
1367
- stats.mtimeMs,
1368
- entry.source
1369
- );
1370
- this.deleteChunksForFile(fileId);
1371
- const chunks = memoryStore.chunkMarkdown(raw);
1372
- for (const chunk of chunks) {
1373
- this.insertChunk(fileId, chunk.startLine, chunk.endLine, chunk.text, chunk.hash);
1374
- }
1375
- filesUpdated += 1;
1376
- chunksWritten += chunks.length;
1377
- }
1378
- let chunksEmbedded = 0;
1379
- if (this.vectorReady && this.embedding !== void 0) {
1380
- chunksEmbedded = await memoryStore.embedMissingChunks({ db: this.db, runtime: this.embedding });
1381
- }
1382
- this.lastSyncMs = Date.now();
1383
- return { filesScanned: files.length, filesUpdated, chunksWritten, chunksEmbedded };
1384
- }
1385
- async search(query, options = {}) {
1386
- if (query.trim().length === 0) return [];
1387
- const { maxResults, minScore } = memoryStore.parseSearchOptions(options);
1388
- const textHits = this.ftsSearch(query, maxResults * 2);
1389
- const vectorHitsById = await this.vectorSearchById(query, maxResults * 2);
1390
- const combined = this.combineHybridScores(textHits, vectorHitsById, options);
1391
- return combined.filter((h) => h.score >= minScore).filter((h) => options.sources === void 0 || options.sources.includes(h.source)).slice(0, maxResults);
1392
- }
1393
- status() {
1394
- const files = this.db.prepare("SELECT COUNT(*) as n FROM files").get() ?? { n: 0 };
1395
- const chunks = this.db.prepare("SELECT COUNT(*) as n FROM chunks").get() ?? { n: 0 };
1396
- const status = {
1397
- backend: this.vectorReady ? "hybrid" : "fts-only",
1398
- filesIndexed: Number(files.n ?? 0),
1399
- chunksIndexed: Number(chunks.n ?? 0)
1400
- };
1401
- if (this.lastSyncMs !== void 0) status.lastSyncMs = this.lastSyncMs;
1402
- return status;
1403
- }
1404
- // ───── search internals ──────────────────────────────────────────────
1405
- ftsSearch(query, limit) {
1406
- const sanitized = persistence.sanitizeFts5Query(query);
1407
- if (sanitized.length === 0) return [];
1408
- const stmt = this.db.prepare(
1409
- `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,
1410
- chunks.start_line as start_line, chunks.end_line as end_line,
1411
- chunks.text as text, bm25(chunks_fts) as bm25_score
1412
- FROM chunks_fts
1413
- JOIN chunks ON chunks_fts.rowid = chunks.id
1414
- JOIN files ON chunks.file_id = files.id
1415
- WHERE chunks_fts MATCH ?
1416
- ORDER BY bm25_score
1417
- LIMIT ?`
1418
- );
1419
- let rows = [];
1420
- try {
1421
- rows = stmt.all(sanitized, limit);
1422
- } catch {
1423
- return [];
1424
- }
1425
- return rows.map((row) => {
1426
- const bm25 = Number(row.bm25_score ?? 0);
1427
- const textScore = bm25 < 0 ? 1 / (1 + Math.abs(bm25)) : 1 / (1 + bm25);
1428
- const startLine = Number(row.start_line ?? 0);
1429
- const endLine = Number(row.end_line ?? 0);
1430
- const path = String(row.rel_path);
1431
- return {
1432
- path,
1433
- startLine,
1434
- endLine,
1435
- score: textScore,
1436
- textScore,
1437
- snippet: truncateSnippet(String(row.text ?? "")),
1438
- source: String(row.source),
1439
- citation: `${path}:${startLine}-${endLine}`,
1440
- // sneak the chunk id through for the hybrid join below
1441
- // (cast away later)
1442
- chunkId: Number(row.id)
1443
- };
1444
- });
1445
- }
1446
- async vectorSearchById(query, limit) {
1447
- if (!this.vectorReady || this.embedding === void 0) return /* @__PURE__ */ new Map();
1448
- const [queryVec] = await this.embedding.embed([query]);
1449
- if (queryVec === void 0) return /* @__PURE__ */ new Map();
1450
- const rows = memoryStore.vectorSearch(this.db, queryVec, limit);
1451
- const out = /* @__PURE__ */ new Map();
1452
- for (const row of rows) {
1453
- const score = 1 / (1 + Math.max(0, row.distance));
1454
- out.set(row.chunk_id, { vectorScore: score });
1455
- }
1456
- return out;
1457
- }
1458
- combineHybridScores(textHits, vectorHitsById, options) {
1459
- const weights = resolveWeights(options);
1460
- const merged = this.mergeHits(textHits, vectorHitsById);
1461
- const combined = [...merged.values()].map(
1462
- (hit) => blendScores(hit, vectorHitsById.get(hit.chunkId)?.vectorScore ?? 0, weights)
1463
- );
1464
- return combined.sort((a, b) => b.score - a.score);
1465
- }
1466
- mergeHits(textHits, vectorHitsById) {
1467
- const merged = /* @__PURE__ */ new Map();
1468
- for (const hit of textHits) merged.set(hit.chunkId, hit);
1469
- const missingIds = [...vectorHitsById.keys()].filter((id) => !merged.has(id));
1470
- if (missingIds.length > 0) {
1471
- for (const hit of this.fetchChunksByIds(missingIds)) {
1472
- merged.set(hit.chunkId, { ...hit, score: 0, textScore: 0 });
1473
- }
1474
- }
1475
- return merged;
1476
- }
1477
- fetchChunksByIds(ids) {
1478
- if (ids.length === 0) return [];
1479
- const placeholders = ids.map(() => "?").join(",");
1480
- const rows = this.db.prepare(
1481
- `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,
1482
- chunks.start_line as start_line, chunks.end_line as end_line,
1483
- chunks.text as text
1484
- FROM chunks JOIN files ON chunks.file_id = files.id
1485
- WHERE chunks.id IN (${placeholders})`
1486
- ).all(...ids);
1487
- return rows.map((row) => {
1488
- const startLine = Number(row.start_line ?? 0);
1489
- const endLine = Number(row.end_line ?? 0);
1490
- const path = String(row.rel_path);
1491
- return {
1492
- chunkId: Number(row.id),
1493
- path,
1494
- startLine,
1495
- endLine,
1496
- score: 0,
1497
- textScore: 0,
1498
- snippet: truncateSnippet(String(row.text ?? "")),
1499
- source: String(row.source),
1500
- citation: `${path}:${startLine}-${endLine}`
1501
- };
1502
- });
1503
- }
1504
- // ───── persistence helpers ─────────────────────────────────────────
1505
- loadFilesIndex() {
1506
- const rows = this.db.prepare("SELECT id, path, hash FROM files").all();
1507
- return new Map(rows.map((row) => [row.path, { id: row.id, hash: row.hash }]));
1508
- }
1509
- upsertFile(absPath, relPath, hash, mtimeMs, source = "memory") {
1510
- const stmt = this.db.prepare(
1511
- `INSERT INTO files (path, rel_path, mtime, hash, source) VALUES (?, ?, ?, ?, ?)
1512
- ON CONFLICT(path) DO UPDATE SET hash = excluded.hash, mtime = excluded.mtime, source = excluded.source
1513
- RETURNING id`
1514
- );
1515
- const row = stmt.get(absPath, relPath, Math.floor(mtimeMs), hash, source);
1516
- return row.id;
1517
- }
1518
- deleteChunksForFile(fileId) {
1519
- this.db.prepare("DELETE FROM chunks WHERE file_id = ?").run(fileId);
1520
- }
1521
- insertChunk(fileId, startLine, endLine, text, hash) {
1522
- this.db.prepare(
1523
- "INSERT INTO chunks (file_id, start_line, end_line, text, hash) VALUES (?, ?, ?, ?, ?)"
1524
- ).run(fileId, startLine, endLine, text, hash);
1525
- }
1526
- close() {
1527
- this.db.close();
1528
- }
1529
- };
1530
- function resolveWeights(options) {
1531
- const vectorWeight = options.vectorWeight ?? 0.6;
1532
- const textWeight = options.textWeight ?? 0.4;
1533
- const total = vectorWeight + textWeight || 1;
1534
- return { vectorWeight, textWeight, total };
1535
- }
1536
- function blendScores(hit, vectorScore, weights) {
1537
- const score = (vectorScore * weights.vectorWeight + hit.textScore * weights.textWeight) / weights.total;
1538
- return {
1539
- path: hit.path,
1540
- startLine: hit.startLine,
1541
- endLine: hit.endLine,
1542
- score,
1543
- textScore: hit.textScore,
1544
- snippet: hit.snippet,
1545
- source: hit.source,
1546
- citation: hit.citation,
1547
- ...vectorScore > 0 ? { vectorScore } : {}
1548
- };
1549
- }
1550
- function sha256(text) {
1551
- return crypto.createHash("sha256").update(text).digest("hex");
1552
- }
1553
- function truncateSnippet(text) {
1554
- const max = 500;
1555
- return text.length <= max ? text : `${text.slice(0, max)}\u2026`;
1556
- }
1557
- function nfcEqual(a, b) {
1558
- return a.normalize("NFC") === b.normalize("NFC");
1559
- }
1560
- async function migrateSqliteToLance(opts) {
1561
- const cwd = opts.cwd;
1562
- const memoryRoot = memoryStore.resolveMemoryRoot(cwd, { directory: opts.directory });
1563
- const finalPath = memoryStore.lanceStoragePath(memoryRoot);
1564
- const newPath = path.join(memoryRoot, "lance-new");
1565
- const rawLog = opts.logger ?? ((m) => console.log(m));
1566
- const log = (m) => rawLog(redactSecrets(m));
1567
- if (fs.existsSync(finalPath)) {
1568
- throw new errors.ConfigurationError(
1569
- `Destination already exists: ${finalPath}. Remove it manually (\`rm -rf ${finalPath}\`) and re-run.`,
1570
- { code: "migration_destination_exists" }
1571
- );
1572
- }
1573
- if (fs.existsSync(newPath)) {
1574
- log(`Removing stale ${newPath} from a previous run...`);
1575
- fs.rmSync(newPath, { recursive: true, force: true });
1576
- }
1577
- log(`Reading SQLite facts from ${cwd}/.theokit/memory/index.sqlite ...`);
1578
- const sqliteFacts = await memoryStore.readAllSqliteFacts(memoryRoot);
1579
- log(`SQLite has ${sqliteFacts.length} facts.`);
1580
- if (sqliteFacts.length === 0) {
1581
- return {
1582
- countSqlite: 0,
1583
- countLance: 0,
1584
- validated: true,
1585
- sampleComparisons: [],
1586
- lancePath: finalPath,
1587
- committed: false
1588
- };
1589
- }
1590
- const placeholderEmbedding = {
1591
- id: "migration-placeholder",
1592
- model: "deterministic-hash",
1593
- dimension: 8,
1594
- embed: async (texts) => {
1595
- return texts.map((t) => {
1596
- const arr = new Array(8).fill(0);
1597
- for (let i = 0; i < t.length; i += 1) {
1598
- arr[i % 8] += t.charCodeAt(i);
1599
- }
1600
- return arr.map((x) => x / 1e3);
1601
- });
1602
- },
1603
- stats: () => ({ cacheHits: 0, cacheMisses: 0, httpCalls: 0, retries: 0 })
1604
- };
1605
- fs.mkdirSync(newPath, { recursive: true });
1606
- log(`Writing Lance index to ${newPath} ...`);
1607
- const lance = await LanceIndex.open({
1608
- cwd,
1609
- embedding: placeholderEmbedding,
1610
- storagePath: newPath
1611
- });
1612
- const batchSize = opts.batchSize ?? 100;
1613
- for (let i = 0; i < sqliteFacts.length; i += batchSize) {
1614
- const batch = sqliteFacts.slice(i, i + batchSize).map((f) => ({
1615
- id: f.id,
1616
- text: f.text,
1617
- source: f.source,
1618
- namespace: f.namespace ?? "default",
1619
- scope: f.scope ?? "agent",
1620
- user_id: f.user_id ?? "default",
1621
- timestamp: 0
1622
- }));
1623
- await lance.addFacts(batch);
1624
- log(` Migrated ${Math.min(i + batchSize, sqliteFacts.length)}/${sqliteFacts.length}`);
1625
- }
1626
- const lanceCount = await lance.countFacts("default");
1627
- log(`Lance has ${lanceCount} facts (expected ${sqliteFacts.length}).`);
1628
- const sampleSize = Math.min(10, sqliteFacts.length);
1629
- const sampleComparisons = [];
1630
- for (let i = 0; i < sampleSize; i += 1) {
1631
- const sqliteFact = sqliteFacts[Math.floor(i * sqliteFacts.length / sampleSize)];
1632
- if (sqliteFact === void 0) continue;
1633
- const hits = await lance.search(sqliteFact.text, {
1634
- namespace: sqliteFact.namespace ?? "default",
1635
- limit: 1
1636
- });
1637
- const hit = hits[0];
1638
- const match = hit !== void 0 && nfcEqual(hit.text, sqliteFact.text);
1639
- sampleComparisons.push({ id: sqliteFact.id, match });
1640
- }
1641
- const allMatch = sampleComparisons.every((c) => c.match);
1642
- const countMatch = lanceCount === sqliteFacts.length;
1643
- const validated = allMatch && countMatch;
1644
- await lance.close();
1645
- if (opts.dryRun === true) {
1646
- log("Dry-run mode \u2014 discarding Lance staging dir.");
1647
- fs.rmSync(newPath, { recursive: true, force: true });
1648
- return {
1649
- countSqlite: sqliteFacts.length,
1650
- countLance: lanceCount,
1651
- validated,
1652
- sampleComparisons,
1653
- lancePath: finalPath,
1654
- committed: false
1655
- };
1656
- }
1657
- if (!validated) {
1658
- log("Validation FAILED \u2014 leaving SQLite intact, removing Lance staging dir.");
1659
- fs.rmSync(newPath, { recursive: true, force: true });
1660
- return {
1661
- countSqlite: sqliteFacts.length,
1662
- countLance: lanceCount,
1663
- validated: false,
1664
- sampleComparisons,
1665
- lancePath: finalPath,
1666
- committed: false
1667
- };
1668
- }
1669
- fs.renameSync(newPath, finalPath);
1670
- log(`Migration committed to ${finalPath}.`);
1671
- return {
1672
- countSqlite: sqliteFacts.length,
1673
- countLance: lanceCount,
1674
- validated: true,
1675
- sampleComparisons,
1676
- lancePath: finalPath,
1677
- committed: true
1678
- };
1679
- }
1680
- async function fileExists(path) {
1681
- try {
1682
- await promises.access(path);
1683
- return true;
1684
- } catch {
1685
- return false;
1686
- }
1687
- }
1688
- async function readLegacyFacts(jsonPath) {
1689
- try {
1690
- const raw = await promises.readFile(jsonPath, "utf8");
1691
- const parsed = JSON.parse(raw);
1692
- return Array.isArray(parsed.facts) ? parsed.facts : [];
1693
- } catch {
1694
- return void 0;
1695
- }
1696
- }
1697
- async function writeMigratedFacts(cwd, jsonPath, facts) {
1698
- try {
1699
- for (const fact of facts) await memoryStore.appendFactToMarkdown(cwd, fact);
1700
- await promises.unlink(jsonPath).catch(() => void 0);
1701
- process.stderr.write(
1702
- `[theokit-sdk] migrated ${facts.length} fact(s) from ${jsonPath} to MEMORY.md
1703
- `
1704
- );
1705
- return { migrated: true, factCount: facts.length };
1706
- } catch (cause) {
1707
- const message = cause instanceof Error ? cause.message : String(cause);
1708
- process.stderr.write(`[theokit-sdk] memory migration failed (readonly fs?): ${message}
1709
- `);
1710
- return { migrated: false, factCount: 0, reason: "readonly-fs" };
1711
- }
1712
- }
1713
- var migrationRun = /* @__PURE__ */ new Set();
1714
- async function migrateLegacyJson(cwd, config) {
1715
- const key = `${cwd}::${config.namespace ?? "default"}::${config.scope ?? "agent"}::${config.userId ?? "default"}`;
1716
- if (migrationRun.has(key)) return { migrated: false, factCount: 0, reason: "already-migrated" };
1717
- migrationRun.add(key);
1718
- const jsonPath = legacyMemoryJsonPath(cwd, config);
1719
- if (!await fileExists(jsonPath)) {
1720
- return { migrated: false, factCount: 0, reason: "no-legacy-json" };
1721
- }
1722
- if (await fileExists(memoryStore.memoryMdPath(memoryStore.resolveMemoryRoot(cwd)))) {
1723
- process.stderr.write(
1724
- `[theokit-sdk] memory migration skipped: both MEMORY.md and legacy JSON exist at ${jsonPath}; leaving both intact
1725
- `
1726
- );
1727
- return { migrated: false, factCount: 0, reason: "markdown-exists" };
1728
- }
1729
- const facts = await readLegacyFacts(jsonPath);
1730
- if (facts === void 0) return { migrated: false, factCount: 0, reason: "no-legacy-json" };
1731
- return writeMigratedFacts(cwd, jsonPath, facts);
1732
- }
1733
- function resetMigrationStateForTests() {
1734
- migrationRun.clear();
1735
- }
1736
1101
  var SEARCH_DESCRIPTION = "Mandatory recall step: semantically search MEMORY.md + memory/notes/*.md (and optional wiki supplements) before answering questions about prior work, decisions, dates, people, preferences, or todos. `corpus=memory` (default) restricts to indexed memory files; `corpus=wiki` restricts to read-only wiki supplements; `corpus=all` returns both. Returns ranked `{ path, startLine, endLine, score, snippet, citation }` hits.";
1737
1102
  var GET_DESCRIPTION = "Safe exact excerpt read from MEMORY.md or memory/notes/*.md. Defaults to a bounded excerpt (200 lines). Returns `{ path, from, linesReturned, totalLines, truncated, remainingLines, text }`. Paths are resolved against the memory root \u2014 attempts to read outside `.theokit/memory/` are rejected.";
1738
1103
  var MEMORY_SEARCH_SCHEMA = {
@@ -1857,6 +1222,14 @@ Object.defineProperty(exports, "DEFAULT_MEMORY_READ_LINES", {
1857
1222
  enumerable: true,
1858
1223
  get: function () { return memoryStore.DEFAULT_MEMORY_READ_LINES; }
1859
1224
  });
1225
+ Object.defineProperty(exports, "IndexManager", {
1226
+ enumerable: true,
1227
+ get: function () { return memoryStore.IndexManager; }
1228
+ });
1229
+ Object.defineProperty(exports, "LanceIndex", {
1230
+ enumerable: true,
1231
+ get: function () { return memoryStore.LanceIndex; }
1232
+ });
1860
1233
  Object.defineProperty(exports, "MEMORY_INDEX_MAX_BYTES", {
1861
1234
  enumerable: true,
1862
1235
  get: function () { return memoryStore.MEMORY_INDEX_MAX_BYTES; }
@@ -1885,6 +1258,10 @@ Object.defineProperty(exports, "SCHEMA_STATEMENTS", {
1885
1258
  enumerable: true,
1886
1259
  get: function () { return memoryStore.SCHEMA_STATEMENTS; }
1887
1260
  });
1261
+ Object.defineProperty(exports, "VALID_BACKENDS", {
1262
+ enumerable: true,
1263
+ get: function () { return memoryStore.VALID_BACKENDS; }
1264
+ });
1888
1265
  Object.defineProperty(exports, "appendDiaryEntry", {
1889
1266
  enumerable: true,
1890
1267
  get: function () { return memoryStore.appendDiaryEntry; }
@@ -1901,6 +1278,10 @@ Object.defineProperty(exports, "asMemoryRoot", {
1901
1278
  enumerable: true,
1902
1279
  get: function () { return memoryStore.asMemoryRoot; }
1903
1280
  });
1281
+ Object.defineProperty(exports, "assertValidBackend", {
1282
+ enumerable: true,
1283
+ get: function () { return memoryStore.assertValidBackend; }
1284
+ });
1904
1285
  Object.defineProperty(exports, "ceilingReachedError", {
1905
1286
  enumerable: true,
1906
1287
  get: function () { return memoryStore.ceilingReachedError; }
@@ -1961,6 +1342,10 @@ Object.defineProperty(exports, "indexBudgetWarning", {
1961
1342
  enumerable: true,
1962
1343
  get: function () { return memoryStore.indexBudgetWarning; }
1963
1344
  });
1345
+ Object.defineProperty(exports, "isLanceAvailable", {
1346
+ enumerable: true,
1347
+ get: function () { return memoryStore.isLanceAvailable; }
1348
+ });
1964
1349
  Object.defineProperty(exports, "lanceStoragePath", {
1965
1350
  enumerable: true,
1966
1351
  get: function () { return memoryStore.lanceStoragePath; }
@@ -1985,10 +1370,22 @@ Object.defineProperty(exports, "memoryReadRoots", {
1985
1370
  enumerable: true,
1986
1371
  get: function () { return memoryStore.memoryReadRoots; }
1987
1372
  });
1373
+ Object.defineProperty(exports, "migrateLegacyJson", {
1374
+ enumerable: true,
1375
+ get: function () { return memoryStore.migrateLegacyJson; }
1376
+ });
1377
+ Object.defineProperty(exports, "migrateSqliteToLance", {
1378
+ enumerable: true,
1379
+ get: function () { return memoryStore.migrateSqliteToLance; }
1380
+ });
1988
1381
  Object.defineProperty(exports, "notesDir", {
1989
1382
  enumerable: true,
1990
1383
  get: function () { return memoryStore.notesDir; }
1991
1384
  });
1385
+ Object.defineProperty(exports, "openLanceIndex", {
1386
+ enumerable: true,
1387
+ get: function () { return memoryStore.openLanceIndex; }
1388
+ });
1992
1389
  Object.defineProperty(exports, "openMemoryDb", {
1993
1390
  enumerable: true,
1994
1391
  get: function () { return memoryStore.openMemoryDb; }
@@ -2037,6 +1434,10 @@ Object.defineProperty(exports, "renderDiaryEntry", {
2037
1434
  enumerable: true,
2038
1435
  get: function () { return memoryStore.renderDiaryEntry; }
2039
1436
  });
1437
+ Object.defineProperty(exports, "resetMigrationStateForTests", {
1438
+ enumerable: true,
1439
+ get: function () { return memoryStore.resetMigrationStateForTests; }
1440
+ });
2040
1441
  Object.defineProperty(exports, "resolveMaxFacts", {
2041
1442
  enumerable: true,
2042
1443
  get: function () { return memoryStore.resolveMaxFacts; }
@@ -2092,12 +1493,8 @@ exports.DEFAULT_OLLAMA_EMBEDDING_MODEL = DEFAULT_OLLAMA_EMBEDDING_MODEL;
2092
1493
  exports.DEFAULT_OPENAI_EMBEDDING_MODEL = DEFAULT_OPENAI_EMBEDDING_MODEL;
2093
1494
  exports.DEFAULT_OPENROUTER_EMBEDDING_MODEL = DEFAULT_OPENROUTER_EMBEDDING_MODEL;
2094
1495
  exports.DEFAULT_VOYAGE_EMBEDDING_MODEL = DEFAULT_VOYAGE_EMBEDDING_MODEL;
2095
- exports.IndexManager = IndexManager;
2096
- exports.LanceIndex = LanceIndex;
2097
1496
  exports.LanceMemoryAdapter = LanceMemoryAdapter;
2098
1497
  exports.MEMORY_EMBEDDING_ADAPTERS = MEMORY_EMBEDDING_ADAPTERS;
2099
- exports.VALID_BACKENDS = VALID_BACKENDS;
2100
- exports.assertValidBackend = assertValidBackend;
2101
1498
  exports.azureOpenAiMemoryEmbeddingProviderAdapter = azureOpenAiMemoryEmbeddingProviderAdapter;
2102
1499
  exports.buildErrorMetadata = buildErrorMetadata;
2103
1500
  exports.cohereMemoryEmbeddingProviderAdapter = cohereMemoryEmbeddingProviderAdapter;
@@ -2107,22 +1504,17 @@ exports.createMemoryGetTool = createMemoryGetTool;
2107
1504
  exports.createMemorySearchTool = createMemorySearchTool;
2108
1505
  exports.deepinfraMemoryEmbeddingProviderAdapter = deepinfraMemoryEmbeddingProviderAdapter;
2109
1506
  exports.geminiMemoryEmbeddingProviderAdapter = geminiMemoryEmbeddingProviderAdapter;
2110
- exports.isLanceAvailable = isLanceAvailable;
2111
1507
  exports.isSqliteVecLoaded = isSqliteVecLoaded;
2112
1508
  exports.jinaMemoryEmbeddingProviderAdapter = jinaMemoryEmbeddingProviderAdapter;
2113
1509
  exports.legacyMemoryJsonPath = legacyMemoryJsonPath;
2114
1510
  exports.listNotes = listNotes;
2115
1511
  exports.mapOpenAICompatibleError = mapOpenAICompatibleError;
2116
- exports.migrateLegacyJson = migrateLegacyJson;
2117
- exports.migrateSqliteToLance = migrateSqliteToLance;
2118
1512
  exports.mistralMemoryEmbeddingProviderAdapter = mistralMemoryEmbeddingProviderAdapter;
2119
1513
  exports.ollamaMemoryEmbeddingProviderAdapter = ollamaMemoryEmbeddingProviderAdapter;
2120
1514
  exports.openAiMemoryEmbeddingProviderAdapter = openAiMemoryEmbeddingProviderAdapter;
2121
- exports.openLanceIndex = openLanceIndex;
2122
1515
  exports.openRouterMemoryEmbeddingProviderAdapter = openRouterMemoryEmbeddingProviderAdapter;
2123
1516
  exports.parseRetryAfter = parseRetryAfter;
2124
1517
  exports.redactSecrets = redactSecrets;
2125
- exports.resetMigrationStateForTests = resetMigrationStateForTests;
2126
1518
  exports.runActiveMemory = runActiveMemory;
2127
1519
  exports.truncateRaw = truncateRaw;
2128
1520
  exports.voyageMemoryEmbeddingProviderAdapter = voyageMemoryEmbeddingProviderAdapter;