lean-ctx 3.8.17

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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
//! On-demand XDG split migration (GH #408 / GL #606).
//!
//! Fresh installs already land in the four typed XDG dirs (config/data/state/
//! cache) since GL #606. Existing **legacy** (`~/.lean-ctx`) and **mixed**
//! (`$XDG_CONFIG_HOME/lean-ctx`) installs keep resolving every category onto
//! their single directory for backward compatibility — splitting them silently
//! would be data-destructive. `lean-ctx doctor --fix` performs the split *on
//! demand* by moving each entry to the directory its category resolves to.
//!
//! ## Why it must be all-or-nothing
//!
//! Resolution collapses onto the single dir only while that dir still
//! `has_data_files` (see `crate::core::paths::single_dir_override`). Moving only
//! *some* categories out would leave data markers behind, so every resolver
//! would keep pointing at the source and the just-moved state/cache files would
//! be orphaned. We therefore move **all** classifiable entries in one pass; the
//! source stops triggering single-dir mode only once its data is gone, which is
//! also what makes a second run a no-op (idempotent + resumable).
//!
//! ## Safety
//!
//! - Per-entry `rename` with a cross-filesystem copy+remove fallback; the source
//!   is only removed after a successful copy, so an aborted run never loses data.
//! - A destination that already exists is **reconciled, never clobbered** (#429):
//!   colliding directories are merged child-by-child, a source file byte-identical
//!   to the destination is dropped as a duplicate, and a genuinely different
//!   source is moved aside next to the destination under a `*.legacy` name. This
//!   is what lets the legacy dir fully empty out — the earlier "skip and leave
//!   the source in place" behaviour meant any pre-existing target (a parallel
//!   data dir, a half-finished earlier run) left items behind forever, so the
//!   `doctor` warning never cleared no matter how often `--fix` ran.
//! - An explicit `LEAN_CTX_DATA_DIR` is treated as a deliberate single-dir
//!   choice and is **never** auto-split.
//! - Runtime files (`daemon.pid`, sockets, lock files) are left in place; they
//!   are ephemeral and regenerated by the daemon.
//!
//! Determinism (#498): the planned move set is sorted by entry name, so report
//! bodies are a pure function of the on-disk layout.

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

/// XDG category an on-disk entry belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Category {
    Config,
    Data,
    State,
    Cache,
    /// Ephemeral runtime files — left in place (regenerated by the daemon).
    Runtime,
}

impl Category {
    /// Stable, human-readable label used in migration reports.
    fn label(self) -> &'static str {
        match self {
            Category::Config => "config",
            Category::Data => "data",
            Category::State => "state",
            Category::Cache => "cache",
            Category::Runtime => "runtime",
        }
    }
}

/// Classify a top-level entry name into its XDG category.
///
/// The CONFIG/STATE/CACHE/RUNTIME sets are explicit and must match where the
/// code actually reads/writes each file (see the GL #603/#604 migrations); every
/// unlisted entry falls through to DATA, the catch-all (`sessions/`, `vectors/`,
/// `graphs/`, `knowledge/`, `archives/`, `stats.json`, `client-id.json`, …).
fn categorize(name: &str) -> Category {
    match name {
        // --- config: RO-safe ---
        "config.toml" | "env.sh" | "layout.toml" => Category::Config,
        n if n.starts_with("shell-hook.") => Category::Config,

        // --- state: events, logs, journals, ledgers, dashboards ---
        "events.jsonl"
        | "journal.md"
        | "tool-calls.log"
        | "mcp-live.json"
        | "feedback.json"
        | "cost_attribution.json"
        | "context_ledger.json"
        | "ledger"
        | "cooccurrence"
        | "slow-commands.log"
        | "pipeline_stats.json"
        | "heatmap.json"
        | "tee"
        | "dashboard.token"
        | "agent_runtime_env.json" => Category::State,

        // --- cache: regenerable models, embeddings, learned patterns ---
        "semantic_cache"
        | "models"
        | "anomaly_detector.json"
        | "autonomy_drivers_v1.json"
        | "context_ir_v1.json"
        | "thresholds_learned.json"
        | "litm_calibration.json"
        | "path_mode_memory.json"
        | "efficacy_snapshots.json"
        | "latest-version.json"
        | ".first_run_wow_done" => Category::Cache,

        // --- runtime: ephemeral, left in place ---
        "daemon.pid" | "daemon.sock" | "daemon-stderr.log" => Category::Runtime,
        n if n.starts_with(".graph-idx-") => Category::Runtime,

        _ => Category::Data,
    }
}

