@claude-flow/memory 3.0.0-alpha.1 → 3.0.0-alpha.11

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