Skip to main content

lean_ctx_server/tools/
startup.rs

1// SPDX-License-Identifier: Apache-2.0
2use super::server::LeanCtxServer;
3
4#[derive(Clone, Debug, Default)]
5pub(super) struct StartupContext {
6    pub(super) project_root: Option<String>,
7    pub(super) shell_cwd: Option<String>,
8}
9
10/// Creates a new `LeanCtxServer` with default configuration.
11pub fn create_server() -> LeanCtxServer {
12    LeanCtxServer::new()
13}
14
15pub(super) fn has_project_marker(dir: &std::path::Path) -> bool {
16    lean_ctx::core::pathutil::has_project_marker(dir)
17}
18
19pub(crate) use lean_ctx::core::pathutil::is_suspicious_root;
20
21pub(super) fn canonicalize_path(path: &std::path::Path) -> String {
22    lean_ctx::core::pathutil::safe_canonicalize_or_self(path)
23        .to_string_lossy()
24        .to_string()
25}
26
27pub(super) fn detect_startup_context(
28    explicit_project_root: Option<&str>,
29    startup_cwd: Option<&std::path::Path>,
30) -> StartupContext {
31    let shell_cwd = startup_cwd.map(canonicalize_path);
32    let project_root = explicit_project_root
33        .map(|root| canonicalize_path(std::path::Path::new(root)))
34        .or_else(|| {
35            startup_cwd
36                .and_then(maybe_derive_project_root_from_absolute)
37                .map(|p| canonicalize_path(&p))
38        });
39
40    let shell_cwd = match (shell_cwd, project_root.as_ref()) {
41        (Some(cwd), Some(root))
42            if std::path::Path::new(&cwd).starts_with(std::path::Path::new(root)) =>
43        {
44            Some(cwd)
45        }
46        (_, Some(root)) => Some(root.clone()),
47        (cwd, None) => cwd,
48    };
49
50    StartupContext {
51        project_root,
52        shell_cwd,
53    }
54}
55
56/// The project an absolute path belongs to: the same rule as the CLI's
57/// (`project_root_of`, #1315) — nearest git root, else the outermost project
58/// marker (#1437), never a broad root, canonical.
59pub(super) fn maybe_derive_project_root_from_absolute(
60    abs: &std::path::Path,
61) -> Option<std::path::PathBuf> {
62    lean_ctx::core::command_root::project_root_of(abs)
63}
64
65/// Incremental background consolidation: import only session items newer than the
66/// per-session watermark, advancing it after a successful save. Delegates to the
67/// canonical engine ([`crate::tools::ctx_knowledge::consolidate_project_knowledge_with`]),
68/// which loads the session for the *requested* project root (cwd bug #2362), runs
69/// under the shared knowledge lock (#326) and reclaims history losslessly (#995).
70pub(crate) fn auto_consolidate_knowledge(project_root: &str) {
71    let _ = crate::tools::ctx_knowledge::consolidate_project_knowledge_with(
72        project_root,
73        &lean_ctx::core::consolidation_engine::ConsolidateOptions::incremental_auto(),
74    );
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    #[test]
82    fn derive_root_promotes_to_outermost_marker_in_monorepo() {
83        // #1437: in a monorepo where sub-packages carry their own package.json,
84        // the derived root must be the outermost marker (repo root with .git),
85        // not the nearest sub-package marker.
86        let tmp = tempfile::tempdir().unwrap();
87        let repo = tmp.path().join("repo");
88        let sub = repo.join("modules").join("payroll");
89        std::fs::create_dir_all(&sub).unwrap();
90        // Repo root has .git + package.json
91        std::fs::create_dir(repo.join(".git")).unwrap();
92        std::fs::write(repo.join("package.json"), "{}").unwrap();
93        // Sub-package has only package.json (no .git)
94        std::fs::write(sub.join("package.json"), "{}").unwrap();
95
96        let result = maybe_derive_project_root_from_absolute(&sub);
97        assert!(result.is_some(), "should find a root");
98        let root = result.unwrap();
99        let canonical_repo = lean_ctx::core::pathutil::safe_canonicalize_or_self(&repo);
100        assert_eq!(
101            root, canonical_repo,
102            "should return repo root, not sub-package"
103        );
104    }
105
106    #[test]
107    fn derive_root_returns_nearest_when_no_outer_marker() {
108        // When there is no outer marker (standalone sub-package), the nearest
109        // marker is the correct root.
110        let tmp = tempfile::tempdir().unwrap();
111        let pkg = tmp.path().join("standalone");
112        std::fs::create_dir_all(&pkg).unwrap();
113        std::fs::write(pkg.join("package.json"), "{}").unwrap();
114
115        let result = maybe_derive_project_root_from_absolute(&pkg);
116        assert!(result.is_some());
117        let root = result.unwrap();
118        let canonical = lean_ctx::core::pathutil::safe_canonicalize_or_self(&pkg);
119        assert_eq!(root, canonical);
120    }
121
122    /// #1315 (rc3-49): the CLI and the MCP server name the same project from
123    /// the same working directory — a marker without `.git`, a symlinked
124    /// checkout, a monorepo sub-package — so `lean-ctx tasks` and
125    /// `ctx_tasks` open one local task store.
126    #[test]
127    fn cli_and_mcp_open_the_same_task_store() {
128        let _data = lean_ctx::core::data_dir::isolated_data_dir();
129        let _pin = lean_ctx::test_env::VarGuard::set("LEAN_CTX_PROJECT_ROOT", "");
130        let tmp = tempfile::tempdir().unwrap();
131        let marker_only = tmp.path().join("marker-only");
132        std::fs::create_dir_all(marker_only.join("src")).unwrap();
133        std::fs::write(marker_only.join("Cargo.toml"), "[package]\n").unwrap();
134        let repo = tmp.path().join("repo");
135        let package = repo.join("packages").join("ui");
136        std::fs::create_dir_all(&package).unwrap();
137        std::fs::create_dir(repo.join(".git")).unwrap();
138        std::fs::write(package.join("package.json"), "{}").unwrap();
139        // Only the unix symlink case below pushes; Windows builds it as is.
140        #[cfg_attr(not(unix), allow(unused_mut))]
141        let mut cwds = vec![marker_only.join("src"), package];
142        #[cfg(unix)]
143        {
144            let link = tmp.path().join("link");
145            std::os::unix::fs::symlink(&repo, &link).unwrap();
146            cwds.push(link.join("packages"));
147        }
148
149        for cwd in cwds {
150            let cli = lean_ctx::core::command_root::detect_project_root_in(&[], Some(&cwd));
151            let mcp = detect_startup_context(None, Some(&cwd))
152                .project_root
153                .expect("the MCP server finds the project");
154            assert_eq!(cli, mcp, "one project root for {}", cwd.display());
155            assert_eq!(
156                lean_ctx_cloud::tasks::local::store_dir(std::path::Path::new(&cli)).unwrap(),
157                lean_ctx_cloud::tasks::local::store_dir(std::path::Path::new(&mcp)).unwrap(),
158            );
159        }
160    }
161}