-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_system.js
More file actions
380 lines (332 loc) · 10.1 KB
/
Copy pathmemory_system.js
File metadata and controls
380 lines (332 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
// Memory System for FRIDAY
// Stores conversations, preferences, and context for persistent learning
const Database = require('better-sqlite3');
const path = require('path');
class MemorySystem {
constructor(dbPath = './friday_memory.db') {
try {
this.db = new Database(dbPath);
this.db.pragma('journal_mode = WAL');
this.initializeTables();
console.log('[Memory System] ✅ Initialized');
} catch (e) {
console.error('[Memory System Error]', e.message);
this.db = null;
}
}
initializeTables() {
// Conversations table
this.db.exec(`
CREATE TABLE IF NOT EXISTS conversations (
id TEXT PRIMARY KEY,
session_id TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
user_message TEXT,
friday_response TEXT,
confidence REAL,
intent TEXT,
entities TEXT,
sentiment TEXT,
context_key TEXT
)
`);
// User preferences table
this.db.exec(`
CREATE TABLE IF NOT EXISTS user_preferences (
key TEXT PRIMARY KEY,
value TEXT,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
// Tasks table
this.db.exec(`
CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY,
title TEXT,
description TEXT,
status TEXT,
priority TEXT,
due_date DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
completed_at DATETIME
)
`);
// Reminders table
this.db.exec(`
CREATE TABLE IF NOT EXISTS reminders (
id TEXT PRIMARY KEY,
message TEXT,
due_time DATETIME,
is_completed BOOLEAN DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
// User learning patterns
this.db.exec(`
CREATE TABLE IF NOT EXISTS learning_patterns (
pattern_id TEXT PRIMARY KEY,
pattern_type TEXT,
keyword TEXT,
action TEXT,
frequency INTEGER DEFAULT 0,
last_used DATETIME,
confidence REAL
)
`);
// User Facts (Persistent Profile)
this.db.exec(`
CREATE TABLE IF NOT EXISTS user_facts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category TEXT,
fact TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
console.log('[Memory System] Tables initialized');
}
// Store a conversation
storeConversation(sessionId, userMessage, fridayResponse, metadata = {}) {
try {
const id = `conv_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
const stmt = this.db.prepare(`
INSERT INTO conversations (
id, session_id, user_message, friday_response,
confidence, intent, entities, sentiment, context_key
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
stmt.run(
id,
sessionId,
userMessage,
fridayResponse,
metadata.confidence || 0.8,
metadata.intent || 'general',
JSON.stringify(metadata.entities || {}),
metadata.sentiment || 'neutral',
metadata.contextKey || 'general'
);
console.log('[Memory] Conversation stored:', id);
return id;
} catch (e) {
console.error('[Memory Error] Storing conversation:', e.message);
}
}
// Retrieve conversation history
getConversationHistory(sessionId, limit = 10) {
try {
const stmt = this.db.prepare(`
SELECT * FROM conversations
WHERE session_id = ?
ORDER BY timestamp DESC
LIMIT ?
`);
const conversations = stmt.all(sessionId, limit);
return conversations.map(conv => ({
...conv,
entities: JSON.parse(conv.entities || '{}')
}));
} catch (e) {
console.error('[Memory Error] Retrieving history:', e.message);
return [];
}
}
// Store user preference
setPreference(key, value) {
try {
const stmt = this.db.prepare(`
INSERT OR REPLACE INTO user_preferences (key, value, updated_at)
VALUES (?, ?, CURRENT_TIMESTAMP)
`);
stmt.run(key, typeof value === 'string' ? value : JSON.stringify(value));
console.log('[Memory] Preference set:', key);
} catch (e) {
console.error('[Memory Error] Setting preference:', e.message);
}
}
// Get user preference
getPreference(key) {
try {
const stmt = this.db.prepare('SELECT value FROM user_preferences WHERE key = ?');
const result = stmt.get(key);
if (result) {
try {
return JSON.parse(result.value);
} catch {
return result.value;
}
}
return null;
} catch (e) {
console.error('[Memory Error] Getting preference:', e.message);
return null;
}
}
// Create a task
createTask(title, description = '', priority = 'medium', dueDate = null) {
try {
const id = `task_${Date.now()}`;
const stmt = this.db.prepare(`
INSERT INTO tasks (id, title, description, status, priority, due_date, created_at)
VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
`);
stmt.run(id, title, description, 'pending', priority, dueDate);
console.log('[Memory] Task created:', id);
return id;
} catch (e) {
console.error('[Memory Error] Creating task:', e.message);
}
}
// Get all tasks
getTasks(status = null) {
try {
let query = 'SELECT * FROM tasks';
const params = [];
if (status) {
query += ' WHERE status = ?';
params.push(status);
}
query += ' ORDER BY priority DESC, due_date ASC';
const stmt = this.db.prepare(query);
return stmt.all(...params);
} catch (e) {
console.error('[Memory Error] Getting tasks:', e.message);
return [];
}
}
// Complete a task
completeTask(taskId) {
try {
const stmt = this.db.prepare(`
UPDATE tasks
SET status = 'completed', completed_at = CURRENT_TIMESTAMP
WHERE id = ?
`);
stmt.run(taskId);
console.log('[Memory] Task completed:', taskId);
} catch (e) {
console.error('[Memory Error] Completing task:', e.message);
}
}
// Create a reminder
createReminder(message, dueTime) {
try {
const id = `reminder_${Date.now()}`;
const stmt = this.db.prepare(`
INSERT INTO reminders (id, message, due_time, created_at)
VALUES (?, ?, ?, CURRENT_TIMESTAMP)
`);
stmt.run(id, message, dueTime);
console.log('[Memory] Reminder created:', id);
return id;
} catch (e) {
console.error('[Memory Error] Creating reminder:', e.message);
}
}
// Get pending reminders
getPendingReminders() {
try {
const stmt = this.db.prepare(`
SELECT * FROM reminders
WHERE is_completed = 0
AND datetime(due_time) <= datetime('now')
ORDER BY due_time ASC
`);
return stmt.all();
} catch (e) {
console.error('[Memory Error] Getting reminders:', e.message);
return [];
}
}
// Learn from user behavior
recordPattern(patternType, keyword, action, confidence = 0.8) {
try {
const patternId = `pattern_${patternType}_${keyword}`.toLowerCase();
// Check if pattern exists
const existing = this.db.prepare('SELECT * FROM learning_patterns WHERE pattern_id = ?').get(patternId);
if (existing) {
const stmt = this.db.prepare(`
UPDATE learning_patterns
SET frequency = frequency + 1, last_used = CURRENT_TIMESTAMP, confidence = ?
WHERE pattern_id = ?
`);
stmt.run(confidence, patternId);
} else {
const stmt = this.db.prepare(`
INSERT INTO learning_patterns (pattern_id, pattern_type, keyword, action, frequency, last_used, confidence)
VALUES (?, ?, ?, ?, 1, CURRENT_TIMESTAMP, ?)
`);
stmt.run(patternId, patternType, keyword, action, confidence);
}
console.log('[Memory] Pattern learned:', patternId);
} catch (e) {
console.error('[Memory Error] Recording pattern:', e.message);
}
}
// Get learned patterns
getPatterns(patternType = null, limit = 10) {
try {
let query = 'SELECT * FROM learning_patterns';
const params = [];
if (patternType) {
query += ' WHERE pattern_type = ?';
params.push(patternType);
}
query += ' ORDER BY frequency DESC, last_used DESC LIMIT ?';
params.push(limit);
const stmt = this.db.prepare(query);
return stmt.all(...params);
} catch (e) {
console.error('[Memory Error] Getting patterns:', e.message);
return [];
}
}
// Get tasks due within a certain timeframe (in hours)
getUpcomingTasks(hours = 24) {
try {
// Calculate the cutoff time
const now = new Date();
const future = new Date(now.getTime() + hours * 60 * 60 * 1000);
const stmt = this.db.prepare(`
SELECT * FROM tasks
WHERE status != 'completed'
AND due_date IS NOT NULL
AND due_date BETWEEN ? AND ?
ORDER BY due_date ASC
`);
return stmt.all(now.toISOString(), future.toISOString());
} catch (e) {
console.error('[Memory Error] Getting upcoming tasks:', e.message);
return [];
}
}
// Get memory stats
getStats() {
try {
const conversations = this.db.prepare('SELECT COUNT(*) as count FROM conversations').get();
const tasks = this.db.prepare('SELECT COUNT(*) as count FROM tasks').get();
const reminders = this.db.prepare('SELECT COUNT(*) as count FROM reminders').get();
const patterns = this.db.prepare('SELECT COUNT(*) as count FROM learning_patterns').get();
return {
conversations: conversations.count,
tasks: tasks.count,
reminders: reminders.count,
patterns: patterns.count
};
} catch (e) {
console.error('[Memory Error] Getting stats:', e.message);
return {};
}
}
// Close database
close() {
try {
if (this.db) {
this.db.close();
console.log('[Memory System] Closed');
}
} catch (e) {
console.error('[Memory Error] Closing:', e.message);
}
}
}
module.exports = MemorySystem;