/// Resolved per-category target directories for a split.
struct Targets {
    config: PathBuf,
    data: PathBuf,
    state: PathBuf,
    cache: PathBuf,
}

impl Targets {
    /// Resolve targets from the environment, bypassing single-dir back-compat.
    fn resolve() -> Result<Self, String> {
        Ok(Self {
            config: crate::core::paths::config_split_target()?,
            data: crate::core::paths::data_split_target()?,
            state: crate::core::paths::state_split_target()?,
            cache: crate::core::paths::cache_split_target()?,
        })
    }

    /// Target dir for a category, or `None` for runtime (left in place).
    fn dir_for(&self, cat: Category) -> Option<&Path> {
        match cat {
            Category::Config => Some(&self.config),
            Category::Data => Some(&self.data),
            Category::State => Some(&self.state),
            Category::Cache => Some(&self.cache),
            Category::Runtime => None,
        }
    }
}

/// A single planned move computed from the source layout.
struct PlannedMove {
    from: PathBuf,
    name: String,
    category: &'static str,
    dest_dir: PathBuf,
    dest: PathBuf,
}

/// Outcome of a migration run, surfaced through `doctor --fix`.
pub struct MigrationReport {
    /// The single directory that was split.
    pub source: PathBuf,
    /// `(entry, category)` for every entry successfully relocated (moved or
    /// merged into an existing destination directory).
    pub moved: Vec<(String, &'static str)>,
    /// Entries dropped because the destination already held a byte-identical
    /// copy — nothing new was written; the duplicate source was removed.
    pub skipped: Vec<String>,
    /// Entries whose destination held *different* data: the source was preserved
    /// next to the destination under a `*.legacy` name rather than lost (#429).
    pub conflicts: Vec<String>,
    /// Per-entry move failures (`entry: error`).
    pub errors: Vec<String>,
}

impl MigrationReport {
    fn new(source: &Path) -> Self {
        Self {
            source: source.to_path_buf(),
            moved: Vec::new(),
            skipped: Vec::new(),
            conflicts: Vec::new(),
            errors: Vec::new(),
        }
    }

