limitless-cli 1.0.0

A beginner-friendly environment diagnostic tool
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
//! **Config & persistence** — user preferences plus durable storage for
//! preferences, lifetime stats and the diagnostic cache.
//!
//! Everything lives under `<home>/.limitless/`:
//!
//! | File          | Contents                                              |
//! |---------------|-------------------------------------------------------|
//! | `config.json` | [`LimitlessConfig`] user preferences (auto-created)   |
//! | `stats.json`  | [`ArcadeStats`] lifetime usage counters               |
//! | `cache.json`  | Last [`EnvironmentState`] snapshot (5-minute TTL)     |
//!
//! The [`PersistenceManager`] owns those paths. Its default instance targets
//! the user's home directory, but `from_home` / `at_dir` let callers (and
//! tests) point persistence at any directory. Writes go through a temp-file
//! then rename so a crash mid-write never corrupts the real file.
//!
//! ```
//! use limitless_cli::modules::config::{LimitlessConfig, PersistenceManager};
//!
//! let dir = std::env::temp_dir().join(format!(
//!     "limitless_config_doc_{}_{}",
//!     std::process::id(),
//!     std::time::SystemTime::now()
//!         .duration_since(std::time::UNIX_EPOCH)
//!         .map(|d| d.as_nanos())
//!         .unwrap_or(0)
//! ));
//! let manager = PersistenceManager::from_home(&dir);
//!
//! // First init creates ~/.limitless/config.json with defaults.
//! let config = manager.init_config().unwrap();
//! assert!(config.color_enabled);
//! assert!(config.animation_enabled);
//!
//! // Stats default to an empty counter set when the file is absent.
//! let stats = manager.load_stats().unwrap();
//! assert_eq!(stats.diagnostics_run, 0);
//!
//! let _ = std::fs::remove_dir_all(&dir);
//! ```

use crate::modules::achievements::{home_dir, AchievementProgress, ArcadeStats};
use crate::models::{EnvironmentState, HealthScore, ProjectStack};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

/// How long a cached [`EnvironmentState`] snapshot is considered fresh.
pub const CACHE_TTL: Duration = Duration::from_secs(300);

/// [`CACHE_TTL`] expressed in seconds (handy for tests).
pub const CACHE_TTL_SECS: u64 = 300;

/// Default colors/animations and empty preferred stack.
pub fn default_config() -> LimitlessConfig {
    LimitlessConfig {
        preferred_stack: None,
        auto_approve_safe_fixes: false,
        color_enabled: true,
        animation_enabled: true,
        verbose_mode: false,
    }
}

/// User preferences, persisted as `config.json`.
///
/// ```
/// use limitless_cli::modules::config::{LimitlessConfig, default_config};
///
/// let config = default_config();
/// assert_eq!(config.auto_approve_safe_fixes, false);
/// assert_eq!(config.color_enabled, true);
/// assert_eq!(config.animation_enabled, true);
/// assert_eq!(config.verbose_mode, false);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct LimitlessConfig {
    /// The stack the user prefers to target, when the current directory is
    /// ambiguous or not a project (null = auto-detect).
    pub preferred_stack: Option<ProjectStack>,
    /// Apply safe, reversible fixes without asking first.
    pub auto_approve_safe_fixes: bool,
    /// Use ANSI colors in terminal output.
    pub color_enabled: bool,
    /// Show progress animations (spinners / progress bars).
    pub animation_enabled: bool,
    /// Show technical details by default.
    pub verbose_mode: bool,
}

impl Default for LimitlessConfig {
    fn default() -> Self {
        default_config()
    }
}

/// Owns the `~/.limitless/` data directory and its three JSON files.
///
/// ```
/// use limitless_cli::modules::config::PersistenceManager;
/// let manager = PersistenceManager::default();
/// assert!(manager.config_file.ends_with("config.json"));
/// assert!(manager.stats_file.ends_with("stats.json"));
/// assert!(manager.cache_file.ends_with("cache.json"));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PersistenceManager {
    /// The `.limitless` data directory.
    pub config_dir: PathBuf,
    /// Path to `config.json` (user preferences).
    pub config_file: PathBuf,
    /// Path to `stats.json` (lifetime counters).
    pub stats_file: PathBuf,
    /// Path to `cache.json` (last diagnostics snapshot).
    pub cache_file: PathBuf,
}

