Skip to main content

lean_ctx/core/session/
mod.rs

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