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                    crate::core::pathutil::safe_canonicalize_or_self(path)
357                        .to_string_lossy()
358                        .to_string(),
359                );
360            }
361        }
362    }
363
364    pub fn format_compact(&self) -> String {
365        let duration = self.updated_at - self.started_at;
366        let hours = duration.num_hours();
367        let mins = duration.num_minutes() % 60;
368        let duration_str = if hours > 0 {
369            format!("{hours}h {mins}m")
370        } else {
371            format!("{mins}m")
372        };
373
374        let mut lines = Vec::new();
375        lines.push(format!(
376            "SESSION v{} | {} | {} calls | {} tok saved",
377            self.version, duration_str, self.stats.total_tool_calls, self.stats.total_tokens_saved
378        ));
379
380        if let Some(ref task) = self.task {
381            let pct = task
382                .progress_pct
383                .map_or(String::new(), |p| format!(" [{p}%]"));
384            lines.push(format!("Task: {}{pct}", task.description));
385        }
386
387        if let Some(ref root) = self.project_root {
388            lines.push(format!("Root: {}", shorten_path(root)));
389        }
390
391        if !self.findings.is_empty() {
392            let items: Vec<String> = self
393                .findings
394                .iter()
395                .rev()
396                .take(5)
397                .map(|f| {
398                    let loc = match (&f.file, f.line) {
399                        (Some(file), Some(line)) => format!("{}:{line}", shorten_path(file)),
400                        (Some(file), None) => shorten_path(file),
401                        _ => String::new(),
402                    };
403                    if loc.is_empty() {
404                        f.summary.clone()
405                    } else {
406                        format!("{loc} \u{2014} {}", f.summary)
407                    }
408                })
409                .collect();
410            lines.push(format!(
411                "Findings ({}): {}",
412                self.findings.len(),
413                items.join(" | ")
414            ));
415        }
416
417        if !self.decisions.is_empty() {
418            let items: Vec<&str> = self
419                .decisions
420                .iter()
421                .rev()
422                .take(3)
423                .map(|d| d.summary.as_str())
424                .collect();
425            lines.push(format!("Decisions: {}", items.join(" | ")));
426        }
427
428        if !self.files_touched.is_empty() {
429            let items: Vec<String> = self
430                .files_touched
431                .iter()
432                .rev()
433                .take(10)
434                .map(|f| {
435                    let status = if f.modified { "mod" } else { &f.last_mode };
436                    let r = f.file_ref.as_deref().unwrap_or("?");
437                    format!("[{r} {} {status}]", shorten_path(&f.path))
438                })
439                .collect();
440            lines.push(format!(
441                "Files ({}): {}",
442                self.files_touched.len(),
443                items.join(" ")
444            ));
445        }
446
447        if let Some(ref tests) = self.test_results {
448            lines.push(format!(
449                "Tests: {}/{} pass ({})",
450                tests.passed, tests.total, tests.command
451            ));
452        }
453
454        if !self.next_steps.is_empty() {
455            lines.push(format!("Next: {}", self.next_steps.join(" | ")));
456        }
457
458        lines.join("\n")
459    }
460
461    pub fn build_compaction_snapshot(&self) -> String {
462        const MAX_SNAPSHOT_BYTES: usize = 2048;
463
464        let mut sections: Vec<(u8, String)> = Vec::new();
465
466        if let Some(ref task) = self.task {
467            let pct = task
468                .progress_pct
469                .map_or(String::new(), |p| format!(" [{p}%]"));
470            sections.push((1, format!("<task>{}{pct}</task>", task.description)));
471        }
472
473        if !self.files_touched.is_empty() {
474            let modified: Vec<&str> = self
475                .files_touched
476                .iter()
477                .filter(|f| f.modified)
478                .map(|f| f.path.as_str())
479                .collect();
480            let read_only: Vec<&str> = self
481                .files_touched
482                .iter()
483                .filter(|f| !f.modified)
484                .take(10)
485                .map(|f| f.path.as_str())
486                .collect();
487            let mut files_section = String::new();
488            if !modified.is_empty() {
489                files_section.push_str(&format!("Modified: {}", modified.join(", ")));
490            }
491            if !read_only.is_empty() {
492                if !files_section.is_empty() {
493                    files_section.push_str(" | ");
494                }
495                files_section.push_str(&format!("Read: {}", read_only.join(", ")));
496            }
497            sections.push((1, format!("<files>{files_section}</files>")));
498        }
499
500        if !self.decisions.is_empty() {
501            let items: Vec<&str> = self.decisions.iter().map(|d| d.summary.as_str()).collect();
502            sections.push((2, format!("<decisions>{}</decisions>", items.join(" | "))));
503        }
504
505        if !self.findings.is_empty() {
506            let items: Vec<String> = self
507                .findings
508                .iter()
509                .rev()
510                .take(5)
511                .map(|f| f.summary.clone())
512                .collect();
513            sections.push((2, format!("<findings>{}</findings>", items.join(" | "))));
514        }
515
516        if !self.progress.is_empty() {
517            let items: Vec<String> = self
518                .progress
519                .iter()
520                .rev()
521                .take(5)
522                .map(|p| {
523                    let detail = p.detail.as_deref().unwrap_or("");
524                    if detail.is_empty() {
525                        p.action.clone()
526                    } else {
527                        format!("{}: {detail}", p.action)
528                    }
529                })
530                .collect();
531            sections.push((2, format!("<progress>{}</progress>", items.join(" | "))));
532        }
533
534        if let Some(ref tests) = self.test_results {
535            sections.push((
536                3,
537                format!(
538                    "<tests>{}/{} pass ({})</tests>",
539                    tests.passed, tests.total, tests.command
540                ),
541            ));
542        }
543
544        if !self.next_steps.is_empty() {
545            sections.push((
546                3,
547                format!("<next_steps>{}</next_steps>", self.next_steps.join(" | ")),
548            ));
549        }
550
551        sections.push((
552            4,
553            format!(
554                "<stats>calls={} saved={}tok</stats>",
555                self.stats.total_tool_calls, self.stats.total_tokens_saved
556            ),
557        ));
558
559        sections.sort_by_key(|(priority, _)| *priority);
560
561        let mut snapshot = String::from("<session_snapshot>\n");
562        for (_, section) in &sections {
563            if snapshot.len() + section.len() + 25 > MAX_SNAPSHOT_BYTES {
564                break;
565            }
566            snapshot.push_str(section);
567            snapshot.push('\n');
568        }
569        snapshot.push_str("</session_snapshot>");
570        snapshot
571    }
572
573    pub fn save_compaction_snapshot(&self) -> Result<String, String> {
574        let snapshot = self.build_compaction_snapshot();
575        let dir = sessions_dir().ok_or("cannot determine home directory")?;
576        if !dir.exists() {
577            std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
578        }
579        let path = dir.join(format!("{}_snapshot.txt", self.id));
580        std::fs::write(&path, &snapshot).map_err(|e| e.to_string())?;
581        Ok(snapshot)
582    }
583
584    pub fn load_compaction_snapshot(session_id: &str) -> Option<String> {
585        let dir = sessions_dir()?;
586        let path = dir.join(format!("{session_id}_snapshot.txt"));
587        std::fs::read_to_string(&path).ok()
588    }
589
590    pub fn load_latest_snapshot() -> Option<String> {
591        let dir = sessions_dir()?;
592        let mut snapshots: Vec<(std::time::SystemTime, PathBuf)> = std::fs::read_dir(&dir)
593            .ok()?
594            .filter_map(|e| e.ok())
595            .filter(|e| e.path().to_string_lossy().ends_with("_snapshot.txt"))
596            .filter_map(|e| {
597                let meta = e.metadata().ok()?;
598                let modified = meta.modified().ok()?;
599                Some((modified, e.path()))
600            })
601            .collect();
602
603        snapshots.sort_by_key(|x| std::cmp::Reverse(x.0));
604        snapshots
605            .first()
606            .and_then(|(_, path)| std::fs::read_to_string(path).ok())
607    }
608
609    pub fn save(&mut self) -> Result<(), String> {
610        let dir = sessions_dir().ok_or("cannot determine home directory")?;
611        if !dir.exists() {
612            std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
613        }
614
615        let path = dir.join(format!("{}.json", self.id));
616        let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
617
618        let tmp = dir.join(format!(".{}.json.tmp", self.id));
619        std::fs::write(&tmp, &json).map_err(|e| e.to_string())?;
620        std::fs::rename(&tmp, &path).map_err(|e| e.to_string())?;
621
622        let pointer = LatestPointer {
623            id: self.id.clone(),
624        };
625        let pointer_json = serde_json::to_string(&pointer).map_err(|e| e.to_string())?;
626        let latest_path = dir.join("latest.json");
627        let latest_tmp = dir.join(".latest.json.tmp");
628        std::fs::write(&latest_tmp, &pointer_json).map_err(|e| e.to_string())?;
629        std::fs::rename(&latest_tmp, &latest_path).map_err(|e| e.to_string())?;
630
631        self.stats.unsaved_changes = 0;
632        Ok(())
633    }
634
635    pub fn load_latest() -> Option<Self> {
636        let dir = sessions_dir()?;
637        let latest_path = dir.join("latest.json");
638        let pointer_json = std::fs::read_to_string(&latest_path).ok()?;
639        let pointer: LatestPointer = serde_json::from_str(&pointer_json).ok()?;
640        Self::load_by_id(&pointer.id)
641    }
642
643    pub fn load_by_id(id: &str) -> Option<Self> {
644        let dir = sessions_dir()?;
645        let path = dir.join(format!("{id}.json"));
646        let json = std::fs::read_to_string(&path).ok()?;
647        let mut session: Self = serde_json::from_str(&json).ok()?;
648        // Legacy/malformed sessions may serialize empty strings instead of null.
649        if matches!(session.project_root.as_deref(), Some(r) if r.trim().is_empty()) {
650            session.project_root = None;
651        }
652        if matches!(session.shell_cwd.as_deref(), Some(c) if c.trim().is_empty()) {
653            session.shell_cwd = None;
654        }
655        Some(session)
656    }
657
658    pub fn list_sessions() -> Vec<SessionSummary> {
659        let dir = match sessions_dir() {
660            Some(d) => d,
661            None => return Vec::new(),
662        };
663
664        let mut summaries = Vec::new();
665        if let Ok(entries) = std::fs::read_dir(&dir) {
666            for entry in entries.flatten() {
667                let path = entry.path();
668                if path.extension().and_then(|e| e.to_str()) != Some("json") {
669                    continue;
670                }
671                if path.file_name().and_then(|n| n.to_str()) == Some("latest.json") {
672                    continue;
673                }
674                if let Ok(json) = std::fs::read_to_string(&path) {
675                    if let Ok(session) = serde_json::from_str::<SessionState>(&json) {
676                        summaries.push(SessionSummary {
677                            id: session.id,
678                            started_at: session.started_at,
679                            updated_at: session.updated_at,
680                            version: session.version,
681                            task: session.task.as_ref().map(|t| t.description.clone()),
682                            tool_calls: session.stats.total_tool_calls,
683                            tokens_saved: session.stats.total_tokens_saved,
684                        });
685                    }
686                }
687            }
688        }
689
690        summaries.sort_by_key(|x| std::cmp::Reverse(x.updated_at));
691        summaries
692    }
693
694    pub fn cleanup_old_sessions(max_age_days: i64) -> u32 {
695        let dir = match sessions_dir() {
696            Some(d) => d,
697            None => return 0,
698        };
699
700        let cutoff = Utc::now() - chrono::Duration::days(max_age_days);
701        let latest = Self::load_latest().map(|s| s.id);
702        let mut removed = 0u32;
703
704        if let Ok(entries) = std::fs::read_dir(&dir) {
705            for entry in entries.flatten() {
706                let path = entry.path();
707                if path.extension().and_then(|e| e.to_str()) != Some("json") {
708                    continue;
709                }
710                let filename = path.file_stem().and_then(|n| n.to_str()).unwrap_or("");
711                if filename == "latest" || filename.starts_with('.') {
712                    continue;
713                }
714                if latest.as_deref() == Some(filename) {
715                    continue;
716                }
717                if let Ok(json) = std::fs::read_to_string(&path) {
718                    if let Ok(session) = serde_json::from_str::<SessionState>(&json) {
719                        if session.updated_at < cutoff && std::fs::remove_file(&path).is_ok() {
720                            removed += 1;
721                        }
722                    }
723                }
724            }
725        }
726
727        removed
728    }
729}
730
731#[derive(Debug, Clone)]
732pub struct SessionSummary {
733    pub id: String,
734    pub started_at: DateTime<Utc>,
735    pub updated_at: DateTime<Utc>,
736    pub version: u32,
737    pub task: Option<String>,
738    pub tool_calls: u32,
739    pub tokens_saved: u64,
740}
741
742fn sessions_dir() -> Option<PathBuf> {
743    crate::core::data_dir::lean_ctx_data_dir()
744        .ok()
745        .map(|d| d.join("sessions"))
746}
747
748fn generate_session_id() -> String {
749    let now = Utc::now();
750    let ts = now.format("%Y%m%d-%H%M%S").to_string();
751    let random: u32 = (std::time::SystemTime::now()
752        .duration_since(std::time::UNIX_EPOCH)
753        .unwrap_or_default()
754        .subsec_nanos())
755        % 10000;
756    format!("{ts}-{random:04}")
757}
758
759/// Extracts the `cd` target from a command string.
760/// Handles patterns like `cd /foo`, `cd foo && bar`, `cd ../dir; cmd`, etc.
761fn extract_cd_target(command: &str, base_cwd: &str) -> Option<String> {
762    let first_cmd = command
763        .split("&&")
764        .next()
765        .unwrap_or(command)
766        .split(';')
767        .next()
768        .unwrap_or(command)
769        .trim();
770
771    if !first_cmd.starts_with("cd ") && first_cmd != "cd" {
772        return None;
773    }
774
775    let target = first_cmd.strip_prefix("cd")?.trim();
776    if target.is_empty() || target == "~" {
777        return dirs::home_dir().map(|h| h.to_string_lossy().to_string());
778    }
779
780    let target = target.trim_matches('"').trim_matches('\'');
781    let path = std::path::Path::new(target);
782
783    if path.is_absolute() {
784        Some(target.to_string())
785    } else {
786        let base = std::path::Path::new(base_cwd);
787        let joined = base.join(target).to_string_lossy().to_string();
788        Some(joined.replace('\\', "/"))
789    }
790}
791
792fn shorten_path(path: &str) -> String {
793    let parts: Vec<&str> = path.split('/').collect();
794    if parts.len() <= 2 {
795        return path.to_string();
796    }
797    let last_two: Vec<&str> = parts.iter().rev().take(2).copied().collect();
798    format!("…/{}/{}", last_two[1], last_two[0])
799}
800
801#[cfg(test)]
802mod tests {
803    use super::*;
804
805    #[test]
806    fn extract_cd_absolute_path() {
807        let result = extract_cd_target("cd /usr/local/bin", "/home/user");
808        assert_eq!(result, Some("/usr/local/bin".to_string()));
809    }
810
811    #[test]
812    fn extract_cd_relative_path() {
813        let result = extract_cd_target("cd subdir", "/home/user");
814        assert_eq!(result, Some("/home/user/subdir".to_string()));
815    }
816
817    #[test]
818    fn extract_cd_with_chained_command() {
819        let result = extract_cd_target("cd /tmp && ls", "/home/user");
820        assert_eq!(result, Some("/tmp".to_string()));
821    }
822
823    #[test]
824    fn extract_cd_with_semicolon() {
825        let result = extract_cd_target("cd /tmp; ls", "/home/user");
826        assert_eq!(result, Some("/tmp".to_string()));
827    }
828
829    #[test]
830    fn extract_cd_parent_dir() {
831        let result = extract_cd_target("cd ..", "/home/user/project");
832        assert_eq!(result, Some("/home/user/project/..".to_string()));
833    }
834
835    #[test]
836    fn extract_cd_no_cd_returns_none() {
837        let result = extract_cd_target("ls -la", "/home/user");
838        assert!(result.is_none());
839    }
840
841    #[test]
842    fn extract_cd_bare_cd_goes_home() {
843        let result = extract_cd_target("cd", "/home/user");
844        assert!(result.is_some());
845    }
846
847    #[test]
848    fn effective_cwd_explicit_takes_priority() {
849        let mut session = SessionState::new();
850        session.project_root = Some("/project".to_string());
851        session.shell_cwd = Some("/project/src".to_string());
852        assert_eq!(session.effective_cwd(Some("/explicit")), "/explicit");
853    }
854
855    #[test]
856    fn effective_cwd_shell_cwd_second_priority() {
857        let mut session = SessionState::new();
858        session.project_root = Some("/project".to_string());
859        session.shell_cwd = Some("/project/src".to_string());
860        assert_eq!(session.effective_cwd(None), "/project/src");
861    }
862
863    #[test]
864    fn effective_cwd_project_root_third_priority() {
865        let mut session = SessionState::new();
866        session.project_root = Some("/project".to_string());
867        assert_eq!(session.effective_cwd(None), "/project");
868    }
869
870    #[test]
871    fn effective_cwd_dot_ignored() {
872        let mut session = SessionState::new();
873        session.project_root = Some("/project".to_string());
874        assert_eq!(session.effective_cwd(Some(".")), "/project");
875    }
876
877    #[test]
878    fn compaction_snapshot_includes_task() {
879        let mut session = SessionState::new();
880        session.set_task("fix auth bug", None);
881        let snapshot = session.build_compaction_snapshot();
882        assert!(snapshot.contains("<task>fix auth bug</task>"));
883        assert!(snapshot.contains("<session_snapshot>"));
884        assert!(snapshot.contains("</session_snapshot>"));
885    }
886
887    #[test]
888    fn compaction_snapshot_includes_files() {
889        let mut session = SessionState::new();
890        session.touch_file("src/auth.rs", None, "full", 500);
891        session.files_touched[0].modified = true;
892        session.touch_file("src/main.rs", None, "map", 100);
893        let snapshot = session.build_compaction_snapshot();
894        assert!(snapshot.contains("auth.rs"));
895        assert!(snapshot.contains("<files>"));
896    }
897
898    #[test]
899    fn compaction_snapshot_includes_decisions() {
900        let mut session = SessionState::new();
901        session.add_decision("Use JWT RS256", None);
902        let snapshot = session.build_compaction_snapshot();
903        assert!(snapshot.contains("JWT RS256"));
904        assert!(snapshot.contains("<decisions>"));
905    }
906
907    #[test]
908    fn compaction_snapshot_respects_size_limit() {
909        let mut session = SessionState::new();
910        session.set_task("a]task", None);
911        for i in 0..100 {
912            session.add_finding(
913                Some(&format!("file{i}.rs")),
914                Some(i),
915                &format!("Finding number {i} with some detail text here"),
916            );
917        }
918        let snapshot = session.build_compaction_snapshot();
919        assert!(snapshot.len() <= 2200);
920    }
921
922    #[test]
923    fn compaction_snapshot_includes_stats() {
924        let mut session = SessionState::new();
925        session.stats.total_tool_calls = 42;
926        session.stats.total_tokens_saved = 10000;
927        let snapshot = session.build_compaction_snapshot();
928        assert!(snapshot.contains("calls=42"));
929        assert!(snapshot.contains("saved=10000"));
930    }
931}