web-agent-bridge 2.2.0 → 2.3.1

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 (39) hide show
  1. package/README.ar.md +7 -0
  2. package/README.md +7 -0
  3. package/package.json +12 -4
  4. package/public/commander-dashboard.html +243 -0
  5. package/public/css/premium.css +317 -317
  6. package/public/demo.html +259 -259
  7. package/public/index.html +644 -592
  8. package/public/llms.txt +1 -0
  9. package/public/mesh-dashboard.html +328 -0
  10. package/public/premium-dashboard.html +2487 -2487
  11. package/public/premium.html +791 -791
  12. package/public/script/wab.min.js +181 -6
  13. package/script/ai-agent-bridge.js +196 -0
  14. package/sdk/agent-mesh.js +449 -0
  15. package/sdk/commander.js +262 -0
  16. package/sdk/index.js +260 -259
  17. package/sdk/package.json +1 -1
  18. package/server/index.js +13 -1
  19. package/server/migrations/002_premium_features.sql +418 -418
  20. package/server/models/db.js +24 -5
  21. package/server/routes/admin-premium.js +671 -671
  22. package/server/routes/commander.js +316 -0
  23. package/server/routes/mesh.js +469 -0
  24. package/server/routes/premium-v2.js +686 -686
  25. package/server/routes/premium.js +724 -724
  26. package/server/services/agent-learning.js +575 -0
  27. package/server/services/agent-memory.js +625 -625
  28. package/server/services/agent-mesh.js +539 -0
  29. package/server/services/agent-symphony.js +711 -0
  30. package/server/services/commander.js +738 -0
  31. package/server/services/edge-compute.js +440 -0
  32. package/server/services/local-ai.js +389 -0
  33. package/server/services/plugins.js +747 -747
  34. package/server/services/self-healing.js +843 -843
  35. package/server/services/swarm.js +788 -788
  36. package/server/services/vision.js +871 -871
  37. package/public/admin/dashboard.html +0 -848
  38. package/public/admin/login.html +0 -84
  39. package/public/video/tutorial.mp4 +0 -0
