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
19/// `TaskInfo.intent` of a task `auto_infer_task` built from touched-file
20/// patterns. A label, never a stated task (#1590).
21pub(crate) const INFERRED_TASK_INTENT: &str = "inferred";
22/// `TaskInfo.intent` of a task `auto_infer_task` built from the working tree's
23/// uncommitted files. Describes state, never a stated task.
24pub(crate) const GIT_TASK_INTENT: &str = "git";
25
26/// Whether a task intent marks an `auto_infer_task` label (re-derivable, never
27/// a stated task). A plan title is a stated task and stays authoritative.
28pub(crate) fn is_auto_task_intent(intent: Option<&str>) -> bool {
29    matches!(intent, Some(INFERRED_TASK_INTENT | GIT_TASK_INTENT))
30}
31
32/// How many file names a git-derived task description lists before `+N more`.
33const GIT_TASK_MAX_FILES: usize = 3;
34
35/// Describe uncommitted files by name — `Uncommitted changes: entropy.rs,
36/// call_graph.rs (+2 more)` — instead of a `git diff --stat` summary whose only
37/// words were "files changed, insertions, deletions". `None` when clean.
38pub(super) fn describe_uncommitted_files<'a>(
39    paths: impl IntoIterator<Item = &'a str>,
40) -> Option<String> {
41    let names: Vec<&str> = paths
42        .into_iter()
43        .map(str::trim)
44        .filter(|p| !p.is_empty())
45        .map(|p| p.rsplit('/').next().unwrap_or(p))
46        .collect();
47    if names.is_empty() {
48        return None;
49    }
50    let listed = names[..names.len().min(GIT_TASK_MAX_FILES)].join(", ");
51    let more = names.len().saturating_sub(GIT_TASK_MAX_FILES);
52    Some(if more > 0 {
53        format!("Uncommitted changes: {listed} (+{more} more)")
54    } else {
55        format!("Uncommitted changes: {listed}")
56    })
57}
58
59/// Converts durable session signals into cross-session knowledge facts.
60pub(crate) fn extract_session_facts(
61    session: &SessionState,
62) -> Vec<crate::core::knowledge::KnowledgeFact> {
63    session
64        .derived_facts()
65        .into_iter()
66        .map(|(fact, _)| fact)
67        .collect()
68}
69
70impl SessionState {
71    /// [`extract_session_facts`], each fact with the finding it is built from
72    /// when it is built from exactly one: the `auto:blocker` facts. A store
73    /// that keeps such a fact carries the finding's source binding over to it
74    /// (`consolidation_engine::import_session_into`). A decision and a
75    /// touched-file record have no source binding to carry: `None`.
76    pub(crate) fn derived_facts(
77        &self,
78    ) -> Vec<(crate::core::knowledge::KnowledgeFact, Option<&Finding>)> {
79        derive_session_facts(self)
80    }
81}
82
83fn derive_session_facts(
84    session: &SessionState,
85) -> Vec<(crate::core::knowledge::KnowledgeFact, Option<&Finding>)> {
86    let mut facts = Vec::new();
87
88    facts.extend(session.decisions.iter().filter_map(|decision| {
89        let summary = decision.summary.trim();
90        if summary.is_empty() {
91            return None;
92        }
93        let value = decision
94            .rationale
95            .as_deref()
96            .filter(|rationale| !rationale.trim().is_empty())
97            .map_or_else(
98                || summary.to_owned(),
99                |rationale| format!("{summary} — {rationale}"),
100            );
101        Some((
102            auto_session_fact("auto:decision", value, session, decision.timestamp, 0.9),
103            None,
104        ))
105    }));
106
107    facts.extend(
108        session
109            .files_touched
110            .iter()
111            .filter(|file| file.modified)
112            .map(|file| {
113                let summary = file
114                    .summary
115                    .as_deref()
116                    .filter(|summary| !summary.trim().is_empty())
117                    .map_or_else(String::new, |summary| format!("; {summary}"));
118                let fact = auto_session_fact(
119                    "auto:pattern",
120                    format!(
121                        "Modified {} (mode: {}, reads: {}){summary}",
122                        file.path, file.last_mode, file.read_count
123                    ),
124                    session,
125                    session.updated_at,
126                    0.8,
127                );
128                (fact, None)
129            }),
130    );
131
132    facts.extend(session.findings.iter().filter_map(|finding| {
133        let summary = finding.summary.trim();
134        if summary.is_empty() || crate::core::auto_findings::is_activity_record(summary) {
135            return None;
136        }
137        let normalized = summary.to_ascii_lowercase();
138        let label = if ["resolved", "fixed", "solved", "unblocked", "passed"]
139            .iter()
140            .any(|keyword| normalized.contains(keyword))
141        {
142            "Resolution"
143        } else if [
144            "block", "fail", "error", "unable", "cannot", "missing", "timeout", "denied",
145        ]
146        .iter()
147        .any(|keyword| normalized.contains(keyword))
148        {
149            "Blocker"
150        } else {
151            "Finding"
152        };
153        let location = finding.file.as_deref().map_or_else(String::new, |file| {
154            finding
155                .line
156                .map_or_else(|| format!("{file}: "), |line| format!("{file}:{line}: "))
157        });
158        let fact = auto_session_fact(
159            "auto:blocker",
160            format!("{label}: {location}{summary}"),
161            session,
162            finding.timestamp,
163            0.75,
164        );
165        Some((fact, Some(finding)))
166    }));
167
168    facts
169}
170
171fn auto_session_fact(
172    category: &str,
173    value: String,
174    session: &SessionState,
175    timestamp: chrono::DateTime<Utc>,
176    confidence: f32,
177) -> crate::core::knowledge::KnowledgeFact {
178    let key = value.clone();
179    crate::core::knowledge::KnowledgeFact {
180        anchors: Vec::new(),
181        review: None,
182        capture: Default::default(),
183        origin: crate::core::knowledge::FactOrigin::Unverified,
184        category: category.to_owned(),
185        key,
186        value,
187        source_session: session.id.clone(),
188        confidence,
189        created_at: timestamp,
190        last_confirmed: timestamp,
191        retrieval_count: 0,
192        last_retrieved: None,
193        valid_from: None,
194        valid_until: None,
195        supersedes: None,
196        confirmation_count: 1,
197        feedback_up: 0,
198        feedback_down: 0,
199        last_feedback: None,
200        privacy: Default::default(),
201        sensitivity: Default::default(),
202        imported_from: None,
203        archetype: Default::default(),
204        fidelity: None,
205        revision_count: 0,
206        status: None,
207        validity: None,
208    }
209}
210
211impl Default for SessionState {
212    fn default() -> Self {
213        Self::new()
214    }
215}
216
217impl SessionState {
218    /// Creates a new session with a unique ID and current timestamp.
219    pub fn new() -> Self {
220        let now = Utc::now();
221        Self {
222            canonical_checkpoint: None,
223            save_gate: Default::default(),
224            last_save_failed: false,
225            id: generate_session_id(),
226            version: 0,
227            started_at: now,
228            updated_at: now,
229            project_root: None,
230            shell_cwd: None,
231            task: None,
232            findings: Vec::new(),
233            decisions: Vec::new(),
234            handoff_context: Vec::new(),
235            files_touched: Vec::new(),
236            test_results: None,
237            progress: Vec::new(),
238            next_steps: Vec::new(),
239            evidence: Vec::new(),
240            intents: Vec::new(),
241            active_structured_intent: None,
242            stats: SessionStats::default(),
243            terse_mode: false,
244            compression_level: String::new(),
245            last_consolidate_ts: None,
246            last_aaak_hash: None,
247            extra_roots: Vec::new(),
248            live_zone: super::types::LiveZoneSessionState::default(),
249            wakeup_manifest: Vec::new(),
250            playbook: super::playbook::Playbook::default(),
251            last_semantic_query: None,
252            last_flush: None,
253        }
254        .with_compression_from_config()
255    }
256
257    pub fn refresh_handoff_context(&mut self) {
258        let Some(project_root) = self.project_root.clone() else {
259            self.handoff_context.clear();
260            return;
261        };
262
263        let session_id = self.id.clone();
264        self.handoff_context = crate::core::knowledge::ProjectKnowledge::load(&project_root)
265            .map(|knowledge| {
266                // The handoff context is printed with its fact values: only
267                // facts that may be delivered now are copied into it
268                // (`ProjectKnowledge::delivery_filter`).
269                let deliverable = knowledge.delivery_filter();
270                knowledge
271                    .recent_decisions(10)
272                    .into_iter()
273                    .filter(|fact| fact.source_session != session_id && deliverable(fact))
274                    .collect()
275            })
276            .unwrap_or_default();
277    }
278
279    fn with_compression_from_config(mut self) -> Self {
280        let cfg = crate::core::config::Config::load();
281        let level = crate::core::config::CompressionLevel::effective(&cfg);
282        self.compression_level = level.label().to_string();
283        self.terse_mode = level.is_active();
284        self
285    }
286
287    /// Bumps the version counter and marks the session as dirty.
288    pub fn increment(&mut self) {
289        self.version += 1;
290        self.updated_at = Utc::now();
291        self.stats.unsaved_changes += 1;
292    }
293
294    /// Returns `true` if enough changes have accumulated to warrant a disk
295    /// save — or, since #717, if any change has waited longer than
296    /// `SESSION_FLUSH_INTERVAL`: the 5-change batch alone left slow
297    /// sessions invisible to the dashboard (stuck "idle") for the whole
298    /// batch window. A fresh in-memory session flushes its first change
299    /// immediately so new activity surfaces at once.
300    pub fn should_save(&self) -> bool {
301        if self.stats.unsaved_changes == 0 {
302            return false;
303        }
304        if self.stats.unsaved_changes >= BATCH_SAVE_INTERVAL {
305            return true;
306        }
307        match self.last_flush {
308            Some(t) => t.elapsed() >= SESSION_FLUSH_INTERVAL,
309            None => true,
310        }
311    }
312
313    /// Sets the active task and infers a structured intent from the description.
314    pub fn set_task(&mut self, description: &str, intent: Option<&str>) {
315        let (description_clean, _) =
316            crate::core::secret_detection::scan_and_redact_from_config(description);
317        // A canonical title edit continues the admitted task, not a new task ID.
318        let progress_pct = if self.canonical_checkpoint.is_some() {
319            self.task.as_ref().and_then(|task| task.progress_pct)
320        } else {
321            None
322        };
323        self.task = Some(TaskInfo {
324            description: description_clean.clone(),
325            intent: intent.map(std::string::ToString::to_string),
326            progress_pct,
327        });
328        // An auto-inferred label is not a stated task: its words must not
329        // become the structured intent that steers entropy/IB reads.
330        if is_auto_task_intent(intent) {
331            self.increment();
332            return;
333        }
334
335        let touched: Vec<String> = self.files_touched.iter().map(|f| f.path.clone()).collect();
336        let si = if touched.is_empty() {
337            crate::core::intent_engine::StructuredIntent::from_query(&description_clean)
338        } else {
339            crate::core::intent_engine::StructuredIntent::from_query_with_session(
340                &description_clean,
341                &touched,
342            )
343        };
344        if si.confidence >= 0.7 {
345            self.active_structured_intent = Some(si);
346        }
347
348        self.increment();
349    }
350
351    /// Auto-infers the task from available context (plans, git diff, file patterns).
352    /// Never overwrites a stated task; an earlier *auto-inferred* one is
353    /// re-derived, so a label from a past session or a since-committed working
354    /// tree does not linger as "the task" forever.
355    pub fn auto_infer_task(&mut self) {
356        if self
357            .task
358            .as_ref()
359            .is_some_and(|t| !is_auto_task_intent(t.intent.as_deref()))
360        {
361            return;
362        }
363        let inferred = self.infer_task();
364        let unchanged = match (&self.task, &inferred) {
365            (Some(t), Some((desc, intent))) => {
366                t.description == *desc && t.intent.as_deref() == Some(*intent)
367            }
368            (None, None) => true,
369            _ => false,
370        };
371        if unchanged {
372            return;
373        }
374        if let Some((desc, intent)) = inferred {
375            self.set_task(&desc, Some(intent));
376        } else {
377            // Nothing to infer any more (plan done, tree committed): a stale
378            // auto label must not outlive the state it described.
379            self.task = None;
380            self.increment();
381        }
382    }
383
384    /// The first available auto source: active plan, uncommitted files,
385    /// touched-file patterns. `(description, intent)`.
386    fn infer_task(&self) -> Option<(String, &'static str)> {
387        if let Some(task_from_plan) = Self::infer_task_from_plans() {
388            return Some((task_from_plan, "plan"));
389        }
390        if let Some(ref root) = self.project_root
391            && let Some(task_from_git) = Self::infer_task_from_git(root)
392        {
393            return Some((task_from_git, GIT_TASK_INTENT));
394        }
395        if self.files_touched.len() < 3 {
396            return None;
397        }
398        let touched: Vec<String> = self.files_touched.iter().map(|f| f.path.clone()).collect();
399        let intent = crate::core::intent_engine::StructuredIntent::from_file_patterns(&touched);
400        if intent.confidence < 0.5 {
401            return None;
402        }
403        let dirs: std::collections::BTreeSet<&str> = touched
404            .iter()
405            .filter_map(|f| std::path::Path::new(f).parent()?.to_str())
406            .collect();
407        let primary_dir = dirs.iter().next().unwrap_or(&".");
408        Some((
409            format!("Working on {} ({})", primary_dir, intent.task_type.as_str()),
410            INFERRED_TASK_INTENT,
411        ))
412    }
413
414    fn infer_task_from_plans() -> Option<String> {
415        let plans_dir = std::path::Path::new(".cursor/plans");
416        if !plans_dir.exists() {
417            return None;
418        }
419
420        let mut newest: Option<(std::time::SystemTime, String)> = None;
421        if let Ok(entries) = std::fs::read_dir(plans_dir) {
422            for entry in entries.flatten() {
423                let path = entry.path();
424                if !path.to_string_lossy().ends_with(".plan.md") {
425                    continue;
426                }
427                let mtime = entry.metadata().ok()?.modified().ok()?;
428                let content = std::fs::read_to_string(&path).ok()?;
429
430                // Check if plan has active (pending/in_progress) todos
431                let has_active =
432                    content.contains("status: pending") || content.contains("status: in_progress");
433                if !has_active {
434                    continue;
435                }
436
437                // Extract plan name from frontmatter
438                let name = content
439                    .lines()
440                    .find(|l| l.starts_with("name:"))
441                    .map_or("Unknown Plan", |l| {
442                        l.trim_start_matches("name:").trim().trim_matches('"')
443                    });
444
445                let better = newest.as_ref().is_none_or(|(t, _)| mtime > *t);
446                if better {
447                    newest = Some((mtime, name.to_string()));
448                }
449            }
450        }
451
452        newest.map(|(_, name)| name)
453    }
454
455    fn infer_task_from_git(project_root: &str) -> Option<String> {
456        let output = std::process::Command::new("git")
457            .args(["diff", "--name-only", "--no-color"])
458            .current_dir(project_root)
459            .output()
460            .ok()?;
461        if !output.status.success() {
462            return None;
463        }
464        describe_uncommitted_files(String::from_utf8_lossy(&output.stdout).lines())
465    }
466
467    /// Records a finding (discovery or observation) in the session log.
468    pub fn add_finding(&mut self, file: Option<&str>, line: Option<u32>, summary: &str) {
469        let (summary_clean, _) =
470            crate::core::secret_detection::scan_and_redact_from_config(summary);
471        self.findings.push(Finding {
472            file: file.map(std::string::ToString::to_string),
473            line,
474            summary: summary_clean,
475            timestamp: Utc::now(),
476        });
477        while self.findings.len() > MAX_FINDINGS {
478            self.findings.remove(0);
479        }
480        self.increment();
481    }
482
483    /// Records a design or implementation decision with optional rationale.
484    pub fn add_decision(&mut self, summary: &str, rationale: Option<&str>) {
485        let (summary_clean, _) =
486            crate::core::secret_detection::scan_and_redact_from_config(summary);
487        let rationale_clean =
488            rationale.map(|r| crate::core::secret_detection::scan_and_redact_from_config(r).0);
489        self.decisions.push(Decision {
490            summary: summary_clean,
491            rationale: rationale_clean,
492            timestamp: Utc::now(),
493        });
494        while self.decisions.len() > MAX_DECISIONS {
495            self.decisions.remove(0);
496        }
497        self.increment();
498    }
499
500    /// Records a file read/access in the session, incrementing its read count.
501    pub fn touch_file(&mut self, path: &str, file_ref: Option<&str>, mode: &str, tokens: usize) {
502        if let Some(existing) = self.files_touched.iter_mut().find(|f| f.path == path) {
503            existing.read_count += 1;
504            existing.last_mode = mode.to_string();
505            existing.tokens = tokens;
506            if let Some(r) = file_ref {
507                existing.file_ref = Some(r.to_string());
508            }
509        } else {
510            let item_id = crate::core::context_field::ContextItemId::from_file(path);
511            self.files_touched.push(FileTouched {
512                path: path.to_string(),
513                file_ref: file_ref.map(std::string::ToString::to_string),
514                read_count: 1,
515                modified: false,
516                last_mode: mode.to_string(),
517                tokens,
518                stale: false,
519                context_item_id: Some(item_id.to_string()),
520                summary: None,
521            });
522            while self.files_touched.len() > MAX_FILES {
523                self.files_touched.remove(0);
524            }
525        }
526        self.stats.files_read += 1;
527        self.increment();
528    }
529
530    /// Marks a previously touched file as modified (written to).
531    pub fn mark_modified(&mut self, path: &str) {
532        if let Some(existing) = self.files_touched.iter_mut().find(|f| f.path == path) {
533            existing.modified = true;
534        }
535        self.increment();
536    }
537
538    /// Sets a one-line content summary for a touched file (max 80 chars).
539    pub fn set_file_summary(&mut self, path: &str, summary: &str) {
540        if let Some(existing) = self.files_touched.iter_mut().find(|f| f.path == path) {
541            let truncated = if summary.len() > 80 {
542                format!("{}…", &summary[..79])
543            } else {
544                summary.to_string()
545            };
546            existing.summary = Some(truncated);
547        }
548    }
549
550    /// Increments the tool call counter and accumulates token savings.
551    pub fn record_tool_call(&mut self, tokens_saved: u64, tokens_input: u64) {
552        self.stats.total_tool_calls += 1;
553        self.stats.total_tokens_saved += tokens_saved;
554        self.stats.total_tokens_input += tokens_input;
555        self.stats.day_mut(Utc::now()).tool_calls += 1;
556        if self.stats.client.is_none() {
557            let client = crate::core::client_capabilities::current().client_id;
558            if client != "unknown" {
559                self.stats.client = Some(client);
560            }
561        }
562    }
563
564    /// Records an inferred or explicit intent, coalescing consecutive duplicates.
565    pub fn record_intent(&mut self, mut intent: IntentRecord) {
566        if intent.occurrences == 0 {
567            intent.occurrences = 1;
568        }
569
570        if let Some(last) = self.intents.last_mut()
571            && last.fingerprint() == intent.fingerprint()
572        {
573            last.occurrences = last.occurrences.saturating_add(intent.occurrences);
574            last.timestamp = intent.timestamp;
575            match intent.source {
576                IntentSource::Inferred => self.stats.intents_inferred += 1,
577                IntentSource::Explicit => self.stats.intents_explicit += 1,
578            }
579            self.increment();
580            return;
581        }
582
583        match intent.source {
584            IntentSource::Inferred => self.stats.intents_inferred += 1,
585            IntentSource::Explicit => self.stats.intents_explicit += 1,
586        }
587
588        self.intents.push(intent);
589        while self.intents.len() > crate::core::budgets::INTENTS_PER_SESSION_LIMIT {
590            self.intents.remove(0);
591        }
592        self.increment();
593    }
594
595    /// Appends an auditable evidence record for a tool invocation.
596    pub fn record_tool_receipt(
597        &mut self,
598        tool: &str,
599        action: Option<&str>,
600        input_md5: &str,
601        output_md5: &str,
602        agent_id: Option<&str>,
603        client_name: Option<&str>,
604    ) {
605        self.record_tool_receipt_with_task(
606            tool,
607            action,
608            input_md5,
609            output_md5,
610            agent_id,
611            client_name,
612            None,
613        );
614    }
615
616    /// Records a tool receipt with optional MCP task lineage.
617    pub fn record_tool_receipt_with_task(
618        &mut self,
619        tool: &str,
620        action: Option<&str>,
621        input_md5: &str,
622        output_md5: &str,
623        agent_id: Option<&str>,
624        client_name: Option<&str>,
625        task_id: Option<&str>,
626    ) {
627        let now = Utc::now();
628        let mut push = |key: String| {
629            self.evidence.push(EvidenceRecord {
630                kind: EvidenceKind::ToolCall,
631                key,
632                value: None,
633                tool: Some(tool.to_string()),
634                input_md5: Some(input_md5.to_string()),
635                output_md5: Some(output_md5.to_string()),
636                agent_id: agent_id.map(std::string::ToString::to_string),
637                client_name: client_name.map(std::string::ToString::to_string),
638                task_id: task_id.map(std::string::ToString::to_string),
639                timestamp: now,
640            });
641        };
642
643        push(format!("tool:{tool}"));
644        if let Some(a) = action {
645            push(format!("tool:{tool}:{a}"));
646        }
647        while self.evidence.len() > MAX_EVIDENCE {
648            self.evidence.remove(0);
649        }
650        self.increment();
651    }
652
653    /// Appends a manual (non-tool) evidence record to the audit log.
654    pub fn record_manual_evidence(&mut self, key: &str, value: Option<&str>) {
655        self.evidence.push(EvidenceRecord {
656            kind: EvidenceKind::Manual,
657            key: key.to_string(),
658            value: value.map(std::string::ToString::to_string),
659            tool: None,
660            input_md5: None,
661            output_md5: None,
662            agent_id: None,
663            client_name: None,
664            task_id: None,
665            timestamp: Utc::now(),
666        });
667        while self.evidence.len() > MAX_EVIDENCE {
668            self.evidence.remove(0);
669        }
670        self.increment();
671    }
672
673    /// Returns `true` if an evidence record with the given key exists.
674    pub fn has_evidence_key(&self, key: &str) -> bool {
675        self.evidence.iter().any(|e| e.key == key)
676    }
677
678    /// Increments the session-level cache hit counter.
679    pub fn record_cache_hit(&mut self) {
680        self.stats.cache_hits += 1;
681        self.stats.day_mut(Utc::now()).cache_hits += 1;
682    }
683
684    /// Increments the session-level command counter.
685    pub fn record_command(&mut self) {
686        self.stats.commands_run += 1;
687    }
688
689    /// Returns the effective working directory for shell commands.
690    /// Priority: explicit cwd arg > session shell_cwd > project_root > process cwd.
691    /// Explicit CWD and stored shell_cwd are jail-checked against the project root
692    /// to prevent MCP clients from escaping the workspace.
693    pub fn effective_cwd(&self, explicit_cwd: Option<&str>) -> String {
694        self.effective_cwd_checked(explicit_cwd).0
695    }
696
697    /// Like [`Self::effective_cwd`], but also reports *why* an explicit `cwd`
698    /// request was rejected by the project-root jail and silently replaced with
699    /// the project root (#629).
700    ///
701    /// The jail itself is deliberate sandboxing (it stops MCP clients escaping
702    /// the workspace) and must stay — the only gap was that the substitution was
703    /// silent, so a caller running `pwd && ls` in what they think is dir A
704    /// actually ran in the project root with no indication why. Callers that
705    /// surface output to a human/agent (e.g. `ctx_shell`) use the returned
706    /// `Option<String>` reason to append a one-line hint instead of letting the
707    /// swap pass unnoticed; `effective_cwd` keeps the original lossless behaviour.
708    pub fn effective_cwd_checked(&self, explicit_cwd: Option<&str>) -> (String, Option<String>) {
709        let root = self.project_root.as_deref().unwrap_or(".");
710        if let Some(cwd) = explicit_cwd
711            && !cwd.is_empty()
712            && cwd != "."
713        {
714            return Self::jail_cwd(cwd, root);
715        }
716        if let Some(ref cwd) = self.shell_cwd {
717            return (cwd.clone(), None);
718        }
719        if let Some(ref r) = self.project_root {
720            return (r.clone(), None);
721        }
722        (
723            std::env::current_dir()
724                .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string()),
725            None,
726        )
727    }
728
729    /// The directory a command is to RUN in, or the reason there is none.
730    ///
731    /// Unlike [`Self::effective_cwd_checked`] nothing is substituted: an
732    /// explicit `cwd` the project jail rejects is an error, so the command is
733    /// not executed, backgrounded or cached under a directory the caller did
734    /// not name. The stored shell cwd is held to the same jail — it was
735    /// accepted when it was stored, but the project root may have changed
736    /// since. Without a project root there is no jail to hold it to, and the
737    /// stored value is used as before.
738    pub fn execution_cwd(&self, explicit_cwd: Option<&str>) -> Result<String, String> {
739        let jailed = |candidate: &str, root: &str| {
740            crate::core::pathjail::jail_path(
741                std::path::Path::new(candidate),
742                std::path::Path::new(root),
743            )
744            .map(|path| path.to_string_lossy().to_string())
745            .map_err(|reason| reason.to_string())
746        };
747        if let Some(cwd) = explicit_cwd
748            && !cwd.is_empty()
749            && cwd != "."
750        {
751            return jailed(cwd, self.project_root.as_deref().unwrap_or("."));
752        }
753        match (self.shell_cwd.as_deref(), self.project_root.as_deref()) {
754            (Some(cwd), Some(root)) => jailed(cwd, root),
755            (Some(cwd), None) => Ok(cwd.to_string()),
756            (None, Some(root)) => Ok(root.to_string()),
757            (None, None) => Ok(std::env::current_dir()
758                .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string())),
759        }
760    }
761
762    /// Verifies that `candidate` is within the project jail.
763    ///
764    /// Falls back to `fallback_root` if the candidate escapes, returning the
765    /// jail-rejection reason as the second tuple element so callers can surface
766    /// it instead of silently substituting the root (#629). `None` means the
767    /// candidate was accepted as-is.
768    fn jail_cwd(candidate: &str, fallback_root: &str) -> (String, Option<String>) {
769        let p = std::path::Path::new(candidate);
770        match crate::core::pathjail::jail_path(p, std::path::Path::new(fallback_root)) {
771            Ok(jailed) => (jailed.to_string_lossy().to_string(), None),
772            Err(reason) => (fallback_root.to_string(), Some(reason.to_string())),
773        }
774    }
775
776    /// Persist an explicit, jail-accepted `cwd` argument as the live shell
777    /// cwd (#707). `update_shell_cwd` only tracks `cd` inside the command
778    /// text, but clients that switch checkouts mid-session (Claude Code
779    /// after `EnterWorktree`) pass the new directory as the `cwd` *param* of
780    /// every subsequent call — without persisting it, the worktree-divergence
781    /// detection in path resolution never sees the switch. Callers must pass
782    /// a cwd that already passed the project-root jail.
783    pub fn note_explicit_cwd(&mut self, cwd: &str) {
784        let path = std::path::Path::new(cwd);
785        if path.is_absolute() && path.is_dir() {
786            self.shell_cwd = Some(
787                crate::core::pathutil::safe_canonicalize_or_self(path)
788                    .to_string_lossy()
789                    .to_string(),
790            );
791        }
792    }
793
794    /// Updates shell_cwd by detecting `cd` in the command.
795    /// Handles: `cd /abs/path`, `cd rel/path` (relative to current cwd),
796    /// `cd ..`, and chained commands like `cd foo && ...`.
797    /// The new CWD is jail-checked against the project root.
798    pub fn update_shell_cwd(&mut self, command: &str) {
799        let base = self.effective_cwd(None);
800        if let Some(new_cwd) = extract_cd_target(command, &base) {
801            let path = std::path::Path::new(&new_cwd);
802            if path.exists() && path.is_dir() {
803                let canonical = crate::core::pathutil::safe_canonicalize_or_self(path)
804                    .to_string_lossy()
805                    .to_string();
806                let root = self.project_root.as_deref().unwrap_or(".");
807                if crate::core::pathjail::jail_path(
808                    std::path::Path::new(&canonical),
809                    std::path::Path::new(root),
810                )
811                .is_ok()
812                {
813                    self.shell_cwd = Some(canonical);
814                }
815            }
816        }
817    }
818}