moflo 4.9.37 → 4.10.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 (73) hide show
  1. package/.claude/guidance/shipped/moflo-memory-protocol.md +5 -1
  2. package/.claude/guidance/shipped/moflo-memorydb-maintenance.md +22 -11
  3. package/.claude/guidance/shipped/moflo-root-cause-discipline.md +47 -0
  4. package/.claude/helpers/statusline.cjs +69 -33
  5. package/.claude/helpers/subagent-bootstrap.json +1 -1
  6. package/.claude/helpers/subagent-start.cjs +1 -1
  7. package/bin/build-embeddings.mjs +6 -20
  8. package/bin/cli.js +5 -0
  9. package/bin/generate-code-map.mjs +4 -24
  10. package/bin/hooks.mjs +3 -12
  11. package/bin/index-all.mjs +3 -13
  12. package/bin/index-guidance.mjs +36 -85
  13. package/bin/index-patterns.mjs +6 -24
  14. package/bin/index-tests.mjs +4 -23
  15. package/bin/lib/db-repair.mjs +4 -25
  16. package/bin/lib/get-backend.mjs +306 -0
  17. package/bin/lib/incremental-write.mjs +27 -7
  18. package/bin/lib/moflo-paths.mjs +64 -4
  19. package/bin/lib/suppress-sqlite-warning.mjs +57 -0
  20. package/bin/migrations/knowledge-purge.mjs +7 -8
  21. package/bin/migrations/knowledge-to-learnings.mjs +7 -9
  22. package/bin/migrations/purge-doc-entries.mjs +7 -8
  23. package/bin/migrations/strip-context-preambles.mjs +4 -6
  24. package/bin/run-migrations.mjs +1 -10
  25. package/bin/semantic-search.mjs +7 -18
  26. package/bin/session-start-launcher.mjs +102 -102
  27. package/bin/simplify-classify.cjs +38 -17
  28. package/dist/src/cli/commands/daemon.js +38 -11
  29. package/dist/src/cli/commands/doctor-checks-coverage-truth.js +136 -0
  30. package/dist/src/cli/commands/doctor-checks-memory-access.js +146 -86
  31. package/dist/src/cli/commands/doctor-checks-memory.js +13 -18
  32. package/dist/src/cli/commands/doctor-checks-version-skew.js +94 -0
  33. package/dist/src/cli/commands/doctor-checks-writers-audit.js +170 -0
  34. package/dist/src/cli/commands/doctor-embedding-hygiene.js +3 -15
  35. package/dist/src/cli/commands/doctor-fixes.js +30 -0
  36. package/dist/src/cli/commands/doctor-registry.js +14 -0
  37. package/dist/src/cli/commands/doctor.js +1 -1
  38. package/dist/src/cli/commands/embeddings.js +17 -22
  39. package/dist/src/cli/commands/memory.js +13 -23
  40. package/dist/src/cli/embeddings/persistent-cache.js +44 -83
  41. package/dist/src/cli/init/moflo-init.js +40 -0
  42. package/dist/src/cli/mcp-tools/memory-tools.js +10 -3
  43. package/dist/src/cli/memory/bridge-core.js +256 -30
  44. package/dist/src/cli/memory/bridge-entries.js +70 -6
  45. package/dist/src/cli/memory/controller-registry.js +7 -2
  46. package/dist/src/cli/memory/controllers/batch-operations.js +5 -1
  47. package/dist/src/cli/memory/controllers/hierarchical-memory.js +7 -2
  48. package/dist/src/cli/memory/controllers/mutation-guard.js +22 -2
  49. package/dist/src/cli/memory/daemon-backend.js +400 -0
  50. package/dist/src/cli/memory/daemon-write-client.js +192 -15
  51. package/dist/src/cli/memory/database-provider.js +57 -40
  52. package/dist/src/cli/memory/hnsw-persistence.js +6 -8
  53. package/dist/src/cli/memory/index.js +0 -1
  54. package/dist/src/cli/memory/memory-bridge.js +40 -8
  55. package/dist/src/cli/memory/memory-initializer.js +269 -209
  56. package/dist/src/cli/memory/rvf-migration.js +25 -11
  57. package/dist/src/cli/memory/sqlite-backend.js +573 -0
  58. package/dist/src/cli/memory/suppress-sqlite-warning.js +49 -0
  59. package/dist/src/cli/services/cherry-pick-learnings.js +32 -21
  60. package/dist/src/cli/services/daemon-dashboard.js +13 -1
  61. package/dist/src/cli/services/daemon-lock.js +58 -1
  62. package/dist/src/cli/services/daemon-memory-rpc.js +245 -10
  63. package/dist/src/cli/services/embeddings-migration.js +9 -12
  64. package/dist/src/cli/services/ephemeral-namespace-purge.js +6 -11
  65. package/dist/src/cli/services/learning-service.js +12 -20
  66. package/dist/src/cli/services/project-root.js +69 -9
  67. package/dist/src/cli/services/soft-delete-purge.js +6 -11
  68. package/dist/src/cli/services/sqljs-migration-store.js +4 -1
  69. package/dist/src/cli/services/subagent-bootstrap.js +1 -1
  70. package/dist/src/cli/shared/events/event-store.js +26 -55
  71. package/dist/src/cli/version.js +1 -1
  72. package/package.json +2 -4
  73. package/dist/src/cli/memory/sqljs-backend.js +0 -643
