-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
681 lines (572 loc) · 21.1 KB
/
cli.ts
File metadata and controls
681 lines (572 loc) · 21.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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
#!/usr/bin/env node
import { Command } from 'commander';
import { MemoryManager } from './src/ingest/cli-commands.js';
import { MemoryType } from './src/utils/types.js';
import {
generatePassphrase,
saveEncryptionPassphrase,
isEncryptionAvailable
} from './src/storage/encryption.js';
import { recordVoiceMemoInteractive } from './src/ingest/voice.js';
import dotenv from 'dotenv';
dotenv.config();
const DATA_DIR = process.env.DATA_DIR || './data';
const program = new Command();
const manager = new MemoryManager();
program
.name('brain')
.description('Manage your second brain')
.version('0.1.0');
program
.command('add <content>')
.description('Add a new memory')
.option('-t, --type <type>', 'Memory type (preference|relationship|goal|experience|fact)', 'experience')
.option('--tags <tags>', 'Comma-separated tags')
.option('-i, --importance <level>', 'Importance level (1-5)', '3')
.option('-e, --encrypt', 'Encrypt this memory (requires setup-encryption first)')
.action(async (content: string, options) => {
try {
await manager.initialize();
const memory = await manager.addMemory({
content,
type: options.type as MemoryType,
tags: options.tags?.split(',').map((t: string) => t.trim()) || [],
importance: parseInt(options.importance),
encrypt: options.encrypt
});
console.log('\n✅ Memory added!');
console.log(` ID: ${memory.id}`);
console.log(` Type: ${memory.type}`);
console.log(` Tags: ${memory.tags.join(', ') || 'none'}`);
if (options.encrypt) {
console.log(` 🔒 Encrypted: Yes`);
}
console.log('');
manager.close();
process.exit(0);
} catch (error) {
console.error('Error:', error);
process.exit(1);
}
});
program
.command('search <query>')
.description('Search memories')
.option('-l, --limit <number>', 'Number of results', '5')
.option('-t, --type <type>', 'Filter by type')
.action(async (query: string, options) => {
try {
await manager.initialize();
const results = await manager.searchMemories(
query,
parseInt(options.limit),
options.type as MemoryType
);
console.log(`\n🔍 Found ${results.length} results:\n`);
results.forEach((result, index) => {
console.log(`${index + 1}. [${result.memory.type}] ${result.memory.content}`);
console.log(` Score: ${(result.score * 100).toFixed(1)}%`);
console.log(` Tags: ${result.memory.tags.join(', ') || 'none'}`);
console.log('');
});
manager.close();
process.exit(0);
} catch (error) {
console.error('Error:', error);
process.exit(1);
}
});
program
.command('list')
.description('List recent memories')
.option('-l, --limit <number>', 'Number of memories', '10')
.option('-t, --type <type>', 'Filter by type')
.action(async (options) => {
try {
await manager.initialize();
const memories = options.type
? manager.getMemoriesByType(options.type as MemoryType)
: manager.listRecent(parseInt(options.limit));
console.log(`\n📝 Recent memories:\n`);
memories.forEach((memory, index) => {
const encryptedFlag = memory.metadata.is_encrypted ? ' 🔒' : '';
console.log(`${index + 1}. [${memory.type}]${encryptedFlag} ${memory.content}`);
console.log(` Tags: ${memory.tags.join(', ') || 'none'}`);
console.log(` Created: ${memory.metadata.created_at.toLocaleString()}`);
console.log('');
});
manager.close();
process.exit(0);
} catch (error) {
console.error('Error:', error);
process.exit(1);
}
});
program
.command('setup-encryption')
.description('Setup encryption for sensitive memories')
.option('-k, --key <passphrase>', 'Custom passphrase (or auto-generate)')
.action((options) => {
try {
if (isEncryptionAvailable(DATA_DIR)) {
console.log('⚠️ Encryption is already set up!');
console.log('Key location: ./data/encrypted/.key');
process.exit(0);
}
const passphrase = options.key || generatePassphrase();
saveEncryptionPassphrase(DATA_DIR, passphrase);
if (!options.key) {
console.log('\n🔐 Generated encryption key:');
console.log(` ${passphrase}`);
console.log('\n⚠️ IMPORTANT: Save this key somewhere safe!');
console.log(' Without it, encrypted memories cannot be recovered.\n');
} else {
console.log('\n✅ Custom encryption key saved!\n');
}
console.log('You can now add encrypted memories with:');
console.log(' yarn cli add "sensitive info" --encrypt\n');
process.exit(0);
} catch (error) {
console.error('Error:', error);
process.exit(1);
}
});
program
.command('edit <id>')
.description('Edit an existing memory')
.option('-c, --content <content>', 'New content')
.option('-t, --type <type>', 'New type')
.option('--tags <tags>', 'New tags (comma-separated)')
.option('-i, --importance <level>', 'New importance level (1-5)')
.action(async (id: string, options) => {
try {
await manager.initialize();
const memory = manager.getMemory(id);
if (!memory) {
console.error(`\n❌ Memory with ID ${id} not found\n`);
manager.close();
process.exit(1);
}
const updates: any = {};
if (options.content) updates.content = options.content;
if (options.type) updates.type = options.type as MemoryType;
if (options.tags) updates.tags = options.tags.split(',').map((t: string) => t.trim());
if (options.importance) {
updates.metadata = { importance: parseInt(options.importance) };
}
const updated = await manager.updateMemory(id, updates);
if (updated) {
console.log('\n✅ Memory updated!');
console.log(` ID: ${updated.id}`);
console.log(` Content: ${updated.content}`);
console.log(` Type: ${updated.type}`);
console.log(` Tags: ${updated.tags.join(', ') || 'none'}\n`);
} else {
console.error('\n❌ Failed to update memory\n');
}
manager.close();
process.exit(0);
} catch (error) {
console.error('Error:', error);
manager.close();
process.exit(1);
}
});
program
.command('delete <id>')
.description('Delete a memory')
.option('-y, --yes', 'Skip confirmation')
.action(async (id: string, options) => {
try {
await manager.initialize();
const memory = manager.getMemory(id);
if (!memory) {
console.error(`\n❌ Memory with ID ${id} not found\n`);
manager.close();
process.exit(1);
}
console.log('\n🗑️ About to delete:');
console.log(` Content: ${memory.content}`);
console.log(` Type: ${memory.type}`);
console.log(` Created: ${memory.metadata.created_at.toLocaleString()}\n`);
if (!options.yes) {
const inquirer = await import('inquirer');
const answer = await inquirer.default.prompt([{
type: 'confirm',
name: 'confirm',
message: 'Are you sure you want to delete this memory?',
default: false
}]);
if (!answer.confirm) {
console.log('\n❌ Deletion cancelled\n');
manager.close();
process.exit(0);
}
}
const deleted = await manager.deleteMemory(id);
if (deleted) {
console.log('\n✅ Memory deleted successfully\n');
} else {
console.error('\n❌ Failed to delete memory\n');
}
manager.close();
process.exit(0);
} catch (error) {
console.error('Error:', error);
manager.close();
process.exit(1);
}
});
program
.command('tags')
.description('List all tags')
.action(async () => {
try {
await manager.initialize();
const tags = manager.getAllTags();
console.log(`\n🏷️ All tags (${tags.length}):\n`);
if (tags.length === 0) {
console.log(' No tags found\n');
} else {
tags.forEach(tag => {
const memories = manager.getMemoriesByTag(tag);
console.log(` ${tag} (${memories.length})`);
});
console.log('');
}
manager.close();
process.exit(0);
} catch (error) {
console.error('Error:', error);
manager.close();
process.exit(1);
}
});
program
.command('tag <tag>')
.description('List memories with a specific tag')
.action(async (tag: string) => {
try {
await manager.initialize();
const memories = manager.getMemoriesByTag(tag);
console.log(`\n🏷️ Memories tagged with "${tag}" (${memories.length}):\n`);
if (memories.length === 0) {
console.log(' No memories found with this tag\n');
} else {
memories.forEach((memory, index) => {
const encryptedFlag = memory.metadata.is_encrypted ? ' 🔒' : '';
console.log(`${index + 1}. [${memory.type}]${encryptedFlag} ${memory.content}`);
console.log(` ID: ${memory.id}`);
console.log(` Created: ${memory.metadata.created_at.toLocaleString()}`);
console.log('');
});
}
manager.close();
process.exit(0);
} catch (error) {
console.error('Error:', error);
manager.close();
process.exit(1);
}
});
program
.command('export [filename]')
.description('Export all memories to JSON file')
.action(async (filename?: string) => {
try {
await manager.initialize();
const data = manager.exportMemories();
const exportFile = filename || `memories-export-${Date.now()}.json`;
const fs = await import('fs');
fs.writeFileSync(exportFile, JSON.stringify(data, null, 2));
console.log(`\n✅ Exported ${data.metadata.count} memories to ${exportFile}\n`);
manager.close();
process.exit(0);
} catch (error) {
console.error('Error:', error);
manager.close();
process.exit(1);
}
});
program
.command('import <filename>')
.description('Import memories from JSON file')
.option('--skip-duplicates', 'Skip memories that appear to be duplicates')
.action(async (filename: string, options) => {
try {
await manager.initialize();
const fs = await import('fs');
if (!fs.existsSync(filename)) {
console.error(`\n❌ File not found: ${filename}\n`);
manager.close();
process.exit(1);
}
const fileContent = fs.readFileSync(filename, 'utf-8');
const data = JSON.parse(fileContent);
console.log(`\n📥 Importing memories from ${filename}...\n`);
const result = await manager.importMemories(data, {
skipDuplicates: options.skipDuplicates
});
console.log(`✅ Import complete!`);
console.log(` Imported: ${result.imported}`);
console.log(` Skipped: ${result.skipped}`);
if (result.errors.length > 0) {
console.log(` Errors: ${result.errors.length}`);
result.errors.forEach(err => console.log(` - ${err}`));
}
console.log('');
manager.close();
process.exit(0);
} catch (error) {
console.error('Error:', error);
manager.close();
process.exit(1);
}
});
program
.command('check-duplicates <content>')
.description('Check if similar memories already exist')
.action(async (content: string) => {
try {
await manager.initialize();
console.log('\n🔍 Checking for duplicates...\n');
const duplicates = await manager.checkDuplicates(content, 0.85);
if (duplicates.length === 0) {
console.log('✅ No similar memories found\n');
} else {
console.log(`⚠️ Found ${duplicates.length} similar memories:\n`);
duplicates.forEach((memory, index) => {
console.log(`${index + 1}. ${memory.content}`);
console.log(` Type: ${memory.type}, Tags: ${memory.tags.join(', ')}`);
console.log('');
});
}
manager.close();
process.exit(0);
} catch (error) {
console.error('Error:', error);
manager.close();
process.exit(1);
}
});
program
.command('encryption-status')
.description('Check encryption status')
.action(() => {
try {
const available = isEncryptionAvailable(DATA_DIR);
console.log('\n🔐 Encryption Status:\n');
if (available) {
console.log(' ✅ Encryption is enabled');
console.log(' 📁 Key file: ./data/encrypted/.key');
console.log('\n You can add encrypted memories with:');
console.log(' yarn cli add "text" --encrypt\n');
} else {
console.log(' ❌ Encryption is not set up');
console.log('\n Run this to enable encryption:');
console.log(' yarn cli setup-encryption\n');
}
process.exit(0);
} catch (error) {
console.error('Error:', error);
process.exit(1);
}
});
program
.command('import-ai')
.description('Import learnings from AI conversation (paste conversation, Ctrl+D when done)')
.option('-t, --type <type>', 'Memory type (default: fact)', 'fact')
.option('--tags <tags>', 'Tags (comma-separated)', 'ai-learning')
.option('--analyze', 'Use AI to extract multiple memories (requires ANTHROPIC_API_KEY)')
.action(async (options) => {
try {
await manager.initialize();
console.log('\n📥 Import from AI Conversation\n');
console.log('Paste your AI conversation below, then press Ctrl+D:\n');
// Read multi-line input from stdin
let conversation = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', (chunk) => {
conversation += chunk;
});
await new Promise<void>((resolve) => {
process.stdin.on('end', () => resolve());
});
conversation = conversation.trim();
if (!conversation) {
console.log('\n❌ No input received\n');
manager.close();
process.exit(0);
}
console.log('\n🧠 Processing...\n');
if (options.analyze && process.env.ANTHROPIC_API_KEY) {
// Use AI to extract memories
const { analyzeConversation } = await import('./src/utils/conversation-analyzer.js');
const extracted = await analyzeConversation(conversation);
if (extracted.length === 0) {
console.log('ℹ️ No distinct memories found. Saving as single memory...\n');
await manager.addMemory({
content: conversation.substring(0, 1000),
type: options.type as MemoryType,
tags: options.tags.split(',').map((t: string) => t.trim()),
importance: 3,
source: 'ai'
});
console.log('✅ Saved as single memory\n');
} else {
console.log(`✅ Extracted ${extracted.length} memories:\n`);
for (const mem of extracted) {
const memory = await manager.addMemory({
content: mem.content,
type: mem.type,
tags: [...mem.tags, 'ai-imported'],
importance: mem.importance,
source: 'ai'
});
console.log(` ✓ [${mem.type}] ${mem.content.substring(0, 60)}...`);
}
console.log('');
}
} else {
// Save as single memory
const memory = await manager.addMemory({
content: conversation.substring(0, 10000), // Limit length
type: options.type as MemoryType,
tags: options.tags.split(',').map((t: string) => t.trim()),
importance: 3,
source: 'ai'
});
console.log('✅ Conversation imported!');
console.log(` ID: ${memory.id}`);
console.log(` Type: ${memory.type}`);
console.log(` Tags: ${memory.tags.join(', ')}\n`);
}
console.log('💡 Tip: Use --analyze flag for automatic extraction\n');
manager.close();
process.exit(0);
} catch (error) {
console.error('Error:', error);
manager.close();
process.exit(1);
}
});
program
.command('chatgpt [topic]')
.description('Generate ChatGPT context file (upload to ChatGPT for personalized responses)')
.option('-l, --limit <number>', 'Number of memories per type', '30')
.action(async (topic?: string, options) => {
try {
await manager.initialize();
let output = '# My Second Brain Context\n\n';
output += `Generated: ${new Date().toLocaleString()}\n`;
if (topic) {
output += `Topic: ${topic}\n\n`;
// Search for topic
console.log(`🔍 Searching for "${topic}"...\n`);
const results = await manager.searchMemories(topic, parseInt(options.limit));
const tagResults = manager.getMemoriesByTag(topic.toLowerCase());
// Combine and deduplicate
const allMemories = [...results.map(r => r.memory)];
tagResults.forEach(m => {
if (!allMemories.find(existing => existing.id === m.id)) {
allMemories.push(m);
}
});
output += `## Results for "${topic}" (${allMemories.length} memories)\n\n`;
allMemories.forEach((m, i) => {
output += `${i + 1}. [${m.type}] ${m.content}\n`;
if (m.tags.length > 0) {
output += ` *Tags: ${m.tags.join(', ')}*\n`;
}
output += '\n';
});
} else {
// Export all by type
console.log('📊 Exporting memories by type...\n');
const types: MemoryType[] = ['preference', 'goal', 'relationship', 'fact', 'experience'];
for (const type of types) {
const memories = manager.getMemoriesByType(type).slice(0, parseInt(options.limit));
if (memories.length > 0) {
output += `## ${type.charAt(0).toUpperCase() + type.slice(1)}s (${memories.length})\n\n`;
memories.forEach((m, i) => {
output += `${i + 1}. ${m.content}\n`;
if (m.tags.length > 0) {
output += ` *Tags: ${m.tags.join(', ')}*\n`;
}
output += '\n';
});
}
}
}
// Add usage instructions
output += '---\n\n';
output += '## How to use this file\n\n';
output += '1. Upload this file to ChatGPT\n';
output += '2. Say: "I\'ve uploaded my personal memories. Use these to give personalized responses."\n';
output += '3. ChatGPT will use this context in our conversation!\n';
const fs = await import('fs');
const filename = topic ? `chatgpt-${topic}.md` : 'chatgpt-context.md';
fs.writeFileSync(filename, output);
console.log(`✅ Created ${filename}`);
console.log(`📊 Ready to upload to ChatGPT!`);
console.log(`\n💡 Tip: Re-export weekly for fresh context\n`);
manager.close();
process.exit(0);
} catch (error) {
console.error('Error:', error);
manager.close();
process.exit(1);
}
});
program
.command('voice')
.description('Record a voice memo and save as memory')
.action(async () => {
try {
await manager.initialize();
console.log('\n🎤 Voice Memo\n');
console.log('This will:');
console.log(' 1. Record audio from your microphone');
console.log(' 2. Transcribe using OpenAI Whisper');
console.log(' 3. Analyze and categorize the memory');
console.log(' 4. Ask for confirmation before saving\n');
// Check for OpenAI API key
if (!process.env.OPENAI_API_KEY) {
console.error('❌ OPENAI_API_KEY not set');
console.error(' Voice features require OpenAI API access.');
console.error(' Add your key to .env file\n');
manager.close();
process.exit(1);
}
const suggestion = await recordVoiceMemoInteractive();
if (!suggestion) {
console.log('\n❌ Voice memo cancelled or failed\n');
manager.close();
process.exit(1);
}
// Save the memory
const memory = await manager.addMemory({
content: suggestion.content,
type: suggestion.type,
tags: suggestion.tags,
importance: suggestion.importance,
source: 'voice',
encrypt: (suggestion as any).encrypt || false
});
console.log('\n✅ Voice memo saved!');
console.log(` ID: ${memory.id}`);
console.log(` Type: ${memory.type}`);
console.log(` Content: ${memory.content}`);
if ((suggestion as any).encrypt) {
console.log(` 🔒 Encrypted: Yes`);
}
console.log('');
manager.close();
process.exit(0);
} catch (error) {
console.error('Error:', error);
manager.close();
process.exit(1);
}
});
program.parse();