@theokit/sdk-memory 0.6.1 → 0.6.3

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