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    /// Set when a too-broad root was narrowed to the session project; the
11    /// tool puts it in front of its output so the agent sees the scope.
12    pub note: Option<String>,
13}
14
15impl ResolvedPaths {
16    fn single(root: String) -> Self {
17        Self {
18            roots: vec![root],
19            is_multi: false,
20            note: None,
21        }
22    }
23
24    /// Prefixes the scope note, if any, to a tool's output text.
25    pub fn annotate(
26        &self,
27        mut output: crate::server::tool_trait::ToolOutput,
28    ) -> crate::server::tool_trait::ToolOutput {
29        if let Some(note) = &self.note {
30            output.text = format!("{note}\n{}", output.text);
31        }
32        output
33    }
34}
35
36/// Walks over a broad root (`~`, `/`, `~/Documents`) never run: narrow them to
37/// the session project when it lies inside, otherwise refuse with guidance
38/// the agent can act on. `requested` is what the caller asked for (before
39/// jail resolution), `root` what it resolved to, if anything.
40fn guard_broad_root(
41    requested: &str,
42    root: Option<String>,
43    ctx: &ToolContext,
44) -> Option<Result<ResolvedPaths, String>> {
45    let probe = root.as_deref().unwrap_or(requested);
46    if let Some((project, note)) =
47        crate::tools::walk_guard::narrow_to_project(probe, &ctx.project_root)
48    {
49        return Some(Ok(ResolvedPaths {
50            note: Some(note),
51            ..ResolvedPaths::single(project)
52        }));
53    }
54    let root = root?;
55    if crate::tools::walk_guard::deny_unsafe_walk_root(&root).is_some() {
56        return Some(Err(crate::tools::walk_guard::broad_root_guidance(
57            requested,
58            &ctx.project_root,
59        )));
60    }
61    None
62}
63
64/// Resolve tool paths with multi-root support.
65///
66/// Priority:
67/// 0. `repo` argument (multi-repo alias → specific root)
68/// 1. `paths` array argument (explicit multi-root)
69/// 2. `path` string argument (single root, pre-resolved by dispatch)
70/// 3. Session `extra_roots` (default multi-root from config/MCP)
71/// 4. Resolve the active project root (never the process working directory)
72///
73/// Returns `Err` when an **explicit** `path`/`paths` argument was supplied but
74/// could not be resolved (outside the project root, secret-screened, or
75/// non-existent). Silently falling back to the project root in that case made
76/// `ctx_tree path=/outside/repo` return the whole project tree (#401).
77pub fn resolve_tool_paths(
78    args: &Map<String, Value>,
79    ctx: &ToolContext,
80) -> Result<ResolvedPaths, String> {
81    if let Some(repo) = get_str(args, "repo")
82        && let Some(root) = crate::core::multi_repo::resolve_repo_root(&repo)
83    {
84        return Ok(ResolvedPaths::single(root));
85    }
86
87    if let Some(paths) = get_str_array(args, "paths")
88        && !paths.is_empty()
89    {
90        let resolved = resolve_paths_sync(ctx, &paths);
91        if !resolved.is_empty() {
92            return Ok(ResolvedPaths {
93                is_multi: resolved.len() > 1,
94                roots: resolved,
95                note: None,
96            });
97        }
98        // The caller explicitly listed paths but none resolved — surface
99        // the failure instead of scanning the project root (#401).
100        return Err(format!(
101            "none of the requested paths could be resolved — they may not exist or are \
102                 outside the project root: {}",
103            paths.join(", ")
104        ));
105    }
106
107    // #846: `file_path` is an alias for `path` in ctx_search — agents
108    // (especially Claude Code) send it expecting file-level scoping.
109    // Without this fallback the parameter is silently ignored and the
110    // search runs on the project root.
111    for key in &["path", "file_path"] {
112        let requested = get_str(args, key).unwrap_or_default();
113        if let Some(p) = ctx.resolved_path(key) {
114            if let Some(guarded) = guard_broad_root(&requested, Some(p.to_string()), ctx) {
115                return guarded;
116            }
117            return Ok(ResolvedPaths::single(p.to_string()));
118        }
119        // An explicit path the dispatcher could not resolve lands in
120        // `path_errors`. Do NOT fall back to the project root — return the
121        // resolution error so the agent learns the path is out of scope
122        // rather than silently receiving an unrelated tree (#401). The one
123        // exception is an ancestor of the session project (`~`, `/`): the
124        // agent asked for a superset, so the project is the right answer.
125        if let Some(detail) = ctx.path_error(key) {
126            if !requested.is_empty()
127                && let Some(Ok(narrowed)) = guard_broad_root(&requested, None, ctx)
128            {
129                return Ok(narrowed);
130            }
131            return Err(detail.to_string());
132        }
133    }
134
135    // Validate before extra roots can return a default scope. An empty or
136    // relative primary must never be interpreted against the process CWD.
137    if ctx.project_root.trim().is_empty() {
138        return Err("active project root is required when no path is supplied".to_string());
139    }
140    if !std::path::Path::new(&ctx.project_root).is_absolute() {
141        return Err("active project root must be absolute when no path is supplied".to_string());
142    }
143
144    if let Some(session_lock) = ctx.session.as_ref() {
145        let (extra, jail_root) = {
146            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
147            let guard = loop {
148                if let Ok(g) = session_lock.clone().try_read_owned() {
149                    break Some(g);
150                }
151                if std::time::Instant::now() >= deadline {
152                    break None;
153                }
154                std::thread::sleep(std::time::Duration::from_millis(25));
155            };
156            match guard {
157                Some(session) => {
158                    let root = session
159                        .project_root
160                        .clone()
161                        .unwrap_or_else(|| ".".to_string());
162                    (session.extra_roots.clone(), root)
163                }
164                None => (Vec::new(), ".".to_string()),
165            }
166        };
167        if !extra.is_empty() {
168            let jail = std::path::Path::new(&jail_root);
169            let mut roots = vec![ctx.project_root.clone()];
170            for r in &extra {
171                let p = std::path::Path::new(r);
172                if !p.is_dir() {
173                    continue;
174                }
175                match crate::core::pathjail::jail_path(p, jail) {
176                    Ok(_) => roots.push(r.clone()),
177                    Err(e) => tracing::warn!("extra_root rejected by PathJail: {e}"),
178                }
179            }
180            if roots.len() > 1 {
181                return Ok(ResolvedPaths {
182                    is_multi: true,
183                    roots,
184                    note: None,
185                });
186            }
187        }
188    }
189
190    let root = ctx.resolve_path_sync(&ctx.project_root)?;
191    if let Some(guarded) = guard_broad_root(&ctx.project_root, Some(root.clone()), ctx) {
192        return guarded;
193    }
194    Ok(ResolvedPaths::single(root))
195}
196
197fn resolve_paths_sync(ctx: &ToolContext, raw: &[String]) -> Vec<String> {
198    let mut out = Vec::with_capacity(raw.len());
199    for p in raw {
200        match ctx.resolve_path_sync(p) {
201            Ok(resolved) => out.push(resolved),
202            Err(e) => {
203                tracing::warn!("multi-path resolve failed for {p}: {e}");
204            }
205        }
206    }
207    out
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use serde_json::json;
214
215    fn test_ctx() -> ToolContext {
216        ToolContext {
217            project_root: "/test/project".to_string(),
218            extra_roots: Vec::new(),
219            minimal: false,
220            resolved_paths: std::collections::HashMap::new(),
221            crp_mode: crate::tools::CrpMode::Off,
222            cache: None,
223            session: None,
224            tool_calls: None,
225            agent_id: None,
226            workflow: None,
227            ledger: None,
228            client_name: None,
229            client_role: None,
230            shell_access: None,
231            pipeline_stats: None,
232            call_count: None,
233            autonomy: None,
234            pressure_snapshot: None,
235            path_errors: std::collections::HashMap::new(),
236            bm25_cache: None,
237            progress_sender: None,
238            cancel: None,
239        }
240    }
241
242    #[test]
243    fn fallback_uses_context_project_not_process_cwd() {
244        let args = Map::new();
245        let project = tempfile::tempdir().unwrap();
246        let root = project.path().canonicalize().unwrap();
247        assert_ne!(
248            root,
249            std::env::current_dir().unwrap().canonicalize().unwrap()
250        );
251        let mut ctx = test_ctx();
252        ctx.project_root = root.to_string_lossy().into_owned();
253        let result = resolve_tool_paths(&args, &ctx).expect("no explicit path → default");
254        assert_eq!(result.roots.len(), 1);
255        assert_eq!(
256            std::fs::canonicalize(&result.roots[0]).expect("resolved project root"),
257            std::fs::canonicalize(root).expect("canonical context project root"),
258            "fallback must resolve to the context project, independent of path spelling"
259        );
260        assert!(!result.is_multi);
261    }
262
263    #[test]
264    fn missing_context_root_does_not_search_process_cwd() {
265        let mut ctx = test_ctx();
266        ctx.project_root.clear();
267        let error = resolve_tool_paths(&Map::new(), &ctx).unwrap_err();
268        assert!(error.contains("active project root is required"));
269    }
270
271    #[test]
272    fn relative_context_root_does_not_search_process_cwd() {
273        for root in [".", "relative-project"] {
274            let mut ctx = test_ctx();
275            ctx.project_root = root.to_string();
276            assert!(
277                resolve_tool_paths(&Map::new(), &ctx).is_err(),
278                "root: {root}"
279            );
280        }
281    }
282
283    #[test]
284    fn extra_roots_cannot_bypass_invalid_primary_root() {
285        let _data = crate::core::data_dir::isolated_data_dir();
286        let extra = tempfile::tempdir().unwrap();
287        let extra_root = extra
288            .path()
289            .canonicalize()
290            .unwrap()
291            .to_string_lossy()
292            .into_owned();
293        let mut session = crate::core::session::SessionState::new();
294        session.project_root = Some(extra_root.clone());
295        session.extra_roots = vec![extra_root.clone()];
296        let mut ctx = test_ctx();
297        ctx.session = Some(std::sync::Arc::new(tokio::sync::RwLock::new(session)));
298        for root in ["", ".", "relative-project"] {
299            ctx.project_root = root.to_string();
300            assert!(
301                resolve_tool_paths(&Map::new(), &ctx).is_err(),
302                "root: {root}"
303            );
304        }
305        // A valid absolute primary still permits the existing multi-root path.
306        ctx.project_root = extra_root;
307        let resolved = resolve_tool_paths(&Map::new(), &ctx).unwrap();
308        assert!(resolved.is_multi);
309        assert!(resolved.roots.iter().all(|root| root == &ctx.project_root));
310    }
311
312    // An agent that asks for `/` or `~` wants a superset of its project:
313    // answer with the project and say so, instead of a refusal it repeats.
314    #[test]
315    fn broad_explicit_path_narrows_to_the_session_project() {
316        let project = tempfile::tempdir().unwrap();
317        std::fs::create_dir_all(project.path().join(".git")).unwrap();
318        let root = crate::core::pathutil::safe_canonicalize(project.path()).unwrap();
319        // The project's own filesystem root: `/`, or `C:\` on Windows.
320        let fs_root = root
321            .ancestors()
322            .last()
323            .unwrap()
324            .to_string_lossy()
325            .into_owned();
326        let mut ctx = test_ctx();
327        ctx.project_root = root.to_string_lossy().into_owned();
328        ctx.path_errors.insert(
329            "path".to_string(),
330            format!("path escapes project root: {fs_root} (root: …)"),
331        );
332        let mut args = Map::new();
333        args.insert("path".to_string(), json!(fs_root));
334        let resolved = resolve_tool_paths(&args, &ctx).expect("narrowed, not refused");
335        assert_eq!(std::path::Path::new(&resolved.roots[0]), root);
336        assert!(
337            resolved
338                .note
339                .as_deref()
340                .is_some_and(|n| n.contains("too broad"))
341        );
342    }
343
344    #[test]
345    fn broad_path_without_a_project_explains_how_to_bind_one() {
346        let mut ctx = test_ctx();
347        ctx.project_root.clear();
348        ctx.resolved_paths
349            .insert("path".to_string(), "/".to_string());
350        let mut args = Map::new();
351        args.insert("path".to_string(), json!("/"));
352        let err = resolve_tool_paths(&args, &ctx).expect_err("nothing to narrow to");
353        assert!(err.contains("not bound this session"), "{err}");
354    }
355
356    #[test]
357    fn uses_resolved_path_when_present() {
358        let args = Map::new();
359        let mut ctx = test_ctx();
360        ctx.resolved_paths
361            .insert("path".to_string(), "/resolved/dir".to_string());
362        let result = resolve_tool_paths(&args, &ctx).expect("resolved path");
363        assert_eq!(result.roots, vec!["/resolved/dir"]);
364        assert!(!result.is_multi);
365    }
366
367    #[test]
368    fn empty_paths_array_falls_back() {
369        let mut args = Map::new();
370        args.insert("paths".to_string(), json!([]));
371        let mut ctx = test_ctx();
372        ctx.resolved_paths
373            .insert("path".to_string(), "/fallback".to_string());
374        let result = resolve_tool_paths(&args, &ctx).expect("empty paths → fallback");
375        assert_eq!(result.roots, vec!["/fallback"]);
376        assert!(!result.is_multi);
377    }
378
379    // #401: an explicit `path` the dispatcher could not resolve (out of jail,
380    // secret-screened, non-existent) must surface the error — NOT silently
381    // fall back to the project root and return an unrelated tree.
382    #[test]
383    fn explicit_unresolvable_path_errors_instead_of_root_fallback() {
384        let mut args = Map::new();
385        args.insert(
386            "path".to_string(),
387            json!("/home/jules/.claude/skills/mpm-config"),
388        );
389        let mut ctx = test_ctx();
390        // Dispatcher could not resolve it → recorded in path_errors, absent
391        // from resolved_paths (exactly what the daemon does for out-of-jail).
392        ctx.path_errors.insert(
393            "path".to_string(),
394            "path escapes project root: /home/jules/.claude/skills/mpm-config \
395             (root: /test/project)"
396                .to_string(),
397        );
398        let err = resolve_tool_paths(&args, &ctx)
399            .expect_err("out-of-jail explicit path must be an error");
400        assert!(
401            err.contains("escapes project root"),
402            "error must explain the path is out of scope: {err}"
403        );
404    }
405
406    // #401: an explicit `paths` array where nothing resolves must error too.
407    //
408    // Uses *real* directories so the PathJail decision is deterministic across
409    // platforms. Canonicalizing non-existent paths is OS-dependent — the first
410    // version of this test fed bogus absolute paths against a non-existent root
411    // and passed on macOS while letting them through on Linux CI.
412    //
413    // Asserts a jail-enforcement invariant, so it only holds when the jail is
414    // compiled in. Under `--features no-jail` (pulled in by `--all-features`) the
415    // jail is intentionally disabled and out-of-root paths resolve, so skip it.
416    #[cfg(not(feature = "no-jail"))]
417    #[test]
418    fn explicit_unresolvable_paths_array_errors() {
419        let base = tempfile::tempdir().unwrap();
420        let root = base.path().join("project");
421        let outside = base.path().join("outside");
422        std::fs::create_dir_all(&root).unwrap();
423        std::fs::create_dir_all(&outside).unwrap();
424
425        let mut ctx = test_ctx();
426        ctx.project_root = root.to_string_lossy().into_owned();
427
428        let mut args = Map::new();
429        args.insert(
430            "paths".to_string(),
431            json!([outside.to_string_lossy().into_owned()]),
432        );
433        let err = resolve_tool_paths(&args, &ctx)
434            .expect_err("a path outside the project root must be an error");
435        assert!(
436            err.contains("none of the requested paths"),
437            "error must report the unresolved paths: {err}"
438        );
439    }
440}