Skip to main content

lean_ctx/core/session/
mod.rs

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