@@ -1,625 +1,625 @@
1
- 'use strict';
2
-
3
- const { db } = require('../models/db');
4
- const { randomUUID } = require('crypto');
5
-
6
- // ─── Schema ──────────────────────────────────────────────────────────────────
7
-
8
- db.exec(`
9
- CREATE TABLE IF NOT EXISTS agent_memories (
10
- id TEXT PRIMARY KEY,
11
- site_id TEXT NOT NULL,
12
- agent_id TEXT NOT NULL,
13
- memory_type TEXT CHECK(memory_type IN ('preference','interaction','correction','pattern')),
14
- category TEXT CHECK(category IN ('navigation','purchase','search','form','custom')),
15
- key TEXT NOT NULL,
16
- value TEXT NOT NULL,
17
- embedding TEXT,
18
- importance REAL DEFAULT 0.5,
19
- access_count INTEGER DEFAULT 0,
20
- last_accessed TEXT,
21
- expires_at TEXT,
22
- created_at TEXT DEFAULT (datetime('now')),
23
- updated_at TEXT DEFAULT (datetime('now')),
24
- FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
25
- );
26
-
27
- CREATE TABLE IF NOT EXISTS memory_sessions (
28
- id TEXT PRIMARY KEY,
29
- site_id TEXT,
30
- agent_id TEXT,
31
- context TEXT,
32
- started_at TEXT DEFAULT (datetime('now')),
33
- ended_at TEXT
34
- );
35
-
36
- CREATE TABLE IF NOT EXISTS memory_associations (
37
- id TEXT PRIMARY KEY,
38
- source_memory_id TEXT,
39
- target_memory_id TEXT,
40
- relationship TEXT CHECK(relationship IN ('leads_to','similar_to','replaces','depends_on')),
41
- strength REAL DEFAULT 0.5,
42
- created_at TEXT DEFAULT (datetime('now')),
43
- FOREIGN KEY (source_memory_id) REFERENCES agent_memories(id) ON DELETE CASCADE,
44
- FOREIGN KEY (target_memory_id) REFERENCES agent_memories(id) ON DELETE CASCADE
45
- );
46
-
47
- CREATE INDEX IF NOT EXISTS idx_mem_site ON agent_memories(site_id);
48
- CREATE INDEX IF NOT EXISTS idx_mem_agent ON agent_memories(agent_id);
49
- CREATE INDEX IF NOT EXISTS idx_mem_type ON agent_memories(memory_type);
50
- CREATE INDEX IF NOT EXISTS idx_mem_category ON agent_memories(category);
51
- CREATE INDEX IF NOT EXISTS idx_mem_importance ON agent_memories(importance);
52
- CREATE INDEX IF NOT EXISTS idx_mem_sessions_site ON memory_sessions(site_id);
53
- CREATE INDEX IF NOT EXISTS idx_mem_sessions_agent ON memory_sessions(agent_id);
54
- CREATE INDEX IF NOT EXISTS idx_mem_assoc_source ON memory_associations(source_memory_id);
55
- CREATE INDEX IF NOT EXISTS idx_mem_assoc_target ON memory_associations(target_memory_id);
56
- `);
57
-
58
- // ─── Prepared Statements ─────────────────────────────────────────────────────
59
-
60
- const stmts = {
61
- insertMemory: db.prepare(`
62
- INSERT INTO agent_memories (id, site_id, agent_id, memory_type, category, key, value, embedding, importance, expires_at)
63
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
64
- `),
65
- getMemory: db.prepare(`SELECT * FROM agent_memories WHERE id = ?`),
66
- queryMemories: db.prepare(`
67
- SELECT * FROM agent_memories
68
- WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
69
- ORDER BY importance DESC, updated_at DESC
70
- `),
71
- queryByCategory: db.prepare(`
72
- SELECT * FROM agent_memories
73
- WHERE site_id = ? AND agent_id = ? AND category = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
74
- ORDER BY importance DESC, updated_at DESC
75
- `),
76
- queryByType: db.prepare(`
77
- SELECT * FROM agent_memories
78
- WHERE site_id = ? AND agent_id = ? AND memory_type = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
79
- ORDER BY importance DESC, updated_at DESC
80
- `),
81
- queryByCategoryAndType: db.prepare(`
82
- SELECT * FROM agent_memories
83
- WHERE site_id = ? AND agent_id = ? AND category = ? AND memory_type = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
84
- ORDER BY importance DESC, updated_at DESC
85
- `),
86
- touchMemory: db.prepare(`
87
- UPDATE agent_memories SET access_count = access_count + 1, last_accessed = datetime('now') WHERE id = ?
88
- `),
89
- softDelete: db.prepare(`
90
- UPDATE agent_memories SET expires_at = datetime('now'), updated_at = datetime('now') WHERE id = ?
91
- `),
92
- updateImportance: db.prepare(`
93
- UPDATE agent_memories SET importance = ?, updated_at = datetime('now') WHERE id = ?
94
- `),
95
- deleteExpired: db.prepare(`
96
- DELETE FROM agent_memories WHERE expires_at IS NOT NULL AND expires_at <= datetime('now')
97
- `),
98
- findDuplicates: db.prepare(`
99
- SELECT key, category, COUNT(*) as cnt, GROUP_CONCAT(id) as ids
100
- FROM agent_memories
101
- WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
102
- GROUP BY key, category HAVING cnt > 1
103
- `),
104
- deleteMemoryById: db.prepare(`DELETE FROM agent_memories WHERE id = ?`),
105
-
106
- insertAssociation: db.prepare(`
107
- INSERT INTO memory_associations (id, source_memory_id, target_memory_id, relationship, strength)
108
- VALUES (?, ?, ?, ?, ?)
109
- `),
110
- getAssociationsFrom: db.prepare(`
111
- SELECT ma.*, am.key, am.value, am.memory_type, am.category, am.importance
112
- FROM memory_associations ma
113
- JOIN agent_memories am ON am.id = ma.target_memory_id
114
- WHERE ma.source_memory_id = ?
115
- ORDER BY ma.strength DESC
116
- `),
117
- getAssociationsFromFiltered: db.prepare(`
118
- SELECT ma.*, am.key, am.value, am.memory_type, am.category, am.importance
119
- FROM memory_associations ma
120
- JOIN agent_memories am ON am.id = ma.target_memory_id
121
- WHERE ma.source_memory_id = ? AND ma.relationship = ?
122
- ORDER BY ma.strength DESC
123
- `),
124
-
125
- insertSession: db.prepare(`
126
- INSERT INTO memory_sessions (id, site_id, agent_id, context) VALUES (?, ?, ?, ?)
127
- `),
128
- endSession: db.prepare(`
129
- UPDATE memory_sessions SET ended_at = datetime('now'), context = json_patch(COALESCE(context, '{}'), ?) WHERE id = ?
130
- `),
131
- getSessionHistory: db.prepare(`
132
- SELECT * FROM memory_sessions WHERE site_id = ? AND agent_id = ? ORDER BY started_at DESC LIMIT ?
133
- `),
134
-
135
- countAll: db.prepare(`
136
- SELECT COUNT(*) as total FROM agent_memories WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
137
- `),
138
- countByType: db.prepare(`
139
- SELECT memory_type, COUNT(*) as count FROM agent_memories
140
- WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
141
- GROUP BY memory_type
142
- `),
143
- countByCategory: db.prepare(`
144
- SELECT category, COUNT(*) as count FROM agent_memories
145
- WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
146
- GROUP BY category
147
- `),
148
- avgImportance: db.prepare(`
149
- SELECT AVG(importance) as avg FROM agent_memories
150
- WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
151
- `),
152
- storageEstimate: db.prepare(`
153
- SELECT SUM(LENGTH(key) + LENGTH(value) + COALESCE(LENGTH(embedding), 0)) as bytes
154
- FROM agent_memories WHERE site_id = ? AND agent_id = ?
155
- `),
156
-
157
- allActiveMemories: db.prepare(`
158
- SELECT * FROM agent_memories
159
- WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
160
- ORDER BY created_at ASC
161
- `),
162
- getPreferences: db.prepare(`
163
- SELECT * FROM agent_memories
164
- WHERE site_id = ? AND agent_id = ? AND memory_type = 'preference' AND (expires_at IS NULL OR expires_at > datetime('now'))
165
- ORDER BY importance DESC
166
- `),
167
- findPreference: db.prepare(`
168
- SELECT * FROM agent_memories
169
- WHERE site_id = ? AND agent_id = ? AND memory_type = 'preference' AND key = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
170
- LIMIT 1
171
- `),
172
- updateMemoryValue: db.prepare(`
173
- UPDATE agent_memories SET value = ?, embedding = ?, importance = ?, updated_at = datetime('now') WHERE id = ?
174
- `),
175
- };
176
-
177
- // ─── Vector Utilities ────────────────────────────────────────────────────────
178
-
179
- const EMBED_DIM = 128;
180
-
181
- /**
182
- * Tokenizes text into lowercase alphanumeric tokens.
183
- * @param {string} text
184
- * @returns {string[]}
185
- */
186
- function tokenize(text) {
187
- return String(text).toLowerCase().match(/[a-z0-9]+/g) || [];
188
- }
189
-
190
- /**
191
- * Deterministic hash of a string to a 32-bit unsigned integer.
192
- * @param {string} str
193
- * @returns {number}
194
- */
195
- function hashStr(str) {
196
- let h = 0x811c9dc5;
197
- for (let i = 0; i < str.length; i++) {
198
- h ^= str.charCodeAt(i);
199
- h = Math.imul(h, 0x01000193);
200
- }
201
- return h >>> 0;
202
- }
203
-
204
- /**
205
- * Computes a TF-IDF-style embedding: hashes tokens into a fixed-size vector and L2-normalizes.
206
- * @param {string} text
207
- * @returns {number[]} 128-dimensional unit vector
208
- */
209
- function computeEmbedding(text) {
210
- const tokens = tokenize(text);
211
- const vec = new Float64Array(EMBED_DIM);
212
- if (tokens.length === 0) return Array.from(vec);
213
-
214
- const tf = {};
215
- for (const t of tokens) tf[t] = (tf[t] || 0) + 1;
216
-
217
- for (const [token, count] of Object.entries(tf)) {
218
- const idx = hashStr(token) % EMBED_DIM;
219
- const sign = (hashStr(token + '_sign') & 1) ? 1 : -1;
220
- const weight = (1 + Math.log(count)) * sign;
221
- vec[idx] += weight;
222
- }
223
-
224
- let norm = 0;
225
- for (let i = 0; i < EMBED_DIM; i++) norm += vec[i] * vec[i];
226
- norm = Math.sqrt(norm);
227
- if (norm > 0) for (let i = 0; i < EMBED_DIM; i++) vec[i] /= norm;
228
-
229
- return Array.from(vec);
230
- }
231
-
232
- /**
233
- * Standard cosine similarity between two equal-length vectors.
234
- * @param {number[]} a
235
- * @param {number[]} b
236
- * @returns {number} similarity in [-1, 1]
237
- */
238
- function cosineSimilarity(a, b) {
239
- if (!a || !b || a.length !== b.length) return 0;
240
- let dot = 0, normA = 0, normB = 0;
241
- for (let i = 0; i < a.length; i++) {
242
- dot += a[i] * b[i];
243
- normA += a[i] * a[i];
244
- normB += b[i] * b[i];
245
- }
246
- const denom = Math.sqrt(normA) * Math.sqrt(normB);
247
- return denom === 0 ? 0 : dot / denom;
248
- }
249
-
250
- // ─── Core Memory Operations ──────────────────────────────────────────────────
251
-
252
- /**
253
- * Stores a memory entry for an agent on a site.
254
- * @param {string} siteId
255
- * @param {string} agentId
256
- * @param {{ type?: string, category?: string, key: string, value: any, importance?: number, ttlSeconds?: number }} opts
257
- * @returns {object} the stored memory row
258
- */
259
- function storeMemory(siteId, agentId, { type, category, key, value, importance, ttlSeconds }) {
260
- const id = randomUUID();
261
- const jsonValue = typeof value === 'string' ? value : JSON.stringify(value);
262
- const embedding = computeEmbedding(`${key} ${typeof value === 'string' ? value : JSON.stringify(value)}`);
263
- const expiresAt = ttlSeconds
264
- ? new Date(Date.now() + ttlSeconds * 1000).toISOString().replace('T', ' ').slice(0, 19)
265
- : null;
266
-
267
- stmts.insertMemory.run(
268
- id, siteId, agentId,
269
- type || null, category || null,
270
- key, jsonValue,
271
- JSON.stringify(embedding),
272
- importance ?? 0.5,
273
- expiresAt
274
- );
275
-
276
- return stmts.getMemory.get(id);
277
- }
278
-
279
- /**
280
- * Recalls memories matching filters, optionally ranked by semantic similarity.
281
- * @param {string} siteId
282
- * @param {string} agentId
283
- * @param {{ query?: string, category?: string, type?: string, limit?: number, minImportance?: number }} opts
284
- * @returns {object[]}
285
- */
286
- function recallMemories(siteId, agentId, { query, category, type, limit, minImportance } = {}) {
287
- let rows;
288
- if (category && type) {
289
- rows = stmts.queryByCategoryAndType.all(siteId, agentId, category, type);
290
- } else if (category) {
291
- rows = stmts.queryByCategory.all(siteId, agentId, category);
292
- } else if (type) {
293
- rows = stmts.queryByType.all(siteId, agentId, type);
294
- } else {
295
- rows = stmts.queryMemories.all(siteId, agentId);
296
- }
297
-
298
- if (minImportance != null) {
299
- rows = rows.filter(r => r.importance >= minImportance);
300
- }
301
-
302
- if (query) {
303
- const queryEmbed = computeEmbedding(query);
304
- rows = rows.map(r => {
305
- const memEmbed = r.embedding ? JSON.parse(r.embedding) : null;
306
- const similarity = memEmbed ? cosineSimilarity(queryEmbed, memEmbed) : 0;
307
- return { ...r, similarity };
308
- });
309
- rows.sort((a, b) => b.similarity - a.similarity);
310
- }
311
-
312
- const maxRows = limit || 20;
313
- rows = rows.slice(0, maxRows);
314
-
315
- const touchTx = db.transaction((ids) => {
316
- for (const id of ids) stmts.touchMemory.run(id);
317
- });
318
- touchTx(rows.map(r => r.id));
319
-
320
- return rows;
321
- }
322
-
323
- // ─── Associations ────────────────────────────────────────────────────────────
324
-
325
- /**
326
- * Creates a directional link between two memories.
327
- * @param {string} sourceId
328
- * @param {string} targetId
329
- * @param {string} relationship - leads_to | similar_to | replaces | depends_on
330
- * @param {number} [strength=0.5]
331
- * @returns {object}
332
- */
333
- function associateMemories(sourceId, targetId, relationship, strength = 0.5) {
334
- const id = randomUUID();
335
- stmts.insertAssociation.run(id, sourceId, targetId, relationship, strength);
336
- return { id, sourceId, targetId, relationship, strength };
337
- }
338
-
339
- /**
340
- * Retrieves memories associated with a given memory.
341
- * @param {string} memoryId
342
- * @param {{ relationship?: string, minStrength?: number }} [opts]
343
- * @returns {object[]}
344
- */
345
- function getAssociatedMemories(memoryId, { relationship, minStrength } = {}) {
346
- let rows;
347
- if (relationship) {
348
- rows = stmts.getAssociationsFromFiltered.all(memoryId, relationship);
349
- } else {
350
- rows = stmts.getAssociationsFrom.all(memoryId);
351
- }
352
- if (minStrength != null) {
353
- rows = rows.filter(r => r.strength >= minStrength);
354
- }
355
- return rows;
356
- }
357
-
358
- // ─── Lifecycle ───────────────────────────────────────────────────────────────
359
-
360
- /**
361
- * Soft-deletes a memory by setting its expiration to now.
362
- * @param {string} memoryId
363
- * @returns {boolean}
364
- */
365
- function forgetMemory(memoryId) {
366
- const info = stmts.softDelete.run(memoryId);
367
- return info.changes > 0;
368
- }
369
-
370
- /**
371
- * Consolidates memories: merges duplicates, adjusts importance, purges expired.
372
- * @param {string} siteId
373
- * @param {string} agentId
374
- * @returns {{ merged: number, boosted: number, decayed: number, expired: number }}
375
- */
376
- function consolidateMemories(siteId, agentId) {
377
- const stats = { merged: 0, boosted: 0, decayed: 0, expired: 0 };
378
-
379
- const expiredInfo = stmts.deleteExpired.run();
380
- stats.expired = expiredInfo.changes;
381
-
382
- const dupes = stmts.findDuplicates.all(siteId, agentId);
383
- const mergeTx = db.transaction(() => {
384
- for (const group of dupes) {
385
- const ids = group.ids.split(',');
386
- const memories = ids.map(id => stmts.getMemory.get(id)).filter(Boolean);
387
- if (memories.length < 2) continue;
388
-
389
- memories.sort((a, b) => b.access_count - a.access_count || b.importance - a.importance);
390
- const keeper = memories[0];
391
-
392
- let mergedValues;
393
- try {
394
- const parsed = memories.map(m => JSON.parse(m.value));
395
- if (typeof parsed[0] === 'object' && parsed[0] !== null && !Array.isArray(parsed[0])) {
396
- mergedValues = JSON.stringify(Object.assign({}, ...parsed.reverse()));
397
- } else {
398
- mergedValues = keeper.value;
399
- }
400
- } catch {
401
- mergedValues = keeper.value;
402
- }
403
-
404
- const newImportance = Math.min(1, keeper.importance + 0.05 * (memories.length - 1));
405
- const newEmbedding = computeEmbedding(`${keeper.key} ${mergedValues}`);
406
- stmts.updateMemoryValue.run(mergedValues, JSON.stringify(newEmbedding), newImportance, keeper.id);
407
-
408
- for (let i = 1; i < memories.length; i++) {
409
- stmts.deleteMemoryById.run(memories[i].id);
410
- stats.merged++;
411
- }
412
- }
413
- });
414
- mergeTx();
415
-
416
- const active = stmts.allActiveMemories.all(siteId, agentId);
417
- const now = Date.now();
418
-
419
- const adjustTx = db.transaction(() => {
420
- for (const mem of active) {
421
- const ageMs = now - new Date(mem.created_at).getTime();
422
- const ageDays = ageMs / 86400000;
423
-
424
- if (mem.access_count >= 5) {
425
- const boost = Math.min(1, mem.importance + 0.02 * Math.log2(mem.access_count));
426
- if (boost > mem.importance) {
427
- stmts.updateImportance.run(Math.min(1, boost), mem.id);
428
- stats.boosted++;
429
- }
430
- }
431
-
432
- if (ageDays > 30 && mem.access_count < 3) {
433
- const decayFactor = Math.max(0.1, 1 - 0.01 * (ageDays - 30));
434
- const decayed = mem.importance * decayFactor;
435
- if (decayed < mem.importance) {
436
- stmts.updateImportance.run(Math.max(0, decayed), mem.id);
437
- stats.decayed++;
438
- }
439
- }
440
- }
441
- });
442
- adjustTx();
443
-
444
- return stats;
445
- }
446
-
447
- // ─── Stats ───────────────────────────────────────────────────────────────────
448
-
449
- /**
450
- * Returns aggregate statistics for an agent's memories on a site.
451
- * @param {string} siteId
452
- * @param {string} agentId
453
- * @returns {object}
454
- */
455
- function getMemoryStats(siteId, agentId) {
456
- const total = stmts.countAll.get(siteId, agentId).total;
457
- const byType = stmts.countByType.all(siteId, agentId);
458
- const byCategory = stmts.countByCategory.all(siteId, agentId);
459
- const avgImportance = stmts.avgImportance.get(siteId, agentId).avg || 0;
460
- const storageBytes = stmts.storageEstimate.get(siteId, agentId).bytes || 0;
461
-
462
- return {
463
- total,
464
- byType: Object.fromEntries(byType.map(r => [r.memory_type, r.count])),
465
- byCategory: Object.fromEntries(byCategory.map(r => [r.category, r.count])),
466
- avgImportance: Math.round(avgImportance * 1000) / 1000,
467
- storageEstimateBytes: storageBytes,
468
- };
469
- }
470
-
471
- // ─── Sessions ────────────────────────────────────────────────────────────────
472
-
473
- /**
474
- * Starts an agent memory session.
475
- * @param {string} siteId
476
- * @param {string} agentId
477
- * @param {object} [context]
478
- * @returns {{ id: string, siteId: string, agentId: string, startedAt: string }}
479
- */
480
- function startSession(siteId, agentId, context = {}) {
481
- const id = randomUUID();
482
- stmts.insertSession.run(id, siteId, agentId, JSON.stringify(context));
483
- return { id, siteId, agentId, startedAt: new Date().toISOString() };
484
- }
485
-
486
- /**
487
- * Ends a session, optionally attaching a summary to the context.
488
- * @param {string} sessionId
489
- * @param {string} [summary]
490
- * @returns {boolean}
491
- */
492
- function endSession(sessionId, summary) {
493
- const patch = summary ? JSON.stringify({ summary }) : '{}';
494
- const info = stmts.endSession.run(patch, sessionId);
495
- return info.changes > 0;
496
- }
497
-
498
- /**
499
- * Returns recent sessions for a site/agent pair.
500
- * @param {string} siteId
501
- * @param {string} agentId
502
- * @param {{ limit?: number }} [opts]
503
- * @returns {object[]}
504
- */
505
- function getSessionHistory(siteId, agentId, { limit } = {}) {
506
- return stmts.getSessionHistory.all(siteId, agentId, limit || 20);
507
- }
508
-
509
- // ─── Import / Export ─────────────────────────────────────────────────────────
510
-
511
- /**
512
- * Exports all active memories as JSON or CSV.
513
- * @param {string} siteId
514
- * @param {string} agentId
515
- * @param {{ format?: 'json'|'csv' }} [opts]
516
- * @returns {string}
517
- */
518
- function exportMemories(siteId, agentId, { format } = {}) {
519
- const rows = stmts.allActiveMemories.all(siteId, agentId);
520
-
521
- if (format === 'csv') {
522
- const cols = ['id', 'site_id', 'agent_id', 'memory_type', 'category', 'key', 'value', 'importance', 'access_count', 'created_at', 'updated_at'];
523
- const escape = (v) => `"${String(v == null ? '' : v).replace(/"/g, '""')}"`;
524
- const header = cols.join(',');
525
- const lines = rows.map(r => cols.map(c => escape(r[c])).join(','));
526
- return [header, ...lines].join('\n');
527
- }
528
-
529
- return JSON.stringify(rows, null, 2);
530
- }
531
-
532
- /**
533
- * Bulk-imports memories from an array of objects.
534
- * @param {string} siteId
535
- * @param {string} agentId
536
- * @param {object[]} data
537
- * @returns {{ imported: number }}
538
- */
539
- function importMemories(siteId, agentId, data) {
540
- let imported = 0;
541
- const tx = db.transaction(() => {
542
- for (const item of data) {
543
- const id = item.id || randomUUID();
544
- const jsonValue = typeof item.value === 'string' ? item.value : JSON.stringify(item.value);
545
- const embedding = item.embedding
546
- ? (typeof item.embedding === 'string' ? item.embedding : JSON.stringify(item.embedding))
547
- : JSON.stringify(computeEmbedding(`${item.key} ${jsonValue}`));
548
-
549
- stmts.insertMemory.run(
550
- id, siteId, agentId,
551
- item.type || item.memory_type || null,
552
- item.category || null,
553
- item.key,
554
- jsonValue,
555
- embedding,
556
- item.importance ?? 0.5,
557
- item.expires_at || null
558
- );
559
- imported++;
560
- }
561
- });
562
- tx();
563
- return { imported };
564
- }
565
-
566
- // ─── Preference Shortcuts ────────────────────────────────────────────────────
567
-
568
- /**
569
- * Returns all 'preference' type memories for a site/agent.
570
- * @param {string} siteId
571
- * @param {string} agentId
572
- * @returns {object[]}
573
- */
574
- function getPreferences(siteId, agentId) {
575
- return stmts.getPreferences.all(siteId, agentId);
576
- }
577
-
578
- /**
579
- * Stores or updates a preference memory. Upserts if the same key exists.
580
- * @param {string} siteId
581
- * @param {string} agentId
582
- * @param {string} key
583
- * @param {any} value
584
- * @returns {object}
585
- */
586
- function recordPreference(siteId, agentId, key, value) {
587
- const existing = stmts.findPreference.get(siteId, agentId, key);
588
- const jsonValue = typeof value === 'string' ? value : JSON.stringify(value);
589
- const embedding = computeEmbedding(`${key} ${jsonValue}`);
590
-
591
- if (existing) {
592
- const newImportance = Math.min(1, existing.importance + 0.05);
593
- stmts.updateMemoryValue.run(jsonValue, JSON.stringify(embedding), newImportance, existing.id);
594
- return stmts.getMemory.get(existing.id);
595
- }
596
-
597
- return storeMemory(siteId, agentId, {
598
- type: 'preference',
599
- category: 'custom',
600
- key,
601
- value: jsonValue,
602
- importance: 0.7,
603
- });
604
- }
605
-
606
- // ─── Exports ─────────────────────────────────────────────────────────────────
607
-
608
- module.exports = {
609
- storeMemory,
610
- recallMemories,
611
- computeEmbedding,
612
- cosineSimilarity,
613
- associateMemories,
614
- getAssociatedMemories,
615
- forgetMemory,
616
- consolidateMemories,
617
- getMemoryStats,
618
- startSession,
619
- endSession,
620
- getSessionHistory,
621
- exportMemories,
622
- importMemories,
623
- getPreferences,
624
- recordPreference,
625
- };
1
+ 'use strict';
2
+
3
+ const { db } = require('../models/db');
4
+ const { randomUUID } = require('crypto');
5
+
6
+ // ─── Schema ──────────────────────────────────────────────────────────────────
7
+
8
+ db.exec(`
9
+ CREATE TABLE IF NOT EXISTS agent_memories (
10
+ id TEXT PRIMARY KEY,
11
+ site_id TEXT NOT NULL,
12
+ agent_id TEXT NOT NULL,
13
+ memory_type TEXT CHECK(memory_type IN ('preference','interaction','correction','pattern')),
14
+ category TEXT CHECK(category IN ('navigation','purchase','search','form','custom')),
15
+ key TEXT NOT NULL,
16
+ value TEXT NOT NULL,
17
+ embedding TEXT,
18
+ importance REAL DEFAULT 0.5,
19
+ access_count INTEGER DEFAULT 0,
20
+ last_accessed TEXT,
21
+ expires_at TEXT,
22
+ created_at TEXT DEFAULT (datetime('now')),
23
+ updated_at TEXT DEFAULT (datetime('now')),
24
+ FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
25
+ );
26
+
27
+ CREATE TABLE IF NOT EXISTS memory_sessions (
28
+ id TEXT PRIMARY KEY,
29
+ site_id TEXT,
30
+ agent_id TEXT,
31
+ context TEXT,
32
+ started_at TEXT DEFAULT (datetime('now')),
33
+ ended_at TEXT
34
+ );
35
+
36
+ CREATE TABLE IF NOT EXISTS memory_associations (
37
+ id TEXT PRIMARY KEY,
38
+ source_memory_id TEXT,
39
+ target_memory_id TEXT,
40
+ relationship TEXT CHECK(relationship IN ('leads_to','similar_to','replaces','depends_on')),
41
+ strength REAL DEFAULT 0.5,
42
+ created_at TEXT DEFAULT (datetime('now')),
43
+ FOREIGN KEY (source_memory_id) REFERENCES agent_memories(id) ON DELETE CASCADE,
44
+ FOREIGN KEY (target_memory_id) REFERENCES agent_memories(id) ON DELETE CASCADE
45
+ );
46
+
47
+ CREATE INDEX IF NOT EXISTS idx_mem_site ON agent_memories(site_id);
48
+ CREATE INDEX IF NOT EXISTS idx_mem_agent ON agent_memories(agent_id);
49
+ CREATE INDEX IF NOT EXISTS idx_mem_type ON agent_memories(memory_type);
50
+ CREATE INDEX IF NOT EXISTS idx_mem_category ON agent_memories(category);
51
+ CREATE INDEX IF NOT EXISTS idx_mem_importance ON agent_memories(importance);
52
+ CREATE INDEX IF NOT EXISTS idx_mem_sessions_site ON memory_sessions(site_id);
53
+ CREATE INDEX IF NOT EXISTS idx_mem_sessions_agent ON memory_sessions(agent_id);
54
+ CREATE INDEX IF NOT EXISTS idx_mem_assoc_source ON memory_associations(source_memory_id);
55
+ CREATE INDEX IF NOT EXISTS idx_mem_assoc_target ON memory_associations(target_memory_id);
56
+ `);
57
+
58
+ // ─── Prepared Statements ─────────────────────────────────────────────────────
59
+
60
+ const stmts = {
61
+ insertMemory: db.prepare(`
62
+ INSERT INTO agent_memories (id, site_id, agent_id, memory_type, category, key, value, embedding, importance, expires_at)
63
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
64
+ `),
65
+ getMemory: db.prepare(`SELECT * FROM agent_memories WHERE id = ?`),
66
+ queryMemories: db.prepare(`
67
+ SELECT * FROM agent_memories
68
+ WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
69
+ ORDER BY importance DESC, updated_at DESC
70
+ `),
71
+ queryByCategory: db.prepare(`
72
+ SELECT * FROM agent_memories
73
+ WHERE site_id = ? AND agent_id = ? AND category = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
74
+ ORDER BY importance DESC, updated_at DESC
75
+ `),
76
+ queryByType: db.prepare(`
77
+ SELECT * FROM agent_memories
78
+ WHERE site_id = ? AND agent_id = ? AND memory_type = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
79
+ ORDER BY importance DESC, updated_at DESC
80
+ `),
81
+ queryByCategoryAndType: db.prepare(`
82
+ SELECT * FROM agent_memories
83
+ WHERE site_id = ? AND agent_id = ? AND category = ? AND memory_type = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
84
+ ORDER BY importance DESC, updated_at DESC
85
+ `),
86
+ touchMemory: db.prepare(`
87
+ UPDATE agent_memories SET access_count = access_count + 1, last_accessed = datetime('now') WHERE id = ?
88
+ `),
89
+ softDelete: db.prepare(`
90
+ UPDATE agent_memories SET expires_at = datetime('now'), updated_at = datetime('now') WHERE id = ?
91
+ `),
92
+ updateImportance: db.prepare(`
93
+ UPDATE agent_memories SET importance = ?, updated_at = datetime('now') WHERE id = ?
94
+ `),
95
+ deleteExpired: db.prepare(`
96
+ DELETE FROM agent_memories WHERE expires_at IS NOT NULL AND expires_at <= datetime('now')
97
+ `),
98
+ findDuplicates: db.prepare(`
99
+ SELECT key, category, COUNT(*) as cnt, GROUP_CONCAT(id) as ids
100
+ FROM agent_memories
101
+ WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
102
+ GROUP BY key, category HAVING cnt > 1
103
+ `),
104
+ deleteMemoryById: db.prepare(`DELETE FROM agent_memories WHERE id = ?`),
105
+
106
+ insertAssociation: db.prepare(`
107
+ INSERT INTO memory_associations (id, source_memory_id, target_memory_id, relationship, strength)
108
+ VALUES (?, ?, ?, ?, ?)
109
+ `),
110
+ getAssociationsFrom: db.prepare(`
111
+ SELECT ma.*, am.key, am.value, am.memory_type, am.category, am.importance
112
+ FROM memory_associations ma
113
+ JOIN agent_memories am ON am.id = ma.target_memory_id
114
+ WHERE ma.source_memory_id = ?
115
+ ORDER BY ma.strength DESC
116
+ `),
117
+ getAssociationsFromFiltered: db.prepare(`
118
+ SELECT ma.*, am.key, am.value, am.memory_type, am.category, am.importance
119
+ FROM memory_associations ma
120
+ JOIN agent_memories am ON am.id = ma.target_memory_id
121
+ WHERE ma.source_memory_id = ? AND ma.relationship = ?
122
+ ORDER BY ma.strength DESC
123
+ `),
124
+
125
+ insertSession: db.prepare(`
126
+ INSERT INTO memory_sessions (id, site_id, agent_id, context) VALUES (?, ?, ?, ?)
127
+ `),
128
+ endSession: db.prepare(`
129
+ UPDATE memory_sessions SET ended_at = datetime('now'), context = json_patch(COALESCE(context, '{}'), ?) WHERE id = ?
130
+ `),
131
+ getSessionHistory: db.prepare(`
132
+ SELECT * FROM memory_sessions WHERE site_id = ? AND agent_id = ? ORDER BY started_at DESC LIMIT ?
133
+ `),
134
+
135
+ countAll: db.prepare(`
136
+ SELECT COUNT(*) as total FROM agent_memories WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
137
+ `),
138
+ countByType: db.prepare(`
139
+ SELECT memory_type, COUNT(*) as count FROM agent_memories
140
+ WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
141
+ GROUP BY memory_type
142
+ `),
143
+ countByCategory: db.prepare(`
144
+ SELECT category, COUNT(*) as count FROM agent_memories
145
+ WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
146
+ GROUP BY category
147
+ `),
148
+ avgImportance: db.prepare(`
149
+ SELECT AVG(importance) as avg FROM agent_memories
150
+ WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
151
+ `),
152
+ storageEstimate: db.prepare(`
153
+ SELECT SUM(LENGTH(key) + LENGTH(value) + COALESCE(LENGTH(embedding), 0)) as bytes
154
+ FROM agent_memories WHERE site_id = ? AND agent_id = ?
155
+ `),
156
+
157
+ allActiveMemories: db.prepare(`
158
+ SELECT * FROM agent_memories
159
+ WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
160
+ ORDER BY created_at ASC
161
+ `),
162
+ getPreferences: db.prepare(`
163
+ SELECT * FROM agent_memories
164
+ WHERE site_id = ? AND agent_id = ? AND memory_type = 'preference' AND (expires_at IS NULL OR expires_at > datetime('now'))
165
+ ORDER BY importance DESC
166
+ `),
167
+ findPreference: db.prepare(`
168
+ SELECT * FROM agent_memories
169
+ WHERE site_id = ? AND agent_id = ? AND memory_type = 'preference' AND key = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
170
+ LIMIT 1
171
+ `),
172
+ updateMemoryValue: db.prepare(`
173
+ UPDATE agent_memories SET value = ?, embedding = ?, importance = ?, updated_at = datetime('now') WHERE id = ?
174
+ `),
175
+ };
176
+
177
+ // ─── Vector Utilities ────────────────────────────────────────────────────────
178
+
179
+ const EMBED_DIM = 128;
180
+
181
+ /**
182
+ * Tokenizes text into lowercase alphanumeric tokens.
183
+ * @param {string} text
184
+ * @returns {string[]}
185
+ */
186
+ function tokenize(text) {
187
+ return String(text).toLowerCase().match(/[a-z0-9]+/g) || [];
188
+ }
189
+
190
+ /**
191
+ * Deterministic hash of a string to a 32-bit unsigned integer.
192
+ * @param {string} str
193
+ * @returns {number}
194
+ */
195
+ function hashStr(str) {
196
+ let h = 0x811c9dc5;
197
+ for (let i = 0; i < str.length; i++) {
198
+ h ^= str.charCodeAt(i);
199
+ h = Math.imul(h, 0x01000193);
200
+ }
201
+ return h >>> 0;
202
+ }
203
+
204
+ /**
205
+ * Computes a TF-IDF-style embedding: hashes tokens into a fixed-size vector and L2-normalizes.
206
+ * @param {string} text
207
+ * @returns {number[]} 128-dimensional unit vector
208
+ */
209
+ function computeEmbedding(text) {
210
+ const tokens = tokenize(text);
211
+ const vec = new Float64Array(EMBED_DIM);
212
+ if (tokens.length === 0) return Array.from(vec);
213
+
214
+ const tf = {};
215
+ for (const t of tokens) tf[t] = (tf[t] || 0) + 1;
216
+
217
+ for (const [token, count] of Object.entries(tf)) {
218
+ const idx = hashStr(token) % EMBED_DIM;
219
+ const sign = (hashStr(token + '_sign') & 1) ? 1 : -1;
220
+ const weight = (1 + Math.log(count)) * sign;
221
+ vec[idx] += weight;
222
+ }
223
+
224
+ let norm = 0;
225
+ for (let i = 0; i < EMBED_DIM; i++) norm += vec[i] * vec[i];
226
+ norm = Math.sqrt(norm);
227
+ if (norm > 0) for (let i = 0; i < EMBED_DIM; i++) vec[i] /= norm;
228
+
229
+ return Array.from(vec);
230
+ }
231
+
232
+ /**
233
+ * Standard cosine similarity between two equal-length vectors.
234
+ * @param {number[]} a
235
+ * @param {number[]} b
236
+ * @returns {number} similarity in [-1, 1]
237
+ */
238
+ function cosineSimilarity(a, b) {
239
+ if (!a || !b || a.length !== b.length) return 0;
240
+ let dot = 0, normA = 0, normB = 0;
241
+ for (let i = 0; i < a.length; i++) {
242
+ dot += a[i] * b[i];
243
+ normA += a[i] * a[i];
244
+ normB += b[i] * b[i];
245
+ }
246
+ const denom = Math.sqrt(normA) * Math.sqrt(normB);
247
+ return denom === 0 ? 0 : dot / denom;
248
+ }
249
+
250
+ // ─── Core Memory Operations ──────────────────────────────────────────────────
251
+
252
+ /**
253
+ * Stores a memory entry for an agent on a site.
254
+ * @param {string} siteId
255
+ * @param {string} agentId
256
+ * @param {{ type?: string, category?: string, key: string, value: any, importance?: number, ttlSeconds?: number }} opts
257
+ * @returns {object} the stored memory row
258
+ */
259
+ function storeMemory(siteId, agentId, { type, category, key, value, importance, ttlSeconds }) {
260
+ const id = randomUUID();
261
+ const jsonValue = typeof value === 'string' ? value : JSON.stringify(value);
262
+ const embedding = computeEmbedding(`${key} ${typeof value === 'string' ? value : JSON.stringify(value)}`);
263
+ const expiresAt = ttlSeconds
264
+ ? new Date(Date.now() + ttlSeconds * 1000).toISOString().replace('T', ' ').slice(0, 19)
265
+ : null;
266
+
267
+ stmts.insertMemory.run(
268
+ id, siteId, agentId,
269
+ type || null, category || null,
270
+ key, jsonValue,
271
+ JSON.stringify(embedding),
272
+ importance ?? 0.5,
273
+ expiresAt
274
+ );
275
+
276
+ return stmts.getMemory.get(id);
277
+ }
278
+
279
+ /**
280
+ * Recalls memories matching filters, optionally ranked by semantic similarity.
281
+ * @param {string} siteId
282
+ * @param {string} agentId
283
+ * @param {{ query?: string, category?: string, type?: string, limit?: number, minImportance?: number }} opts
284
+ * @returns {object[]}
285
+ */
286
+ function recallMemories(siteId, agentId, { query, category, type, limit, minImportance } = {}) {
287
+ let rows;
288
+ if (category && type) {
289
+ rows = stmts.queryByCategoryAndType.all(siteId, agentId, category, type);
290
+ } else if (category) {
291
+ rows = stmts.queryByCategory.all(siteId, agentId, category);
292
+ } else if (type) {
293
+ rows = stmts.queryByType.all(siteId, agentId, type);
294
+ } else {
295
+ rows = stmts.queryMemories.all(siteId, agentId);
296
+ }
297
+
298
+ if (minImportance != null) {
299
+ rows = rows.filter(r => r.importance >= minImportance);
300
+ }
301
+
302
+ if (query) {
303
+ const queryEmbed = computeEmbedding(query);
304
+ rows = rows.map(r => {
305
+ const memEmbed = r.embedding ? JSON.parse(r.embedding) : null;
306
+ const similarity = memEmbed ? cosineSimilarity(queryEmbed, memEmbed) : 0;
307
+ return { ...r, similarity };
308
+ });
309
+ rows.sort((a, b) => b.similarity - a.similarity);
310
+ }
311
+
312
+ const maxRows = limit || 20;
313
+ rows = rows.slice(0, maxRows);
314
+
315
+ const touchTx = db.transaction((ids) => {
316
+ for (const id of ids) stmts.touchMemory.run(id);
317
+ });
318
+ touchTx(rows.map(r => r.id));
319
+
320
+ return rows;
321
+ }
322
+
323
+ // ─── Associations ────────────────────────────────────────────────────────────
324
+
325
+ /**
326
+ * Creates a directional link between two memories.
327
+ * @param {string} sourceId
328
+ * @param {string} targetId
329
+ * @param {string} relationship - leads_to | similar_to | replaces | depends_on
330
+ * @param {number} [strength=0.5]
331
+ * @returns {object}
332
+ */
333
+ function associateMemories(sourceId, targetId, relationship, strength = 0.5) {
334
+ const id = randomUUID();
335
+ stmts.insertAssociation.run(id, sourceId, targetId, relationship, strength);
336
+ return { id, sourceId, targetId, relationship, strength };
337
+ }
338
+
339
+ /**
340
+ * Retrieves memories associated with a given memory.
341
+ * @param {string} memoryId
342
+ * @param {{ relationship?: string, minStrength?: number }} [opts]
343
+ * @returns {object[]}
344
+ */
345
+ function getAssociatedMemories(memoryId, { relationship, minStrength } = {}) {
346
+ let rows;
347
+ if (relationship) {
348
+ rows = stmts.getAssociationsFromFiltered.all(memoryId, relationship);
349
+ } else {
350
+ rows = stmts.getAssociationsFrom.all(memoryId);
351
+ }
352
+ if (minStrength != null) {
353
+ rows = rows.filter(r => r.strength >= minStrength);
354
+ }
355
+ return rows;
356
+ }
357
+
358
+ // ─── Lifecycle ───────────────────────────────────────────────────────────────
359
+
360
+ /**
361
+ * Soft-deletes a memory by setting its expiration to now.
362
+ * @param {string} memoryId
363
+ * @returns {boolean}
364
+ */
365
+ function forgetMemory(memoryId) {
366
+ const info = stmts.softDelete.run(memoryId);
367
+ return info.changes > 0;
368
+ }
369
+
370
+ /**
371
+ * Consolidates memories: merges duplicates, adjusts importance, purges expired.
372
+ * @param {string} siteId
373
+ * @param {string} agentId
374
+ * @returns {{ merged: number, boosted: number, decayed: number, expired: number }}
375
+ */
376
+ function consolidateMemories(siteId, agentId) {
377
+ const stats = { merged: 0, boosted: 0, decayed: 0, expired: 0 };
378
+
379
+ const expiredInfo = stmts.deleteExpired.run();
380
+ stats.expired = expiredInfo.changes;
381
+
382
+ const dupes = stmts.findDuplicates.all(siteId, agentId);
383
+ const mergeTx = db.transaction(() => {
384
+ for (const group of dupes) {
385
+ const ids = group.ids.split(',');
386
+ const memories = ids.map(id => stmts.getMemory.get(id)).filter(Boolean);
387
+ if (memories.length < 2) continue;
388
+
389
+ memories.sort((a, b) => b.access_count - a.access_count || b.importance - a.importance);
390
+ const keeper = memories[0];
391
+
392
+ let mergedValues;
393
+ try {
394
+ const parsed = memories.map(m => JSON.parse(m.value));
395
+ if (typeof parsed[0] === 'object' && parsed[0] !== null && !Array.isArray(parsed[0])) {
396
+ mergedValues = JSON.stringify(Object.assign({}, ...parsed.reverse()));
397
+ } else {
398
+ mergedValues = keeper.value;
399
+ }
400
+ } catch {
401
+ mergedValues = keeper.value;
402
+ }
403
+
404
+ const newImportance = Math.min(1, keeper.importance + 0.05 * (memories.length - 1));
405
+ const newEmbedding = computeEmbedding(`${keeper.key} ${mergedValues}`);
406
+ stmts.updateMemoryValue.run(mergedValues, JSON.stringify(newEmbedding), newImportance, keeper.id);
407
+
408
+ for (let i = 1; i < memories.length; i++) {
409
+ stmts.deleteMemoryById.run(memories[i].id);
410
+ stats.merged++;
411
+ }
412
+ }
413
+ });
414
+ mergeTx();
415
+
416
+ const active = stmts.allActiveMemories.all(siteId, agentId);
417
+ const now = Date.now();
418
+
419
+ const adjustTx = db.transaction(() => {
420
+ for (const mem of active) {
421
+ const ageMs = now - new Date(mem.created_at).getTime();
422
+ const ageDays = ageMs / 86400000;
423
+
424
+ if (mem.access_count >= 5) {
425
+ const boost = Math.min(1, mem.importance + 0.02 * Math.log2(mem.access_count));
426
+ if (boost > mem.importance) {
427
+ stmts.updateImportance.run(Math.min(1, boost), mem.id);
428
+ stats.boosted++;
429
+ }
430
+ }
431
+
432
+ if (ageDays > 30 && mem.access_count < 3) {
433
+ const decayFactor = Math.max(0.1, 1 - 0.01 * (ageDays - 30));
434
+ const decayed = mem.importance * decayFactor;
435
+ if (decayed < mem.importance) {
436
+ stmts.updateImportance.run(Math.max(0, decayed), mem.id);
437
+ stats.decayed++;
438
+ }
439
+ }
440
+ }
441
+ });
442
+ adjustTx();
443
+
444
+ return stats;
445
+ }
446
+
447
+ // ─── Stats ───────────────────────────────────────────────────────────────────
448
+
449
+ /**
450
+ * Returns aggregate statistics for an agent's memories on a site.
451
+ * @param {string} siteId
452
+ * @param {string} agentId
453
+ * @returns {object}
454
+ */
455
+ function getMemoryStats(siteId, agentId) {
456
+ const total = stmts.countAll.get(siteId, agentId).total;
457
+ const byType = stmts.countByType.all(siteId, agentId);
458
+ const byCategory = stmts.countByCategory.all(siteId, agentId);
459
+ const avgImportance = stmts.avgImportance.get(siteId, agentId).avg || 0;
460
+ const storageBytes = stmts.storageEstimate.get(siteId, agentId).bytes || 0;
461
+
462
+ return {
463
+ total,
464
+ byType: Object.fromEntries(byType.map(r => [r.memory_type, r.count])),
465
+ byCategory: Object.fromEntries(byCategory.map(r => [r.category, r.count])),
466
+ avgImportance: Math.round(avgImportance * 1000) / 1000,
467
+ storageEstimateBytes: storageBytes,
468
+ };
469
+ }
470
+
471
+ // ─── Sessions ────────────────────────────────────────────────────────────────
472
+
473
+ /**
474
+ * Starts an agent memory session.
475
+ * @param {string} siteId
476
+ * @param {string} agentId
477
+ * @param {object} [context]
478
+ * @returns {{ id: string, siteId: string, agentId: string, startedAt: string }}
479
+ */
480
+ function startSession(siteId, agentId, context = {}) {
481
+ const id = randomUUID();
482
+ stmts.insertSession.run(id, siteId, agentId, JSON.stringify(context));
483
+ return { id, siteId, agentId, startedAt: new Date().toISOString() };
484
+ }
485
+
486
+ /**
487
+ * Ends a session, optionally attaching a summary to the context.
488
+ * @param {string} sessionId
489
+ * @param {string} [summary]
490
+ * @returns {boolean}
491
+ */
492
+ function endSession(sessionId, summary) {
493
+ const patch = summary ? JSON.stringify({ summary }) : '{}';
494
+ const info = stmts.endSession.run(patch, sessionId);
495
+ return info.changes > 0;
496
+ }
497
+
498
+ /**
499
+ * Returns recent sessions for a site/agent pair.
500
+ * @param {string} siteId
501
+ * @param {string} agentId
502
+ * @param {{ limit?: number }} [opts]
503
+ * @returns {object[]}
504
+ */
505
+ function getSessionHistory(siteId, agentId, { limit } = {}) {
506
+ return stmts.getSessionHistory.all(siteId, agentId, limit || 20);
507
+ }
508
+
509
+ // ─── Import / Export ─────────────────────────────────────────────────────────
510
+
511
+ /**
512
+ * Exports all active memories as JSON or CSV.
513
+ * @param {string} siteId
514
+ * @param {string} agentId
515
+ * @param {{ format?: 'json'|'csv' }} [opts]
516
+ * @returns {string}
517
+ */
518
+ function exportMemories(siteId, agentId, { format } = {}) {
519
+ const rows = stmts.allActiveMemories.all(siteId, agentId);
520
+
521
+ if (format === 'csv') {
522
+ const cols = ['id', 'site_id', 'agent_id', 'memory_type', 'category', 'key', 'value', 'importance', 'access_count', 'created_at', 'updated_at'];
523
+ const escape = (v) => `"${String(v == null ? '' : v).replace(/"/g, '""')}"`;
524
+ const header = cols.join(',');
525
+ const lines = rows.map(r => cols.map(c => escape(r[c])).join(','));
526
+ return [header, ...lines].join('\n');
527
+ }
528
+
529
+ return JSON.stringify(rows, null, 2);
530
+ }
531
+
532
+ /**
533
+ * Bulk-imports memories from an array of objects.
534
+ * @param {string} siteId
535
+ * @param {string} agentId
536
+ * @param {object[]} data
537
+ * @returns {{ imported: number }}
538
+ */
539
+ function importMemories(siteId, agentId, data) {
540
+ let imported = 0;
541
+ const tx = db.transaction(() => {
542
+ for (const item of data) {
543
+ const id = item.id || randomUUID();
544
+ const jsonValue = typeof item.value === 'string' ? item.value : JSON.stringify(item.value);
545
+ const embedding = item.embedding
546
+ ? (typeof item.embedding === 'string' ? item.embedding : JSON.stringify(item.embedding))
547
+ : JSON.stringify(computeEmbedding(`${item.key} ${jsonValue}`));
548
+
549
+ stmts.insertMemory.run(
550
+ id, siteId, agentId,
551
+ item.type || item.memory_type || null,
552
+ item.category || null,
553
+ item.key,
554
+ jsonValue,
555
+ embedding,
556
+ item.importance ?? 0.5,
557
+ item.expires_at || null
558
+ );
559
+ imported++;
560
+ }
561
+ });
562
+ tx();
563
+ return { imported };
564
+ }
565
+
566
+ // ─── Preference Shortcuts ────────────────────────────────────────────────────
567
+
568
+ /**
569
+ * Returns all 'preference' type memories for a site/agent.
570
+ * @param {string} siteId
571
+ * @param {string} agentId
572
+ * @returns {object[]}
573
+ */
574
+ function getPreferences(siteId, agentId) {
575
+ return stmts.getPreferences.all(siteId, agentId);
576
+ }
577
+
578
+ /**
579
+ * Stores or updates a preference memory. Upserts if the same key exists.
580
+ * @param {string} siteId
581
+ * @param {string} agentId
582
+ * @param {string} key
583
+ * @param {any} value
584
+ * @returns {object}
585
+ */
586
+ function recordPreference(siteId, agentId, key, value) {
587
+ const existing = stmts.findPreference.get(siteId, agentId, key);
588
+ const jsonValue = typeof value === 'string' ? value : JSON.stringify(value);
589
+ const embedding = computeEmbedding(`${key} ${jsonValue}`);
590
+
591
+ if (existing) {
592
+ const newImportance = Math.min(1, existing.importance + 0.05);
593
+ stmts.updateMemoryValue.run(jsonValue, JSON.stringify(embedding), newImportance, existing.id);
594
+ return stmts.getMemory.get(existing.id);
595
+ }
596
+
597
+ return storeMemory(siteId, agentId, {
598
+ type: 'preference',
599
+ category: 'custom',
600
+ key,
601
+ value: jsonValue,
602
+ importance: 0.7,
603
+ });
604
+ }
605
+
606
+ // ─── Exports ─────────────────────────────────────────────────────────────────
607
+
608
+ module.exports = {
609
+ storeMemory,
610
+ recallMemories,
611
+ computeEmbedding,
612
+ cosineSimilarity,
613
+ associateMemories,
614
+ getAssociatedMemories,
615
+ forgetMemory,
616
+ consolidateMemories,
617
+ getMemoryStats,
618
+ startSession,
619
+ endSession,
620
+ getSessionHistory,
621
+ exportMemories,
622
+ importMemories,
623
+ getPreferences,
624
+ recordPreference,
625
+ };