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