Skip to main content

lean_ctx/core/
command_root.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The project a command-line invocation acts for, and the read boundary a
3//! command-line read enforces against it.
4//!
5//! The root comes from `--root`/`--project-root`, then `LEAN_CTX_PROJECT_ROOT`
6//! (reconciled with the working directory, AP04-G10), then [`project_root_of`]
7//! the working directory. Shared by the CLI commands, the daemon client and the
8//! shell-hook rewriters, so every entry point names the same project; the MCP
9//! server derives its startup root with the same [`project_root_of`] (#1315).
10
11use std::path::Path;
12
13/// The project this process acts for, from `args` and the working directory.
14pub fn detect_project_root(args: &[String]) -> String {
15    detect_project_root_in(args, std::env::current_dir().ok().as_deref())
16}
17
18/// The project a command that writes project-scoped state acts for; `Err`
19/// instead of `~`, `/` or an agent directory (AP04-G10).
20pub fn require_project_root() -> Result<String, String> {
21    require_project_root_in(std::env::current_dir().ok().as_deref())
22}
23
24fn require_project_root_in(cwd: Option<&Path>) -> Result<String, String> {
25    let root = detect_project_root_in(&[], cwd);
26    if crate::core::pathutil::is_broad_or_unsafe_root(Path::new(&root)) {
27        return Err(format!(
28            "{root} is not a project — run inside a project or set LEAN_CTX_PROJECT_ROOT"
29        ));
30    }
31    Ok(root)
32}
33
34/// [`detect_project_root`] for an explicit working directory.
35pub fn detect_project_root_in(args: &[String], cwd: Option<&Path>) -> String {
36    let mut it = args.iter().peekable();
37    while let Some(a) = it.next() {
38        if let Some(v) = a.strip_prefix("--root=")
39            && !v.trim().is_empty()
40        {
41            return normalize_explicit_root(v);
42        }
43        if let Some(v) = a.strip_prefix("--project-root=")
44            && !v.trim().is_empty()
45        {
46            return normalize_explicit_root(v);
47        }
48        if (a == "--root" || a == "--project-root")
49            && let Some(v) = it.peek()
50            && !v.starts_with("--")
51            && !v.trim().is_empty()
52        {
53            return normalize_explicit_root(v);
54        }
55    }
56    let cwd_root = cwd.map(|cwd| {
57        project_root_of(cwd)
58            .unwrap_or_else(|| crate::core::pathutil::safe_canonicalize_or_self(cwd))
59            .to_string_lossy()
60            .into_owned()
61    });
62    if let Ok(root) = std::env::var("LEAN_CTX_PROJECT_ROOT")
63        && !root.trim().is_empty()
64    {
65        return crate::core::mcp_roots::reconcile_pinned_root(
66            normalize_explicit_root(&root),
67            cwd_root,
68        );
69    }
70    cwd_root.unwrap_or_else(|| ".".to_string())
71}
72
73fn normalize_explicit_root(path: &str) -> String {
74    let expanded = expand_home(path.trim());
75    crate::core::index_paths::normalize_project_root(&expanded)
76}
77
78fn expand_home(path: &str) -> String {
79    if path == "~" {
80        return dirs::home_dir().map_or_else(
81            || path.to_string(),
82            |home| home.to_string_lossy().to_string(),
83        );
84    }
85    if let Some(rest) = path.strip_prefix("~/") {
86        return dirs::home_dir().map_or_else(
87            || path.to_string(),
88            |home| home.join(rest).to_string_lossy().to_string(),
89        );
90    }
91    path.to_string()
92}
93
94/// #1315: the project `path` belongs to, for the CLI and the MCP server alike
95/// — the nearest git root at or above it, else the outermost directory with a
96/// project marker (`Cargo.toml`, `package.json`, …; #1437: a monorepo
97/// sub-package is not its own project). A broad root (`~` as a dotfiles
98/// repository, `/`, an agent directory) never counts, and the walk continues
99/// past it. The result is canonical, so every entry point keys the
100/// project-scoped stores (local tasks, agent registry) on the same directory.
101/// `None` when no directory above `path` is a project.
102pub fn project_root_of(path: &Path) -> Option<std::path::PathBuf> {
103    let start = if path.is_dir() { path } else { path.parent()? };
104    let start = crate::core::pathutil::safe_canonicalize_or_self(start);
105    let mut outermost_marker = None;
106    for dir in start.ancestors() {
107        if !crate::core::pathutil::has_project_marker(dir)
108            || crate::core::pathutil::is_broad_or_unsafe_root(dir)
109        {
110            continue;
111        }
112        if dir.join(".git").exists() {
113            return Some(dir.to_path_buf());
114        }
115        outermost_marker = Some(dir.to_path_buf());
116    }
117    outermost_marker
118}
119
120pub fn promote_to_git_root(path: &str) -> String {
121    let mut p = Path::new(path);
122    loop {
123        // A dotfiles repository at `~` is not the project of everything below.
124        if p.join(".git").exists() && !crate::core::pathutil::is_broad_or_unsafe_root(p) {
125            return p.to_string_lossy().to_string();
126        }
127        match p.parent() {
128            Some(parent) => p = parent,
129            None => return path.to_string(),
130        }
131    }
132}
133
134/// #1903: `lean-ctx read` enforces the same boundary as MCP `ctx_read` — the
135/// PathJail (project root + `allow_paths`/`extra_roots`/`read_only_roots` + the
136/// lean-ctx state dir) and the secret-path policy — with the same error text.
137/// A relative path is resolved against the process CWD (a shell user's
138/// intent), never re-anchored at the project root. A broad root (home, `/`,
139/// agent config dir) is refused like `lean-ctx call` does, unless the jail is
140/// disabled (`path_jail = false`), because jailing to `~` would admit every
141/// file the user owns.
142pub fn jail_cli_read_path(raw: &str, project_root: &str) -> Result<String, String> {
143    let candidate = if Path::new(raw).is_relative() {
144        std::env::current_dir().map_or_else(
145            |_| raw.to_string(),
146            |cwd| cwd.join(raw).to_string_lossy().into_owned(),
147        )
148    } else {
149        raw.to_string()
150    };
151    let jail_disabled = crate::core::config::Config::load().path_jail == Some(false);
152    if !jail_disabled && crate::core::pathutil::is_broad_or_unsafe_root(Path::new(project_root)) {
153        return Err(format!(
154            "path escapes project root: {candidate} (root: {project_root}). Access denied: \
155             no project detected — run inside a project, or pass --root <dir> \
156             (or set LEAN_CTX_PROJECT_ROOT)"
157        ));
158    }
159    crate::core::path_resolve::resolve_tool_path(Some(project_root), None, &candidate)
160}
161
162/// Whether `lean-ctx read <raw>` from this process would be refused (#1903).
163/// Shell-hook rewriters keep such reads on the native command instead of
164/// turning a working `cat` into an access-denied error.
165pub fn cli_read_is_refused(raw: &str) -> bool {
166    jail_cli_read_path(raw, &detect_project_root(&[])).is_err()
167}
168
169#[cfg(test)]
170#[path = "command_root_tests.rs"]
171mod tests;