    /// Whether the run produced any observable effect worth reporting.
    fn is_empty(&self) -> bool {
        self.moved.is_empty()
            && self.skipped.is_empty()
            && self.conflicts.is_empty()
            && self.errors.is_empty()
    }
}

/// Compute the deterministic set of entries that must move to split `src` into
/// `targets`. Entries whose category target equals `src` (e.g. config files in a
/// mixed `$XDG_CONFIG_HOME/lean-ctx`) and runtime files stay put.
fn entries_to_move(src: &Path, targets: &Targets) -> Vec<PlannedMove> {
    let mut moves = Vec::new();
    let Ok(rd) = std::fs::read_dir(src) else {
        return moves;
    };
    for entry in rd.flatten() {
        let raw_name = entry.file_name();
        let name = raw_name.to_string_lossy().to_string();
        let cat = categorize(&name);
        let Some(dest_dir) = targets.dir_for(cat) else {
            continue; // runtime → leave in place
        };
        if dest_dir == src {
            continue; // already in the right place (e.g. mixed config dir)
        }
        moves.push(PlannedMove {
            from: entry.path(),
            name,
            category: cat.label(),
            dest_dir: dest_dir.to_path_buf(),
            dest: dest_dir.join(&raw_name),
        });
    }
    moves.sort_by(|a, b| a.name.cmp(&b.name));
    moves
}

/// Recursively copy `from` into `to` (used as the cross-filesystem fallback when
/// `rename` cannot move across mount points).
fn copy_tree(from: &Path, to: &Path) -> std::io::Result<()> {
    std::fs::create_dir_all(to)?;
    for entry in std::fs::read_dir(from)? {
        let entry = entry?;
        let dst = to.join(entry.file_name());
        if entry.file_type()?.is_dir() {
            copy_tree(&entry.path(), &dst)?;
        } else {
            std::fs::copy(entry.path(), &dst)?;
        }
    }
    Ok(())
}

/// Move `from` to `to`, preferring an atomic `rename` and falling back to
/// copy+remove across filesystems. The source is removed only after the copy
/// succeeds, so an interrupted move never loses data.
fn move_entry(from: &Path, to: &Path) -> std::io::Result<()> {
    if std::fs::rename(from, to).is_ok() {
        return Ok(());
    }
    if from.is_dir() {
        copy_tree(from, to)?;
        std::fs::remove_dir_all(from)?;
    } else {
        std::fs::copy(from, to)?;
        std::fs::remove_file(from)?;
    }
    Ok(())
}

/// How an entry whose destination already existed was reconciled (#429).
enum Reconciled {
    /// Source directory merged into the existing destination directory.
    Merged,
    /// Source was a byte-identical duplicate and was dropped.
    Deduped,
    /// Destination held different data; source preserved next to it as `*.legacy`.
    Conflict,
}

/// Execute the split of `src` into `targets`. Pure with respect to its inputs
/// (no environment access) so it can be tested hermetically.
fn migrate_from(src: &Path, targets: &Targets) -> MigrationReport {
    let mut report = MigrationReport::new(src);
    for mv in entries_to_move(src, targets) {
        if let Err(e) = std::fs::create_dir_all(&mv.dest_dir) {
            report.errors.push(format!("{}: {e}", mv.name));
            continue;
        }
        crate::core::data_dir::ensure_dir_permissions(&mv.dest_dir);

        if mv.dest.exists() {
            match reconcile_existing(&mv.from, &mv.dest) {
                Ok(Reconciled::Merged) => report.moved.push((mv.name, mv.category)),
                Ok(Reconciled::Deduped) => report.skipped.push(mv.name),
                Ok(Reconciled::Conflict) => report.conflicts.push(mv.name),
                Err(e) => report.errors.push(format!("{}: {e}", mv.name)),
            }
            continue;
        }

        match move_entry(&mv.from, &mv.dest) {
            Ok(()) => report.moved.push((mv.name, mv.category)),
            Err(e) => report.errors.push(format!("{}: {e}", mv.name)),
        }
    }
    report
}

/// Reconcile a source entry whose destination already exists, without ever
/// overwriting the destination or leaving the source behind (#429): merge
/// directories child-by-child, drop byte-identical duplicate files, and preserve
/// a genuinely different source next to the destination under a `*.legacy` name.
fn reconcile_existing(from: &Path, dest: &Path) -> std::io::Result<Reconciled> {
    if from.is_dir() && dest.is_dir() {
        merge_dir(from, dest)?;
        return Ok(Reconciled::Merged);
    }
    if from.is_file() && dest.is_file() && files_identical(from, dest)? {
        std::fs::remove_file(from)?;
        return Ok(Reconciled::Deduped);
    }
    // Genuine conflict (differing files, or a file-vs-dir type clash): keep the
    // destination as the winner and move the source aside, so the legacy dir
    // can still empty out. Data is preserved, just renamed.
    let backup = backup_path(dest);
    move_entry(from, &backup)?;
    Ok(Reconciled::Conflict)
}

/// Recursively merge `from`'s children into the existing directory `dest`,
/// reconciling each per-child collision, then remove `from` once it is empty.
fn merge_dir(from: &Path, dest: &Path) -> std::io::Result<()> {
    for entry in std::fs::read_dir(from)? {
        let entry = entry?;
        let child_dest = dest.join(entry.file_name());
        if child_dest.exists() {
            reconcile_existing(&entry.path(), &child_dest)?;
        } else {
            move_entry(&entry.path(), &child_dest)?;
        }
    }
    // Succeeds only when every child was relocated; a leftover keeps the dir so
    // nothing is ever silently dropped.
    let _ = std::fs::remove_dir(from);
    Ok(())
}

/// Byte-compare two files, cheaply short-circuiting on differing length.
fn files_identical(a: &Path, b: &Path) -> std::io::Result<bool> {
    let (ma, mb) = (std::fs::metadata(a)?, std::fs::metadata(b)?);
    if ma.len() != mb.len() {
        return Ok(false);
    }
    Ok(std::fs::read(a)? == std::fs::read(b)?)
}

/// First free `<dest>.legacy`, `<dest>.legacy-2`, … sibling path, so a conflicting
/// source lives right next to the winner — clearly marked, never lost.
fn backup_path(dest: &Path) -> PathBuf {
    let base = dest.as_os_str().to_os_string();
    let make = |suffix: &str| {
        let mut s = base.clone();
        s.push(suffix);
        PathBuf::from(s)
    };
    let mut candidate = make(".legacy");
    let mut n = 2;
    while candidate.exists() {
        candidate = make(&format!(".legacy-{n}"));
        n += 1;
    }
    candidate
}

/// Returns the single-dir source plus the resolved split targets, or `None`
/// when there is nothing to split: a fresh/already-split install, or an explicit
/// `LEAN_CTX_DATA_DIR` (a deliberate single-dir choice we must not override).
fn detect() -> Option<(PathBuf, Targets)> {
    if std::env::var_os("LEAN_CTX_DATA_DIR").is_some() {
        return None;
    }
    let src = crate::core::paths::single_dir_override()?;
    if !src.is_dir() {
        return None;
    }
    let targets = Targets::resolve().ok()?;
    Some((src, targets))
}

/// Count entries that a split would relocate, for the read-only `doctor` report.
/// Returns `None` when no migration applies.
pub fn pending() -> Option<(PathBuf, usize)> {
    let (src, targets) = detect()?;
    let n = entries_to_move(&src, &targets).len();
    if n == 0 {
        return None;
    }
    Some((src, n))
}

/// Split a legacy/mixed single-dir install into the four XDG dirs. Returns
/// `None` when nothing applies (fresh install, explicit `LEAN_CTX_DATA_DIR`, or
/// already split). Drives `lean-ctx doctor --fix`.
pub fn migrate() -> Option<MigrationReport> {
    let (src, targets) = detect()?;
    let report = migrate_from(&src, &targets);
    if report.is_empty() {
        return None;
    }
    Some(report)
}

/// Reclaim a residual legacy `~/.lean-ctx` directory after its data has already
/// moved to XDG (an earlier `--fix`, or the GH #408 default flip). Unlike
/// [`migrate`] — which only fires while the source still `has_data_files` — this
/// drains whatever non-runtime entries linger (old `doctor/`, `setup/`,
/// `status/` reports, stray catch-all files) into their typed XDG dirs and then
/// removes the now-empty legacy dir, so `~/.lean-ctx` actually disappears
/// instead of being silently re-adopted as the data dir (GH #434, #436).
///
/// Safety:
/// - Operates ONLY on `~/.lean-ctx` (never a mixed `$XDG_CONFIG_HOME` source).
/// - Skips when `LEAN_CTX_DATA_DIR` pins a single dir, or when the legacy dir is
///   still the active data dir (unmigrated data present) — `migrate` performs the
///   split first, and this guard prevents ever draining a live data dir.
/// - Reuses the copy-before-remove / reconcile logic, so no data is ever lost.
/// - Removes the dir only when it ends up empty; a surviving runtime file
///   (e.g. a live socket) keeps it — fine, it is no longer the data dir.
///
/// `true` when a residual legacy `~/.lean-ctx` directory still exists on disk.
///
/// Diagnostics (`doctor`) use this to surface a leftover dir that [`heal`] /
/// [`reclaim_legacy`] will drain on the next start — without reconstructing
/// `home.join(".lean-ctx")` themselves, which the legacy-path firewall
/// (`tests/legacy_path_firewall.rs`) forbids outside the resolver/migrator
/// modules. The migrator owns the legacy path, so the knowledge lives here.
///
/// [`heal`]: crate::core::layout_pin::heal
#[must_use]
pub fn residual_legacy_present() -> bool {
    dirs::home_dir().is_some_and(|h| h.join(".lean-ctx").is_dir())
}

pub fn reclaim_legacy() -> Option<MigrationReport> {
    if std::env::var_os("LEAN_CTX_DATA_DIR").is_some() {
        return None;
    }
    let legacy = dirs::home_dir()?.join(".lean-ctx");
    if !legacy.is_dir() {
        return None;
    }
    // Never drain the directory that is still the active data dir (an unmigrated
    // legacy install, or a migration that left markers behind).
    if crate::core::data_dir::lean_ctx_data_dir().ok().as_deref() == Some(legacy.as_path()) {
        return None;
    }
    let targets = Targets::resolve().ok()?;
    let report = migrate_from(&legacy, &targets);
    // Best-effort: drop the dir once it is empty.
    let _ = std::fs::remove_dir(&legacy);
    if report.is_empty() {
        return None;
    }
    Some(report)
}

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

