memory-crystal 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/.env.example +20 -0
  2. package/CHANGELOG.md +6 -0
  3. package/LETTERS.md +22 -0
  4. package/LICENSE +21 -0
  5. package/README-ENTERPRISE.md +162 -0
  6. package/README-old.md +275 -0
  7. package/README.md +91 -0
  8. package/RELAY.md +88 -0
  9. package/TECHNICAL.md +379 -0
  10. package/ai/dev-updates/2026-02-25--cc-air--phase2-architecture-pivot.md +70 -0
  11. package/ai/dev-updates/2026-02-25--cc-air--phase2-worker-build.md +72 -0
  12. package/ai/dev-updates/2026-02-26--10-25-16--cc-mini--phase2-implementation.md +49 -0
  13. package/ai/dev-updates/2026-02-27--20-30-00--cc-mini--readme-overhaul-and-public-deploy.md +69 -0
  14. package/ai/notes/2026-02-26--cc-air--notes.md +412 -0
  15. package/ai/notes/2026-02-27--cc-mini--grok-feedback.md +44 -0
  16. package/ai/notes/2026-02-27--cc-mini--lesa-feedback.md +45 -0
  17. package/ai/notes/RESEARCH.md +1185 -0
  18. package/ai/notes/salience-research/README.md +29 -0
  19. package/ai/notes/salience-research/eurosla-salience-review.md +64 -0
  20. package/ai/notes/salience-research/full-research-summary.md +269 -0
  21. package/ai/notes/salience-research/salience-levels-diagram.png +0 -0
  22. package/ai/plan/2026-02-27--cc-mini--qr-pairing-spec.md +203 -0
  23. package/ai/plan/_archive/PLAN.md +194 -0
  24. package/ai/plan/_archive/PRD.md +1014 -0
  25. package/ai/plan/cc-plans-duplicates-from-dot-claude/2026-02-26--cc-mini--phase2-implementation-plan.md +245 -0
  26. package/ai/plan/dev-conventions-note.md +70 -0
  27. package/ai/plan/ldm-os-install-and-boot-architecture.md +285 -0
  28. package/ai/plan/memory-crystal-phase2-plan.md +192 -0
  29. package/ai/plan/memory-system-lay-of-the-land.md +214 -0
  30. package/ai/plan/phase2-ephemeral-relay.md +238 -0
  31. package/ai/plan/readme-first.md +68 -0
  32. package/ai/plan/roadmap.md +159 -0
  33. package/ai/todos/PUNCHLIST.md +44 -0
  34. package/ai/todos/README.md +31 -0
  35. package/ai/todos/inboxes/cc-air/2026-02-26--cc-air--post-relay-todos.md +85 -0
  36. package/ai/todos/inboxes/cc-mini/2026-02-26--cc-mini--phase2-status.md +100 -0
  37. package/ai/todos/inboxes/cc-mini/_archive/TODO.md +25 -0
  38. package/ai/todos/inboxes/parker/2026-02-25--cc-air--setup-checklist.md +139 -0
  39. package/ai/todos/inboxes/parker/2026-02-26--cc-mini--phase2-your-moves.md +72 -0
  40. package/dist/cc-hook.d.ts +1 -0
  41. package/dist/cc-hook.js +349 -0
  42. package/dist/chunk-3VFIJYS4.js +818 -0
  43. package/dist/chunk-52QE3YI3.js +1169 -0
  44. package/dist/chunk-AA3OPP4Z.js +432 -0
  45. package/dist/chunk-D3I3ZSE2.js +411 -0
  46. package/dist/chunk-EKSACBTJ.js +1070 -0
  47. package/dist/chunk-F3Y7EL7K.js +83 -0
  48. package/dist/chunk-JWZXYVET.js +1068 -0
  49. package/dist/chunk-KYVWO6ZM.js +1069 -0
  50. package/dist/chunk-L3VHARQH.js +413 -0
  51. package/dist/chunk-LOVAHSQV.js +411 -0
  52. package/dist/chunk-LQOYCAGG.js +446 -0
  53. package/dist/chunk-MK42FMEG.js +147 -0
  54. package/dist/chunk-NIJCVN3O.js +147 -0
  55. package/dist/chunk-O2UITJGH.js +465 -0
  56. package/dist/chunk-PEK6JH65.js +432 -0
  57. package/dist/chunk-PJ6FFKEX.js +77 -0
  58. package/dist/chunk-PLUBBZYR.js +800 -0
  59. package/dist/chunk-SGL6ISBJ.js +1061 -0
  60. package/dist/chunk-UNHVZB5G.js +411 -0
  61. package/dist/chunk-VAFTWSTE.js +1061 -0
  62. package/dist/chunk-XZ3S56RQ.js +1061 -0
  63. package/dist/chunk-Y72C7F6O.js +148 -0
  64. package/dist/cli.d.ts +1 -0
  65. package/dist/cli.js +325 -0
  66. package/dist/core.d.ts +188 -0
  67. package/dist/core.js +12 -0
  68. package/dist/crypto.d.ts +16 -0
  69. package/dist/crypto.js +18 -0
  70. package/dist/dev-update-SZ2Z4WCQ.js +6 -0
  71. package/dist/ldm.d.ts +17 -0
  72. package/dist/ldm.js +12 -0
  73. package/dist/mcp-server.d.ts +1 -0
  74. package/dist/mcp-server.js +250 -0
  75. package/dist/migrate.d.ts +1 -0
  76. package/dist/migrate.js +89 -0
  77. package/dist/mirror-sync.d.ts +1 -0
  78. package/dist/mirror-sync.js +130 -0
  79. package/dist/openclaw.d.ts +5 -0
  80. package/dist/openclaw.js +349 -0
  81. package/dist/poller.d.ts +1 -0
  82. package/dist/poller.js +272 -0
  83. package/dist/summarize.d.ts +19 -0
  84. package/dist/summarize.js +10 -0
  85. package/dist/worker.js +137 -0
  86. package/openclaw.plugin.json +11 -0
  87. package/package.json +40 -0
  88. package/scripts/migrate-lance-to-sqlite.mjs +217 -0
  89. package/skills/memory/SKILL.md +61 -0
  90. package/src/cc-hook.ts +447 -0
  91. package/src/cli.ts +356 -0
  92. package/src/core.ts +1472 -0
  93. package/src/crypto.ts +113 -0
  94. package/src/dev-update.ts +178 -0
  95. package/src/ldm.ts +117 -0
  96. package/src/mcp-server.ts +274 -0
  97. package/src/migrate.ts +104 -0
  98. package/src/mirror-sync.ts +175 -0
  99. package/src/openclaw.ts +250 -0
  100. package/src/poller.ts +345 -0
  101. package/src/summarize.ts +210 -0
  102. package/src/worker.ts +208 -0
  103. package/tsconfig.json +18 -0
  104. package/wrangler.toml +20 -0
