Skip to main content

lean_ctx/server/
multi_path.rs

1use serde_json::{Map, Value};
2
3use crate::server::tool_trait::{ToolContext, get_str, get_str_array};
4
5#[derive(Debug)]
6pub struct ResolvedPaths {
7    pub roots: Vec<String>,
8    pub is_multi: bool,
9}
10
11/// Resolve tool paths with multi-root support.
12///
13/// Priority:
14/// 0. `repo` argument (multi-repo alias → specific root)
15/// 1. `paths` array argument (explicit multi-root)
16/// 2. `path` string argument (single root, pre-resolved by dispatch)
17/// 3. Session `extra_roots` (default multi-root from config/MCP)
18/// 4. Fallback to `"."` (project root)
19///
20/// Returns `Err` when an **explicit** `path`/`paths` argument was supplied but
21/// could not be resolved (outside the project root, secret-screened, or
22/// non-existent). Silently falling back to the project root in that case made
23/// `ctx_tree path=/outside/repo` return the whole project tree (#401).
24pub fn resolve_tool_paths(
25    args: &Map<String, Value>,
26    ctx: &ToolContext,
27) -> Result<ResolvedPaths, String> {
28    if let Some(repo) = get_str(args, "repo")
29        && let Some(root) = crate::core::multi_repo::resolve_repo_root(&repo)
30    {
31        return Ok(ResolvedPaths {
32            roots: vec![root],
33            is_multi: false,
34        });
35    }
36
37    if let Some(paths) = get_str_array(args, "paths")
38        && !paths.is_empty()
39    {
40        let resolved = resolve_paths_sync(ctx, &paths);
41        if !resolved.is_empty() {
42            return Ok(ResolvedPaths {
43                is_multi: resolved.len() > 1,
44                roots: resolved,
45            });
46        }
47        // The caller explicitly listed paths but none resolved — surface
48        // the failure instead of scanning the project root (#401).
49        return Err(format!(
50            "none of the requested paths could be resolved — they may not exist or are \
51                 outside the project root: {}",
52            paths.join(", ")
53        ));
54    }
55
56    // #846: `file_path` is an alias for `path` in ctx_search — agents
57    // (especially Claude Code) send it expecting file-level scoping.
58    // Without this fallback the parameter is silently ignored and the
59    // search runs on the project root.
60    for key in &["path", "file_path"] {
61        if let Some(p) = ctx.resolved_path(key) {
62            return Ok(ResolvedPaths {
63                roots: vec![p.to_string()],
64                is_multi: false,
65            });
66        }
67        // An explicit path the dispatcher could not resolve lands in
68        // `path_errors`. Do NOT fall back to the project root — return the
69        // resolution error so the agent learns the path is out of scope
70        // rather than silently receiving an unrelated tree (#401).
71        if let Some(detail) = ctx.path_error(key) {
72            return Err(detail.to_string());
73        }
74    }
75
76    if let Some(session_lock) = ctx.session.as_ref() {
77        let (extra, jail_root) = tokio::task::block_in_place(|| {
78            let rt = tokio::runtime::Handle::current();
79            rt.block_on(async {
80                let session = session_lock.read().await;
81                let root = session
82                    .project_root
83                    .clone()
84                    .unwrap_or_else(|| ".".to_string());
85                (session.extra_roots.clone(), root)
86            })
87        });
88        if !extra.is_empty() {
89            let jail = std::path::Path::new(&jail_root);
90            let mut roots = vec![ctx.project_root.clone()];
91            for r in &extra {
92                let p = std::path::Path::new(r);
93                if !p.is_dir() {
94                    continue;
95                }
96                match crate::core::pathjail::jail_path(p, jail) {
97                    Ok(_) => roots.push(r.clone()),
98                    Err(e) => tracing::warn!("extra_root rejected by PathJail: {e}"),
99                }
100            }
101            if roots.len() > 1 {
102                return Ok(ResolvedPaths {
103                    is_multi: true,
104                    roots,
105                });
106            }
107        }
108    }
109
110    Ok(ResolvedPaths {
111        roots: vec![".".to_string()],
112        is_multi: false,
113    })
114}
115
116fn resolve_paths_sync(ctx: &ToolContext, raw: &[String]) -> Vec<String> {
117    let mut out = Vec::with_capacity(raw.len());
118    for p in raw {
119        match ctx.resolve_path_sync(p) {
120            Ok(resolved) => out.push(resolved),
121            Err(e) => {
122                tracing::warn!("multi-path resolve failed for {p}: {e}");
123            }
124        }
125    }
126    out
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132    use serde_json::json;
133
134    fn test_ctx() -> ToolContext {
135        ToolContext {
136            project_root: "/test/project".to_string(),
137            extra_roots: Vec::new(),
138            minimal: false,
139            resolved_paths: std::collections::HashMap::new(),
140            crp_mode: crate::tools::CrpMode::Off,
141            cache: None,
142            session: None,
143            tool_calls: None,
144            agent_id: None,
145            workflow: None,
146            ledger: None,
147            client_name: None,
148            client_role: None,
149            shell_access: None,
150            pipeline_stats: None,
151            call_count: None,
152            autonomy: None,
153            pressure_snapshot: None,
154            path_errors: std::collections::HashMap::new(),
155            bm25_cache: None,
156            progress_sender: None,
157        }
158    }
159
160    #[test]
161    fn fallback_to_dot_when_nothing_set() {
162        let args = Map::new();
163        let ctx = test_ctx();
164        let result = resolve_tool_paths(&args, &ctx).expect("no explicit path → default");
165        assert_eq!(result.roots, vec!["."]);
166        assert!(!result.is_multi);
167    }
168
169    #[test]
170    fn uses_resolved_path_when_present() {
171        let args = Map::new();
172        let mut ctx = test_ctx();
173        ctx.resolved_paths
174            .insert("path".to_string(), "/resolved/dir".to_string());
175        let result = resolve_tool_paths(&args, &ctx).expect("resolved path");
176        assert_eq!(result.roots, vec!["/resolved/dir"]);
177        assert!(!result.is_multi);
178    }
179
180    #[test]
181    fn empty_paths_array_falls_back() {
182        let mut args = Map::new();
183        args.insert("paths".to_string(), json!([]));
184        let mut ctx = test_ctx();
185        ctx.resolved_paths
186            .insert("path".to_string(), "/fallback".to_string());
187        let result = resolve_tool_paths(&args, &ctx).expect("empty paths → fallback");
188        assert_eq!(result.roots, vec!["/fallback"]);
189        assert!(!result.is_multi);
190    }
191
192    // #401: an explicit `path` the dispatcher could not resolve (out of jail,
193    // secret-screened, non-existent) must surface the error — NOT silently
194    // fall back to the project root and return an unrelated tree.
195    #[test]
196    fn explicit_unresolvable_path_errors_instead_of_root_fallback() {
197        let mut args = Map::new();
198        args.insert(
199            "path".to_string(),
200            json!("/home/jules/.claude/skills/mpm-config"),
201        );
202        let mut ctx = test_ctx();
203        // Dispatcher could not resolve it → recorded in path_errors, absent
204        // from resolved_paths (exactly what the daemon does for out-of-jail).
205        ctx.path_errors.insert(
206            "path".to_string(),
207            "path escapes project root: /home/jules/.claude/skills/mpm-config \
208             (root: /test/project)"
209                .to_string(),
210        );
211        let err = resolve_tool_paths(&args, &ctx)
212            .expect_err("out-of-jail explicit path must be an error");
213        assert!(
214            err.contains("escapes project root"),
215            "error must explain the path is out of scope: {err}"
216        );
217    }
218
219    // #401: an explicit `paths` array where nothing resolves must error too.
220    //
221    // Uses *real* directories so the PathJail decision is deterministic across
222    // platforms. Canonicalizing non-existent paths is OS-dependent — the first
223    // version of this test fed bogus absolute paths against a non-existent root
224    // and passed on macOS while letting them through on Linux CI.
225    //
226    // Asserts a jail-enforcement invariant, so it only holds when the jail is
227    // compiled in. Under `--features no-jail` (pulled in by `--all-features`) the
228    // jail is intentionally disabled and out-of-root paths resolve, so skip it.
229    #[cfg(not(feature = "no-jail"))]
230    #[test]
231    fn explicit_unresolvable_paths_array_errors() {
232        let base = tempfile::tempdir().unwrap();
233        let root = base.path().join("project");
234        let outside = base.path().join("outside");
235        std::fs::create_dir_all(&root).unwrap();
236        std::fs::create_dir_all(&outside).unwrap();
237
238        let mut ctx = test_ctx();
239        ctx.project_root = root.to_string_lossy().into_owned();
240
241        let mut args = Map::new();
242        args.insert(
243            "paths".to_string(),
244            json!([outside.to_string_lossy().into_owned()]),
245        );
246        let err = resolve_tool_paths(&args, &ctx)
247            .expect_err("a path outside the project root must be an error");
248        assert!(
249            err.contains("none of the requested paths"),
250            "error must report the unresolved paths: {err}"
251        );
252    }
253}