impl PersistenceManager {
    /// A manager rooted at an explicit `.limitless` directory (tests use
    /// this to keep the real home directory untouched).
    pub fn at_dir(dir: impl AsRef<Path>) -> Self {
        let dir = dir.as_ref().to_path_buf();
        Self {
            config_dir: dir.clone(),
            config_file: dir.join("config.json"),
            stats_file: dir.join("stats.json"),
            cache_file: dir.join("cache.json"),
        }
    }

    /// A manager rooted at `<home>/.limitless` for a given home directory.
    pub fn from_home(home: impl AsRef<Path>) -> Self {
        Self::at_dir(home.as_ref().join(".limitless"))
    }

    // ------------------------------------------------------------------
    // Configuration
    // ------------------------------------------------------------------

    /// Loads the config file, or `None` when it does not exist.
    ///
    /// A corrupt file is an error (not silently a default), so bad edits are
    /// visible instead of silently reset.
    pub fn load_config(&self) -> Result<Option<LimitlessConfig>, String> {
        if !self.config_file.exists() {
            return Ok(None);
        }
        let raw = fs::read_to_string(&self.config_file)
            .map_err(|err| format!("could not read {}: {err}", self.config_file.display()))?;
        serde_json::from_str(&raw)
            .map(Some)
            .map_err(|err| format!("invalid config file {}: {err}", self.config_file.display()))
    }

    /// Ensures the data directory and config file exist, then returns the
    /// parsed configuration. Missing files are recreated with defaults.
    pub fn init_config(&self) -> Result<LimitlessConfig, String> {
        fs::create_dir_all(&self.config_dir)
            .map_err(|err| format!("could not create {}: {err}", self.config_dir.display()))?;
        if !self.config_file.exists() {
            self.save_config(&LimitlessConfig::default())?;
        }
        self.load_config()?.ok_or_else(|| {
            format!("{} disappeared during init", self.config_file.display())
        })
    }

    /// Persists the configuration atomically, creating directories as needed.
    pub fn save_config(&self, config: &LimitlessConfig) -> Result<(), String> {
        let json = serde_json::to_string_pretty(config)
            .map_err(|err| format!("could not serialize config: {err}"))?;
        atomic_write(&self.config_file, json.as_bytes())
    }

    // ------------------------------------------------------------------
    // Stats
    // ------------------------------------------------------------------

    /// Loads the lifetime usage counters. A missing file yields an empty
    /// [`ArcadeStats`]; a corrupt file is surfaced as an error. Pre-`config.rs`
    /// files that stored the old `{stats, unlocked}` progress wrapper in
    /// `stats.json` are read via the inner counters.
    pub fn load_stats(&self) -> Result<ArcadeStats, String> {
        if !self.stats_file.exists() {
            return Ok(ArcadeStats::default());
        }
        let raw = fs::read_to_string(&self.stats_file)
            .map_err(|err| format!("could not read {}: {err}", self.stats_file.display()))?;
        if let Ok(stats) = serde_json::from_str::<ArcadeStats>(&raw) {
            return Ok(stats);
        }
        if let Ok(legacy) = serde_json::from_str::<AchievementProgress>(&raw) {
            return Ok(legacy.stats);
        }
        Err(format!(
            "invalid stats file {}",
            self.stats_file.display()
        ))
    }

    /// Persists the lifetime counters atomically, creating directories as
    /// needed. Always saves a full snapshot (counters keep accumulating
    /// across runs).
    pub fn save_stats(&self, stats: &ArcadeStats) -> Result<(), String> {
        let json = serde_json::to_string_pretty(stats)
            .map_err(|err| format!("could not serialize stats: {err}"))?;
        atomic_write(&self.stats_file, json.as_bytes())
    }

    // ------------------------------------------------------------------
    // Cache
    // ------------------------------------------------------------------

    /// Snapshots the current diagnostics state with a fresh timestamp.
    pub fn cache_diagnostics(&self, state: &EnvironmentState) -> Result<(), String> {
        let entry = CacheEntry::fresh(state.clone());
        let json = serde_json::to_string_pretty(&entry)
            .map_err(|err| format!("could not serialize cache: {err}"))?;
        atomic_write(&self.cache_file, json.as_bytes())
    }

    /// Reads the raw cache entry, or `None` when the file is missing.
    fn cached_entry(&self) -> Result<Option<CacheEntry>, String> {
        if !self.cache_file.exists() {
            return Ok(None);
        }
        let raw = fs::read_to_string(&self.cache_file)
            .map_err(|err| format!("could not read {}: {err}", self.cache_file.display()))?;
        serde_json::from_str(&raw)
            .map(Some)
            .map_err(|err| format!("invalid cache file {}: {err}", self.cache_file.display()))
    }

