Skip to main content

hematite/memory/
deep_reflect.rs

1/// DeepReflect v2 — idle-triggered session memory synthesis.
2///
3/// After 5 minutes of TUI inactivity, reads the day's transcript and calls
4/// the local model to extract structured memories: files changed, decisions
5/// made, patterns observed, next steps.
6///
7/// Outputs are written to `.hematite/memories/<YYYY-MM-DD>.md`.
8/// These files are automatically injected into the system prompt at startup
9/// so Hematite knows what you were working on when you come back.
10use std::path::PathBuf;
11use std::sync::{Arc, Mutex};
12use std::time::Instant;
13use tokio::time::{sleep, Duration};
14
15pub fn spawn_deep_reflect_system(
16    last_interaction: Arc<Mutex<Instant>>,
17    engine: Arc<crate::agent::inference::InferenceEngine>,
18) {
19    tokio::spawn(async move {
20        let mut last_synthesized_hash: u64 = 0;
21
22        loop {
23            sleep(Duration::from_secs(60)).await;
24
25            let idle = { last_interaction.lock().unwrap().elapsed() };
26            if idle < Duration::from_secs(300) {
27                continue;
28            }
29
30            let today = date_string();
31            let log_path = PathBuf::from(".hematite_logs").join(format!("{}.log", today));
32            if !log_path.exists() {
33                continue;
34            }
35
36            let Ok(log_content) = std::fs::read_to_string(&log_path) else {
37                continue;
38            };
39            if log_content.trim().is_empty() {
40                continue;
41            }
42
43            // Skip if we already synthesized this exact content.
44            let hash = fast_hash(&log_content);
45            if hash == last_synthesized_hash {
46                continue;
47            }
48
49            // Cap transcript to avoid blowing the context window.
50            let transcript_slice = if log_content.len() > 8_000 {
51                &log_content[log_content.len() - 8_000..]
52            } else {
53                &log_content
54            };
55
56            let prompt = format!(
57                "You are a memory synthesizer for a coding agent. Analyze this session transcript \
58                 and extract the key information in structured form.\n\n\
59                 SESSION TRANSCRIPT:\n{}\n\n\
60                 Output ONLY this structure (no preamble, no explanation):\n\
61                 ## Files Modified\n\
62                 - list each file that was created, edited, or deleted\n\n\
63                 ## Decisions Made\n\
64                 - list key architectural or design decisions\n\n\
65                 ## Patterns Observed\n\
66                 - list any recurring issues, model behaviour patterns, or code patterns noted\n\n\
67                 ## Next Steps\n\
68                 - list any unfinished work, TODOs, or follow-up tasks mentioned\n\n\
69                 Be concise. Maximum 250 words total.",
70                transcript_slice
71            );
72
73            if let Ok(summary) = engine.generate_task(&prompt, true).await {
74                let memory_dir = PathBuf::from(".hematite").join("memories");
75                let _ = std::fs::create_dir_all(&memory_dir);
76                let mem_file = memory_dir.join(format!("{}.md", today));
77
78                let content = format!(
79                    "# Session Memory — {}\n_Synthesized by DeepReflect after idle period_\n\n{}\n",
80                    today, summary
81                );
82                let _ = std::fs::write(&mem_file, content);
83                last_synthesized_hash = hash;
84            }
85
86            // Reset idle timer so we don't re-synthesize immediately.
87            *last_interaction.lock().unwrap() = Instant::now();
88        }
89    });
90}
91
92/// Load recent memory files (last 3 days) to inject into the system prompt.
93/// Returns a formatted string ready for system prompt injection, or empty string.
94pub fn load_recent_memories() -> String {
95    let memory_dir = PathBuf::from(".hematite").join("memories");
96    if !memory_dir.exists() {
97        return String::new();
98    }
99
100    // Get last 3 memory files sorted by name (date-named, so lexicographic = chronological).
101    let mut files: Vec<_> = std::fs::read_dir(&memory_dir)
102        .ok()
103        .into_iter()
104        .flatten()
105        .filter_map(|e| e.ok())
106        .filter(|e| e.path().extension().map(|x| x == "md").unwrap_or(false))
107        .collect();
108    files.sort_by_key(|e| e.file_name());
109    files.reverse(); // newest first
110
111    let mut result = String::new();
112    let mut total = 0usize;
113    const MAX_TOTAL: usize = 3_000;
114
115    for entry in files.into_iter().take(3) {
116        let Ok(content) = std::fs::read_to_string(entry.path()) else {
117            continue;
118        };
119        if content.trim().is_empty() {
120            continue;
121        }
122        let snippet = if content.len() > 1_000 {
123            format!("{}...", &content[..1_000])
124        } else {
125            content
126        };
127        if total + snippet.len() > MAX_TOTAL {
128            break;
129        }
130        total += snippet.len();
131        result.push_str(&snippet);
132        result.push('\n');
133    }
134
135    if result.is_empty() {
136        return String::new();
137    }
138    format!("\n\n# Cross-Session Memory (DeepReflect)\n{}", result)
139}
140
141/// Fast non-cryptographic hash for change detection.
142fn fast_hash(s: &str) -> u64 {
143    use std::collections::hash_map::DefaultHasher;
144    use std::hash::{Hash, Hasher};
145    let mut h = DefaultHasher::new();
146    s.hash(&mut h);
147    h.finish()
148}
149
150/// Returns today's date as YYYY-MM-DD using the system clock.
151fn date_string() -> String {
152    let secs = std::time::SystemTime::now()
153        .duration_since(std::time::UNIX_EPOCH)
154        .unwrap_or_default()
155        .as_secs();
156
157    // Days since epoch
158    let days = secs / 86_400;
159    // Gregorian approximation (accurate for ~100 years from 1970)
160    let mut year = 1970u64;
161    let mut remaining = days;
162    loop {
163        let days_in_year = if is_leap(year) { 366 } else { 365 };
164        if remaining < days_in_year {
165            break;
166        }
167        remaining -= days_in_year;
168        year += 1;
169    }
170    let months = [
171        31u64,
172        if is_leap(year) { 29 } else { 28 },
173        31,
174        30,
175        31,
176        30,
177        31,
178        31,
179        30,
180        31,
181        30,
182        31,
183    ];
184    let mut month = 1u64;
185    for days_in_month in &months {
186        if remaining < *days_in_month {
187            break;
188        }
189        remaining -= days_in_month;
190        month += 1;
191    }
192    let day = remaining + 1;
193    format!("{:04}-{:02}-{:02}", year, month, day)
194}
195
196fn is_leap(year: u64) -> bool {
197    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
198}