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