Skip to main content

lean_ctx/core/
session.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use std::path::PathBuf;
4
5use crate::core::intent_protocol::{IntentRecord, IntentSource};
6
7const MAX_FINDINGS: usize = 20;
8const MAX_DECISIONS: usize = 10;
9const MAX_FILES: usize = 50;
10const MAX_EVIDENCE: usize = 500;
11const BATCH_SAVE_INTERVAL: u32 = 5;
12
13#[derive(Serialize, Deserialize, Clone, Debug)]
14pub struct SessionState {
15    pub id: String,
16    pub version: u32,
17    pub started_at: DateTime<Utc>,
18    pub updated_at: DateTime<Utc>,
19    pub project_root: Option<String>,
20    #[serde(default)]
21    pub shell_cwd: Option<String>,
22    pub task: Option<TaskInfo>,
23    pub findings: Vec<Finding>,
24    pub decisions: Vec<Decision>,
25    pub files_touched: Vec<FileTouched>,
26    pub test_results: Option<TestSnapshot>,
27    pub progress: Vec<ProgressEntry>,
28    pub next_steps: Vec<String>,
29    #[serde(default)]
30    pub evidence: Vec<EvidenceRecord>,
31    #[serde(default)]
32    pub intents: Vec<IntentRecord>,
33    pub stats: SessionStats,
34}
35
36#[derive(Serialize, Deserialize, Clone, Debug)]
37pub struct TaskInfo {
38    pub description: String,
39    pub intent: Option<String>,
40    pub progress_pct: Option<u8>,
41}
42
43#[derive(Serialize, Deserialize, Clone, Debug)]
44pub struct Finding {
45    pub file: Option<String>,
46    pub line: Option<u32>,
47    pub summary: String,
48    pub timestamp: DateTime<Utc>,
49}
50
51#[derive(Serialize, Deserialize, Clone, Debug)]
52pub struct Decision {
53    pub summary: String,
54    pub rationale: Option<String>,
55    pub timestamp: DateTime<Utc>,
56}
57
58#[derive(Serialize, Deserialize, Clone, Debug)]
59pub struct FileTouched {
60    pub path: String,
61    pub file_ref: Option<String>,
62    pub read_count: u32,
63    pub modified: bool,
64    pub last_mode: String,
65    pub tokens: usize,
66}
67
68#[derive(Serialize, Deserialize, Clone, Debug)]
69pub struct TestSnapshot {
70    pub command: String,
71    pub passed: u32,
72    pub failed: u32,
73    pub total: u32,
74    pub timestamp: DateTime<Utc>,
75}
76
77#[derive(Serialize, Deserialize, Clone, Debug)]
78pub struct ProgressEntry {
79    pub action: String,
80    pub detail: Option<String>,
81    pub timestamp: DateTime<Utc>,
82}
83
84#[derive(Serialize, Deserialize, Clone, Debug)]
85#[serde(rename_all = "snake_case")]
86pub enum EvidenceKind {
87    ToolCall,
88    Manual,
89}
90
91#[derive(Serialize, Deserialize, Clone, Debug)]
92pub struct EvidenceRecord {
93    pub kind: EvidenceKind,
94    pub key: String,
95    pub value: Option<String>,
96    pub tool: Option<String>,
97    pub input_md5: Option<String>,
98    pub output_md5: Option<String>,
99    pub agent_id: Option<String>,
100    pub client_name: Option<String>,
101    pub timestamp: DateTime<Utc>,
102}
103
104#[derive(Serialize, Deserialize, Clone, Debug, Default)]
105#[serde(default)]
106pub struct SessionStats {
107    pub total_tool_calls: u32,
108    pub total_tokens_saved: u64,
109    pub total_tokens_input: u64,
110    pub cache_hits: u32,
111    pub files_read: u32,
112    pub commands_run: u32,
113    pub intents_inferred: u32,
114    pub intents_explicit: u32,
115    pub unsaved_changes: u32,
116}
117
118#[derive(Serialize, Deserialize, Clone, Debug)]
119struct LatestPointer {
120    id: String,
121}
122
123impl Default for SessionState {
124    fn default() -> Self {
125        Self::new()
126    }
127}
128
129impl SessionState {
130    pub fn new() -> Self {
131        let now = Utc::now();
132        Self {
133            id: generate_session_id(),
134            version: 0,
135            started_at: now,
136            updated_at: now,
137            project_root: None,
138            shell_cwd: None,
139            task: None,
140            findings: Vec::new(),
141            decisions: Vec::new(),
142            files_touched: Vec::new(),
143            test_results: None,
144            progress: Vec::new(),
145            next_steps: Vec::new(),
146            evidence: Vec::new(),
147            intents: Vec::new(),
148            stats: SessionStats::default(),
149        }
150    }
151
152    pub fn increment(&mut self) {
153        self.version += 1;
154        self.updated_at = Utc::now();
155        self.stats.unsaved_changes += 1;
156    }
157
158    pub fn should_save(&self) -> bool {
159        self.stats.unsaved_changes >= BATCH_SAVE_INTERVAL
160    }
161
162    pub fn set_task(&mut self, description: &str, intent: Option<&str>) {
163        self.task = Some(TaskInfo {
164            description: description.to_string(),
165            intent: intent.map(|s| s.to_string()),
166            progress_pct: None,
167        });
168        self.increment();
169    }
170
171    pub fn add_finding(&mut self, file: Option<&str>, line: Option<u32>, summary: &str) {
172        self.findings.push(Finding {
173            file: file.map(|s| s.to_string()),
174            line,
175            summary: summary.to_string(),
176            timestamp: Utc::now(),
177        });
178        while self.findings.len() > MAX_FINDINGS {
179            self.findings.remove(0);
180        }
181        self.increment();
182    }
183
184    pub fn add_decision(&mut self, summary: &str, rationale: Option<&str>) {
185        self.decisions.push(Decision {
186            summary: summary.to_string(),
187            rationale: rationale.map(|s| s.to_string()),
188            timestamp: Utc::now(),
189        });
190        while self.decisions.len() > MAX_DECISIONS {
191            self.decisions.remove(0);
192        }
193        self.increment();
194    }
195
196    pub fn touch_file(&mut self, path: &str, file_ref: Option<&str>, mode: &str, tokens: usize) {
197        if let Some(existing) = self.files_touched.iter_mut().find(|f| f.path == path) {
198            existing.read_count += 1;
199            existing.last_mode = mode.to_string();
200            existing.tokens = tokens;
201            if let Some(r) = file_ref {
202                existing.file_ref = Some(r.to_string());
203            }
204        } else {
205            self.files_touched.push(FileTouched {
206                path: path.to_string(),
207                file_ref: file_ref.map(|s| s.to_string()),
208                read_count: 1,
209                modified: false,
210                last_mode: mode.to_string(),
211                tokens,
212            });
213            while self.files_touched.len() > MAX_FILES {
214                self.files_touched.remove(0);
215            }
216        }
217        self.stats.files_read += 1;
218        self.increment();
219    }
220
221    pub fn mark_modified(&mut self, path: &str) {
222        if let Some(existing) = self.files_touched.iter_mut().find(|f| f.path == path) {
223            existing.modified = true;
224        }
225        self.increment();
226    }
227
228    pub fn record_tool_call(&mut self, tokens_saved: u64, tokens_input: u64) {
229        self.stats.total_tool_calls += 1;
230        self.stats.total_tokens_saved += tokens_saved;
231        self.stats.total_tokens_input += tokens_input;
232    }
233
234    pub fn record_intent(&mut self, mut intent: IntentRecord) {
235        if intent.occurrences == 0 {
236            intent.occurrences = 1;
237        }
238
239        if let Some(last) = self.intents.last_mut() {
240            if last.fingerprint() == intent.fingerprint() {
241                last.occurrences = last.occurrences.saturating_add(intent.occurrences);
242                last.timestamp = intent.timestamp;
243                match intent.source {
244                    IntentSource::Inferred => self.stats.intents_inferred += 1,
245                    IntentSource::Explicit => self.stats.intents_explicit += 1,
246                }
247                self.increment();
248                return;
249            }
250        }
251
252        match intent.source {
253            IntentSource::Inferred => self.stats.intents_inferred += 1,
254            IntentSource::Explicit => self.stats.intents_explicit += 1,
255        }
256
257        self.intents.push(intent);
258        while self.intents.len() > crate::core::budgets::INTENTS_PER_SESSION_LIMIT {
259            self.intents.remove(0);
260        }
261        self.increment();
262    }
263
264    pub fn record_tool_receipt(
265        &mut self,
266        tool: &str,
267        action: Option<&str>,
268        input_md5: &str,
269        output_md5: &str,
270        agent_id: Option<&str>,
271        client_name: Option<&str>,
272    ) {
273        let now = Utc::now();
274        let mut push = |key: String| {
275            self.evidence.push(EvidenceRecord {
276                kind: EvidenceKind::ToolCall,
277                key,
278                value: None,
279                tool: Some(tool.to_string()),
280                input_md5: Some(input_md5.to_string()),
281                output_md5: Some(output_md5.to_string()),
282                agent_id: agent_id.map(|s| s.to_string()),
283                client_name: client_name.map(|s| s.to_string()),
284                timestamp: now,
285            });
286        };
287
288        push(format!("tool:{tool}"));
289        if let Some(a) = action {
290            push(format!("tool:{tool}:{a}"));
291        }
292        while self.evidence.len() > MAX_EVIDENCE {
293            self.evidence.remove(0);
294        }
295        self.increment();
296    }
297
298    pub fn record_manual_evidence(&mut self, key: &str, value: Option<&str>) {
299        self.evidence.push(EvidenceRecord {
300            kind: EvidenceKind::Manual,
301            key: key.to_string(),
302            value: value.map(|s| s.to_string()),
303            tool: None,
304            input_md5: None,
305            output_md5: None,
306            agent_id: None,
307            client_name: None,
308            timestamp: Utc::now(),
309        });
310        while self.evidence.len() > MAX_EVIDENCE {
311            self.evidence.remove(0);
312        }
313        self.increment();
314    }
315
316    pub fn has_evidence_key(&self, key: &str) -> bool {
317        self.evidence.iter().any(|e| e.key == key)
318    }
319
320    pub fn record_cache_hit(&mut self) {
321        self.stats.cache_hits += 1;
322    }
323
324    pub fn record_command(&mut self) {
325        self.stats.commands_run += 1;
326    }
327
328    /// Returns the effective working directory for shell commands.
329    /// Priority: explicit cwd arg > session shell_cwd > project_root > process cwd
330    pub fn effective_cwd(&self, explicit_cwd: Option<&str>) -> String {
331        if let Some(cwd) = explicit_cwd {
332            if !cwd.is_empty() && cwd != "." {
333                return cwd.to_string();
334            }
335        }
336        if let Some(ref cwd) = self.shell_cwd {
337            return cwd.clone();
338        }
339        if let Some(ref root) = self.project_root {
340            return root.clone();
341        }
342        std::env::current_dir()
343            .map(|p| p.to_string_lossy().to_string())
344            .unwrap_or_else(|_| ".".to_string())
345    }
346
347    /// Updates shell_cwd by detecting `cd` in the command.
348    /// Handles: `cd /abs/path`, `cd rel/path` (relative to current cwd),
349    /// `cd ..`, and chained commands like `cd foo && ...`.
350    pub fn update_shell_cwd(&mut self, command: &str) {
351        let base = self.effective_cwd(None);
352        if let Some(new_cwd) = extract_cd_target(command, &base) {
353            let path = std::path::Path::new(&new_cwd);
354            if path.exists() && path.is_dir() {
355                self.shell_cwd = Some(
356                    path.canonicalize()
357                        .unwrap_or_else(|_| path.to_path_buf())
358                        .to_string_lossy()
359                        .to_string(),
360                );
361            }
362        }
363    }
364
365    pub fn format_compact(&self) -> String {
366        let duration = self.updated_at - self.started_at;
367        let hours = duration.num_hours();
368        let mins = duration.num_minutes() % 60;
369        let duration_str = if hours > 0 {
370            format!("{hours}h {mins}m")
371        } else {
372            format!("{mins}m")
373        };
374
375        let mut lines = Vec::new();
376        lines.push(format!(
377            "SESSION v{} | {} | {} calls | {} tok saved",
378            self.version, duration_str, self.stats.total_tool_calls, self.stats.total_tokens_saved
379        ));
380
381        if let Some(ref task) = self.task {
382            let pct = task
383                .progress_pct
384                .map_or(String::new(), |p| format!(" [{p}%]"));
385            lines.push(format!("Task: {}{pct}", task.description));
386        }
387
388        if let Some(ref root) = self.project_root {
389            lines.push(format!("Root: {}", shorten_path(root)));
390        }
391
392        if !self.findings.is_empty() {
393            let items: Vec<String> = self
394                .findings
395                .iter()
396                .rev()
397                .take(5)
398                .map(|f| {
399                    let loc = match (&f.file, f.line) {
400                        (Some(file), Some(line)) => format!("{}:{line}", shorten_path(file)),
401                        (Some(file), None) => shorten_path(file),
402                        _ => String::new(),
403                    };
404                    if loc.is_empty() {
405                        f.summary.clone()
406                    } else {
407                        format!("{loc} \u{2014} {}", f.summary)
408                    }
409                })
410                .collect();
411            lines.push(format!(
412                "Findings ({}): {}",
413                self.findings.len(),
414                items.join(" | ")
415            ));
416        }
417
418        if !self.decisions.is_empty() {
419            let items: Vec<&str> = self
420                .decisions
421                .iter()
422                .rev()
423                .take(3)
424                .map(|d| d.summary.as_str())
425                .collect();
426            lines.push(format!("Decisions: {}", items.join(" | ")));
427        }
428
429        if !self.files_touched.is_empty() {
430            let items: Vec<String> = self
431                .files_touched
432                .iter()
433                .rev()
434                .take(10)
435                .map(|f| {
436                    let status = if f.modified { "mod" } else { &f.last_mode };
437                    let r = f.file_ref.as_deref().unwrap_or("?");
438                    format!("[{r} {} {status}]", shorten_path(&f.path))
439                })
440                .collect();
441            lines.push(format!(
442                "Files ({}): {}",
443                self.files_touched.len(),
444                items.join(" ")
445            ));
446        }
447
448        if let Some(ref tests) = self.test_results {
449            lines.push(format!(
450                "Tests: {}/{} pass ({})",
451                tests.passed, tests.total, tests.command
452            ));
453        }
454
455        if !self.next_steps.is_empty() {
456            lines.push(format!("Next: {}", self.next_steps.join(" | ")));
457        }
458
459        lines.join("\n")
460    }
461
462    pub fn build_compaction_snapshot(&self) -> String {
463        const MAX_SNAPSHOT_BYTES: usize = 2048;
464
465        let mut sections: Vec<(u8, String)> = Vec::new();
466
467        if let Some(ref task) = self.task {
468            let pct = task
469                .progress_pct
470                .map_or(String::new(), |p| format!(" [{p}%]"));
471            sections.push((1, format!("<task>{}{pct}</task>", task.description)));
472        }
473
474        if !self.files_touched.is_empty() {
475            let modified: Vec<&str> = self
476                .files_touched
477                .iter()
478                .filter(|f| f.modified)
479                .map(|f| f.path.as_str())
480                .collect();
481            let read_only: Vec<&str> = self
482                .files_touched
483                .iter()
484                .filter(|f| !f.modified)
485                .take(10)
486                .map(|f| f.path.as_str())
487                .collect();
488            let mut files_section = String::new();
489            if !modified.is_empty() {
490                files_section.push_str(&format!("Modified: {}", modified.join(", ")));
491            }
492            if !read_only.is_empty() {
493                if !files_section.is_empty() {
494                    files_section.push_str(" | ");
495                }
496                files_section.push_str(&format!("Read: {}", read_only.join(", ")));
497            }
498            sections.push((1, format!("<files>{files_section}</files>")));
499        }
500
501        if !self.decisions.is_empty() {
502            let items: Vec<&str> = self.decisions.iter().map(|d| d.summary.as_str()).collect();
503            sections.push((2, format!("<decisions>{}</decisions>", items.join(" | "))));
504        }
505
506        if !self.findings.is_empty() {
507            let items: Vec<String> = self
508                .findings
509                .iter()
510                .rev()
511                .take(5)
512                .map(|f| f.summary.clone())
513                .collect();
514            sections.push((2, format!("<findings>{}</findings>", items.join(" | "))));
515        }
516
517        if !self.progress.is_empty() {
518            let items: Vec<String> = self
519                .progress
520                .iter()
521                .rev()
522                .take(5)
523                .map(|p| {
524                    let detail = p.detail.as_deref().unwrap_or("");
525                    if detail.is_empty() {
526                        p.action.clone()
527                    } else {
528                        format!("{}: {detail}", p.action)
529                    }
530                })
531                .collect();
532            sections.push((2, format!("<progress>{}</progress>", items.join(" | "))));
533        }
534
535        if let Some(ref tests) = self.test_results {
536            sections.push((
537                3,
538                format!(
539                    "<tests>{}/{} pass ({})</tests>",
540                    tests.passed, tests.total, tests.command
541                ),
542            ));
543        }
544
545        if !self.next_steps.is_empty() {
546            sections.push((
547                3,
548                format!("<next_steps>{}</next_steps>", self.next_steps.join(" | ")),
549            ));
550        }
551
552        sections.push((
553            4,
554            format!(
555                "<stats>calls={} saved={}tok</stats>",
556                self.stats.total_tool_calls, self.stats.total_tokens_saved
557            ),
558        ));
559
560        sections.sort_by_key(|(priority, _)| *priority);
561
562        let mut snapshot = String::from("<session_snapshot>\n");
563        for (_, section) in &sections {
564            if snapshot.len() + section.len() + 25 > MAX_SNAPSHOT_BYTES {
565                break;
566            }
567            snapshot.push_str(section);
568            snapshot.push('\n');
569        }
570        snapshot.push_str("</session_snapshot>");
571        snapshot
572    }
573
574    pub fn save_compaction_snapshot(&self) -> Result<String, String> {
575        let snapshot = self.build_compaction_snapshot();
576        let dir = sessions_dir().ok_or("cannot determine home directory")?;
577        if !dir.exists() {
578            std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
579        }
580        let path = dir.join(format!("{}_snapshot.txt", self.id));
581        std::fs::write(&path, &snapshot).map_err(|e| e.to_string())?;
582        Ok(snapshot)
583    }
584
585    pub fn load_compaction_snapshot(session_id: &str) -> Option<String> {
586        let dir = sessions_dir()?;
587        let path = dir.join(format!("{session_id}_snapshot.txt"));
588        std::fs::read_to_string(&path).ok()
589    }
590
591    pub fn load_latest_snapshot() -> Option<String> {
592        let dir = sessions_dir()?;
593        let mut snapshots: Vec<(std::time::SystemTime, PathBuf)> = std::fs::read_dir(&dir)
594            .ok()?
595            .filter_map(|e| e.ok())
596            .filter(|e| e.path().to_string_lossy().ends_with("_snapshot.txt"))
597            .filter_map(|e| {
598                let meta = e.metadata().ok()?;
599                let modified = meta.modified().ok()?;
600                Some((modified, e.path()))
601            })
602            .collect();
603
604        snapshots.sort_by_key(|x| std::cmp::Reverse(x.0));
605        snapshots
606            .first()
607            .and_then(|(_, path)| std::fs::read_to_string(path).ok())
608    }
609
610    pub fn save(&mut self) -> Result<(), String> {
611        let dir = sessions_dir().ok_or("cannot determine home directory")?;
612        if !dir.exists() {
613            std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
614        }
615
616        let path = dir.join(format!("{}.json", self.id));
617        let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
618
619        let tmp = dir.join(format!(".{}.json.tmp", self.id));
620        std::fs::write(&tmp, &json).map_err(|e| e.to_string())?;
621        std::fs::rename(&tmp, &path).map_err(|e| e.to_string())?;
622
623        let pointer = LatestPointer {
624            id: self.id.clone(),
625        };
626        let pointer_json = serde_json::to_string(&pointer).map_err(|e| e.to_string())?;
627        let latest_path = dir.join("latest.json");
628        let latest_tmp = dir.join(".latest.json.tmp");
629        std::fs::write(&latest_tmp, &pointer_json).map_err(|e| e.to_string())?;
630        std::fs::rename(&latest_tmp, &latest_path).map_err(|e| e.to_string())?;
631
632        self.stats.unsaved_changes = 0;
633        Ok(())
634    }
635
636    pub fn load_latest() -> Option<Self> {
637        let dir = sessions_dir()?;
638        let latest_path = dir.join("latest.json");
639        let pointer_json = std::fs::read_to_string(&latest_path).ok()?;
640        let pointer: LatestPointer = serde_json::from_str(&pointer_json).ok()?;
641        Self::load_by_id(&pointer.id)
642    }
643
644    pub fn load_by_id(id: &str) -> Option<Self> {
645        let dir = sessions_dir()?;
646        let path = dir.join(format!("{id}.json"));
647        let json = std::fs::read_to_string(&path).ok()?;
648        let mut session: Self = serde_json::from_str(&json).ok()?;
649        // Legacy/malformed sessions may serialize empty strings instead of null.
650        if matches!(session.project_root.as_deref(), Some(r) if r.trim().is_empty()) {
651            session.project_root = None;
652        }
653        if matches!(session.shell_cwd.as_deref(), Some(c) if c.trim().is_empty()) {
654            session.shell_cwd = None;
655        }
656        Some(session)
657    }
658
659    pub fn list_sessions() -> Vec<SessionSummary> {
660        let dir = match sessions_dir() {
661            Some(d) => d,
662            None => return Vec::new(),
663        };
664
665        let mut summaries = Vec::new();
666        if let Ok(entries) = std::fs::read_dir(&dir) {
667            for entry in entries.flatten() {
668                let path = entry.path();
669                if path.extension().and_then(|e| e.to_str()) != Some("json") {
670                    continue;
671                }
672                if path.file_name().and_then(|n| n.to_str()) == Some("latest.json") {
673                    continue;
674                }
675                if let Ok(json) = std::fs::read_to_string(&path) {
676                    if let Ok(session) = serde_json::from_str::<SessionState>(&json) {
677                        summaries.push(SessionSummary {
678                            id: session.id,
679                            started_at: session.started_at,
680                            updated_at: session.updated_at,
681                            version: session.version,
682                            task: session.task.as_ref().map(|t| t.description.clone()),
683                            tool_calls: session.stats.total_tool_calls,
684                            tokens_saved: session.stats.total_tokens_saved,
685                        });
686                    }
687                }
688            }
689        }
690
691        summaries.sort_by_key(|x| std::cmp::Reverse(x.updated_at));
692        summaries
693    }
694
695    pub fn cleanup_old_sessions(max_age_days: i64) -> u32 {
696        let dir = match sessions_dir() {
697            Some(d) => d,
698            None => return 0,
699        };
700
701        let cutoff = Utc::now() - chrono::Duration::days(max_age_days);
702        let latest = Self::load_latest().map(|s| s.id);
703        let mut removed = 0u32;
704
705        if let Ok(entries) = std::fs::read_dir(&dir) {
706            for entry in entries.flatten() {
707                let path = entry.path();
708                if path.extension().and_then(|e| e.to_str()) != Some("json") {
709                    continue;
710                }
711                let filename = path.file_stem().and_then(|n| n.to_str()).unwrap_or("");
712                if filename == "latest" || filename.starts_with('.') {
713                    continue;
714                }
715                if latest.as_deref() == Some(filename) {
716                    continue;
717                }
718                if let Ok(json) = std::fs::read_to_string(&path) {
719                    if let Ok(session) = serde_json::from_str::<SessionState>(&json) {
720                        if session.updated_at < cutoff && std::fs::remove_file(&path).is_ok() {
721                            removed += 1;
722                        }
723                    }
724                }
725            }
726        }
727
728        removed
729    }
730}
731
732#[derive(Debug, Clone)]
733pub struct SessionSummary {
734    pub id: String,
735    pub started_at: DateTime<Utc>,
736    pub updated_at: DateTime<Utc>,
737    pub version: u32,
738    pub task: Option<String>,
739    pub tool_calls: u32,
740    pub tokens_saved: u64,
741}
742
743fn sessions_dir() -> Option<PathBuf> {
744    crate::core::data_dir::lean_ctx_data_dir()
745        .ok()
746        .map(|d| d.join("sessions"))
747}
748
749fn generate_session_id() -> String {
750    let now = Utc::now();
751    let ts = now.format("%Y%m%d-%H%M%S").to_string();
752    let random: u32 = (std::time::SystemTime::now()
753        .duration_since(std::time::UNIX_EPOCH)
754        .unwrap_or_default()
755        .subsec_nanos())
756        % 10000;
757    format!("{ts}-{random:04}")
758}
759
760/// Extracts the `cd` target from a command string.
761/// Handles patterns like `cd /foo`, `cd foo && bar`, `cd ../dir; cmd`, etc.
762fn extract_cd_target(command: &str, base_cwd: &str) -> Option<String> {
763    let first_cmd = command
764        .split("&&")
765        .next()
766        .unwrap_or(command)
767        .split(';')
768        .next()
769        .unwrap_or(command)
770        .trim();
771
772    if !first_cmd.starts_with("cd ") && first_cmd != "cd" {
773        return None;
774    }
775
776    let target = first_cmd.strip_prefix("cd")?.trim();
777    if target.is_empty() || target == "~" {
778        return dirs::home_dir().map(|h| h.to_string_lossy().to_string());
779    }
780
781    let target = target.trim_matches('"').trim_matches('\'');
782    let path = std::path::Path::new(target);
783
784    if path.is_absolute() {
785        Some(target.to_string())
786    } else {
787        let base = std::path::Path::new(base_cwd);
788        let joined = base.join(target).to_string_lossy().to_string();
789        Some(joined.replace('\\', "/"))
790    }
791}
792
793fn shorten_path(path: &str) -> String {
794    let parts: Vec<&str> = path.split('/').collect();
795    if parts.len() <= 2 {
796        return path.to_string();
797    }
798    let last_two: Vec<&str> = parts.iter().rev().take(2).copied().collect();
799    format!("…/{}/{}", last_two[1], last_two[0])
800}
801
802#[cfg(test)]
803mod tests {
804    use super::*;
805
806    #[test]
807    fn extract_cd_absolute_path() {
808        let result = extract_cd_target("cd /usr/local/bin", "/home/user");
809        assert_eq!(result, Some("/usr/local/bin".to_string()));
810    }
811
812    #[test]
813    fn extract_cd_relative_path() {
814        let result = extract_cd_target("cd subdir", "/home/user");
815        assert_eq!(result, Some("/home/user/subdir".to_string()));
816    }
817
818    #[test]
819    fn extract_cd_with_chained_command() {
820        let result = extract_cd_target("cd /tmp && ls", "/home/user");
821        assert_eq!(result, Some("/tmp".to_string()));
822    }
823
824    #[test]
825    fn extract_cd_with_semicolon() {
826        let result = extract_cd_target("cd /tmp; ls", "/home/user");
827        assert_eq!(result, Some("/tmp".to_string()));
828    }
829
830    #[test]
831    fn extract_cd_parent_dir() {
832        let result = extract_cd_target("cd ..", "/home/user/project");
833        assert_eq!(result, Some("/home/user/project/..".to_string()));
834    }
835
836    #[test]
837    fn extract_cd_no_cd_returns_none() {
838        let result = extract_cd_target("ls -la", "/home/user");
839        assert!(result.is_none());
840    }
841
842    #[test]
843    fn extract_cd_bare_cd_goes_home() {
844        let result = extract_cd_target("cd", "/home/user");
845        assert!(result.is_some());
846    }
847
848    #[test]
849    fn effective_cwd_explicit_takes_priority() {
850        let mut session = SessionState::new();
851        session.project_root = Some("/project".to_string());
852        session.shell_cwd = Some("/project/src".to_string());
853        assert_eq!(session.effective_cwd(Some("/explicit")), "/explicit");
854    }
855
856    #[test]
857    fn effective_cwd_shell_cwd_second_priority() {
858        let mut session = SessionState::new();
859        session.project_root = Some("/project".to_string());
860        session.shell_cwd = Some("/project/src".to_string());
861        assert_eq!(session.effective_cwd(None), "/project/src");
862    }
863
864    #[test]
865    fn effective_cwd_project_root_third_priority() {
866        let mut session = SessionState::new();
867        session.project_root = Some("/project".to_string());
868        assert_eq!(session.effective_cwd(None), "/project");
869    }
870
871    #[test]
872    fn effective_cwd_dot_ignored() {
873        let mut session = SessionState::new();
874        session.project_root = Some("/project".to_string());
875        assert_eq!(session.effective_cwd(Some(".")), "/project");
876    }
877
878    #[test]
879    fn compaction_snapshot_includes_task() {
880        let mut session = SessionState::new();
881        session.set_task("fix auth bug", None);
882        let snapshot = session.build_compaction_snapshot();
883        assert!(snapshot.contains("<task>fix auth bug</task>"));
884        assert!(snapshot.contains("<session_snapshot>"));
885        assert!(snapshot.contains("</session_snapshot>"));
886    }
887
888    #[test]
889    fn compaction_snapshot_includes_files() {
890        let mut session = SessionState::new();
891        session.touch_file("src/auth.rs", None, "full", 500);
892        session.files_touched[0].modified = true;
893        session.touch_file("src/main.rs", None, "map", 100);
894        let snapshot = session.build_compaction_snapshot();
895        assert!(snapshot.contains("auth.rs"));
896        assert!(snapshot.contains("<files>"));
897    }
898
899    #[test]
900    fn compaction_snapshot_includes_decisions() {
901        let mut session = SessionState::new();
902        session.add_decision("Use JWT RS256", None);
903        let snapshot = session.build_compaction_snapshot();
904        assert!(snapshot.contains("JWT RS256"));
905        assert!(snapshot.contains("<decisions>"));
906    }
907
908    #[test]
909    fn compaction_snapshot_respects_size_limit() {
910        let mut session = SessionState::new();
911        session.set_task("a]task", None);
912        for i in 0..100 {
913            session.add_finding(
914                Some(&format!("file{i}.rs")),
915                Some(i),
916                &format!("Finding number {i} with some detail text here"),
917            );
918        }
919        let snapshot = session.build_compaction_snapshot();
920        assert!(snapshot.len() <= 2200);
921    }
922
923    #[test]
924    fn compaction_snapshot_includes_stats() {
925        let mut session = SessionState::new();
926        session.stats.total_tool_calls = 42;
927        session.stats.total_tokens_saved = 10000;
928        let snapshot = session.build_compaction_snapshot();
929        assert!(snapshot.contains("calls=42"));
930        assert!(snapshot.contains("saved=10000"));
931    }
932}