@aitytech/agentkits-memory 1.0.0 → 2.0.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 (110) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +267 -149
  3. package/assets/agentkits-memory-add-memory.png +0 -0
  4. package/assets/agentkits-memory-memory-detail.png +0 -0
  5. package/assets/agentkits-memory-memory-list.png +0 -0
  6. package/assets/logo.svg +24 -0
  7. package/dist/better-sqlite3-backend.d.ts +192 -0
  8. package/dist/better-sqlite3-backend.d.ts.map +1 -0
  9. package/dist/better-sqlite3-backend.js +801 -0
  10. package/dist/better-sqlite3-backend.js.map +1 -0
  11. package/dist/cli/save.js +0 -0
  12. package/dist/cli/setup.d.ts +6 -2
  13. package/dist/cli/setup.d.ts.map +1 -1
  14. package/dist/cli/setup.js +289 -42
  15. package/dist/cli/setup.js.map +1 -1
  16. package/dist/cli/viewer.js +25 -56
  17. package/dist/cli/viewer.js.map +1 -1
  18. package/dist/cli/web-viewer.d.ts +14 -0
  19. package/dist/cli/web-viewer.d.ts.map +1 -0
  20. package/dist/cli/web-viewer.js +1769 -0
  21. package/dist/cli/web-viewer.js.map +1 -0
  22. package/dist/embeddings/embedding-cache.d.ts +131 -0
  23. package/dist/embeddings/embedding-cache.d.ts.map +1 -0
  24. package/dist/embeddings/embedding-cache.js +217 -0
  25. package/dist/embeddings/embedding-cache.js.map +1 -0
  26. package/dist/embeddings/index.d.ts +11 -0
  27. package/dist/embeddings/index.d.ts.map +1 -0
  28. package/dist/embeddings/index.js +11 -0
  29. package/dist/embeddings/index.js.map +1 -0
  30. package/dist/embeddings/local-embeddings.d.ts +140 -0
  31. package/dist/embeddings/local-embeddings.d.ts.map +1 -0
  32. package/dist/embeddings/local-embeddings.js +293 -0
  33. package/dist/embeddings/local-embeddings.js.map +1 -0
  34. package/dist/hooks/context.d.ts +6 -1
  35. package/dist/hooks/context.d.ts.map +1 -1
  36. package/dist/hooks/context.js +12 -2
  37. package/dist/hooks/context.js.map +1 -1
  38. package/dist/hooks/observation.d.ts +6 -1
  39. package/dist/hooks/observation.d.ts.map +1 -1
  40. package/dist/hooks/observation.js +12 -2
  41. package/dist/hooks/observation.js.map +1 -1
  42. package/dist/hooks/service.d.ts +1 -6
  43. package/dist/hooks/service.d.ts.map +1 -1
  44. package/dist/hooks/service.js +33 -85
  45. package/dist/hooks/service.js.map +1 -1
  46. package/dist/hooks/session-init.d.ts +6 -1
  47. package/dist/hooks/session-init.d.ts.map +1 -1
  48. package/dist/hooks/session-init.js +12 -2
  49. package/dist/hooks/session-init.js.map +1 -1
  50. package/dist/hooks/summarize.d.ts +6 -1
  51. package/dist/hooks/summarize.d.ts.map +1 -1
  52. package/dist/hooks/summarize.js +12 -2
  53. package/dist/hooks/summarize.js.map +1 -1
  54. package/dist/index.d.ts +10 -17
  55. package/dist/index.d.ts.map +1 -1
  56. package/dist/index.js +172 -94
  57. package/dist/index.js.map +1 -1
  58. package/dist/mcp/server.js +17 -3
  59. package/dist/mcp/server.js.map +1 -1
  60. package/dist/migration.js +3 -3
  61. package/dist/migration.js.map +1 -1
  62. package/dist/search/hybrid-search.d.ts +262 -0
  63. package/dist/search/hybrid-search.d.ts.map +1 -0
  64. package/dist/search/hybrid-search.js +688 -0
  65. package/dist/search/hybrid-search.js.map +1 -0
  66. package/dist/search/index.d.ts +13 -0
  67. package/dist/search/index.d.ts.map +1 -0
  68. package/dist/search/index.js +13 -0
  69. package/dist/search/index.js.map +1 -0
  70. package/dist/search/token-economics.d.ts +161 -0
  71. package/dist/search/token-economics.d.ts.map +1 -0
  72. package/dist/search/token-economics.js +239 -0
  73. package/dist/search/token-economics.js.map +1 -0
  74. package/dist/types.d.ts +0 -68
  75. package/dist/types.d.ts.map +1 -1
  76. package/dist/types.js.map +1 -1
  77. package/package.json +23 -8
  78. package/src/__tests__/better-sqlite3-backend.test.ts +1466 -0
  79. package/src/__tests__/cache-manager.test.ts +499 -0
  80. package/src/__tests__/embedding-integration.test.ts +481 -0
  81. package/src/__tests__/hnsw-index.test.ts +727 -0
  82. package/src/__tests__/index.test.ts +432 -0
  83. package/src/better-sqlite3-backend.ts +1000 -0
  84. package/src/cli/setup.ts +358 -47
  85. package/src/cli/viewer.ts +28 -63
  86. package/src/cli/web-viewer.ts +1956 -0
  87. package/src/embeddings/__tests__/embedding-cache.test.ts +269 -0
  88. package/src/embeddings/__tests__/local-embeddings.test.ts +495 -0
  89. package/src/embeddings/embedding-cache.ts +318 -0
  90. package/src/embeddings/index.ts +20 -0
  91. package/src/embeddings/local-embeddings.ts +419 -0
  92. package/src/hooks/__tests__/handlers.test.ts +58 -17
  93. package/src/hooks/__tests__/integration.test.ts +77 -26
  94. package/src/hooks/context.ts +13 -2
  95. package/src/hooks/observation.ts +13 -2
  96. package/src/hooks/service.ts +39 -100
  97. package/src/hooks/session-init.ts +13 -2
  98. package/src/hooks/summarize.ts +13 -2
  99. package/src/index.ts +210 -116
  100. package/src/mcp/server.ts +20 -3
  101. package/src/search/__tests__/hybrid-search.test.ts +669 -0
  102. package/src/search/__tests__/token-economics.test.ts +276 -0
  103. package/src/search/hybrid-search.ts +968 -0
  104. package/src/search/index.ts +29 -0
  105. package/src/search/token-economics.ts +367 -0
  106. package/src/types.ts +0 -96
  107. package/src/__tests__/sqljs-backend.test.ts +0 -410
  108. package/src/migration.ts +0 -574
  109. package/src/sql.js.d.ts +0 -70
  110. package/src/sqljs-backend.ts +0 -789
