Skip to main content

lean_ctx/core/
paths.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Typed XDG base-directory resolvers for lean-ctx (GH #408 / GL #602).
4//!
5//! Historically every lean-ctx file joined onto a single [`lean_ctx_data_dir`]
6//! rooted at `$XDG_CONFIG_HOME/lean-ctx`, mixing `config.toml` with 30+ runtime
7//! data files (sessions, vectors, graphs, events, logs, caches). That violates
8//! the XDG Base Directory Spec and makes a read-only config sandbox impossible.
9//!
10//! This module introduces one typed resolver per XDG category so call-sites can
11//! migrate to the correct base over the following phases (GL #603/#604/#606/#607).
12//!
13//! ## Backward compatibility (single-dir mode)
14//!
15//! Existing installs MUST NOT split silently. `single_dir_override` returns
16//! `Some(dir)` when `LEAN_CTX_DATA_DIR` is set or a legacy/mixed install with
17//! data exists; in that case every category resolves to that one directory —
18//! byte-for-byte today's behavior. The real per-category split only applies to
19//! fresh installs (and, later, on-demand via `lean-ctx doctor --fix`).
20//!
21//! ## `data_dir()` and the fresh-install flip
22//!
23//! [`data_dir`] delegates to [`lean_ctx_data_dir`]. Config (`config.toml` +
24//! hooks) and the runtime STATE/CACHE files were migrated onto [`config_dir`],
25//! [`state_dir`] and [`cache_dir`] (GL #603/#604) so that, since GL #606, the
26//! data resolver defaults fresh installs to `$XDG_DATA_HOME/lean-ctx` without
27//! scattering config or state into the data dir. Legacy and pre-split mixed
28//! installs keep resolving every category to their existing single directory.
29//!
30//! Determinism (#498): every resolver is a pure function of environment + HOME;
31//! no timestamps, counters or randomness.
32
33use std::path::{Path, PathBuf};
34
35use super::data_dir::{ensure_dir_permissions, has_data_files, lean_ctx_data_dir};
36
37/// Reads a directory path from `name`, treating empty/whitespace as unset.
38fn env_path(name: &str) -> Option<PathBuf> {
39    std::env::var(name)
40        .ok()
41        .map(|v| v.trim().to_string())
42        .filter(|v| !v.is_empty())
43        .map(PathBuf::from)
44}
45
46/// The per-process directory overrides. Any of them makes this process run on
47/// directories other than the install's default layout.
48const DIR_OVERRIDES: [&str; 4] = [
49    "LEAN_CTX_CONFIG_DIR",
50    "LEAN_CTX_DATA_DIR",
51    "LEAN_CTX_STATE_DIR",
52    "LEAN_CTX_CACHE_DIR",
53];
54
55/// `true` when a directory override is set. Layout healing that moves files in
56/// the *default* locations (`~/.lean-ctx`, the XDG config dir, the layout pin)
57/// must then do nothing: the override applies to this process only, and the
58/// default locations belong to the real install (GH #2007).
59#[must_use]
60pub(crate) fn dir_override_active() -> bool {
61    DIR_OVERRIDES.iter().any(|name| env_path(name).is_some())
62}
63
64/// Resolves an XDG base directory (e.g. `~/.config`), honoring the `env_name`
65/// override and falling back to `$HOME/<home_fallback>`. Returns the base only;
66/// callers append `lean-ctx`.
67pub(crate) fn xdg_base(env_name: &str, home_fallback: &str) -> Result<PathBuf, String> {
68    if let Some(p) = env_path(env_name) {
69        return Ok(p);
70    }
71    dirs::home_dir()
72        .map(|h| h.join(home_fallback))
73        .ok_or_else(|| "Cannot determine home directory".to_string())
74}
75
76/// Pure resolution order for a category: explicit override > single-dir
77/// backward-compat > XDG split default (`<base>/lean-ctx`).
78fn resolve(
79    category_override: Option<PathBuf>,
80    single: Option<PathBuf>,
81    xdg_base_dir: &Path,
82) -> PathBuf {
83    category_override
84        .or(single)
85        .unwrap_or_else(|| xdg_base_dir.join("lean-ctx"))
86}
87
88/// Returns the single directory that ALL categories must collapse onto for
89/// backward compatibility, or `None` for a fresh install that may split.
90///
91/// `Some` when an *explicit* `LEAN_CTX_DATA_DIR` points at a non-standard
92/// location (a deliberate single-dir choice: a custom dir, or `~/.lean-ctx` via
93/// env), or a legacy `~/.lean-ctx` / mixed `$XDG_CONFIG_HOME/lean-ctx` install
94/// already holds data. An empty directory does NOT trigger single-dir mode
95/// (matches [`lean_ctx_data_dir`] semantics).
96///
97/// A `LEAN_CTX_DATA_DIR` equal to the *standard* XDG data dir
98/// (`$XDG_DATA_HOME/lean-ctx`) is a DATA pin only, NOT a single-dir directive:
99/// editors used to bake that exact value into the MCP server's `env`, and
100/// honoring it as single-dir collapsed config/state/cache onto the data dir for
101/// the MCP process while the terminal CLI kept the XDG split — so the two read
102/// different `config.toml` files (#594). Falling through keeps config in
103/// `$XDG_CONFIG_HOME/lean-ctx` for both; data still resolves to the pin via
104/// [`lean_ctx_data_dir`], which consumes the env var before reaching here.
105pub(crate) fn single_dir_override() -> Option<PathBuf> {
106    if let Some(p) = env_path("LEAN_CTX_DATA_DIR")
107        && !is_standard_xdg_data_dir(&p)
108    {
109        return Some(p);
110    }
111    let home = dirs::home_dir()?;
112    let xdg_config_base = xdg_base("XDG_CONFIG_HOME", ".config").ok()?;
113    let xdg_data_base = xdg_base("XDG_DATA_HOME", ".local/share").ok();
114    single_dir_override_fs(&home, &xdg_config_base, xdg_data_base.as_deref())
115}
116
117/// True when `p` is exactly the standard XDG data dir (`$XDG_DATA_HOME/lean-ctx`,
118/// default `~/.local/share/lean-ctx`). Pure function of env + HOME (no filesystem
119/// access) so category resolution stays deterministic (#498).
120fn is_standard_xdg_data_dir(p: &Path) -> bool {
121    xdg_base("XDG_DATA_HOME", ".local/share")
122        .map(|base| base.join("lean-ctx"))
123        .is_ok_and(|standard| standard.as_path() == p)
124}
125
126/// Whether an editor-baked `LEAN_CTX_DATA_DIR` value (`pin`) would make that
127/// editor's MCP server resolve a *different* `config.toml` than the terminal
128/// CLI. Only a **non-standard** pin collapses config/state/cache onto the data
129/// dir (#594); a pin equal to the standard `$XDG_DATA_HOME/lean-ctx` is a
130/// data-only pin and keeps config parity. Pure function of `pin` + the current
131/// process' env/HOME (the terminal's view), so `doctor` can compare an editor's
132/// baked pin against the CLI's own resolution without mutating env or spawning.
133pub(crate) fn data_pin_diverges_config(pin: &Path) -> bool {
134    !is_standard_xdg_data_dir(pin)
135}
136
137/// Filesystem half of [`single_dir_override`], parameterized for hermetic tests.
138fn single_dir_override_fs(
139    home: &Path,
140    xdg_config_base: &Path,
141    xdg_data_base: Option<&Path>,
142) -> Option<PathBuf> {
143    // A committed XDG install is the single source of truth: never re-collapse
144    // it onto a stray legacy/mixed data marker (GL #623). The pin lives next to
145    // the mixed probe below, so the two reads always agree on `xdg_config_base`.
146    if crate::core::layout_pin::is_xdg_pinned_in(xdg_config_base) {
147        return None;
148    }
149    let legacy = home.join(".lean-ctx");
150    if legacy.exists() && has_data_files(&legacy) {
151        return Some(legacy);
152    }
153    let mixed = xdg_config_base.join("lean-ctx");
154    if mixed.exists() && has_data_files(&mixed) {
155        // GL #623 follow-up: an already-split XDG install (real data under
156        // `$XDG_DATA_HOME/lean-ctx`) must NOT re-collapse config/state/cache/data
157        // onto the *config* dir just because a stray data marker leaked there
158        // (e.g. during an upgrade, before the layout pin is written). That would
159        // scatter stats/events/journal/sessions into `$XDG_CONFIG_HOME` and split
160        // history across two trees.
161        if let Some(data_base) = xdg_data_base
162            && has_data_files(&data_base.join("lean-ctx"))
163        {
164            return None;
165        }
166        return Some(mixed);
167    }
168    None
169}
170
171/// Shared resolver for the config/state/cache categories.
172fn category_dir(cat_env: &str, xdg_env: &str, home_fallback: &str) -> Result<PathBuf, String> {
173    let dir = resolve_category_dir(cat_env, xdg_env, home_fallback)?;
174    ensure_dir_permissions(&dir);
175    Ok(dir)
176}
177
178/// The same category identity, without creating or changing the resolved directory.
179// Under `#[cfg(test)]` the body always succeeds (returns the sandbox); the
180// fallible XDG resolution only runs in real builds.
181#[cfg_attr(test, allow(clippy::unnecessary_wraps))]
182fn resolve_category_dir(
183    cat_env: &str,
184    xdg_env: &str,
185    home_fallback: &str,
186) -> Result<PathBuf, String> {
187    let category_override = env_path(cat_env);
188
189    // A category override always wins, even under #[cfg(test)] — this lets the
190    // RO-config sandbox integration test point each category at a temp dir.
191    #[cfg(test)]
192    {
193        if let Some(p) = category_override {
194            return Ok(p);
195        }
196        // Unit tests share one per-process sandbox so stray store writes can't
197        // escape to a developer's real dirs. The branch logic itself is covered
198        // by the pure `resolve` / `single_dir_override_fs` tests below.
199        let _ = (xdg_env, home_fallback);
200        Ok(super::data_dir::test_sandbox_dir())
201    }
202    #[cfg(not(test))]
203    {
204        let base = xdg_base(xdg_env, home_fallback)?;
205        Ok(resolve(category_override, single_dir_override(), &base))
206    }
207}
208
209/// Config directory — `config.toml`, shell hooks, `env.sh`. RO-safe.
210/// Override: `LEAN_CTX_CONFIG_DIR`; default `$XDG_CONFIG_HOME/lean-ctx`.
211pub fn config_dir() -> Result<PathBuf, String> {
212    category_dir("LEAN_CTX_CONFIG_DIR", "XDG_CONFIG_HOME", ".config")
213}
214
215/// Resolve CONFIG without creating directories or repairing permissions.
216pub fn config_dir_read_only() -> Result<PathBuf, String> {
217    resolve_category_dir("LEAN_CTX_CONFIG_DIR", "XDG_CONFIG_HOME", ".config")
218}
219
220/// Resolve a member (a file or sub-directory) of the config dir, adopting a copy
221/// that older builds wrote under the OS-native `dirs::config_dir()` location.
222///
223/// Before #594 (A3), providers/personas/plugins/multi-repo config resolved via
224/// `dirs::config_dir()` — on macOS `~/Library/Application Support`, a *different*
225/// base than the `$XDG_CONFIG_HOME/lean-ctx` dir used for `config.toml`, so those
226/// features silently diverged from the main config. Routing them through
227/// [`config_dir`] unifies the base; this helper performs a one-time,
228/// non-destructive adoption so a user who already had config at the old path
229/// keeps it. The canonical location always wins — an existing canonical entry is
230/// never overwritten — and adoption is skipped entirely in tests so it can never
231/// touch a developer's real `~/Library/Application Support`.
232pub fn config_dir_member(sub: &str) -> Result<PathBuf, String> {
233    let canonical = config_dir()?.join(sub);
234    #[cfg(not(test))]
235    adopt_legacy_config_member(sub, &canonical);
236    Ok(canonical)
237}
238
239/// Decide whether a legacy config member should be adopted: only when the
240/// canonical entry is still absent, the legacy entry actually exists, and the two
241/// paths genuinely differ (on Linux the two bases coincide, making this a no-op).
242fn legacy_adoption_source(legacy: &Path, canonical: &Path) -> Option<PathBuf> {
243    if canonical.exists() || legacy == canonical || !legacy.exists() {
244        return None;
245    }
246    Some(legacy.to_path_buf())
247}
248
249/// Move `src` onto `dst` (file or directory). Prefers an atomic rename on the
250/// same filesystem; falls back to a recursive copy for the rare cross-device
251/// case so no config is ever left stranded. The caller guarantees `dst`'s parent
252/// exists.
253fn relocate(src: &Path, dst: &Path) -> std::io::Result<()> {
254    if std::fs::rename(src, dst).is_ok() {
255        return Ok(());
256    }
257    if src.is_dir() {
258        std::fs::create_dir_all(dst)?;
259        for entry in std::fs::read_dir(src)? {
260            let entry = entry?;
261            relocate(&entry.path(), &dst.join(entry.file_name()))?;
262        }
263        std::fs::remove_dir_all(src)?;
264    } else {
265        std::fs::copy(src, dst)?;
266        std::fs::remove_file(src)?;
267    }
268    Ok(())
269}
270
271/// One-time adoption of a legacy `dirs::config_dir()/lean-ctx/<sub>` member into
272/// the canonical config dir. Best-effort: any IO failure leaves the legacy copy
273/// in place and resolution simply proceeds against the canonical path.
274#[cfg(not(test))]
275fn adopt_legacy_config_member(sub: &str, canonical: &Path) {
276    let Some(legacy_base) = dirs::config_dir() else {
277        return;
278    };
279    let legacy = legacy_base.join("lean-ctx").join(sub);
280    let Some(src) = legacy_adoption_source(&legacy, canonical) else {
281        return;
282    };
283    if let Some(parent) = canonical.parent()
284        && std::fs::create_dir_all(parent).is_err()
285    {
286        return;
287    }
288    let _ = relocate(&src, canonical);
289}
290
291/// Data directory — sessions, vectors, graphs, knowledge, archives, memory.
292///
293/// Delegates to [`lean_ctx_data_dir`], which since GL #606 defaults fresh
294/// installs to `$XDG_DATA_HOME/lean-ctx`. Legacy `~/.lean-ctx` and pre-split
295/// mixed `$XDG_CONFIG_HOME/lean-ctx` installs (and an explicit
296/// `LEAN_CTX_DATA_DIR`) continue to resolve in place for backward compatibility.
297pub fn data_dir() -> Result<PathBuf, String> {
298    lean_ctx_data_dir()
299}
300
301/// State directory — events, stats, logs, journals, ledgers, captured keys.
302/// Override: `LEAN_CTX_STATE_DIR`; default `$XDG_STATE_HOME/lean-ctx`.
303pub fn state_dir() -> Result<PathBuf, String> {
304    category_dir("LEAN_CTX_STATE_DIR", "XDG_STATE_HOME", ".local/state")
305}
306
307/// Resolve STATE without creating directories or repairing permissions.
308pub(crate) fn state_dir_read_only() -> Result<PathBuf, String> {
309    resolve_category_dir("LEAN_CTX_STATE_DIR", "XDG_STATE_HOME", ".local/state")
310}
311
312/// Cache directory — semantic cache, models, learned patterns. tmpfs-safe.
313/// Override: `LEAN_CTX_CACHE_DIR`; default `$XDG_CACHE_HOME/lean-ctx`.
314pub fn cache_dir() -> Result<PathBuf, String> {
315    category_dir("LEAN_CTX_CACHE_DIR", "XDG_CACHE_HOME", ".cache")
316}
317
318/// Resolve CACHE without creating directories or repairing permissions.
319pub(crate) fn cache_dir_read_only() -> Result<PathBuf, String> {
320    resolve_category_dir("LEAN_CTX_CACHE_DIR", "XDG_CACHE_HOME", ".cache")
321}
322
323/// Runtime directory — `daemon.pid`, `daemon.sock`. `$XDG_RUNTIME_DIR/lean-ctx`.
324///
325/// When `XDG_RUNTIME_DIR` is unset (common on macOS), falls back to
326/// [`state_dir`] so runtime files stay in a private, writable, non-config path
327/// rather than a world-readable temp location.
328pub fn runtime_dir() -> Result<PathBuf, String> {
329    if let Some(base) = env_path("XDG_RUNTIME_DIR") {
330        return Ok(base.join("lean-ctx"));
331    }
332    state_dir()
333}
334
335/// Raw per-category target dir for the four XDG categories, **bypassing**
336/// single-dir back-compat and the test sandbox. Honors an explicit
337/// `LEAN_CTX_<CAT>_DIR` override, otherwise `<XDG base>/lean-ctx`.
338///
339/// `category_dir`/[`data_dir`] deliberately collapse onto one directory for a
340/// legacy/mixed install; the `doctor --fix` migration (GH #408) needs to know
341/// where each category SHOULD live *after* a split, which is what this returns.
342fn raw_category_dir(cat_env: &str, xdg_env: &str, home_fallback: &str) -> Result<PathBuf, String> {
343    if let Some(p) = env_path(cat_env) {
344        return Ok(p);
345    }
346    Ok(xdg_base(xdg_env, home_fallback)?.join("lean-ctx"))
347}
348
349/// Split target for the config category (`$XDG_CONFIG_HOME/lean-ctx`).
350pub(crate) fn config_split_target() -> Result<PathBuf, String> {
351    raw_category_dir("LEAN_CTX_CONFIG_DIR", "XDG_CONFIG_HOME", ".config")
352}
353
354/// `$XDG_CONFIG_HOME/lean-ctx` (or `~/.config/lean-ctx`) — where `config.toml`
355/// and the layout pin (`layout.toml`) live. Resolved through the XDG config base
356/// only, bypassing single-dir collapse, so the pin that governs that collapse
357/// never depends on it (GL #623). `None` only when HOME cannot be determined.
358pub(crate) fn xdg_config_lean_ctx_dir() -> Option<PathBuf> {
359    xdg_base("XDG_CONFIG_HOME", ".config")
360        .ok()
361        .map(|b| b.join("lean-ctx"))
362}
363
364/// Split target for the data category (`$XDG_DATA_HOME/lean-ctx`).
365pub(crate) fn data_split_target() -> Result<PathBuf, String> {
366    raw_category_dir("LEAN_CTX_DATA_DIR", "XDG_DATA_HOME", ".local/share")
367}
368
369/// Resolve DATA without creating directories or repairing permissions.
370pub fn data_dir_read_only() -> Result<PathBuf, String> {
371    raw_category_dir("LEAN_CTX_DATA_DIR", "XDG_DATA_HOME", ".local/share")
372}
373
374/// Split target for the state category (`$XDG_STATE_HOME/lean-ctx`).
375pub(crate) fn state_split_target() -> Result<PathBuf, String> {
376    raw_category_dir("LEAN_CTX_STATE_DIR", "XDG_STATE_HOME", ".local/state")
377}
378
379/// Split target for the cache category (`$XDG_CACHE_HOME/lean-ctx`).
380pub(crate) fn cache_split_target() -> Result<PathBuf, String> {
381    raw_category_dir("LEAN_CTX_CACHE_DIR", "XDG_CACHE_HOME", ".cache")
382}
383
384#[cfg(test)]
385mod tests {
386    use super::*;
387
388    #[test]
389    fn resolve_prefers_override_then_single_then_xdg() {
390        let over = PathBuf::from("/over/ride");
391        let single = PathBuf::from("/single/dir");
392        let base = PathBuf::from("/xdg/base");
393
394        assert_eq!(
395            resolve(Some(over.clone()), Some(single.clone()), &base),
396            over
397        );
398        assert_eq!(resolve(None, Some(single.clone()), &base), single);
399        assert_eq!(
400            resolve(None, None, &base),
401            PathBuf::from("/xdg/base/lean-ctx")
402        );
403    }
404
405    #[test]
406    fn single_dir_fs_detects_legacy_with_data() {
407        let home = tempfile::tempdir().unwrap();
408        let xdg = tempfile::tempdir().unwrap();
409        let legacy = home.path().join(".lean-ctx");
410        std::fs::create_dir_all(&legacy).unwrap();
411        std::fs::write(legacy.join("stats.json"), "{}").unwrap();
412
413        assert_eq!(
414            single_dir_override_fs(home.path(), xdg.path(), None),
415            Some(legacy)
416        );
417    }
418
419    #[test]
420    fn single_dir_fs_detects_mixed_with_data() {
421        let home = tempfile::tempdir().unwrap();
422        let xdg = tempfile::tempdir().unwrap();
423        let mixed = xdg.path().join("lean-ctx");
424        std::fs::create_dir_all(&mixed).unwrap();
425        // A real data marker (stats.json) — NOT config.toml, which post-split
426        // lives alone in the config dir and must not trigger single-dir mode.
427        std::fs::write(mixed.join("stats.json"), "{}").unwrap();
428
429        assert_eq!(
430            single_dir_override_fs(home.path(), xdg.path(), None),
431            Some(mixed)
432        );
433    }
434
435    #[test]
436    fn single_dir_fs_ignores_config_only_dir() {
437        // GH #408: a clean post-split config dir (only config.toml + hooks) must
438        // NOT collapse the four-dir layout.
439        let home = tempfile::tempdir().unwrap();
440        let xdg = tempfile::tempdir().unwrap();
441        let mixed = xdg.path().join("lean-ctx");
442        std::fs::create_dir_all(&mixed).unwrap();
443        std::fs::write(mixed.join("config.toml"), "").unwrap();
444        std::fs::write(mixed.join("shell-hook.zsh"), "").unwrap();
445
446        assert_eq!(single_dir_override_fs(home.path(), xdg.path(), None), None);
447    }
448
449    #[test]
450    fn single_dir_fs_prefers_legacy_over_mixed() {
451        let home = tempfile::tempdir().unwrap();
452        let xdg = tempfile::tempdir().unwrap();
453        let legacy = home.path().join(".lean-ctx");
454        std::fs::create_dir_all(&legacy).unwrap();
455        std::fs::write(legacy.join("sessions"), "x").unwrap();
456        let mixed = xdg.path().join("lean-ctx");
457        std::fs::create_dir_all(&mixed).unwrap();
458        std::fs::write(mixed.join("stats.json"), "{}").unwrap();
459
460        assert_eq!(
461            single_dir_override_fs(home.path(), xdg.path(), None),
462            Some(legacy)
463        );
464    }
465
466    #[test]
467    fn xdg_pinned_install_ignores_stray_legacy_marker() {
468        // GL #623: once committed to XDG (pin in the config dir), a stray
469        // `~/.lean-ctx/stats.json` (legacy residue, restored backup, concurrent
470        // old binary) must NOT re-collapse the layout onto the legacy dir.
471        let home = tempfile::tempdir().unwrap();
472        let xdg = tempfile::tempdir().unwrap();
473        crate::core::layout_pin::write_xdg_pin_in(xdg.path()).unwrap();
474
475        let legacy = home.path().join(".lean-ctx");
476        std::fs::create_dir_all(&legacy).unwrap();
477        std::fs::write(legacy.join("stats.json"), "{}").unwrap();
478
479        assert_eq!(single_dir_override_fs(home.path(), xdg.path(), None), None);
480    }
481
482    #[test]
483    fn xdg_pinned_install_ignores_stray_mixed_marker() {
484        // GL #623: same protection for a stray data marker that lands in the
485        // mixed `$XDG_CONFIG_HOME/lean-ctx` dir after the install committed.
486        let home = tempfile::tempdir().unwrap();
487        let xdg = tempfile::tempdir().unwrap();
488        crate::core::layout_pin::write_xdg_pin_in(xdg.path()).unwrap();
489
490        let mixed = xdg.path().join("lean-ctx");
491        std::fs::write(mixed.join("stats.json"), "{}").unwrap();
492
493        assert_eq!(single_dir_override_fs(home.path(), xdg.path(), None), None);
494    }
495
496    #[test]
497    fn split_install_ignores_stray_mixed_marker_when_xdg_data_present() {
498        // Regression: an XDG-split install with real data under
499        // `$XDG_DATA_HOME/lean-ctx` must not re-collapse onto the config dir just
500        // because a stray marker leaked into `$XDG_CONFIG_HOME/lean-ctx` before
501        // the layout pin was written (the upgrade window). Without the guard this
502        // scattered stats/events/journal/sessions into the config dir and split
503        // history across two trees.
504        let home = tempfile::tempdir().unwrap();
505        let xdg_config = tempfile::tempdir().unwrap();
506        let xdg_data = tempfile::tempdir().unwrap();
507
508        let mixed = xdg_config.path().join("lean-ctx");
509        std::fs::create_dir_all(&mixed).unwrap();
510        std::fs::write(mixed.join("stats.json"), "{}").unwrap();
511
512        let data = xdg_data.path().join("lean-ctx");
513        std::fs::create_dir_all(&data).unwrap();
514        std::fs::write(data.join("stats.json"), "{}").unwrap();
515
516        assert_eq!(
517            single_dir_override_fs(home.path(), xdg_config.path(), Some(xdg_data.path())),
518            None,
519            "a populated XDG data dir must keep the config dir from collapsing"
520        );
521
522        // With no real data dir the stray marker still collapses (legacy
523        // single-dir semantics preserved).
524        let empty_data = tempfile::tempdir().unwrap();
525        assert_eq!(
526            single_dir_override_fs(home.path(), xdg_config.path(), Some(empty_data.path())),
527            Some(mixed)
528        );
529    }
530
531    #[test]
532    fn single_dir_fs_ignores_empty_dirs() {
533        let home = tempfile::tempdir().unwrap();
534        let xdg = tempfile::tempdir().unwrap();
535        std::fs::create_dir_all(home.path().join(".lean-ctx")).unwrap();
536        std::fs::create_dir_all(xdg.path().join("lean-ctx")).unwrap();
537
538        assert_eq!(single_dir_override_fs(home.path(), xdg.path(), None), None);
539    }
540
541    #[test]
542    fn single_dir_fs_ignores_non_marker_files() {
543        let home = tempfile::tempdir().unwrap();
544        let xdg = tempfile::tempdir().unwrap();
545        let mixed = xdg.path().join("lean-ctx");
546        std::fs::create_dir_all(&mixed).unwrap();
547        std::fs::write(mixed.join("random.txt"), "x").unwrap();
548
549        assert_eq!(single_dir_override_fs(home.path(), xdg.path(), None), None);
550    }
551
552    #[test]
553    fn xdg_base_honors_env_then_home_fallback() {
554        let _lock = crate::core::data_dir::test_env_lock();
555        let tmp = tempfile::tempdir().unwrap();
556        crate::test_env::set_var("XDG_CONFIG_HOME", tmp.path());
557        let from_env = xdg_base("XDG_CONFIG_HOME", ".config").unwrap();
558        crate::test_env::remove_var("XDG_CONFIG_HOME");
559        assert_eq!(from_env, tmp.path());
560
561        // Unset var → falls back to $HOME/<home_fallback>.
562        let fallback = xdg_base("LEAN_CTX_NONEXISTENT_XDG_VAR", ".cache").unwrap();
563        assert!(fallback.ends_with(".cache"), "got: {}", fallback.display());
564    }
565
566    #[test]
567    fn legacy_adoption_source_only_when_canonical_absent() {
568        let tmp = tempfile::tempdir().unwrap();
569        let legacy = tmp.path().join("legacy");
570        let canonical = tmp.path().join("canonical");
571
572        // Legacy missing → nothing to adopt.
573        assert_eq!(legacy_adoption_source(&legacy, &canonical), None);
574
575        // Legacy present, canonical absent → adopt the legacy copy.
576        std::fs::create_dir_all(&legacy).unwrap();
577        assert_eq!(
578            legacy_adoption_source(&legacy, &canonical),
579            Some(legacy.clone())
580        );
581
582        // Canonical present → the newer location wins, never overwrite it.
583        std::fs::create_dir_all(&canonical).unwrap();
584        assert_eq!(legacy_adoption_source(&legacy, &canonical), None);
585    }
586
587    #[test]
588    fn relocate_moves_file_then_directory() {
589        let tmp = tempfile::tempdir().unwrap();
590
591        // File: dst parent must be created by the caller (as adopt does).
592        let src_file = tmp.path().join("providers.toml");
593        std::fs::write(&src_file, "id = \"x\"\n").unwrap();
594        let dst_file = tmp.path().join("config/lean-ctx/providers.toml");
595        std::fs::create_dir_all(dst_file.parent().unwrap()).unwrap();
596        relocate(&src_file, &dst_file).unwrap();
597        assert!(!src_file.exists(), "source file must be moved, not copied");
598        assert_eq!(std::fs::read_to_string(&dst_file).unwrap(), "id = \"x\"\n");
599
600        // Directory with nested content.
601        let src_dir = tmp.path().join("personas");
602        std::fs::create_dir_all(src_dir.join("nested")).unwrap();
603        std::fs::write(src_dir.join("a.toml"), "a").unwrap();
604        std::fs::write(src_dir.join("nested/b.toml"), "b").unwrap();
605        let dst_dir = tmp.path().join("config/lean-ctx/personas");
606        std::fs::create_dir_all(dst_dir.parent().unwrap()).unwrap();
607        relocate(&src_dir, &dst_dir).unwrap();
608        assert!(!src_dir.exists(), "source dir must be moved");
609        assert_eq!(
610            std::fs::read_to_string(dst_dir.join("a.toml")).unwrap(),
611            "a"
612        );
613        assert_eq!(
614            std::fs::read_to_string(dst_dir.join("nested/b.toml")).unwrap(),
615            "b"
616        );
617    }
618
619    #[test]
620    fn single_dir_override_honors_data_dir_env() {
621        let _lock = crate::core::data_dir::test_env_lock();
622        let tmp = tempfile::tempdir().unwrap();
623        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
624        let got = single_dir_override();
625        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
626        // A custom (non-standard) data dir is a deliberate single-dir choice.
627        assert_eq!(got, Some(tmp.path().to_path_buf()));
628    }
629
630    #[test]
631    fn is_standard_xdg_data_dir_matches_xdg_data_home() {
632        let _lock = crate::core::data_dir::test_env_lock();
633        let data_home = tempfile::tempdir().unwrap();
634        crate::test_env::set_var("XDG_DATA_HOME", data_home.path());
635        let is_std = is_standard_xdg_data_dir(&data_home.path().join("lean-ctx"));
636        let is_custom = is_standard_xdg_data_dir(Path::new("/some/custom/lean-ctx"));
637        crate::test_env::remove_var("XDG_DATA_HOME");
638        assert!(is_std, "$XDG_DATA_HOME/lean-ctx is the standard data dir");
639        assert!(!is_custom, "a custom path is not the standard data dir");
640    }
641
642    #[test]
643    fn standard_data_pin_does_not_collapse_categories() {
644        // #594: an editor (MCP env) that pins LEAN_CTX_DATA_DIR to the *standard*
645        // XDG data dir must NOT drag config/state/cache along — single_dir_override
646        // must return None so they keep their own XDG bases, matching the CLI.
647        let _lock = crate::core::data_dir::test_env_lock();
648        let home = tempfile::tempdir().unwrap();
649        let xdg_config = tempfile::tempdir().unwrap();
650        let xdg_data = tempfile::tempdir().unwrap();
651        let data_pin = xdg_data.path().join("lean-ctx");
652        crate::test_env::set_var("HOME", home.path());
653        crate::test_env::set_var("XDG_CONFIG_HOME", xdg_config.path());
654        crate::test_env::set_var("XDG_DATA_HOME", xdg_data.path());
655        crate::test_env::set_var("LEAN_CTX_DATA_DIR", &data_pin);
656
657        let got = single_dir_override();
658
659        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
660        crate::test_env::remove_var("XDG_DATA_HOME");
661        crate::test_env::remove_var("XDG_CONFIG_HOME");
662        crate::test_env::remove_var("HOME");
663
664        assert_eq!(got, None);
665    }
666
667    #[test]
668    fn config_dir_honors_explicit_override() {
669        let _lock = crate::core::data_dir::test_env_lock();
670        let tmp = tempfile::tempdir().unwrap();
671        crate::test_env::set_var("LEAN_CTX_CONFIG_DIR", tmp.path());
672        let got = config_dir().unwrap();
673        crate::test_env::remove_var("LEAN_CTX_CONFIG_DIR");
674        assert_eq!(got, tmp.path());
675    }
676
677    #[test]
678    fn state_and_cache_dirs_honor_explicit_overrides() {
679        let _lock = crate::core::data_dir::test_env_lock();
680        let state = tempfile::tempdir().unwrap();
681        let cache = tempfile::tempdir().unwrap();
682        crate::test_env::set_var("LEAN_CTX_STATE_DIR", state.path());
683        crate::test_env::set_var("LEAN_CTX_CACHE_DIR", cache.path());
684        let got_state = state_dir().unwrap();
685        let got_cache = cache_dir().unwrap();
686        crate::test_env::remove_var("LEAN_CTX_STATE_DIR");
687        crate::test_env::remove_var("LEAN_CTX_CACHE_DIR");
688        assert_eq!(got_state, state.path());
689        assert_eq!(got_cache, cache.path());
690    }
691
692    #[test]
693    fn data_dir_matches_lean_ctx_data_dir() {
694        let _guard = crate::core::data_dir::isolated_data_dir();
695        assert_eq!(
696            data_dir().unwrap(),
697            crate::core::data_dir::lean_ctx_data_dir().unwrap()
698        );
699    }
700
701    #[test]
702    fn runtime_dir_honors_xdg_runtime_dir() {
703        let _lock = crate::core::data_dir::test_env_lock();
704        let tmp = tempfile::tempdir().unwrap();
705        crate::test_env::set_var("XDG_RUNTIME_DIR", tmp.path());
706        let got = runtime_dir().unwrap();
707        crate::test_env::remove_var("XDG_RUNTIME_DIR");
708        assert_eq!(got, tmp.path().join("lean-ctx"));
709    }
710}