@theokit/sdk-memory 0.6.0 → 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.
Files changed (42) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/index.cjs +174 -1138
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +42 -1107
  6. package/dist/index.js.map +1 -1
  7. package/dist/internal/active-memory/active-memory-cache.d.ts +1 -66
  8. package/dist/internal/active-memory/active-memory-cache.d.ts.map +1 -1
  9. package/dist/internal/active-memory/active-memory-types.d.ts +1 -54
  10. package/dist/internal/active-memory/active-memory-types.d.ts.map +1 -1
  11. package/dist/internal/adapter-http-error.d.ts.map +1 -1
  12. package/dist/internal/dreaming/dreaming-phases.d.ts +5 -53
  13. package/dist/internal/dreaming/dreaming-phases.d.ts.map +1 -1
  14. package/dist/internal/dreaming/dreaming-run.d.ts +3 -83
  15. package/dist/internal/dreaming/dreaming-run.d.ts.map +1 -1
  16. package/dist/internal/index/index-db.d.ts +1 -67
  17. package/dist/internal/index/index-db.d.ts.map +1 -1
  18. package/dist/internal/index/index-manager-dispatch.d.ts +1 -35
  19. package/dist/internal/index/index-manager-dispatch.d.ts.map +1 -1
  20. package/dist/internal/index/index-manager.d.ts +1 -130
  21. package/dist/internal/index/index-manager.d.ts.map +1 -1
  22. package/dist/internal/index/index-schema.d.ts +1 -29
  23. package/dist/internal/index/index-schema.d.ts.map +1 -1
  24. package/dist/internal/index/lance-index.d.ts +1 -91
  25. package/dist/internal/index/lance-index.d.ts.map +1 -1
  26. package/dist/internal/index/lance-memory-adapter.d.ts +16 -115
  27. package/dist/internal/index/lance-memory-adapter.d.ts.map +1 -1
  28. package/dist/internal/index/memory-index.d.ts +3 -12
  29. package/dist/internal/index/memory-index.d.ts.map +1 -1
  30. package/dist/internal/index/migrate-sqlite-to-lance.d.ts +1 -65
  31. package/dist/internal/index/migrate-sqlite-to-lance.d.ts.map +1 -1
  32. package/dist/internal/index/migration.d.ts +1 -35
  33. package/dist/internal/index/migration.d.ts.map +1 -1
  34. package/dist/internal/index/sqlite-vec-loader.d.ts +2 -59
  35. package/dist/internal/index/sqlite-vec-loader.d.ts.map +1 -1
  36. package/dist/internal/index/vec-index.d.ts +1 -131
  37. package/dist/internal/index/vec-index.d.ts.map +1 -1
  38. package/dist/internal/store/chunk-markdown.d.ts +1 -82
  39. package/dist/internal/store/chunk-markdown.d.ts.map +1 -1
  40. package/dist/internal/store/reader.d.ts +1 -86
  41. package/dist/internal/store/reader.d.ts.map +1 -1
  42. package/package.json +3 -3
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, readFactsFromMarkdown, appendDiaryEntry, lanceStoragePath, defaultIndexPath, projectMemoryDir, collectMarkdownFiles, readAllSqliteFacts, memoryMdPath, appendFactToMarkdown, ceilingReachedError } from '@theokit/sdk/internal/memory-store';
5
- export { MEMORY_INDEX_MAX_BYTES, MEMORY_INDEX_MAX_LINES, appendDiaryEntry, appendFact, appendFactToMarkdown, asMemoryRoot, ceilingReachedError, claudeProjectMemoryDir, collectMarkdownFiles, defaultIndexPath, diaryPath, discoverSessionFiles, discoverWikiFiles, entryHash, indexBudgetWarning, lanceStoragePath, memoryIndexRoot, memoryMdPath, memoryReadRoots, notesDir, persistActiveMemoryTranscript, projectMemoryDir, readAllSqliteFacts, readFacts, readFactsFromMarkdown, renderDiaryEntry, resolveMaxFacts, resolveMemoryRoot, sessionSummaryPath, sessionsDir, wikiDir, writeSessionSummary } from '@theokit/sdk/internal/memory-store';
6
- import { replaceFileAtomic, withCwdMutex, openSqliteResilient, sanitizeFts5Query } from '@theokit/sdk/persistence';
7
- import { createHash } from 'crypto';
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';
8
7
  import { createOpenAiCompatibleRuntime } from '@theokit/sdk/internal/memory-adapters';
9
8
  export { createOpenAiCompatibleRuntime } from '@theokit/sdk/internal/memory-adapters';
10
9
  import { AuthenticationError, RateLimitError, ConfigurationError, NetworkError, UnknownAgentError } from '@theokit/sdk/errors';
11
10
  import { sanitizeIdentifier, safePathJoin } from '@theokit/sdk/path-safety';
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";
@@ -504,48 +501,6 @@ var CircuitBreaker = class {
504
501
  return this.opts.now?.() ?? Date.now();
505
502
  }
506
503
  };
507
- var DEFAULT_TTL_MS = 15e3;
508
- var DEFAULT_CAPACITY = 1e3;
509
- var ActiveMemoryCache = class {
510
- constructor(opts = {}) {
511
- this.opts = opts;
512
- }
513
- opts;
514
- map = /* @__PURE__ */ new Map();
515
- get(userText, queryMode, tenantCtx) {
516
- const key = cacheKey(userText, queryMode, tenantCtx);
517
- const entry = this.map.get(key);
518
- if (entry === void 0) return void 0;
519
- if (this.now() >= entry.expiresAtMs) {
520
- this.map.delete(key);
521
- return void 0;
522
- }
523
- this.map.delete(key);
524
- this.map.set(key, entry);
525
- return entry.result;
526
- }
527
- set(userText, queryMode, result, tenantCtx) {
528
- const key = cacheKey(userText, queryMode, tenantCtx);
529
- if (this.map.size >= (this.opts.capacity ?? DEFAULT_CAPACITY)) {
530
- const oldest = this.map.keys().next().value;
531
- if (oldest !== void 0) this.map.delete(oldest);
532
- }
533
- this.map.set(key, {
534
- expiresAtMs: this.now() + (this.opts.ttlMs ?? DEFAULT_TTL_MS),
535
- result
536
- });
537
- }
538
- size() {
539
- return this.map.size;
540
- }
541
- now() {
542
- return this.opts.now?.() ?? Date.now();
543
- }
544
- };
545
- function cacheKey(userText, queryMode, ctx) {
546
- const parts = [queryMode, ctx?.namespace ?? "", ctx?.userId ?? "", ctx?.scope ?? "", userText];
547
- return createHash("sha256").update(parts.join("\0")).digest("hex");
548
- }
549
504
 
550
505
  // src/internal/embedding/azure-openai-embedding.ts
551
506
  var DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL = "text-embedding-3-small";
@@ -885,6 +840,8 @@ function legacyMemoryJsonPath(cwd, config) {
885
840
 
886
841
  // src/internal/adapter-http-error.ts
887
842
  var RAW_MAX_BYTES = 2048;
843
+ var PROVIDER_DETAIL_MAX_CHARS = 512;
844
+ var MISSING_MODEL_MESSAGE = /no endpoints found/i;
888
845
  function parseRetryAfter(headers) {
889
846
  if (headers === void 0) return void 0;
890
847
  const raw = headers.get("retry-after");
@@ -896,8 +853,8 @@ function parseRetryAfter(headers) {
896
853
  function truncateRaw(body) {
897
854
  if (body === null || body === void 0) return void 0;
898
855
  const s = typeof body === "string" ? body : JSON.stringify(body);
899
- const truncated = s.length <= RAW_MAX_BYTES ? s : `${s.slice(0, RAW_MAX_BYTES)}\u2026`;
900
- return redactSecrets(truncated);
856
+ const redacted = redactSecrets(s);
857
+ return redacted.length <= RAW_MAX_BYTES ? redacted : `${redacted.slice(0, RAW_MAX_BYTES)}\u2026`;
901
858
  }
902
859
  function buildErrorMetadata(args) {
903
860
  const retryAfter = parseRetryAfter(args.headers);
@@ -929,8 +886,16 @@ function mapOpenAICompatibleError(args) {
929
886
  if (status === 429) {
930
887
  return new RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });
931
888
  }
889
+ if (status === 404 && code === "model_unavailable") {
890
+ const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));
891
+ return new ConfigurationError(detailed, {
892
+ code: `${providerId}_model_unavailable`,
893
+ metadata
894
+ });
895
+ }
932
896
  if (status === 400) {
933
- return new ConfigurationError(message, { code: `${providerId}_${code}`, metadata });
897
+ const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));
898
+ return new ConfigurationError(detailed, { code: `${providerId}_${code}`, metadata });
934
899
  }
