Skip to main content

lean_ctx/core/session/
state.rs

1use chrono::Utc;
2
3use crate::core::intent_protocol::{IntentRecord, IntentSource};
4
5use super::paths::{extract_cd_target, generate_session_id};
6#[allow(clippy::wildcard_imports)]
7use super::types::*;
8
9const MAX_FINDINGS: usize = 20;
10const MAX_DECISIONS: usize = 10;
11const MAX_FILES: usize = 50;
12const MAX_EVIDENCE: usize = 500;
13pub(crate) const BATCH_SAVE_INTERVAL: u32 = 5;
14/// #717: max time an unsaved change may linger before it is flushed even
15/// below the batch threshold — the dashboard reads session JSONs from disk,
16/// so a slow trickle of tool calls must still become visible promptly.
17pub(crate) const SESSION_FLUSH_INTERVAL: std::time::Duration = std::time::Duration::from_mins(1);
18
19impl Default for SessionState {
20    fn default() -> Self {
21        Self::new()
22    }
23}
24
25impl SessionState {
26    /// Creates a new session with a unique ID and current timestamp.
27    pub fn new() -> Self {
28        let now = Utc::now();
29        Self {
30            id: generate_session_id(),
31            version: 0,
32            started_at: now,
33            updated_at: now,
34            project_root: None,
35            shell_cwd: None,
36            task: None,
37            findings: Vec::new(),
38            decisions: Vec::new(),
39            files_touched: Vec::new(),
40            test_results: None,
41            progress: Vec::new(),
42            next_steps: Vec::new(),
43            evidence: Vec::new(),
44            intents: Vec::new(),
45            active_structured_intent: None,
46            stats: SessionStats::default(),
47            terse_mode: false,
48            compression_level: String::new(),
49            last_consolidate_ts: None,
50            extra_roots: Vec::new(),
51            wakeup_manifest: Vec::new(),
52            playbook: super::playbook::Playbook::default(),
53            last_semantic_query: None,
54            last_flush: None,
55        }
56        .with_compression_from_config()
57    }
58
59    fn with_compression_from_config(mut self) -> Self {
60        let cfg = crate::core::config::Config::load();
61        let level = crate::core::config::CompressionLevel::effective(&cfg);
62        self.compression_level = level.label().to_string();
63        self.terse_mode = level.is_active();
64        self
65    }
66
67    /// Bumps the version counter and marks the session as dirty.
68    pub fn increment(&mut self) {
69        self.version += 1;
70        self.updated_at = Utc::now();
71        self.stats.unsaved_changes += 1;
72    }
73
74    /// Returns `true` if enough changes have accumulated to warrant a disk
75    /// save — or, since #717, if any change has waited longer than
76    /// `SESSION_FLUSH_INTERVAL`: the 5-change batch alone left slow
77    /// sessions invisible to the dashboard (stuck "idle") for the whole
78    /// batch window. A fresh in-memory session flushes its first change
79    /// immediately so new activity surfaces at once.
80    pub fn should_save(&self) -> bool {
81        if self.stats.unsaved_changes == 0 {
82            return false;
83        }
84        if self.stats.unsaved_changes >= BATCH_SAVE_INTERVAL {
85            return true;
86        }
87        match self.last_flush {
88            Some(t) => t.elapsed() >= SESSION_FLUSH_INTERVAL,
89            None => true,
90        }
91    }
92
93    /// Sets the active task and infers a structured intent from the description.
94    pub fn set_task(&mut self, description: &str, intent: Option<&str>) {
95        self.task = Some(TaskInfo {
96            description: description.to_string(),
97            intent: intent.map(std::string::ToString::to_string),
98            progress_pct: None,
99        });
100
101        let touched: Vec<String> = self.files_touched.iter().map(|f| f.path.clone()).collect();
102        let si = if touched.is_empty() {
103            crate::core::intent_engine::StructuredIntent::from_query(description)
104        } else {
105            crate::core::intent_engine::StructuredIntent::from_query_with_session(
106                description,
107                &touched,
108            )
109        };
110        if si.confidence >= 0.7 {
111            self.active_structured_intent = Some(si);
112        }
113
114        self.increment();
115    }
116
117    /// Auto-infers the task from available context (plans, git diff, file patterns).
118    /// Only sets if no explicit task is already set or it's stale.
119    pub fn auto_infer_task(&mut self) {
120        // Don't overwrite explicitly set tasks
121        if self.task.is_some() {
122            return;
123        }
124
125        // Source 1: Active .cursor/plans/*.plan.md
126        if let Some(task_from_plan) = Self::infer_task_from_plans() {
127            self.set_task(&task_from_plan, Some("plan"));
128            return;
129        }
130
131        // Source 2: git diff summary
132        if let Some(ref root) = self.project_root
133            && let Some(task_from_git) = Self::infer_task_from_git(root)
134        {
135            self.set_task(&task_from_git, Some("git"));
136            return;
137        }
138
139        // Source 3: File patterns from intent engine
140        if self.files_touched.len() >= 3 {
141            let touched: Vec<String> = self.files_touched.iter().map(|f| f.path.clone()).collect();
142            let intent = crate::core::intent_engine::StructuredIntent::from_file_patterns(&touched);
143            if intent.confidence >= 0.5 {
144                let dirs: std::collections::HashSet<&str> = touched
145                    .iter()
146                    .filter_map(|f| std::path::Path::new(f).parent()?.to_str())
147                    .collect();
148                let primary_dir = dirs.iter().next().unwrap_or(&".");
149                let desc = format!("Working on {} ({})", primary_dir, intent.task_type.as_str());
150                self.set_task(&desc, Some("inferred"));
151            }
152        }
153    }
154
155    fn infer_task_from_plans() -> Option<String> {
156        let plans_dir = std::path::Path::new(".cursor/plans");
157        if !plans_dir.exists() {
158            return None;
159        }
160
161        let mut newest: Option<(std::time::SystemTime, String)> = None;
162        if let Ok(entries) = std::fs::read_dir(plans_dir) {
163            for entry in entries.flatten() {
164                let path = entry.path();
165                if !path.to_string_lossy().ends_with(".plan.md") {
166                    continue;
167                }
168                let mtime = entry.metadata().ok()?.modified().ok()?;
169                let content = std::fs::read_to_string(&path).ok()?;
170
171                // Check if plan has active (pending/in_progress) todos
172                let has_active =
173                    content.contains("status: pending") || content.contains("status: in_progress");
174                if !has_active {
175                    continue;
176                }
177
178                // Extract plan name from frontmatter
179                let name = content
180                    .lines()
181                    .find(|l| l.starts_with("name:"))
182                    .map_or("Unknown Plan", |l| {
183                        l.trim_start_matches("name:").trim().trim_matches('"')
184                    });
185
186                let better = newest.as_ref().is_none_or(|(t, _)| mtime > *t);
187                if better {
188                    newest = Some((mtime, name.to_string()));
189                }
190            }
191        }
192
193        newest.map(|(_, name)| name)
194    }
195
196    fn infer_task_from_git(project_root: &str) -> Option<String> {
197        let output = std::process::Command::new("git")
198            .args(["diff", "--stat", "--no-color"])
199            .current_dir(project_root)
200            .output()
201            .ok()?;
202
203        if !output.status.success() {
204            return None;
205        }
206
207        let stat = String::from_utf8_lossy(&output.stdout);
208        let lines: Vec<&str> = stat.lines().collect();
209        if lines.is_empty() {
210            return None;
211        }
212
213        // Last line typically has "N files changed, M insertions(+), K deletions(-)"
214        let summary_line = lines.last()?;
215        if !summary_line.contains("changed") {
216            return None;
217        }
218
219        // Find common directory prefix
220        let file_lines: Vec<&str> = lines[..lines.len() - 1].to_vec();
221        let dirs: std::collections::HashSet<&str> = file_lines
222            .iter()
223            .filter_map(|l| {
224                let path = l.split('|').next()?.trim();
225                std::path::Path::new(path).parent()?.to_str()
226            })
227            .collect();
228
229        let primary = if dirs.len() == 1 {
230            dirs.into_iter().next().unwrap_or(".")
231        } else {
232            "multiple dirs"
233        };
234
235        Some(format!("Modified: {} in {}", summary_line.trim(), primary))
236    }
237
238    /// Records a finding (discovery or observation) in the session log.
239    pub fn add_finding(&mut self, file: Option<&str>, line: Option<u32>, summary: &str) {
240        let (summary_clean, _) =
241            crate::core::secret_detection::scan_and_redact_from_config(summary);
242        self.findings.push(Finding {
243            file: file.map(std::string::ToString::to_string),
244            line,
245            summary: summary_clean,
246            timestamp: Utc::now(),
247        });
248        while self.findings.len() > MAX_FINDINGS {
249            self.findings.remove(0);
250        }
251        self.increment();
252    }
253
254    /// Records a design or implementation decision with optional rationale.
255    pub fn add_decision(&mut self, summary: &str, rationale: Option<&str>) {
256        let (summary_clean, _) =
257            crate::core::secret_detection::scan_and_redact_from_config(summary);
258        let rationale_clean =
259            rationale.map(|r| crate::core::secret_detection::scan_and_redact_from_config(r).0);
260        self.decisions.push(Decision {
261            summary: summary_clean,
262            rationale: rationale_clean,
263            timestamp: Utc::now(),
264        });
265        while self.decisions.len() > MAX_DECISIONS {
266            self.decisions.remove(0);
267        }
268        self.increment();
269    }
270
271    /// Records a file read/access in the session, incrementing its read count.
272    pub fn touch_file(&mut self, path: &str, file_ref: Option<&str>, mode: &str, tokens: usize) {
273        if let Some(existing) = self.files_touched.iter_mut().find(|f| f.path == path) {
274            existing.read_count += 1;
275            existing.last_mode = mode.to_string();
276            existing.tokens = tokens;
277            if let Some(r) = file_ref {
278                existing.file_ref = Some(r.to_string());
279            }
280        } else {
281            let item_id = crate::core::context_field::ContextItemId::from_file(path);
282            self.files_touched.push(FileTouched {
283                path: path.to_string(),
284                file_ref: file_ref.map(std::string::ToString::to_string),
285                read_count: 1,
286                modified: false,
287                last_mode: mode.to_string(),
288                tokens,
289                stale: false,
290                context_item_id: Some(item_id.to_string()),
291                summary: None,
292            });
293            while self.files_touched.len() > MAX_FILES {
294                self.files_touched.remove(0);
295            }
296        }
297        self.stats.files_read += 1;
298        self.increment();
299    }
300
301    /// Marks a previously touched file as modified (written to).
302    pub fn mark_modified(&mut self, path: &str) {
303        if let Some(existing) = self.files_touched.iter_mut().find(|f| f.path == path) {
304            existing.modified = true;
305        }
306        self.increment();
307    }
308
309    /// Sets a one-line content summary for a touched file (max 80 chars).
310    pub fn set_file_summary(&mut self, path: &str, summary: &str) {
311        if let Some(existing) = self.files_touched.iter_mut().find(|f| f.path == path) {
312            let truncated = if summary.len() > 80 {
313                format!("{}…", &summary[..79])
314            } else {
315                summary.to_string()
316            };
317            existing.summary = Some(truncated);
318        }
319    }
320
321    /// Increments the tool call counter and accumulates token savings.
322    pub fn record_tool_call(&mut self, tokens_saved: u64, tokens_input: u64) {
323        self.stats.total_tool_calls += 1;
324        self.stats.total_tokens_saved += tokens_saved;
325        self.stats.total_tokens_input += tokens_input;
326    }
327
328    /// Records an inferred or explicit intent, coalescing consecutive duplicates.
329    pub fn record_intent(&mut self, mut intent: IntentRecord) {
330        if intent.occurrences == 0 {
331            intent.occurrences = 1;
332        }
333
334        if let Some(last) = self.intents.last_mut()
335            && last.fingerprint() == intent.fingerprint()
336        {
337            last.occurrences = last.occurrences.saturating_add(intent.occurrences);
338            last.timestamp = intent.timestamp;
339            match intent.source {
340                IntentSource::Inferred => self.stats.intents_inferred += 1,
341                IntentSource::Explicit => self.stats.intents_explicit += 1,
342            }
343            self.increment();
344            return;
345        }
346
347        match intent.source {
348            IntentSource::Inferred => self.stats.intents_inferred += 1,
349            IntentSource::Explicit => self.stats.intents_explicit += 1,
350        }
351
352        self.intents.push(intent);
353        while self.intents.len() > crate::core::budgets::INTENTS_PER_SESSION_LIMIT {
354            self.intents.remove(0);
355        }
356        self.increment();
357    }
358
359    /// Appends an auditable evidence record for a tool invocation.
360    pub fn record_tool_receipt(
361        &mut self,
362        tool: &str,
363        action: Option<&str>,
364        input_md5: &str,
365        output_md5: &str,
366        agent_id: Option<&str>,
367        client_name: Option<&str>,
368    ) {
369        let now = Utc::now();
370        let mut push = |key: String| {
371            self.evidence.push(EvidenceRecord {
372                kind: EvidenceKind::ToolCall,
373                key,
374                value: None,
375                tool: Some(tool.to_string()),
376                input_md5: Some(input_md5.to_string()),
377                output_md5: Some(output_md5.to_string()),
378                agent_id: agent_id.map(std::string::ToString::to_string),
379                client_name: client_name.map(std::string::ToString::to_string),
380                timestamp: now,
381            });
382        };
383
384        push(format!("tool:{tool}"));
385        if let Some(a) = action {
386            push(format!("tool:{tool}:{a}"));
387        }
388        while self.evidence.len() > MAX_EVIDENCE {
389            self.evidence.remove(0);
390        }
391        self.increment();
392    }
393
394    /// Appends a manual (non-tool) evidence record to the audit log.
395    pub fn record_manual_evidence(&mut self, key: &str, value: Option<&str>) {
396        self.evidence.push(EvidenceRecord {
397            kind: EvidenceKind::Manual,
398            key: key.to_string(),
399            value: value.map(std::string::ToString::to_string),
400            tool: None,
401            input_md5: None,
402            output_md5: None,
403            agent_id: None,
404            client_name: None,
405            timestamp: Utc::now(),
406        });
407        while self.evidence.len() > MAX_EVIDENCE {
408            self.evidence.remove(0);
409        }
410        self.increment();
411    }
412
413    /// Returns `true` if an evidence record with the given key exists.
414    pub fn has_evidence_key(&self, key: &str) -> bool {
415        self.evidence.iter().any(|e| e.key == key)
416    }
417
418    /// Increments the session-level cache hit counter.
419    pub fn record_cache_hit(&mut self) {
420        self.stats.cache_hits += 1;
421    }
422
423    /// Increments the session-level command counter.
424    pub fn record_command(&mut self) {
425        self.stats.commands_run += 1;
426    }
427
428    /// Returns the effective working directory for shell commands.
429    /// Priority: explicit cwd arg > session shell_cwd > project_root > process cwd.
430    /// Explicit CWD and stored shell_cwd are jail-checked against the project root
431    /// to prevent MCP clients from escaping the workspace.
432    pub fn effective_cwd(&self, explicit_cwd: Option<&str>) -> String {
433        self.effective_cwd_checked(explicit_cwd).0
434    }
435
436    /// Like [`Self::effective_cwd`], but also reports *why* an explicit `cwd`
437    /// request was rejected by the project-root jail and silently replaced with
438    /// the project root (#629).
439    ///
440    /// The jail itself is deliberate sandboxing (it stops MCP clients escaping
441    /// the workspace) and must stay — the only gap was that the substitution was
442    /// silent, so a caller running `pwd && ls` in what they think is dir A
443    /// actually ran in the project root with no indication why. Callers that
444    /// surface output to a human/agent (e.g. `ctx_shell`) use the returned
445    /// `Option<String>` reason to append a one-line hint instead of letting the
446    /// swap pass unnoticed; `effective_cwd` keeps the original lossless behaviour.
447    pub fn effective_cwd_checked(&self, explicit_cwd: Option<&str>) -> (String, Option<String>) {
448        let root = self.project_root.as_deref().unwrap_or(".");
449        if let Some(cwd) = explicit_cwd
450            && !cwd.is_empty()
451            && cwd != "."
452        {
453            return Self::jail_cwd(cwd, root);
454        }
455        if let Some(ref cwd) = self.shell_cwd {
456            return (cwd.clone(), None);
457        }
458        if let Some(ref r) = self.project_root {
459            return (r.clone(), None);
460        }
461        (
462            std::env::current_dir()
463                .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string()),
464            None,
465        )
466    }
467
468    /// Verifies that `candidate` is within the project jail.
469    ///
470    /// Falls back to `fallback_root` if the candidate escapes, returning the
471    /// jail-rejection reason as the second tuple element so callers can surface
472    /// it instead of silently substituting the root (#629). `None` means the
473    /// candidate was accepted as-is.
474    fn jail_cwd(candidate: &str, fallback_root: &str) -> (String, Option<String>) {
475        let p = std::path::Path::new(candidate);
476        match crate::core::pathjail::jail_path(p, std::path::Path::new(fallback_root)) {
477            Ok(jailed) => (jailed.to_string_lossy().to_string(), None),
478            Err(reason) => (fallback_root.to_string(), Some(reason.to_string())),
479        }
480    }
481
482    /// Persist an explicit, jail-accepted `cwd` argument as the live shell
483    /// cwd (#707). `update_shell_cwd` only tracks `cd` inside the command
484    /// text, but clients that switch checkouts mid-session (Claude Code
485    /// after `EnterWorktree`) pass the new directory as the `cwd` *param* of
486    /// every subsequent call — without persisting it, the worktree-divergence
487    /// detection in path resolution never sees the switch. Callers must pass
488    /// a cwd that already passed the project-root jail.
489    pub fn note_explicit_cwd(&mut self, cwd: &str) {
490        let path = std::path::Path::new(cwd);
491        if path.is_absolute() && path.is_dir() {
492            self.shell_cwd = Some(
493                crate::core::pathutil::safe_canonicalize_or_self(path)
494                    .to_string_lossy()
495                    .to_string(),
496            );
497        }
498    }
499
500    /// Updates shell_cwd by detecting `cd` in the command.
501    /// Handles: `cd /abs/path`, `cd rel/path` (relative to current cwd),
502    /// `cd ..`, and chained commands like `cd foo && ...`.
503    /// The new CWD is jail-checked against the project root.
504    pub fn update_shell_cwd(&mut self, command: &str) {
505        let base = self.effective_cwd(None);
506        if let Some(new_cwd) = extract_cd_target(command, &base) {
507            let path = std::path::Path::new(&new_cwd);
508            if path.exists() && path.is_dir() {
509                let canonical = crate::core::pathutil::safe_canonicalize_or_self(path)
510                    .to_string_lossy()
511                    .to_string();
512                let root = self.project_root.as_deref().unwrap_or(".");
513                if crate::core::pathjail::jail_path(
514                    std::path::Path::new(&canonical),
515                    std::path::Path::new(root),
516                )
517                .is_ok()
518                {
519                    self.shell_cwd = Some(canonical);
520                }
521            }
522        }
523    }
524}