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
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
//! Consciousness persistence for Smart Tree MCP sessions
//!
//! This module saves and restores Claude's working context between sessions,
//! maintaining continuity of thought and reducing token usage by preserving
//! critical state information in .m8 consciousness files.

use anyhow::{Context, Result};
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

/// Maximum age in hours before context is considered stale
const MAX_AGE_HOURS: i64 = 24;

/// Consciousness state that persists between Claude sessions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsciousnessState {
    /// Session identifier
    pub session_id: String,

    /// Timestamp of last save
    pub last_saved: DateTime<Utc>,

    /// Current working directory
    pub working_directory: PathBuf,

    /// Active project context
    pub project_context: ProjectContext,

    /// Recent file operations
    pub file_history: Vec<FileOperation>,

    /// Tokenization state (0x80 = node_modules, etc)
    pub tokenization_rules: HashMap<String, u8>,

    /// Key insights and breakthroughs
    pub insights: Vec<Insight>,

    /// SID/VIC-II philosophy embeddings
    pub philosophy: PhilosophyEmbedding,

    /// Active todo items
    pub todos: Vec<TodoItem>,

    /// Custom context notes
    pub notes: String,
}

/// Project-specific context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectContext {
    pub project_name: String,
    pub project_type: String, // rust, node, python, etc
    pub key_files: Vec<PathBuf>,
    pub dependencies: Vec<String>,
    pub current_focus: String, // What we're working on
}

/// Record of file operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileOperation {
    pub timestamp: DateTime<Utc>,
    pub operation: String, // read, write, edit, create
    pub file_path: PathBuf,
    pub summary: String,
}

/// Captured insights and breakthroughs
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Insight {
    pub timestamp: DateTime<Utc>,
    pub category: String, // breakthrough, solution, pattern, joke
    pub content: String,
    pub keywords: Vec<String>,
}

/// SID/VIC-II philosophy from C64 era
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PhilosophyEmbedding {
    pub sid_waves: bool,       // Wave-based sound synthesis
    pub vic_sprites: bool,     // Sprite-based visualization
    pub c64_nostalgia: String, // "A gentleman and a scholar"
}

/// Todo item tracking
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TodoItem {
    pub content: String,
    pub status: String, // pending, in_progress, completed
    pub created: DateTime<Utc>,
}

/// Result of relevance check for consciousness state
struct RelevanceResult {
    is_relevant: bool,
    reason: String,
}

impl Default for ConsciousnessState {
    fn default() -> Self {
        let mut tokenization_rules = HashMap::new();
        // Default tokenization from our work
        tokenization_rules.insert("node_modules".to_string(), 0x80);
        tokenization_rules.insert(".git".to_string(), 0x81);
        tokenization_rules.insert("target".to_string(), 0x82);
        tokenization_rules.insert("dist".to_string(), 0x83);

        Self {
            session_id: uuid::Uuid::new_v4().to_string(),
            last_saved: Utc::now(),
            working_directory: std::env::current_dir().unwrap_or_default(),
            project_context: ProjectContext {
                project_name: "unknown".to_string(),
                project_type: "unknown".to_string(),
                key_files: vec![],
                dependencies: vec![],
                current_focus: String::new(),
            },
            file_history: vec![],
            tokenization_rules,
            insights: vec![],
            philosophy: PhilosophyEmbedding {
                sid_waves: true,
                vic_sprites: true,
                c64_nostalgia: "A gentleman and a scholar indeed!".to_string(),
            },
            todos: vec![],
            notes: String::new(),
        }
    }
}

/// Manages consciousness persistence
pub struct ConsciousnessManager {
    state: ConsciousnessState,
    save_path: PathBuf,
}

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

impl ConsciousnessManager {
    /// Create new consciousness manager
    pub fn new() -> Self {
        let save_path = PathBuf::from(".mem8/.aye_consciousness.m8");
        let state = Self::load_or_default(&save_path, false);

        Self { state, save_path }
    }

    /// Create new consciousness manager (silent - no output)
    pub fn new_silent() -> Self {
        let save_path = PathBuf::from("/.mem8/.aye_consciousness.m8");
        let state = Self::load_or_default(&save_path, true);

        Self { state, save_path }
    }

    /// Initialize with custom path
    pub fn with_path(save_path: PathBuf) -> Self {
        let state = Self::load_or_default(&save_path, false);
        Self { state, save_path }
    }

    /// Load consciousness from file or create default
    fn load_or_default(path: &Path, silent: bool) -> ConsciousnessState {
        if path.exists() {
            match fs::read_to_string(path) {
                Ok(content) => match serde_json::from_str(&content) {
                    Ok(state) => {
                        if !silent {
                            eprintln!("🧠 Restored consciousness from {}", path.display());
                        }
                        return state;
                    }
                    Err(e) => {
                        if !silent {
                            eprintln!("⚠️ Failed to parse consciousness: {}", e);
                        }
                    }
                },
                Err(e) => {
                    if !silent {
                        eprintln!("⚠️ Failed to read consciousness: {}", e);
                    }
                }
            }
        }

        ConsciousnessState::default()
    }

