Skip to main content

lean_ctx/core/session/
mod.rs

1mod compaction;
2mod heuristics;
3mod paths;
4mod persistence;
5pub mod playbook;
6mod state;
7pub(crate) use state::extract_session_facts;
8mod types;
9
10pub use playbook::{DeltaOutcome, EntryKind, Playbook, PlaybookEntry};
11pub use types::{
12    Decision, EvidenceKind, EvidenceRecord, FileTouched, Finding, LiveZoneSessionState,
13    ManifestEntry, PreparedSave, ProgressEntry, SessionState, SessionStats, SessionSummary,
14    TaskInfo, TestSnapshot,
15};
16
17#[cfg(test)]
18mod tests {
19    use super::paths::{extract_cd_target, sessions_dir};
20    use super::types::*;
21    use chrono::{Duration, Utc};
22
23    #[test]
24    fn load_latest_for_broad_root_returns_none_without_scanning() {
25        // The daemon boots with cwd "/" and the dispatcher passes that as the
26        // project root. Broad roots must bail out before walking the session
27        // store — stat-ing persisted roots under ~/Documents from the launchd
28        // daemon pops the macOS TCC prompt (#356).
29        assert!(SessionState::load_latest_for_project_root("/").is_none());
30        if let Some(home) = dirs::home_dir() {
31            let home = home.to_string_lossy().to_string();
32            assert!(SessionState::load_latest_for_project_root(&home).is_none());
33        }
34    }
35
36    #[test]
37    #[cfg(target_os = "macos")]
38    #[serial_test::serial]
39    fn normalize_session_skips_marker_probe_for_real_roots() {
40        // Both guards are needed: `#[serial]` and `test_env_lock` are separate
41        // mutexes, and the `LEAN_CTX_TCC_STANDALONE` this test relies on is read
42        // by every path normalization, including in tests that take only the lock.
43        let _env_lock = crate::core::data_dir::test_env_lock();
44        // A session whose project_root is a plausible real project must not be
45        // marker-probed at load time when the process is TCC-standalone: the
46        // probe itself would trip the privacy prompt (#356). The repair
47        // heuristic only ever fires for agent/temp roots.
48        crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
49        let mut session = SessionState::new();
50        let docs_root = dirs::home_dir()
51            .unwrap_or_default()
52            .join("Documents/some-project")
53            .to_string_lossy()
54            .to_string();
55        session.project_root = Some(docs_root.clone());
56        session.shell_cwd = Some(docs_root.clone());
57        let normalized = super::heuristics::normalize_loaded_session(session);
58        // Root is not an agent/temp dir → kept as-is, no probe needed.
59        assert_eq!(normalized.project_root.as_deref(), Some(docs_root.as_str()));
60        crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
61    }
62
63    /// #707: an explicit, jail-accepted `cwd` param must persist as the live
64    /// shell cwd — worktree switches arrive as `cwd` params, not `cd`
65    /// commands, and the divergence check in path resolution reads
66    /// `shell_cwd`. Relative or nonexistent paths are ignored.
67    #[test]
68    fn note_explicit_cwd_persists_absolute_dirs_only() {
69        let tmp = std::env::temp_dir().join(format!("lc_707_cwd_{}", std::process::id()));
70        std::fs::create_dir_all(&tmp).unwrap();
71
72        let mut session = SessionState::new();
73        session.note_explicit_cwd(&tmp.to_string_lossy());
74        let noted = session.shell_cwd.clone().expect("cwd should persist");
75        // Canonicalized (macOS /tmp → /private/tmp), so compare canonical forms.
76        assert_eq!(
77            noted,
78            crate::core::pathutil::safe_canonicalize_or_self(&tmp)
79                .to_string_lossy()
80                .to_string()
81        );
82
83        session.note_explicit_cwd("relative/dir");
84        assert_eq!(session.shell_cwd.as_deref(), Some(noted.as_str()));
85        session.note_explicit_cwd(&tmp.join("does-not-exist").to_string_lossy());
86        assert_eq!(session.shell_cwd.as_deref(), Some(noted.as_str()));
87
88        let _ = std::fs::remove_dir_all(&tmp);
89    }
90
91    /// #717: the 5-change batch alone left slowly-ticking sessions invisible
92    /// to the dashboard. First change on a fresh in-memory session flushes
93    /// immediately; afterwards the time-based trigger fires once a change is
94    /// older than SESSION_FLUSH_INTERVAL, and the batch threshold still wins.
95    #[test]
96    fn should_save_flushes_first_change_and_stale_changes() {
97        use super::state::SESSION_FLUSH_INTERVAL;
98        let mut session = SessionState::new();
99        assert!(!session.should_save(), "no changes → no save");
100
101        session.increment();
102        assert!(session.should_save(), "first change must flush immediately");
103
104        session.last_flush = Some(std::time::Instant::now());
105        assert!(
106            !session.should_save(),
107            "inside window + below batch → defer"
108        );
109
110        for _ in 0..4 {
111            session.increment();
112        }
113        assert!(session.should_save(), "batch threshold still applies");
114
115        session.stats.unsaved_changes = 1;
116        if let Some(old) = std::time::Instant::now().checked_sub(SESSION_FLUSH_INTERVAL) {
117            session.last_flush = Some(old);
118            assert!(session.should_save(), "stale change must trigger flush");
119        }
120    }
121
122    #[test]
123    fn delete_session_removes_file_snapshot_and_latest_pointer() {
124        let _data = crate::core::data_dir::isolated_data_dir();
125        let mut session = SessionState::new();
126        session.id = "delete-me".to_string();
127        session.save().unwrap();
128
129        let dir = sessions_dir().unwrap();
130        let path = dir.join("delete-me.json");
131        let snapshot = dir.join("delete-me_snapshot.txt");
132        let latest = dir.join("latest.json");
133        std::fs::write(&snapshot, "snapshot").unwrap();
134        assert!(path.exists());
135        assert!(snapshot.exists());
136        assert!(latest.exists());
137
138        assert!(SessionState::delete_session("delete-me").unwrap());
139
140        assert!(!path.exists());
141        assert!(!snapshot.exists());
142        assert!(!latest.exists());
143        assert!(SessionState::list_sessions().is_empty());
144    }
145
146    #[test]
147    fn delete_latest_session_repoints_latest_to_newest_remaining() {
148        let _data = crate::core::data_dir::isolated_data_dir();
149        let mut older = SessionState::new();
150        older.id = "older".to_string();
151        older.updated_at = Utc::now() - Duration::days(1);
152        older.save().unwrap();
153
154        let mut newer = SessionState::new();
155        newer.id = "newer".to_string();
156        newer.updated_at = Utc::now();
157        newer.save().unwrap();
158        assert_eq!(
159            SessionState::load_global_latest_pointer().unwrap().id,
160            "newer"
161        );
162
163        assert!(SessionState::delete_session("newer").unwrap());
164
165        let latest = SessionState::load_global_latest_pointer().unwrap();
166        assert_eq!(latest.id, "older");
167        assert_eq!(SessionState::list_sessions().len(), 1);
168    }
169
170    #[test]
171    fn delete_session_rejects_path_traversal_id() {
172        let data = crate::core::data_dir::isolated_data_dir();
173        let outside = data.path().join("outside.json");
174        std::fs::write(&outside, "{}").unwrap();
175
176        let err = SessionState::delete_session("../outside").unwrap_err();
177
178        assert_eq!(err, "invalid session id");
179        assert!(outside.exists());
180    }
181
182    #[test]
183    fn extract_cd_absolute_path() {
184        let result = extract_cd_target("cd /usr/local/bin", "/home/user");
185        assert_eq!(result, Some("/usr/local/bin".to_string()));
186    }
187
188    #[test]
189    fn extract_cd_relative_path() {
190        let result = extract_cd_target("cd subdir", "/home/user");
191        assert_eq!(result, Some("/home/user/subdir".to_string()));
192    }
193
194    #[test]
195    fn extract_cd_with_chained_command() {
196        let result = extract_cd_target("cd /tmp && ls", "/home/user");
197        assert_eq!(result, Some("/tmp".to_string()));
198    }
199
200    #[test]
201    fn extract_cd_with_semicolon() {
202        let result = extract_cd_target("cd /tmp; ls", "/home/user");
203        assert_eq!(result, Some("/tmp".to_string()));
204    }
205
206    #[test]
207    fn extract_cd_parent_dir() {
208        let result = extract_cd_target("cd ..", "/home/user/project");
209        assert_eq!(result, Some("/home/user/project/..".to_string()));
210    }
211
212    #[test]
213    fn extract_cd_no_cd_returns_none() {
214        let result = extract_cd_target("ls -la", "/home/user");
215        assert!(result.is_none());
216    }
217
218    #[test]
219    fn extract_cd_bare_cd_goes_home() {
220        let result = extract_cd_target("cd", "/home/user");
221        assert!(result.is_some());
222    }
223
224    #[test]
225    fn effective_cwd_explicit_takes_priority() {
226        let tmp = std::env::temp_dir().join("lean-ctx-test-cwd-explicit");
227        let sub = tmp.join("sub");
228        let _ = std::fs::create_dir_all(&sub);
229        let root_canon = crate::core::pathutil::safe_canonicalize_or_self(&tmp)
230            .to_string_lossy()
231            .to_string();
232        let sub_canon = crate::core::pathutil::safe_canonicalize_or_self(&sub)
233            .to_string_lossy()
234            .to_string();
235
236        let mut session = SessionState::new();
237        session.project_root = Some(root_canon);
238        let result = session.effective_cwd(Some(&sub_canon));
239        assert_eq!(result, sub_canon);
240        let _ = std::fs::remove_dir_all(&tmp);
241    }
242
243    #[cfg(not(feature = "no-jail"))]
244    #[test]
245    fn effective_cwd_explicit_outside_root_is_jailed() {
246        let tmp = std::env::temp_dir().join("lean-ctx-test-cwd-jail");
247        let _ = std::fs::create_dir_all(&tmp);
248        let root_canon = crate::core::pathutil::safe_canonicalize_or_self(&tmp)
249            .to_string_lossy()
250            .to_string();
251
252        let mut session = SessionState::new();
253        session.project_root = Some(root_canon.clone());
254        let result = session.effective_cwd(Some("/nonexistent-outside-path"));
255        assert_eq!(result, root_canon);
256        let _ = std::fs::remove_dir_all(&tmp);
257    }
258
259    /// The checked variant must report *why* a jailed cwd was rejected, so
260    /// `ctx_shell` can surface it instead of silently swapping in the root (#629).
261    #[cfg(not(feature = "no-jail"))]
262    #[test]
263    fn effective_cwd_checked_reports_jail_rejection_reason() {
264        let tmp = std::env::temp_dir().join("lean-ctx-test-cwd-checked");
265        let _ = std::fs::create_dir_all(&tmp);
266        let root_canon = crate::core::pathutil::safe_canonicalize_or_self(&tmp)
267            .to_string_lossy()
268            .to_string();
269
270        let mut session = SessionState::new();
271        session.project_root = Some(root_canon.clone());
272
273        // Rejected: falls back to the root AND surfaces a non-empty reason.
274        let (path, reason) = session.effective_cwd_checked(Some("/nonexistent-outside-path"));
275        assert_eq!(path, root_canon);
276        let reason = reason.expect("a jailed cwd must report a rejection reason");
277        assert!(!reason.is_empty(), "the rejection reason must not be empty");
278
279        // Accepted (no explicit cwd): no reason, path is the project root.
280        let (accepted, none_reason) = session.effective_cwd_checked(None);
281        assert_eq!(accepted, root_canon);
282        assert!(
283            none_reason.is_none(),
284            "a non-jailed path must not report a reason"
285        );
286
287        let _ = std::fs::remove_dir_all(&tmp);
288    }
289
290    #[test]
291    fn effective_cwd_shell_cwd_second_priority() {
292        let mut session = SessionState::new();
293        session.project_root = Some("/project".to_string());
294        session.shell_cwd = Some("/project/src".to_string());
295        assert_eq!(session.effective_cwd(None), "/project/src");
296    }
297
298    #[test]
299    fn effective_cwd_project_root_third_priority() {
300        let mut session = SessionState::new();
301        session.project_root = Some("/project".to_string());
302        assert_eq!(session.effective_cwd(None), "/project");
303    }
304
305    #[test]
306    fn effective_cwd_dot_ignored() {
307        let mut session = SessionState::new();
308        session.project_root = Some("/project".to_string());
309        assert_eq!(session.effective_cwd(Some(".")), "/project");
310    }
311
312    #[test]
313    fn compaction_snapshot_includes_compression_config_when_enabled() {
314        let mut session = SessionState::new();
315        session.compression_level = "standard".to_string();
316        session.terse_mode = true;
317        session.set_task("x", None);
318        let snapshot = session.build_compaction_snapshot();
319        assert!(snapshot.contains("<config compression=\"standard\" />"));
320    }
321
322    #[test]
323    fn resume_block_prefixes_compression_hint_when_enabled() {
324        let mut session = SessionState::new();
325        session.compression_level = "lite".to_string();
326        session.terse_mode = true;
327        let block = session.build_resume_block();
328        assert!(block.contains("[COMPRESSION: lite]"));
329    }
330
331    #[test]
332    fn compaction_snapshot_includes_task() {
333        let mut session = SessionState::new();
334        session.set_task("fix auth bug", None);
335        let snapshot = session.build_compaction_snapshot();
336        assert!(snapshot.contains("<task>fix auth bug</task>"));
337        assert!(snapshot.contains("<session_snapshot>"));
338        assert!(snapshot.contains("</session_snapshot>"));
339    }
340
341    #[test]
342    fn compaction_snapshot_includes_files() {
343        let mut session = SessionState::new();
344        session.touch_file("src/auth.rs", None, "full", 500);
345        session.files_touched[0].modified = true;
346        session.touch_file("src/main.rs", None, "map", 100);
347        let snapshot = session.build_compaction_snapshot();
348        assert!(snapshot.contains("auth.rs"));
349        assert!(snapshot.contains("<files>"));
350    }
351
352    #[test]
353    fn compaction_snapshot_includes_decisions() {
354        let mut session = SessionState::new();
355        session.add_decision("Use JWT RS256", None);
356        let snapshot = session.build_compaction_snapshot();
357        assert!(snapshot.contains("JWT RS256"));
358        assert!(snapshot.contains("<decisions>"));
359    }
360
361    #[test]
362    fn compaction_snapshot_respects_size_limit() {
363        let mut session = SessionState::new();
364        session.set_task("a]task", None);
365        for i in 0..100 {
366            session.add_finding(
367                Some(&format!("file{i}.rs")),
368                Some(i),
369                &format!("Finding number {i} with some detail text here"),
370            );
371        }
372        let snapshot = session.build_compaction_snapshot();
373        assert!(snapshot.len() <= 2200);
374    }
375
376    #[test]
377    fn compaction_snapshot_includes_stats() {
378        let mut session = SessionState::new();
379        session.stats.total_tool_calls = 42;
380        session.stats.total_tokens_saved = 10000;
381        let snapshot = session.build_compaction_snapshot();
382        assert!(snapshot.contains("calls=42"));
383        assert!(snapshot.contains("saved=10000"));
384    }
385}