Skip to main content

lean_ctx_ext/core/
workspace_config.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::path::{Path, PathBuf};
3
4use serde::Deserialize;
5
6#[derive(Debug, Default)]
7pub struct LinkedProjects {
8    pub roots: Vec<PathBuf>,
9    pub warnings: Vec<String>,
10    pub source: Option<PathBuf>,
11}
12
13#[derive(Debug, Default, Deserialize)]
14struct WorkspaceConfigFile {
15    #[serde(default, rename = "linkedProjects", alias = "linked_projects")]
16    linked_projects: Vec<String>,
17}
18
19pub fn load_linked_projects(project_root: &Path) -> LinkedProjects {
20    let mut out = LinkedProjects::default();
21
22    let Some((source, content)) = read_config_file(project_root) else {
23        return out;
24    };
25    out.source = Some(source.clone());
26
27    let cfg: WorkspaceConfigFile = match serde_json::from_str(&content) {
28        Ok(v) => v,
29        Err(e) => {
30            out.warnings.push(format!(
31                "workspace config parse failed ({}): {e}",
32                source.display()
33            ));
34            return out;
35        }
36    };
37
38    let root_canon = project_root
39        .canonicalize()
40        .unwrap_or_else(|_| project_root.to_path_buf());
41
42    for raw in cfg.linked_projects {
43        let s = raw.trim();
44        if s.is_empty() {
45            continue;
46        }
47
48        let candidate = if Path::new(s).is_absolute() {
49            PathBuf::from(s)
50        } else {
51            project_root.join(s)
52        };
53
54        let Ok(abs) = candidate.canonicalize() else {
55            out.warnings.push(format!(
56                "linked project missing/unreadable: {}",
57                candidate.to_string_lossy()
58            ));
59            continue;
60        };
61        if abs == root_canon {
62            continue;
63        }
64        if !abs.is_dir() {
65            out.warnings.push(format!(
66                "linked project is not a directory: {}",
67                abs.display()
68            ));
69            continue;
70        }
71
72        match crate::core::io_boundary::jail_and_check_path("linkedProjects", &abs, project_root) {
73            Ok((_, _)) => out.roots.push(abs),
74            Err(e) => out.warnings.push(format!(
75                "linked project rejected by pathjail: {} ({e})",
76                abs.display()
77            )),
78        }
79    }
80
81    out.roots.sort();
82    out.roots.dedup();
83    out
84}
85
86fn read_config_file(project_root: &Path) -> Option<(PathBuf, String)> {
87    let new = project_root.join(".lean-ctx.json");
88    if let Ok(s) = std::fs::read_to_string(&new) {
89        return Some((new, s));
90    }
91    let legacy = project_root.join(".leanctx.json");
92    if let Ok(s) = std::fs::read_to_string(&legacy) {
93        return Some((legacy, s));
94    }
95    let socrati = project_root.join(".socraticode.json");
96    if let Ok(s) = std::fs::read_to_string(&socrati) {
97        return Some((socrati, s));
98    }
99    None
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    fn write_linked_config(root: &Path, linked: &Path) {
107        let cfg = serde_json::json!({
108            "linkedProjects": [linked.to_string_lossy()]
109        })
110        .to_string();
111        std::fs::write(root.join(".lean-ctx.json"), cfg).expect("write cfg");
112    }
113
114    #[cfg(not(feature = "no-jail"))]
115    #[test]
116    fn linked_projects_outside_root_are_rejected_without_allow_path() {
117        // Global lock (not module-local): every LEAN_CTX_ALLOW_PATH mutation
118        // process-wide serializes through test_env_lock (#695 flake report).
119        let _guard = crate::core::data_dir::test_env_lock();
120        let root = tempfile::tempdir().expect("root");
121        let other = tempfile::tempdir().expect("other");
122
123        write_linked_config(root.path(), other.path());
124
125        crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
126        let res = load_linked_projects(root.path());
127        assert_eq!(res.roots, Vec::<PathBuf>::new());
128        assert!(
129            res.warnings
130                .iter()
131                .any(|w| w.contains("rejected by pathjail")),
132            "expected pathjail warning, got: {:?}",
133            res.warnings
134        );
135    }
136
137    #[test]
138    fn linked_projects_outside_root_are_allowed_with_allow_path() {
139        let _guard = crate::core::data_dir::test_env_lock();
140        let root = tempfile::tempdir().expect("root");
141        let other = tempfile::tempdir().expect("other");
142
143        write_linked_config(root.path(), other.path());
144
145        crate::test_env::set_var(
146            "LEAN_CTX_ALLOW_PATH",
147            other.path().to_string_lossy().to_string(),
148        );
149        let res = load_linked_projects(root.path());
150        assert_eq!(res.roots.len(), 1);
151        assert_eq!(res.roots[0], other.path().canonicalize().expect("canon"));
152
153        crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
154    }
155}