Skip to main content

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