Skip to main content

lean_ctx/core/session/
mod.rs

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