-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
2943 lines (2507 loc) · 115 KB
/
index.js
File metadata and controls
2943 lines (2507 loc) · 115 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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* DRAGMAN AGENT - Smart Note-Taking Assistant for Base App
*
* RECENT IMPROVEMENTS (Latest Version):
* ✅ Security: Sanitized logging (no sensitive data exposure)
* ✅ Security: Input validation and XSS prevention
* ✅ Security: Rate limiting (20 actions/min, 10 saves/min)
* ✅ Performance: Database indexes for faster queries
* ✅ Performance: Multi-keyword search with relevance ranking
* ✅ Reliability: Error handling for all DB operations
* ✅ Reliability: Memory leak fixes (context cleanup)
* ✅ Code Quality: Extracted constants, DRY principles
* ✅ Code Quality: Helper functions for repeated operations
*
* 🔥 NEW GROUP INTELLIGENCE FEATURES:
* ✅ Passive Detection: Auto-detect wallet addresses, URLs, keywords (background)
* ✅ Trending Topics: Analyze group focus, top contributors, hot keywords
* ✅ Related Notes: Show similar notes when searching
* ✅ Smart Suggestions: Proactive hints for unsaved important info
* ✅ Knowledge Insights: Weekly analytics of group activity
* ✅ Weekly Digest: Auto-scheduled team reports (MVP, trends, progress, gamification)
*
* PRODUCTION NOTES:
* - Currently uses SQLite (good for single instance)
* - For PM2 cluster mode, migrate to PostgreSQL
* - Mention required in groups: @dragman [command]
* - See TODO section in code for scaling recommendations
*/
import { Agent } from "@xmtp/agent-sdk";
import OpenAI from 'openai';
import dotenv from 'dotenv';
import fs from 'fs';
import Database from 'better-sqlite3';
dotenv.config();
// ==================== CONFIGURATION ====================
const CONFIG = {
// Context & Timing
CONTEXT_TIMEOUT_MS: 5 * 60 * 1000, // 5 minutes
MIN_RESPONSE_DELAY_MS: 2000, // 2 seconds
MAX_RESPONSE_DELAY_MS: 5000, // 5 seconds
CONTEXT_CLEANUP_INTERVAL_MS: 60 * 1000, // 1 minute
// Content Limits
MAX_NOTE_CONTENT_LENGTH: 2000, // characters
MAX_SEARCH_RESULTS_DISPLAY: 5, // notes to show
MAX_RECENT_NOTES: 5, // recent notes limit
MIN_KEYWORD_LENGTH: 3, // minimum keyword length
// Weekly Digest
WEEKLY_DIGEST_DAY: 1, // 0=Sunday, 1=Monday, etc
WEEKLY_DIGEST_HOUR: 9, // 9 AM
WEEKLY_DIGEST_ENABLED: true, // Enable/disable auto-digest
// Rate Limiting
RATE_LIMIT_WINDOW_MS: 60 * 1000, // 1 minute
RATE_LIMIT_MAX_ACTIONS: 20, // max actions per window
RATE_LIMIT_SAVE_MAX: 10, // max saves per window
// OpenAI
OPENAI_MODEL: "gpt-3.5-turbo",
OPENAI_CATEGORIZATION_MAX_TOKENS: 10,
OPENAI_CONVERSATION_MAX_TOKENS: 150,
OPENAI_TEMPERATURE: 0.7,
OPENAI_CATEGORIZATION_TEMP: 0.3,
};
// ==================== SETUP ====================
const installationPath = process.env.XMTP_INSTALLATION_PATH || './.xmtp-installation';
if (!fs.existsSync(installationPath)) {
fs.mkdirSync(installationPath, { recursive: true });
console.log(`📁 Created XMTP installation directory: ${installationPath}`);
}
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
// TODO: FOR PRODUCTION SCALING (when traffic increases):
// 1. Migrate SQLite → PostgreSQL (for PM2 cluster mode support)
// 2. Add Redis for distributed context storage (survives restarts)
// 3. Implement message queue (Bull/BullMQ) for handling traffic spikes
// 4. Add OpenAI response caching to reduce API costs
// 5. Consider vector embeddings for semantic search
// 6. Add monitoring/metrics (Prometheus/Grafana)
const agent = await Agent.createFromEnv({
env: process.env.XMTP_ENV || 'production',
persistConversations: true,
installationPath: installationPath
});
// ==================== LOGGING ====================
function log(level, message, data = {}) {
const timestamp = new Date().toISOString();
// Sanitize sensitive data before logging
const sanitized = { ...data };
if (sanitized.from) {
sanitized.from = shortenAddress(sanitized.from); // Hide full address
}
if (sanitized.user) {
sanitized.user = shortenAddress(sanitized.user);
}
if (sanitized.message) {
sanitized.message = '[REDACTED]'; // Never log message content
}
console.log(`[${timestamp}] [${level.toUpperCase()}]: ${message}`, JSON.stringify(sanitized));
}
// Helper function moved up for use in log()
function shortenAddress(address) {
if (!address) return 'Unknown';
return `${address.slice(0, 6)}...${address.slice(-4)}`;
}
// ==================== DATABASE SETUP ====================
const db = new Database('./dragman.db');
// In-memory store for group analytics (could move to DB later)
const groupAnalytics = new Map(); // { chatId: { detectedInfo: [], recentTopics: [], activityLog: [] } }
// Weekly stats tracking
const weeklyStats = new Map(); // { chatId: { weekStart: timestamp, saves: 0, searches: 0, views: 0, lastDigestSent: timestamp } }
// Track conversation types (DM vs Group) - remember after first interaction
const conversationTypes = new Map(); // { conversationId: 'dm' | 'group' }
const ignoredUnknownConversations = new Map(); // { chatId: count } - track how many times we ignored an unknown conversation
// Track pending replies - Base App might send 'message' event with reference, then 'text' event with content
const pendingReplies = new Map(); // { conversationId_timestamp: { reference, chatId, senderAddress, isGroupChat, timestamp } }
db.exec(`
CREATE TABLE IF NOT EXISTS notes (
id TEXT PRIMARY KEY,
chatId TEXT NOT NULL,
chatType TEXT NOT NULL,
content TEXT NOT NULL,
category TEXT,
savedBy TEXT NOT NULL,
fromUser TEXT,
originalMessage TEXT,
createdAt TEXT NOT NULL,
tags TEXT,
viewCount INTEGER DEFAULT 0
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS conversation_types (
chatId TEXT PRIMARY KEY,
chatType TEXT NOT NULL,
updatedAt TEXT NOT NULL
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS categories (
chatId TEXT NOT NULL,
category TEXT NOT NULL,
count INTEGER DEFAULT 1,
PRIMARY KEY (chatId, category)
)
`);
// Create indexes for better search performance
db.exec(`CREATE INDEX IF NOT EXISTS idx_notes_chatId ON notes(chatId)`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_notes_savedBy ON notes(savedBy)`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_notes_category ON notes(category)`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_notes_createdAt ON notes(createdAt DESC)`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_categories_chatId ON categories(chatId)`);
log('info', 'Database initialized with indexes');
// ==================== CONTEXT TRACKING ====================
const userContexts = new Map();
function setUserContext(address, context, data = null) {
userContexts.set(address, { context, data, timestamp: Date.now() });
}
function getUserContext(address) {
const ctx = userContexts.get(address);
if (ctx && Date.now() - ctx.timestamp < CONFIG.CONTEXT_TIMEOUT_MS) { // 5 minutes
return ctx;
}
userContexts.delete(address);
return null;
}
function clearUserContext(address) {
userContexts.delete(address);
}
// Cleanup old contexts periodically to prevent memory leaks
setInterval(() => {
const now = Date.now();
for (const [address, ctx] of userContexts.entries()) {
if (now - ctx.timestamp > CONFIG.CONTEXT_TIMEOUT_MS) {
userContexts.delete(address);
log('info', 'Cleaned up expired context', { user: address });
}
}
}, CONFIG.CONTEXT_CLEANUP_INTERVAL_MS);
// ==================== RATE LIMITING ====================
const rateLimitStore = new Map(); // { address: { actions: [...timestamps], saves: [...timestamps] } }
function checkRateLimit(address, actionType = 'general') {
const now = Date.now();
const windowStart = now - CONFIG.RATE_LIMIT_WINDOW_MS;
if (!rateLimitStore.has(address)) {
rateLimitStore.set(address, { actions: [], saves: [] });
}
const userLimits = rateLimitStore.get(address);
// Clean old timestamps
userLimits.actions = userLimits.actions.filter(ts => ts > windowStart);
userLimits.saves = userLimits.saves.filter(ts => ts > windowStart);
// Check general actions limit
if (userLimits.actions.length >= CONFIG.RATE_LIMIT_MAX_ACTIONS) {
return { allowed: false, reason: 'too_many_actions', resetIn: Math.ceil((userLimits.actions[0] + CONFIG.RATE_LIMIT_WINDOW_MS - now) / 1000) };
}
// Check save-specific limit
if (actionType === 'save' && userLimits.saves.length >= CONFIG.RATE_LIMIT_SAVE_MAX) {
return { allowed: false, reason: 'too_many_saves', resetIn: Math.ceil((userLimits.saves[0] + CONFIG.RATE_LIMIT_WINDOW_MS - now) / 1000) };
}
// Record action
userLimits.actions.push(now);
if (actionType === 'save') {
userLimits.saves.push(now);
}
return { allowed: true };
}
// Cleanup rate limit store periodically
setInterval(() => {
const now = Date.now();
const windowStart = now - CONFIG.RATE_LIMIT_WINDOW_MS;
for (const [address, limits] of rateLimitStore.entries()) {
limits.actions = limits.actions.filter(ts => ts > windowStart);
limits.saves = limits.saves.filter(ts => ts > windowStart);
// Remove empty entries
if (limits.actions.length === 0 && limits.saves.length === 0) {
rateLimitStore.delete(address);
}
}
}, CONFIG.CONTEXT_CLEANUP_INTERVAL_MS);
// Natural response delay to feel more human (2-5 seconds)
// Prevents spam and makes it feel like agent is carefully reading/thinking
async function naturalDelay() {
const delay = CONFIG.MIN_RESPONSE_DELAY_MS + Math.random() * (CONFIG.MAX_RESPONSE_DELAY_MS - CONFIG.MIN_RESPONSE_DELAY_MS);
await new Promise(resolve => setTimeout(resolve, delay));
}
// ==================== INPUT VALIDATION ====================
function validateNoteContent(content) {
if (!content || content.trim().length === 0) {
return { valid: false, error: '❌ Note cannot be empty.' };
}
if (content.length > CONFIG.MAX_NOTE_CONTENT_LENGTH) {
return {
valid: false,
error: `❌ Note too long. Maximum ${CONFIG.MAX_NOTE_CONTENT_LENGTH} characters (you have ${content.length}).`
};
}
// Basic XSS prevention (strip potentially dangerous patterns)
const dangerousPatterns = [/<script/i, /javascript:/i, /onerror=/i, /onclick=/i];
for (const pattern of dangerousPatterns) {
if (pattern.test(content)) {
return { valid: false, error: '❌ Invalid content detected. Please remove special characters.' };
}
}
return { valid: true };
}
function sanitizeInput(input) {
// Remove null bytes and control characters
return input.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '').trim();
}
// ==================== QUICK ACTIONS ====================
async function sendMainQuickActions(ctx, chatType) {
// Text-based menu (different for DM vs Group)
let interactiveMenu;
if (chatType === 'group') {
interactiveMenu = `🐉 What would you like to do?\n\n` +
`🎯 QUICK ACTIONS\n\n` +
`1️⃣ 💾 Save Note\n` +
`2️⃣ 🔍 Search Notes\n` +
`3️⃣ 📂 View Categories\n` +
`4️⃣ ❓ Help\n\n` +
`💡 Just type the number (1-4) with tag @dragman.base.eth first`;
} else {
// DM menu includes group features option
interactiveMenu = `🐉 What would you like to do?\n\n` +
`🎯 QUICK ACTIONS\n\n` +
`1️⃣ 💾 Save Note\n` +
`2️⃣ 🔍 Search Notes\n` +
`3️⃣ 📂 View Categories\n` +
`4️⃣ ❓ Help\n` +
`5️⃣ 🚀 Group Features\n\n` +
`💡 Just type the number (1-5)`;
}
try {
await ctx.sendText(interactiveMenu);
log('info', 'Sent Quick Actions menu', { chatType });
} catch (error) {
log('error', 'Failed to send Quick Actions', { error: error.message });
}
}
async function sendCategoryActions(ctx, chatId, senderAddress, isGroupChat = false) {
// CRITICAL PRIVACY FIX:
// 1. In DMs, only show categories from user's own notes
// 2. ALWAYS filter by chatType to prevent DM notes leaking into groups
const chatType = isGroupChat ? 'group' : 'dm';
let categories;
if (!isGroupChat && senderAddress) {
// Get categories from user's notes only (DM privacy)
categories = db.prepare(`
SELECT category, COUNT(*) as count
FROM notes
WHERE chatId = ? AND chatType = ? AND savedBy = ?
GROUP BY category
ORDER BY count DESC
`).all(chatId, chatType, senderAddress);
} else {
// Groups: show all categories (shared knowledge) - but filter by chatType!
categories = db.prepare(`
SELECT category, count FROM categories
WHERE chatId = ?
ORDER BY count DESC
`).all(chatId);
// Double-check: Only include categories that actually exist for this chatType
// This prevents DM categories from showing in groups
const validCategories = db.prepare(`
SELECT DISTINCT category FROM notes
WHERE chatId = ? AND chatType = ?
`).all(chatId, chatType);
const validCategorySet = new Set(validCategories.map(c => c.category));
categories = categories.filter(cat => validCategorySet.has(cat.category));
}
if (categories.length === 0) {
await ctx.sendText("📭 No categories yet. Start by saving some notes!");
return;
}
setUserContext(senderAddress, 'viewing_categories', { categories, isGroupChat });
let text = "🐉 Browse notes by category:\n\n";
categories.forEach((cat, index) => {
text += `${index + 1}. ${getCategoryEmoji(cat.category)} ${cat.category} (${cat.count})\n`;
});
text += `\nReply with the number to view notes in that category.`;
text += `\n\n💡 Tip: Type /menu anytime to return here`;
await ctx.sendText(text);
}
async function sendSearchResultActions(ctx, results, senderAddress) {
setUserContext(senderAddress, 'viewing_search_results', { results });
let text = formatNotesList(results.slice(0, CONFIG.MAX_SEARCH_RESULTS_DISPLAY));
if (results.length > CONFIG.MAX_SEARCH_RESULTS_DISPLAY) {
text += `\n...and ${results.length - CONFIG.MAX_SEARCH_RESULTS_DISPLAY} more results\n`;
}
text += `\nReply with number to view full note`;
text += `\n\n💡 Tip: Type /menu for main menu`;
await ctx.sendText(text);
}
// ==================== SMART NOTE SAVING ====================
async function saveNote(content, chatId, chatType, savedBy, fromUser = null, originalMessage = null, explicitCategory = null) {
try {
const noteId = `note_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
const category = explicitCategory || await categorizeContent(content);
const tags = extractTags(content);
db.prepare(`
INSERT INTO notes (id, chatId, chatType, content, category, savedBy, fromUser, originalMessage, createdAt, tags)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
noteId, chatId, chatType, content, category, savedBy, fromUser, originalMessage,
new Date().toISOString(), JSON.stringify(tags)
);
db.prepare(`
INSERT INTO categories (chatId, category, count)
VALUES (?, ?, 1)
ON CONFLICT(chatId, category)
DO UPDATE SET count = count + 1
`).run(chatId, category);
log('info', 'Note saved', { noteId, category, user: savedBy });
return { noteId, category, tags };
} catch (error) {
log('error', 'Failed to save note', { error: error.message, user: savedBy });
throw new Error('Failed to save note to database');
}
}
async function categorizeContent(content) {
// Regex patterns for common categories
if (/0x[a-fA-F0-9]{40}/.test(content)) return 'Addresses';
if (/contract|deploy|solidity/i.test(content)) return 'Contract';
if (/transaction|tx|transfer|swap/i.test(content)) return 'Transaction';
if (/(https?:\/\/|www\.)/i.test(content)) return 'Links';
if (/tutorial|guide|how to|steps/i.test(content)) return 'Tutorial';
if (/strategy|plan|approach/i.test(content)) return 'Strategy';
if (/meeting|call|discussion/i.test(content)) return 'Meeting';
if (/api|key|token|secret/i.test(content)) return 'API';
if (/defi|yield|liquidity|stake/i.test(content)) return 'DeFi';
if (/game|gaming|nft|play/i.test(content)) return 'Gaming';
if (/code|dev|debug|error/i.test(content)) return 'Dev';
if (/trade|trading|price|chart/i.test(content)) return 'Trading';
if (/personal|private|me|my|myself/i.test(content)) return 'Personal';
if (/idea|thought|brainstorm/i.test(content)) return 'Ideas';
if (/\?$|question|why|how|what|when/i.test(content)) return 'Questions';
if (/resource|tool|link|doc/i.test(content)) return 'Resources';
try {
const completion = await openai.chat.completions.create({
model: CONFIG.OPENAI_MODEL,
messages: [{
role: "system",
content: "You are a categorization assistant. Return ONLY a 1-2 word category name for the note. Categories: Addresses, Contract, Transaction, Links, Tutorial, Strategy, Meeting, API, DeFi, Gaming, Dev, Trading, Personal, Ideas, Questions, Resources, General. Return just the category word, nothing else."
}, {
role: "user",
content: `Categorize this note: "${content}"`
}],
max_tokens: CONFIG.OPENAI_CATEGORIZATION_MAX_TOKENS,
temperature: CONFIG.OPENAI_CATEGORIZATION_TEMP,
});
return completion.choices[0].message.content.trim() || 'General';
} catch (error) {
log('error', 'OpenAI categorization failed', { error: error.message });
return 'General';
}
}
function extractTags(content) {
const tags = [];
const words = content.toLowerCase().split(/\s+/);
const keywords = ['eth', 'base', 'uniswap', 'nft', 'dao', 'defi', 'web3', 'smart contract', 'yield', 'stake'];
keywords.forEach(keyword => {
if (content.toLowerCase().includes(keyword)) {
tags.push(keyword);
}
});
return tags;
}
// ==================== SMART NOTE SEARCHING ====================
function searchNotes(query, chatId, senderAddress = null, isGroupChat = false) {
// CRITICAL PRIVACY FIX:
// 1. In DMs, only show user's own notes
// 2. ALWAYS filter by chatType to prevent DM notes leaking into groups
const chatType = isGroupChat ? 'group' : 'dm';
if (!isGroupChat && senderAddress) {
return db.prepare(`
SELECT * FROM notes
WHERE chatId = ? AND chatType = ? AND savedBy = ? AND (
LOWER(content) LIKE ? OR
LOWER(category) LIKE ? OR
LOWER(tags) LIKE ?
)
ORDER BY createdAt DESC
`).all(chatId, chatType, senderAddress, `%${query.toLowerCase()}%`, `%${query.toLowerCase()}%`, `%${query.toLowerCase()}%`);
} else {
return db.prepare(`
SELECT * FROM notes
WHERE chatId = ? AND chatType = ? AND (
LOWER(content) LIKE ? OR
LOWER(category) LIKE ? OR
LOWER(tags) LIKE ?
)
ORDER BY createdAt DESC
`).all(chatId, chatType, `%${query.toLowerCase()}%`, `%${query.toLowerCase()}%`, `%${query.toLowerCase()}%`);
}
}
function getNotesByCategory(category, chatId, senderAddress = null, isGroupChat = false) {
// CRITICAL PRIVACY FIX:
// 1. In DMs, only show user's own notes
// 2. ALWAYS filter by chatType to prevent DM notes leaking into groups
const chatType = isGroupChat ? 'group' : 'dm';
if (!isGroupChat && senderAddress) {
return db.prepare(`
SELECT * FROM notes
WHERE chatId = ? AND chatType = ? AND savedBy = ? AND category = ?
ORDER BY createdAt DESC
`).all(chatId, chatType, senderAddress, category);
} else {
return db.prepare(`
SELECT * FROM notes
WHERE chatId = ? AND chatType = ? AND category = ?
ORDER BY createdAt DESC
`).all(chatId, chatType, category);
}
}
function getRecentNotes(chatId, limit = CONFIG.MAX_RECENT_NOTES, senderAddress = null, isGroupChat = false) {
// CRITICAL PRIVACY FIX:
// 1. In DMs, only show user's own notes
// 2. ALWAYS filter by chatType to prevent DM notes leaking into groups
const chatType = isGroupChat ? 'group' : 'dm';
if (!isGroupChat && senderAddress) {
return db.prepare(`
SELECT * FROM notes
WHERE chatId = ? AND chatType = ? AND savedBy = ?
ORDER BY createdAt DESC
LIMIT ?
`).all(chatId, chatType, senderAddress, limit);
} else {
return db.prepare(`
SELECT * FROM notes
WHERE chatId = ? AND chatType = ?
ORDER BY createdAt DESC
LIMIT ?
`).all(chatId, chatType, limit);
}
}
function incrementViewCount(noteId) {
try {
db.prepare(`
UPDATE notes
SET viewCount = viewCount + 1
WHERE id = ?
`).run(noteId);
} catch (error) {
log('error', 'Failed to increment view count', { noteId, error: error.message });
}
}
// ==================== GROUP INTELLIGENCE FEATURES ====================
// PASSIVE DETECTION: Detect important info in background (doesn't auto-respond)
function detectImportantInfo(message, chatId, senderAddress) {
const detectedItems = [];
// Detect Ethereum addresses
const addressMatches = message.match(/0x[a-fA-F0-9]{40,}/g);
if (addressMatches) {
detectedItems.push({
type: 'address',
content: addressMatches[0],
detectedBy: senderAddress,
timestamp: Date.now()
});
}
// Detect URLs
const urlMatches = message.match(/https?:\/\/[^\s]+/g);
if (urlMatches) {
detectedItems.push({
type: 'url',
content: urlMatches[0],
detectedBy: senderAddress,
timestamp: Date.now()
});
}
// Detect important keywords (contract, deploy, wallet, key, api)
const importantKeywords = ['contract', 'deploy', 'wallet', 'private key', 'api key', 'token', 'mainnet'];
const lowerMessage = message.toLowerCase();
for (const keyword of importantKeywords) {
if (lowerMessage.includes(keyword)) {
detectedItems.push({
type: 'keyword',
content: keyword,
context: message.substring(0, 100),
detectedBy: senderAddress,
timestamp: Date.now()
});
break; // Only track first important keyword
}
}
// Store detected items for analytics
if (detectedItems.length > 0) {
if (!groupAnalytics.has(chatId)) {
groupAnalytics.set(chatId, { detectedInfo: [], recentTopics: [], activityLog: [] });
}
const analytics = groupAnalytics.get(chatId);
analytics.detectedInfo.push(...detectedItems);
// Keep only last 50 detected items
if (analytics.detectedInfo.length > 50) {
analytics.detectedInfo = analytics.detectedInfo.slice(-50);
}
}
return detectedItems;
}
// TRENDING TOPICS: Analyze what the group is focusing on
function analyzeTrendingTopics(chatId, days = 7, senderAddress = null, isGroupChat = false) {
const cutoffDate = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
// CRITICAL PRIVACY FIX:
// 1. In DMs, only analyze user's own notes
// 2. ALWAYS filter by chatType to prevent DM notes leaking into groups
const chatType = isGroupChat ? 'group' : 'dm';
let recentNotes;
if (!isGroupChat && senderAddress) {
recentNotes = db.prepare(`
SELECT category, content, savedBy, createdAt, viewCount
FROM notes
WHERE chatId = ? AND chatType = ? AND savedBy = ? AND createdAt > ?
ORDER BY createdAt DESC
`).all(chatId, chatType, senderAddress, cutoffDate);
} else {
recentNotes = db.prepare(`
SELECT category, content, savedBy, createdAt, viewCount
FROM notes
WHERE chatId = ? AND chatType = ? AND createdAt > ?
ORDER BY createdAt DESC
`).all(chatId, chatType, cutoffDate);
}
if (recentNotes.length === 0) {
return null;
}
// Count category frequency
const categoryCount = {};
const contributorCount = {};
const keywordCount = {};
for (const note of recentNotes) {
// Count categories
categoryCount[note.category] = (categoryCount[note.category] || 0) + 1;
// Count contributors
const shortAddr = shortenAddress(note.savedBy);
contributorCount[shortAddr] = (contributorCount[shortAddr] || 0) + 1;
// Extract keywords from content
const words = note.content.toLowerCase().split(/\s+/);
for (const word of words) {
if (word.length > 4 && !['about', 'which', 'where', 'there'].includes(word)) {
keywordCount[word] = (keywordCount[word] || 0) + 1;
}
}
}
// Sort and get top items
const topCategories = Object.entries(categoryCount)
.sort((a, b) => b[1] - a[1])
.slice(0, 3);
const topContributors = Object.entries(contributorCount)
.sort((a, b) => b[1] - a[1])
.slice(0, 3);
const topKeywords = Object.entries(keywordCount)
.filter(([word, count]) => count > 1)
.sort((a, b) => b[1] - a[1])
.slice(0, 5);
// Get most viewed notes
const popularNotes = recentNotes
.sort((a, b) => b.viewCount - a.viewCount)
.slice(0, 3);
return {
totalNotes: recentNotes.length,
topCategories,
topContributors,
topKeywords,
popularNotes,
timeframe: `${days} days`
};
}
// FIND RELATED NOTES: Find notes similar to current one
function findRelatedNotes(noteId, chatId, limit = 3, senderAddress = null, isGroupChat = false) {
// Get the source note
const sourceNote = db.prepare('SELECT * FROM notes WHERE id = ? AND chatId = ?').get(noteId, chatId);
if (!sourceNote) return [];
// CRITICAL PRIVACY FIX:
// 1. In DMs, only find related notes from user's own notes
// 2. ALWAYS filter by chatType to prevent DM notes leaking into groups
const chatType = isGroupChat ? 'group' : 'dm';
// Extract keywords from source note
const keywords = sourceNote.content.toLowerCase()
.split(/\s+/)
.filter(word => word.length > 4);
if (keywords.length === 0) return [];
// Find notes with similar keywords (excluding source note)
let allNotes;
if (!isGroupChat && senderAddress) {
allNotes = db.prepare(`
SELECT * FROM notes
WHERE chatId = ? AND chatType = ? AND savedBy = ? AND id != ?
ORDER BY createdAt DESC
LIMIT 20
`).all(chatId, chatType, senderAddress, noteId);
} else {
allNotes = db.prepare(`
SELECT * FROM notes
WHERE chatId = ? AND chatType = ? AND id != ?
ORDER BY createdAt DESC
LIMIT 20
`).all(chatId, chatType, noteId);
}
// Calculate similarity scores
const scored = allNotes.map(note => {
let score = 0;
const noteContent = note.content.toLowerCase();
for (const keyword of keywords) {
if (noteContent.includes(keyword)) score += 1;
}
// Boost same category
if (note.category === sourceNote.category) score += 2;
return { note, score };
});
// Return top matches
return scored
.filter(item => item.score > 0)
.sort((a, b) => b.score - a.score)
.slice(0, limit)
.map(item => item.note);
}
// CHECK FOR UNSAVED IMPORTANT INFO
function checkUnsavedInfo(chatId, isGroupChat = false) {
if (!groupAnalytics.has(chatId)) return [];
// CRITICAL PRIVACY FIX: Only check unsaved info for groups, and filter by chatType
const chatType = isGroupChat ? 'group' : 'dm';
const analytics = groupAnalytics.get(chatId);
const recentDetections = analytics.detectedInfo.filter(
item => Date.now() - item.timestamp < 30 * 60 * 1000 // Last 30 minutes
);
// Check which detected items haven't been saved
const unsaved = [];
for (const detection of recentDetections) {
if (detection.type === 'address' || detection.type === 'url') {
// CRITICAL PRIVACY FIX: Filter by chatType to prevent checking DM notes in group context
const exists = db.prepare(`
SELECT id FROM notes
WHERE chatId = ? AND chatType = ? AND content LIKE ?
LIMIT 1
`).get(chatId, chatType, `%${detection.content}%`);
if (!exists) {
unsaved.push(detection);
}
}
}
return unsaved;
}
// WEEKLY DIGEST: Generate comprehensive weekly report
function generateWeeklyDigest(chatId, chatTypeParam, senderAddress = null, isGroupChat = false) {
const trends = analyzeTrendingTopics(chatId, 7, senderAddress, isGroupChat);
if (!trends || trends.totalNotes < 3) {
return null; // Not enough data for meaningful digest
}
// Get weekly stats
let stats = weeklyStats.get(chatId);
if (!stats) {
stats = { weekStart: Date.now(), saves: 0, searches: 0, views: 0, lastDigestSent: 0 };
weeklyStats.set(chatId, stats);
}
// Calculate previous week stats (from notes created in last 7 days)
const lastWeekStart = new Date(Date.now() - 14 * 24 * 60 * 60 * 1000).toISOString();
let previousWeekNotes, totalNotes;
// CRITICAL PRIVACY FIX:
// 1. In DMs, only count user's own notes
// 2. ALWAYS filter by chatType to prevent DM notes leaking into groups
// Use parameter if provided, otherwise derive from isGroupChat
const actualChatType = chatTypeParam || (isGroupChat ? 'group' : 'dm');
if (!isGroupChat && senderAddress) {
previousWeekNotes = db.prepare(`
SELECT COUNT(*) as count FROM notes
WHERE chatId = ? AND chatType = ? AND savedBy = ? AND createdAt BETWEEN ? AND ?
`).get(chatId, actualChatType, senderAddress, lastWeekStart, new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString());
totalNotes = db.prepare('SELECT COUNT(*) as count FROM notes WHERE chatId = ? AND chatType = ? AND savedBy = ?').get(chatId, actualChatType, senderAddress);
} else {
previousWeekNotes = db.prepare(`
SELECT COUNT(*) as count FROM notes
WHERE chatId = ? AND chatType = ? AND createdAt BETWEEN ? AND ?
`).get(chatId, actualChatType, lastWeekStart, new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString());
totalNotes = db.prepare('SELECT COUNT(*) as count FROM notes WHERE chatId = ? AND chatType = ?').get(chatId, actualChatType);
}
const weekChange = trends.totalNotes - (previousWeekNotes?.count || 0);
// Calculate team level based on total notes
const teamLevel = Math.floor(totalNotes.count / 10) + 1;
const nextLevelAt = teamLevel * 10;
const progress = ((totalNotes.count % 10) / 10) * 100;
// Get unsaved detections from last week (only for groups)
const unsaved = [];
if (isGroupChat && groupAnalytics.has(chatId)) {
const analytics = groupAnalytics.get(chatId);
const weeklyDetections = analytics.detectedInfo.filter(
item => Date.now() - item.timestamp < 7 * 24 * 60 * 60 * 1000
);
for (const detection of weeklyDetections) {
if (detection.type === 'address' || detection.type === 'url') {
// CRITICAL PRIVACY FIX: Filter by chatType to prevent checking DM notes in group context
const exists = db.prepare(`
SELECT id FROM notes WHERE chatId = ? AND chatType = ? AND content LIKE ? LIMIT 1
`).get(chatId, actualChatType, `%${detection.content}%`);
if (!exists) {
unsaved.push(detection);
}
}
}
}
// Find knowledge gaps (keywords mentioned but few notes)
const knowledgeGaps = [];
if (trends.topKeywords.length > 0) {
for (const [keyword, count] of trends.topKeywords.slice(0, 3)) {
let notesCount;
if (!isGroupChat && senderAddress) {
notesCount = db.prepare(`
SELECT COUNT(*) as count FROM notes
WHERE chatId = ? AND chatType = ? AND savedBy = ? AND LOWER(content) LIKE ?
`).get(chatId, actualChatType, senderAddress, `%${keyword}%`);
} else {
notesCount = db.prepare(`
SELECT COUNT(*) as count FROM notes
WHERE chatId = ? AND chatType = ? AND LOWER(content) LIKE ?
`).get(chatId, actualChatType, `%${keyword}%`);
}
if (count > 3 && notesCount.count < 2) {
knowledgeGaps.push({ keyword, mentions: count, notes: notesCount.count });
}
}
}
return {
totalNotes: trends.totalNotes,
weekChange,
topContributor: trends.topContributors[0],
topCategory: trends.topCategories[0],
topKeywords: trends.topKeywords.slice(0, 3),
popularNotes: trends.popularNotes.slice(0, 2),
teamLevel,
nextLevelAt,
progress,
unsaved: unsaved.slice(0, 3),
knowledgeGaps: knowledgeGaps.slice(0, 2),
chatType: actualChatType
};
}
// FORMAT WEEKLY DIGEST
function formatWeeklyDigest(digest) {
if (!digest) return null;
const changeEmoji = digest.weekChange > 0 ? '📈' : digest.weekChange < 0 ? '📉' : '➡️';
const changeText = digest.weekChange > 0 ? `+${digest.weekChange}` : digest.weekChange < 0 ? `${digest.weekChange}` : '±0';
let report = `📊 DRAGMAN WEEKLY REPORT\n\n`;
report += `Your ${digest.chatType === 'group' ? 'team' : 'knowledge base'} had a productive week! 🎉\n\n`;
// Activity section
report += `📈 ACTIVITY\n`;
report += `• ${digest.totalNotes} notes saved this week ${changeEmoji} (${changeText} from last week)\n`;
// MVP section (only for groups)
if (digest.chatType === 'group' && digest.topContributor) {
report += `\n🏆 MVP OF THE WEEK\n`;
report += `🥇 ${digest.topContributor[0]}: ${digest.topContributor[1]} saves\n`;
if (digest.topContributor[1] >= 5) {
report += ` ${digest.topContributor[0]} is on fire! 🔥\n`;
}
}
// Trending section
if (digest.topCategory) {
report += `\n🔥 TRENDING\n`;
digest.topKeywords.forEach(([keyword, count], idx) => {
report += `${idx + 1}. ${keyword} (${count} mentions)\n`;
});
}
// Popular notes
if (digest.popularNotes.length > 0) {
report += `\n⭐ MOST VIEWED\n`;
digest.popularNotes.forEach((note, idx) => {
report += `${idx + 1}. ${truncate(note.content, 50)} (${note.viewCount} views)\n`;
});
}
// Smart insights
const hasInsights = digest.unsaved.length > 0 || digest.knowledgeGaps.length > 0;
if (hasInsights) {
report += `\n💡 SMART INSIGHTS\n`;
if (digest.unsaved.length > 0) {
const unsavedCount = digest.unsaved.length;
const types = [...new Set(digest.unsaved.map(item => item.type))];
const typeText = types.includes('address') ? 'addresses' : types.includes('url') ? 'links' : 'items';
report += `• ${unsavedCount} ${typeText} detected but not saved\n`;
report += ` Type @dragman suggestions to review\n\n`;
}
if (digest.knowledgeGaps.length > 0) {
digest.knowledgeGaps.forEach(gap => {
report += `• "${gap.keyword}" mentioned ${gap.mentions}x but only ${gap.notes} note(s) saved\n`;
report += ` Missing knowledge? Save some guides!\n\n`;
});
}
}
// Team progress (gamification)
report += `🎯 TEAM PROGRESS\n`;
report += `Level ${digest.teamLevel} → ${Math.round(digest.progress)}% to Level ${digest.teamLevel + 1}\n`;
report += `(${digest.nextLevelAt - (digest.teamLevel - 1) * 10 - Math.floor((digest.progress / 100) * 10)} more notes to next level!)\n\n`;
if (digest.teamLevel >= 5) {
report += `🏆 Achievement unlocked: Knowledge Masters!\n\n`;
}
report += `Keep building ${digest.chatType === 'group' ? 'team' : ''} knowledge! 🚀`;
return report;
}
// ==================== HELPER FUNCTIONS ====================
function saveConversationType(chatId, chatType) {
try {
db.prepare(`
INSERT INTO conversation_types (chatId, chatType, updatedAt)
VALUES (?, ?, ?)
ON CONFLICT(chatId) DO UPDATE SET chatType = ?, updatedAt = ?
`).run(chatId, chatType, new Date().toISOString(), chatType, new Date().toISOString());
conversationTypes.set(chatId, chatType); // Also update memory
} catch (e) {
log('error', 'Failed to save conversation type', { chatId: chatId.substring(0, 20), error: e.message });