Skip to main content

lean_ctx/tools/
server_paths.rs

1use super::server::LeanCtxServer;
2use super::startup::{
3    has_project_marker, is_suspicious_root, maybe_derive_project_root_from_absolute,
4};
5
6impl LeanCtxServer {
7    pub fn checkpoint_interval_effective() -> usize {
8        if let Ok(v) = std::env::var("LEAN_CTX_CHECKPOINT_INTERVAL")
9            && let Ok(parsed) = v.trim().parse::<usize>()
10        {
11            return parsed;
12        }
13        let profile_interval = crate::core::profiles::active_profile()
14            .autonomy
15            .checkpoint_interval_effective();
16        if profile_interval > 0 {
17            return profile_interval as usize;
18        }
19        crate::core::config::Config::load().checkpoint_interval as usize
20    }
21
22    /// Resolves a (possibly relative) tool path against the session's project_root.
23    /// Absolute paths and "." are returned as-is. Relative paths like "src/main.rs"
24    /// are joined with project_root so tools work regardless of the server's cwd.
25    pub async fn resolve_path(&self, path: &str) -> Result<String, String> {
26        let normalized = crate::core::pathutil::normalize_tool_path(path);
27        if normalized.is_empty() || normalized == "." {
28            let root = self.session.read().await.project_root.clone();
29            return crate::core::workspace_authority::project_dot(&normalized, root.as_deref());
30        }
31        let p = std::path::Path::new(&normalized);
32
33        let (resolved, jail_root, extra_roots) = {
34            let session = self.session.read().await;
35            let jail_root = session
36                .project_root
37                .as_deref()
38                .or(session.shell_cwd.as_deref())
39                .unwrap_or(".")
40                .to_string();
41
42            // #707: a shell_cwd tracking a mid-session worktree switch
43            // (different git checkout) outranks the stale project_root — same
44            // precedence as core::path_resolve. Checked BEFORE the `p.exists()`
45            // probe below: that probe runs against the *process* CWD, which
46            // IDEs routinely set to the original project root, so it would
47            // short-circuit every relative path back to the stale checkout and
48            // the divergence rule could never apply.
49            let worktree_cwd = if p.is_absolute() {
50                None
51            } else {
52                session
53                    .project_root
54                    .as_deref()
55                    .zip(session.shell_cwd.as_deref())
56                    .filter(|(root, cwd)| {
57                        crate::core::path_resolve::shell_cwd_is_divergent_checkout(root, cwd)
58                    })
59                    .map(|(_, cwd)| std::path::Path::new(cwd).join(&normalized))
60            };
61
62            let resolved = if let Some(overridden) = worktree_cwd {
63                overridden
64            } else if p.is_absolute() || p.exists() {
65                std::path::PathBuf::from(&normalized)
66            } else if let Some(ref root) = session.project_root {
67                let joined = std::path::Path::new(root).join(&normalized);
68                if joined.exists() {
69                    joined
70                } else if let Some(ref cwd) = session.shell_cwd {
71                    std::path::Path::new(cwd).join(&normalized)
72                } else {
73                    std::path::Path::new(&jail_root).join(&normalized)
74                }
75            } else if let Some(ref cwd) = session.shell_cwd {
76                std::path::Path::new(cwd).join(&normalized)
77            } else {
78                std::path::Path::new(&jail_root).join(&normalized)
79            };
80
81            // Session-scoped trusted roots (MCP roots/list, config extra_roots,
82            // git worktrees) must widen the jail for an explicit path (#403).
83            if session.project_root.is_none()
84                && let Some(error) =
85                    crate::core::path_resolve::unbound_relative_path(path, &resolved, &jail_root)
86            {
87                return Err(error);
88            }
89            (resolved, jail_root, session.extra_roots.clone())
90        };
91
92        let jail_root_path = std::path::Path::new(&jail_root);
93        let jailed = match crate::core::pathjail::jail_path_with_roots(
94            &resolved,
95            jail_root_path,
96            &extra_roots,
97        ) {
98            Ok(p) => self
99                .maybe_reroot_for_absolute_path(&resolved, jail_root_path, &extra_roots)
100                .await?
101                .unwrap_or(p),
102            Err(e) => {
103                // #899: a refused path in a language cache or an agent
104                // instruction folder is admitted read-only for the session
105                // and resolved again (see `jail_path_auto_admitting`). If it
106                // is still refused, report why — "retry" would only repeat
107                // the same refusal.
108                if crate::core::pathjail::detect_language_cache_root(&resolved).is_some() {
109                    match crate::core::pathjail::jail_path_auto_admitting(
110                        &resolved,
111                        jail_root_path,
112                        &extra_roots,
113                    ) {
114                        Ok(jailed) => jailed,
115                        Err(retry) => {
116                            crate::core::security_events::record_one(
117                                "resolve_path",
118                                "unknown",
119                                crate::core::security_events::SecurityKind::PathBlocked,
120                            );
121                            crate::core::hive::metrics_v2::signals::blocked(
122                                &crate::core::hive::metrics_v2::signals::path_jail_rule(),
123                            );
124                            return Err(retry.to_string());
125                        }
126                    }
127                } else if let Some(jailed) = self
128                    .maybe_reroot_for_absolute_path(&resolved, jail_root_path, &extra_roots)
129                    .await?
130                {
131                    jailed
132                } else {
133                    // Resolution runs on the async side, outside the handler's
134                    // collector, so the refusal is recorded directly.
135                    crate::core::security_events::record_one(
136                        "resolve_path",
137                        "unknown",
138                        crate::core::security_events::SecurityKind::PathBlocked,
139                    );
140                    crate::core::hive::metrics_v2::signals::blocked(
141                        &crate::core::hive::metrics_v2::signals::path_jail_rule(),
142                    );
143                    return Err(e.to_string());
144                }
145            }
146        };
147
148        crate::core::io_boundary::check_secret_path_for_tool("resolve_path", &jailed)?;
149
150        Ok(crate::core::pathutil::normalize_tool_path(
151            &jailed.to_string_lossy().replace('\\', "/"),
152        ))
153    }
154
155    async fn maybe_reroot_for_absolute_path(
156        &self,
157        resolved: &std::path::Path,
158        jail_root_path: &std::path::Path,
159        extra_roots: &[String],
160    ) -> Result<Option<std::path::PathBuf>, String> {
161        // A shared session is every client's: one client's path never moves
162        // it (AP04-G5/G6).
163        if !resolved.is_absolute() || self.session_mode == super::SessionMode::Shared {
164            return Ok(None);
165        }
166        // Under a Workspace the session root follows the snapshot only
167        // (#2120); a path never moves it.
168        if crate::core::workspace_authority::is_configured() {
169            return Ok(None);
170        }
171        // A root pinned with `LEAN_CTX_PROJECT_ROOT` is a boundary the operator
172        // set, not a guess to correct: a markerless pinned directory inside a
173        // larger checkout must not be widened to that checkout — and every
174        // index, policy and receipt moved with it — by the first absolute path.
175        if crate::server::roots::pinned_root().is_some_and(|pinned| {
176            crate::core::pathutil::safe_canonicalize_or_self(std::path::Path::new(&pinned))
177                == crate::core::pathutil::safe_canonicalize_or_self(jail_root_path)
178        }) {
179            return Ok(None);
180        }
181        // The outermost marker above a path can be `~` itself (a dotfiles
182        // repository) or an agent directory: never a project to move to
183        // (AP04-G6).
184        let Some(new_root) = maybe_derive_project_root_from_absolute(resolved)
185            .filter(|root| !crate::core::pathutil::is_broad_or_unsafe_root(root))
186        else {
187            return Ok(None);
188        };
189        let jail_is_real_project =
190            has_project_marker(jail_root_path) && !is_suspicious_root(jail_root_path);
191        let candidate_under_jail = resolved.starts_with(jail_root_path);
192        // #1437: never reroot to a child when jail is a real project. Skip when
193        // jail is suspicious (/, home, agent-config) — not a real boundary.
194        if jail_is_real_project
195            && new_root.starts_with(jail_root_path)
196            && new_root != jail_root_path
197        {
198            return Ok(None);
199        }
200        // Universal auto-reroot: when the jail root is not a real project
201        // (suspicious, None, or markerless), correct to derived project root.
202        // No IDE-specific logic — works for all IDEs and daemon.
203        let allow_reroot = if candidate_under_jail && jail_is_real_project {
204            false
205        } else {
206            !jail_is_real_project || self.session.read().await.project_root.is_none()
207        };
208
209        if !allow_reroot {
210            return Ok(None);
211        }
212
213        if !self.reroot_to_project(&new_root).await {
214            return Ok(None);
215        }
216        crate::core::pathjail::jail_path_with_roots(resolved, &new_root, extra_roots)
217            .map(Some)
218            .map_err(|e| e.to_string())
219    }
220
221    /// Move the session — and the request that corrected it — to `new_root`
222    /// through the same switch as a host's root change: that project's own
223    /// session, the stale one saved where it was (AP04 review S4). Refused
224    /// under a pinned source view, whose request project cannot follow.
225    async fn reroot_to_project(&self, new_root: &std::path::Path) -> bool {
226        if crate::core::policy::runtime::inherited_source_view().is_some() {
227            return false;
228        }
229        let new_root_str = new_root.to_string_lossy().to_string();
230        let shell_cwd = self
231            .startup_shell_cwd
232            .as_ref()
233            .filter(|cwd| std::path::Path::new(cwd).starts_with(new_root))
234            .cloned()
235            .or_else(|| Some(new_root_str.clone()));
236        let current = self.session.instance();
237        let extra_roots = current.read().await.extra_roots.clone();
238        let switch = crate::server::SessionSwitch {
239            new_root: &new_root_str,
240            extra_roots,
241            shell_cwd,
242            rebind_request: true,
243        };
244        let Some(saves) = self.switch_session_root(&current, switch).await else {
245            return false;
246        };
247        for save in saves {
248            let _ = save.await;
249        }
250        true
251    }
252
253    /// Like `resolve_path`, but returns the original path on failure instead of an error.
254    pub async fn resolve_path_or_passthrough(&self, path: &str) -> String {
255        self.resolve_path(path)
256            .await
257            .unwrap_or_else(|_| path.to_string())
258    }
259}