935
900
  if (status === 408) {
936
901
  return new NetworkError(message, { code: `${providerId}_timeout`, metadata });
@@ -940,6 +905,18 @@ function mapOpenAICompatibleError(args) {
940
905
  }
941
906
  return new UnknownAgentError(message, { code: `${providerId}_unknown`, metadata });
942
907
  }
908
+ function extractOpenAiErrorMessage(body) {
909
+ if (body === null || typeof body !== "object") return void 0;
910
+ const err = body.error;
911
+ if (err === void 0 || err === null) return void 0;
912
+ return typeof err.message === "string" ? err.message : void 0;
913
+ }
914
+ function boundedProviderDetail(body) {
915
+ const raw = extractOpenAiErrorMessage(body);
916
+ if (raw === void 0 || raw.trim() === "") return void 0;
917
+ const redacted = redactSecrets(raw);
918
+ return redacted.length <= PROVIDER_DETAIL_MAX_CHARS ? redacted : `${redacted.slice(0, PROVIDER_DETAIL_MAX_CHARS)}\u2026`;
919
+ }
943
920
  function extractOpenAiErrorCode(body) {
944
921
  if (body === null || typeof body !== "object") return void 0;
945
922
  const err = body.error;
@@ -962,6 +939,9 @@ function mapOpenAiStatusToCode(status, body) {
962
939
  if (status === 402 || rawCode.includes("insufficient_quota") || rawCode.includes("quota_exceeded")) {
963
940
  return "quota_exceeded";
964
941
  }
942
+ if (status === 404 && MISSING_MODEL_MESSAGE.test(extractOpenAiErrorMessage(body) ?? "")) {
943
+ return "model_unavailable";
944
+ }
965
945
  if (status === 401 || status === 403) return "auth_failed";
966
946
  if (status === 429) return "rate_limit";
967
947
  if (status === 408) return "timeout";
@@ -969,8 +949,9 @@ function mapOpenAiStatusToCode(status, body) {
969
949
  if (status >= 500 && status < 600) return "server_error";
970
950
  return "unknown";
971
951
  }
972
- function formatMessage(providerId, status, code) {
973
- return `${providerId} API error: ${code} (HTTP ${status})`;
952
+ function formatMessage(providerId, status, code, detail) {
953
+ const base = `${providerId} API error: ${code} (HTTP ${status})`;
954
+ return detail === void 0 || detail === "" ? base : `${base}: ${detail}`;
974
955
  }
975
956
  var FACTS_HEADING = "## Facts";
976
957
  function createCategorizedMemory(options) {
@@ -1098,536 +1079,17 @@ ${bullet}
1098
1079
  return `${raw.slice(0, insertAt)}
1099
1080
  ${bullet}${raw.slice(insertAt)}`;
1100
1081
  }
1101
-
1102
- // src/internal/dreaming/dreaming-phases.ts
1103
- var DEFAULT_DEDUP_THRESHOLD = 0.95;
1104
- var DEFAULT_CLUSTER_THRESHOLD = 0.75;
1105
- async function lightPhase(facts, embedding, threshold = DEFAULT_DEDUP_THRESHOLD) {
1106
- if (facts.length <= 1) return { kept: [...facts], duplicatesRemoved: 0 };
1107
- const vectors = await embedding.embed(facts.map((f) => f.text));
1108
- const keptIdx = [];
1109
- const keptVecs = [];
1110
- for (let i = 0; i < facts.length; i++) {
1111
- const vec = vectors[i] ?? [];
1112
- const isDup = keptVecs.some((kept2) => cosineSimilarity(vec, kept2) >= threshold);
1113
- if (isDup) continue;
1114
- keptIdx.push(i);
1115
- keptVecs.push(vec);
1116
- }
1117
- const kept = keptIdx.map((i) => facts[i]);
1118
- return { kept, duplicatesRemoved: facts.length - kept.length };
1119
- }
1120
- var DEFAULT_MAX_FACTS_PER_SWEEP = 500;
1121
- async function remPhase(facts, embedding, threshold = DEFAULT_CLUSTER_THRESHOLD, maxFactsPerSweep = DEFAULT_MAX_FACTS_PER_SWEEP) {
1122
- if (facts.length === 0) return { clusters: [], factsLeftOut: 0 };
1123
- const capped = facts.length > maxFactsPerSweep ? facts.slice(0, maxFactsPerSweep) : facts;
1124
- const vectors = await embedding.embed(capped.map((f) => f.text));
1125
- const clusterOfIdx = unionFindByPairs(vectors, threshold);
1126
- const groups = bucketFactsByClusterRoot(capped, clusterOfIdx);
1127
- return {
1128
- clusters: [...groups.values()].map(buildClusterFromMembers),
1129
- factsLeftOut: facts.length - capped.length
1130
- };
1131
- }
1132
- function unionFindByPairs(vectors, threshold) {
1133
- const clusterOfIdx = vectors.map((_, i) => i);
1134
- for (let i = 0; i < vectors.length; i++) {
1135
- for (let j = i + 1; j < vectors.length; j++) {
1136
- if (cosineSimilarity(vectors[i] ?? [], vectors[j] ?? []) >= threshold) {
1137
- unifyClusters(clusterOfIdx, i, j);
1138
- }
1139
- }
1140
- }
1141
- return clusterOfIdx;
1142
- }
1143
- function bucketFactsByClusterRoot(facts, clusterOfIdx) {
1144
- const groups = /* @__PURE__ */ new Map();
1145
- for (let i = 0; i < facts.length; i++) {
1146
- const root = findRoot(clusterOfIdx, i);
1147
- const list = groups.get(root) ?? [];
1148
- list.push(facts[i]);
1149
- groups.set(root, list);
1150
- }
1151
- return groups;
1152
- }
1153
- function buildClusterFromMembers(members) {
1154
- const sorted = [...members].sort((a, b) => b.text.length - a.text.length);
1155
- return { representativeText: sorted[0]?.text ?? "", members };
1156
- }
1157
- function deepPhase(clusters, timestampMs) {
1158
- if (clusters.length === 0) return "";
1159
- const isoStamp = new Date(timestampMs).toISOString();
1160
- const lines = [`# Dreamed ${isoStamp}`, ""];
1161
- for (let i = 0; i < clusters.length; i++) {
1162
- const c = clusters[i];
1163
- if (c === void 0) continue;
1164
- lines.push(`## Cluster ${i + 1}: ${c.representativeText}`);
1165
- lines.push("");
1166
- for (const member of c.members) lines.push(`- ${member.text}`);
1167
- lines.push("");
1168
- }
1169
- return `${lines.join("\n")}
1170
- `;
1171
- }
1172
- function cosineSimilarity(a, b) {
1173
- if (a.length === 0 || b.length === 0 || a.length !== b.length) return 0;
1174
- let dot = 0;
1175
- let aNorm = 0;
1176
- let bNorm = 0;
1177
- for (let i = 0; i < a.length; i++) {
1178
- const ai = a[i] ?? 0;
1179
- const bi = b[i] ?? 0;
1180
- dot += ai * bi;
1181
- aNorm += ai * ai;
1182
- bNorm += bi * bi;
1183
- }
1184
- const denom = Math.sqrt(aNorm) * Math.sqrt(bNorm);
1185
- return denom === 0 ? 0 : dot / denom;
1186
- }
1187
- function findRoot(parents, i) {
1188
- let root = i;
1189
- while (parents[root] !== root) {
1190
- const next = parents[root] ?? root;
1191
- if (next === root) break;
1192
- root = next;
1193
- }
1194
- parents[i] = root;
1195
- return root;
1196
- }
1197
- function unifyClusters(parents, a, b) {
1198
- const rootA = findRoot(parents, a);
1199
- const rootB = findRoot(parents, b);
1200
- if (rootA !== rootB) parents[rootB] = rootA;
1201
- }
1202
- function runDreamingSweep(options) {
1203
- return withCwdMutex(`dream:${options.cwd}`, () => runInner(options));
1204
- }
1205
- async function runInner(options) {
1206
- const now = options.now ?? Date.now;
1207
- const timestampMs = now();
1208
- try {
1209
- const facts = await readFactsFromMarkdown(options.cwd);
1210
- if (facts.length === 0) {
1211
- return emptyResult("skipped");
1212
- }
1213
- const dedup = await lightPhase(facts, options.embedding, options.dedupThreshold);
1214
- const rem = await remPhase(dedup.kept, options.embedding, options.clusterThreshold);
1215
- const notesWritten = await writeConsolidatedNotes(options.cwd, rem.clusters, timestampMs);
1216
- const result = {
1217
- status: "ok",
1218
- factsBefore: facts.length,
1219
- factsAfter: dedup.kept.length,
1220
- duplicatesRemoved: dedup.duplicatesRemoved,
1221
- clustersCreated: rem.clusters.length,
1222
- notesWritten,
1223
- diaryEntryHash: void 0,
1224
- factsLeftOut: rem.factsLeftOut
1225
- };
1226
- await appendDiaryEntry(resolveMemoryRoot(options.cwd), {
1227
- timestampMs,
1228
- factsBefore: result.factsBefore,
1229
- factsAfter: result.factsAfter,
1230
- duplicatesRemoved: result.duplicatesRemoved,
1231
- clustersCreated: result.clustersCreated,
1232
- notesWritten: result.notesWritten
1233
- });
1234
- return result;
1235
- } catch (cause) {
1236
- const message = cause instanceof Error ? cause.message : String(cause);
1237
- process.stderr.write(`[theokit-sdk] dreaming sweep failed: ${message}
1238
- `);
1239
- return emptyResult("error");
1240
- }
1241
- }
1242
- async function writeConsolidatedNotes(cwd, clusters, timestampMs) {
1243
- if (clusters.length === 0) return 0;
1244
- const notesDir3 = join(resolveMemoryRoot(cwd), "notes");
1245
- await mkdir(notesDir3, { recursive: true });
1246
- const isoSlug = new Date(timestampMs).toISOString().replace(/[^\dT]/g, "-");
1247
- const file = join(notesDir3, `dreamed-${isoSlug}.md`);
1248
- const body = deepPhase(clusters, timestampMs);
1249
- await replaceFileAtomic(file, body);
1250
- return 1;
1251
- }
1252
- function emptyResult(status) {
1253
- const result = {
1254
- status,
1255
- factsBefore: 0,
1256
- factsAfter: 0,
1257
- duplicatesRemoved: 0,
1258
- clustersCreated: 0,
1259
- notesWritten: 0,
1260
- diaryEntryHash: void 0
1261
- };
1262
- return status === "skipped" ? { ...result, factsLeftOut: 0 } : result;
1263
- }
1264
-
1265
- // src/internal/index/index-schema.ts
1266
- var SCHEMA_STATEMENTS = [
1267
- `CREATE TABLE IF NOT EXISTS files (
1268
- id INTEGER PRIMARY KEY AUTOINCREMENT,
1269
- path TEXT UNIQUE NOT NULL,
1270
- rel_path TEXT NOT NULL,
1271
- mtime INTEGER NOT NULL,
1272
- hash TEXT NOT NULL,
1273
- source TEXT NOT NULL DEFAULT 'memory'
1274
- )`,
1275
- `CREATE TABLE IF NOT EXISTS chunks (
1276
- id INTEGER PRIMARY KEY AUTOINCREMENT,
1277
- file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
1278
- start_line INTEGER NOT NULL,
1279
- end_line INTEGER NOT NULL,
1280
- text TEXT NOT NULL,
1281
- hash TEXT NOT NULL,
1282
- session_key TEXT
1283
- )`,
1284
- `CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
1285
- text,
1286
- content='chunks',
1287
- content_rowid='id'
1288
- )`,
1289
- `CREATE TRIGGER IF NOT EXISTS chunks_fts_insert AFTER INSERT ON chunks BEGIN
1290
- INSERT INTO chunks_fts(rowid, text) VALUES (new.id, new.text);
1291
- END`,
1292
- `CREATE TRIGGER IF NOT EXISTS chunks_fts_delete AFTER DELETE ON chunks BEGIN
1293
- INSERT INTO chunks_fts(chunks_fts, rowid, text) VALUES ('delete', old.id, old.text);
1294
- END`,
1295
- `CREATE TABLE IF NOT EXISTS meta (
1296
- key TEXT PRIMARY KEY,
1297
- value TEXT
1298
- )`,
1299
- `CREATE INDEX IF NOT EXISTS idx_chunks_file_id ON chunks(file_id)`
1300
- ];
1301
- var PRAGMA_STATEMENTS = [
1302
- "PRAGMA synchronous=NORMAL",
1303
- "PRAGMA foreign_keys=ON"
1304
- ];
1305
-
1306
- // src/internal/index/index-db.ts
1307
- async function openMemoryDb(opts) {
1308
- return openSqliteResilient({
1309
- filePath: opts.filePath,
1310
- label: "memory-index",
1311
- recoverCorrupt: opts.recoverCorrupt,
1312
- onOpen: (db) => {
1313
- for (const pragma of PRAGMA_STATEMENTS) db.exec(pragma);
1314
- for (const stmt of SCHEMA_STATEMENTS) db.exec(stmt);
1315
- }
1316
- });
1317
- }
1318
- var HEADING_RE = /^(#{1,6})\s+(.+?)\s*$/;
1319
- function chunkMarkdown(text, options = {}) {
1320
- const maxChars = options.maxChars ?? 800;
1321
- if (text.length === 0) return [];
1322
- const lines = text.split("\n");
1323
- const acc = { chunks: [], lines: [], start: 1, heading: void 0 };
1324
- for (let i = 0; i < lines.length; i++) {
1325
- const line = lines[i] ?? "";
1326
- const lineNumber = i + 1;
1327
- processLine(acc, line, lineNumber, maxChars);
1328
- }
1329
- flushAccumulator(acc, lines.length, maxChars);
1330
- return acc.chunks;
1331
- }
1332
- function processLine(acc, line, lineNumber, maxChars) {
1333
- const headingMatch = HEADING_RE.exec(line);
1334
- const isBlank = line.trim().length === 0;
1335
- if (headingMatch !== null && acc.lines.length > 0) {
1336
- flushAccumulator(acc, lineNumber - 1, maxChars);
1337
- }
1338
- if (headingMatch !== null) acc.heading = headingMatch[2];
1339
- acc.lines.push(line);
1340
- if (isBlank && acc.lines.length > 1) {
1341
- const joined = acc.lines.join("\n");
1342
- if (joined.trim().length > 0) flushAccumulator(acc, lineNumber, maxChars);
1343
- }
1344
- }
1345
- function flushAccumulator(acc, endLineExclusive, maxChars) {
1346
- if (acc.lines.length === 0) return;
1347
- const chunkText = acc.lines.join("\n");
1348
- if (chunkText.trim().length === 0) {
1349
- acc.lines = [];
1350
- acc.start = endLineExclusive + 1;
1351
- return;
1352
- }
1353
- if (chunkText.length > maxChars) {
1354
- pushOversizedSlices(acc.chunks, chunkText, acc.start, acc.heading, maxChars);
1355
- } else {
1356
- acc.chunks.push(buildChunk(chunkText, acc.start, endLineExclusive, acc.heading));
1357
- }
1358
- acc.lines = [];
1359
- acc.start = endLineExclusive + 1;
1360
- }
1361
- function buildChunk(text, startLine, endLine, heading) {
1362
- return {
1363
- startLine,
1364
- endLine,
1365
- text,
1366
- hash: createHash("sha256").update(text).digest("hex"),
1367
- ...heading !== void 0 ? { heading } : {}
1368
- };
1369
- }
1370
- function pushOversizedSlices(chunks, text, startLine, heading, maxChars) {
1371
- let remaining = text;
1372
- let lineCursor = startLine;
1373
- while (remaining.length > maxChars) {
1374
- const splitAt = findWordBoundarySplit(remaining, maxChars);
1375
- const slice = remaining.slice(0, splitAt);
1376
- const sliceLines = slice.split("\n").length;
1377
- chunks.push(buildChunk(slice, lineCursor, lineCursor + sliceLines - 1, heading));
1378
- remaining = remaining.slice(splitAt).replace(/^\s+/, "");
1379
- lineCursor += sliceLines - 1;
1380
- }
1381
- if (remaining.length > 0) {
1382
- const sliceLines = remaining.split("\n").length;
1383
- chunks.push(buildChunk(remaining, lineCursor, lineCursor + sliceLines - 1, heading));
1384
- }
1385
- }
1386
- function findWordBoundarySplit(text, maxChars) {
1387
- if (text.length <= maxChars) return text.length;
1388
- for (let i = maxChars; i > Math.max(0, maxChars - 200); i--) {
1389
- if (/\s/.test(text[i] ?? "x")) return i;
1390
- }
1391
- return maxChars;
1392
- }
1393
- function requireLance() {
1394
- try {
1395
- const r = createRequire(import.meta.url);
1396
- return r("@lancedb/lancedb");
1397
- } catch (cause) {
1398
- throw new ConfigurationError(
1399
- 'Lance backend selected but `@lancedb/lancedb` is not installed. Install with: `pnpm add @lancedb/lancedb`. SQLite remains available as the default (omit `backend: "lance"`).',
1400
- { code: "lance_backend_unavailable", cause }
1401
- );
1402
- }
1403
- }
1404
- var LanceIndex = class _LanceIndex {
1405
- constructor(table, embedding, embeddingDim) {
1406
- this.table = table;
1407
- this.embedding = embedding;
1408
- this.embeddingDim = embeddingDim;
1409
- }
1410
- table;
1411
- embedding;
1412
- embeddingDim;
1413
- static async open(opts) {
1414
- const lance = requireLance();
1415
- const storagePath = opts.storagePath ?? lanceStoragePath(opts.memoryRoot ?? resolveMemoryRoot(opts.cwd));
1416
- mkdirSync(storagePath, { recursive: true });
1417
- const conn = await lance.connect(storagePath);
1418
- const dim = opts.embedding.dimension;
1419
- const tableName = "facts";
1420
- const existing = await conn.tableNames();
1421
- let table;
1422
- if (existing.includes(tableName)) {
1423
- table = await conn.openTable(tableName);
1424
- const schema = await table.schema();
1425
- const embField = schema.fields.find((f) => f.name === "embedding");
1426
- const existingDim = embField?.type?.listSize ?? embField?.type?.fixedSize;
1427
- if (typeof existingDim === "number" && existingDim !== dim) {
1428
- throw new ConfigurationError(
1429
- `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.`,
1430
- { code: "embedding_dimension_mismatch" }
1431
- );
1432
- }
1433
- } else {
1434
- const bootstrap = {
1435
- id: "__bootstrap__",
1436
- text: "",
1437
- source: "memory",
1438
- embedding: new Array(dim).fill(0),
1439
- namespace: "__bootstrap__",
1440
- scope: "__bootstrap__",
1441
- user_id: "__bootstrap__",
1442
- timestamp: 0
1443
- };
1444
- table = await conn.createTable(tableName, [bootstrap]);
1445
- await table.delete("namespace = '__bootstrap__'");
1446
- }
1447
- return new _LanceIndex(table, opts.embedding, dim);
1448
- }
1449
- async addFacts(facts) {
1450
- if (facts.length === 0) return;
1451
- const texts = facts.map((f) => f.text);
1452
- const embeddings = await this.embedding.embed(texts);
1453
- const rows = facts.map((f, i) => ({
1454
- ...f,
1455
- embedding: embeddings[i] ?? new Array(this.embeddingDim).fill(0)
1456
- }));
1457
- await this.table.add(rows);
1458
- }
1459
- /**
1460
- * Search facts by semantic similarity. EC-1: filters use Lance's
1461
- * SQL string predicate with `'` → `''` escape — bind parameters are
1462
- * not supported by Lance 0.30.
1463
- */
1464
- async search(query, opts) {
1465
- const [embedding] = await this.embedding.embed([query]);
1466
- if (embedding === void 0) return [];
1467
- const predicates = [`namespace = '${escapeSqlValue(opts.namespace)}'`];
1468
- if (opts.scope !== void 0) {
1469
- predicates.push(`scope = '${escapeSqlValue(opts.scope)}'`);
1470
- }
1471
- let q = this.table.search(embedding).where(predicates.join(" AND "));
1472
- if (opts.limit !== void 0) q = q.limit(opts.limit);
1473
- const results = await q.toArray();
1474
- return results.filter((r) => opts.sources === void 0 || opts.sources.includes(r.source)).map((r) => ({
1475
- id: r.id,
1476
- text: r.text,
1477
- source: r.source,
1478
- namespace: r.namespace,
1479
- scope: r.scope,
1480
- userId: r.user_id,
1481
- // Lower _distance = better match; normalize to 0..1 (1=best).
1482
- score: 1 / (1 + (r._distance ?? 1))
1483
- }));
1484
- }
1485
- async countFacts(namespace) {
1486
- return this.table.countRows();
1487
- }
1488
- async removeFacts(ids) {
1489
- if (ids.length === 0) return;
1490
- const escaped = ids.map((id) => `'${id.replace(/'/g, "''")}'`).join(", ");
1491
- await this.table.delete(`id IN (${escaped})`);
1492
- }
1493
- async close() {
1494
- }
1495
- };
1496
- function escapeSqlValue(value) {
1497
- for (let i = 0; i < value.length; i++) {
1498
- const code = value.charCodeAt(i);
1499
- if (code === 0 || code >= 1 && code <= 31 || code === 127) {
1500
- throw new ConfigurationError(
1501
- `SQL filter value contains control character at position ${i} (0x${code.toString(16)}). This may indicate an injection attempt.`,
1502
- { code: "sql_injection_blocked" }
1503
- );
1504
- }
1505
- }
1506
- return value.replace(/\\/g, "\\\\").replace(/'/g, "''");
1507
- }
1508
- function isLanceAvailable() {
1509
- try {
1510
- const r = createRequire(import.meta.url);
1511
- r("@lancedb/lancedb");
1512
- return true;
1513
- } catch {
1514
- return false;
1515
- }
1516
- }
1517
-
1518
- // src/internal/index/memory-index.ts
1519
- function parseSearchOptions(options = {}) {
1520
- return {
1521
- maxResults: Math.max(1, options.maxResults ?? 10),
1522
- minScore: options.minScore ?? 0
1523
- };
1524
- }
1525
-
1526
- // src/internal/index/lance-memory-adapter.ts
1527
- var DEFAULT_NAMESPACE = "default";
1528
- var EMPTY_SYNC_RESULT = Object.freeze({
1529
- filesScanned: 0,
1530
- filesUpdated: 0,
1531
- chunksWritten: 0,
1532
- chunksEmbedded: 0
1533
- });
1534
- var LanceMemoryAdapter = class {
1082
+ var LanceMemoryAdapter = class extends LanceMemoryAdapter$1 {
1083
+ #lance;
1535
1084
  constructor(inner) {
1536
- this.inner = inner;
1537
- }
1538
- inner;
1539
- /**
1540
- * No-op for Lance — see file header. Returns zero counts so callers'
1541
- * existing logging (`filesScanned: X`) does not break.
1542
- */
1543
- async sync() {
1544
- return EMPTY_SYNC_RESULT;
1085
+ super(inner);
1086
+ this.#lance = inner;
1545
1087
  }
1546
- // jscpd:ignore-start — search signature + early-out is idiomatic
1547
- // overlap with IndexManager.search; further factoring would hurt
1548
- // readability (the bodies diverge sharply right after).
1549
- async search(query, options = {}) {
1550
- if (query.trim().length === 0) return [];
1551
- const { maxResults, minScore } = parseSearchOptions(options);
1552
- const lanceHits = await this.inner.search(query, {
1553
- namespace: DEFAULT_NAMESPACE,
1554
- limit: maxResults * 2,
1555
- ...options.sources !== void 0 ? { sources: options.sources } : {}
1556
- });
1557
- return lanceHits.filter((h) => h.score >= minScore).slice(0, maxResults).map((h) => translateLanceHit(h));
1558
- }
1559
- status() {
1560
- return {
1561
- backend: "hybrid",
1562
- filesIndexed: 0,
1563
- chunksIndexed: 0
1564
- };
1565
- }
1566
- async close() {
1567
- await this.inner.close();
1568
- }
1569
- /**
1570
- * Escape hatch for advanced callers (migration tool, benchmark script)
1571
- * that need direct access to addFacts/countFacts/removeFacts.
1572
- */
1088
+ /** The wrapped `LanceIndex`, for `addFacts`, `countFacts` and `removeFacts`. */
1573
1089
  unwrap() {
1574
- return this.inner;
1090
+ return this.#lance;
1575
1091
  }
1576
1092
  };
1577
- function translateLanceHit(hit) {
1578
- return {
1579
- path: hit.id,
1580
- startLine: 0,
1581
- endLine: 0,
1582
- score: hit.score,
1583
- textScore: 0,
1584
- vectorScore: hit.score,
1585
- snippet: hit.text.slice(0, 200),
1586
- source: hit.source,
1587
- citation: hit.id
1588
- };
1589
- }
1590
-
1591
- // src/internal/index/index-manager-dispatch.ts
1592
- var VALID_BACKENDS = ["sqlite-vec", "lance"];
1593
- function assertValidBackend(backend) {
1594
- if (!VALID_BACKENDS.includes(backend)) {
1595
- throw new ConfigurationError(
1596
- `Invalid memory backend "${backend}". Valid values: ${VALID_BACKENDS.join(", ")}.`,
1597
- { code: "invalid_memory_backend" }
1598
- );
1599
- }
1600
- }
1601
- async function openLanceIndex(opts) {
1602
- if (opts.embedding === void 0) {
1603
- throw new ConfigurationError(
1604
- "Lance backend requires an embedding runtime. Pass `embedding: { provider, model, apiKey }` in Memory.create options (or omit `backend` to use SQLite default).",
1605
- { code: "lance_requires_embedding" }
1606
- );
1607
- }
1608
- const lance = await LanceIndex.open({
1609
- cwd: opts.cwd,
1610
- embedding: opts.embedding,
1611
- ...opts.filePath !== void 0 ? { storagePath: opts.filePath } : {}
1612
- });
1613
- return new LanceMemoryAdapter(lance);
1614
- }
1615
- async function loadSqliteVecExtension(db) {
1616
- try {
1617
- const mod = await import('sqlite-vec');
1618
- const loadFn = mod.load;
1619
- if (typeof loadFn !== "function") {
1620
- throw new Error("sqlite-vec module exposes no `load` export");
1621
- }
1622
- loadFn(db);
1623
- } catch (cause) {
1624
- const message = cause instanceof Error ? cause.message : String(cause);
1625
- throw new ConfigurationError(
1626
- `sqlite-vec extension unavailable. Install \`sqlite-vec\` and ensure the native binary matches your Node + OS. Cause: ${message}`,
1627
- { code: "sqlite_vec_unavailable", cause }
1628
- );
1629
- }
1630
- }
1631
1093
  function isSqliteVecLoaded(db) {
1632
1094
  try {
1633
1095
  const row = db.prepare("SELECT vec_version() as v").get();
@@ -1636,533 +1098,6 @@ function isSqliteVecLoaded(db) {
1636
1098
  return false;
1637
1099
  }
1638
1100
  }
1639
-
1640
- // src/internal/index/vec-index.ts
1641
- var META_KEY_PROVIDER_ID = "embedding.providerId";
1642
- var META_KEY_MODEL = "embedding.model";
1643
- var META_KEY_DIMENSION = "embedding.dimension";
1644
- function readEmbeddingIdentity(db) {
1645
- const get = (key) => {
1646
- const row = db.prepare("SELECT value FROM meta WHERE key = ?").get(key);
1647
- return row !== void 0 ? String(row.value) : void 0;
1648
- };
1649
- const providerId = get(META_KEY_PROVIDER_ID);
1650
- const model = get(META_KEY_MODEL);
1651
- const dimRaw = get(META_KEY_DIMENSION);
1652
- if (providerId === void 0 || model === void 0 || dimRaw === void 0) return void 0;
1653
- const dimension = Number(dimRaw);
1654
- if (!Number.isFinite(dimension) || dimension <= 0) return void 0;
1655
- return { providerId, model, dimension };
1656
- }
1657
- function writeEmbeddingIdentity(db, identity) {
1658
- const stmt = db.prepare(
1659
- "INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
1660
- );
1661
- stmt.run(META_KEY_PROVIDER_ID, identity.providerId);
1662
- stmt.run(META_KEY_MODEL, identity.model);
1663
- stmt.run(META_KEY_DIMENSION, String(identity.dimension));
1664
- }
1665
- function identityMatches(a, b) {
1666
- return a.providerId === b.providerId && a.model === b.model && a.dimension === b.dimension;
1667
- }
1668
- function dropVectorIndex(db) {
1669
- db.exec("DROP TABLE IF EXISTS embeddings");
1670
- }
1671
- function createVectorIndex(db, dimension) {
1672
- db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS embeddings USING vec0(
1673
- chunk_id INTEGER PRIMARY KEY,
1674
- vec FLOAT[${dimension}]
1675
- )`);
1676
- }
1677
- function packVector(vec) {
1678
- const f32 = new Float32Array(vec.length);
1679
- for (let i = 0; i < vec.length; i++) f32[i] = vec[i] ?? 0;
1680
- return Buffer.from(f32.buffer);
1681
- }
1682
- function upsertEmbedding(db, chunkId, vec) {
1683
- const id = BigInt(chunkId);
1684
- db.prepare("DELETE FROM embeddings WHERE chunk_id = ?").run(id);
1685
- db.prepare("INSERT INTO embeddings (chunk_id, vec) VALUES (?, ?)").run(id, packVector(vec));
1686
- }
1687
- function vectorSearch(db, query, k) {
1688
- const rows = db.prepare(
1689
- `SELECT chunk_id, distance FROM embeddings
1690
- WHERE vec MATCH ? AND k = ?
1691
- ORDER BY distance`
1692
- ).all(packVector(query), BigInt(k));
1693
- return rows.map((row) => ({ chunk_id: Number(row.chunk_id), distance: Number(row.distance) }));
1694
- }
1695
- async function embedMissingChunks(args) {
1696
- const rows = args.db.prepare(
1697
- `SELECT chunks.id as id, chunks.text as text
1698
- FROM chunks
1699
- LEFT JOIN embeddings ON embeddings.chunk_id = chunks.id
1700
- WHERE embeddings.chunk_id IS NULL`
1701
- ).all();
1702
- if (rows.length === 0) return 0;
1703
- const normalized = rows.map((row) => ({ id: Number(row.id), text: String(row.text ?? "") }));
1704
- const vectors = await args.runtime.embed(normalized.map((r) => r.text));
1705
- for (let i = 0; i < normalized.length; i++) {
1706
- const row = normalized[i];
1707
- const vector = vectors[i];
1708
- if (row === void 0 || vector === void 0) continue;
1709
- upsertEmbedding(args.db, row.id, vector);
1710
- }
1711
- return normalized.length;
1712
- }
1713
-
1714
- // src/internal/index/index-manager.ts
1715
- var IndexManager = class _IndexManager {
1716
- constructor(memoryRoot, db, embedding) {
1717
- this.memoryRoot = memoryRoot;
1718
- this.db = db;
1719
- this.embedding = embedding;
1720
- }
1721
- memoryRoot;
1722
- db;
1723
- embedding;
1724
- lastSyncMs;
1725
- vectorReady = false;
1726
- static async open(opts) {
1727
- const backend = opts.backend ?? "sqlite-vec";
1728
- assertValidBackend(backend);
1729
- if (backend === "lance") return await openLanceIndex(opts);
1730
- return await _IndexManager.openSqliteInternal(opts);
1731
- }
1732
- /** Internal SQLite-path open. Renamed from previous public `open`. */
1733
- static async openSqliteInternal(opts) {
1734
- const memoryRoot = opts.memoryRoot ?? resolveMemoryRoot(opts.cwd);
1735
- const filePath = opts.filePath ?? defaultIndexPath(projectMemoryDir(opts.cwd));
1736
- const db = await openMemoryDb({ filePath });
1737
- const manager = new _IndexManager(memoryRoot, db, opts.embedding);
1738
- if (opts.embedding !== void 0) await manager.initVectorBackend(opts.embedding);
1739
- return manager;
1740
- }
1741
- async initVectorBackend(runtime) {
1742
- await loadSqliteVecExtension(this.db);
1743
- const currentIdentity = {
1744
- providerId: runtime.id,
1745
- model: runtime.model,
1746
- dimension: runtime.dimension
1747
- };
1748
- const persisted = readEmbeddingIdentity(this.db);
1749
- if (persisted !== void 0 && !identityMatches(persisted, currentIdentity)) {
1750
- dropVectorIndex(this.db);
1751
- }
1752
- createVectorIndex(this.db, runtime.dimension);
1753
- writeEmbeddingIdentity(this.db, currentIdentity);
1754
- this.vectorReady = true;
1755
- }
1756
- /** Walk the memory corpus + (re)index changed files. */
1757
- async sync() {
1758
- const files = await collectMarkdownFiles(this.memoryRoot);
1759
- let filesUpdated = 0;
1760
- let chunksWritten = 0;
1761
- const existingByPath = this.loadFilesIndex();
1762
- for (const entry of files) {
1763
- const raw = await readFile(entry.absolutePath, "utf8");
1764
- const hash = sha256(raw);
1765
- const existing = existingByPath.get(entry.absolutePath);
1766
- if (existing !== void 0 && existing.hash === hash) continue;
1767
- const stats = await stat(entry.absolutePath);
1768
- const fileId = this.upsertFile(
1769
- entry.absolutePath,
1770
- entry.relPath,
1771
- hash,
1772
- stats.mtimeMs,
1773
- entry.source
1774
- );
1775
- this.deleteChunksForFile(fileId);
1776
- const chunks = chunkMarkdown(raw);
1777
- for (const chunk of chunks) {
1778
- this.insertChunk(fileId, chunk.startLine, chunk.endLine, chunk.text, chunk.hash);
1779
- }
1780
- filesUpdated += 1;
1781
- chunksWritten += chunks.length;
1782
- }
1783
- let chunksEmbedded = 0;
1784
- if (this.vectorReady && this.embedding !== void 0) {
1785
- chunksEmbedded = await embedMissingChunks({ db: this.db, runtime: this.embedding });
1786
- }
1787
- this.lastSyncMs = Date.now();
1788
- return { filesScanned: files.length, filesUpdated, chunksWritten, chunksEmbedded };
1789
- }
1790
- async search(query, options = {}) {
1791
- if (query.trim().length === 0) return [];
1792
- const { maxResults, minScore } = parseSearchOptions(options);
1793
- const textHits = this.ftsSearch(query, maxResults * 2);
1794
- const vectorHitsById = await this.vectorSearchById(query, maxResults * 2);
1795
- const combined = this.combineHybridScores(textHits, vectorHitsById, options);
1796
- return combined.filter((h) => h.score >= minScore).filter((h) => options.sources === void 0 || options.sources.includes(h.source)).slice(0, maxResults);
1797
- }
1798
- status() {
1799
- const files = this.db.prepare("SELECT COUNT(*) as n FROM files").get() ?? { n: 0 };
1800
- const chunks = this.db.prepare("SELECT COUNT(*) as n FROM chunks").get() ?? { n: 0 };
1801
- const status = {
1802
- backend: this.vectorReady ? "hybrid" : "fts-only",
1803
- filesIndexed: Number(files.n ?? 0),
1804
- chunksIndexed: Number(chunks.n ?? 0)
1805
- };
1806
- if (this.lastSyncMs !== void 0) status.lastSyncMs = this.lastSyncMs;
1807
- return status;
1808
- }
1809
- // ───── search internals ──────────────────────────────────────────────
1810
- ftsSearch(query, limit) {
1811
- const sanitized = sanitizeFts5Query(query);
1812
- if (sanitized.length === 0) return [];
1813
- const stmt = this.db.prepare(
1814
- `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,
1815
- chunks.start_line as start_line, chunks.end_line as end_line,
1816
- chunks.text as text, bm25(chunks_fts) as bm25_score
1817
- FROM chunks_fts
1818
- JOIN chunks ON chunks_fts.rowid = chunks.id
1819
- JOIN files ON chunks.file_id = files.id
1820
- WHERE chunks_fts MATCH ?
1821
- ORDER BY bm25_score
1822
- LIMIT ?`
1823
- );
1824
- let rows = [];
1825
- try {
1826
- rows = stmt.all(sanitized, limit);
1827
- } catch {
1828
- return [];
1829
- }
1830
- return rows.map((row) => {
1831
- const bm25 = Number(row.bm25_score ?? 0);
1832
- const textScore = bm25 < 0 ? 1 / (1 + Math.abs(bm25)) : 1 / (1 + bm25);
1833
- const startLine = Number(row.start_line ?? 0);
1834
- const endLine = Number(row.end_line ?? 0);
1835
- const path = String(row.rel_path);
1836
- return {
1837
- path,
1838
- startLine,
1839
- endLine,
1840
- score: textScore,
1841
- textScore,
1842
- snippet: truncateSnippet(String(row.text ?? "")),
1843
- source: String(row.source),
1844
- citation: `${path}:${startLine}-${endLine}`,
1845
- // sneak the chunk id through for the hybrid join below
1846
- // (cast away later)
1847
- chunkId: Number(row.id)
1848
- };
1849
- });
1850
- }
1851
- async vectorSearchById(query, limit) {
1852
- if (!this.vectorReady || this.embedding === void 0) return /* @__PURE__ */ new Map();
1853
- const [queryVec] = await this.embedding.embed([query]);
1854
- if (queryVec === void 0) return /* @__PURE__ */ new Map();
1855
- const rows = vectorSearch(this.db, queryVec, limit);
1856
- const out = /* @__PURE__ */ new Map();
1857
- for (const row of rows) {
1858
- const score = 1 / (1 + Math.max(0, row.distance));
1859
- out.set(row.chunk_id, { vectorScore: score });
1860
- }
1861
- return out;
1862
- }
1863
- combineHybridScores(textHits, vectorHitsById, options) {
1864
- const weights = resolveWeights(options);
1865
- const merged = this.mergeHits(textHits, vectorHitsById);
1866
- const combined = [...merged.values()].map(
1867
- (hit) => blendScores(hit, vectorHitsById.get(hit.chunkId)?.vectorScore ?? 0, weights)
1868
- );
1869
- return combined.sort((a, b) => b.score - a.score);
1870
- }
1871
- mergeHits(textHits, vectorHitsById) {
1872
- const merged = /* @__PURE__ */ new Map();
1873
- for (const hit of textHits) merged.set(hit.chunkId, hit);
1874
- const missingIds = [...vectorHitsById.keys()].filter((id) => !merged.has(id));
1875
- if (missingIds.length > 0) {
1876
- for (const hit of this.fetchChunksByIds(missingIds)) {
1877
- merged.set(hit.chunkId, { ...hit, score: 0, textScore: 0 });
1878
- }
1879
- }
1880
- return merged;
1881
- }
1882
- fetchChunksByIds(ids) {
1883
- if (ids.length === 0) return [];
1884
- const placeholders = ids.map(() => "?").join(",");
1885
- const rows = this.db.prepare(
1886
- `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,
1887
- chunks.start_line as start_line, chunks.end_line as end_line,
1888
- chunks.text as text
1889
- FROM chunks JOIN files ON chunks.file_id = files.id
1890
- WHERE chunks.id IN (${placeholders})`
1891
- ).all(...ids);
1892
- return rows.map((row) => {
1893
- const startLine = Number(row.start_line ?? 0);
1894
- const endLine = Number(row.end_line ?? 0);
1895
- const path = String(row.rel_path);
1896
- return {
1897
- chunkId: Number(row.id),
1898
- path,
1899
- startLine,
1900
- endLine,
1901
- score: 0,
1902
- textScore: 0,
1903
- snippet: truncateSnippet(String(row.text ?? "")),
1904
- source: String(row.source),
1905
- citation: `${path}:${startLine}-${endLine}`
1906
- };
1907
- });
1908
- }
1909
- // ───── persistence helpers ─────────────────────────────────────────
1910
- loadFilesIndex() {
1911
- const rows = this.db.prepare("SELECT id, path, hash FROM files").all();
1912
- return new Map(rows.map((row) => [row.path, { id: row.id, hash: row.hash }]));
1913
- }
1914
- upsertFile(absPath, relPath, hash, mtimeMs, source = "memory") {
1915
- const stmt = this.db.prepare(
1916
- `INSERT INTO files (path, rel_path, mtime, hash, source) VALUES (?, ?, ?, ?, ?)
1917
- ON CONFLICT(path) DO UPDATE SET hash = excluded.hash, mtime = excluded.mtime, source = excluded.source
1918
- RETURNING id`
1919
- );
1920
- const row = stmt.get(absPath, relPath, Math.floor(mtimeMs), hash, source);
1921
- return row.id;
1922
- }
1923
- deleteChunksForFile(fileId) {
1924
- this.db.prepare("DELETE FROM chunks WHERE file_id = ?").run(fileId);
1925
- }
1926
- insertChunk(fileId, startLine, endLine, text, hash) {
1927
- this.db.prepare(
1928
- "INSERT INTO chunks (file_id, start_line, end_line, text, hash) VALUES (?, ?, ?, ?, ?)"
1929
- ).run(fileId, startLine, endLine, text, hash);
1930
- }
1931
- close() {
1932
- this.db.close();
1933
- }
1934
- };
1935
- function resolveWeights(options) {
1936
- const vectorWeight = options.vectorWeight ?? 0.6;
1937
- const textWeight = options.textWeight ?? 0.4;
1938
- const total = vectorWeight + textWeight || 1;
1939
- return { vectorWeight, textWeight, total };
1940
- }
1941
- function blendScores(hit, vectorScore, weights) {
1942
- const score = (vectorScore * weights.vectorWeight + hit.textScore * weights.textWeight) / weights.total;
1943
- return {
1944
- path: hit.path,
1945
- startLine: hit.startLine,
1946
- endLine: hit.endLine,
1947
- score,
1948
- textScore: hit.textScore,
1949
- snippet: hit.snippet,
1950
- source: hit.source,
1951
- citation: hit.citation,
1952
- ...vectorScore > 0 ? { vectorScore } : {}
1953
- };
1954
- }
1955
- function sha256(text) {
1956
- return createHash("sha256").update(text).digest("hex");
1957
- }
1958
- function truncateSnippet(text) {
1959
- const max = 500;
1960
- return text.length <= max ? text : `${text.slice(0, max)}\u2026`;
1961
- }
1962
- function nfcEqual(a, b) {
1963
- return a.normalize("NFC") === b.normalize("NFC");
1964
- }
1965
- async function migrateSqliteToLance(opts) {
1966
- const cwd = opts.cwd;
1967
- const memoryRoot = resolveMemoryRoot(cwd, { directory: opts.directory });
1968
- const finalPath = lanceStoragePath(memoryRoot);
1969
- const newPath = join(memoryRoot, "lance-new");
1970
- const rawLog = opts.logger ?? ((m) => console.log(m));
1971
- const log = (m) => rawLog(redactSecrets(m));
1972
- if (existsSync(finalPath)) {
1973
- throw new ConfigurationError(
1974
- `Destination already exists: ${finalPath}. Remove it manually (\`rm -rf ${finalPath}\`) and re-run.`,
1975
- { code: "migration_destination_exists" }
1976
- );
1977
- }
1978
- if (existsSync(newPath)) {
1979
- log(`Removing stale ${newPath} from a previous run...`);
1980
- rmSync(newPath, { recursive: true, force: true });
1981
- }
1982
- log(`Reading SQLite facts from ${cwd}/.theokit/memory/index.sqlite ...`);
1983
- const sqliteFacts = await readAllSqliteFacts(memoryRoot);
1984
- log(`SQLite has ${sqliteFacts.length} facts.`);
1985
- if (sqliteFacts.length === 0) {
1986
- return {
1987
- countSqlite: 0,
1988
- countLance: 0,
1989
- validated: true,
1990
- sampleComparisons: [],
1991
- lancePath: finalPath,
1992
- committed: false
1993
- };
1994
- }
1995
- const placeholderEmbedding = {
1996
- id: "migration-placeholder",
1997
- model: "deterministic-hash",
1998
- dimension: 8,
1999
- embed: async (texts) => {
2000
- return texts.map((t) => {
2001
- const arr = new Array(8).fill(0);
2002
- for (let i = 0; i < t.length; i += 1) {
2003
- arr[i % 8] += t.charCodeAt(i);
2004
- }
2005
- return arr.map((x) => x / 1e3);
2006
- });
2007
- },
2008
- stats: () => ({ cacheHits: 0, cacheMisses: 0, httpCalls: 0, retries: 0 })
2009
- };
2010
- mkdirSync(newPath, { recursive: true });
2011
- log(`Writing Lance index to ${newPath} ...`);
2012
- const lance = await LanceIndex.open({
2013
- cwd,
2014
- embedding: placeholderEmbedding,
2015
- storagePath: newPath
2016
- });
2017
- const batchSize = opts.batchSize ?? 100;
2018
- for (let i = 0; i < sqliteFacts.length; i += batchSize) {
2019
- const batch = sqliteFacts.slice(i, i + batchSize).map((f) => ({
2020
- id: f.id,
2021
- text: f.text,
2022
- source: f.source,
2023
- namespace: f.namespace ?? "default",
2024
- scope: f.scope ?? "agent",
2025
- user_id: f.user_id ?? "default",
2026
- timestamp: 0
2027
- }));
2028
- await lance.addFacts(batch);
2029
- log(` Migrated ${Math.min(i + batchSize, sqliteFacts.length)}/${sqliteFacts.length}`);
2030
- }
2031
- const lanceCount = await lance.countFacts("default");
2032
- log(`Lance has ${lanceCount} facts (expected ${sqliteFacts.length}).`);
2033
- const sampleSize = Math.min(10, sqliteFacts.length);
2034
- const sampleComparisons = [];
2035
- for (let i = 0; i < sampleSize; i += 1) {
2036
- const sqliteFact = sqliteFacts[Math.floor(i * sqliteFacts.length / sampleSize)];
2037
- if (sqliteFact === void 0) continue;
2038
- const hits = await lance.search(sqliteFact.text, {
2039
- namespace: sqliteFact.namespace ?? "default",
2040
- limit: 1
2041
- });
2042
- const hit = hits[0];
2043
- const match = hit !== void 0 && nfcEqual(hit.text, sqliteFact.text);
2044
- sampleComparisons.push({ id: sqliteFact.id, match });
2045
- }
2046
- const allMatch = sampleComparisons.every((c) => c.match);
2047
- const countMatch = lanceCount === sqliteFacts.length;
2048
- const validated = allMatch && countMatch;
2049
- await lance.close();
2050
- if (opts.dryRun === true) {
2051
- log("Dry-run mode \u2014 discarding Lance staging dir.");
2052
- rmSync(newPath, { recursive: true, force: true });
2053
- return {
2054
- countSqlite: sqliteFacts.length,
2055
- countLance: lanceCount,
2056
- validated,
2057
- sampleComparisons,
2058
- lancePath: finalPath,
2059
- committed: false
2060
- };
2061
- }
2062
- if (!validated) {
2063
- log("Validation FAILED \u2014 leaving SQLite intact, removing Lance staging dir.");
2064
- rmSync(newPath, { recursive: true, force: true });
2065
- return {
2066
- countSqlite: sqliteFacts.length,
2067
- countLance: lanceCount,
2068
- validated: false,
2069
- sampleComparisons,
2070
- lancePath: finalPath,
2071
- committed: false
2072
- };
2073
- }
2074
- renameSync(newPath, finalPath);
2075
- log(`Migration committed to ${finalPath}.`);
2076
- return {
2077
- countSqlite: sqliteFacts.length,
2078
- countLance: lanceCount,
2079
- validated: true,
2080
- sampleComparisons,
2081
- lancePath: finalPath,
2082
- committed: true
2083
- };
2084
- }
2085
- async function fileExists(path) {
2086
- try {
2087
- await access(path);
2088
- return true;
2089
- } catch {
2090
- return false;
2091
- }
2092
- }
2093
- async function readLegacyFacts(jsonPath) {
2094
- try {
2095
- const raw = await readFile(jsonPath, "utf8");
2096
- const parsed = JSON.parse(raw);
2097
- return Array.isArray(parsed.facts) ? parsed.facts : [];
2098
- } catch {
2099
- return void 0;
2100
- }
2101
- }
2102
- async function writeMigratedFacts(cwd, jsonPath, facts) {
2103
- try {
2104
- for (const fact of facts) await appendFactToMarkdown(cwd, fact);
2105
- await unlink(jsonPath).catch(() => void 0);
2106
- process.stderr.write(
2107
- `[theokit-sdk] migrated ${facts.length} fact(s) from ${jsonPath} to MEMORY.md
2108
- `
2109
- );
2110
- return { migrated: true, factCount: facts.length };
2111
- } catch (cause) {
2112
- const message = cause instanceof Error ? cause.message : String(cause);
2113
- process.stderr.write(`[theokit-sdk] memory migration failed (readonly fs?): ${message}
2114
- `);
2115
- return { migrated: false, factCount: 0, reason: "readonly-fs" };
2116
- }
2117
- }
2118
- var migrationRun = /* @__PURE__ */ new Set();
2119
- async function migrateLegacyJson(cwd, config) {
2120
- const key = `${cwd}::${config.namespace ?? "default"}::${config.scope ?? "agent"}::${config.userId ?? "default"}`;
2121
- if (migrationRun.has(key)) return { migrated: false, factCount: 0, reason: "already-migrated" };
2122
- migrationRun.add(key);
2123
- const jsonPath = legacyMemoryJsonPath(cwd, config);
2124
- if (!await fileExists(jsonPath)) {
2125
- return { migrated: false, factCount: 0, reason: "no-legacy-json" };
2126
- }
2127
- if (await fileExists(memoryMdPath(resolveMemoryRoot(cwd)))) {
2128
- process.stderr.write(
2129
- `[theokit-sdk] memory migration skipped: both MEMORY.md and legacy JSON exist at ${jsonPath}; leaving both intact
2130
- `
2131
- );
2132
- return { migrated: false, factCount: 0, reason: "markdown-exists" };
2133
- }
2134
- const facts = await readLegacyFacts(jsonPath);
2135
- if (facts === void 0) return { migrated: false, factCount: 0, reason: "no-legacy-json" };
2136
- return writeMigratedFacts(cwd, jsonPath, facts);
2137
- }
2138
- function resetMigrationStateForTests() {
2139
- migrationRun.clear();
2140
- }
2141
- var DEFAULT_MEMORY_READ_LINES = 200;
2142
- async function readMemoryFileBounded(opts) {
2143
- const absolutePath = resolve(opts.cwd, opts.relPath);
2144
- const raw = await readFile(absolutePath, "utf8");
2145
- const allLines = raw.split("\n");
2146
- const trimmedLines = allLines.length > 0 && allLines[allLines.length - 1] === "" ? allLines.slice(0, -1) : allLines;
2147
- const totalLines = trimmedLines.length;
2148
- const requestedFrom = Math.max(1, opts.from ?? 1);
2149
- const requestedLines = Math.max(1, opts.lines ?? DEFAULT_MEMORY_READ_LINES);
2150
- const startIdx = requestedFrom - 1;
2151
- const endIdx = Math.min(totalLines, startIdx + requestedLines);
2152
- const slice = trimmedLines.slice(startIdx, endIdx);
2153
- const linesReturned = slice.length;
2154
- const remainingLines = Math.max(0, totalLines - endIdx);
2155
- const truncated = remainingLines > 0;
2156
- return {
2157
- path: opts.relPath,
2158
- from: requestedFrom,
2159
- linesReturned,
2160
- totalLines,
2161
- truncated,
2162
- remainingLines,
2163
- text: slice.join("\n")
2164
- };
2165
- }
2166
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.";
2167
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.";
2168
1103
  var MEMORY_SEARCH_SCHEMA = {
@@ -2279,6 +1214,6 @@ function isPathInside(root, candidate) {
2279
1214
  return candidate === root || candidate.startsWith(normalizedRoot);
2280
1215
  }
2281
1216
 
2282
- export { ActiveMemoryCache, CircuitBreaker, DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL, DEFAULT_COHERE_EMBEDDING_MODEL, DEFAULT_DEEPINFRA_EMBEDDING_MODEL, DEFAULT_GEMINI_EMBEDDING_MODEL, DEFAULT_JINA_EMBEDDING_MODEL, DEFAULT_MEMORY_READ_LINES, 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, META_KEY_DIMENSION, META_KEY_MODEL, META_KEY_PROVIDER_ID, PRAGMA_STATEMENTS, SCHEMA_STATEMENTS, VALID_BACKENDS, assertValidBackend, azureOpenAiMemoryEmbeddingProviderAdapter, buildErrorMetadata, chunkMarkdown, cohereMemoryEmbeddingProviderAdapter, createCategorizedMemory, createInMemoryMarkdownProvider, createMemoryGetTool, createMemorySearchTool, createVectorIndex, deepPhase, deepinfraMemoryEmbeddingProviderAdapter, dropVectorIndex, embedMissingChunks, geminiMemoryEmbeddingProviderAdapter, identityMatches, isLanceAvailable, isSqliteVecLoaded, jinaMemoryEmbeddingProviderAdapter, legacyMemoryJsonPath, lightPhase, listNotes, loadSqliteVecExtension, mapOpenAICompatibleError, migrateLegacyJson, migrateSqliteToLance, mistralMemoryEmbeddingProviderAdapter, ollamaMemoryEmbeddingProviderAdapter, openAiMemoryEmbeddingProviderAdapter, openLanceIndex, openMemoryDb, openRouterMemoryEmbeddingProviderAdapter, packVector, parseRetryAfter, parseSearchOptions, readEmbeddingIdentity, readMemoryFileBounded, redactSecrets, remPhase, resetMigrationStateForTests, runActiveMemory, runDreamingSweep, truncateRaw, upsertEmbedding, vectorSearch, voyageMemoryEmbeddingProviderAdapter, writeEmbeddingIdentity };
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 };
2283
1218
  //# sourceMappingURL=index.js.map
2284
1219
  //# sourceMappingURL=index.js.map