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.
10pub(crate) const DATA_MARKERS: &[&str] =
11    &["stats.json", "sessions", "vectors", "graphs", "knowledge"];
12
13/// Resolve the lean-ctx data directory.
14///
15/// Priority order (backward-compatible XDG split, GH #408):
16/// 1. `LEAN_CTX_DATA_DIR` env var (explicit override)
17/// 2. `~/.lean-ctx` if it has actual data (legacy installs)
18/// 3. `$XDG_CONFIG_HOME/lean-ctx` if it has actual data (pre-split installs that
19///    mixed data into the config dir — kept in place, never silently moved)
20/// 4. `$XDG_DATA_HOME/lean-ctx` (default `~/.local/share/lean-ctx`) for fresh
21///    installs, so the config dir holds only config and stays RO-sandbox-safe.
22///
23/// An empty `~/.lean-ctx/` directory does NOT trigger legacy mode — this prevents
24/// data directory splits when setup creates the dir before MCP writes stats.
25pub fn lean_ctx_data_dir() -> Result<PathBuf, String> {
26    let path = resolve_data_dir()?;
27    ensure_dir_permissions(&path);
28    Ok(path)
29}
30
31/// Resolve the existing data-directory taxonomy without changing permissions.
32/// Security-sensitive stores must validate paths before any filesystem mutation.
33pub(crate) fn resolve_data_dir() -> Result<PathBuf, String> {
34    if let Ok(dir) = std::env::var("LEAN_CTX_DATA_DIR") {
35        let trimmed = dir.trim();
36        if !trimmed.is_empty() {
37            let p = PathBuf::from(trimmed);
38            return Ok(p);
39        }
40    }
41
42    // Test sandbox (GL #512): without this, any unit test that triggers a
43    // store write (stats, savings ledger, context ledger, heatmap, ...)
44    // silently pollutes the developer's real ~/.lean-ctx — bounce events from
45    // test fixtures showed up as "today 61%" on the user dashboard. Tests that
46    // set LEAN_CTX_DATA_DIR keep full control (handled above); everyone else
47    // lands in a per-process temp dir and physically cannot touch real data.
48    #[cfg(test)]
49    {
50        Ok(test_sandbox_dir())
51    }
52
53    #[cfg(not(test))]
54    {
55        resolve_home_data_dir()
56    }
57}
58
59/// Per-process temp sandbox used as the default data dir under `#[cfg(test)]`,
60/// so any store write from a test fixture lands in a throwaway dir instead of
61/// the developer's real `~/.lean-ctx` (GL #512). Tests that need an *empty*,
62/// private dir should use [`isolated_data_dir`] instead (the shared sandbox is
63/// not empty: parallel tests write into it).
64#[cfg(test)]
65pub(crate) fn test_sandbox_dir() -> PathBuf {
66    static TEST_SANDBOX: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
67    TEST_SANDBOX
68        .get_or_init(|| {
69            let d = std::env::temp_dir().join(format!("lean-ctx-testdata-{}", std::process::id()));
70            let _ = std::fs::create_dir_all(&d);
71            d
72        })
73        .clone()
74}
75
76/// Home-based resolution (legacy `~/.lean-ctx` / mixed vs XDG). Split out so the
77/// priority rules stay unit-testable despite the test sandbox above.
78///
79/// The legacy/mixed back-compat decision lives in exactly ONE place,
80/// [`crate::core::paths::single_dir_override`], so the data dir can never
81/// disagree with config/state/cache (which all resolve through it): a legacy
82/// `~/.lean-ctx` or mixed `$XDG_CONFIG_HOME/lean-ctx` install wins only while it
83/// still holds data markers. Once `doctor --fix` has split it out, every
84/// category — data included — flips to its typed XDG dir, and a leftover
85/// (marker-free) `~/.lean-ctx` is no longer silently re-adopted (GH #436).
86fn resolve_home_data_dir() -> Result<PathBuf, String> {
87    // 1./2. Legacy or mixed single-dir install that still holds data → keep it
88    //       in place (back-compat). `LEAN_CTX_DATA_DIR` is handled by the caller,
89    //       and `single_dir_override` honors it too.
90    if let Some(dir) = crate::core::paths::single_dir_override() {
91        return Ok(dir);
92    }
93
94    // 3. Fresh / fully-split install: default DATA to `$XDG_DATA_HOME/lean-ctx`
95    //    (GH #408) so the config dir (`$XDG_CONFIG_HOME`) holds only config and
96    //    stays read-only-sandbox-safe.
97    let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
98    let xdg_data = std::env::var("XDG_DATA_HOME")
99        .ok()
100        .filter(|s| !s.trim().is_empty())
101        .map_or_else(|| home.join(".local").join("share"), PathBuf::from);
102    let data_dir = xdg_data.join("lean-ctx");
103    Ok(data_dir)
104}
105
106pub(crate) fn has_data_files(dir: &std::path::Path) -> bool {
107    DATA_MARKERS.iter().any(|f| marker_has_data(&dir.join(f)))
108}
109
110/// A marker counts only when it actually carries data: a non-empty file, or a
111/// directory with at least one entry. An empty `sessions/` (a stray `mkdir`, a
112/// half-removed residue, a backup-restore artifact) must NOT collapse the whole
113/// layout onto a directory that holds no real data (GL #623 / #625).
114fn marker_has_data(path: &std::path::Path) -> bool {
115    match std::fs::metadata(path) {
116        Ok(m) if m.is_dir() => std::fs::read_dir(path).is_ok_and(|mut it| it.next().is_some()),
117        Ok(m) => m.len() > 0,
118        Err(_) => false,
119    }
120}
121
122/// Every location a LeanCTX data directory can resolve to for this user, in
123/// resolution priority order (legacy → mixed config → XDG data), whether or
124/// not it exists. Used to keep one telemetry identity per installation when
125/// processes resolve different directories.
126pub fn candidate_data_dirs() -> Vec<PathBuf> {
127    let Some(home) = dirs::home_dir() else {
128        return Vec::new();
129    };
130    let base = |variable: &str, fallback: PathBuf| {
131        std::env::var(variable)
132            .ok()
133            .filter(|value| !value.trim().is_empty())
134            .map_or(fallback, PathBuf::from)
135            .join("lean-ctx")
136    };
137    vec![
138        home.join(".lean-ctx"),
139        base("XDG_CONFIG_HOME", home.join(".config")),
140        base("XDG_DATA_HOME", home.join(".local").join("share")),
141    ]
142}
143
144/// Returns all known data directories that contain stats data, in resolution
145/// priority order (legacy → mixed config → XDG data). Used by the dual-dir
146/// consolidation (`crate::core::data_consolidate`) and doctor diagnostics.
147///
148/// `$XDG_DATA_HOME/lean-ctx` is included (GH #414): after the #408 default flip
149/// a fresh install writes stats there, so a user who *also* has a legacy/mixed
150/// tree has the split that the consolidation must detect and merge.
151pub fn all_data_dirs_with_stats() -> Vec<PathBuf> {
152    let mut dirs = Vec::new();
153    if let Some(home) = dirs::home_dir() {
154        let legacy = home.join(".lean-ctx");
155        if legacy.join("stats.json").exists() {
156            dirs.push(legacy);
157        }
158        let xdg_config = std::env::var("XDG_CONFIG_HOME")
159            .ok()
160            .filter(|s| !s.trim().is_empty())
161            .map_or_else(|| home.join(".config"), PathBuf::from)
162            .join("lean-ctx");
163        if xdg_config.join("stats.json").exists() && !dirs.contains(&xdg_config) {
164            dirs.push(xdg_config);
165        }
166        let xdg_data = std::env::var("XDG_DATA_HOME")
167            .ok()
168            .filter(|s| !s.trim().is_empty())
169            .map_or_else(|| home.join(".local").join("share"), PathBuf::from)
170            .join("lean-ctx");
171        if xdg_data.join("stats.json").exists() && !dirs.contains(&xdg_data) {
172            dirs.push(xdg_data);
173        }
174    }
175    dirs
176}
177
178#[cfg(unix)]
179pub(crate) fn ensure_dir_permissions(path: &std::path::Path) {
180    use std::os::unix::fs::PermissionsExt;
181    if path.is_dir() {
182        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700));
183    }
184}
185
186#[cfg(not(unix))]
187pub(crate) fn ensure_dir_permissions(_path: &std::path::Path) {}
188
189static TEST_ENV_MUTEX: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
190
191thread_local! {
192    /// Re-entrancy depth for the current thread. >0 means this thread already
193    /// holds the lock, so a nested acquire is a no-op bump instead of a
194    /// self-deadlock.
195    static TEST_ENV_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
196    /// The real guard, held only while depth transitions 0→…→0.
197    static TEST_ENV_HELD: std::cell::RefCell<Option<std::sync::MutexGuard<'static, ()>>> =
198        const { std::cell::RefCell::new(None) };
199}
200
201/// Reentrant test env lock. Serializes env-mutating tests across threads (the
202/// point — `std::env::set_var` is not thread-safe) while letting the SAME
203/// thread re-acquire without deadlocking. A test and a `setup()` helper (or
204/// `isolated_data_dir`) can both take it; only the outermost acquisition holds
205/// the underlying mutex, nested ones just bump a per-thread depth. Other
206/// threads still block, so cross-test serialization is unchanged.
207pub fn test_env_lock() -> TestEnvGuard {
208    let mutex = TEST_ENV_MUTEX.get_or_init(|| std::sync::Mutex::new(()));
209    TEST_ENV_DEPTH.with(|depth| {
210        if depth.get() == 0 {
211            let guard = mutex
212                .lock()
213                .unwrap_or_else(std::sync::PoisonError::into_inner);
214            TEST_ENV_HELD.with(|held| *held.borrow_mut() = Some(guard));
215        }
216        depth.set(depth.get() + 1);
217    });
218    TestEnvGuard { _private: () }
219}
220
221/// Whether the current thread holds [`test_env_lock`].
222pub fn holds_test_env_lock() -> bool {
223    TEST_ENV_DEPTH.with(|depth| depth.get() > 0)
224}
225
226/// RAII guard for [`test_env_lock`]. Dropping the outermost one releases the
227/// underlying mutex; nested guards just decrement the depth.
228pub struct TestEnvGuard {
229    _private: (),
230}
231
232impl Drop for TestEnvGuard {
233    fn drop(&mut self) {
234        TEST_ENV_DEPTH.with(|depth| {
235            let next = depth.get().saturating_sub(1);
236            depth.set(next);
237            if next == 0 {
238                TEST_ENV_HELD.with(|held| *held.borrow_mut() = None);
239            }
240        });
241    }
242}
243
244/// RAII data-dir isolation for tests (GL #556): holds `test_env_lock` for
245/// the guard's lifetime, points `LEAN_CTX_DATA_DIR` at a fresh temp dir and
246/// restores the env on drop — even on panic, so a failing test cannot leak
247/// the override into others. Use this instead of hand-rolled
248/// `set_var`/`remove_var` pairs whenever a test needs an empty, private
249/// data dir (the shared per-process sandbox is NOT empty: parallel tests
250/// write stores like feedback, bandit and sessions into it).
251#[cfg(test)]
252pub struct IsolatedDataDir {
253    tmp: tempfile::TempDir,
254    _guard: TestEnvGuard,
255}
256
257#[cfg(test)]
258impl IsolatedDataDir {
259    pub fn path(&self) -> &std::path::Path {
260        self.tmp.path()
261    }
262}
263
264/// Category env vars pointed at the isolated temp dir so all four XDG
265/// categories (config/data/state/cache) collapse onto it in tests (GH #408).
266#[cfg(test)]
267const ISOLATED_ENV_VARS: &[&str] = &[
268    "LEAN_CTX_DATA_DIR",
269    "LEAN_CTX_CONFIG_DIR",
270    "LEAN_CTX_STATE_DIR",
271    "LEAN_CTX_CACHE_DIR",
272];
273
274#[cfg(test)]
275impl Drop for IsolatedDataDir {
276    fn drop(&mut self) {
277        // Struct Drop runs before field drops, so the env is restored while
278        // the lock is still held.
279        for var in ISOLATED_ENV_VARS {
280            crate::test_env::remove_var(var);
281        }
282    }
283}
284
285#[cfg(test)]
286pub fn isolated_data_dir() -> IsolatedDataDir {
287    let guard = test_env_lock();
288    let tmp = tempfile::tempdir().expect("tempdir for isolated data dir");
289    for var in ISOLATED_ENV_VARS {
290        crate::test_env::set_var(var, tmp.path());
291    }
292    IsolatedDataDir { tmp, _guard: guard }
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    #[test]
300    fn has_data_files_empty_dir() {
301        let dir = std::env::temp_dir().join("test_data_dir_empty");
302        let _ = std::fs::remove_dir_all(&dir);
303        let _ = std::fs::create_dir_all(&dir);
304        assert!(!has_data_files(&dir));
305        let _ = std::fs::remove_dir_all(&dir);
306    }
307
308    #[test]
309    fn has_data_files_with_stats() {
310        let dir = std::env::temp_dir().join("test_data_dir_stats");
311        let _ = std::fs::remove_dir_all(&dir);
312        let _ = std::fs::create_dir_all(&dir);
313        std::fs::write(dir.join("stats.json"), "{}").unwrap();
314        assert!(has_data_files(&dir));
315        let _ = std::fs::remove_dir_all(&dir);
316    }
317
318    #[test]
319    fn has_data_files_ignores_config_only() {
320        // GH #408: config.toml (+ hooks) alone must NOT mark a dir as "has data",
321        // otherwise a clean post-split config dir would re-collapse the four-dir
322        // layout back onto itself via single_dir_override.
323        let dir = std::env::temp_dir().join("test_data_dir_config_only");
324        let _ = std::fs::remove_dir_all(&dir);
325        let _ = std::fs::create_dir_all(&dir);
326        std::fs::write(dir.join("config.toml"), "").unwrap();
327        std::fs::write(dir.join("env.sh"), "").unwrap();
328        assert!(!has_data_files(&dir), "config-only dir is not a data dir");
329        let _ = std::fs::remove_dir_all(&dir);
330    }
331
332    #[test]
333    fn fresh_install_defaults_data_to_xdg_data_home() {
334        // GH #408 flip: with no legacy/mixed data, a fresh install resolves DATA
335        // to $XDG_DATA_HOME/lean-ctx (not the config dir).
336        let _lock = test_env_lock();
337        let xdg_config = tempfile::tempdir().unwrap();
338        let xdg_data = tempfile::tempdir().unwrap();
339        crate::test_env::set_var("LEAN_CTX_DATA_DIR", "");
340        crate::test_env::set_var("XDG_CONFIG_HOME", xdg_config.path());
341        crate::test_env::set_var("XDG_DATA_HOME", xdg_data.path());
342
343        let result = resolve_home_data_dir().unwrap();
344
345        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
346        crate::test_env::remove_var("XDG_CONFIG_HOME");
347        crate::test_env::remove_var("XDG_DATA_HOME");
348
349        // A real `~/.lean-ctx` (legacy) would correctly take precedence; only
350        // assert the fresh default when it is absent (always true on CI).
351        let legacy = dirs::home_dir().unwrap().join(".lean-ctx");
352        if !legacy.exists() {
353            assert_eq!(result, xdg_data.path().join("lean-ctx"));
354        }
355    }
356
357    #[test]
358    fn empty_marker_dir_does_not_count() {
359        // GL #623/#625: an empty `sessions/` (a stray mkdir, a half-removed
360        // residue) must not flip the whole layout — only a marker carrying real
361        // data counts.
362        let dir = std::env::temp_dir().join("test_data_dir_empty_marker");
363        let _ = std::fs::remove_dir_all(&dir);
364        let _ = std::fs::create_dir_all(dir.join("sessions"));
365        assert!(!has_data_files(&dir), "empty marker dir must not count");
366        let _ = std::fs::remove_dir_all(&dir);
367    }
368
369    #[test]
370    fn empty_marker_file_does_not_count() {
371        // A zero-byte `stats.json` is not real data either (GL #625).
372        let dir = std::env::temp_dir().join("test_data_dir_empty_marker_file");
373        let _ = std::fs::remove_dir_all(&dir);
374        let _ = std::fs::create_dir_all(&dir);
375        std::fs::write(dir.join("stats.json"), "").unwrap();
376        assert!(!has_data_files(&dir), "empty marker file must not count");
377        let _ = std::fs::remove_dir_all(&dir);
378    }
379
380    #[test]
381    fn has_data_files_with_sessions() {
382        let dir = std::env::temp_dir().join("test_data_dir_sessions");
383        let _ = std::fs::remove_dir_all(&dir);
384        let _ = std::fs::create_dir_all(dir.join("sessions"));
385        // A non-empty sessions/ is real data (GL #625: empty dirs no longer count).
386        std::fs::write(dir.join("sessions").join("s1.json"), "{}").unwrap();
387        assert!(has_data_files(&dir));
388        let _ = std::fs::remove_dir_all(&dir);
389    }
390
391    #[test]
392    fn lean_ctx_data_dir_env_override() {
393        let _lock = test_env_lock();
394        let dir = std::env::temp_dir().join("test_data_dir_env");
395        let _ = std::fs::remove_dir_all(&dir);
396        let _ = std::fs::create_dir_all(&dir);
397        crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
398        let result = lean_ctx_data_dir().unwrap();
399        assert_eq!(result, dir);
400        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
401        let _ = std::fs::remove_dir_all(&dir);
402    }
403
404    #[test]
405    fn has_data_files_is_false_for_empty_dir() {
406        let dir = std::env::temp_dir().join("test_data_dir_no_data");
407        let _ = std::fs::remove_dir_all(&dir);
408        let _ = std::fs::create_dir_all(&dir);
409        std::fs::write(dir.join("random.txt"), "not a marker").unwrap();
410        assert!(!has_data_files(&dir));
411        let _ = std::fs::remove_dir_all(&dir);
412    }
413
414    #[test]
415    fn xdg_override_with_data_wins() {
416        let _lock = test_env_lock();
417
418        let xdg_base = std::env::temp_dir().join("test_xdg_override_wins");
419        let _ = std::fs::remove_dir_all(&xdg_base);
420        let xdg_dir = xdg_base.join("lean-ctx");
421        let _ = std::fs::create_dir_all(&xdg_dir);
422        std::fs::write(xdg_dir.join("stats.json"), r#"{"total_commands":1}"#).unwrap();
423
424        crate::test_env::set_var("LEAN_CTX_DATA_DIR", "");
425        crate::test_env::set_var("XDG_CONFIG_HOME", xdg_base.to_str().unwrap());
426        // Isolate XDG_DATA_HOME to an empty base so the mixed config dir (not a
427        // pre-existing XDG data tree) is what wins here.
428        let xdg_data_base = std::env::temp_dir().join("test_xdg_override_wins_data");
429        let _ = std::fs::remove_dir_all(&xdg_data_base);
430        crate::test_env::set_var("XDG_DATA_HOME", xdg_data_base.to_str().unwrap());
431
432        // Calls the home resolver directly: lean_ctx_data_dir() is sandboxed
433        // under cfg(test) (GL #512) and would short-circuit before XDG logic.
434        let result = resolve_home_data_dir().unwrap();
435
436        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
437        crate::test_env::remove_var("XDG_CONFIG_HOME");
438        crate::test_env::remove_var("XDG_DATA_HOME");
439
440        let home = dirs::home_dir().unwrap();
441        let legacy = home.join(".lean-ctx");
442        if !has_data_files(&legacy) {
443            assert_eq!(
444                result, xdg_dir,
445                "XDG with data should win when legacy has no data"
446            );
447        }
448
449        let _ = std::fs::remove_dir_all(&xdg_base);
450        let _ = std::fs::remove_dir_all(&xdg_data_base);
451    }
452
453    #[cfg(unix)]
454    fn restore_env(key: &str, val: Option<std::ffi::OsString>) {
455        match val {
456            Some(v) => crate::test_env::set_var(key, v),
457            None => crate::test_env::remove_var(key),
458        }
459    }
460
461    #[cfg(unix)]
462    #[test]
463    fn markerless_legacy_dir_does_not_win() {
464        // GH #436: after `doctor --fix` moves data to XDG, `~/.lean-ctx` lingers
465        // (runtime leftovers) but holds no data markers. It must NOT keep being
466        // re-adopted as the data dir — data must flip to $XDG_DATA_HOME/lean-ctx,
467        // exactly like config/state/cache already do via single_dir_override.
468        let _lock = test_env_lock();
469        let tmp = tempfile::tempdir().unwrap();
470        let home = tmp.path().join("home");
471        let xdg_data = tmp.path().join("xdg-data");
472        let legacy = home.join(".lean-ctx");
473        std::fs::create_dir_all(&legacy).unwrap();
474        // A runtime leftover (daemon.pid) is not a data marker.
475        std::fs::write(legacy.join("daemon.pid"), "123").unwrap();
476
477        let saved_home = std::env::var_os("HOME");
478        let saved_config = std::env::var_os("XDG_CONFIG_HOME");
479        let saved_data = std::env::var_os("XDG_DATA_HOME");
480        crate::test_env::set_var("HOME", &home);
481        crate::test_env::remove_var("XDG_CONFIG_HOME");
482        crate::test_env::set_var("XDG_DATA_HOME", &xdg_data);
483        crate::test_env::set_var("LEAN_CTX_DATA_DIR", "");
484
485        let result = resolve_home_data_dir().unwrap();
486
487        // Restore before asserting so a failure can't leak env into other tests.
488        restore_env("HOME", saved_home);
489        restore_env("XDG_CONFIG_HOME", saved_config);
490        restore_env("XDG_DATA_HOME", saved_data);
491        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
492
493        assert_eq!(
494            result,
495            xdg_data.join("lean-ctx"),
496            "marker-free legacy dir must not be re-adopted as the data dir"
497        );
498    }
499}