@@ -0,0 +1,1061 @@
1
+ // src/core.ts
2
+ import * as lancedb from "@lancedb/lancedb";
3
+ import Database from "better-sqlite3";
4
+ import * as sqliteVec from "sqlite-vec";
5
+ import { readFileSync, existsSync, mkdirSync, readdirSync, statSync } from "fs";
6
+ import { execSync } from "child_process";
7
+ import { join, relative, extname, basename } from "path";
8
+ import { createHash } from "crypto";
9
+ import http from "http";
10
+ import https from "https";
11
+ async function embedOpenAI(texts, apiKey, model) {
12
+ return new Promise((resolve, reject) => {
13
+ const body = JSON.stringify({ input: texts, model });
14
+ const req = https.request({
15
+ hostname: "api.openai.com",
16
+ path: "/v1/embeddings",
17
+ method: "POST",
18
+ headers: {
19
+ "Content-Type": "application/json",
20
+ "Authorization": `Bearer ${apiKey}`,
21
+ "Content-Length": Buffer.byteLength(body)
22
+ },
23
+ timeout: 3e4
24
+ }, (res) => {
25
+ let data = "";
26
+ res.on("data", (chunk) => data += chunk);
27
+ res.on("end", () => {
28
+ if (res.statusCode !== 200) {
29
+ reject(new Error(`OpenAI API error ${res.statusCode}: ${data.slice(0, 200)}`));
30
+ return;
31
+ }
32
+ const parsed = JSON.parse(data);
33
+ resolve(parsed.data.map((d) => d.embedding));
34
+ });
35
+ });
36
+ req.on("error", reject);
37
+ req.on("timeout", () => {
38
+ req.destroy();
39
+ reject(new Error("OpenAI timeout"));
40
+ });
41
+ req.write(body);
42
+ req.end();
43
+ });
44
+ }
45
+ async function embedOllama(texts, host, model) {
46
+ const results = [];
47
+ for (const text of texts) {
48
+ const result = await new Promise((resolve, reject) => {
49
+ const url = new URL("/api/embeddings", host);
50
+ const body = JSON.stringify({ model, prompt: text });
51
+ const req = http.request({
52
+ hostname: url.hostname,
53
+ port: url.port,
54
+ path: url.pathname,
55
+ method: "POST",
56
+ headers: {
57
+ "Content-Type": "application/json",
58
+ "Content-Length": Buffer.byteLength(body)
59
+ },
60
+ timeout: 15e3
61
+ }, (res) => {
62
+ let data = "";
63
+ res.on("data", (chunk) => data += chunk);
64
+ res.on("end", () => {
65
+ if (res.statusCode !== 200) {
66
+ reject(new Error(`Ollama error ${res.statusCode}: ${data.slice(0, 200)}`));
67
+ return;
68
+ }
69
+ resolve(JSON.parse(data).embedding);
70
+ });
71
+ });
72
+ req.on("error", reject);
73
+ req.on("timeout", () => {
74
+ req.destroy();
75
+ reject(new Error("Ollama timeout"));
76
+ });
77
+ req.write(body);
78
+ req.end();
79
+ });
80
+ results.push(result);
81
+ }
82
+ return results;
83
+ }
84
+ async function embedGoogle(texts, apiKey, model) {
85
+ return new Promise((resolve, reject) => {
86
+ const body = JSON.stringify({
87
+ requests: texts.map((text) => ({ model: `models/${model}`, content: { parts: [{ text }] } }))
88
+ });
89
+ const req = https.request({
90
+ hostname: "generativelanguage.googleapis.com",
91
+ path: `/v1beta/models/${model}:batchEmbedContents?key=${apiKey}`,
92
+ method: "POST",
93
+ headers: {
94
+ "Content-Type": "application/json",
95
+ "Content-Length": Buffer.byteLength(body)
96
+ },
97
+ timeout: 3e4
98
+ }, (res) => {
99
+ let data = "";
100
+ res.on("data", (chunk) => data += chunk);
101
+ res.on("end", () => {
102
+ if (res.statusCode !== 200) {
103
+ reject(new Error(`Google API error ${res.statusCode}: ${data.slice(0, 200)}`));
104
+ return;
105
+ }
106
+ const parsed = JSON.parse(data);
107
+ resolve(parsed.embeddings.map((e) => e.values));
108
+ });
109
+ });
110
+ req.on("error", reject);
111
+ req.on("timeout", () => {
112
+ req.destroy();
113
+ reject(new Error("Google timeout"));
114
+ });
115
+ req.write(body);
116
+ req.end();
117
+ });
118
+ }
119
+ var Crystal = class _Crystal {
120
+ config;
121
+ lanceDb = null;
122
+ sqliteDb = null;
123
+ chunksTable = null;
124
+ vecDimensions = null;
125
+ constructor(config) {
126
+ this.config = config;
127
+ if (!existsSync(config.dataDir)) {
128
+ mkdirSync(config.dataDir, { recursive: true });
129
+ }
130
+ }
131
+ // ── Initialization ──
132
+ async init() {
133
+ const lanceDir = join(this.config.dataDir, "lance");
134
+ const sqlitePath = join(this.config.dataDir, "crystal.db");
135
+ if (!existsSync(lanceDir)) mkdirSync(lanceDir, { recursive: true });
136
+ this.lanceDb = await lancedb.connect(lanceDir);
137
+ this.sqliteDb = new Database(sqlitePath);
138
+ this.sqliteDb.pragma("journal_mode = WAL");
139
+ sqliteVec.load(this.sqliteDb);
140
+ this.initSqliteTables();
141
+ this.initChunksTables();
142
+ await this.initLanceTables();
143
+ }
144
+ initSqliteTables() {
145
+ const db = this.sqliteDb;
146
+ db.exec(`
147
+ CREATE TABLE IF NOT EXISTS sources (
148
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
149
+ type TEXT NOT NULL,
150
+ uri TEXT NOT NULL,
151
+ title TEXT,
152
+ agent_id TEXT NOT NULL,
153
+ metadata TEXT DEFAULT '{}',
154
+ ingested_at TEXT NOT NULL,
155
+ chunk_count INTEGER DEFAULT 0
156
+ );
157
+
158
+ CREATE TABLE IF NOT EXISTS capture_state (
159
+ agent_id TEXT NOT NULL,
160
+ source_id TEXT NOT NULL,
161
+ last_message_count INTEGER DEFAULT 0,
162
+ capture_count INTEGER DEFAULT 0,
163
+ last_capture_at TEXT,
164
+ PRIMARY KEY (agent_id, source_id)
165
+ );
166
+
167
+ CREATE TABLE IF NOT EXISTS memories (
168
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
169
+ text TEXT NOT NULL,
170
+ category TEXT NOT NULL DEFAULT 'fact',
171
+ confidence REAL NOT NULL DEFAULT 1.0,
172
+ source_ids TEXT DEFAULT '[]',
173
+ status TEXT NOT NULL DEFAULT 'active',
174
+ created_at TEXT NOT NULL,
175
+ updated_at TEXT NOT NULL
176
+ );
177
+
178
+ CREATE TABLE IF NOT EXISTS entities (
179
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
180
+ name TEXT NOT NULL UNIQUE,
181
+ type TEXT NOT NULL DEFAULT 'concept',
182
+ description TEXT,
183
+ properties TEXT DEFAULT '{}',
184
+ created_at TEXT NOT NULL,
185
+ updated_at TEXT NOT NULL
186
+ );
187
+
188
+ CREATE TABLE IF NOT EXISTS relationships (
189
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
190
+ source_id INTEGER NOT NULL REFERENCES entities(id),
191
+ target_id INTEGER NOT NULL REFERENCES entities(id),
192
+ type TEXT NOT NULL,
193
+ description TEXT,
194
+ weight REAL DEFAULT 1.0,
195
+ valid_from TEXT NOT NULL,
196
+ valid_until TEXT,
197
+ created_at TEXT NOT NULL
198
+ );
199
+
200
+ CREATE INDEX IF NOT EXISTS idx_sources_agent ON sources(agent_id);
201
+ CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status);
202
+ CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
203
+ CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_id);
204
+ CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_id);
205
+
206
+ -- Source file indexing (optional feature)
207
+ CREATE TABLE IF NOT EXISTS source_collections (
208
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
209
+ name TEXT NOT NULL UNIQUE,
210
+ root_path TEXT NOT NULL,
211
+ glob_patterns TEXT NOT NULL DEFAULT '["**/*"]',
212
+ ignore_patterns TEXT NOT NULL DEFAULT '[]',
213
+ file_count INTEGER DEFAULT 0,
214
+ chunk_count INTEGER DEFAULT 0,
215
+ last_sync_at TEXT,
216
+ created_at TEXT NOT NULL
217
+ );
218
+
219
+ CREATE TABLE IF NOT EXISTS source_files (
220
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
221
+ collection_id INTEGER NOT NULL REFERENCES source_collections(id) ON DELETE CASCADE,
222
+ file_path TEXT NOT NULL,
223
+ file_hash TEXT NOT NULL,
224
+ file_size INTEGER NOT NULL,
225
+ chunk_count INTEGER DEFAULT 0,
226
+ last_indexed_at TEXT NOT NULL
227
+ );
228
+
229
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_source_files_path ON source_files(collection_id, file_path);
230
+ CREATE INDEX IF NOT EXISTS idx_source_files_collection ON source_files(collection_id);
231
+ `);
232
+ }
233
+ initChunksTables() {
234
+ const db = this.sqliteDb;
235
+ db.exec(`
236
+ CREATE TABLE IF NOT EXISTS chunks (
237
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
238
+ text TEXT NOT NULL,
239
+ text_hash TEXT NOT NULL,
240
+ role TEXT,
241
+ source_type TEXT,
242
+ source_id TEXT,
243
+ agent_id TEXT,
244
+ token_count INTEGER,
245
+ created_at TEXT NOT NULL
246
+ );
247
+
248
+ CREATE INDEX IF NOT EXISTS idx_chunks_agent ON chunks(agent_id);
249
+ CREATE INDEX IF NOT EXISTS idx_chunks_source ON chunks(source_type);
250
+ CREATE INDEX IF NOT EXISTS idx_chunks_hash ON chunks(text_hash);
251
+ CREATE INDEX IF NOT EXISTS idx_chunks_created ON chunks(created_at);
252
+
253
+ -- FTS5 full-text search table
254
+ CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
255
+ text,
256
+ tokenize='porter unicode61'
257
+ );
258
+
259
+ -- Sync trigger: populate FTS on chunk insert
260
+ CREATE TRIGGER IF NOT EXISTS chunks_fts_insert AFTER INSERT ON chunks
261
+ BEGIN
262
+ INSERT INTO chunks_fts(rowid, text) VALUES (NEW.id, NEW.text);
263
+ END;
264
+ `);
265
+ const vecTable = db.prepare(
266
+ `SELECT name FROM sqlite_master WHERE type='table' AND name='chunks_vec'`
267
+ ).get();
268
+ if (vecTable) {
269
+ try {
270
+ const row = db.prepare("SELECT embedding FROM chunks_vec LIMIT 1").get();
271
+ if (row?.embedding) {
272
+ this.vecDimensions = row.embedding.length / 4;
273
+ }
274
+ } catch {
275
+ }
276
+ }
277
+ }
278
+ ensureVecTable(dimensions) {
279
+ const db = this.sqliteDb;
280
+ const existing = db.prepare(
281
+ `SELECT name FROM sqlite_master WHERE type='table' AND name='chunks_vec'`
282
+ ).get();
283
+ if (!existing) {
284
+ db.exec(`
285
+ CREATE VIRTUAL TABLE chunks_vec USING vec0(
286
+ chunk_id INTEGER PRIMARY KEY,
287
+ embedding float[${dimensions}] distance_metric=cosine
288
+ );
289
+ `);
290
+ }
291
+ this.vecDimensions = dimensions;
292
+ }
293
+ async initLanceTables() {
294
+ const db = this.lanceDb;
295
+ const tableNames = await db.tableNames();
296
+ if (tableNames.includes("chunks")) {
297
+ this.chunksTable = await db.openTable("chunks");
298
+ }
299
+ }
300
+ // ── Embedding ──
301
+ async embed(texts) {
302
+ if (texts.length === 0) return [];
303
+ const cfg = this.config;
304
+ switch (cfg.embeddingProvider) {
305
+ case "openai": {
306
+ if (!cfg.openaiApiKey) throw new Error("OpenAI API key required");
307
+ const model = cfg.openaiModel || "text-embedding-3-small";
308
+ const maxCharsPerBatch = 8e5;
309
+ const results = [];
310
+ let batch = [];
311
+ let batchChars = 0;
312
+ for (const text of texts) {
313
+ if (batchChars + text.length > maxCharsPerBatch && batch.length > 0) {
314
+ results.push(...await embedOpenAI(batch, cfg.openaiApiKey, model));
315
+ batch = [];
316
+ batchChars = 0;
317
+ }
318
+ batch.push(text);
319
+ batchChars += text.length;
320
+ }
321
+ if (batch.length > 0) {
322
+ results.push(...await embedOpenAI(batch, cfg.openaiApiKey, model));
323
+ }
324
+ return results;
325
+ }
326
+ case "ollama":
327
+ return embedOllama(texts, cfg.ollamaHost || "http://localhost:11434", cfg.ollamaModel || "nomic-embed-text");
328
+ case "google":
329
+ if (!cfg.googleApiKey) throw new Error("Google API key required");
330
+ return embedGoogle(texts, cfg.googleApiKey, cfg.googleModel || "text-embedding-004");
331
+ default:
332
+ throw new Error(`Unknown embedding provider: ${cfg.embeddingProvider}`);
333
+ }
334
+ }
335
+ // ── Chunking ──
336
+ chunkText(text, targetTokens = 400, overlapTokens = 80) {
337
+ const targetChars = targetTokens * 4;
338
+ const overlapChars = overlapTokens * 4;
339
+ const chunks = [];
340
+ let start = 0;
341
+ while (start < text.length) {
342
+ let end = Math.min(start + targetChars, text.length);
343
+ if (end < text.length) {
344
+ const minBreak = start + Math.floor(targetChars * 0.5);
345
+ const paraBreak = text.lastIndexOf("\n\n", end);
346
+ if (paraBreak > minBreak) {
347
+ end = paraBreak;
348
+ } else {
349
+ const sentBreak = text.lastIndexOf(". ", end);
350
+ if (sentBreak > minBreak) {
351
+ end = sentBreak + 1;
352
+ }
353
+ }
354
+ }
355
+ const chunk = text.slice(start, end).trim();
356
+ if (chunk.length > 0) chunks.push(chunk);
357
+ if (end >= text.length) break;
358
+ start = end - overlapChars;
359
+ if (start <= (chunks.length > 0 ? end - targetChars : 0)) {
360
+ start = end;
361
+ }
362
+ }
363
+ return chunks;
364
+ }
365
+ // ── Ingest ──
366
+ async ingest(chunks) {
367
+ if (chunks.length === 0) return 0;
368
+ const db = this.sqliteDb;
369
+ const newChunks = chunks.filter((c) => {
370
+ const hash = createHash("sha256").update(c.text).digest("hex");
371
+ return !db.prepare("SELECT 1 FROM chunks WHERE text_hash = ?").get(hash);
372
+ });
373
+ if (newChunks.length === 0) return 0;
374
+ const texts = newChunks.map((c) => c.text);
375
+ const embeddings = await this.embed(texts);
376
+ if (!this.vecDimensions && embeddings.length > 0) {
377
+ this.ensureVecTable(embeddings[0].length);
378
+ }
379
+ const insertChunk = db.prepare(`
380
+ INSERT INTO chunks (text, text_hash, role, source_type, source_id, agent_id, token_count, created_at)
381
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
382
+ `);
383
+ const insertVec = db.prepare(`
384
+ INSERT INTO chunks_vec (chunk_id, embedding) VALUES (?, ?)
385
+ `);
386
+ const transaction = db.transaction(() => {
387
+ for (let i = 0; i < newChunks.length; i++) {
388
+ const c = newChunks[i];
389
+ const hash = createHash("sha256").update(c.text).digest("hex");
390
+ const result = insertChunk.run(
391
+ c.text,
392
+ hash,
393
+ c.role,
394
+ c.source_type,
395
+ c.source_id,
396
+ c.agent_id,
397
+ c.token_count,
398
+ c.created_at || (/* @__PURE__ */ new Date()).toISOString()
399
+ );
400
+ const chunkId = typeof result.lastInsertRowid === "bigint" ? result.lastInsertRowid : BigInt(result.lastInsertRowid);
401
+ insertVec.run(chunkId, new Float32Array(embeddings[i]));
402
+ }
403
+ });
404
+ transaction();
405
+ const records = newChunks.map((chunk, i) => ({
406
+ text: chunk.text,
407
+ vector: embeddings[i],
408
+ role: chunk.role,
409
+ source_type: chunk.source_type,
410
+ source_id: chunk.source_id,
411
+ agent_id: chunk.agent_id,
412
+ token_count: chunk.token_count,
413
+ created_at: chunk.created_at || (/* @__PURE__ */ new Date()).toISOString()
414
+ }));
415
+ try {
416
+ if (!this.chunksTable) {
417
+ this.chunksTable = await this.lanceDb.createTable("chunks", records);
418
+ } else {
419
+ await this.chunksTable.add(records);
420
+ }
421
+ } catch (err) {
422
+ console.warn("LanceDB dual-write failed (non-fatal):", err.message);
423
+ }
424
+ return newChunks.length;
425
+ }
426
+ // ── Recency helpers ──
427
+ recencyWeight(ageDays) {
428
+ return Math.max(0.5, 1 - ageDays * 0.01);
429
+ }
430
+ freshnessLabel(ageDays) {
431
+ if (ageDays < 3) return "fresh";
432
+ if (ageDays < 7) return "recent";
433
+ if (ageDays < 14) return "aging";
434
+ return "stale";
435
+ }
436
+ // ── Search (Hybrid: BM25 + Vector + RRF fusion + Recency) ──
437
+ async search(query, limit = 5, filter) {
438
+ const db = this.sqliteDb;
439
+ const chunkCount = db.prepare("SELECT COUNT(*) as count FROM chunks").get()?.count || 0;
440
+ if (chunkCount === 0) {
441
+ return this.searchLanceFallback(query, limit, filter);
442
+ }
443
+ const [embedding] = await this.embed([query]);
444
+ const fetchLimit = Math.max(limit * 3, 30);
445
+ const vecResults = this.searchVec(embedding, fetchLimit, filter);
446
+ const ftsResults = this.searchFTS(query, fetchLimit, filter);
447
+ const fused = this.reciprocalRankFusion([ftsResults, vecResults], [1, 1]);
448
+ const now = Date.now();
449
+ const scored = fused.map((r) => {
450
+ const ageDays = r.created_at ? (now - new Date(r.created_at).getTime()) / 864e5 : 0;
451
+ const recency = r.created_at ? this.recencyWeight(ageDays) : 1;
452
+ return {
453
+ ...r,
454
+ score: r.score * recency,
455
+ freshness: r.created_at ? this.freshnessLabel(ageDays) : void 0
456
+ };
457
+ });
458
+ return scored.sort((a, b) => b.score - a.score).slice(0, limit);
459
+ }
460
+ /** Vector search via sqlite-vec. Two-step pattern: MATCH first, then JOIN. */
461
+ searchVec(embedding, limit, filter) {
462
+ const db = this.sqliteDb;
463
+ if (!this.vecDimensions) return [];
464
+ const vecRows = db.prepare(`
465
+ SELECT chunk_id, distance
466
+ FROM chunks_vec
467
+ WHERE embedding MATCH ? AND k = ?
468
+ `).all(new Float32Array(embedding), limit);
469
+ if (vecRows.length === 0) return [];
470
+ const ids = vecRows.map((r) => r.chunk_id);
471
+ const distMap = new Map(vecRows.map((r) => [r.chunk_id, r.distance]));
472
+ const placeholders = ids.map(() => "?").join(",");
473
+ let sql = `SELECT id, text, role, source_type, source_id, agent_id, created_at FROM chunks WHERE id IN (${placeholders})`;
474
+ const params = [...ids];
475
+ if (filter?.agent_id) {
476
+ sql += " AND agent_id = ?";
477
+ params.push(filter.agent_id);
478
+ }
479
+ if (filter?.source_type) {
480
+ sql += " AND source_type = ?";
481
+ params.push(filter.source_type);
482
+ }
483
+ const rows = db.prepare(sql).all(...params);
484
+ return rows.map((row) => ({
485
+ text: row.text,
486
+ role: row.role,
487
+ score: 1 - (distMap.get(row.id) || 1),
488
+ // cosine similarity from distance
489
+ source_type: row.source_type,
490
+ source_id: row.source_id,
491
+ agent_id: row.agent_id,
492
+ created_at: row.created_at
493
+ }));
494
+ }
495
+ /** Full-text search via FTS5 with BM25 scoring. */
496
+ searchFTS(query, limit, filter) {
497
+ const db = this.sqliteDb;
498
+ const ftsQuery = this.buildFTS5Query(query);
499
+ if (!ftsQuery) return [];
500
+ let sql = `
501
+ SELECT c.id, c.text, c.role, c.source_type, c.source_id, c.agent_id, c.created_at,
502
+ bm25(chunks_fts) as bm25_score
503
+ FROM chunks_fts f
504
+ JOIN chunks c ON c.id = f.rowid
505
+ WHERE chunks_fts MATCH ?
506
+ `;
507
+ const params = [ftsQuery];
508
+ if (filter?.agent_id) {
509
+ sql += " AND c.agent_id = ?";
510
+ params.push(filter.agent_id);
511
+ }
512
+ if (filter?.source_type) {
513
+ sql += " AND c.source_type = ?";
514
+ params.push(filter.source_type);
515
+ }
516
+ sql += " ORDER BY bm25_score LIMIT ?";
517
+ params.push(limit);
518
+ const rows = db.prepare(sql).all(...params);
519
+ return rows.map((row) => ({
520
+ text: row.text,
521
+ role: row.role,
522
+ // BM25 scores are negative (lower = better). Normalize to [0..1).
523
+ // |x| / (1 + |x|) maps: strong(-10)->0.91, medium(-2)->0.67, weak(-0.5)->0.33
524
+ score: Math.abs(row.bm25_score) / (1 + Math.abs(row.bm25_score)),
525
+ source_type: row.source_type,
526
+ source_id: row.source_id,
527
+ agent_id: row.agent_id,
528
+ created_at: row.created_at
529
+ }));
530
+ }
531
+ /** Build a safe FTS5 query from user input. */
532
+ buildFTS5Query(query) {
533
+ const terms = query.split(/\s+/).map((t) => t.replace(/[^\p{L}\p{N}']/gu, "").toLowerCase()).filter((t) => t.length > 0);
534
+ if (terms.length === 0) return null;
535
+ if (terms.length === 1) return `"${terms[0]}"*`;
536
+ return terms.map((t) => `"${t}"*`).join(" AND ");
537
+ }
538
+ /**
539
+ * Reciprocal Rank Fusion. Ported from QMD (MIT License, Tobi Lutke, 2024-2026).
540
+ * Fuses multiple ranked result lists into one using RRF scoring.
541
+ * Uses text content as dedup key (instead of QMD's file path).
542
+ */
543
+ reciprocalRankFusion(resultLists, weights = [], k = 60) {
544
+ const scores = /* @__PURE__ */ new Map();
545
+ for (let listIdx = 0; listIdx < resultLists.length; listIdx++) {
546
+ const list = resultLists[listIdx];
547
+ if (!list) continue;
548
+ const weight = weights[listIdx] ?? 1;
549
+ for (let rank = 0; rank < list.length; rank++) {
550
+ const result = list[rank];
551
+ if (!result) continue;
552
+ const rrfContribution = weight / (k + rank + 1);
553
+ const dedup = result.text.slice(0, 200);
554
+ const existing = scores.get(dedup);
555
+ if (existing) {
556
+ existing.rrfScore += rrfContribution;
557
+ existing.topRank = Math.min(existing.topRank, rank);
558
+ } else {
559
+ scores.set(dedup, {
560
+ result,
561
+ rrfScore: rrfContribution,
562
+ topRank: rank
563
+ });
564
+ }
565
+ }
566
+ }
567
+ for (const entry of scores.values()) {
568
+ if (entry.topRank === 0) {
569
+ entry.rrfScore += 0.05;
570
+ } else if (entry.topRank <= 2) {
571
+ entry.rrfScore += 0.02;
572
+ }
573
+ }
574
+ return Array.from(scores.values()).sort((a, b) => b.rrfScore - a.rrfScore).map((e) => ({ ...e.result, score: e.rrfScore }));
575
+ }
576
+ /** LanceDB fallback for search (used when sqlite-vec tables are empty, pre-migration). */
577
+ async searchLanceFallback(query, limit, filter) {
578
+ if (!this.chunksTable) return [];
579
+ const [embedding] = await this.embed([query]);
580
+ const fetchLimit = Math.max(limit * 3, 30);
581
+ let queryBuilder = this.chunksTable.vectorSearch(embedding).distanceType("cosine").limit(fetchLimit);
582
+ if (filter?.agent_id) {
583
+ queryBuilder = queryBuilder.where(`agent_id = '${filter.agent_id}'`);
584
+ }
585
+ if (filter?.source_type) {
586
+ queryBuilder = queryBuilder.where(`source_type = '${filter.source_type}'`);
587
+ }
588
+ const results = await queryBuilder.toArray();
589
+ const now = Date.now();
590
+ return results.map((row) => {
591
+ const cosine = row._distance != null ? 1 - row._distance : 0;
592
+ const createdAt = row.created_at || "";
593
+ const ageDays = createdAt ? (now - new Date(createdAt).getTime()) / 864e5 : 0;
594
+ const weight = createdAt ? this.recencyWeight(ageDays) : 1;
595
+ return {
596
+ text: row.text,
597
+ role: row.role,
598
+ score: cosine * weight,
599
+ source_type: row.source_type,
600
+ source_id: row.source_id,
601
+ agent_id: row.agent_id,
602
+ created_at: createdAt,
603
+ freshness: createdAt ? this.freshnessLabel(ageDays) : void 0
604
+ };
605
+ }).sort((a, b) => b.score - a.score).slice(0, limit);
606
+ }
607
+ // ── Remember (explicit fact storage) ──
608
+ async remember(text, category = "fact") {
609
+ const db = this.sqliteDb;
610
+ const now = (/* @__PURE__ */ new Date()).toISOString();
611
+ const stmt = db.prepare(`
612
+ INSERT INTO memories (text, category, confidence, source_ids, status, created_at, updated_at)
613
+ VALUES (?, ?, 1.0, '[]', 'active', ?, ?)
614
+ `);
615
+ const result = stmt.run(text, category, now, now);
616
+ await this.ingest([{
617
+ text,
618
+ role: "system",
619
+ source_type: "manual",
620
+ source_id: `memory:${result.lastInsertRowid}`,
621
+ agent_id: "system",
622
+ token_count: Math.ceil(text.length / 4),
623
+ created_at: now
624
+ }]);
625
+ return result.lastInsertRowid;
626
+ }
627
+ // ── Forget (deprecate a memory) ──
628
+ forget(memoryId) {
629
+ const db = this.sqliteDb;
630
+ const now = (/* @__PURE__ */ new Date()).toISOString();
631
+ const result = db.prepare(`
632
+ UPDATE memories SET status = 'deprecated', updated_at = ? WHERE id = ? AND status = 'active'
633
+ `).run(now, memoryId);
634
+ return result.changes > 0;
635
+ }
636
+ // ── Status ──
637
+ async status() {
638
+ const db = this.sqliteDb;
639
+ const sqliteChunks = db.prepare("SELECT COUNT(*) as count FROM chunks").get()?.count || 0;
640
+ let chunks = sqliteChunks;
641
+ if (chunks === 0 && this.chunksTable) {
642
+ try {
643
+ chunks = await this.chunksTable.countRows();
644
+ } catch {
645
+ }
646
+ }
647
+ const oldest = db.prepare("SELECT MIN(created_at) as ts FROM chunks").get()?.ts || null;
648
+ const newest = db.prepare("SELECT MAX(created_at) as ts FROM chunks").get()?.ts || null;
649
+ const memories = db.prepare("SELECT COUNT(*) as count FROM memories WHERE status = ?").get("active")?.count || 0;
650
+ const sources = db.prepare("SELECT COUNT(*) as count FROM sources").get()?.count || 0;
651
+ const chunkAgentRows = db.prepare("SELECT DISTINCT agent_id FROM chunks WHERE agent_id IS NOT NULL").all();
652
+ const sourceAgentRows = db.prepare("SELECT DISTINCT agent_id FROM sources").all();
653
+ const captureAgentRows = db.prepare("SELECT DISTINCT agent_id FROM capture_state").all();
654
+ const agents = [.../* @__PURE__ */ new Set([
655
+ ...chunkAgentRows.map((r) => r.agent_id),
656
+ ...sourceAgentRows.map((r) => r.agent_id),
657
+ ...captureAgentRows.map((r) => r.agent_id)
658
+ ])];
659
+ const captureInfo = db.prepare(
660
+ "SELECT COUNT(*) as count, MAX(last_capture_at) as latest FROM capture_state"
661
+ ).get();
662
+ return {
663
+ chunks,
664
+ memories,
665
+ sources,
666
+ agents,
667
+ oldestChunk: oldest,
668
+ newestChunk: newest,
669
+ embeddingProvider: this.config.embeddingProvider,
670
+ dataDir: this.config.dataDir,
671
+ capturedSessions: captureInfo?.count || 0,
672
+ latestCapture: captureInfo?.latest || null
673
+ };
674
+ }
675
+ // ── Capture State (for incremental ingestion) ──
676
+ getCaptureState(agentId, sourceId) {
677
+ const db = this.sqliteDb;
678
+ const row = db.prepare("SELECT last_message_count, capture_count FROM capture_state WHERE agent_id = ? AND source_id = ?").get(agentId, sourceId);
679
+ if (!row) return { lastMessageCount: 0, captureCount: 0 };
680
+ return {
681
+ lastMessageCount: row.last_message_count,
682
+ captureCount: row.capture_count
683
+ };
684
+ }
685
+ setCaptureState(agentId, sourceId, messageCount, captureCount) {
686
+ const db = this.sqliteDb;
687
+ db.prepare(`
688
+ INSERT OR REPLACE INTO capture_state (agent_id, source_id, last_message_count, capture_count, last_capture_at)
689
+ VALUES (?, ?, ?, ?, ?)
690
+ `).run(agentId, sourceId, messageCount, captureCount, (/* @__PURE__ */ new Date()).toISOString());
691
+ }
692
+ // ── Source File Indexing (optional feature) ──
693
+ //
694
+ // Add directories as "collections", sync to index/re-index changed files.
695
+ // All source chunks get source_type='file' so they're searchable alongside
696
+ // conversations and memories. Nothing here is required... you can use MC
697
+ // without ever touching sources.
698
+ // Default patterns for files worth indexing
699
+ static DEFAULT_INCLUDE = [
700
+ "**/*.ts",
701
+ "**/*.js",
702
+ "**/*.tsx",
703
+ "**/*.jsx",
704
+ "**/*.py",
705
+ "**/*.rs",
706
+ "**/*.go",
707
+ "**/*.java",
708
+ "**/*.md",
709
+ "**/*.txt",
710
+ "**/*.json",
711
+ "**/*.yaml",
712
+ "**/*.yml",
713
+ "**/*.toml",
714
+ "**/*.sh",
715
+ "**/*.bash",
716
+ "**/*.zsh",
717
+ "**/*.css",
718
+ "**/*.html",
719
+ "**/*.svg",
720
+ "**/*.sql",
721
+ "**/*.graphql",
722
+ "**/*.c",
723
+ "**/*.cpp",
724
+ "**/*.h",
725
+ "**/*.hpp",
726
+ "**/*.swift",
727
+ "**/*.kt",
728
+ "**/*.rb",
729
+ "**/*.env.example",
730
+ "**/*.gitignore",
731
+ "**/Makefile",
732
+ "**/Dockerfile",
733
+ "**/Cargo.toml",
734
+ "**/package.json",
735
+ "**/tsconfig.json"
736
+ ];
737
+ static DEFAULT_IGNORE = [
738
+ "**/node_modules/**",
739
+ "**/.git/**",
740
+ "**/dist/**",
741
+ "**/build/**",
742
+ "**/.next/**",
743
+ "**/.cache/**",
744
+ "**/coverage/**",
745
+ "**/__pycache__/**",
746
+ "**/target/**",
747
+ "**/vendor/**",
748
+ "**/.venv/**",
749
+ "**/*.lock",
750
+ "**/package-lock.json",
751
+ "**/yarn.lock",
752
+ "**/bun.lockb",
753
+ "**/*.min.js",
754
+ "**/*.min.css",
755
+ "**/*.map",
756
+ "**/*.png",
757
+ "**/*.jpg",
758
+ "**/*.jpeg",
759
+ "**/*.gif",
760
+ "**/*.ico",
761
+ "**/*.webp",
762
+ "**/*.woff",
763
+ "**/*.woff2",
764
+ "**/*.ttf",
765
+ "**/*.eot",
766
+ "**/*.mp3",
767
+ "**/*.mp4",
768
+ "**/*.wav",
769
+ "**/*.ogg",
770
+ "**/*.webm",
771
+ "**/*.zip",
772
+ "**/*.tar",
773
+ "**/*.gz",
774
+ "**/*.br",
775
+ "**/*.sqlite",
776
+ "**/*.db",
777
+ "**/*.lance/**",
778
+ "**/*.jsonl",
779
+ "**/secrets/**",
780
+ "**/.env"
781
+ ];
782
+ /** Add a directory as a source collection for indexing. */
783
+ async sourcesAdd(rootPath, name, options) {
784
+ const db = this.sqliteDb;
785
+ const now = (/* @__PURE__ */ new Date()).toISOString();
786
+ const includePatterns = JSON.stringify(options?.include || _Crystal.DEFAULT_INCLUDE);
787
+ const ignorePatterns = JSON.stringify(options?.ignore || _Crystal.DEFAULT_IGNORE);
788
+ const existing = db.prepare("SELECT * FROM source_collections WHERE name = ?").get(name);
789
+ if (existing) {
790
+ throw new Error(`Collection "${name}" already exists. Use sourcesSync() to update it.`);
791
+ }
792
+ db.prepare(`
793
+ INSERT INTO source_collections (name, root_path, glob_patterns, ignore_patterns, created_at)
794
+ VALUES (?, ?, ?, ?, ?)
795
+ `).run(name, rootPath, includePatterns, ignorePatterns, now);
796
+ const row = db.prepare("SELECT * FROM source_collections WHERE name = ?").get(name);
797
+ return row;
798
+ }
799
+ /** Remove a source collection and its file records. Chunks remain in LanceDB. */
800
+ sourcesRemove(name) {
801
+ const db = this.sqliteDb;
802
+ const col = db.prepare("SELECT id FROM source_collections WHERE name = ?").get(name);
803
+ if (!col) return false;
804
+ db.prepare("DELETE FROM source_files WHERE collection_id = ?").run(col.id);
805
+ db.prepare("DELETE FROM source_collections WHERE id = ?").run(col.id);
806
+ return true;
807
+ }
808
+ /** Sync a collection: scan files, detect changes, re-index what changed. */
809
+ async sourcesSync(name, options) {
810
+ const db = this.sqliteDb;
811
+ const startTime = Date.now();
812
+ const batchSize = options?.batchSize || 20;
813
+ const col = db.prepare("SELECT * FROM source_collections WHERE name = ?").get(name);
814
+ if (!col) throw new Error(`Collection "${name}" not found. Add it first with sourcesAdd().`);
815
+ const includePatterns = JSON.parse(col.glob_patterns);
816
+ const ignorePatterns = JSON.parse(col.ignore_patterns);
817
+ const files = this.scanDirectory(col.root_path, includePatterns, ignorePatterns);
818
+ const existingFiles = /* @__PURE__ */ new Map();
819
+ const rows = db.prepare("SELECT id, file_path, file_hash FROM source_files WHERE collection_id = ?").all(col.id);
820
+ for (const row of rows) {
821
+ existingFiles.set(row.file_path, { id: row.id, file_hash: row.file_hash });
822
+ }
823
+ let added = 0;
824
+ let updated = 0;
825
+ let removed = 0;
826
+ let chunksAdded = 0;
827
+ const now = (/* @__PURE__ */ new Date()).toISOString();
828
+ const toIndex = [];
829
+ for (const absPath of files) {
830
+ const relPath = relative(col.root_path, absPath);
831
+ let content;
832
+ try {
833
+ content = readFileSync(absPath, "utf-8");
834
+ } catch {
835
+ continue;
836
+ }
837
+ const stat = statSync(absPath);
838
+ if (stat.size > 500 * 1024) continue;
839
+ const hash = createHash("sha256").update(content).digest("hex");
840
+ const existing = existingFiles.get(relPath);
841
+ if (existing) {
842
+ existingFiles.delete(relPath);
843
+ if (existing.file_hash === hash) continue;
844
+ toIndex.push({ relPath, absPath, hash, size: stat.size, isUpdate: true });
845
+ } else {
846
+ toIndex.push({ relPath, absPath, hash, size: stat.size, isUpdate: false });
847
+ }
848
+ }
849
+ if (options?.dryRun) {
850
+ const newFiles = toIndex.filter((f) => !f.isUpdate).length;
851
+ const updatedFiles = toIndex.filter((f) => f.isUpdate).length;
852
+ return {
853
+ collection: name,
854
+ added: newFiles,
855
+ updated: updatedFiles,
856
+ removed: existingFiles.size,
857
+ chunks_added: 0,
858
+ duration_ms: Date.now() - startTime
859
+ };
860
+ }
861
+ for (let i = 0; i < toIndex.length; i += batchSize) {
862
+ const batch = toIndex.slice(i, i + batchSize);
863
+ const allChunks = [];
864
+ for (const file of batch) {
865
+ const content = readFileSync(file.absPath, "utf-8");
866
+ const ext = extname(file.absPath);
867
+ const fileName = basename(file.absPath);
868
+ const header = `File: ${file.relPath}
869
+
870
+ `;
871
+ const textChunks = this.chunkText(header + content, 400, 80);
872
+ const fileChunks = textChunks.map((text) => ({
873
+ text,
874
+ role: "system",
875
+ source_type: "file",
876
+ source_id: `file:${name}:${file.relPath}`,
877
+ agent_id: "system",
878
+ token_count: Math.ceil(text.length / 4),
879
+ created_at: now
880
+ }));
881
+ allChunks.push(...fileChunks);
882
+ if (file.isUpdate) {
883
+ db.prepare(`
884
+ UPDATE source_files SET file_hash = ?, file_size = ?, chunk_count = ?, last_indexed_at = ?
885
+ WHERE collection_id = ? AND file_path = ?
886
+ `).run(file.hash, file.size, fileChunks.length, now, col.id, file.relPath);
887
+ updated++;
888
+ } else {
889
+ db.prepare(`
890
+ INSERT INTO source_files (collection_id, file_path, file_hash, file_size, chunk_count, last_indexed_at)
891
+ VALUES (?, ?, ?, ?, ?, ?)
892
+ `).run(col.id, file.relPath, file.hash, file.size, fileChunks.length, now);
893
+ added++;
894
+ }
895
+ }
896
+ if (allChunks.length > 0) {
897
+ const ingested = await this.ingest(allChunks);
898
+ chunksAdded += ingested;
899
+ }
900
+ }
901
+ for (const [relPath, { id }] of existingFiles) {
902
+ db.prepare("DELETE FROM source_files WHERE id = ?").run(id);
903
+ removed++;
904
+ }
905
+ const fileCount = db.prepare("SELECT COUNT(*) as count FROM source_files WHERE collection_id = ?").get(col.id).count;
906
+ const chunkCount = db.prepare("SELECT SUM(chunk_count) as total FROM source_files WHERE collection_id = ?").get(col.id).total || 0;
907
+ db.prepare("UPDATE source_collections SET file_count = ?, chunk_count = ?, last_sync_at = ? WHERE id = ?").run(fileCount, chunkCount, now, col.id);
908
+ return {
909
+ collection: name,
910
+ added,
911
+ updated,
912
+ removed,
913
+ chunks_added: chunksAdded,
914
+ duration_ms: Date.now() - startTime
915
+ };
916
+ }
917
+ /** Get status of all source collections. */
918
+ sourcesStatus() {
919
+ const db = this.sqliteDb;
920
+ const collections = db.prepare("SELECT name, root_path, file_count, chunk_count, last_sync_at FROM source_collections").all();
921
+ const totalFiles = collections.reduce((sum, c) => sum + c.file_count, 0);
922
+ const totalChunks = collections.reduce((sum, c) => sum + c.chunk_count, 0);
923
+ return {
924
+ collections: collections.map((c) => ({
925
+ name: c.name,
926
+ root_path: c.root_path,
927
+ file_count: c.file_count,
928
+ chunk_count: c.chunk_count,
929
+ last_sync_at: c.last_sync_at
930
+ })),
931
+ total_files: totalFiles,
932
+ total_chunks: totalChunks
933
+ };
934
+ }
935
+ /** Scan a directory recursively, matching include/ignore patterns. */
936
+ scanDirectory(rootPath, includePatterns, ignorePatterns) {
937
+ const results = [];
938
+ const allowedExtensions = /* @__PURE__ */ new Set();
939
+ const allowedExactNames = /* @__PURE__ */ new Set();
940
+ for (const pattern of includePatterns) {
941
+ const extMatch = pattern.match(/\*\*\/\*(\.\w+)$/);
942
+ if (extMatch) {
943
+ allowedExtensions.add(extMatch[1]);
944
+ }
945
+ const nameMatch = pattern.match(/\*\*\/([^*]+)$/);
946
+ if (nameMatch && !nameMatch[1].startsWith("*.")) {
947
+ allowedExactNames.add(nameMatch[1]);
948
+ }
949
+ }
950
+ const ignoreDirs = /* @__PURE__ */ new Set();
951
+ for (const pattern of ignorePatterns) {
952
+ const dirMatch = pattern.match(/\*\*\/([^/*]+)\/\*\*$/);
953
+ if (dirMatch) {
954
+ ignoreDirs.add(dirMatch[1]);
955
+ }
956
+ }
957
+ const ignoreFiles = /* @__PURE__ */ new Set();
958
+ for (const pattern of ignorePatterns) {
959
+ const fileMatch = pattern.match(/\*\*\/\*(\.\w+)$/);
960
+ if (fileMatch) {
961
+ ignoreFiles.add(fileMatch[1]);
962
+ }
963
+ const exactMatch = pattern.match(/\*\*\/([^*]+)$/);
964
+ if (exactMatch && !exactMatch[1].includes("/")) {
965
+ ignoreFiles.add(exactMatch[1]);
966
+ }
967
+ }
968
+ const walk = (dir) => {
969
+ let entries;
970
+ try {
971
+ entries = readdirSync(dir);
972
+ } catch {
973
+ return;
974
+ }
975
+ for (const entry of entries) {
976
+ const fullPath = join(dir, entry);
977
+ let stat;
978
+ try {
979
+ stat = statSync(fullPath);
980
+ } catch {
981
+ continue;
982
+ }
983
+ if (stat.isDirectory()) {
984
+ if (ignoreDirs.has(entry)) continue;
985
+ if (entry.startsWith(".")) continue;
986
+ walk(fullPath);
987
+ } else if (stat.isFile()) {
988
+ const ext = extname(entry);
989
+ if (ignoreFiles.has(ext)) continue;
990
+ if (ignoreFiles.has(entry)) continue;
991
+ if (allowedExtensions.has(ext) || allowedExactNames.has(entry)) {
992
+ results.push(fullPath);
993
+ }
994
+ }
995
+ }
996
+ };
997
+ walk(rootPath);
998
+ return results;
999
+ }
1000
+ // ── Cleanup ──
1001
+ close() {
1002
+ this.sqliteDb?.close();
1003
+ }
1004
+ };
1005
+ function resolveConfig(overrides) {
1006
+ const openclawHome = process.env.OPENCLAW_HOME || join(process.env.HOME || "/Users/lesa", ".openclaw");
1007
+ const dataDir = overrides?.dataDir || join(openclawHome, "memory-crystal");
1008
+ loadEnvFile(join(dataDir, ".env"));
1009
+ const openaiApiKey = overrides?.openaiApiKey || process.env.OPENAI_API_KEY || opRead(openclawHome, "OpenAI API", "api key");
1010
+ const googleApiKey = overrides?.googleApiKey || process.env.GOOGLE_API_KEY || opRead(openclawHome, "Google AI", "api key");
1011
+ const remoteToken = overrides?.remoteToken || process.env.CRYSTAL_REMOTE_TOKEN || opRead(openclawHome, "Memory Crystal Remote", "token");
1012
+ return {
1013
+ dataDir,
1014
+ embeddingProvider: overrides?.embeddingProvider || process.env.CRYSTAL_EMBEDDING_PROVIDER || "openai",
1015
+ openaiApiKey,
1016
+ openaiModel: overrides?.openaiModel || process.env.CRYSTAL_OPENAI_MODEL || "text-embedding-3-small",
1017
+ ollamaHost: overrides?.ollamaHost || process.env.CRYSTAL_OLLAMA_HOST || "http://localhost:11434",
1018
+ ollamaModel: overrides?.ollamaModel || process.env.CRYSTAL_OLLAMA_MODEL || "nomic-embed-text",
1019
+ googleApiKey,
1020
+ googleModel: overrides?.googleModel || process.env.CRYSTAL_GOOGLE_MODEL || "text-embedding-004",
1021
+ remoteUrl: overrides?.remoteUrl || process.env.CRYSTAL_REMOTE_URL,
1022
+ remoteToken
1023
+ };
1024
+ }
1025
+ function loadEnvFile(path) {
1026
+ if (!existsSync(path)) return;
1027
+ const content = readFileSync(path, "utf8");
1028
+ for (const line of content.split("\n")) {
1029
+ const trimmed = line.trim();
1030
+ if (!trimmed || trimmed.startsWith("#")) continue;
1031
+ const eqIdx = trimmed.indexOf("=");
1032
+ if (eqIdx === -1) continue;
1033
+ const key = trimmed.slice(0, eqIdx).trim();
1034
+ let value = trimmed.slice(eqIdx + 1).trim();
1035
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
1036
+ value = value.slice(1, -1);
1037
+ }
1038
+ if (key && !process.env[key]) {
1039
+ process.env[key] = value;
1040
+ }
1041
+ }
1042
+ }
1043
+ function opRead(openclawHome, item, field) {
1044
+ try {
1045
+ const saTokenPath = join(openclawHome, "secrets", "op-sa-token");
1046
+ if (!existsSync(saTokenPath)) return void 0;
1047
+ const saToken = readFileSync(saTokenPath, "utf8").trim();
1048
+ return execSync(`op read "op://Agent Secrets/${item}/${field}" 2>/dev/null`, {
1049
+ encoding: "utf8",
1050
+ env: { ...process.env, OP_SERVICE_ACCOUNT_TOKEN: saToken },
1051
+ timeout: 1e4
1052
+ }).trim() || void 0;
1053
+ } catch {
1054
+ return void 0;
1055
+ }
1056
+ }
1057
+
1058
+ export {
1059
+ Crystal,
1060
+ resolveConfig
1061
+ };