    /// Save current consciousness state
    pub fn save(&mut self) -> Result<()> {
        self.state.last_saved = Utc::now();

        let json = serde_json::to_string_pretty(&self.state)
            .context("Failed to serialize consciousness")?;

        fs::write(&self.save_path, json).context("Failed to write consciousness file")?;

        eprintln!("💾 Saved consciousness to {}", self.save_path.display());
        Ok(())
    }

    /// Restore consciousness from file with smart relevance checking
    pub fn restore(&mut self) -> Result<()> {
        if !self.save_path.exists() {
            return Err(anyhow::anyhow!(
                "No consciousness file found at {}",
                self.save_path.display()
            ));
        }

        let content =
            fs::read_to_string(&self.save_path).context("Failed to read consciousness file")?;

        self.state = serde_json::from_str(&content).context("Failed to parse consciousness")?;

        // Check relevance before displaying
        let relevance = self.check_relevance();
        if !relevance.is_relevant {
            eprintln!("🧠 Previous context skipped: {}", relevance.reason);
            eprintln!("   Use `st -m context .` for fresh project overview.");
            // Reset to fresh state
            self.state = ConsciousnessState::default();
            return Ok(());
        }

        eprintln!(
            "🧠 Consciousness restored from {}",
            self.save_path.display()
        );

        Ok(())
    }

    /// Silent restore - returns true if context is relevant, false otherwise
    pub fn restore_silent(&mut self) -> Result<bool> {
        if !self.save_path.exists() {
            return Err(anyhow::anyhow!(
                "No consciousness file found at {}",
                self.save_path.display()
            ));
        }

        let content =
            fs::read_to_string(&self.save_path).context("Failed to read consciousness file")?;

        self.state = serde_json::from_str(&content).context("Failed to parse consciousness")?;

        // Check relevance
        let relevance = self.check_relevance();
        if !relevance.is_relevant {
            // Reset to fresh state
            self.state = ConsciousnessState::default();
            return Ok(false);
        }

        Ok(true)
    }

    /// Check if the saved state is relevant to the current session
    fn check_relevance(&self) -> RelevanceResult {
        let current_dir = std::env::current_dir().unwrap_or_default();

        // Check 1: Project directory match (allow same project name even if path differs)
        let saved_name = self
            .state
            .working_directory
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_default();
        let current_name = current_dir
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_default();

        if !saved_name.is_empty() && !current_name.is_empty() && saved_name != current_name {
            return RelevanceResult {
                is_relevant: false,
                reason: format!(
                    "different project (saved: {}, current: {})",
                    saved_name, current_name
                ),
            };
        }

        // Check 2: Age - context older than 24 hours is stale
        let age = Utc::now().signed_duration_since(self.state.last_saved);
        if age > Duration::hours(MAX_AGE_HOURS) {
            return RelevanceResult {
                is_relevant: false,
                reason: format!("stale context ({}h old)", age.num_hours()),
            };
        }

        // Check 3: Meaningful content (filter out test data)
        let has_meaningful_history = self.state.file_history.iter().any(|op| {
            op.summary != "test"
                && !op
                    .file_path
                    .file_name()
                    .map(|n| n.to_string_lossy().starts_with("file"))
                    .unwrap_or(false)
        });

        let has_insights = !self.state.insights.is_empty();
        let has_todos = self.state.todos.iter().any(|t| t.status != "completed");
        let has_notes = !self.state.notes.is_empty();
        let has_focus = !self.state.project_context.current_focus.is_empty();
        let has_project_name = !self.state.project_context.project_name.is_empty()
            && self.state.project_context.project_name != "unknown";

        if !has_meaningful_history
            && !has_insights
            && !has_todos
            && !has_notes
            && !has_focus
            && !has_project_name
        {
            return RelevanceResult {
                is_relevant: false,
                reason: "no meaningful content (test data only)".to_string(),
            };
        }

        RelevanceResult {
            is_relevant: true,
            reason: String::new(),
        }
    }

    /// Add file operation to history
    pub fn record_file_operation(&mut self, op: &str, path: &Path, summary: &str) {
        self.state.file_history.push(FileOperation {
            timestamp: Utc::now(),
            operation: op.to_string(),
            file_path: path.to_path_buf(),
            summary: summary.to_string(),
        });

        // Keep only last 100 operations
        if self.state.file_history.len() > 100 {
            self.state.file_history.drain(0..50);
        }
    }

    /// Add insight or breakthrough
    pub fn add_insight(&mut self, category: &str, content: &str, keywords: Vec<String>) {
        self.state.insights.push(Insight {
            timestamp: Utc::now(),
            category: category.to_string(),
            content: content.to_string(),
            keywords,
        });
    }