    fn targets_in(root: &Path) -> Targets {
        Targets {
            config: root.join("config"),
            data: root.join("data"),
            state: root.join("state"),
            cache: root.join("cache"),
        }
    }

    fn touch(dir: &Path, name: &str) {
        std::fs::create_dir_all(dir).unwrap();
        std::fs::write(dir.join(name), b"x").unwrap();
    }

    #[test]
    fn categorize_routes_each_category() {
        assert_eq!(categorize("config.toml"), Category::Config);
        assert_eq!(categorize("shell-hook.zsh"), Category::Config);
        assert_eq!(categorize("events.jsonl"), Category::State);
        assert_eq!(categorize("pipeline_stats.json"), Category::State);
        assert_eq!(categorize("semantic_cache"), Category::Cache);
        assert_eq!(categorize("models"), Category::Cache);
        assert_eq!(categorize(".first_run_wow_done"), Category::Cache);
        assert_eq!(categorize("daemon.sock"), Category::Runtime);
        assert_eq!(categorize(".graph-idx-abc.lock"), Category::Runtime);
        // catch-all → data
        assert_eq!(categorize("sessions"), Category::Data);
        assert_eq!(categorize("stats.json"), Category::Data);
        assert_eq!(categorize("client-id.json"), Category::Data);
        assert_eq!(categorize("something-new"), Category::Data);
    }

