Skip to main content

lean_ctx/core/
data_dir.rs

1use std::path::PathBuf;
2
3/// Markers that identify a legacy / pre-split install whose categories must
4/// stay collapsed onto one directory (GH #408).
5///
6/// Deliberately excludes `config.toml`: after the XDG split it legitimately
7/// lives alone in the config dir, so treating it as a data marker would
8/// re-collapse a clean four-dir install back onto the config dir. These are all
9/// real data/state artifacts that only exist in a pre-split (mixed) install.
10const DATA_MARKERS: &[&str] = &["stats.json", "sessions", "vectors", "graphs", "knowledge"];
11
12/// Resolve the lean-ctx data directory.
13///
14/// Priority order (backward-compatible XDG split, GH #408):
15/// 1. `LEAN_CTX_DATA_DIR` env var (explicit override)
16/// 2. `~/.lean-ctx` if it has actual data (legacy installs)
17/// 3. `$XDG_CONFIG_HOME/lean-ctx` if it has actual data (pre-split installs that
18///    mixed data into the config dir — kept in place, never silently moved)
19/// 4. `$XDG_DATA_HOME/lean-ctx` (default `~/.local/share/lean-ctx`) for fresh
20///    installs, so the config dir holds only config and stays RO-sandbox-safe.
21///
22/// An empty `~/.lean-ctx/` directory does NOT trigger legacy mode — this prevents
23/// data directory splits when setup creates the dir before MCP writes stats.
24pub fn lean_ctx_data_dir() -> Result<PathBuf, String> {
25    if let Ok(dir) = std::env::var("LEAN_CTX_DATA_DIR") {
26        let trimmed = dir.trim();
27        if !trimmed.is_empty() {
28            let p = PathBuf::from(trimmed);
29            ensure_dir_permissions(&p);
30            return Ok(p);
31        }
32    }
33
34    // Test sandbox (GL #512): without this, any unit test that triggers a
35    // store write (stats, savings ledger, context ledger, heatmap, ...)
36    // silently pollutes the developer's real ~/.lean-ctx — bounce events from
37    // test fixtures showed up as "today 61%" on the user dashboard. Tests that
38    // set LEAN_CTX_DATA_DIR keep full control (handled above); everyone else
39    // lands in a per-process temp dir and physically cannot touch real data.
40    #[cfg(test)]
41    {
42        Ok(test_sandbox_dir())
43    }
44
45    #[cfg(not(test))]
46    {
47        resolve_home_data_dir()
48    }
49}
50
51/// Per-process temp sandbox used as the default data dir under `#[cfg(test)]`,
52/// so any store write from a test fixture lands in a throwaway dir instead of
53/// the developer's real `~/.lean-ctx` (GL #512). Tests that need an *empty*,
54/// private dir should use [`isolated_data_dir`] instead (the shared sandbox is
55/// not empty: parallel tests write into it).
56#[cfg(test)]
57pub(crate) fn test_sandbox_dir() -> PathBuf {
58    static TEST_SANDBOX: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
59    TEST_SANDBOX
60        .get_or_init(|| {
61            let d = std::env::temp_dir().join(format!("lean-ctx-testdata-{}", std::process::id()));
62            let _ = std::fs::create_dir_all(&d);
63            d
64        })
65        .clone()
66}
67
68/// Home-based resolution (legacy `~/.lean-ctx` / mixed vs XDG). Split out so the
69/// priority rules stay unit-testable despite the test sandbox above.
70///
71/// The legacy/mixed back-compat decision lives in exactly ONE place,
72/// [`crate::core::paths::single_dir_override`], so the data dir can never
73/// disagree with config/state/cache (which all resolve through it): a legacy
74/// `~/.lean-ctx` or mixed `$XDG_CONFIG_HOME/lean-ctx` install wins only while it
75/// still holds data markers. Once `doctor --fix` has split it out, every
76/// category — data included — flips to its typed XDG dir, and a leftover
77/// (marker-free) `~/.lean-ctx` is no longer silently re-adopted (GH #436).
78fn resolve_home_data_dir() -> Result<PathBuf, String> {
79    // 1./2. Legacy or mixed single-dir install that still holds data → keep it
80    //       in place (back-compat). `LEAN_CTX_DATA_DIR` is handled by the caller,
81    //       and `single_dir_override` honors it too.
82    if let Some(dir) = crate::core::paths::single_dir_override() {
83        ensure_dir_permissions(&dir);
84        return Ok(dir);
85    }
86
87    // 3. Fresh / fully-split install: default DATA to `$XDG_DATA_HOME/lean-ctx`
88    //    (GH #408) so the config dir (`$XDG_CONFIG_HOME`) holds only config and
89    //    stays read-only-sandbox-safe.
90    let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
91    let xdg_data = std::env::var("XDG_DATA_HOME")
92        .ok()
93        .filter(|s| !s.trim().is_empty())
94        .map_or_else(|| home.join(".local").join("share"), PathBuf::from);
95    let data_dir = xdg_data.join("lean-ctx");
96    ensure_dir_permissions(&data_dir);
97    Ok(data_dir)
98}
99
100pub(crate) fn has_data_files(dir: &std::path::Path) -> bool {
101    DATA_MARKERS.iter().any(|f| dir.join(f).exists())
102}
103
104/// Returns all known data directories that contain stats data, in resolution
105/// priority order (legacy → mixed config → XDG data). Used by the dual-dir
106/// consolidation ([`crate::core::data_consolidate`]) and doctor diagnostics.
107///
108/// `$XDG_DATA_HOME/lean-ctx` is included (GH #414): after the #408 default flip
109/// a fresh install writes stats there, so a user who *also* has a legacy/mixed
110/// tree has the split that the consolidation must detect and merge.
111pub fn all_data_dirs_with_stats() -> Vec<PathBuf> {
112    let mut dirs = Vec::new();
113    if let Some(home) = dirs::home_dir() {
114        let legacy = home.join(".lean-ctx");
115        if legacy.join("stats.json").exists() {
116            dirs.push(legacy);
117        }
118        let xdg_config = std::env::var("XDG_CONFIG_HOME")
119            .ok()
120            .filter(|s| !s.trim().is_empty())
121            .map_or_else(|| home.join(".config"), PathBuf::from)
122            .join("lean-ctx");
123        if xdg_config.join("stats.json").exists() && !dirs.contains(&xdg_config) {
124            dirs.push(xdg_config);
125        }
126        let xdg_data = std::env::var("XDG_DATA_HOME")
127            .ok()
128            .filter(|s| !s.trim().is_empty())
129            .map_or_else(|| home.join(".local").join("share"), PathBuf::from)
130            .join("lean-ctx");
131        if xdg_data.join("stats.json").exists() && !dirs.contains(&xdg_data) {
132            dirs.push(xdg_data);
133        }
134    }
135    dirs
136}
137
138#[cfg(unix)]
139pub(crate) fn ensure_dir_permissions(path: &std::path::Path) {
140    use std::os::unix::fs::PermissionsExt;
141    if path.is_dir() {
142        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700));
143    }
144}
145
146#[cfg(not(unix))]
147pub(crate) fn ensure_dir_permissions(_path: &std::path::Path) {}
148
149pub fn test_env_lock() -> std::sync::MutexGuard<'static, ()> {
150    use std::sync::{Mutex, OnceLock};
151    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
152    let mutex = LOCK.get_or_init(|| Mutex::new(()));
153    mutex
154        .lock()
155        .unwrap_or_else(std::sync::PoisonError::into_inner)
156}
157
158/// RAII data-dir isolation for tests (GL #556): holds `test_env_lock` for
159/// the guard's lifetime, points `LEAN_CTX_DATA_DIR` at a fresh temp dir and
160/// restores the env on drop — even on panic, so a failing test cannot leak
161/// the override into others. Use this instead of hand-rolled
162/// `set_var`/`remove_var` pairs whenever a test needs an empty, private
163/// data dir (the shared per-process sandbox is NOT empty: parallel tests
164/// write stores like feedback, bandit and sessions into it).
165#[cfg(test)]
166pub struct IsolatedDataDir {
167    tmp: tempfile::TempDir,
168    _guard: std::sync::MutexGuard<'static, ()>,
169}
170
171#[cfg(test)]
172impl IsolatedDataDir {
173    pub fn path(&self) -> &std::path::Path {
174        self.tmp.path()
175    }
176}
177
178/// Category env vars pointed at the isolated temp dir so all four XDG
179/// categories (config/data/state/cache) collapse onto it in tests (GH #408).
180#[cfg(test)]
181const ISOLATED_ENV_VARS: &[&str] = &[
182    "LEAN_CTX_DATA_DIR",
183    "LEAN_CTX_CONFIG_DIR",
184    "LEAN_CTX_STATE_DIR",
185    "LEAN_CTX_CACHE_DIR",
186];
187
188#[cfg(test)]
189impl Drop for IsolatedDataDir {
190    fn drop(&mut self) {
191        // Struct Drop runs before field drops, so the env is restored while
192        // the lock is still held.
193        for var in ISOLATED_ENV_VARS {
194            crate::test_env::remove_var(var);
195        }
196    }
197}
198
199#[cfg(test)]
200pub fn isolated_data_dir() -> IsolatedDataDir {
201    let guard = test_env_lock();
202    let tmp = tempfile::tempdir().expect("tempdir for isolated data dir");
203    for var in ISOLATED_ENV_VARS {
204        crate::test_env::set_var(var, tmp.path());
205    }
206    IsolatedDataDir { tmp, _guard: guard }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[test]
214    fn has_data_files_empty_dir() {
215        let dir = std::env::temp_dir().join("test_data_dir_empty");
216        let _ = std::fs::remove_dir_all(&dir);
217        let _ = std::fs::create_dir_all(&dir);
218        assert!(!has_data_files(&dir));
219        let _ = std::fs::remove_dir_all(&dir);
220    }
221
222    #[test]
223    fn has_data_files_with_stats() {
224        let dir = std::env::temp_dir().join("test_data_dir_stats");
225        let _ = std::fs::remove_dir_all(&dir);
226        let _ = std::fs::create_dir_all(&dir);
227        std::fs::write(dir.join("stats.json"), "{}").unwrap();
228        assert!(has_data_files(&dir));
229        let _ = std::fs::remove_dir_all(&dir);
230    }
231
232    #[test]
233    fn has_data_files_ignores_config_only() {
234        // GH #408: config.toml (+ hooks) alone must NOT mark a dir as "has data",
235        // otherwise a clean post-split config dir would re-collapse the four-dir
236        // layout back onto itself via single_dir_override.
237        let dir = std::env::temp_dir().join("test_data_dir_config_only");
238        let _ = std::fs::remove_dir_all(&dir);
239        let _ = std::fs::create_dir_all(&dir);
240        std::fs::write(dir.join("config.toml"), "").unwrap();
241        std::fs::write(dir.join("env.sh"), "").unwrap();
242        assert!(!has_data_files(&dir), "config-only dir is not a data dir");
243        let _ = std::fs::remove_dir_all(&dir);
244    }
245
246    #[test]
247    fn fresh_install_defaults_data_to_xdg_data_home() {
248        // GH #408 flip: with no legacy/mixed data, a fresh install resolves DATA
249        // to $XDG_DATA_HOME/lean-ctx (not the config dir).
250        let _lock = test_env_lock();
251        let xdg_config = tempfile::tempdir().unwrap();
252        let xdg_data = tempfile::tempdir().unwrap();
253        crate::test_env::set_var("LEAN_CTX_DATA_DIR", "");
254        crate::test_env::set_var("XDG_CONFIG_HOME", xdg_config.path());
255        crate::test_env::set_var("XDG_DATA_HOME", xdg_data.path());
256
257        let result = resolve_home_data_dir().unwrap();
258
259        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
260        crate::test_env::remove_var("XDG_CONFIG_HOME");
261        crate::test_env::remove_var("XDG_DATA_HOME");
262
263        // A real `~/.lean-ctx` (legacy) would correctly take precedence; only
264        // assert the fresh default when it is absent (always true on CI).
265        let legacy = dirs::home_dir().unwrap().join(".lean-ctx");
266        if !legacy.exists() {
267            assert_eq!(result, xdg_data.path().join("lean-ctx"));
268        }
269    }
270
271    #[test]
272    fn has_data_files_with_sessions() {
273        let dir = std::env::temp_dir().join("test_data_dir_sessions");
274        let _ = std::fs::remove_dir_all(&dir);
275        let _ = std::fs::create_dir_all(&dir);
276        let _ = std::fs::create_dir_all(dir.join("sessions"));
277        assert!(has_data_files(&dir));
278        let _ = std::fs::remove_dir_all(&dir);
279    }
280
281    #[test]
282    fn lean_ctx_data_dir_env_override() {
283        let _lock = test_env_lock();
284        let dir = std::env::temp_dir().join("test_data_dir_env");
285        let _ = std::fs::remove_dir_all(&dir);
286        let _ = std::fs::create_dir_all(&dir);
287        crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
288        let result = lean_ctx_data_dir().unwrap();
289        assert_eq!(result, dir);
290        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
291        let _ = std::fs::remove_dir_all(&dir);
292    }
293
294    #[test]
295    fn has_data_files_is_false_for_empty_dir() {
296        let dir = std::env::temp_dir().join("test_data_dir_no_data");
297        let _ = std::fs::remove_dir_all(&dir);
298        let _ = std::fs::create_dir_all(&dir);
299        std::fs::write(dir.join("random.txt"), "not a marker").unwrap();
300        assert!(!has_data_files(&dir));
301        let _ = std::fs::remove_dir_all(&dir);
302    }
303
304    #[test]
305    fn xdg_override_with_data_wins() {
306        let _lock = test_env_lock();
307
308        let xdg_base = std::env::temp_dir().join("test_xdg_override_wins");
309        let _ = std::fs::remove_dir_all(&xdg_base);
310        let xdg_dir = xdg_base.join("lean-ctx");
311        let _ = std::fs::create_dir_all(&xdg_dir);
312        std::fs::write(xdg_dir.join("stats.json"), r#"{"total_commands":1}"#).unwrap();
313
314        crate::test_env::set_var("LEAN_CTX_DATA_DIR", "");
315        crate::test_env::set_var("XDG_CONFIG_HOME", xdg_base.to_str().unwrap());
316
317        // Calls the home resolver directly: lean_ctx_data_dir() is sandboxed
318        // under cfg(test) (GL #512) and would short-circuit before XDG logic.
319        let result = resolve_home_data_dir().unwrap();
320
321        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
322        crate::test_env::remove_var("XDG_CONFIG_HOME");
323
324        let home = dirs::home_dir().unwrap();
325        let legacy = home.join(".lean-ctx");
326        if !has_data_files(&legacy) {
327            assert_eq!(
328                result, xdg_dir,
329                "XDG with data should win when legacy has no data"
330            );
331        }
332
333        let _ = std::fs::remove_dir_all(&xdg_base);
334    }
335
336    #[cfg(unix)]
337    fn restore_env(key: &str, val: Option<std::ffi::OsString>) {
338        match val {
339            Some(v) => crate::test_env::set_var(key, v),
340            None => crate::test_env::remove_var(key),
341        }
342    }
343
344    #[cfg(unix)]
345    #[test]
346    fn markerless_legacy_dir_does_not_win() {
347        // GH #436: after `doctor --fix` moves data to XDG, `~/.lean-ctx` lingers
348        // (runtime leftovers) but holds no data markers. It must NOT keep being
349        // re-adopted as the data dir — data must flip to $XDG_DATA_HOME/lean-ctx,
350        // exactly like config/state/cache already do via single_dir_override.
351        let _lock = test_env_lock();
352        let tmp = tempfile::tempdir().unwrap();
353        let home = tmp.path().join("home");
354        let xdg_data = tmp.path().join("xdg-data");
355        let legacy = home.join(".lean-ctx");
356        std::fs::create_dir_all(&legacy).unwrap();
357        // A runtime leftover (daemon.pid) is not a data marker.
358        std::fs::write(legacy.join("daemon.pid"), "123").unwrap();
359
360        let saved_home = std::env::var_os("HOME");
361        let saved_config = std::env::var_os("XDG_CONFIG_HOME");
362        let saved_data = std::env::var_os("XDG_DATA_HOME");
363        crate::test_env::set_var("HOME", &home);
364        crate::test_env::remove_var("XDG_CONFIG_HOME");
365        crate::test_env::set_var("XDG_DATA_HOME", &xdg_data);
366        crate::test_env::set_var("LEAN_CTX_DATA_DIR", "");
367
368        let result = resolve_home_data_dir().unwrap();
369
370        // Restore before asserting so a failure can't leak env into other tests.
371        restore_env("HOME", saved_home);
372        restore_env("XDG_CONFIG_HOME", saved_config);
373        restore_env("XDG_DATA_HOME", saved_data);
374        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
375
376        assert_eq!(
377            result,
378            xdg_data.join("lean-ctx"),
379            "marker-free legacy dir must not be re-adopted as the data dir"
380        );
381    }
382}