    /// Returns the cached [`EnvironmentState`] when it is fresh (≤ 5 minutes
    /// old). Expired, missing or corrupt caches yield `None`.
    ///
    /// On a hit the health score is recomputed so it is never stale.
    pub fn get_cached_diagnostics(&self) -> Option<EnvironmentState> {
        let entry = self.cached_entry().ok().flatten()?;
        if !entry.is_fresh() {
            return None;
        }
        let mut state = entry.state;
        state.health_score = HealthScore::from_results(&state.diagnostics);
        Some(state)
    }
}

impl Default for PersistenceManager {
    /// Points at `<home>/.limitless`, falling back to the current directory
    /// when no home directory can be resolved.
    fn default() -> Self {
        match home_dir() {
            Some(home) => Self::from_home(home),
            None => Self::at_dir(
                std::env::current_dir()
                    .unwrap_or_else(|_| PathBuf::from("."))
                    .join(".limitless"),
            ),
        }
    }
}

/// A cached [`EnvironmentState`] with the Unix timestamp when it was saved.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CacheEntry {
    /// Seconds since the Unix epoch at save time.
    pub saved_at: u64,
    /// The snapshot that was cached.
    pub state: EnvironmentState,
}

impl CacheEntry {
    /// A fresh entry stamped "now".
    pub fn fresh(state: EnvironmentState) -> Self {
        Self {
            saved_at: unix_secs_now(),
            state,
        }
    }

    /// How many seconds old the entry is.
    pub fn age_secs(&self) -> u64 {
        unix_secs_now().saturating_sub(self.saved_at)
    }

    /// Whether the entry is still within [`CACHE_TTL`].
    pub fn is_fresh(&self) -> bool {
        self.age_secs() < CACHE_TTL_SECS
    }
}

/// Current time as Unix seconds.
pub fn unix_secs_now() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_secs())
        .unwrap_or(0)
}

/// Writes `contents` to `path` via a sibling temp file and a rename, so a
/// crash mid-write never leaves a half-written target file behind. Parent
/// directories are created on demand.
fn atomic_write(path: &Path, contents: &[u8]) -> Result<(), String> {
    let parent = path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));
    fs::create_dir_all(parent)
        .map_err(|err| format!("could not create {}: {err}", parent.display()))?;

    let name = path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("data.json");
    let tmp = parent.join(format!(".{name}.tmp"));

    fs::write(&tmp, contents)
        .map_err(|err| format!("could not write {}: {err}", tmp.display()))?;
    if path.exists() {
        fs::remove_file(path)
            .map_err(|err| format!("could not replace {}: {err}", path.display()))?;
    }
    fs::rename(&tmp, path)
        .map_err(|err| format!("could not finalize {}: {err}", path.display()))?;
    Ok(())
}

// ---------------------------------------------------------------------------
// Convenience accessors against the default (home-dir) manager
// ---------------------------------------------------------------------------

/// Initializes the default config, creating `~/.limitless/` on first run.
pub fn init_config() -> Result<LimitlessConfig, String> {
    PersistenceManager::default().init_config()
}

/// Saves the configuration to `~/.limitless/config.json`.
pub fn save_config(config: &LimitlessConfig) -> Result<(), String> {
    PersistenceManager::default().save_config(config)
}

/// Loads lifetime stats from `~/.limitless/stats.json` (empty when missing).
pub fn load_stats() -> Result<ArcadeStats, String> {
    PersistenceManager::default().load_stats()
}

/// Saves lifetime stats to `~/.limitless/stats.json`.
pub fn save_stats(stats: &ArcadeStats) -> Result<(), String> {
    PersistenceManager::default().save_stats(stats)
}

/// Returns the cached diagnostics snapshot when it is fresh.
pub fn get_cached_diagnostics() -> Option<EnvironmentState> {
    PersistenceManager::default().get_cached_diagnostics()
}

/// Snapshots the given state to the cache file.
pub fn cache_diagnostics(state: &EnvironmentState) -> Result<(), String> {
    PersistenceManager::default().cache_diagnostics(state)
}

