1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use std::path::PathBuf;
4
5const MAX_FINDINGS: usize = 20;
6const MAX_DECISIONS: usize = 10;
7const MAX_FILES: usize = 50;
8#[allow(dead_code)]
9const MAX_PROGRESS: usize = 30;
10#[allow(dead_code)]
11const MAX_NEXT_STEPS: usize = 10;
12const BATCH_SAVE_INTERVAL: u32 = 5;
13
14#[derive(Serialize, Deserialize, Clone, Debug)]
15pub struct SessionState {
16 pub id: String,
17 pub version: u32,
18 pub started_at: DateTime<Utc>,
19 pub updated_at: DateTime<Utc>,
20 pub project_root: Option<String>,
21 pub task: Option<TaskInfo>,
22 pub findings: Vec<Finding>,
23 pub decisions: Vec<Decision>,
24 pub files_touched: Vec<FileTouched>,
25 pub test_results: Option<TestSnapshot>,
26 pub progress: Vec<ProgressEntry>,
27 pub next_steps: Vec<String>,
28 pub stats: SessionStats,
29}
30
31#[derive(Serialize, Deserialize, Clone, Debug)]
32pub struct TaskInfo {
33 pub description: String,
34 pub intent: Option<String>,
35 pub progress_pct: Option<u8>,
36}
37
38#[derive(Serialize, Deserialize, Clone, Debug)]
39pub struct Finding {
40 pub file: Option<String>,
41 pub line: Option<u32>,
42 pub summary: String,
43 pub timestamp: DateTime<Utc>,
44}
45
46#[derive(Serialize, Deserialize, Clone, Debug)]
47pub struct Decision {
48 pub summary: String,
49 pub rationale: Option<String>,
50 pub timestamp: DateTime<Utc>,
51}
52
53#[derive(Serialize, Deserialize, Clone, Debug)]
54pub struct FileTouched {
55 pub path: String,
56 pub file_ref: Option<String>,
57 pub read_count: u32,
58 pub modified: bool,
59 pub last_mode: String,
60 pub tokens: usize,
61}
62
63#[derive(Serialize, Deserialize, Clone, Debug)]
64pub struct TestSnapshot {
65 pub command: String,
66 pub passed: u32,
67 pub failed: u32,
68 pub total: u32,
69 pub timestamp: DateTime<Utc>,
70}
71
72#[derive(Serialize, Deserialize, Clone, Debug)]
73pub struct ProgressEntry {
74 pub action: String,
75 pub detail: Option<String>,
76 pub timestamp: DateTime<Utc>,
77}
78
79#[derive(Serialize, Deserialize, Clone, Debug, Default)]
80pub struct SessionStats {
81 pub total_tool_calls: u32,
82 pub total_tokens_saved: u64,
83 pub total_tokens_input: u64,
84 pub cache_hits: u32,
85 pub files_read: u32,
86 pub commands_run: u32,
87 pub unsaved_changes: u32,
88}
89
90#[derive(Serialize, Deserialize, Clone, Debug)]
91struct LatestPointer {
92 id: String,
93}
94
95impl Default for SessionState {
96 fn default() -> Self {
97 Self::new()
98 }
99}
100
101impl SessionState {
102 pub fn new() -> Self {
103 let now = Utc::now();
104 Self {
105 id: generate_session_id(),
106 version: 0,
107 started_at: now,
108 updated_at: now,
109 project_root: None,
110 task: None,
111 findings: Vec::new(),
112 decisions: Vec::new(),
113 files_touched: Vec::new(),
114 test_results: None,
115 progress: Vec::new(),
116 next_steps: Vec::new(),
117 stats: SessionStats::default(),
118 }
119 }
120
121 pub fn increment(&mut self) {
122 self.version += 1;
123 self.updated_at = Utc::now();
124 self.stats.unsaved_changes += 1;
125 }
126
127 pub fn should_save(&self) -> bool {
128 self.stats.unsaved_changes >= BATCH_SAVE_INTERVAL
129 }
130
131 pub fn set_task(&mut self, description: &str, intent: Option<&str>) {
132 self.task = Some(TaskInfo {
133 description: description.to_string(),
134 intent: intent.map(|s| s.to_string()),
135 progress_pct: None,
136 });
137 self.increment();
138 }
139
140 pub fn add_finding(&mut self, file: Option<&str>, line: Option<u32>, summary: &str) {
141 self.findings.push(Finding {
142 file: file.map(|s| s.to_string()),
143 line,
144 summary: summary.to_string(),
145 timestamp: Utc::now(),
146 });
147 while self.findings.len() > MAX_FINDINGS {
148 self.findings.remove(0);
149 }
150 self.increment();
151 }
152
153 pub fn add_decision(&mut self, summary: &str, rationale: Option<&str>) {
154 self.decisions.push(Decision {
155 summary: summary.to_string(),
156 rationale: rationale.map(|s| s.to_string()),
157 timestamp: Utc::now(),
158 });
159 while self.decisions.len() > MAX_DECISIONS {
160 self.decisions.remove(0);
161 }
162 self.increment();
163 }
164
165 pub fn touch_file(&mut self, path: &str, file_ref: Option<&str>, mode: &str, tokens: usize) {
166 if let Some(existing) = self.files_touched.iter_mut().find(|f| f.path == path) {
167 existing.read_count += 1;
168 existing.last_mode = mode.to_string();
169 existing.tokens = tokens;
170 if let Some(r) = file_ref {
171 existing.file_ref = Some(r.to_string());
172 }
173 } else {
174 self.files_touched.push(FileTouched {
175 path: path.to_string(),
176 file_ref: file_ref.map(|s| s.to_string()),
177 read_count: 1,
178 modified: false,
179 last_mode: mode.to_string(),
180 tokens,
181 });
182 while self.files_touched.len() > MAX_FILES {
183 self.files_touched.remove(0);
184 }
185 }
186 self.stats.files_read += 1;
187 self.increment();
188 }
189
190 pub fn mark_modified(&mut self, path: &str) {
191 if let Some(existing) = self.files_touched.iter_mut().find(|f| f.path == path) {
192 existing.modified = true;
193 }
194 self.increment();
195 }
196
197 #[allow(dead_code)]
198 pub fn set_test_results(&mut self, command: &str, passed: u32, failed: u32, total: u32) {
199 self.test_results = Some(TestSnapshot {
200 command: command.to_string(),
201 passed,
202 failed,
203 total,
204 timestamp: Utc::now(),
205 });
206 self.increment();
207 }
208
209 #[allow(dead_code)]
210 pub fn add_progress(&mut self, action: &str, detail: Option<&str>) {
211 self.progress.push(ProgressEntry {
212 action: action.to_string(),
213 detail: detail.map(|s| s.to_string()),
214 timestamp: Utc::now(),
215 });
216 while self.progress.len() > MAX_PROGRESS {
217 self.progress.remove(0);
218 }
219 self.increment();
220 }
221
222 pub fn record_tool_call(&mut self, tokens_saved: u64, tokens_input: u64) {
223 self.stats.total_tool_calls += 1;
224 self.stats.total_tokens_saved += tokens_saved;
225 self.stats.total_tokens_input += tokens_input;
226 }
227
228 pub fn record_cache_hit(&mut self) {
229 self.stats.cache_hits += 1;
230 }
231
232 pub fn record_command(&mut self) {
233 self.stats.commands_run += 1;
234 }
235
236 pub fn format_compact(&self) -> String {
237 let duration = self.updated_at - self.started_at;
238 let hours = duration.num_hours();
239 let mins = duration.num_minutes() % 60;
240 let duration_str = if hours > 0 {
241 format!("{hours}h {mins}m")
242 } else {
243 format!("{mins}m")
244 };
245
246 let mut lines = Vec::new();
247 lines.push(format!(
248 "SESSION v{} | {} | {} calls | {} tok saved",
249 self.version, duration_str, self.stats.total_tool_calls, self.stats.total_tokens_saved
250 ));
251
252 if let Some(ref task) = self.task {
253 let pct = task
254 .progress_pct
255 .map_or(String::new(), |p| format!(" [{p}%]"));
256 lines.push(format!("Task: {}{pct}", task.description));
257 }
258
259 if let Some(ref root) = self.project_root {
260 lines.push(format!("Root: {}", shorten_path(root)));
261 }
262
263 if !self.findings.is_empty() {
264 let items: Vec<String> = self
265 .findings
266 .iter()
267 .rev()
268 .take(5)
269 .map(|f| {
270 let loc = match (&f.file, f.line) {
271 (Some(file), Some(line)) => format!("{}:{line}", shorten_path(file)),
272 (Some(file), None) => shorten_path(file),
273 _ => String::new(),
274 };
275 if loc.is_empty() {
276 f.summary.clone()
277 } else {
278 format!("{loc} \u{2014} {}", f.summary)
279 }
280 })
281 .collect();
282 lines.push(format!(
283 "Findings ({}): {}",
284 self.findings.len(),
285 items.join(" | ")
286 ));
287 }
288
289 if !self.decisions.is_empty() {
290 let items: Vec<&str> = self
291 .decisions
292 .iter()
293 .rev()
294 .take(3)
295 .map(|d| d.summary.as_str())
296 .collect();
297 lines.push(format!("Decisions: {}", items.join(" | ")));
298 }
299
300 if !self.files_touched.is_empty() {
301 let items: Vec<String> = self
302 .files_touched
303 .iter()
304 .rev()
305 .take(10)
306 .map(|f| {
307 let status = if f.modified { "mod" } else { &f.last_mode };
308 let r = f.file_ref.as_deref().unwrap_or("?");
309 format!("[{r} {} {status}]", shorten_path(&f.path))
310 })
311 .collect();
312 lines.push(format!(
313 "Files ({}): {}",
314 self.files_touched.len(),
315 items.join(" ")
316 ));
317 }
318
319 if let Some(ref tests) = self.test_results {
320 lines.push(format!(
321 "Tests: {}/{} pass ({})",
322 tests.passed, tests.total, tests.command
323 ));
324 }
325
326 if !self.next_steps.is_empty() {
327 lines.push(format!("Next: {}", self.next_steps.join(" | ")));
328 }
329
330 lines.join("\n")
331 }
332
333 pub fn build_compaction_snapshot(&self) -> String {
334 const MAX_SNAPSHOT_BYTES: usize = 2048;
335
336 let mut sections: Vec<(u8, String)> = Vec::new();
337
338 if let Some(ref task) = self.task {
339 let pct = task
340 .progress_pct
341 .map_or(String::new(), |p| format!(" [{p}%]"));
342 sections.push((1, format!("<task>{}{pct}</task>", task.description)));
343 }
344
345 if !self.files_touched.is_empty() {
346 let modified: Vec<&str> = self
347 .files_touched
348 .iter()
349 .filter(|f| f.modified)
350 .map(|f| f.path.as_str())
351 .collect();
352 let read_only: Vec<&str> = self
353 .files_touched
354 .iter()
355 .filter(|f| !f.modified)
356 .take(10)
357 .map(|f| f.path.as_str())
358 .collect();
359 let mut files_section = String::new();
360 if !modified.is_empty() {
361 files_section.push_str(&format!("Modified: {}", modified.join(", ")));
362 }
363 if !read_only.is_empty() {
364 if !files_section.is_empty() {
365 files_section.push_str(" | ");
366 }
367 files_section.push_str(&format!("Read: {}", read_only.join(", ")));
368 }
369 sections.push((1, format!("<files>{files_section}</files>")));
370 }
371
372 if !self.decisions.is_empty() {
373 let items: Vec<&str> = self.decisions.iter().map(|d| d.summary.as_str()).collect();
374 sections.push((2, format!("<decisions>{}</decisions>", items.join(" | "))));
375 }
376
377 if !self.findings.is_empty() {
378 let items: Vec<String> = self
379 .findings
380 .iter()
381 .rev()
382 .take(5)
383 .map(|f| f.summary.clone())
384 .collect();
385 sections.push((2, format!("<findings>{}</findings>", items.join(" | "))));
386 }
387
388 if !self.progress.is_empty() {
389 let items: Vec<String> = self
390 .progress
391 .iter()
392 .rev()
393 .take(5)
394 .map(|p| {
395 let detail = p.detail.as_deref().unwrap_or("");
396 if detail.is_empty() {
397 p.action.clone()
398 } else {
399 format!("{}: {detail}", p.action)
400 }
401 })
402 .collect();
403 sections.push((2, format!("<progress>{}</progress>", items.join(" | "))));
404 }
405
406 if let Some(ref tests) = self.test_results {
407 sections.push((
408 3,
409 format!(
410 "<tests>{}/{} pass ({})</tests>",
411 tests.passed, tests.total, tests.command
412 ),
413 ));
414 }
415
416 if !self.next_steps.is_empty() {
417 sections.push((
418 3,
419 format!("<next_steps>{}</next_steps>", self.next_steps.join(" | ")),
420 ));
421 }
422
423 sections.push((
424 4,
425 format!(
426 "<stats>calls={} saved={}tok</stats>",
427 self.stats.total_tool_calls, self.stats.total_tokens_saved
428 ),
429 ));
430
431 sections.sort_by_key(|(priority, _)| *priority);
432
433 let mut snapshot = String::from("<session_snapshot>\n");
434 for (_, section) in §ions {
435 if snapshot.len() + section.len() + 25 > MAX_SNAPSHOT_BYTES {
436 break;
437 }
438 snapshot.push_str(section);
439 snapshot.push('\n');
440 }
441 snapshot.push_str("</session_snapshot>");
442 snapshot
443 }
444
445 pub fn save_compaction_snapshot(&self) -> Result<String, String> {
446 let snapshot = self.build_compaction_snapshot();
447 let dir = sessions_dir().ok_or("cannot determine home directory")?;
448 if !dir.exists() {
449 std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
450 }
451 let path = dir.join(format!("{}_snapshot.txt", self.id));
452 std::fs::write(&path, &snapshot).map_err(|e| e.to_string())?;
453 Ok(snapshot)
454 }
455
456 pub fn load_compaction_snapshot(session_id: &str) -> Option<String> {
457 let dir = sessions_dir()?;
458 let path = dir.join(format!("{session_id}_snapshot.txt"));
459 std::fs::read_to_string(&path).ok()
460 }
461
462 pub fn load_latest_snapshot() -> Option<String> {
463 let dir = sessions_dir()?;
464 let mut snapshots: Vec<(std::time::SystemTime, PathBuf)> = std::fs::read_dir(&dir)
465 .ok()?
466 .filter_map(|e| e.ok())
467 .filter(|e| e.path().to_string_lossy().ends_with("_snapshot.txt"))
468 .filter_map(|e| {
469 let meta = e.metadata().ok()?;
470 let modified = meta.modified().ok()?;
471 Some((modified, e.path()))
472 })
473 .collect();
474
475 snapshots.sort_by(|a, b| b.0.cmp(&a.0));
476 snapshots
477 .first()
478 .and_then(|(_, path)| std::fs::read_to_string(path).ok())
479 }
480
481 pub fn save(&mut self) -> Result<(), String> {
482 let dir = sessions_dir().ok_or("cannot determine home directory")?;
483 if !dir.exists() {
484 std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
485 }
486
487 let path = dir.join(format!("{}.json", self.id));
488 let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
489
490 let tmp = dir.join(format!(".{}.json.tmp", self.id));
491 std::fs::write(&tmp, &json).map_err(|e| e.to_string())?;
492 std::fs::rename(&tmp, &path).map_err(|e| e.to_string())?;
493
494 let pointer = LatestPointer {
495 id: self.id.clone(),
496 };
497 let pointer_json = serde_json::to_string(&pointer).map_err(|e| e.to_string())?;
498 let latest_path = dir.join("latest.json");
499 let latest_tmp = dir.join(".latest.json.tmp");
500 std::fs::write(&latest_tmp, &pointer_json).map_err(|e| e.to_string())?;
501 std::fs::rename(&latest_tmp, &latest_path).map_err(|e| e.to_string())?;
502
503 self.stats.unsaved_changes = 0;
504 Ok(())
505 }
506
507 pub fn load_latest() -> Option<Self> {
508 let dir = sessions_dir()?;
509 let latest_path = dir.join("latest.json");
510 let pointer_json = std::fs::read_to_string(&latest_path).ok()?;
511 let pointer: LatestPointer = serde_json::from_str(&pointer_json).ok()?;
512 Self::load_by_id(&pointer.id)
513 }
514
515 pub fn load_by_id(id: &str) -> Option<Self> {
516 let dir = sessions_dir()?;
517 let path = dir.join(format!("{id}.json"));
518 let json = std::fs::read_to_string(&path).ok()?;
519 serde_json::from_str(&json).ok()
520 }
521
522 pub fn list_sessions() -> Vec<SessionSummary> {
523 let dir = match sessions_dir() {
524 Some(d) => d,
525 None => return Vec::new(),
526 };
527
528 let mut summaries = Vec::new();
529 if let Ok(entries) = std::fs::read_dir(&dir) {
530 for entry in entries.flatten() {
531 let path = entry.path();
532 if path.extension().and_then(|e| e.to_str()) != Some("json") {
533 continue;
534 }
535 if path.file_name().and_then(|n| n.to_str()) == Some("latest.json") {
536 continue;
537 }
538 if let Ok(json) = std::fs::read_to_string(&path) {
539 if let Ok(session) = serde_json::from_str::<SessionState>(&json) {
540 summaries.push(SessionSummary {
541 id: session.id,
542 started_at: session.started_at,
543 updated_at: session.updated_at,
544 version: session.version,
545 task: session.task.as_ref().map(|t| t.description.clone()),
546 tool_calls: session.stats.total_tool_calls,
547 tokens_saved: session.stats.total_tokens_saved,
548 });
549 }
550 }
551 }
552 }
553
554 summaries.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
555 summaries
556 }
557
558 pub fn cleanup_old_sessions(max_age_days: i64) -> u32 {
559 let dir = match sessions_dir() {
560 Some(d) => d,
561 None => return 0,
562 };
563
564 let cutoff = Utc::now() - chrono::Duration::days(max_age_days);
565 let latest = Self::load_latest().map(|s| s.id);
566 let mut removed = 0u32;
567
568 if let Ok(entries) = std::fs::read_dir(&dir) {
569 for entry in entries.flatten() {
570 let path = entry.path();
571 if path.extension().and_then(|e| e.to_str()) != Some("json") {
572 continue;
573 }
574 let filename = path.file_stem().and_then(|n| n.to_str()).unwrap_or("");
575 if filename == "latest" || filename.starts_with('.') {
576 continue;
577 }
578 if latest.as_deref() == Some(filename) {
579 continue;
580 }
581 if let Ok(json) = std::fs::read_to_string(&path) {
582 if let Ok(session) = serde_json::from_str::<SessionState>(&json) {
583 if session.updated_at < cutoff && std::fs::remove_file(&path).is_ok() {
584 removed += 1;
585 }
586 }
587 }
588 }
589 }
590
591 removed
592 }
593}
594
595#[derive(Debug, Clone)]
596#[allow(dead_code)]
597pub struct SessionSummary {
598 pub id: String,
599 pub started_at: DateTime<Utc>,
600 pub updated_at: DateTime<Utc>,
601 pub version: u32,
602 pub task: Option<String>,
603 pub tool_calls: u32,
604 pub tokens_saved: u64,
605}
606
607fn sessions_dir() -> Option<PathBuf> {
608 dirs::home_dir().map(|h| h.join(".lean-ctx").join("sessions"))
609}
610
611fn generate_session_id() -> String {
612 let now = Utc::now();
613 let ts = now.format("%Y%m%d-%H%M%S").to_string();
614 let random: u32 = (std::time::SystemTime::now()
615 .duration_since(std::time::UNIX_EPOCH)
616 .unwrap_or_default()
617 .subsec_nanos())
618 % 10000;
619 format!("{ts}-{random:04}")
620}
621
622fn shorten_path(path: &str) -> String {
623 let parts: Vec<&str> = path.split('/').collect();
624 if parts.len() <= 2 {
625 return path.to_string();
626 }
627 let last_two: Vec<&str> = parts.iter().rev().take(2).copied().collect();
628 format!("…/{}/{}", last_two[1], last_two[0])
629}
630
631#[cfg(test)]
632mod tests {
633 use super::*;
634
635 #[test]
636 fn compaction_snapshot_includes_task() {
637 let mut session = SessionState::new();
638 session.set_task("fix auth bug", None);
639 let snapshot = session.build_compaction_snapshot();
640 assert!(snapshot.contains("<task>fix auth bug</task>"));
641 assert!(snapshot.contains("<session_snapshot>"));
642 assert!(snapshot.contains("</session_snapshot>"));
643 }
644
645 #[test]
646 fn compaction_snapshot_includes_files() {
647 let mut session = SessionState::new();
648 session.touch_file("src/auth.rs", None, "full", 500);
649 session.files_touched[0].modified = true;
650 session.touch_file("src/main.rs", None, "map", 100);
651 let snapshot = session.build_compaction_snapshot();
652 assert!(snapshot.contains("auth.rs"));
653 assert!(snapshot.contains("<files>"));
654 }
655
656 #[test]
657 fn compaction_snapshot_includes_decisions() {
658 let mut session = SessionState::new();
659 session.add_decision("Use JWT RS256", None);
660 let snapshot = session.build_compaction_snapshot();
661 assert!(snapshot.contains("JWT RS256"));
662 assert!(snapshot.contains("<decisions>"));
663 }
664
665 #[test]
666 fn compaction_snapshot_respects_size_limit() {
667 let mut session = SessionState::new();
668 session.set_task("a]task", None);
669 for i in 0..100 {
670 session.add_finding(
671 Some(&format!("file{i}.rs")),
672 Some(i),
673 &format!("Finding number {i} with some detail text here"),
674 );
675 }
676 let snapshot = session.build_compaction_snapshot();
677 assert!(snapshot.len() <= 2200);
678 }
679
680 #[test]
681 fn compaction_snapshot_includes_stats() {
682 let mut session = SessionState::new();
683 session.stats.total_tool_calls = 42;
684 session.stats.total_tokens_saved = 10000;
685 let snapshot = session.build_compaction_snapshot();
686 assert!(snapshot.contains("calls=42"));
687 assert!(snapshot.contains("saved=10000"));
688 }
689}