smart-tree 8.0.1

Smart Tree - An intelligent, AI-friendly directory visualization tool
Documentation
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
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use uuid::Uuid;

/// Master index for all .m8 memory blocks and user context
#[derive(Debug, Serialize, Deserialize)]
pub struct Mem8Index {
    /// Index metadata
    pub metadata: IndexMetadata,
    
    /// User profile with preferences, patterns, and quirks
    pub user_profile: UserProfile,
    
    /// All registered memory blocks
    pub memory_blocks: HashMap<Uuid, MemoryBlockEntry>,
    
    /// Active projects and their status
    pub projects: HashMap<String, ProjectContext>,
    
    /// Relationship graph between concepts, projects, and memories
    pub relationships: RelationshipGraph,
    
    /// Temporal index for time-based queries
    pub temporal_index: TemporalIndex,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct IndexMetadata {
    pub version: String,
    pub created_at: DateTime<Utc>,
    pub last_updated: DateTime<Utc>,
    pub total_memories: usize,
    pub total_conversations: usize,
    pub compression_ratio: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UserProfile {
    /// User's name or identifier
    pub name: String,
    
    /// Technology preferences
    pub preferences: TechPreferences,
    
    /// Communication patterns and triggers
    pub communication_style: CommunicationStyle,
    
    /// Learning progress and knowledge areas
    pub knowledge_map: KnowledgeMap,
    
    /// Personality insights from conversations
    pub personality_insights: PersonalityInsights,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TechPreferences {
    /// Package managers (npm -> pnpm preference)
    pub package_managers: HashMap<String, PreferenceLevel>,
    
    /// Programming languages by preference
    pub languages: HashMap<String, PreferenceLevel>,
    
    /// Operating systems and reactions
    pub operating_systems: HashMap<String, OSPreference>,
    
    /// Development tools and IDEs
    pub tools: HashMap<String, PreferenceLevel>,
    
    /// Framework choices
    pub frameworks: HashMap<String, PreferenceLevel>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PreferenceLevel {
    pub preference: i8, // -10 (hate) to +10 (love)
    pub reasons: Vec<String>,
    pub context: Vec<String>, // When this preference applies
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct OSPreference {
    pub base_preference: i8,
    pub reactions: Vec<String>, // "Adverse reaction when over-discussing"
    pub nudge_strategy: Option<String>, // "Mention WSL for compatibility"
    pub compatibility_focus: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CommunicationStyle {
    /// Topics that trigger reactions
    pub trigger_topics: HashMap<String, ReactionPattern>,
    
    /// Preferred explanation depth
    pub detail_preference: DetailLevel,
    
    /// Humor tolerance and type
    pub humor_style: HumorStyle,
    
    /// Learning patterns
    pub learning_style: LearningStyle,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ReactionPattern {
    pub topic: String,
    pub reaction_type: String, // "adverse", "enthusiastic", "skeptical"
    pub suggested_approach: Option<String>,
    pub examples: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum DetailLevel {
    Concise,
    Balanced,
    Comprehensive,
    ExtremeDetail,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct HumorStyle {
    pub appreciates_puns: bool,
    pub dark_humor_tolerance: f32,
    pub technical_jokes: bool,
    pub pop_culture_references: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LearningStyle {
    pub prefers_examples: bool,
    pub learns_by_doing: bool,
    pub needs_theory_first: bool,
    pub pattern_recognition: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct KnowledgeMap {
    /// Areas of expertise
    pub expertise: HashMap<String, ExpertiseLevel>,
    
    /// Current learning topics
    pub learning: HashMap<String, LearningProgress>,
    
    /// Completed projects/skills
    pub accomplished: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ExpertiseLevel {
    pub level: u8, // 0-10
    pub demonstrated_in: Vec<Uuid>, // Memory block references
    pub key_insights: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LearningProgress {
    pub started: DateTime<Utc>,
    pub current_understanding: u8, // 0-10
    pub blockers: Vec<String>,
    pub breakthrough_moments: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PersonalityInsights {
    /// Work style patterns
    pub work_style: WorkStyle,
    
    /// Problem-solving approach
    pub problem_solving: ProblemSolvingStyle,
    
    /// Collaboration preferences
    pub collaboration: CollaborationStyle,
    
    /// Stress indicators and management
    pub stress_patterns: StressPatterns,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct WorkStyle {
    pub perfectionist_score: f32,
    pub experimentation_willingness: f32,
    pub planning_vs_doing: f32, // -1 (all planning) to +1 (all doing)
    pub multitasking_preference: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ProblemSolvingStyle {
    pub bottom_up_vs_top_down: f32, // -1 to +1
    pub research_first: bool,
    pub trial_and_error_comfort: f32,
    pub asks_for_help_threshold: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CollaborationStyle {
    pub prefers_autonomy: bool,
    pub pair_programming_comfort: f32,
    pub feedback_style: String, // "direct", "gentle", "humor-wrapped"
    pub teaching_enthusiasm: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct StressPatterns {
    pub indicators: Vec<String>, // "Increased typos", "Shorter messages"
    pub triggers: Vec<String>, // "Deadlines", "Unclear requirements"
    pub coping_mechanisms: Vec<String>, // "Humor", "Deep technical dives"
}

#[derive(Debug, Serialize, Deserialize)]
pub struct MemoryBlockEntry {
    pub id: Uuid,
    pub file_path: PathBuf,
    pub source_type: String, // "claude", "chatgpt", "local"
    pub created_at: DateTime<Utc>,
    pub message_count: usize,
    pub compressed_size: usize,
    pub tags: Vec<String>,
    pub summary: String,
    pub key_concepts: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ProjectContext {
    pub name: String,
    pub path: PathBuf,
    pub status: ProjectStatus,
    pub technologies: Vec<String>,
    pub current_focus: Option<String>,
    pub blockers: Vec<String>,
    pub last_worked: DateTime<Utc>,
    pub related_memories: Vec<Uuid>,
    pub notes: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum ProjectStatus {
    Active,
    Paused,
    Completed,
    Archived,
    Planning,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RelationshipGraph {
    /// Concept -> Related concepts with strength
    pub concept_links: HashMap<String, Vec<(String, f32)>>,
    
    /// Project -> Related projects
    pub project_links: HashMap<String, Vec<String>>,
    
    /// Memory blocks that reference each other
    pub memory_links: HashMap<Uuid, Vec<Uuid>>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TemporalIndex {
    /// Date -> Memory blocks created that day
    pub daily_index: HashMap<String, Vec<Uuid>>,
    
    /// Week -> Summary of that week's work
    pub weekly_summaries: HashMap<String, WeeklySummary>,
    
    /// Patterns by time of day
    pub circadian_patterns: CircadianPatterns,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct WeeklySummary {
    pub projects_touched: Vec<String>,
    pub concepts_explored: Vec<String>,
    pub breakthrough_moments: Vec<String>,
    pub total_messages: usize,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CircadianPatterns {
    pub most_active_hours: Vec<u8>,
    pub deep_work_windows: Vec<(u8, u8)>,
    pub communication_peaks: Vec<u8>,
}

impl Mem8Index {
    /// Load or create index at ~/.mem8/index.m8
    pub fn load_or_create() -> Result<Self> {
        let index_path = Self::index_path()?;
        
        if index_path.exists() {
            let data = fs::read(&index_path)?;
            let decompressed = zstd::decode_all(&data[..])?;
            let index = rmp_serde::from_slice(&decompressed)?;
            Ok(index)
        } else {
            Ok(Self::new())
        }
    }
    
    /// Create new empty index
    pub fn new() -> Self {
        Self {
            metadata: IndexMetadata {
                version: "1.0.0".to_string(),
                created_at: Utc::now(),
                last_updated: Utc::now(),
                total_memories: 0,
                total_conversations: 0,
                compression_ratio: 0.0,
            },
            user_profile: UserProfile::default(),
            memory_blocks: HashMap::new(),
            projects: HashMap::new(),
            relationships: RelationshipGraph {
                concept_links: HashMap::new(),
                project_links: HashMap::new(),
                memory_links: HashMap::new(),
            },
            temporal_index: TemporalIndex {
                daily_index: HashMap::new(),
                weekly_summaries: HashMap::new(),
                circadian_patterns: CircadianPatterns {
                    most_active_hours: vec![],
                    deep_work_windows: vec![],
                    communication_peaks: vec![],
                },
            },
        }
    }
    
    /// Save index to disk
    pub fn save(&self) -> Result<()> {
        let index_path = Self::index_path()?;
        
        // Ensure directory exists
        if let Some(parent) = index_path.parent() {
            fs::create_dir_all(parent)?;
        }
        
        // Serialize and compress
        let serialized = rmp_serde::to_vec(self)?;
        let compressed = zstd::encode_all(&serialized[..], 3)?;
        
        fs::write(&index_path, compressed)?;
        Ok(())
    }
    
    /// Get index file path
    fn index_path() -> Result<PathBuf> {
        let home = dirs::home_dir()
            .context("Could not find home directory")?;
        Ok(home.join(".st").join("mem8").join("index.m8"))
    }
    
    /// Update from conversation analysis
    pub fn learn_from_conversation(&mut self, messages: &[Message]) {
        // Extract preferences
        for msg in messages {
            self.extract_preferences(&msg.content);
            self.extract_project_references(&msg.content);
            self.update_communication_patterns(&msg.content);
        }
        
        self.metadata.last_updated = Utc::now();
    }
    
    fn extract_preferences(&mut self, content: &str) {
        // Example: Detect package manager preferences
        if content.contains("npm") && content.contains("hate") {
            self.user_profile.preferences.package_managers
                .entry("npm".to_string())
                .or_insert(PreferenceLevel {
                    preference: -8,
                    reasons: vec!["Expressed hatred".to_string()],
                    context: vec![],
                })
                .preference = -8;
        }
        
        if content.contains("pnpm") && (content.contains("prefer") || content.contains("love")) {
            self.user_profile.preferences.package_managers
                .entry("pnpm".to_string())
                .or_insert(PreferenceLevel {
                    preference: 8,
                    reasons: vec!["Expressed preference".to_string()],
                    context: vec![],
                })
                .preference = 8;
        }
        
        // Detect OS reactions
        if content.to_lowercase().contains("windows") {
            let words: Vec<&str> = content.split_whitespace().collect();
            let window_pos = words.iter().position(|&w| w.to_lowercase().contains("windows"));
            
            if let Some(pos) = window_pos {
                // Check surrounding context for reaction
                let negative_words = ["hate", "dislike", "avoid", "annoying", "frustrating"];
                let has_negative = words.iter().any(|w| negative_words.contains(&w.to_lowercase().as_str()));
                
                if has_negative {
                    self.user_profile.preferences.operating_systems
                        .entry("Windows".to_string())
                        .or_insert(OSPreference {
                            base_preference: -5,
                            reactions: vec!["Adverse reaction detected".to_string()],
                            nudge_strategy: Some("Mention WSL for compatibility".to_string()),
                            compatibility_focus: true,
                        });
                }
            }
        }
    }
    
    fn extract_project_references(&mut self, content: &str) {
        // Look for project paths
        let path_regex = regex::Regex::new(r"(?:^|[\s\"\'])((?:/[\w\-\.]+)+|(?:~/[\w\-\.]+)+)").unwrap();
        for cap in path_regex.captures_iter(content) {
            if let Some(path_match) = cap.get(1) {
                let path = path_match.as_str();
                if path.contains("source") || path.contains("project") {
                    // Potential project reference
                    let project_name = path.split('/').last().unwrap_or("unknown");
                    self.projects.entry(project_name.to_string())
                        .or_insert(ProjectContext {
                            name: project_name.to_string(),
                            path: PathBuf::from(path),
                            status: ProjectStatus::Active,
                            technologies: vec![],
                            current_focus: None,
                            blockers: vec![],
                            last_worked: Utc::now(),
                            related_memories: vec![],
                            notes: vec![],
                        })
                        .last_worked = Utc::now();
                }
            }
        }
    }
    
    fn update_communication_patterns(&mut self, content: &str) {
        // This would analyze communication style, but keeping it simple for now
        let word_count = content.split_whitespace().count();
        if word_count > 200 {
            self.user_profile.communication_style.detail_preference = DetailLevel::Comprehensive;
        }
    }
}

impl Default for UserProfile {
    fn default() -> Self {
        Self {
            name: String::from("User"),
            preferences: TechPreferences {
                package_managers: HashMap::new(),
                languages: HashMap::new(),
                operating_systems: HashMap::new(),
                tools: HashMap::new(),
                frameworks: HashMap::new(),
            },
            communication_style: CommunicationStyle {
                trigger_topics: HashMap::new(),
                detail_preference: DetailLevel::Balanced,
                humor_style: HumorStyle {
                    appreciates_puns: true,
                    dark_humor_tolerance: 0.5,
                    technical_jokes: true,
                    pop_culture_references: true,
                },
                learning_style: LearningStyle {
                    prefers_examples: true,
                    learns_by_doing: true,
                    needs_theory_first: false,
                    pattern_recognition: 0.8,
                },
            },
            knowledge_map: KnowledgeMap {
                expertise: HashMap::new(),
                learning: HashMap::new(),
                accomplished: vec![],
            },
            personality_insights: PersonalityInsights {
                work_style: WorkStyle {
                    perfectionist_score: 0.5,
                    experimentation_willingness: 0.8,
                    planning_vs_doing: 0.3,
                    multitasking_preference: true,
                },
                problem_solving: ProblemSolvingStyle {
                    bottom_up_vs_top_down: 0.0,
                    research_first: true,
                    trial_and_error_comfort: 0.7,
                    asks_for_help_threshold: 0.3,
                },
                collaboration: CollaborationStyle {
                    prefers_autonomy: false,
                    pair_programming_comfort: 0.8,
                    feedback_style: "direct".to_string(),
                    teaching_enthusiasm: 0.9,
                },
                stress_patterns: StressPatterns {
                    indicators: vec![],
                    triggers: vec![],
                    coping_mechanisms: vec![],
                },
            },
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Message {
    pub role: String,
    pub content: String,
    pub timestamp: Option<i64>,
}