// ---------------------------------------------------------------------------
// Tests (isolated to a temp directory — never touches the real home)
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::{CheckStatus, DiagnosticResult, HealthScore, ProjectStack};
    use std::fs;

    struct TempDir(PathBuf);

    impl TempDir {
        fn new(tag: &str) -> Self {
            let path = std::env::temp_dir().join(format!(
                "limitless_config_{}_{}_{}",
                tag,
                std::process::id(),
                unix_secs_now()
            ));
            Self(path)
        }

        fn path(&self) -> &Path {
            &self.0
        }
    }

    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    fn manager(tag: &str) -> (PersistenceManager, TempDir) {
        let dir = TempDir::new(tag);
        let manager = PersistenceManager::at_dir(dir.path().join(".limitless"));
        (manager, dir)
    }

    fn sample_state() -> EnvironmentState {
        let diagnostics = vec![
            DiagnosticResult::new("Runtime Check", CheckStatus::Pass, "ok"),
            DiagnosticResult::new("Env Audit", CheckStatus::Warn, "no .env"),
        ];
        EnvironmentState {
            detected_stack: ProjectStack::Node {
                version: "22.0.0".into(),
                package_manager: "npm".into(),
            },
            runtime_version: Some("v22.0.0".into()),
            env_file_exists: false,
            env_example_exists: true,
            dependencies_healthy: true,
            blocked_ports: vec![(3000, 1234)],
            diagnostics: diagnostics.clone(),
            health_score: HealthScore::from_results(&diagnostics),
        }
    }

    #[test]
    fn default_config_json_matches_spec() {
        let json = serde_json::to_string_pretty(&LimitlessConfig::default()).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["preferred_stack"], serde_json::Value::Null);
        assert_eq!(parsed["auto_approve_safe_fixes"], false);
        assert_eq!(parsed["color_enabled"], true);
        assert_eq!(parsed["animation_enabled"], true);
        assert_eq!(parsed["verbose_mode"], false);
    }

    #[test]
    fn init_config_creates_directory_and_default_file() {
        let (manager, dir) = manager("init_default");
        let config = manager.init_config().unwrap();
        assert_eq!(config, LimitlessConfig::default());
        assert!(dir.path().join(".limitless").is_dir());
        assert!(manager.config_file.is_file());

        let json = fs::read_to_string(&manager.config_file).unwrap();
        assert!(json.contains("\"preferred_stack\": null"));
        assert!(json.contains("\"color_enabled\": true"));
    }

    #[test]
    fn init_config_preserves_existing_settings() {
        let (manager, _dir) = manager("init_keep");
        let custom = LimitlessConfig {
            preferred_stack: Some(ProjectStack::Python { version: "3.12".into() }),
            auto_approve_safe_fixes: true,
            color_enabled: false,
            animation_enabled: false,
            verbose_mode: true,
        };
        manager.save_config(&custom).unwrap();
        assert_eq!(manager.init_config().unwrap(), custom);
    }

    #[test]
    fn initializing_twice_is_idempotent() {
        let (manager, _dir) = manager("init_idem");
        let first = manager.init_config().unwrap();
        let second = manager.init_config().unwrap();
        assert_eq!(first, second);
        let text = fs::read_to_string(&manager.config_file).unwrap();
        assert!(!text.contains("__idem__"));
    }

    #[test]
    fn init_config_errors_on_corrupt_file() {
        let (manager, _dir) = manager("init_corrupt");
        fs::create_dir_all(&manager.config_dir).unwrap();
        fs::write(&manager.config_file, "not json {").unwrap();
        let err = manager.init_config().unwrap_err();
        assert!(err.contains("config.json"), "{err}");
    }

    #[test]
    fn load_config_is_none_when_missing() {
        let (manager, _dir) = manager("load_missing");
        assert_eq!(manager.load_config().unwrap(), None);
    }

    #[test]
    fn save_config_creates_nested_directory_atomically() {
        let dir = TempDir::new("deep");
        let manager = PersistenceManager::at_dir(dir.path().join("a").join("b").join(".limitless"));
        manager.save_config(&LimitlessConfig::default()).unwrap();
        assert!(manager.config_file.is_file());

        let leftover: Vec<_> = fs::read_dir(&manager.config_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))
            .collect();
        assert!(leftover.is_empty(), "temp file left behind");
    }

    #[test]
    fn preferred_stack_round_trips() {
        let (manager, _dir) = manager("stack_rt");
        let config = LimitlessConfig {
            preferred_stack: Some(ProjectStack::Rust { version: "1.80.0".into() }),
            ..LimitlessConfig::default()
        };
        manager.save_config(&config).unwrap();
        assert_eq!(manager.load_config().unwrap(), Some(config));
    }

    #[test]
    fn load_stats_returns_defaults_when_missing() {
        let (manager, _dir) = manager("stats_missing");
        let stats = manager.load_stats().unwrap();
        assert_eq!(stats.diagnostics_run, 0);
        assert_eq!(stats.best_arcade_score, 0);
    }

    #[test]
    fn save_then_load_stats_round_trips() {
        let (manager, _dir) = manager("stats_rt");
        let mut stats = ArcadeStats::default();
        stats.record_diagnostic_at(1200, 3);
        stats.record_fix();
        stats.record_process_killed();
        stats.record_arcade_game(900);

        manager.save_stats(&stats).unwrap();
        assert!(manager.stats_file.is_file());
        assert_eq!(manager.load_stats().unwrap(), stats);
    }

    #[test]
    fn load_stats_errors_on_corrupt_file() {
        let (manager, _dir) = manager("stats_corrupt");
        fs::create_dir_all(&manager.config_dir).unwrap();
        fs::write(&manager.stats_file, "{oops").unwrap();
        let err = manager.load_stats().unwrap_err();
        assert!(err.contains("stats.json"), "{err}");
    }

    #[test]
    fn cache_round_trips_within_ttl() {
        let (manager, _dir) = manager("cache_rt");
        let state = sample_state();
        manager.cache_diagnostics(&state).unwrap();
        assert!(manager.cache_file.is_file());
        assert_eq!(manager.get_cached_diagnostics(), Some(state));
    }

    #[test]
    fn cache_expires_after_ttl() {
        let (manager, _dir) = manager("cache_ttl");
        let state = sample_state();
        // Write an entry stamped just past the TTL.
        let entry = CacheEntry {
            saved_at: unix_secs_now().saturating_sub(CACHE_TTL_SECS + 1),
            state,
        };
        fs::create_dir_all(&manager.config_dir).unwrap();
        fs::write(
            &manager.cache_file,
            serde_json::to_string_pretty(&entry).unwrap(),
        )
        .unwrap();
        assert!(entry.age_secs() >= CACHE_TTL_SECS);
        assert_eq!(manager.get_cached_diagnostics(), None);
    }

    #[test]
    fn cache_boundary_exactly_at_ttl_still_counts_fresh() {
        let (manager, _dir) = manager("cache_edge");
        let entry = CacheEntry {
            saved_at: unix_secs_now().saturating_sub(CACHE_TTL_SECS - 1),
            state: sample_state(),
        };
        fs::create_dir_all(&manager.config_dir).unwrap();
        fs::write(
            &manager.cache_file,
            serde_json::to_string_pretty(&entry).unwrap(),
        )
        .unwrap();
        assert!(entry.is_fresh());
        assert!(manager.get_cached_diagnostics().is_some());
    }

    #[test]
    fn cache_missing_file_returns_none() {
        let (manager, _dir) = manager("cache_missing");
        assert_eq!(manager.get_cached_diagnostics(), None);
    }

    #[test]
    fn cache_corrupt_file_returns_none() {
        let (manager, _dir) = manager("cache_bad");
        fs::create_dir_all(&manager.config_dir).unwrap();
        fs::write(&manager.cache_file, "garbage").unwrap();
        assert_eq!(manager.get_cached_diagnostics(), None);
    }

    #[test]
    fn default_manager_uses_home_directory() {
        let home = home_dir().expect("home dir should exist in tests");
        let manager = PersistenceManager::default();
        assert_eq!(manager.config_dir, home.join(".limitless"));
    }

    #[test]
    fn load_stats_reads_legacy_progress_wrapper() {
        let (manager, _dir) = manager("stats_wrapper");
        let mut wrapped = AchievementProgress::default();
        wrapped.stats.record_diagnostic(500);
        wrapped.unlocked.push("Speed Runner".into());
        let json = serde_json::to_string_pretty(&wrapped).unwrap();
        // Confirm this is the wrapper shape, not bare stats.
        assert!(json.contains("\"unlocked\""));
        fs::create_dir_all(&manager.config_dir).unwrap();
        fs::write(&manager.stats_file, json).unwrap();
        assert_eq!(manager.load_stats().unwrap(), wrapped.stats);
    }

    #[test]
    fn free_functions_target_the_default_manager() {
        assert!(init_config().is_ok());
        assert!(load_stats().is_ok());
        assert_eq!(get_cached_diagnostics(), None);
    }
}