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
use anyhow::{Context, Result};
use chrono::{DateTime, Local, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

/// Main memory index - the unified relationship file
#[derive(Debug, Serialize, Deserialize)]
pub struct MemIndex {
    /// Index version
    pub version: String,

    /// User identification and context
    pub user: UserContext,

    /// All memory blocks with metadata
    pub blocks: HashMap<String, BlockMeta>,

    /// Active projects and their relationships
    pub projects: HashMap<String, ProjectInfo>,

    /// Concept graph - relationships between ideas
    pub concepts: ConceptGraph,

    /// Current session context
    pub session: SessionContext,

    /// Statistics and metadata
    pub stats: IndexStats,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UserContext {
    /// User identifier (name or handle)
    pub name: String,

    /// Quick preference flags (loaded from prefs/user_flags.json)
    pub flags: HashMap<String, bool>,

    /// Style preferences (loaded from prefs/style.json)
    pub style: StylePrefs,

    /// Communication tone (loaded from prefs/tone.json)
    pub tone: TonePrefs,

    /// Current working directory preference
    pub preferred_cwd: Option<PathBuf>,

    /// Active project (if any)
    pub active_project: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct StylePrefs {
    /// Output style: terse, normal, verbose
    pub verbosity: String,

    /// Prefers bullet points
    pub bullet_preference: bool,

    /// ASCII over emoji
    pub ascii_preferred: bool,

    /// Code style preferences
    pub code_style: HashMap<String, String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TonePrefs {
    /// Humor level 0-10
    pub humor_level: u8,

    /// Warning verbosity
    pub warning_style: String, // "minimal", "normal", "detailed"

    /// Explanation depth
    pub explanation_depth: String, // "eli5", "normal", "expert"

    /// Encouragement style
    pub encouragement: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct BlockMeta {
    /// Filename in blocks/ directory
    pub filename: String,

    /// When this block was created
    pub created: DateTime<Utc>,

    /// Last accessed time
    pub last_accessed: DateTime<Utc>,

    /// Size in bytes
    pub size: usize,

    /// Number of messages/entries
    pub entry_count: usize,

    /// Key topics/concepts in this block
    pub topics: Vec<String>,

    /// Related projects
    pub projects: Vec<String>,

    /// Quick summary
    pub summary: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ProjectInfo {
    /// Project name
    pub name: String,

    /// Project root path
    pub path: PathBuf,

    /// Current status
    pub status: String, // "active", "paused", "completed"

    /// Technologies used
    pub tech_stack: Vec<String>,

    /// Related memory blocks
    pub memory_blocks: Vec<String>,

    /// Current focus/task
    pub current_focus: Option<String>,

    /// Key decisions/notes
    pub notes: Vec<String>,

    /// Last activity
    pub last_activity: DateTime<Utc>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ConceptGraph {
    /// Concept -> Related concepts with weight
    pub relationships: HashMap<String, Vec<(String, f32)>>,

    /// Concept -> Memory blocks containing it
    pub concept_blocks: HashMap<String, Vec<String>>,

    /// Recent concepts (for quick access)
    pub recent: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SessionContext {
    /// Current session ID
    pub session_id: String,

    /// Session start time
    pub started: DateTime<Utc>,

    /// Topics discussed this session
    pub topics: Vec<String>,

    /// Files/directories accessed
    pub accessed_paths: Vec<PathBuf>,

    /// Tools used
    pub tools_used: Vec<String>,

    /// Nudges given (what we suggested)
    pub nudges: Vec<Nudge>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Nudge {
    /// What was suggested
    pub suggestion: String,

    /// Why it was suggested
    pub reason: String,

    /// When it was suggested
    pub timestamp: DateTime<Utc>,

    /// Was it accepted/rejected/ignored
    pub response: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct IndexStats {
    /// Total memory blocks
    pub total_blocks: usize,

    /// Total size of all blocks
    pub total_size: usize,

    /// Total conversations
    pub total_conversations: usize,

    /// Index created date
    pub created: DateTime<Utc>,

    /// Last updated
    pub last_updated: DateTime<Utc>,

    /// Compression ratio achieved
    pub avg_compression_ratio: f32,
}

impl Default for MemIndex {
    fn default() -> Self {
        Self::new()
    }
}

impl MemIndex {
    /// Load the index from ~/.mem8/memindex.json
    pub fn load() -> Result<Self> {
        let path = Self::index_path()?;

        if path.exists() {
            let content = fs::read_to_string(&path)?;
            let mut index: MemIndex = serde_json::from_str(&content)?;

            // Load user preferences
            index.load_user_prefs()?;

            Ok(index)
        } else {
            Ok(Self::new())
        }
    }

    /// Create a new index
    pub fn new() -> Self {
        Self {
            version: "1.0.0".to_string(),
            user: UserContext {
                name: whoami::username(),
                flags: HashMap::new(),
                style: StylePrefs {
                    verbosity: "normal".to_string(),
                    bullet_preference: true,
                    ascii_preferred: false,
                    code_style: HashMap::new(),
                },
                tone: TonePrefs {
                    humor_level: 5,
                    warning_style: "normal".to_string(),
                    explanation_depth: "normal".to_string(),
                    encouragement: true,
                },
                preferred_cwd: None,
                active_project: None,
            },
            blocks: HashMap::new(),
            projects: HashMap::new(),
            concepts: ConceptGraph {
                relationships: HashMap::new(),
                concept_blocks: HashMap::new(),
                recent: Vec::new(),
            },
            session: SessionContext {
                session_id: uuid::Uuid::new_v4().to_string(),
                started: Utc::now(),
                topics: Vec::new(),
                accessed_paths: Vec::new(),
                tools_used: Vec::new(),
                nudges: Vec::new(),
            },
            stats: IndexStats {
                total_blocks: 0,
                total_size: 0,
                total_conversations: 0,
                created: Utc::now(),
                last_updated: Utc::now(),
                avg_compression_ratio: 0.0,
            },
        }
    }

    /// Save the index
    pub fn save(&self) -> Result<()> {
        let path = Self::index_path()?;

        // Ensure directory exists
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }

        // Save main index
        let content = serde_json::to_string_pretty(self)?;
        fs::write(&path, content)?;

        // Save user preferences
        self.save_user_prefs()?;

        Ok(())
    }

    /// Get index file path
    fn index_path() -> Result<PathBuf> {
        let home = dirs::home_dir().context("Could not find home directory")?;
        Ok(home.join(".mem8").join("memindex.json"))
    }

    /// Load user preferences from separate files
    fn load_user_prefs(&mut self) -> Result<()> {
        let mem8_dir = dirs::home_dir()
            .context("Could not find home directory")?
            .join(".mem8");

        // Load user flags
        let flags_path = mem8_dir.join("prefs").join("user_flags.json");
        if flags_path.exists() {
            let content = fs::read_to_string(&flags_path)?;
            self.user.flags = serde_json::from_str(&content)?;
        }

        // Load style preferences
        let style_path = mem8_dir.join("prefs").join("style.json");
        if style_path.exists() {
            let content = fs::read_to_string(&style_path)?;
            self.user.style = serde_json::from_str(&content)?;
        }

        // Load tone preferences
        let tone_path = mem8_dir.join("prefs").join("tone.json");
        if tone_path.exists() {
            let content = fs::read_to_string(&tone_path)?;
            self.user.tone = serde_json::from_str(&content)?;
        }

        Ok(())
    }

    /// Save user preferences to separate files
    fn save_user_prefs(&self) -> Result<()> {
        let prefs_dir = dirs::home_dir()
            .context("Could not find home directory")?
            .join(".mem8")
            .join("prefs");

        fs::create_dir_all(&prefs_dir)?;

        // Save user flags
        let flags_content = serde_json::to_string_pretty(&self.user.flags)?;
        fs::write(prefs_dir.join("user_flags.json"), flags_content)?;

        // Save style
        let style_content = serde_json::to_string_pretty(&self.user.style)?;
        fs::write(prefs_dir.join("style.json"), style_content)?;

        // Save tone
        let tone_content = serde_json::to_string_pretty(&self.user.tone)?;
        fs::write(prefs_dir.join("tone.json"), tone_content)?;

        Ok(())
    }

    /// Register a new memory block
    pub fn register_block(&mut self, filename: &str, path: &Path) -> Result<()> {
        let metadata = fs::metadata(path)?;

        let block_meta = BlockMeta {
            filename: filename.to_string(),
            created: Utc::now(),
            last_accessed: Utc::now(),
            size: metadata.len() as usize,
            entry_count: 0, // Would be extracted from .m8 file
            topics: Vec::new(),
            projects: Vec::new(),
            summary: format!("Memory block: {}", filename),
        };

        self.blocks.insert(filename.to_string(), block_meta);
        self.stats.total_blocks = self.blocks.len();
        self.stats.total_size = self.blocks.values().map(|b| b.size).sum();
        self.stats.last_updated = Utc::now();

        Ok(())
    }

    /// Add or update a project
    pub fn update_project(&mut self, name: &str, path: PathBuf) {
        let project = self
            .projects
            .entry(name.to_string())
            .or_insert_with(|| ProjectInfo {
                name: name.to_string(),
                path: path.clone(),
                status: "active".to_string(),
                tech_stack: Vec::new(),
                memory_blocks: Vec::new(),
                current_focus: None,
                notes: Vec::new(),
                last_activity: Utc::now(),
            });

        project.last_activity = Utc::now();
        self.stats.last_updated = Utc::now();
    }

    /// Record a nudge given to the user
    pub fn add_nudge(&mut self, suggestion: &str, reason: &str) {
        self.session.nudges.push(Nudge {
            suggestion: suggestion.to_string(),
            reason: reason.to_string(),
            timestamp: Utc::now(),
            response: None,
        });
    }

    /// Update concept relationships
    pub fn add_concept_relation(&mut self, concept1: &str, concept2: &str, weight: f32) {
        self.concepts
            .relationships
            .entry(concept1.to_string())
            .or_default()
            .push((concept2.to_string(), weight));

        self.concepts
            .relationships
            .entry(concept2.to_string())
            .or_default()
            .push((concept1.to_string(), weight));
    }

    /// Write daily journal entry
    pub fn write_journal_entry(&self, content: &str) -> Result<()> {
        let journal_dir = dirs::home_dir()
            .context("Could not find home directory")?
            .join(".mem8")
            .join("journal");

        fs::create_dir_all(&journal_dir)?;

        let today = Local::now().format("%Y-%m-%d");
        let journal_path = journal_dir.join(format!("{}.ctx.md", today));

        // Append to existing or create new
        let mut existing = if journal_path.exists() {
            fs::read_to_string(&journal_path)?
        } else {
            format!("# Memory Journal - {}\n\n", today)
        };

        existing.push_str(&format!(
            "\n## {} - Session {}\n\n",
            Local::now().format("%H:%M"),
            &self.session.session_id[..8]
        ));
        existing.push_str(content);
        existing.push('\n');

        fs::write(&journal_path, existing)?;

        Ok(())
    }
}