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/// Returns all known data directories that contain stats data, in resolution
123/// priority order (legacy → mixed config → XDG data). Used by the dual-dir
124/// consolidation (`crate::core::data_consolidate`) and doctor diagnostics.
125///
126/// `$XDG_DATA_HOME/lean-ctx` is included (GH #414): after the #408 default flip
127/// a fresh install writes stats there, so a user who *also* has a legacy/mixed
128/// tree has the split that the consolidation must detect and merge.
129pub fn all_data_dirs_with_stats() -> Vec<PathBuf> {
130    let mut dirs = Vec::new();
131    if let Some(home) = dirs::home_dir() {
132        let legacy = home.join(".lean-ctx");
133        if legacy.join("stats.json").exists() {
134            dirs.push(legacy);
135        }
136        let xdg_config = std::env::var("XDG_CONFIG_HOME")
137            .ok()
138            .filter(|s| !s.trim().is_empty())
139            .map_or_else(|| home.join(".config"), PathBuf::from)
140            .join("lean-ctx");
141        if xdg_config.join("stats.json").exists() && !dirs.contains(&xdg_config) {
142            dirs.push(xdg_config);
143        }
144        let xdg_data = std::env::var("XDG_DATA_HOME")
145            .ok()
146            .filter(|s| !s.trim().is_empty())
147            .map_or_else(|| home.join(".local").join("share"), PathBuf::from)
148            .join("lean-ctx");
149        if xdg_data.join("stats.json").exists() && !dirs.contains(&xdg_data) {
150            dirs.push(xdg_data);
151        }
152    }
153    dirs
154}
155
156#[cfg(unix)]
157pub(crate) fn ensure_dir_permissions(path: &std::path::Path) {
158    use std::os::unix::fs::PermissionsExt;
159    if path.is_dir() {
160        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700));
161    }
162}
163
164#[cfg(not(unix))]
165pub(crate) fn ensure_dir_permissions(_path: &std::path::Path) {}
166
167static TEST_ENV_MUTEX: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
168
169thread_local! {
170    /// Re-entrancy depth for the current thread. >0 means this thread already
171    /// holds the lock, so a nested acquire is a no-op bump instead of a
172    /// self-deadlock.
173    static TEST_ENV_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
174    /// The real guard, held only while depth transitions 0→…→0.
175    static TEST_ENV_HELD: std::cell::RefCell<Option<std::sync::MutexGuard<'static, ()>>> =
176        const { std::cell::RefCell::new(None) };
177}
178
179/// Reentrant test env lock. Serializes env-mutating tests across threads (the
180/// point — `std::env::set_var` is not thread-safe) while letting the SAME
181/// thread re-acquire without deadlocking. A test and a `setup()` helper (or
182/// `isolated_data_dir`) can both take it; only the outermost acquisition holds
183/// the underlying mutex, nested ones just bump a per-thread depth. Other
184/// threads still block, so cross-test serialization is unchanged.
185pub fn test_env_lock() -> TestEnvGuard {
186    let mutex = TEST_ENV_MUTEX.get_or_init(|| std::sync::Mutex::new(()));
187    TEST_ENV_DEPTH.with(|depth| {
188        if depth.get() == 0 {
189            let guard = mutex
190                .lock()
191                .unwrap_or_else(std::sync::PoisonError::into_inner);
192            TEST_ENV_HELD.with(|held| *held.borrow_mut() = Some(guard));
193        }
194        depth.set(depth.get() + 1);
195    });
196    TestEnvGuard { _private: () }
197}
198
199/// RAII guard for [`test_env_lock`]. Dropping the outermost one releases the
200/// underlying mutex; nested guards just decrement the depth.
201pub struct TestEnvGuard {
202    _private: (),
203}
204
205impl Drop for TestEnvGuard {
206    fn drop(&mut self) {
207        TEST_ENV_DEPTH.with(|depth| {
208            let next = depth.get().saturating_sub(1);
209            depth.set(next);
210            if next == 0 {
211                TEST_ENV_HELD.with(|held| *held.borrow_mut() = None);
212            }
213        });
214    }
215}
216
217/// RAII data-dir isolation for tests (GL #556): holds `test_env_lock` for
218/// the guard's lifetime, points `LEAN_CTX_DATA_DIR` at a fresh temp dir and
219/// restores the env on drop — even on panic, so a failing test cannot leak
220/// the override into others. Use this instead of hand-rolled
221/// `set_var`/`remove_var` pairs whenever a test needs an empty, private
222/// data dir (the shared per-process sandbox is NOT empty: parallel tests
223/// write stores like feedback, bandit and sessions into it).
224#[cfg(test)]
225pub struct IsolatedDataDir {
226    tmp: tempfile::TempDir,
227    _guard: TestEnvGuard,
228}
229
230#[cfg(test)]
231impl IsolatedDataDir {
232    pub fn path(&self) -> &std::path::Path {
233        self.tmp.path()
234    }
235}
236
237/// Category env vars pointed at the isolated temp dir so all four XDG
238/// categories (config/data/state/cache) collapse onto it in tests (GH #408).
239#[cfg(test)]
240const ISOLATED_ENV_VARS: &[&str] = &[
241    "LEAN_CTX_DATA_DIR",
242    "LEAN_CTX_CONFIG_DIR",
243    "LEAN_CTX_STATE_DIR",
244    "LEAN_CTX_CACHE_DIR",
245];
246
247#[cfg(test)]
248impl Drop for IsolatedDataDir {
249    fn drop(&mut self) {
250        // Struct Drop runs before field drops, so the env is restored while
251        // the lock is still held.
252        for var in ISOLATED_ENV_VARS {
253            crate::test_env::remove_var(var);
254        }
255    }
256}
257
258#[cfg(test)]
259pub fn isolated_data_dir() -> IsolatedDataDir {
260    let guard = test_env_lock();
261    let tmp = tempfile::tempdir().expect("tempdir for isolated data dir");
262    for var in ISOLATED_ENV_VARS {
263        crate::test_env::set_var(var, tmp.path());
264    }
265    IsolatedDataDir { tmp, _guard: guard }
266}
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271
272    #[test]
273    fn has_data_files_empty_dir() {
274        let dir = std::env::temp_dir().join("test_data_dir_empty");
275        let _ = std::fs::remove_dir_all(&dir);
276        let _ = std::fs::create_dir_all(&dir);
277        assert!(!has_data_files(&dir));
278        let _ = std::fs::remove_dir_all(&dir);
279    }
280
281    #[test]
282    fn has_data_files_with_stats() {
283        let dir = std::env::temp_dir().join("test_data_dir_stats");
284        let _ = std::fs::remove_dir_all(&dir);
285        let _ = std::fs::create_dir_all(&dir);
286        std::fs::write(dir.join("stats.json"), "{}").unwrap();
287        assert!(has_data_files(&dir));
288        let _ = std::fs::remove_dir_all(&dir);
289    }
290
291    #[test]
292    fn has_data_files_ignores_config_only() {
293        // GH #408: config.toml (+ hooks) alone must NOT mark a dir as "has data",
294        // otherwise a clean post-split config dir would re-collapse the four-dir
295        // layout back onto itself via single_dir_override.
296        let dir = std::env::temp_dir().join("test_data_dir_config_only");
297        let _ = std::fs::remove_dir_all(&dir);
298        let _ = std::fs::create_dir_all(&dir);
299        std::fs::write(dir.join("config.toml"), "").unwrap();
300        std::fs::write(dir.join("env.sh"), "").unwrap();
301        assert!(!has_data_files(&dir), "config-only dir is not a data dir");
302        let _ = std::fs::remove_dir_all(&dir);
303    }
304
305    #[test]
306    fn fresh_install_defaults_data_to_xdg_data_home() {
307        // GH #408 flip: with no legacy/mixed data, a fresh install resolves DATA
308        // to $XDG_DATA_HOME/lean-ctx (not the config dir).
309        let _lock = test_env_lock();
310        let xdg_config = tempfile::tempdir().unwrap();
311        let xdg_data = tempfile::tempdir().unwrap();
312        crate::test_env::set_var("LEAN_CTX_DATA_DIR", "");
313        crate::test_env::set_var("XDG_CONFIG_HOME", xdg_config.path());
314        crate::test_env::set_var("XDG_DATA_HOME", xdg_data.path());
315
316        let result = resolve_home_data_dir().unwrap();
317
318        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
319        crate::test_env::remove_var("XDG_CONFIG_HOME");
320        crate::test_env::remove_var("XDG_DATA_HOME");
321
322        // A real `~/.lean-ctx` (legacy) would correctly take precedence; only
323        // assert the fresh default when it is absent (always true on CI).
324        let legacy = dirs::home_dir().unwrap().join(".lean-ctx");
325        if !legacy.exists() {
326            assert_eq!(result, xdg_data.path().join("lean-ctx"));
327        }
328    }
329
330    #[test]
331    fn empty_marker_dir_does_not_count() {
332        // GL #623/#625: an empty `sessions/` (a stray mkdir, a half-removed
333        // residue) must not flip the whole layout — only a marker carrying real
334        // data counts.
335        let dir = std::env::temp_dir().join("test_data_dir_empty_marker");
336        let _ = std::fs::remove_dir_all(&dir);
337        let _ = std::fs::create_dir_all(dir.join("sessions"));
338        assert!(!has_data_files(&dir), "empty marker dir must not count");
339        let _ = std::fs::remove_dir_all(&dir);
340    }
341
342    #[test]
343    fn empty_marker_file_does_not_count() {
344        // A zero-byte `stats.json` is not real data either (GL #625).
345        let dir = std::env::temp_dir().join("test_data_dir_empty_marker_file");
346        let _ = std::fs::remove_dir_all(&dir);
347        let _ = std::fs::create_dir_all(&dir);
348        std::fs::write(dir.join("stats.json"), "").unwrap();
349        assert!(!has_data_files(&dir), "empty marker file must not count");
350        let _ = std::fs::remove_dir_all(&dir);
351    }
352
353    #[test]
354    fn has_data_files_with_sessions() {
355        let dir = std::env::temp_dir().join("test_data_dir_sessions");
356        let _ = std::fs::remove_dir_all(&dir);
357        let _ = std::fs::create_dir_all(dir.join("sessions"));
358        // A non-empty sessions/ is real data (GL #625: empty dirs no longer count).
359        std::fs::write(dir.join("sessions").join("s1.json"), "{}").unwrap();
360        assert!(has_data_files(&dir));
361        let _ = std::fs::remove_dir_all(&dir);
362    }
363
364    #[test]
365    fn lean_ctx_data_dir_env_override() {
366        let _lock = test_env_lock();
367        let dir = std::env::temp_dir().join("test_data_dir_env");
368        let _ = std::fs::remove_dir_all(&dir);
369        let _ = std::fs::create_dir_all(&dir);
370        crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
371        let result = lean_ctx_data_dir().unwrap();
372        assert_eq!(result, dir);
373        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
374        let _ = std::fs::remove_dir_all(&dir);
375    }
376
377    #[test]
378    fn has_data_files_is_false_for_empty_dir() {
379        let dir = std::env::temp_dir().join("test_data_dir_no_data");
380        let _ = std::fs::remove_dir_all(&dir);
381        let _ = std::fs::create_dir_all(&dir);
382        std::fs::write(dir.join("random.txt"), "not a marker").unwrap();
383        assert!(!has_data_files(&dir));
384        let _ = std::fs::remove_dir_all(&dir);
385    }
386
387    #[test]
388    fn xdg_override_with_data_wins() {
389        let _lock = test_env_lock();
390
391        let xdg_base = std::env::temp_dir().join("test_xdg_override_wins");
392        let _ = std::fs::remove_dir_all(&xdg_base);
393        let xdg_dir = xdg_base.join("lean-ctx");
394        let _ = std::fs::create_dir_all(&xdg_dir);
395        std::fs::write(xdg_dir.join("stats.json"), r#"{"total_commands":1}"#).unwrap();
396
397        crate::test_env::set_var("LEAN_CTX_DATA_DIR", "");
398        crate::test_env::set_var("XDG_CONFIG_HOME", xdg_base.to_str().unwrap());
399        // Isolate XDG_DATA_HOME to an empty base so the mixed config dir (not a
400        // pre-existing XDG data tree) is what wins here.
401        let xdg_data_base = std::env::temp_dir().join("test_xdg_override_wins_data");
402        let _ = std::fs::remove_dir_all(&xdg_data_base);
403        crate::test_env::set_var("XDG_DATA_HOME", xdg_data_base.to_str().unwrap());
404
405        // Calls the home resolver directly: lean_ctx_data_dir() is sandboxed
406        // under cfg(test) (GL #512) and would short-circuit before XDG logic.
407        let result = resolve_home_data_dir().unwrap();
408
409        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
410        crate::test_env::remove_var("XDG_CONFIG_HOME");
411        crate::test_env::remove_var("XDG_DATA_HOME");
412
413        let home = dirs::home_dir().unwrap();
414        let legacy = home.join(".lean-ctx");
415        if !has_data_files(&legacy) {
416            assert_eq!(
417                result, xdg_dir,
418                "XDG with data should win when legacy has no data"
419            );
420        }
421
422        let _ = std::fs::remove_dir_all(&xdg_base);
423        let _ = std::fs::remove_dir_all(&xdg_data_base);
424    }
425
426    #[cfg(unix)]
427    fn restore_env(key: &str, val: Option<std::ffi::OsString>) {
428        match val {
429            Some(v) => crate::test_env::set_var(key, v),
430            None => crate::test_env::remove_var(key),
431        }
432    }
433
434    #[cfg(unix)]
435    #[test]
436    fn markerless_legacy_dir_does_not_win() {
437        // GH #436: after `doctor --fix` moves data to XDG, `~/.lean-ctx` lingers
438        // (runtime leftovers) but holds no data markers. It must NOT keep being
439        // re-adopted as the data dir — data must flip to $XDG_DATA_HOME/lean-ctx,
440        // exactly like config/state/cache already do via single_dir_override.
441        let _lock = test_env_lock();
442        let tmp = tempfile::tempdir().unwrap();
443        let home = tmp.path().join("home");
444        let xdg_data = tmp.path().join("xdg-data");
445        let legacy = home.join(".lean-ctx");
446        std::fs::create_dir_all(&legacy).unwrap();
447        // A runtime leftover (daemon.pid) is not a data marker.
448        std::fs::write(legacy.join("daemon.pid"), "123").unwrap();
449
450        let saved_home = std::env::var_os("HOME");
451        let saved_config = std::env::var_os("XDG_CONFIG_HOME");
452        let saved_data = std::env::var_os("XDG_DATA_HOME");
453        crate::test_env::set_var("HOME", &home);
454        crate::test_env::remove_var("XDG_CONFIG_HOME");
455        crate::test_env::set_var("XDG_DATA_HOME", &xdg_data);
456        crate::test_env::set_var("LEAN_CTX_DATA_DIR", "");
457
458        let result = resolve_home_data_dir().unwrap();
459
460        // Restore before asserting so a failure can't leak env into other tests.
461        restore_env("HOME", saved_home);
462        restore_env("XDG_CONFIG_HOME", saved_config);
463        restore_env("XDG_DATA_HOME", saved_data);
464        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
465
466        assert_eq!(
467            result,
468            xdg_data.join("lean-ctx"),
469            "marker-free legacy dir must not be re-adopted as the data dir"
470        );
471    }
472}