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