lean-ctx 3.9.3

Context Runtime for AI Agents with CCP. 71 MCP tools, 10 read modes, 95+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing, LITM-aware positioning, AAAK compact format, adaptive compression with Thompson Sampling bandits. Supports 24+ AI tools. Reduces LLM token consumption by up to 99%.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! Typed XDG base-directory resolvers for lean-ctx (GH #408 / GL #602).
//!
//! Historically every lean-ctx file joined onto a single [`lean_ctx_data_dir`]
//! rooted at `$XDG_CONFIG_HOME/lean-ctx`, mixing `config.toml` with 30+ runtime
//! data files (sessions, vectors, graphs, events, logs, caches). That violates
//! the XDG Base Directory Spec and makes a read-only config sandbox impossible.
//!
//! This module introduces one typed resolver per XDG category so call-sites can
//! migrate to the correct base over the following phases (GL #603/#604/#606/#607).
//!
//! ## Backward compatibility (single-dir mode)
//!
//! Existing installs MUST NOT split silently. `single_dir_override` returns
//! `Some(dir)` when `LEAN_CTX_DATA_DIR` is set or a legacy/mixed install with
//! data exists; in that case every category resolves to that one directory —
//! byte-for-byte today's behavior. The real per-category split only applies to
//! fresh installs (and, later, on-demand via `lean-ctx doctor --fix`).
//!
//! ## `data_dir()` and the fresh-install flip
//!
//! [`data_dir`] delegates to [`lean_ctx_data_dir`]. Config (`config.toml` +
//! hooks) and the runtime STATE/CACHE files were migrated onto [`config_dir`],
//! [`state_dir`] and [`cache_dir`] (GL #603/#604) so that, since GL #606, the
//! data resolver defaults fresh installs to `$XDG_DATA_HOME/lean-ctx` without
//! scattering config or state into the data dir. Legacy and pre-split mixed
//! installs keep resolving every category to their existing single directory.
//!
//! Determinism (#498): every resolver is a pure function of environment + HOME;
//! no timestamps, counters or randomness.

use std::path::{Path, PathBuf};

use super::data_dir::{ensure_dir_permissions, has_data_files, lean_ctx_data_dir};

/// Reads a directory path from `name`, treating empty/whitespace as unset.
fn env_path(name: &str) -> Option<PathBuf> {
    std::env::var(name)
        .ok()
        .map(|v| v.trim().to_string())
        .filter(|v| !v.is_empty())
        .map(PathBuf::from)
}

/// Resolves an XDG base directory (e.g. `~/.config`), honoring the `env_name`
/// override and falling back to `$HOME/<home_fallback>`. Returns the base only;
/// callers append `lean-ctx`.
fn xdg_base(env_name: &str, home_fallback: &str) -> Result<PathBuf, String> {
    if let Some(p) = env_path(env_name) {
        return Ok(p);
    }
    dirs::home_dir()
        .map(|h| h.join(home_fallback))
        .ok_or_else(|| "Cannot determine home directory".to_string())
}

/// Pure resolution order for a category: explicit override > single-dir
/// backward-compat > XDG split default (`<base>/lean-ctx`).
fn resolve(
    category_override: Option<PathBuf>,
    single: Option<PathBuf>,
    xdg_base_dir: &Path,
) -> PathBuf {
    category_override
        .or(single)
        .unwrap_or_else(|| xdg_base_dir.join("lean-ctx"))
}

/// Returns the single directory that ALL categories must collapse onto for
/// backward compatibility, or `None` for a fresh install that may split.
///
/// `Some` when an *explicit* `LEAN_CTX_DATA_DIR` points at a non-standard
/// location (a deliberate single-dir choice: a custom dir, or `~/.lean-ctx` via
/// env), or a legacy `~/.lean-ctx` / mixed `$XDG_CONFIG_HOME/lean-ctx` install
/// already holds data. An empty directory does NOT trigger single-dir mode
/// (matches [`lean_ctx_data_dir`] semantics).
///
/// A `LEAN_CTX_DATA_DIR` equal to the *standard* XDG data dir
/// (`$XDG_DATA_HOME/lean-ctx`) is a DATA pin only, NOT a single-dir directive:
/// editors used to bake that exact value into the MCP server's `env`, and
/// honoring it as single-dir collapsed config/state/cache onto the data dir for
/// the MCP process while the terminal CLI kept the XDG split — so the two read
/// different `config.toml` files (#594). Falling through keeps config in
/// `$XDG_CONFIG_HOME/lean-ctx` for both; data still resolves to the pin via
/// [`lean_ctx_data_dir`], which consumes the env var before reaching here.
pub(crate) fn single_dir_override() -> Option<PathBuf> {
    if let Some(p) = env_path("LEAN_CTX_DATA_DIR")
        && !is_standard_xdg_data_dir(&p)
    {
        return Some(p);
    }
    let home = dirs::home_dir()?;
    let xdg_config_base = xdg_base("XDG_CONFIG_HOME", ".config").ok()?;
    single_dir_override_fs(&home, &xdg_config_base)
}

/// True when `p` is exactly the standard XDG data dir (`$XDG_DATA_HOME/lean-ctx`,
/// default `~/.local/share/lean-ctx`). Pure function of env + HOME (no filesystem
/// access) so category resolution stays deterministic (#498).
fn is_standard_xdg_data_dir(p: &Path) -> bool {
    xdg_base("XDG_DATA_HOME", ".local/share")
        .map(|base| base.join("lean-ctx"))
        .is_ok_and(|standard| standard.as_path() == p)
}

/// Whether an editor-baked `LEAN_CTX_DATA_DIR` value (`pin`) would make that
/// editor's MCP server resolve a *different* `config.toml` than the terminal
/// CLI. Only a **non-standard** pin collapses config/state/cache onto the data
/// dir (#594); a pin equal to the standard `$XDG_DATA_HOME/lean-ctx` is a
/// data-only pin and keeps config parity. Pure function of `pin` + the current
/// process' env/HOME (the terminal's view), so `doctor` can compare an editor's
/// baked pin against the CLI's own resolution without mutating env or spawning.
pub(crate) fn data_pin_diverges_config(pin: &Path) -> bool {
    !is_standard_xdg_data_dir(pin)
}

/// Filesystem half of [`single_dir_override`], parameterized for hermetic tests.
fn single_dir_override_fs(home: &Path, xdg_config_base: &Path) -> Option<PathBuf> {
    // A committed XDG install is the single source of truth: never re-collapse
    // it onto a stray legacy/mixed data marker (GL #623). The pin lives next to
    // the mixed probe below, so the two reads always agree on `xdg_config_base`.
    if crate::core::layout_pin::is_xdg_pinned_in(xdg_config_base) {
        return None;
    }
    let legacy = home.join(".lean-ctx");
    if legacy.exists() && has_data_files(&legacy) {
        return Some(legacy);
    }
    let mixed = xdg_config_base.join("lean-ctx");
    if mixed.exists() && has_data_files(&mixed) {
        return Some(mixed);
    }
    None
}

/// Shared resolver for the config/state/cache categories.
// Under `#[cfg(test)]` the body always succeeds (returns the sandbox); the
// fallible XDG resolution only runs in real builds.
#[cfg_attr(test, allow(clippy::unnecessary_wraps))]
fn category_dir(cat_env: &str, xdg_env: &str, home_fallback: &str) -> Result<PathBuf, String> {
    let category_override = env_path(cat_env);

    // A category override always wins, even under #[cfg(test)] — this lets the
    // RO-config sandbox integration test point each category at a temp dir.
    #[cfg(test)]
    {
        if let Some(p) = category_override {
            ensure_dir_permissions(&p);
            return Ok(p);
        }
        // Unit tests share one per-process sandbox so stray store writes can't
        // escape to a developer's real dirs. The branch logic itself is covered
        // by the pure `resolve` / `single_dir_override_fs` tests below.
        let _ = (xdg_env, home_fallback);
        Ok(super::data_dir::test_sandbox_dir())
    }
    #[cfg(not(test))]
    {
        let base = xdg_base(xdg_env, home_fallback)?;
        let dir = resolve(category_override, single_dir_override(), &base);
        ensure_dir_permissions(&dir);
        Ok(dir)
    }
}

/// Config directory — `config.toml`, shell hooks, `env.sh`. RO-safe.
/// Override: `LEAN_CTX_CONFIG_DIR`; default `$XDG_CONFIG_HOME/lean-ctx`.
pub fn config_dir() -> Result<PathBuf, String> {
    category_dir("LEAN_CTX_CONFIG_DIR", "XDG_CONFIG_HOME", ".config")
}

/// Resolve a member (a file or sub-directory) of the config dir, adopting a copy
/// that older builds wrote under the OS-native `dirs::config_dir()` location.
///
/// Before #594 (A3), providers/personas/plugins/multi-repo config resolved via
/// `dirs::config_dir()` — on macOS `~/Library/Application Support`, a *different*
/// base than the `$XDG_CONFIG_HOME/lean-ctx` dir used for `config.toml`, so those
/// features silently diverged from the main config. Routing them through
/// [`config_dir`] unifies the base; this helper performs a one-time,
/// non-destructive adoption so a user who already had config at the old path
/// keeps it. The canonical location always wins — an existing canonical entry is
/// never overwritten — and adoption is skipped entirely in tests so it can never
/// touch a developer's real `~/Library/Application Support`.
pub fn config_dir_member(sub: &str) -> Result<PathBuf, String> {
    let canonical = config_dir()?.join(sub);
    #[cfg(not(test))]
    adopt_legacy_config_member(sub, &canonical);
    Ok(canonical)
}

/// Decide whether a legacy config member should be adopted: only when the
/// canonical entry is still absent, the legacy entry actually exists, and the two
/// paths genuinely differ (on Linux the two bases coincide, making this a no-op).
fn legacy_adoption_source(legacy: &Path, canonical: &Path) -> Option<PathBuf> {
    if canonical.exists() || legacy == canonical || !legacy.exists() {
        return None;
    }
    Some(legacy.to_path_buf())
}

/// Move `src` onto `dst` (file or directory). Prefers an atomic rename on the
/// same filesystem; falls back to a recursive copy for the rare cross-device
/// case so no config is ever left stranded. The caller guarantees `dst`'s parent
/// exists.
fn relocate(src: &Path, dst: &Path) -> std::io::Result<()> {
    if std::fs::rename(src, dst).is_ok() {
        return Ok(());
    }
    if src.is_dir() {
        std::fs::create_dir_all(dst)?;
        for entry in std::fs::read_dir(src)? {
            let entry = entry?;
            relocate(&entry.path(), &dst.join(entry.file_name()))?;
        }
        std::fs::remove_dir_all(src)?;
    } else {
        std::fs::copy(src, dst)?;
        std::fs::remove_file(src)?;
    }
    Ok(())
}

/// One-time adoption of a legacy `dirs::config_dir()/lean-ctx/<sub>` member into
/// the canonical config dir. Best-effort: any IO failure leaves the legacy copy
/// in place and resolution simply proceeds against the canonical path.
#[cfg(not(test))]
fn adopt_legacy_config_member(sub: &str, canonical: &Path) {
    let Some(legacy_base) = dirs::config_dir() else {
        return;
    };
    let legacy = legacy_base.join("lean-ctx").join(sub);
    let Some(src) = legacy_adoption_source(&legacy, canonical) else {
        return;
    };
    if let Some(parent) = canonical.parent()
        && std::fs::create_dir_all(parent).is_err()
    {
        return;
    }
    let _ = relocate(&src, canonical);
}

/// Data directory — sessions, vectors, graphs, knowledge, archives, memory.
///
/// Delegates to [`lean_ctx_data_dir`], which since GL #606 defaults fresh
/// installs to `$XDG_DATA_HOME/lean-ctx`. Legacy `~/.lean-ctx` and pre-split
/// mixed `$XDG_CONFIG_HOME/lean-ctx` installs (and an explicit
/// `LEAN_CTX_DATA_DIR`) continue to resolve in place for backward compatibility.
pub fn data_dir() -> Result<PathBuf, String> {
    lean_ctx_data_dir()
}

/// State directory — events, stats, logs, journals, ledgers, captured keys.
/// Override: `LEAN_CTX_STATE_DIR`; default `$XDG_STATE_HOME/lean-ctx`.
pub fn state_dir() -> Result<PathBuf, String> {
    category_dir("LEAN_CTX_STATE_DIR", "XDG_STATE_HOME", ".local/state")
}

/// Cache directory — semantic cache, models, learned patterns. tmpfs-safe.
/// Override: `LEAN_CTX_CACHE_DIR`; default `$XDG_CACHE_HOME/lean-ctx`.
pub fn cache_dir() -> Result<PathBuf, String> {
    category_dir("LEAN_CTX_CACHE_DIR", "XDG_CACHE_HOME", ".cache")
}

/// Runtime directory — `daemon.pid`, `daemon.sock`. `$XDG_RUNTIME_DIR/lean-ctx`.
///
/// When `XDG_RUNTIME_DIR` is unset (common on macOS), falls back to
/// [`state_dir`] so runtime files stay in a private, writable, non-config path
/// rather than a world-readable temp location.
pub fn runtime_dir() -> Result<PathBuf, String> {
    if let Some(base) = env_path("XDG_RUNTIME_DIR") {
        return Ok(base.join("lean-ctx"));
    }
    state_dir()
}

/// Raw per-category target dir for the four XDG categories, **bypassing**
/// single-dir back-compat and the test sandbox. Honors an explicit
/// `LEAN_CTX_<CAT>_DIR` override, otherwise `<XDG base>/lean-ctx`.
///
/// `category_dir`/[`data_dir`] deliberately collapse onto one directory for a
/// legacy/mixed install; the `doctor --fix` migration (GH #408) needs to know
/// where each category SHOULD live *after* a split, which is what this returns.
fn raw_category_dir(cat_env: &str, xdg_env: &str, home_fallback: &str) -> Result<PathBuf, String> {
    if let Some(p) = env_path(cat_env) {
        return Ok(p);
    }
    Ok(xdg_base(xdg_env, home_fallback)?.join("lean-ctx"))
}

/// Split target for the config category (`$XDG_CONFIG_HOME/lean-ctx`).
pub(crate) fn config_split_target() -> Result<PathBuf, String> {
    raw_category_dir("LEAN_CTX_CONFIG_DIR", "XDG_CONFIG_HOME", ".config")
}

/// `$XDG_CONFIG_HOME/lean-ctx` (or `~/.config/lean-ctx`) — where `config.toml`
/// and the layout pin (`layout.toml`) live. Resolved through the XDG config base
/// only, bypassing single-dir collapse, so the pin that governs that collapse
/// never depends on it (GL #623). `None` only when HOME cannot be determined.
pub(crate) fn xdg_config_lean_ctx_dir() -> Option<PathBuf> {
    xdg_base("XDG_CONFIG_HOME", ".config")
        .ok()
        .map(|b| b.join("lean-ctx"))
}

/// Split target for the data category (`$XDG_DATA_HOME/lean-ctx`).
pub(crate) fn data_split_target() -> Result<PathBuf, String> {
    raw_category_dir("LEAN_CTX_DATA_DIR", "XDG_DATA_HOME", ".local/share")
}

/// Split target for the state category (`$XDG_STATE_HOME/lean-ctx`).
pub(crate) fn state_split_target() -> Result<PathBuf, String> {
    raw_category_dir("LEAN_CTX_STATE_DIR", "XDG_STATE_HOME", ".local/state")
}

/// Split target for the cache category (`$XDG_CACHE_HOME/lean-ctx`).
pub(crate) fn cache_split_target() -> Result<PathBuf, String> {
    raw_category_dir("LEAN_CTX_CACHE_DIR", "XDG_CACHE_HOME", ".cache")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn resolve_prefers_override_then_single_then_xdg() {
        let over = PathBuf::from("/over/ride");
        let single = PathBuf::from("/single/dir");
        let base = PathBuf::from("/xdg/base");

        assert_eq!(
            resolve(Some(over.clone()), Some(single.clone()), &base),
            over
        );
        assert_eq!(resolve(None, Some(single.clone()), &base), single);
        assert_eq!(
            resolve(None, None, &base),
            PathBuf::from("/xdg/base/lean-ctx")
        );
    }

    #[test]
    fn single_dir_fs_detects_legacy_with_data() {
        let home = tempfile::tempdir().unwrap();
        let xdg = tempfile::tempdir().unwrap();
        let legacy = home.path().join(".lean-ctx");
        std::fs::create_dir_all(&legacy).unwrap();
        std::fs::write(legacy.join("stats.json"), "{}").unwrap();

        assert_eq!(
            single_dir_override_fs(home.path(), xdg.path()),
            Some(legacy)
        );
    }

    #[test]
    fn single_dir_fs_detects_mixed_with_data() {
        let home = tempfile::tempdir().unwrap();
        let xdg = tempfile::tempdir().unwrap();
        let mixed = xdg.path().join("lean-ctx");
        std::fs::create_dir_all(&mixed).unwrap();
        // A real data marker (stats.json) — NOT config.toml, which post-split
        // lives alone in the config dir and must not trigger single-dir mode.
        std::fs::write(mixed.join("stats.json"), "{}").unwrap();

        assert_eq!(single_dir_override_fs(home.path(), xdg.path()), Some(mixed));
    }

    #[test]
    fn single_dir_fs_ignores_config_only_dir() {
        // GH #408: a clean post-split config dir (only config.toml + hooks) must
        // NOT collapse the four-dir layout.
        let home = tempfile::tempdir().unwrap();
        let xdg = tempfile::tempdir().unwrap();
        let mixed = xdg.path().join("lean-ctx");
        std::fs::create_dir_all(&mixed).unwrap();
        std::fs::write(mixed.join("config.toml"), "").unwrap();
        std::fs::write(mixed.join("shell-hook.zsh"), "").unwrap();

        assert_eq!(single_dir_override_fs(home.path(), xdg.path()), None);
    }

    #[test]
    fn single_dir_fs_prefers_legacy_over_mixed() {
        let home = tempfile::tempdir().unwrap();
        let xdg = tempfile::tempdir().unwrap();
        let legacy = home.path().join(".lean-ctx");
        std::fs::create_dir_all(&legacy).unwrap();
        std::fs::write(legacy.join("sessions"), "x").unwrap();
        let mixed = xdg.path().join("lean-ctx");
        std::fs::create_dir_all(&mixed).unwrap();
        std::fs::write(mixed.join("stats.json"), "{}").unwrap();

        assert_eq!(
            single_dir_override_fs(home.path(), xdg.path()),
            Some(legacy)
        );
    }

    #[test]
    fn xdg_pinned_install_ignores_stray_legacy_marker() {
        // GL #623: once committed to XDG (pin in the config dir), a stray
        // `~/.lean-ctx/stats.json` (legacy residue, restored backup, concurrent
        // old binary) must NOT re-collapse the layout onto the legacy dir.
        let home = tempfile::tempdir().unwrap();
        let xdg = tempfile::tempdir().unwrap();
        crate::core::layout_pin::write_xdg_pin_in(xdg.path()).unwrap();

        let legacy = home.path().join(".lean-ctx");
        std::fs::create_dir_all(&legacy).unwrap();
        std::fs::write(legacy.join("stats.json"), "{}").unwrap();

        assert_eq!(single_dir_override_fs(home.path(), xdg.path()), None);
    }

    #[test]
    fn xdg_pinned_install_ignores_stray_mixed_marker() {
        // GL #623: same protection for a stray data marker that lands in the
        // mixed `$XDG_CONFIG_HOME/lean-ctx` dir after the install committed.
        let home = tempfile::tempdir().unwrap();
        let xdg = tempfile::tempdir().unwrap();
        crate::core::layout_pin::write_xdg_pin_in(xdg.path()).unwrap();

        let mixed = xdg.path().join("lean-ctx");
        std::fs::write(mixed.join("stats.json"), "{}").unwrap();

        assert_eq!(single_dir_override_fs(home.path(), xdg.path()), None);
    }

    #[test]
    fn single_dir_fs_ignores_empty_dirs() {
        let home = tempfile::tempdir().unwrap();
        let xdg = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(home.path().join(".lean-ctx")).unwrap();
        std::fs::create_dir_all(xdg.path().join("lean-ctx")).unwrap();

        assert_eq!(single_dir_override_fs(home.path(), xdg.path()), None);
    }

    #[test]
    fn single_dir_fs_ignores_non_marker_files() {
        let home = tempfile::tempdir().unwrap();
        let xdg = tempfile::tempdir().unwrap();
        let mixed = xdg.path().join("lean-ctx");
        std::fs::create_dir_all(&mixed).unwrap();
        std::fs::write(mixed.join("random.txt"), "x").unwrap();

        assert_eq!(single_dir_override_fs(home.path(), xdg.path()), None);
    }

    #[test]
    fn xdg_base_honors_env_then_home_fallback() {
        let _lock = crate::core::data_dir::test_env_lock();
        let tmp = tempfile::tempdir().unwrap();
        crate::test_env::set_var("XDG_CONFIG_HOME", tmp.path());
        let from_env = xdg_base("XDG_CONFIG_HOME", ".config").unwrap();
        crate::test_env::remove_var("XDG_CONFIG_HOME");
        assert_eq!(from_env, tmp.path());

        // Unset var → falls back to $HOME/<home_fallback>.
        let fallback = xdg_base("LEAN_CTX_NONEXISTENT_XDG_VAR", ".cache").unwrap();
        assert!(fallback.ends_with(".cache"), "got: {}", fallback.display());
    }

    #[test]
    fn legacy_adoption_source_only_when_canonical_absent() {
        let tmp = tempfile::tempdir().unwrap();
        let legacy = tmp.path().join("legacy");
        let canonical = tmp.path().join("canonical");

        // Legacy missing → nothing to adopt.
        assert_eq!(legacy_adoption_source(&legacy, &canonical), None);

        // Legacy present, canonical absent → adopt the legacy copy.
        std::fs::create_dir_all(&legacy).unwrap();
        assert_eq!(
            legacy_adoption_source(&legacy, &canonical),
            Some(legacy.clone())
        );

        // Canonical present → the newer location wins, never overwrite it.
        std::fs::create_dir_all(&canonical).unwrap();
        assert_eq!(legacy_adoption_source(&legacy, &canonical), None);
    }

    #[test]
    fn relocate_moves_file_then_directory() {
        let tmp = tempfile::tempdir().unwrap();

        // File: dst parent must be created by the caller (as adopt does).
        let src_file = tmp.path().join("providers.toml");
        std::fs::write(&src_file, "id = \"x\"\n").unwrap();
        let dst_file = tmp.path().join("config/lean-ctx/providers.toml");
        std::fs::create_dir_all(dst_file.parent().unwrap()).unwrap();
        relocate(&src_file, &dst_file).unwrap();
        assert!(!src_file.exists(), "source file must be moved, not copied");
        assert_eq!(std::fs::read_to_string(&dst_file).unwrap(), "id = \"x\"\n");

        // Directory with nested content.
        let src_dir = tmp.path().join("personas");
        std::fs::create_dir_all(src_dir.join("nested")).unwrap();
        std::fs::write(src_dir.join("a.toml"), "a").unwrap();
        std::fs::write(src_dir.join("nested/b.toml"), "b").unwrap();
        let dst_dir = tmp.path().join("config/lean-ctx/personas");
        std::fs::create_dir_all(dst_dir.parent().unwrap()).unwrap();
        relocate(&src_dir, &dst_dir).unwrap();
        assert!(!src_dir.exists(), "source dir must be moved");
        assert_eq!(
            std::fs::read_to_string(dst_dir.join("a.toml")).unwrap(),
            "a"
        );
        assert_eq!(
            std::fs::read_to_string(dst_dir.join("nested/b.toml")).unwrap(),
            "b"
        );
    }

    #[test]
    fn single_dir_override_honors_data_dir_env() {
        let _lock = crate::core::data_dir::test_env_lock();
        let tmp = tempfile::tempdir().unwrap();
        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
        let got = single_dir_override();
        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
        // A custom (non-standard) data dir is a deliberate single-dir choice.
        assert_eq!(got, Some(tmp.path().to_path_buf()));
    }

    #[test]
    fn is_standard_xdg_data_dir_matches_xdg_data_home() {
        let _lock = crate::core::data_dir::test_env_lock();
        let data_home = tempfile::tempdir().unwrap();
        crate::test_env::set_var("XDG_DATA_HOME", data_home.path());
        let is_std = is_standard_xdg_data_dir(&data_home.path().join("lean-ctx"));
        let is_custom = is_standard_xdg_data_dir(Path::new("/some/custom/lean-ctx"));
        crate::test_env::remove_var("XDG_DATA_HOME");
        assert!(is_std, "$XDG_DATA_HOME/lean-ctx is the standard data dir");
        assert!(!is_custom, "a custom path is not the standard data dir");
    }

    #[test]
    fn standard_data_pin_does_not_collapse_categories() {
        // #594: an editor (MCP env) that pins LEAN_CTX_DATA_DIR to the *standard*
        // XDG data dir must NOT drag config/state/cache along — single_dir_override
        // must return None so they keep their own XDG bases, matching the CLI.
        let _lock = crate::core::data_dir::test_env_lock();
        let home = tempfile::tempdir().unwrap();
        let xdg_config = tempfile::tempdir().unwrap();
        let xdg_data = tempfile::tempdir().unwrap();
        let data_pin = xdg_data.path().join("lean-ctx");
        crate::test_env::set_var("HOME", home.path());
        crate::test_env::set_var("XDG_CONFIG_HOME", xdg_config.path());
        crate::test_env::set_var("XDG_DATA_HOME", xdg_data.path());
        crate::test_env::set_var("LEAN_CTX_DATA_DIR", &data_pin);

        let got = single_dir_override();

        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
        crate::test_env::remove_var("XDG_DATA_HOME");
        crate::test_env::remove_var("XDG_CONFIG_HOME");
        crate::test_env::remove_var("HOME");

        assert_eq!(got, None);
    }

    #[test]
    fn config_dir_honors_explicit_override() {
        let _lock = crate::core::data_dir::test_env_lock();
        let tmp = tempfile::tempdir().unwrap();
        crate::test_env::set_var("LEAN_CTX_CONFIG_DIR", tmp.path());
        let got = config_dir().unwrap();
        crate::test_env::remove_var("LEAN_CTX_CONFIG_DIR");
        assert_eq!(got, tmp.path());
    }

    #[test]
    fn state_and_cache_dirs_honor_explicit_overrides() {
        let _lock = crate::core::data_dir::test_env_lock();
        let state = tempfile::tempdir().unwrap();
        let cache = tempfile::tempdir().unwrap();
        crate::test_env::set_var("LEAN_CTX_STATE_DIR", state.path());
        crate::test_env::set_var("LEAN_CTX_CACHE_DIR", cache.path());
        let got_state = state_dir().unwrap();
        let got_cache = cache_dir().unwrap();
        crate::test_env::remove_var("LEAN_CTX_STATE_DIR");
        crate::test_env::remove_var("LEAN_CTX_CACHE_DIR");
        assert_eq!(got_state, state.path());
        assert_eq!(got_cache, cache.path());
    }

    #[test]
    fn data_dir_matches_lean_ctx_data_dir() {
        let _guard = crate::core::data_dir::isolated_data_dir();
        assert_eq!(
            data_dir().unwrap(),
            crate::core::data_dir::lean_ctx_data_dir().unwrap()
        );
    }

    #[test]
    fn runtime_dir_honors_xdg_runtime_dir() {
        let _lock = crate::core::data_dir::test_env_lock();
        let tmp = tempfile::tempdir().unwrap();
        crate::test_env::set_var("XDG_RUNTIME_DIR", tmp.path());
        let got = runtime_dir().unwrap();
        crate::test_env::remove_var("XDG_RUNTIME_DIR");
        assert_eq!(got, tmp.path().join("lean-ctx"));
    }
}