Skip to main content

lean_ctx/server/
multi_path.rs

1// SPDX-License-Identifier: Apache-2.0
2use serde_json::{Map, Value};
3
4use crate::server::tool_trait::{ToolContext, get_str, get_str_array};
5
6#[derive(Debug)]
7pub struct ResolvedPaths {
8    pub roots: Vec<String>,
9    pub is_multi: bool,
10}
11
12/// Resolve tool paths with multi-root support.
13///
14/// Priority:
15/// 0. `repo` argument (multi-repo alias → specific root)
16/// 1. `paths` array argument (explicit multi-root)
17/// 2. `path` string argument (single root, pre-resolved by dispatch)
18/// 3. Session `extra_roots` (default multi-root from config/MCP)
19/// 4. Resolve the active project root (never the process working directory)
20///
21/// Returns `Err` when an **explicit** `path`/`paths` argument was supplied but
22/// could not be resolved (outside the project root, secret-screened, or
23/// non-existent). Silently falling back to the project root in that case made
24/// `ctx_tree path=/outside/repo` return the whole project tree (#401).
25pub fn resolve_tool_paths(
26    args: &Map<String, Value>,
27    ctx: &ToolContext,
28) -> Result<ResolvedPaths, String> {
29    if let Some(repo) = get_str(args, "repo")
30        && let Some(root) = crate::core::multi_repo::resolve_repo_root(&repo)
31    {
32        return Ok(ResolvedPaths {
33            roots: vec![root],
34            is_multi: false,
35        });
36    }
37
38    if let Some(paths) = get_str_array(args, "paths")
39        && !paths.is_empty()
40    {
41        let resolved = resolve_paths_sync(ctx, &paths);
42        if !resolved.is_empty() {
43            return Ok(ResolvedPaths {
44                is_multi: resolved.len() > 1,
45                roots: resolved,
46            });
47        }
48        // The caller explicitly listed paths but none resolved — surface
49        // the failure instead of scanning the project root (#401).
50        return Err(format!(
51            "none of the requested paths could be resolved — they may not exist or are \
52                 outside the project root: {}",
53            paths.join(", ")
54        ));
55    }
56
57    // #846: `file_path` is an alias for `path` in ctx_search — agents
58    // (especially Claude Code) send it expecting file-level scoping.
59    // Without this fallback the parameter is silently ignored and the
60    // search runs on the project root.
61    for key in &["path", "file_path"] {
62        if let Some(p) = ctx.resolved_path(key) {
63            return Ok(ResolvedPaths {
64                roots: vec![p.to_string()],
65                is_multi: false,
66            });
67        }
68        // An explicit path the dispatcher could not resolve lands in
69        // `path_errors`. Do NOT fall back to the project root — return the
70        // resolution error so the agent learns the path is out of scope
71        // rather than silently receiving an unrelated tree (#401).
72        if let Some(detail) = ctx.path_error(key) {
73            return Err(detail.to_string());
74        }
75    }
76
77    // Validate before extra roots can return a default scope. An empty or
78    // relative primary must never be interpreted against the process CWD.
79    if ctx.project_root.trim().is_empty() {
80        return Err("active project root is required when no path is supplied".to_string());
81    }
82    if !std::path::Path::new(&ctx.project_root).is_absolute() {
83        return Err("active project root must be absolute when no path is supplied".to_string());
84    }
85
86    if let Some(session_lock) = ctx.session.as_ref() {
87        let (extra, jail_root) = {
88            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
89            let guard = loop {
90                if let Ok(g) = session_lock.clone().try_read_owned() {
91                    break Some(g);
92                }
93                if std::time::Instant::now() >= deadline {
94                    break None;
95                }
96                std::thread::sleep(std::time::Duration::from_millis(25));
97            };
98            match guard {
99                Some(session) => {
100                    let root = session
101                        .project_root
102                        .clone()
103                        .unwrap_or_else(|| ".".to_string());
104                    (session.extra_roots.clone(), root)
105                }
106                None => (Vec::new(), ".".to_string()),
107            }
108        };
109        if !extra.is_empty() {
110            let jail = std::path::Path::new(&jail_root);
111            let mut roots = vec![ctx.project_root.clone()];
112            for r in &extra {
113                let p = std::path::Path::new(r);
114                if !p.is_dir() {
115                    continue;
116                }
117                match crate::core::pathjail::jail_path(p, jail) {
118                    Ok(_) => roots.push(r.clone()),
119                    Err(e) => tracing::warn!("extra_root rejected by PathJail: {e}"),
120                }
121            }
122            if roots.len() > 1 {
123                return Ok(ResolvedPaths {
124                    is_multi: true,
125                    roots,
126                });
127            }
128        }
129    }
130
131    Ok(ResolvedPaths {
132        roots: vec![ctx.resolve_path_sync(&ctx.project_root)?],
133        is_multi: false,
134    })
135}
136
137fn resolve_paths_sync(ctx: &ToolContext, raw: &[String]) -> Vec<String> {
138    let mut out = Vec::with_capacity(raw.len());
139    for p in raw {
140        match ctx.resolve_path_sync(p) {
141            Ok(resolved) => out.push(resolved),
142            Err(e) => {
143                tracing::warn!("multi-path resolve failed for {p}: {e}");
144            }
145        }
146    }
147    out
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153    use serde_json::json;
154
155    fn test_ctx() -> ToolContext {
156        ToolContext {
157            project_root: "/test/project".to_string(),
158            extra_roots: Vec::new(),
159            minimal: false,
160            resolved_paths: std::collections::HashMap::new(),
161            crp_mode: crate::tools::CrpMode::Off,
162            cache: None,
163            session: None,
164            tool_calls: None,
165            agent_id: None,
166            workflow: None,
167            ledger: None,
168            client_name: None,
169            client_role: None,
170            shell_access: None,
171            pipeline_stats: None,
172            call_count: None,
173            autonomy: None,
174            pressure_snapshot: None,
175            path_errors: std::collections::HashMap::new(),
176            bm25_cache: None,
177            progress_sender: None,
178            cancel: None,
179        }
180    }
181
182    #[test]
183    fn fallback_uses_context_project_not_process_cwd() {
184        let args = Map::new();
185        let project = tempfile::tempdir().unwrap();
186        let root = project.path().canonicalize().unwrap();
187        assert_ne!(
188            root,
189            std::env::current_dir().unwrap().canonicalize().unwrap()
190        );
191        let mut ctx = test_ctx();
192        ctx.project_root = root.to_string_lossy().into_owned();
193        let result = resolve_tool_paths(&args, &ctx).expect("no explicit path → default");
194        assert_eq!(result.roots.len(), 1);
195        assert_eq!(
196            std::fs::canonicalize(&result.roots[0]).expect("resolved project root"),
197            std::fs::canonicalize(root).expect("canonical context project root"),
198            "fallback must resolve to the context project, independent of path spelling"
199        );
200        assert!(!result.is_multi);
201    }
202
203    #[test]
204    fn missing_context_root_does_not_search_process_cwd() {
205        let mut ctx = test_ctx();
206        ctx.project_root.clear();
207        let error = resolve_tool_paths(&Map::new(), &ctx).unwrap_err();
208        assert!(error.contains("active project root is required"));
209    }
210
211    #[test]
212    fn relative_context_root_does_not_search_process_cwd() {
213        for root in [".", "relative-project"] {
214            let mut ctx = test_ctx();
215            ctx.project_root = root.to_string();
216            assert!(
217                resolve_tool_paths(&Map::new(), &ctx).is_err(),
218                "root: {root}"
219            );
220        }
221    }
222
223    #[test]
224    fn extra_roots_cannot_bypass_invalid_primary_root() {
225        let _data = crate::core::data_dir::isolated_data_dir();
226        let extra = tempfile::tempdir().unwrap();
227        let extra_root = extra
228            .path()
229            .canonicalize()
230            .unwrap()
231            .to_string_lossy()
232            .into_owned();
233        let mut session = crate::core::session::SessionState::new();
234        session.project_root = Some(extra_root.clone());
235        session.extra_roots = vec![extra_root.clone()];
236        let mut ctx = test_ctx();
237        ctx.session = Some(std::sync::Arc::new(tokio::sync::RwLock::new(session)));
238        for root in ["", ".", "relative-project"] {
239            ctx.project_root = root.to_string();
240            assert!(
241                resolve_tool_paths(&Map::new(), &ctx).is_err(),
242                "root: {root}"
243            );
244        }
245        // A valid absolute primary still permits the existing multi-root path.
246        ctx.project_root = extra_root;
247        let resolved = resolve_tool_paths(&Map::new(), &ctx).unwrap();
248        assert!(resolved.is_multi);
249        assert!(resolved.roots.iter().all(|root| root == &ctx.project_root));
250    }
251
252    #[test]
253    fn uses_resolved_path_when_present() {
254        let args = Map::new();
255        let mut ctx = test_ctx();
256        ctx.resolved_paths
257            .insert("path".to_string(), "/resolved/dir".to_string());
258        let result = resolve_tool_paths(&args, &ctx).expect("resolved path");
259        assert_eq!(result.roots, vec!["/resolved/dir"]);
260        assert!(!result.is_multi);
261    }
262
263    #[test]
264    fn empty_paths_array_falls_back() {
265        let mut args = Map::new();
266        args.insert("paths".to_string(), json!([]));
267        let mut ctx = test_ctx();
268        ctx.resolved_paths
269            .insert("path".to_string(), "/fallback".to_string());
270        let result = resolve_tool_paths(&args, &ctx).expect("empty paths → fallback");
271        assert_eq!(result.roots, vec!["/fallback"]);
272        assert!(!result.is_multi);
273    }
274
275    // #401: an explicit `path` the dispatcher could not resolve (out of jail,
276    // secret-screened, non-existent) must surface the error — NOT silently
277    // fall back to the project root and return an unrelated tree.
278    #[test]
279    fn explicit_unresolvable_path_errors_instead_of_root_fallback() {
280        let mut args = Map::new();
281        args.insert(
282            "path".to_string(),
283            json!("/home/jules/.claude/skills/mpm-config"),
284        );
285        let mut ctx = test_ctx();
286        // Dispatcher could not resolve it → recorded in path_errors, absent
287        // from resolved_paths (exactly what the daemon does for out-of-jail).
288        ctx.path_errors.insert(
289            "path".to_string(),
290            "path escapes project root: /home/jules/.claude/skills/mpm-config \
291             (root: /test/project)"
292                .to_string(),
293        );
294        let err = resolve_tool_paths(&args, &ctx)
295            .expect_err("out-of-jail explicit path must be an error");
296        assert!(
297            err.contains("escapes project root"),
298            "error must explain the path is out of scope: {err}"
299        );
300    }
301
302    // #401: an explicit `paths` array where nothing resolves must error too.
303    //
304    // Uses *real* directories so the PathJail decision is deterministic across
305    // platforms. Canonicalizing non-existent paths is OS-dependent — the first
306    // version of this test fed bogus absolute paths against a non-existent root
307    // and passed on macOS while letting them through on Linux CI.
308    //
309    // Asserts a jail-enforcement invariant, so it only holds when the jail is
310    // compiled in. Under `--features no-jail` (pulled in by `--all-features`) the
311    // jail is intentionally disabled and out-of-root paths resolve, so skip it.
312    #[cfg(not(feature = "no-jail"))]
313    #[test]
314    fn explicit_unresolvable_paths_array_errors() {
315        let base = tempfile::tempdir().unwrap();
316        let root = base.path().join("project");
317        let outside = base.path().join("outside");
318        std::fs::create_dir_all(&root).unwrap();
319        std::fs::create_dir_all(&outside).unwrap();
320
321        let mut ctx = test_ctx();
322        ctx.project_root = root.to_string_lossy().into_owned();
323
324        let mut args = Map::new();
325        args.insert(
326            "paths".to_string(),
327            json!([outside.to_string_lossy().into_owned()]),
328        );
329        let err = resolve_tool_paths(&args, &ctx)
330            .expect_err("a path outside the project root must be an error");
331        assert!(
332            err.contains("none of the requested paths"),
333            "error must report the unresolved paths: {err}"
334        );
335    }
336}