    #[test]
    fn mixed_config_source_splits_data_state_cache_keeps_config() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        // Source IS the config target → config entries must stay.
        let src = root.join("config");
        let mut t = targets_in(root);
        t.config = src.clone();

        touch(&src, "config.toml");
        touch(&src, "events.jsonl");
        touch(&src, "anomaly_detector.json");
        touch(&src, "stats.json");
        touch(&src.join("sessions"), "s1.json");
        touch(&src, "daemon.pid"); // runtime stays

        let report = migrate_from(&src, &t);
        assert!(report.errors.is_empty(), "errors: {:?}", report.errors);

        // config + runtime stay
        assert!(src.join("config.toml").exists());
        assert!(src.join("daemon.pid").exists());
        // categories relocate
        assert!(t.state.join("events.jsonl").exists());
        assert!(t.cache.join("anomaly_detector.json").exists());
        assert!(t.data.join("stats.json").exists());
        assert!(t.data.join("sessions/s1.json").exists());
        // originals gone
        assert!(!src.join("events.jsonl").exists());
        assert!(!src.join("sessions").exists());

        let labels: Vec<_> = report.moved.iter().map(|(n, c)| (n.as_str(), *c)).collect();
        assert!(labels.contains(&("events.jsonl", "state")));
        assert!(labels.contains(&("anomaly_detector.json", "cache")));
        assert!(labels.contains(&("sessions", "data")));
        assert!(labels.contains(&("stats.json", "data")));
    }

    #[test]
    fn legacy_source_moves_everything_including_config() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let src = root.join("legacy"); // distinct from every target
        let t = targets_in(root);

        touch(&src, "config.toml");
        touch(&src, "events.jsonl");
        touch(&src.join("vectors"), "v.bin");

        let report = migrate_from(&src, &t);
        assert!(report.errors.is_empty());
        assert!(t.config.join("config.toml").exists());
        assert!(t.state.join("events.jsonl").exists());
        assert!(t.data.join("vectors/v.bin").exists());
        assert!(!src.join("config.toml").exists());
    }

    #[test]
    fn identical_dest_is_deduped_and_source_cleared() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let src = root.join("legacy");
        let t = targets_in(root);

        // Destination already holds a byte-identical copy.
        touch(&src, "events.jsonl"); // content "x"
        std::fs::create_dir_all(&t.state).unwrap();
        std::fs::write(t.state.join("events.jsonl"), b"x").unwrap();

        let report = migrate_from(&src, &t);
        assert!(report.errors.is_empty());
        assert!(report.moved.is_empty());
        assert_eq!(report.skipped, vec!["events.jsonl".to_string()]);
        assert!(report.conflicts.is_empty());
        // Duplicate source dropped; destination untouched.
        assert!(
            !src.join("events.jsonl").exists(),
            "duplicate source dropped"
        );
        assert_eq!(
            std::fs::read_to_string(t.state.join("events.jsonl")).unwrap(),
            "x"
        );
        // Legacy dir is now empty → a re-scan plans nothing (warning clears).
        assert!(entries_to_move(&src, &t).is_empty());
    }

    #[test]
    fn conflicting_dest_backs_up_source_and_clears_legacy() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let src = root.join("legacy");
        let t = targets_in(root);

        touch(&src, "events.jsonl"); // content "x"
        std::fs::create_dir_all(&t.state).unwrap();
        std::fs::write(t.state.join("events.jsonl"), b"keep").unwrap(); // differs

        let report = migrate_from(&src, &t);
        assert!(report.errors.is_empty());
        assert_eq!(report.conflicts, vec!["events.jsonl".to_string()]);
        // Winner preserved, source moved aside as *.legacy, legacy dir emptied.
        assert_eq!(
            std::fs::read_to_string(t.state.join("events.jsonl")).unwrap(),
            "keep",
            "existing destination must not be overwritten"
        );
        assert_eq!(
            std::fs::read_to_string(t.state.join("events.jsonl.legacy")).unwrap(),
            "x",
            "different source preserved next to the winner"
        );
        assert!(!src.join("events.jsonl").exists());
        assert!(
            entries_to_move(&src, &t).is_empty(),
            "warning clears once the source is reconciled"
        );
    }

    /// #429: a destination directory that already holds *some* content (a parallel
    /// data dir, a half-finished earlier run) must be merged, not skipped —
    /// otherwise the legacy entries linger and `doctor` warns forever no matter
    /// how often `--fix` runs. After the merge the legacy source is fully empty.
    #[test]
    fn dir_collision_merges_and_empties_legacy_429() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let src = root.join("legacy");
        let t = targets_in(root);

        // Source sessions/ has a new file and a duplicate; dest sessions/ exists
        // already with its own file plus the same duplicate.
        touch(&src.join("sessions"), "old.json"); // only in source
        std::fs::write(src.join("sessions").join("dup.json"), b"same").unwrap();
        touch(&t.data.join("sessions"), "existing.json"); // only in dest
        std::fs::write(t.data.join("sessions").join("dup.json"), b"same").unwrap();

        let report = migrate_from(&src, &t);
        assert!(report.errors.is_empty(), "errors: {:?}", report.errors);

        // Merged: destination keeps its own entry and gains the source-only one.
        assert!(t.data.join("sessions/existing.json").exists());
        assert!(t.data.join("sessions/old.json").exists());
        assert!(t.data.join("sessions/dup.json").exists());
        // Source dir fully removed → legacy no longer triggers single-dir mode.
        assert!(!src.join("sessions").exists(), "merged source dir removed");
        assert!(
            entries_to_move(&src, &t).is_empty(),
            "#429: nothing left to migrate after a merge"
        );
    }

    #[test]
    fn entries_to_move_is_sorted_for_determinism() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let src = root.join("legacy");
        let t = targets_in(root);
        touch(&src, "events.jsonl");
        touch(&src, "config.toml");
        touch(&src, "anomaly_detector.json");
        let names: Vec<_> = entries_to_move(&src, &t)
            .into_iter()
            .map(|m| m.name)
            .collect();
        let mut sorted = names.clone();
        sorted.sort();
        assert_eq!(names, sorted);
    }

    /// Saves a set of env vars and restores them on drop (panic-safe) so an
    /// env-driven test can never leak `HOME`/`XDG_*` into other tests.
    ///
    /// Only the `#[cfg(unix)]` end-to-end tests below construct this, so the
    /// helper is unix-gated too — otherwise it is dead code on Windows where
    /// `-D warnings` would fail the build.
    #[cfg(unix)]
    struct EnvVars(Vec<(&'static str, Option<std::ffi::OsString>)>);

    #[cfg(unix)]
    impl EnvVars {
        fn apply(pairs: &[(&'static str, Option<&Path>)]) -> Self {
            let saved = pairs
                .iter()
                .map(|(k, _)| (*k, std::env::var_os(k)))
                .collect();
            for (k, v) in pairs {
                match v {
                    Some(p) => crate::test_env::set_var(k, p),
                    None => crate::test_env::remove_var(k),
                }
            }
            EnvVars(saved)
        }
    }

    #[cfg(unix)]
    impl Drop for EnvVars {
        fn drop(&mut self) {
            for (k, v) in &self.0 {
                match v {
                    Some(val) => crate::test_env::set_var(k, val),
                    None => crate::test_env::remove_var(k),
                }
            }
        }
    }

    // End-to-end through the real env-detection + split-target wiring (the unit
    // tests above drive `migrate_from` with explicit dirs). Proves a mixed
    // `$XDG_CONFIG_HOME/lean-ctx` install splits into the four XDG homes and that
    // a second run is a no-op once the data markers are gone.
    #[cfg(unix)]
    #[test]
    fn migrate_end_to_end_splits_mixed_xdg_config_install() {
        let _g = crate::core::data_dir::test_env_lock();
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let home = root.join("home");
        let xc = root.join("xc");
        let xd = root.join("xd");
        let xs = root.join("xs");
        let xk = root.join("xk");
        std::fs::create_dir_all(&home).unwrap();

        let _env = EnvVars::apply(&[
            ("HOME", Some(home.as_path())),
            ("XDG_CONFIG_HOME", Some(xc.as_path())),
            ("XDG_DATA_HOME", Some(xd.as_path())),
            ("XDG_STATE_HOME", Some(xs.as_path())),
            ("XDG_CACHE_HOME", Some(xk.as_path())),
            ("LEAN_CTX_DATA_DIR", None),
            ("LEAN_CTX_CONFIG_DIR", None),
            ("LEAN_CTX_STATE_DIR", None),
            ("LEAN_CTX_CACHE_DIR", None),
        ]);

        // Mixed install: config + every category mixed under $XDG_CONFIG_HOME.
        let mixed = xc.join("lean-ctx");
        touch(&mixed, "config.toml");
        touch(&mixed, "events.jsonl");
        touch(&mixed, "anomaly_detector.json");
        touch(&mixed, "stats.json");
        touch(&mixed.join("sessions"), "s.json");

        let report = migrate().expect("mixed install must migrate");
        assert!(report.errors.is_empty(), "errors: {:?}", report.errors);

        assert!(mixed.join("config.toml").exists(), "config stays in place");
        assert!(
            xs.join("lean-ctx/events.jsonl").exists(),
            "state → XDG_STATE"
        );
        assert!(
            xk.join("lean-ctx/anomaly_detector.json").exists(),
            "cache → XDG_CACHE"
        );
        assert!(xd.join("lean-ctx/stats.json").exists(), "data → XDG_DATA");
        assert!(
            xd.join("lean-ctx/sessions/s.json").exists(),
            "data subdir → XDG_DATA"
        );
        assert!(
            !mixed.join("events.jsonl").exists(),
            "moved source file removed"
        );

        assert!(migrate().is_none(), "second run is a no-op (idempotent)");
    }

    // An explicit `LEAN_CTX_DATA_DIR` is a deliberate single-dir choice and must
    // never be auto-split, even when the dir clearly mixes categories.
    #[cfg(unix)]
    #[test]
    fn migrate_respects_explicit_data_dir_override() {
        let _g = crate::core::data_dir::test_env_lock();
        let tmp = tempfile::tempdir().unwrap();
        let single = tmp.path().join("single");
        touch(&single, "stats.json");
        touch(&single, "events.jsonl");

        let _env = EnvVars::apply(&[("LEAN_CTX_DATA_DIR", Some(single.as_path()))]);
        assert!(
            migrate().is_none(),
            "explicit LEAN_CTX_DATA_DIR must not be split"
        );
        assert!(single.join("events.jsonl").exists(), "nothing moved");
    }

    // #434/#436: a residual `~/.lean-ctx` left behind after the data already
    // moved to XDG (only a stale `doctor/` report, no data markers) must be
    // drained into the typed XDG dirs and the empty dir removed, so it stops
    // being re-adopted as the data dir.
    #[cfg(unix)]
    #[test]
    fn reclaim_legacy_drains_and_removes_residual_dir() {
        let _g = crate::core::data_dir::test_env_lock();
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let home = root.join("home");
        let xc = root.join("xc");
        let xd = root.join("xd");
        let xs = root.join("xs");
        let xk = root.join("xk");
        std::fs::create_dir_all(&home).unwrap();
        let legacy = home.join(".lean-ctx");
        // Residual leftover: a doctor report (catch-all → data), NO data markers.
        touch(&legacy.join("doctor"), "latest.json");

        let _env = EnvVars::apply(&[
            ("HOME", Some(home.as_path())),
            ("XDG_CONFIG_HOME", Some(xc.as_path())),
            ("XDG_DATA_HOME", Some(xd.as_path())),
            ("XDG_STATE_HOME", Some(xs.as_path())),
            ("XDG_CACHE_HOME", Some(xk.as_path())),
            ("LEAN_CTX_DATA_DIR", None),
            ("LEAN_CTX_CONFIG_DIR", None),
            ("LEAN_CTX_STATE_DIR", None),
            ("LEAN_CTX_CACHE_DIR", None),
        ]);

        let report = reclaim_legacy().expect("residual legacy must be reclaimed");
        assert!(report.errors.is_empty(), "errors: {:?}", report.errors);
        assert!(
            xd.join("lean-ctx/doctor/latest.json").exists(),
            "report drained into XDG data"
        );
        assert!(!legacy.exists(), "empty legacy dir removed");
        assert!(reclaim_legacy().is_none(), "second run is a no-op");
    }
}