    /// Update project context
    pub fn update_project_context(&mut self, name: &str, project_type: &str, focus: &str) {
        self.state.project_context.project_name = name.to_string();
        self.state.project_context.project_type = project_type.to_string();
        self.state.project_context.current_focus = focus.to_string();
    }

    /// Set key files for the project context
    pub fn set_key_files(&mut self, files: Vec<PathBuf>) {
        self.state.project_context.key_files = files;
    }

    /// Set dependencies for the project context
    pub fn set_dependencies(&mut self, deps: Vec<String>) {
        self.state.project_context.dependencies = deps;
    }

    /// Clear stale test data from file history
    pub fn clean_test_data(&mut self) {
        self.state.file_history.retain(|op| {
            op.summary != "test"
                || !op
                    .file_path
                    .file_name()
                    .map(|n| n.to_string_lossy().starts_with("file"))
                    .unwrap_or(false)
        });
    }

    /// Add or update todo
    pub fn update_todo(&mut self, content: &str, status: &str) {
        // Check if todo already exists
        for todo in &mut self.state.todos {
            if todo.content == content {
                todo.status = status.to_string();
                return;
            }
        }

        // Add new todo
        self.state.todos.push(TodoItem {
            content: content.to_string(),
            status: status.to_string(),
            created: Utc::now(),
        });
    }

    /// Get consciousness summary for display (relevance-aware)
    pub fn get_summary(&self) -> String {
        let relevance = self.check_relevance();
        if !relevance.is_relevant {
            return format!(
                "🧠 Previous context unavailable: {}\n   Run `st -m context .` for fresh overview.",
                relevance.reason
            );
        }

        let mut parts = Vec::new();

        // Only show project info if meaningful
        if self.state.project_context.project_name != "unknown"
            && !self.state.project_context.project_name.is_empty()
        {
            parts.push(format!(
                "📁 {} ({})",
                self.state.project_context.project_name, self.state.project_context.project_type
            ));
        }

        if !self.state.project_context.current_focus.is_empty() {
            parts.push(format!("🎯 {}", self.state.project_context.current_focus));
        }

        // Age indicator
        let age = Utc::now().signed_duration_since(self.state.last_saved);
        let age_str = if age.num_hours() > 0 {
            format!("{}h ago", age.num_hours())
        } else {
            format!("{}m ago", age.num_minutes())
        };
        parts.push(format!("⏱️ {}", age_str));

        parts.join(" | ")
    }

    /// Get context reminder for Claude (filters out test data)
    pub fn get_context_reminder(&self) -> String {
        // Only show context if we have meaningful content
        let relevance = self.check_relevance();
        if !relevance.is_relevant {
            return String::new();
        }

        let mut parts = Vec::new();

        if !self.state.project_context.current_focus.is_empty() {
            parts.push(format!(
                "Working on: {}",
                self.state.project_context.current_focus
            ));
        }

        let active_todos = self
            .state
            .todos
            .iter()
            .filter(|t| t.status != "completed")
            .count();
        if active_todos > 0 {
            parts.push(format!("{} pending todos", active_todos));
        }

        if parts.is_empty() {
            return String::new();
        }

        parts.join(" | ")
    }
}

/// Auto-save consciousness on drop
impl Drop for ConsciousnessManager {
    fn drop(&mut self) {
        // Best effort save on drop - silent to avoid duplicate messages
        self.state.last_saved = chrono::Utc::now();
        if let Ok(json) = serde_json::to_string_pretty(&self.state) {
            let _ = std::fs::write(&self.save_path, json);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn test_consciousness_persistence() {
        let dir = tempdir().unwrap();
        let save_path = dir.path().join("test_consciousness.m8");

        // Create and save
        {
            let mut manager = ConsciousnessManager::with_path(save_path.clone());
            manager.update_project_context("smart-tree", "rust", "Adding consciousness");
            manager.add_insight(
                "breakthrough",
                "Tokenization reduces context by 10x",
                vec!["tokenization".to_string(), "compression".to_string()],
            );
            manager.save().unwrap();
        }

        // Load and verify
        {
            let mut manager = ConsciousnessManager::with_path(save_path);
            manager.restore().unwrap();

            assert_eq!(manager.state.project_context.project_name, "smart-tree");
            assert_eq!(manager.state.insights.len(), 1);
            assert_eq!(manager.state.insights[0].category, "breakthrough");
        }
    }

    #[test]
    fn test_file_history_limit() {
        // Use a tempdir to avoid polluting the project's .aye_consciousness.m8
        let dir = tempdir().unwrap();
        let save_path = dir.path().join("test_history_limit.m8");
        let mut manager = ConsciousnessManager::with_path(save_path);

        // Add 150 operations
        for i in 0..150 {
            manager.record_file_operation("read", Path::new(&format!("file{}.rs", i)), "test");
        }

        // Should keep only last 100
        assert_eq!(manager.state.file_history.len(), 100);
    }
}