@@ -1,789 +0,0 @@
1
- /**
2
- * SqlJsBackend - Pure JavaScript SQLite for Windows compatibility
3
- *
4
- * When better-sqlite3 native compilation fails on Windows,
5
- * sql.js provides a WASM-based fallback that works everywhere.
6
- *
7
- * @module @agentkits/memory/sqljs-backend
8
- */
9
-
10
- import { EventEmitter } from 'node:events';
11
- import { readFileSync, writeFileSync, existsSync } from 'node:fs';
12
- import * as path from 'node:path';
13
- import { createRequire } from 'node:module';
14
- import initSqlJs, { Database as SqlJsDatabase } from 'sql.js';
15
- import {
16
- IMemoryBackend,
17
- MemoryEntry,
18
- MemoryEntryInput,
19
- MemoryEntryUpdate,
20
- MemoryQuery,
21
- SearchOptions,
22
- SearchResult,
23
- BackendStats,
24
- HealthCheckResult,
25
- ComponentHealth,
26
- MemoryType,
27
- EmbeddingGenerator,
28
- generateMemoryId,
29
- createDefaultEntry,
30
- } from './types.js';
31
-
32
- /**
33
- * Configuration for SqlJs Backend
34
- */
35
- export interface SqlJsBackendConfig {
36
- /** Path to SQLite database file (:memory: for in-memory) */
37
- databasePath: string;
38
-
39
- /** Enable query optimization */
40
- optimize: boolean;
41
-
42
- /** Default namespace */
43
- defaultNamespace: string;
44
-
45
- /** Embedding generator (for compatibility with hybrid mode) */
46
- embeddingGenerator?: EmbeddingGenerator;
47
-
48
- /** Maximum entries before auto-cleanup */
49
- maxEntries: number;
50
-
51
- /** Enable verbose logging */
52
- verbose: boolean;
53
-
54
- /** Auto-persist interval in milliseconds (0 = manual only) */
55
- autoPersistInterval: number;
56
-
57
- /** Path to sql.js WASM file (optional, will use CDN default) */
58
- wasmPath?: string;
59
- }
60
-
61
- /**
62
- * Default configuration values
63
- */
64
- const DEFAULT_CONFIG: SqlJsBackendConfig = {
65
- databasePath: ':memory:',
66
- optimize: true,
67
- defaultNamespace: 'default',
68
- maxEntries: 1000000,
69
- verbose: false,
70
- autoPersistInterval: 5000, // 5 seconds
71
- };
72
-
73
- /**
74
- * SqlJs Backend for Cross-Platform Memory Storage
75
- *
76
- * Provides:
77
- * - Pure JavaScript/WASM implementation (no native compilation)
78
- * - Windows, macOS, Linux compatibility
79
- * - Same SQL interface as better-sqlite3
80
- * - In-memory with periodic disk persistence
81
- * - Fallback when native SQLite fails
82
- */
83
- export class SqlJsBackend extends EventEmitter implements IMemoryBackend {
84
- private config: SqlJsBackendConfig;
85
- private db: SqlJsDatabase | null = null;
86
- private initialized: boolean = false;
87
- private persistTimer: NodeJS.Timeout | null = null;
88
- private SQL: any = null;
89
-
90
- // Performance tracking
91
- private stats = {
92
- queryCount: 0,
93
- totalQueryTime: 0,
94
- writeCount: 0,
95
- totalWriteTime: 0,
96
- };
97
-
98
- constructor(config: Partial<SqlJsBackendConfig> = {}) {
99
- super();
100
- this.config = { ...DEFAULT_CONFIG, ...config };
101
- }
102
-
103
- /**
104
- * Initialize the SqlJs backend
105
- */
106
- async initialize(): Promise<void> {
107
- if (this.initialized) return;
108
-
109
- // Load sql.js WASM - use local file from node_modules
110
- this.SQL = await initSqlJs({
111
- locateFile: this.config.wasmPath
112
- ? () => this.config.wasmPath!
113
- : (file: string) => {
114
- // Try to find the wasm file in node_modules
115
- try {
116
- const require = createRequire(import.meta.url);
117
- const sqlJsPath = require.resolve('sql.js');
118
- // sql.js resolves to dist/sql.js, so dirname gives us dist/
119
- return path.join(path.dirname(sqlJsPath), file);
120
- } catch {
121
- // Fallback to CDN if local not found
122
- return `https://sql.js.org/dist/${file}`;
123
- }
124
- },
125
- });
126
-
127
- // Load existing database if exists and not in-memory
128
- if (this.config.databasePath !== ':memory:' && existsSync(this.config.databasePath)) {
129
- const buffer = readFileSync(this.config.databasePath);
130
- this.db = new this.SQL.Database(new Uint8Array(buffer));
131
-
132
- if (this.config.verbose) {
133
- console.log(`[SqlJsBackend] Loaded database from ${this.config.databasePath}`);
134
- }
135
- } else {
136
- // Create new database
137
- this.db = new this.SQL.Database();
138
-
139
- if (this.config.verbose) {
140
- console.log('[SqlJsBackend] Created new in-memory database');
141
- }
142
- }
143
-
144
- // Create schema
145
- this.createSchema();
146
-
147
- // Set up auto-persist if enabled
148
- if (this.config.autoPersistInterval > 0 && this.config.databasePath !== ':memory:') {
149
- this.persistTimer = setInterval(() => {
150
- this.persist().catch((err) => {
151
- this.emit('error', { operation: 'auto-persist', error: err });
152
- });
153
- }, this.config.autoPersistInterval);
154
- }
155
-
156
- this.initialized = true;
157
- this.emit('initialized');
158
- }
159
-
160
- /**
161
- * Shutdown the backend
162
- */
163
- async shutdown(): Promise<void> {
164
- if (!this.initialized || !this.db) return;
165
-
166
- // Stop auto-persist timer
167
- if (this.persistTimer) {
168
- clearInterval(this.persistTimer);
169
- this.persistTimer = null;
170
- }
171
-
172
- // Final persist before shutdown
173
- if (this.config.databasePath !== ':memory:') {
174
- await this.persist();
175
- }
176
-
177
- this.db.close();
178
- this.db = null;
179
- this.initialized = false;
180
- this.emit('shutdown');
181
- }
182
-
183
- /**
184
- * Create database schema
185
- */
186
- private createSchema(): void {
187
- if (!this.db) return;
188
-
189
- // Main entries table
190
- this.db.run(`
191
- CREATE TABLE IF NOT EXISTS memory_entries (
192
- id TEXT PRIMARY KEY,
193
- key TEXT NOT NULL,
194
- content TEXT NOT NULL,
195
- embedding BLOB,
196
- type TEXT NOT NULL,
197
- namespace TEXT NOT NULL,
198
- tags TEXT NOT NULL,
199
- metadata TEXT NOT NULL,
200
- owner_id TEXT,
201
- access_level TEXT NOT NULL,
202
- created_at INTEGER NOT NULL,
203
- updated_at INTEGER NOT NULL,
204
- expires_at INTEGER,
205
- version INTEGER NOT NULL DEFAULT 1,
206
- "references" TEXT NOT NULL,
207
- access_count INTEGER NOT NULL DEFAULT 0,
208
- last_accessed_at INTEGER NOT NULL
209
- )
210
- `);
211
-
212
- // Indexes for performance
213
- this.db.run('CREATE INDEX IF NOT EXISTS idx_namespace ON memory_entries(namespace)');
214
- this.db.run('CREATE INDEX IF NOT EXISTS idx_key ON memory_entries(key)');
215
- this.db.run('CREATE INDEX IF NOT EXISTS idx_type ON memory_entries(type)');
216
- this.db.run('CREATE INDEX IF NOT EXISTS idx_created_at ON memory_entries(created_at)');
217
- this.db.run('CREATE INDEX IF NOT EXISTS idx_expires_at ON memory_entries(expires_at)');
218
- this.db.run(
219
- 'CREATE UNIQUE INDEX IF NOT EXISTS idx_namespace_key ON memory_entries(namespace, key)'
220
- );
221
-
222
- if (this.config.verbose) {
223
- console.log('[SqlJsBackend] Schema created successfully');
224
- }
225
- }
226
-
227
- /**
228
- * Store a memory entry
229
- */
230
- async store(entry: MemoryEntry): Promise<void> {
231
- this.ensureInitialized();
232
- const startTime = performance.now();
233
-
234
- const stmt = `
235
- INSERT OR REPLACE INTO memory_entries (
236
- id, key, content, embedding, type, namespace, tags, metadata,
237
- owner_id, access_level, created_at, updated_at, expires_at,
238
- version, "references", access_count, last_accessed_at
239
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
240
- `;
241
-
242
- const embeddingBuffer = entry.embedding
243
- ? Buffer.from(entry.embedding.buffer)
244
- : null;
245
-
246
- this.db!.run(stmt, [
247
- entry.id,
248
- entry.key,
249
- entry.content,
250
- embeddingBuffer,
251
- entry.type,
252
- entry.namespace,
253
- JSON.stringify(entry.tags),
254
- JSON.stringify(entry.metadata),
255
- entry.ownerId || null,
256
- entry.accessLevel,
257
- entry.createdAt,
258
- entry.updatedAt,
259
- entry.expiresAt || null,
260
- entry.version,
261
- JSON.stringify(entry.references),
262
- entry.accessCount,
263
- entry.lastAccessedAt,
264
- ]);
265
-
266
- const duration = performance.now() - startTime;
267
- this.stats.writeCount++;
268
- this.stats.totalWriteTime += duration;
269
-
270
- this.emit('entry:stored', { entry, duration });
271
- }
272
-
273
- /**
274
- * Retrieve a memory entry by ID
275
- */
276
- async get(id: string): Promise<MemoryEntry | null> {
277
- this.ensureInitialized();
278
- const startTime = performance.now();
279
-
280
- const stmt = this.db!.prepare('SELECT * FROM memory_entries WHERE id = ?');
281
- stmt.bind([id]);
282
-
283
- const duration = performance.now() - startTime;
284
- this.stats.queryCount++;
285
- this.stats.totalQueryTime += duration;
286
-
287
- if (!stmt.step()) {
288
- stmt.free();
289
- return null;
290
- }
291
-
292
- const row = stmt.getAsObject();
293
- stmt.free();
294
-
295
- const entry = this.rowToEntry(row);
296
-
297
- // Update access tracking
298
- this.updateAccessTracking(id);
299
-
300
- this.emit('entry:retrieved', { id, duration });
301
- return entry;
302
- }
303
-
304
- /**
305
- * Retrieve a memory entry by key within a namespace
306
- */
307
- async getByKey(namespace: string, key: string): Promise<MemoryEntry | null> {
308
- this.ensureInitialized();
309
- const startTime = performance.now();
310
-
311
- const stmt = this.db!.prepare(
312
- 'SELECT * FROM memory_entries WHERE namespace = ? AND key = ?'
313
- );
314
- stmt.bind([namespace, key]);
315
-
316
- const duration = performance.now() - startTime;
317
- this.stats.queryCount++;
318
- this.stats.totalQueryTime += duration;
319
-
320
- if (!stmt.step()) {
321
- stmt.free();
322
- return null;
323
- }
324
-
325
- const row = stmt.getAsObject();
326
- stmt.free();
327
-
328
- const entry = this.rowToEntry(row);
329
-
330
- // Update access tracking
331
- this.updateAccessTracking(entry.id);
332
-
333
- this.emit('entry:retrieved', { namespace, key, duration });
334
- return entry;
335
- }
336
-
337
- /**
338
- * Update a memory entry
339
- */
340
- async update(id: string, updateData: MemoryEntryUpdate): Promise<MemoryEntry | null> {
341
- this.ensureInitialized();
342
- const startTime = performance.now();
343
-
344
- // Get existing entry
345
- const existing = await this.get(id);
346
- if (!existing) return null;
347
-
348
- // Merge updates
349
- const updated: MemoryEntry = {
350
- ...existing,
351
- ...updateData,
352
- updatedAt: Date.now(),
353
- version: existing.version + 1,
354
- };
355
-
356
- // Store updated entry
357
- await this.store(updated);
358
-
359
- const duration = performance.now() - startTime;
360
- this.emit('entry:updated', { id, update: updateData, duration });
361
-
362
- return updated;
363
- }
364
-
365
- /**
366
- * Delete a memory entry
367
- */
368
- async delete(id: string): Promise<boolean> {
369
- this.ensureInitialized();
370
- const startTime = performance.now();
371
-
372
- this.db!.run('DELETE FROM memory_entries WHERE id = ?', [id]);
373
- const rowsDeleted = this.db!.getRowsModified();
374
-
375
- const duration = performance.now() - startTime;
376
- this.stats.writeCount++;
377
- this.stats.totalWriteTime += duration;
378
-
379
- if (rowsDeleted > 0) {
380
- this.emit('entry:deleted', { id, duration });
381
- return true;
382
- }
383
- return false;
384
- }
385
-
386
- /**
387
- * Query memory entries
388
- */
389
- async query(query: MemoryQuery): Promise<MemoryEntry[]> {
390
- this.ensureInitialized();
391
- const startTime = performance.now();
392
-
393
- let sql = 'SELECT * FROM memory_entries WHERE 1=1';
394
- const params: any[] = [];
395
-
396
- // Namespace filter
397
- if (query.namespace) {
398
- sql += ' AND namespace = ?';
399
- params.push(query.namespace);
400
- }
401
-
402
- // Type filter
403
- if (query.memoryType) {
404
- sql += ' AND type = ?';
405
- params.push(query.memoryType);
406
- }
407
-
408
- // Owner filter
409
- if (query.ownerId) {
410
- sql += ' AND owner_id = ?';
411
- params.push(query.ownerId);
412
- }
413
-
414
- // Access level filter
415
- if (query.accessLevel) {
416
- sql += ' AND access_level = ?';
417
- params.push(query.accessLevel);
418
- }
419
-
420
- // Key filters
421
- if (query.key) {
422
- sql += ' AND key = ?';
423
- params.push(query.key);
424
- } else if (query.keyPrefix) {
425
- sql += ' AND key LIKE ?';
426
- params.push(query.keyPrefix + '%');
427
- }
428
-
429
- // Time range filters
430
- if (query.createdAfter) {
431
- sql += ' AND created_at >= ?';
432
- params.push(query.createdAfter);
433
- }
434
- if (query.createdBefore) {
435
- sql += ' AND created_at <= ?';
436
- params.push(query.createdBefore);
437
- }
438
- if (query.updatedAfter) {
439
- sql += ' AND updated_at >= ?';
440
- params.push(query.updatedAfter);
441
- }
442
- if (query.updatedBefore) {
443
- sql += ' AND updated_at <= ?';
444
- params.push(query.updatedBefore);
445
- }
446
-
447
- // Expiration filter
448
- if (!query.includeExpired) {
449
- sql += ' AND (expires_at IS NULL OR expires_at > ?)';
450
- params.push(Date.now());
451
- }
452
-
453
- // Ordering and pagination
454
- sql += ' ORDER BY created_at DESC';
455
- if (query.limit) {
456
- sql += ' LIMIT ?';
457
- params.push(query.limit);
458
- }
459
- if (query.offset) {
460
- sql += ' OFFSET ?';
461
- params.push(query.offset);
462
- }
463
-
464
- const stmt = this.db!.prepare(sql);
465
- if (params.length > 0) {
466
- stmt.bind(params);
467
- }
468
- const results: MemoryEntry[] = [];
469
-
470
- while (stmt.step()) {
471
- const row = stmt.getAsObject();
472
- const entry = this.rowToEntry(row);
473
-
474
- // Tag filtering (post-query since tags are JSON)
475
- if (query.tags && query.tags.length > 0) {
476
- const hasAllTags = query.tags.every((tag) => entry.tags.includes(tag));
477
- if (!hasAllTags) continue;
478
- }
479
-
480
- // Metadata filtering (post-query since metadata is JSON)
481
- if (query.metadata) {
482
- const matchesMetadata = Object.entries(query.metadata).every(
483
- ([key, value]) => entry.metadata[key] === value
484
- );
485
- if (!matchesMetadata) continue;
486
- }
487
-
488
- results.push(entry);
489
- }
490
-
491
- stmt.free();
492
-
493
- const duration = performance.now() - startTime;
494
- this.stats.queryCount++;
495
- this.stats.totalQueryTime += duration;
496
-
497
- this.emit('query:executed', { query, resultCount: results.length, duration });
498
- return results;
499
- }
500
-
501
- /**
502
- * Semantic vector search (limited without vector index)
503
- */
504
- async search(embedding: Float32Array, options: SearchOptions): Promise<SearchResult[]> {
505
- this.ensureInitialized();
506
-
507
- // Get all entries with embeddings
508
- const entries = await this.query({
509
- type: 'hybrid',
510
- limit: options.filters?.limit || 1000,
511
- });
512
-
513
- // Calculate cosine similarity for each entry
514
- const results: SearchResult[] = [];
515
-
516
- for (const entry of entries) {
517
- if (!entry.embedding) continue;
518
-
519
- const similarity = this.cosineSimilarity(embedding, entry.embedding);
520
-
521
- if (options.threshold && similarity < options.threshold) {
522
- continue;
523
- }
524
-
525
- results.push({
526
- entry,
527
- score: similarity,
528
- distance: 1 - similarity,
529
- });
530
- }
531
-
532
- // Sort by score descending
533
- results.sort((a, b) => b.score - a.score);
534
-
535
- // Return top k results
536
- return results.slice(0, options.k);
537
- }
538
-
539
- /**
540
- * Bulk insert entries
541
- */
542
- async bulkInsert(entries: MemoryEntry[]): Promise<void> {
543
- this.ensureInitialized();
544
-
545
- for (const entry of entries) {
546
- await this.store(entry);
547
- }
548
-
549
- this.emit('bulk:inserted', { count: entries.length });
550
- }
551
-
552
- /**
553
- * Bulk delete entries
554
- */
555
- async bulkDelete(ids: string[]): Promise<number> {
556
- this.ensureInitialized();
557
-
558
- let count = 0;
559
- for (const id of ids) {
560
- const success = await this.delete(id);
561
- if (success) count++;
562
- }
563
-
564
- this.emit('bulk:deleted', { count });
565
- return count;
566
- }
567
-
568
- /**
569
- * Get entry count
570
- */
571
- async count(namespace?: string): Promise<number> {
572
- this.ensureInitialized();
573
-
574
- let sql = 'SELECT COUNT(*) as count FROM memory_entries';
575
- const params: any[] = [];
576
-
577
- if (namespace) {
578
- sql += ' WHERE namespace = ?';
579
- params.push(namespace);
580
- }
581
-
582
- const stmt = this.db!.prepare(sql);
583
- const row = stmt.getAsObject(params);
584
- stmt.free();
585
-
586
- return (row.count as number) || 0;
587
- }
588
-
589
- /**
590
- * List all namespaces
591
- */
592
- async listNamespaces(): Promise<string[]> {
593
- this.ensureInitialized();
594
-
595
- const stmt = this.db!.prepare('SELECT DISTINCT namespace FROM memory_entries');
596
- const namespaces: string[] = [];
597
-
598
- while (stmt.step()) {
599
- const row = stmt.getAsObject();
600
- namespaces.push(row.namespace as string);
601
- }
602
-
603
- stmt.free();
604
- return namespaces;
605
- }
606
-
607
- /**
608
- * Clear all entries in a namespace
609
- */
610
- async clearNamespace(namespace: string): Promise<number> {
611
- this.ensureInitialized();
612
-
613
- const countBefore = await this.count(namespace);
614
- this.db!.run('DELETE FROM memory_entries WHERE namespace = ?', [namespace]);
615
-
616
- this.emit('namespace:cleared', { namespace, count: countBefore });
617
- return countBefore;
618
- }
619
-
620
- /**
621
- * Get backend statistics
622
- */
623
- async getStats(): Promise<BackendStats> {
624
- this.ensureInitialized();
625
-
626
- const total = await this.count();
627
-
628
- // Count by namespace
629
- const entriesByNamespace: Record<string, number> = {};
630
- const namespaces = await this.listNamespaces();
631
- for (const ns of namespaces) {
632
- entriesByNamespace[ns] = await this.count(ns);
633
- }
634
-
635
- // Count by type
636
- const entriesByType: Record<MemoryType, number> = {} as any;
637
- const types: MemoryType[] = ['episodic', 'semantic', 'procedural', 'working', 'cache'];
638
- for (const type of types) {
639
- const stmt = this.db!.prepare('SELECT COUNT(*) as count FROM memory_entries WHERE type = ?');
640
- const row = stmt.getAsObject([type]);
641
- stmt.free();
642
- entriesByType[type] = (row.count as number) || 0;
643
- }
644
-
645
- return {
646
- totalEntries: total,
647
- entriesByNamespace,
648
- entriesByType,
649
- memoryUsage: this.estimateMemoryUsage(),
650
- avgQueryTime: this.stats.queryCount > 0 ? this.stats.totalQueryTime / this.stats.queryCount : 0,
651
- avgSearchTime: 0, // Not tracked separately
652
- };
653
- }
654
-
655
- /**
656
- * Perform health check
657
- */
658
- async healthCheck(): Promise<HealthCheckResult> {
659
- const issues: string[] = [];
660
- const recommendations: string[] = [];
661
-
662
- // Storage health
663
- const storageStart = performance.now();
664
- const storageHealthy = this.db !== null;
665
- const storageLatency = performance.now() - storageStart;
666
-
667
- if (!storageHealthy) {
668
- issues.push('Database not initialized');
669
- }
670
-
671
- // Index health (sql.js doesn't have native vector index)
672
- const indexHealth: ComponentHealth = {
673
- status: 'healthy',
674
- latency: 0,
675
- message: 'No vector index (brute-force search)',
676
- };
677
-
678
- recommendations.push('Consider using better-sqlite3 with HNSW for faster vector search');
679
-
680
- // Cache health (not applicable for sql.js)
681
- const cacheHealth: ComponentHealth = {
682
- status: 'healthy',
683
- latency: 0,
684
- message: 'No separate cache layer',
685
- };
686
-
687
- const status = issues.length === 0 ? 'healthy' : 'degraded';
688
-
689
- return {
690
- status,
691
- components: {
692
- storage: {
693
- status: storageHealthy ? 'healthy' : 'unhealthy',
694
- latency: storageLatency,
695
- },
696
- index: indexHealth,
697
- cache: cacheHealth,
698
- },
699
- timestamp: Date.now(),
700
- issues,
701
- recommendations,
702
- };
703
- }
704
-
705
- /**
706
- * Persist changes to disk (sql.js is in-memory, needs explicit save)
707
- */
708
- async persist(): Promise<void> {
709
- if (!this.db || this.config.databasePath === ':memory:') {
710
- return;
711
- }
712
-
713
- const data = this.db.export();
714
- const buffer = Buffer.from(data);
715
-
716
- writeFileSync(this.config.databasePath, buffer);
717
-
718
- if (this.config.verbose) {
719
- console.log(`[SqlJsBackend] Persisted ${buffer.length} bytes to ${this.config.databasePath}`);
720
- }
721
-
722
- this.emit('persisted', { size: buffer.length, path: this.config.databasePath });
723
- }
724
-
725
- // ===== Helper Methods =====
726
-
727
- private ensureInitialized(): void {
728
- if (!this.initialized || !this.db) {
729
- throw new Error('SqlJsBackend not initialized. Call initialize() first.');
730
- }
731
- }
732
-
733
- private rowToEntry(row: any): MemoryEntry {
734
- return {
735
- id: row.id as string,
736
- key: row.key as string,
737
- content: row.content as string,
738
- embedding: row.embedding
739
- ? new Float32Array(new Uint8Array(row.embedding as Uint8Array).buffer)
740
- : undefined,
741
- type: row.type as MemoryType,
742
- namespace: row.namespace as string,
743
- tags: JSON.parse(row.tags as string),
744
- metadata: JSON.parse(row.metadata as string),
745
- ownerId: row.owner_id as string | undefined,
746
- accessLevel: row.access_level as any,
747
- createdAt: row.created_at as number,
748
- updatedAt: row.updated_at as number,
749
- expiresAt: row.expires_at as number | undefined,
750
- version: row.version as number,
751
- references: JSON.parse(row.references as string),
752
- accessCount: row.access_count as number,
753
- lastAccessedAt: row.last_accessed_at as number,
754
- };
755
- }
756
-
757
- private updateAccessTracking(id: string): void {
758
- if (!this.db) return;
759
-
760
- this.db.run(
761
- 'UPDATE memory_entries SET access_count = access_count + 1, last_accessed_at = ? WHERE id = ?',
762
- [Date.now(), id]
763
- );
764
- }
765
-
766
- private cosineSimilarity(a: Float32Array, b: Float32Array): number {
767
- let dotProduct = 0;
768
- let normA = 0;
769
- let normB = 0;
770
-
771
- for (let i = 0; i < a.length; i++) {
772
- dotProduct += a[i] * b[i];
773
- normA += a[i] * a[i];
774
- normB += b[i] * b[i];
775
- }
776
-
777
- if (normA === 0 || normB === 0) return 0;
778
-
779
- return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
780
- }
781
-
782
- private estimateMemoryUsage(): number {
783
- if (!this.db) return 0;
784
-
785
- // Export to get size
786
- const data = this.db.export();
787
- return data.length;
788
- }
789
- }