Skip to main content

lean_ctx/tools/
startup.rs

1use super::server::LeanCtxServer;
2
3#[derive(Clone, Debug, Default)]
4pub(super) struct StartupContext {
5    pub(super) project_root: Option<String>,
6    pub(super) shell_cwd: Option<String>,
7}
8
9/// Creates a new `LeanCtxServer` with default configuration.
10pub fn create_server() -> LeanCtxServer {
11    LeanCtxServer::new()
12}
13
14pub(super) fn has_project_marker(dir: &std::path::Path) -> bool {
15    crate::core::pathutil::has_project_marker(dir)
16}
17
18pub(crate) fn is_suspicious_root(dir: &std::path::Path) -> bool {
19    crate::core::pathutil::is_broad_or_unsafe_root(dir)
20        || crate::core::pathutil::is_agent_config_dir(dir)
21}
22
23pub(super) fn canonicalize_path(path: &std::path::Path) -> String {
24    crate::core::pathutil::safe_canonicalize_or_self(path)
25        .to_string_lossy()
26        .to_string()
27}
28
29pub(super) fn detect_startup_context(
30    explicit_project_root: Option<&str>,
31    startup_cwd: Option<&std::path::Path>,
32) -> StartupContext {
33    let shell_cwd = startup_cwd.map(canonicalize_path);
34    let project_root = explicit_project_root
35        .map(|root| canonicalize_path(std::path::Path::new(root)))
36        .or_else(|| {
37            startup_cwd
38                .and_then(maybe_derive_project_root_from_absolute)
39                .map(|p| canonicalize_path(&p))
40        });
41
42    let shell_cwd = match (shell_cwd, project_root.as_ref()) {
43        (Some(cwd), Some(root))
44            if std::path::Path::new(&cwd).starts_with(std::path::Path::new(root)) =>
45        {
46            Some(cwd)
47        }
48        (_, Some(root)) => Some(root.clone()),
49        (cwd, None) => cwd,
50    };
51
52    StartupContext {
53        project_root,
54        shell_cwd,
55    }
56}
57
58pub(super) fn maybe_derive_project_root_from_absolute(
59    abs: &std::path::Path,
60) -> Option<std::path::PathBuf> {
61    let mut cur = if abs.is_dir() {
62        abs.to_path_buf()
63    } else {
64        abs.parent()?.to_path_buf()
65    };
66    // #1437: keep walking up and return the OUTERMOST project marker, matching
67    // `detect_project_root`. The old "first match = return" behaviour caused
68    // monorepo sub-packages (own `package.json`, no `.git`) to become the
69    // derived root, which then poisoned the daemon session for all later queries.
70    let mut best: Option<std::path::PathBuf> = None;
71    loop {
72        if has_project_marker(&cur) {
73            best = Some(crate::core::pathutil::safe_canonicalize_or_self(&cur));
74        }
75        if !cur.pop() {
76            break;
77        }
78    }
79    best
80}
81
82/// Incremental background consolidation: import only session items newer than the
83/// per-session watermark, advancing it after a successful save. Delegates to the
84/// canonical engine ([`crate::tools::ctx_knowledge::consolidate_project_knowledge_with`]),
85/// which loads the session for the *requested* project root (cwd bug #2362), runs
86/// under the shared knowledge lock (#326) and reclaims history losslessly (#995).
87pub(crate) fn auto_consolidate_knowledge(project_root: &str) {
88    let _ = crate::tools::ctx_knowledge::consolidate_project_knowledge_with(
89        project_root,
90        &crate::core::consolidation_engine::ConsolidateOptions::incremental_auto(),
91    );
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    #[test]
99    fn derive_root_promotes_to_outermost_marker_in_monorepo() {
100        // #1437: in a monorepo where sub-packages carry their own package.json,
101        // the derived root must be the outermost marker (repo root with .git),
102        // not the nearest sub-package marker.
103        let tmp = tempfile::tempdir().unwrap();
104        let repo = tmp.path().join("repo");
105        let sub = repo.join("modules").join("payroll");
106        std::fs::create_dir_all(&sub).unwrap();
107        // Repo root has .git + package.json
108        std::fs::create_dir(repo.join(".git")).unwrap();
109        std::fs::write(repo.join("package.json"), "{}").unwrap();
110        // Sub-package has only package.json (no .git)
111        std::fs::write(sub.join("package.json"), "{}").unwrap();
112
113        let result = maybe_derive_project_root_from_absolute(&sub);
114        assert!(result.is_some(), "should find a root");
115        let root = result.unwrap();
116        let canonical_repo = crate::core::pathutil::safe_canonicalize_or_self(&repo);
117        assert_eq!(
118            root, canonical_repo,
119            "should return repo root, not sub-package"
120        );
121    }
122
123    #[test]
124    fn derive_root_returns_nearest_when_no_outer_marker() {
125        // When there is no outer marker (standalone sub-package), the nearest
126        // marker is the correct root.
127        let tmp = tempfile::tempdir().unwrap();
128        let pkg = tmp.path().join("standalone");
129        std::fs::create_dir_all(&pkg).unwrap();
130        std::fs::write(pkg.join("package.json"), "{}").unwrap();
131
132        let result = maybe_derive_project_root_from_absolute(&pkg);
133        assert!(result.is_some());
134        let root = result.unwrap();
135        let canonical = crate::core::pathutil::safe_canonicalize_or_self(&pkg);
136        assert_eq!(root, canonical);
137    }
138}