@@ -1,643 +0,0 @@
1
- /**
2
- * SqlJsBackend - Pure JavaScript SQLite for Windows compatibility
3
- *
4
- * Pure JavaScript/WASM SQLite backend that works everywhere
5
- * without native compilation.
6
- *
7
- * @module v3/memory/sqljs-backend
8
- */
9
- import { EventEmitter } from 'node:events';
10
- import { readFileSync, writeFileSync, existsSync } from 'node:fs';
11
- import { createRequire } from 'node:module';
12
- import { dirname, join as joinPath } from 'node:path';
13
- import initSqlJs from 'sql.js';
14
- /**
15
- * Resolve the directory that bundles sql-wasm.wasm alongside sql.js. In Node
16
- * the default `locateFile` (sql.js.org CDN) is treated as a file path and
17
- * fails with ENOENT — sql.js then crashes on WASM cleanup. Walk to the
18
- * installed sql.js package and point at its local dist/ instead.
19
- */
20
- let cachedSqlJsWasmDir = null;
21
- function resolveSqlJsWasmDir() {
22
- if (cachedSqlJsWasmDir !== null)
23
- return cachedSqlJsWasmDir;
24
- try {
25
- // Resolve sql.js's main entry (sql-wasm.js lives next to it in dist/).
26
- // Can't use require.resolve('sql.js/package.json') because sql.js's
27
- // `exports` field doesn't expose it. `require.resolve` returns an OS-
28
- // native absolute path — works on Windows (backslashes) and POSIX.
29
- const require = createRequire(import.meta.url);
30
- const mainEntry = require.resolve('sql.js');
31
- cachedSqlJsWasmDir = dirname(mainEntry);
32
- }
33
- catch {
34
- cachedSqlJsWasmDir = null;
35
- }
36
- return cachedSqlJsWasmDir;
37
- }
38
- /**
39
- * Initialize sql.js with a Node-aware `locateFile` that points at the
40
- * installed sql.js package's own dist/ directory. Prefer this over bare
41
- * `initSqlJs()` anywhere sql.js is used in Node.
42
- */
43
- export async function initSqlJsForNode(wasmPath) {
44
- return initSqlJs({ locateFile: buildLocateFile(wasmPath) });
45
- }
46
- function buildLocateFile(wasmPath) {
47
- if (wasmPath)
48
- return () => wasmPath;
49
- const localWasmDir = resolveSqlJsWasmDir();
50
- if (localWasmDir)
51
- return (file) => joinPath(localWasmDir, file);
52
- // Browser/unbundled fallback — sql.js can fetch over HTTP when running in
53
- // environments where require.resolve('sql.js') can't find the package.
54
- return (file) => `https://sql.js.org/dist/${file}`;
55
- }
56
- /**
57
- * Load sql.js WASM and open a Database — from disk if `dbPath` exists,
58
- * otherwise in-memory. Shared between `SqlJsBackend` and `ControllerRegistry`.
59
- */
60
- export async function openSqlJsDatabase(dbPath, wasmPath) {
61
- const SQL = await initSqlJsForNode(wasmPath);
62
- if (dbPath !== ':memory:' && existsSync(dbPath)) {
63
- return new SQL.Database(new Uint8Array(readFileSync(dbPath)));
64
- }
65
- return new SQL.Database();
66
- }
67
- /**
68
- * Default configuration values
69
- */
70
- const DEFAULT_CONFIG = {
71
- databasePath: ':memory:',
72
- optimize: true,
73
- defaultNamespace: 'default',
74
- maxEntries: 1000000,
75
- verbose: false,
76
- autoPersistInterval: 5000, // 5 seconds
77
- };
78
- /**
79
- * SqlJs Backend for Cross-Platform Memory Storage
80
- *
81
- * Provides:
82
- * - Pure JavaScript/WASM implementation (no native compilation)
83
- * - Windows, macOS, Linux compatibility
84
- * - Same SQL interface as native SQLite
85
- * - In-memory with periodic disk persistence
86
- */
87
- export class SqlJsBackend extends EventEmitter {
88
- config;
89
- db = null;
90
- initialized = false;
91
- persistTimer = null;
92
- // Performance tracking
93
- stats = {
94
- queryCount: 0,
95
- totalQueryTime: 0,
96
- writeCount: 0,
97
- totalWriteTime: 0,
98
- };
99
- constructor(config = {}) {
100
- super();
101
- this.config = { ...DEFAULT_CONFIG, ...config };
102
- }
103
- /**
104
- * Initialize the SqlJs backend
105
- */
106
- async initialize() {
107
- if (this.initialized)
108
- return;
109
- this.db = await openSqlJsDatabase(this.config.databasePath, this.config.wasmPath);
110
- if (this.config.verbose) {
111
- const loaded = this.config.databasePath !== ':memory:' && existsSync(this.config.databasePath);
112
- console.log(loaded
113
- ? `[SqlJsBackend] Loaded database from ${this.config.databasePath}`
114
- : '[SqlJsBackend] Created new in-memory database');
115
- }
116
- // Create schema
117
- this.createSchema();
118
- // Set up auto-persist if enabled
119
- if (this.config.autoPersistInterval > 0 && this.config.databasePath !== ':memory:') {
120
- this.persistTimer = setInterval(() => {
121
- this.persist().catch((err) => {
122
- this.emit('error', { operation: 'auto-persist', error: err });
123
- });
124
- }, this.config.autoPersistInterval);
125
- // Don't keep the event loop alive — short-lived CLI commands shouldn't
126
- // have to wait for auto-persist to decide to exit (issue #504).
127
- this.persistTimer.unref?.();
128
- }
129
- this.initialized = true;
130
- this.emit('initialized');
131
- }
132
- /**
133
- * Shutdown the backend
134
- */
135
- async shutdown() {
136
- if (!this.initialized || !this.db)
137
- return;
138
- // Stop auto-persist timer
139
- if (this.persistTimer) {
140
- clearInterval(this.persistTimer);
141
- this.persistTimer = null;
142
- }
143
- // Final persist before shutdown
144
- if (this.config.databasePath !== ':memory:') {
145
- await this.persist();
146
- }
147
- this.db.close();
148
- this.db = null;
149
- this.initialized = false;
150
- this.emit('shutdown');
151
- }
152
- /**
153
- * Create database schema
154
- */
155
- createSchema() {
156
- if (!this.db)
157
- return;
158
- // Main entries table
159
- this.db.run(`
160
- CREATE TABLE IF NOT EXISTS memory_entries (
161
- id TEXT PRIMARY KEY,
162
- key TEXT NOT NULL,
163
- content TEXT NOT NULL,
164
- embedding BLOB,
165
- type TEXT NOT NULL,
166
- namespace TEXT NOT NULL,
167
- tags TEXT NOT NULL,
168
- metadata TEXT NOT NULL,
169
- owner_id TEXT,
170
- access_level TEXT NOT NULL,
171
- created_at INTEGER NOT NULL,
172
- updated_at INTEGER NOT NULL,
173
- expires_at INTEGER,
174
- version INTEGER NOT NULL DEFAULT 1,
175
- "references" TEXT NOT NULL,
176
- access_count INTEGER NOT NULL DEFAULT 0,
177
- last_accessed_at INTEGER NOT NULL
178
- )
179
- `);
180
- // Indexes for performance
181
- this.db.run('CREATE INDEX IF NOT EXISTS idx_namespace ON memory_entries(namespace)');
182
- this.db.run('CREATE INDEX IF NOT EXISTS idx_key ON memory_entries(key)');
183
- this.db.run('CREATE INDEX IF NOT EXISTS idx_type ON memory_entries(type)');
184
- this.db.run('CREATE INDEX IF NOT EXISTS idx_created_at ON memory_entries(created_at)');
185
- this.db.run('CREATE INDEX IF NOT EXISTS idx_expires_at ON memory_entries(expires_at)');
186
- this.db.run('CREATE UNIQUE INDEX IF NOT EXISTS idx_namespace_key ON memory_entries(namespace, key)');
187
- if (this.config.verbose) {
188
- console.log('[SqlJsBackend] Schema created successfully');
189
- }
190
- }
191
- /**
192
- * Store a memory entry
193
- */
194
- async store(entry) {
195
- this.ensureInitialized();
196
- const startTime = performance.now();
197
- const stmt = `
198
- INSERT OR REPLACE INTO memory_entries (
199
- id, key, content, embedding, type, namespace, tags, metadata,
200
- owner_id, access_level, created_at, updated_at, expires_at,
201
- version, "references", access_count, last_accessed_at
202
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
203
- `;
204
- const embeddingBuffer = entry.embedding
205
- ? Buffer.from(entry.embedding.buffer)
206
- : null;
207
- this.db.run(stmt, [
208
- entry.id,
209
- entry.key,
210
- entry.content,
211
- embeddingBuffer,
212
- entry.type,
213
- entry.namespace,
214
- JSON.stringify(entry.tags),
215
- JSON.stringify(entry.metadata),
216
- entry.ownerId || null,
217
- entry.accessLevel,
218
- entry.createdAt,
219
- entry.updatedAt,
220
- entry.expiresAt || null,
221
- entry.version,
222
- JSON.stringify(entry.references),
223
- entry.accessCount,
224
- entry.lastAccessedAt,
225
- ]);
226
- const duration = performance.now() - startTime;
227
- this.stats.writeCount++;
228
- this.stats.totalWriteTime += duration;
229
- this.emit('entry:stored', { entry, duration });
230
- }
231
- /**
232
- * Retrieve a memory entry by ID
233
- */
234
- async get(id) {
235
- this.ensureInitialized();
236
- const startTime = performance.now();
237
- const stmt = this.db.prepare('SELECT * FROM memory_entries WHERE id = ?');
238
- const row = stmt.getAsObject([id]);
239
- stmt.free();
240
- const duration = performance.now() - startTime;
241
- this.stats.queryCount++;
242
- this.stats.totalQueryTime += duration;
243
- if (!row || Object.keys(row).length === 0) {
244
- return null;
245
- }
246
- const entry = this.rowToEntry(row);
247
- // Update access tracking
248
- this.updateAccessTracking(id);
249
- this.emit('entry:retrieved', { id, duration });
250
- return entry;
251
- }
252
- /**
253
- * Retrieve a memory entry by key within a namespace
254
- */
255
- async getByKey(namespace, key) {
256
- this.ensureInitialized();
257
- const startTime = performance.now();
258
- const stmt = this.db.prepare('SELECT * FROM memory_entries WHERE namespace = ? AND key = ?');
259
- const row = stmt.getAsObject([namespace, key]);
260
- stmt.free();
261
- const duration = performance.now() - startTime;
262
- this.stats.queryCount++;
263
- this.stats.totalQueryTime += duration;
264
- if (!row || Object.keys(row).length === 0) {
265
- return null;
266
- }
267
- const entry = this.rowToEntry(row);
268
- // Update access tracking
269
- this.updateAccessTracking(entry.id);
270
- this.emit('entry:retrieved', { namespace, key, duration });
271
- return entry;
272
- }
273
- /**
274
- * Update a memory entry
275
- */
276
- async update(id, updateData) {
277
- this.ensureInitialized();
278
- const startTime = performance.now();
279
- // Get existing entry
280
- const existing = await this.get(id);
281
- if (!existing)
282
- return null;
283
- // Merge updates
284
- const updated = {
285
- ...existing,
286
- ...updateData,
287
- updatedAt: Date.now(),
288
- version: existing.version + 1,
289
- };
290
- // Store updated entry
291
- await this.store(updated);
292
- const duration = performance.now() - startTime;
293
- this.emit('entry:updated', { id, update: updateData, duration });
294
- return updated;
295
- }
296
- /**
297
- * Delete a memory entry
298
- */
299
- async delete(id) {
300
- this.ensureInitialized();
301
- const startTime = performance.now();
302
- this.db.run('DELETE FROM memory_entries WHERE id = ?', [id]);
303
- const duration = performance.now() - startTime;
304
- this.stats.writeCount++;
305
- this.stats.totalWriteTime += duration;
306
- this.emit('entry:deleted', { id, duration });
307
- return true;
308
- }
309
- /**
310
- * Query memory entries
311
- */
312
- async query(query) {
313
- this.ensureInitialized();
314
- const startTime = performance.now();
315
- let sql = 'SELECT * FROM memory_entries WHERE 1=1';
316
- const params = [];
317
- // Namespace filter
318
- if (query.namespace) {
319
- sql += ' AND namespace = ?';
320
- params.push(query.namespace);
321
- }
322
- // Type filter
323
- if (query.memoryType) {
324
- sql += ' AND type = ?';
325
- params.push(query.memoryType);
326
- }
327
- // Owner filter
328
- if (query.ownerId) {
329
- sql += ' AND owner_id = ?';
330
- params.push(query.ownerId);
331
- }
332
- // Access level filter
333
- if (query.accessLevel) {
334
- sql += ' AND access_level = ?';
335
- params.push(query.accessLevel);
336
- }
337
- // Key filters
338
- if (query.key) {
339
- sql += ' AND key = ?';
340
- params.push(query.key);
341
- }
342
- else if (query.keyPrefix) {
343
- sql += ' AND key LIKE ?';
344
- params.push(query.keyPrefix + '%');
345
- }
346
- // Time range filters
347
- if (query.createdAfter) {
348
- sql += ' AND created_at >= ?';
349
- params.push(query.createdAfter);
350
- }
351
- if (query.createdBefore) {
352
- sql += ' AND created_at <= ?';
353
- params.push(query.createdBefore);
354
- }
355
- if (query.updatedAfter) {
356
- sql += ' AND updated_at >= ?';
357
- params.push(query.updatedAfter);
358
- }
359
- if (query.updatedBefore) {
360
- sql += ' AND updated_at <= ?';
361
- params.push(query.updatedBefore);
362
- }
363
- // Expiration filter
364
- if (!query.includeExpired) {
365
- sql += ' AND (expires_at IS NULL OR expires_at > ?)';
366
- params.push(Date.now());
367
- }
368
- // Ordering and pagination
369
- sql += ' ORDER BY created_at DESC';
370
- if (query.limit) {
371
- sql += ' LIMIT ?';
372
- params.push(query.limit);
373
- }
374
- if (query.offset) {
375
- sql += ' OFFSET ?';
376
- params.push(query.offset);
377
- }
378
- const stmt = this.db.prepare(sql);
379
- if (params.length > 0) {
380
- stmt.bind(params);
381
- }
382
- const results = [];
383
- while (stmt.step()) {
384
- const row = stmt.getAsObject();
385
- const entry = this.rowToEntry(row);
386
- // Tag filtering (post-query since tags are JSON)
387
- if (query.tags && query.tags.length > 0) {
388
- const hasAllTags = query.tags.every((tag) => entry.tags.includes(tag));
389
- if (!hasAllTags)
390
- continue;
391
- }
392
- // Metadata filtering (post-query since metadata is JSON)
393
- if (query.metadata) {
394
- const matchesMetadata = Object.entries(query.metadata).every(([key, value]) => entry.metadata[key] === value);
395
- if (!matchesMetadata)
396
- continue;
397
- }
398
- results.push(entry);
399
- }
400
- stmt.free();
401
- const duration = performance.now() - startTime;
402
- this.stats.queryCount++;
403
- this.stats.totalQueryTime += duration;
404
- this.emit('query:executed', { query, resultCount: results.length, duration });
405
- return results;
406
- }
407
- /**
408
- * Semantic vector search (limited without vector index)
409
- */
410
- async search(embedding, options) {
411
- this.ensureInitialized();
412
- // Get all entries with embeddings
413
- const entries = await this.query({
414
- type: 'hybrid',
415
- limit: options.filters?.limit || 1000,
416
- });
417
- // Calculate cosine similarity for each entry
418
- const results = [];
419
- for (const entry of entries) {
420
- if (!entry.embedding)
421
- continue;
422
- const similarity = this.cosineSimilarity(embedding, entry.embedding);
423
- if (options.threshold && similarity < options.threshold) {
424
- continue;
425
- }
426
- results.push({
427
- entry,
428
- score: similarity,
429
- distance: 1 - similarity,
430
- });
431
- }
432
- // Sort by score descending
433
- results.sort((a, b) => b.score - a.score);
434
- // Return top k results
435
- return results.slice(0, options.k);
436
- }
437
- /**
438
- * Bulk insert entries
439
- */
440
- async bulkInsert(entries) {
441
- this.ensureInitialized();
442
- for (const entry of entries) {
443
- await this.store(entry);
444
- }
445
- this.emit('bulk:inserted', { count: entries.length });
446
- }
447
- /**
448
- * Bulk delete entries
449
- */
450
- async bulkDelete(ids) {
451
- this.ensureInitialized();
452
- let count = 0;
453
- for (const id of ids) {
454
- const success = await this.delete(id);
455
- if (success)
456
- count++;
457
- }
458
- this.emit('bulk:deleted', { count });
459
- return count;
460
- }
461
- /**
462
- * Get entry count
463
- */
464
- async count(namespace) {
465
- this.ensureInitialized();
466
- let sql = 'SELECT COUNT(*) as count FROM memory_entries';
467
- const params = [];
468
- if (namespace) {
469
- sql += ' WHERE namespace = ?';
470
- params.push(namespace);
471
- }
472
- const stmt = this.db.prepare(sql);
473
- const row = stmt.getAsObject(params);
474
- stmt.free();
475
- return row.count || 0;
476
- }
477
- /**
478
- * List all namespaces
479
- */
480
- async listNamespaces() {
481
- this.ensureInitialized();
482
- const stmt = this.db.prepare('SELECT DISTINCT namespace FROM memory_entries');
483
- const namespaces = [];
484
- while (stmt.step()) {
485
- const row = stmt.getAsObject();
486
- namespaces.push(row.namespace);
487
- }
488
- stmt.free();
489
- return namespaces;
490
- }
491
- /**
492
- * Clear all entries in a namespace
493
- */
494
- async clearNamespace(namespace) {
495
- this.ensureInitialized();
496
- const countBefore = await this.count(namespace);
497
- this.db.run('DELETE FROM memory_entries WHERE namespace = ?', [namespace]);
498
- this.emit('namespace:cleared', { namespace, count: countBefore });
499
- return countBefore;
500
- }
501
- /**
502
- * Get backend statistics
503
- */
504
- async getStats() {
505
- this.ensureInitialized();
506
- const total = await this.count();
507
- // Count by namespace
508
- const entriesByNamespace = {};
509
- const namespaces = await this.listNamespaces();
510
- for (const ns of namespaces) {
511
- entriesByNamespace[ns] = await this.count(ns);
512
- }
513
- // Count by type
514
- const entriesByType = {};
515
- const types = ['episodic', 'semantic', 'procedural', 'working', 'cache'];
516
- for (const type of types) {
517
- const stmt = this.db.prepare('SELECT COUNT(*) as count FROM memory_entries WHERE type = ?');
518
- const row = stmt.getAsObject([type]);
519
- stmt.free();
520
- entriesByType[type] = row.count || 0;
521
- }
522
- return {
523
- totalEntries: total,
524
- entriesByNamespace,
525
- entriesByType,
526
- memoryUsage: this.estimateMemoryUsage(),
527
- avgQueryTime: this.stats.queryCount > 0 ? this.stats.totalQueryTime / this.stats.queryCount : 0,
528
- avgSearchTime: 0, // Not tracked separately
529
- };
530
- }
531
- /**
532
- * Perform health check
533
- */
534
- async healthCheck() {
535
- const issues = [];
536
- const recommendations = [];
537
- // Storage health
538
- const storageStart = performance.now();
539
- const storageHealthy = this.db !== null;
540
- const storageLatency = performance.now() - storageStart;
541
- if (!storageHealthy) {
542
- issues.push('Database not initialized');
543
- }
544
- // Index health (sql.js doesn't have native vector index)
545
- const indexHealth = {
546
- status: 'healthy',
547
- latency: 0,
548
- message: 'No vector index (brute-force search)',
549
- };
550
- recommendations.push('Consider using MofloDbAdapter for HNSW-indexed vector search');
551
- // Cache health (not applicable for sql.js)
552
- const cacheHealth = {
553
- status: 'healthy',
554
- latency: 0,
555
- message: 'No separate cache layer',
556
- };
557
- const status = issues.length === 0 ? 'healthy' : 'degraded';
558
- return {
559
- status,
560
- components: {
561
- storage: {
562
- status: storageHealthy ? 'healthy' : 'unhealthy',
563
- latency: storageLatency,
564
- },
565
- index: indexHealth,
566
- cache: cacheHealth,
567
- },
568
- timestamp: Date.now(),
569
- issues,
570
- recommendations,
571
- };
572
- }
573
- /**
574
- * Persist changes to disk (sql.js is in-memory, needs explicit save)
575
- */
576
- async persist() {
577
- if (!this.db || this.config.databasePath === ':memory:') {
578
- return;
579
- }
580
- const data = this.db.export();
581
- const buffer = Buffer.from(data);
582
- writeFileSync(this.config.databasePath, buffer);
583
- if (this.config.verbose) {
584
- console.log(`[SqlJsBackend] Persisted ${buffer.length} bytes to ${this.config.databasePath}`);
585
- }
586
- this.emit('persisted', { size: buffer.length, path: this.config.databasePath });
587
- }
588
- // ===== Helper Methods =====
589
- ensureInitialized() {
590
- if (!this.initialized || !this.db) {
591
- throw new Error('SqlJsBackend not initialized. Call initialize() first.');
592
- }
593
- }
594
- rowToEntry(row) {
595
- return {
596
- id: row.id,
597
- key: row.key,
598
- content: row.content,
599
- embedding: row.embedding
600
- ? new Float32Array(new Uint8Array(row.embedding).buffer)
601
- : undefined,
602
- type: row.type,
603
- namespace: row.namespace,
604
- tags: JSON.parse(row.tags),
605
- metadata: JSON.parse(row.metadata),
606
- ownerId: row.owner_id,
607
- accessLevel: row.access_level,
608
- createdAt: row.created_at,
609
- updatedAt: row.updated_at,
610
- expiresAt: row.expires_at,
611
- version: row.version,
612
- references: JSON.parse(row.references),
613
- accessCount: row.access_count,
614
- lastAccessedAt: row.last_accessed_at,
615
- };
616
- }
617
- updateAccessTracking(id) {
618
- if (!this.db)
619
- return;
620
- this.db.run('UPDATE memory_entries SET access_count = access_count + 1, last_accessed_at = ? WHERE id = ?', [Date.now(), id]);
621
- }
622
- cosineSimilarity(a, b) {
623
- let dotProduct = 0;
624
- let normA = 0;
625
- let normB = 0;
626
- for (let i = 0; i < a.length; i++) {
627
- dotProduct += a[i] * b[i];
628
- normA += a[i] * a[i];
629
- normB += b[i] * b[i];
630
- }
631
- if (normA === 0 || normB === 0)
632
- return 0;
633
- return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
634
- }
635
- estimateMemoryUsage() {
636
- if (!this.db)
637
- return 0;
638
- // Export to get size
639
- const data = this.db.export();
640
- return data.length;
641
- }
642
- }
643
- //# sourceMappingURL=sqljs-backend.js.map