Skip to main content

limitless_cli/modules/
config.rs

1//! **Config & persistence** — user preferences plus durable storage for
2//! preferences, lifetime stats and the diagnostic cache.
3//!
4//! Everything lives under `<home>/.limitless/`:
5//!
6//! | File          | Contents                                              |
7//! |---------------|-------------------------------------------------------|
8//! | `config.json` | [`LimitlessConfig`] user preferences (auto-created)   |
9//! | `stats.json`  | [`ArcadeStats`] lifetime usage counters               |
10//! | `cache.json`  | Last [`EnvironmentState`] snapshot (5-minute TTL)     |
11//!
12//! The [`PersistenceManager`] owns those paths. Its default instance targets
13//! the user's home directory, but `from_home` / `at_dir` let callers (and
14//! tests) point persistence at any directory. Writes go through a temp-file
15//! then rename so a crash mid-write never corrupts the real file.
16//!
17//! ```
18//! use limitless_cli::modules::config::{LimitlessConfig, PersistenceManager};
19//!
20//! let dir = std::env::temp_dir().join(format!(
21//!     "limitless_config_doc_{}_{}",
22//!     std::process::id(),
23//!     std::time::SystemTime::now()
24//!         .duration_since(std::time::UNIX_EPOCH)
25//!         .map(|d| d.as_nanos())
26//!         .unwrap_or(0)
27//! ));
28//! let manager = PersistenceManager::from_home(&dir);
29//!
30//! // First init creates ~/.limitless/config.json with defaults.
31//! let config = manager.init_config().unwrap();
32//! assert!(config.color_enabled);
33//! assert!(config.animation_enabled);
34//!
35//! // Stats default to an empty counter set when the file is absent.
36//! let stats = manager.load_stats().unwrap();
37//! assert_eq!(stats.diagnostics_run, 0);
38//!
39//! let _ = std::fs::remove_dir_all(&dir);
40//! ```
41
42use crate::modules::achievements::{home_dir, AchievementProgress, ArcadeStats};
43use crate::models::{EnvironmentState, HealthScore, ProjectStack};
44use serde::{Deserialize, Serialize};
45use std::fs;
46use std::path::{Path, PathBuf};
47use std::time::{Duration, SystemTime, UNIX_EPOCH};
48
49/// How long a cached [`EnvironmentState`] snapshot is considered fresh.
50pub const CACHE_TTL: Duration = Duration::from_secs(300);
51
52/// [`CACHE_TTL`] expressed in seconds (handy for tests).
53pub const CACHE_TTL_SECS: u64 = 300;
54
55/// Default colors/animations and empty preferred stack.
56pub fn default_config() -> LimitlessConfig {
57    LimitlessConfig {
58        preferred_stack: None,
59        auto_approve_safe_fixes: false,
60        color_enabled: true,
61        animation_enabled: true,
62        verbose_mode: false,
63    }
64}
65
66/// User preferences, persisted as `config.json`.
67///
68/// ```
69/// use limitless_cli::modules::config::{LimitlessConfig, default_config};
70///
71/// let config = default_config();
72/// assert_eq!(config.auto_approve_safe_fixes, false);
73/// assert_eq!(config.color_enabled, true);
74/// assert_eq!(config.animation_enabled, true);
75/// assert_eq!(config.verbose_mode, false);
76/// ```
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(default)]
79pub struct LimitlessConfig {
80    /// The stack the user prefers to target, when the current directory is
81    /// ambiguous or not a project (null = auto-detect).
82    pub preferred_stack: Option<ProjectStack>,
83    /// Apply safe, reversible fixes without asking first.
84    pub auto_approve_safe_fixes: bool,
85    /// Use ANSI colors in terminal output.
86    pub color_enabled: bool,
87    /// Show progress animations (spinners / progress bars).
88    pub animation_enabled: bool,
89    /// Show technical details by default.
90    pub verbose_mode: bool,
91}
92
93impl Default for LimitlessConfig {
94    fn default() -> Self {
95        default_config()
96    }
97}
98
99/// Owns the `~/.limitless/` data directory and its three JSON files.
100///
101/// ```
102/// use limitless_cli::modules::config::PersistenceManager;
103/// let manager = PersistenceManager::default();
104/// assert!(manager.config_file.ends_with("config.json"));
105/// assert!(manager.stats_file.ends_with("stats.json"));
106/// assert!(manager.cache_file.ends_with("cache.json"));
107/// ```
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct PersistenceManager {
110    /// The `.limitless` data directory.
111    pub config_dir: PathBuf,
112    /// Path to `config.json` (user preferences).
113    pub config_file: PathBuf,
114    /// Path to `stats.json` (lifetime counters).
115    pub stats_file: PathBuf,
116    /// Path to `cache.json` (last diagnostics snapshot).
117    pub cache_file: PathBuf,
118}
119
120impl PersistenceManager {
121    /// A manager rooted at an explicit `.limitless` directory (tests use
122    /// this to keep the real home directory untouched).
123    pub fn at_dir(dir: impl AsRef<Path>) -> Self {
124        let dir = dir.as_ref().to_path_buf();
125        Self {
126            config_dir: dir.clone(),
127            config_file: dir.join("config.json"),
128            stats_file: dir.join("stats.json"),
129            cache_file: dir.join("cache.json"),
130        }
131    }
132
133    /// A manager rooted at `<home>/.limitless` for a given home directory.
134    pub fn from_home(home: impl AsRef<Path>) -> Self {
135        Self::at_dir(home.as_ref().join(".limitless"))
136    }
137
138    // ------------------------------------------------------------------
139    // Configuration
140    // ------------------------------------------------------------------
141
142    /// Loads the config file, or `None` when it does not exist.
143    ///
144    /// A corrupt file is an error (not silently a default), so bad edits are
145    /// visible instead of silently reset.
146    pub fn load_config(&self) -> Result<Option<LimitlessConfig>, String> {
147        if !self.config_file.exists() {
148            return Ok(None);
149        }
150        let raw = fs::read_to_string(&self.config_file)
151            .map_err(|err| format!("could not read {}: {err}", self.config_file.display()))?;
152        serde_json::from_str(&raw)
153            .map(Some)
154            .map_err(|err| format!("invalid config file {}: {err}", self.config_file.display()))
155    }
156
157    /// Ensures the data directory and config file exist, then returns the
158    /// parsed configuration. Missing files are recreated with defaults.
159    pub fn init_config(&self) -> Result<LimitlessConfig, String> {
160        fs::create_dir_all(&self.config_dir)
161            .map_err(|err| format!("could not create {}: {err}", self.config_dir.display()))?;
162        if !self.config_file.exists() {
163            self.save_config(&LimitlessConfig::default())?;
164        }
165        self.load_config()?.ok_or_else(|| {
166            format!("{} disappeared during init", self.config_file.display())
167        })
168    }
169
170    /// Persists the configuration atomically, creating directories as needed.
171    pub fn save_config(&self, config: &LimitlessConfig) -> Result<(), String> {
172        let json = serde_json::to_string_pretty(config)
173            .map_err(|err| format!("could not serialize config: {err}"))?;
174        atomic_write(&self.config_file, json.as_bytes())
175    }
176
177    // ------------------------------------------------------------------
178    // Stats
179    // ------------------------------------------------------------------
180
181    /// Loads the lifetime usage counters. A missing file yields an empty
182    /// [`ArcadeStats`]; a corrupt file is surfaced as an error. Pre-`config.rs`
183    /// files that stored the old `{stats, unlocked}` progress wrapper in
184    /// `stats.json` are read via the inner counters.
185    pub fn load_stats(&self) -> Result<ArcadeStats, String> {
186        if !self.stats_file.exists() {
187            return Ok(ArcadeStats::default());
188        }
189        let raw = fs::read_to_string(&self.stats_file)
190            .map_err(|err| format!("could not read {}: {err}", self.stats_file.display()))?;
191        if let Ok(stats) = serde_json::from_str::<ArcadeStats>(&raw) {
192            return Ok(stats);
193        }
194        if let Ok(legacy) = serde_json::from_str::<AchievementProgress>(&raw) {
195            return Ok(legacy.stats);
196        }
197        Err(format!(
198            "invalid stats file {}",
199            self.stats_file.display()
200        ))
201    }
202
203    /// Persists the lifetime counters atomically, creating directories as
204    /// needed. Always saves a full snapshot (counters keep accumulating
205    /// across runs).
206    pub fn save_stats(&self, stats: &ArcadeStats) -> Result<(), String> {
207        let json = serde_json::to_string_pretty(stats)
208            .map_err(|err| format!("could not serialize stats: {err}"))?;
209        atomic_write(&self.stats_file, json.as_bytes())
210    }
211
212    // ------------------------------------------------------------------
213    // Cache
214    // ------------------------------------------------------------------
215
216    /// Snapshots the current diagnostics state with a fresh timestamp.
217    pub fn cache_diagnostics(&self, state: &EnvironmentState) -> Result<(), String> {
218        let entry = CacheEntry::fresh(state.clone());
219        let json = serde_json::to_string_pretty(&entry)
220            .map_err(|err| format!("could not serialize cache: {err}"))?;
221        atomic_write(&self.cache_file, json.as_bytes())
222    }
223
224    /// Reads the raw cache entry, or `None` when the file is missing.
225    fn cached_entry(&self) -> Result<Option<CacheEntry>, String> {
226        if !self.cache_file.exists() {
227            return Ok(None);
228        }
229        let raw = fs::read_to_string(&self.cache_file)
230            .map_err(|err| format!("could not read {}: {err}", self.cache_file.display()))?;
231        serde_json::from_str(&raw)
232            .map(Some)
233            .map_err(|err| format!("invalid cache file {}: {err}", self.cache_file.display()))
234    }
235
236    /// Returns the cached [`EnvironmentState`] when it is fresh (≤ 5 minutes
237    /// old). Expired, missing or corrupt caches yield `None`.
238    ///
239    /// On a hit the health score is recomputed so it is never stale.
240    pub fn get_cached_diagnostics(&self) -> Option<EnvironmentState> {
241        let entry = self.cached_entry().ok().flatten()?;
242        if !entry.is_fresh() {
243            return None;
244        }
245        let mut state = entry.state;
246        state.health_score = HealthScore::from_results(&state.diagnostics);
247        Some(state)
248    }
249}
250
251impl Default for PersistenceManager {
252    /// Points at `<home>/.limitless`, falling back to the current directory
253    /// when no home directory can be resolved.
254    fn default() -> Self {
255        match home_dir() {
256            Some(home) => Self::from_home(home),
257            None => Self::at_dir(
258                std::env::current_dir()
259                    .unwrap_or_else(|_| PathBuf::from("."))
260                    .join(".limitless"),
261            ),
262        }
263    }
264}
265
266/// A cached [`EnvironmentState`] with the Unix timestamp when it was saved.
267#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
268pub struct CacheEntry {
269    /// Seconds since the Unix epoch at save time.
270    pub saved_at: u64,
271    /// The snapshot that was cached.
272    pub state: EnvironmentState,
273}
274
275impl CacheEntry {
276    /// A fresh entry stamped "now".
277    pub fn fresh(state: EnvironmentState) -> Self {
278        Self {
279            saved_at: unix_secs_now(),
280            state,
281        }
282    }
283
284    /// How many seconds old the entry is.
285    pub fn age_secs(&self) -> u64 {
286        unix_secs_now().saturating_sub(self.saved_at)
287    }
288
289    /// Whether the entry is still within [`CACHE_TTL`].
290    pub fn is_fresh(&self) -> bool {
291        self.age_secs() < CACHE_TTL_SECS
292    }
293}
294
295/// Current time as Unix seconds.
296pub fn unix_secs_now() -> u64 {
297    SystemTime::now()
298        .duration_since(UNIX_EPOCH)
299        .map(|duration| duration.as_secs())
300        .unwrap_or(0)
301}
302
303/// Writes `contents` to `path` via a sibling temp file and a rename, so a
304/// crash mid-write never leaves a half-written target file behind. Parent
305/// directories are created on demand.
306fn atomic_write(path: &Path, contents: &[u8]) -> Result<(), String> {
307    let parent = path
308        .parent()
309        .filter(|p| !p.as_os_str().is_empty())
310        .unwrap_or_else(|| Path::new("."));
311    fs::create_dir_all(parent)
312        .map_err(|err| format!("could not create {}: {err}", parent.display()))?;
313
314    let name = path
315        .file_name()
316        .and_then(|name| name.to_str())
317        .unwrap_or("data.json");
318    let tmp = parent.join(format!(".{name}.tmp"));
319
320    fs::write(&tmp, contents)
321        .map_err(|err| format!("could not write {}: {err}", tmp.display()))?;
322    if path.exists() {
323        fs::remove_file(path)
324            .map_err(|err| format!("could not replace {}: {err}", path.display()))?;
325    }
326    fs::rename(&tmp, path)
327        .map_err(|err| format!("could not finalize {}: {err}", path.display()))?;
328    Ok(())
329}
330
331// ---------------------------------------------------------------------------
332// Convenience accessors against the default (home-dir) manager
333// ---------------------------------------------------------------------------
334
335/// Initializes the default config, creating `~/.limitless/` on first run.
336pub fn init_config() -> Result<LimitlessConfig, String> {
337    PersistenceManager::default().init_config()
338}
339
340/// Saves the configuration to `~/.limitless/config.json`.
341pub fn save_config(config: &LimitlessConfig) -> Result<(), String> {
342    PersistenceManager::default().save_config(config)
343}
344
345/// Loads lifetime stats from `~/.limitless/stats.json` (empty when missing).
346pub fn load_stats() -> Result<ArcadeStats, String> {
347    PersistenceManager::default().load_stats()
348}
349
350/// Saves lifetime stats to `~/.limitless/stats.json`.
351pub fn save_stats(stats: &ArcadeStats) -> Result<(), String> {
352    PersistenceManager::default().save_stats(stats)
353}
354
355/// Returns the cached diagnostics snapshot when it is fresh.
356pub fn get_cached_diagnostics() -> Option<EnvironmentState> {
357    PersistenceManager::default().get_cached_diagnostics()
358}
359
360/// Snapshots the given state to the cache file.
361pub fn cache_diagnostics(state: &EnvironmentState) -> Result<(), String> {
362    PersistenceManager::default().cache_diagnostics(state)
363}
364
365// ---------------------------------------------------------------------------
366// Tests (isolated to a temp directory — never touches the real home)
367// ---------------------------------------------------------------------------
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372    use crate::models::{CheckStatus, DiagnosticResult, HealthScore, ProjectStack};
373    use std::fs;
374
375    struct TempDir(PathBuf);
376
377    impl TempDir {
378        fn new(tag: &str) -> Self {
379            let path = std::env::temp_dir().join(format!(
380                "limitless_config_{}_{}_{}",
381                tag,
382                std::process::id(),
383                unix_secs_now()
384            ));
385            Self(path)
386        }
387
388        fn path(&self) -> &Path {
389            &self.0
390        }
391    }
392
393    impl Drop for TempDir {
394        fn drop(&mut self) {
395            let _ = fs::remove_dir_all(&self.0);
396        }
397    }
398
399    fn manager(tag: &str) -> (PersistenceManager, TempDir) {
400        let dir = TempDir::new(tag);
401        let manager = PersistenceManager::at_dir(dir.path().join(".limitless"));
402        (manager, dir)
403    }
404
405    fn sample_state() -> EnvironmentState {
406        let diagnostics = vec![
407            DiagnosticResult::new("Runtime Check", CheckStatus::Pass, "ok"),
408            DiagnosticResult::new("Env Audit", CheckStatus::Warn, "no .env"),
409        ];
410        EnvironmentState {
411            detected_stack: ProjectStack::Node {
412                version: "22.0.0".into(),
413                package_manager: "npm".into(),
414            },
415            runtime_version: Some("v22.0.0".into()),
416            env_file_exists: false,
417            env_example_exists: true,
418            dependencies_healthy: true,
419            blocked_ports: vec![(3000, 1234)],
420            diagnostics: diagnostics.clone(),
421            health_score: HealthScore::from_results(&diagnostics),
422        }
423    }
424
425    #[test]
426    fn default_config_json_matches_spec() {
427        let json = serde_json::to_string_pretty(&LimitlessConfig::default()).unwrap();
428        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
429        assert_eq!(parsed["preferred_stack"], serde_json::Value::Null);
430        assert_eq!(parsed["auto_approve_safe_fixes"], false);
431        assert_eq!(parsed["color_enabled"], true);
432        assert_eq!(parsed["animation_enabled"], true);
433        assert_eq!(parsed["verbose_mode"], false);
434    }
435
436    #[test]
437    fn init_config_creates_directory_and_default_file() {
438        let (manager, dir) = manager("init_default");
439        let config = manager.init_config().unwrap();
440        assert_eq!(config, LimitlessConfig::default());
441        assert!(dir.path().join(".limitless").is_dir());
442        assert!(manager.config_file.is_file());
443
444        let json = fs::read_to_string(&manager.config_file).unwrap();
445        assert!(json.contains("\"preferred_stack\": null"));
446        assert!(json.contains("\"color_enabled\": true"));
447    }
448
449    #[test]
450    fn init_config_preserves_existing_settings() {
451        let (manager, _dir) = manager("init_keep");
452        let custom = LimitlessConfig {
453            preferred_stack: Some(ProjectStack::Python { version: "3.12".into() }),
454            auto_approve_safe_fixes: true,
455            color_enabled: false,
456            animation_enabled: false,
457            verbose_mode: true,
458        };
459        manager.save_config(&custom).unwrap();
460        assert_eq!(manager.init_config().unwrap(), custom);
461    }
462
463    #[test]
464    fn initializing_twice_is_idempotent() {
465        let (manager, _dir) = manager("init_idem");
466        let first = manager.init_config().unwrap();
467        let second = manager.init_config().unwrap();
468        assert_eq!(first, second);
469        let text = fs::read_to_string(&manager.config_file).unwrap();
470        assert!(!text.contains("__idem__"));
471    }
472
473    #[test]
474    fn init_config_errors_on_corrupt_file() {
475        let (manager, _dir) = manager("init_corrupt");
476        fs::create_dir_all(&manager.config_dir).unwrap();
477        fs::write(&manager.config_file, "not json {").unwrap();
478        let err = manager.init_config().unwrap_err();
479        assert!(err.contains("config.json"), "{err}");
480    }
481
482    #[test]
483    fn load_config_is_none_when_missing() {
484        let (manager, _dir) = manager("load_missing");
485        assert_eq!(manager.load_config().unwrap(), None);
486    }
487
488    #[test]
489    fn save_config_creates_nested_directory_atomically() {
490        let dir = TempDir::new("deep");
491        let manager = PersistenceManager::at_dir(dir.path().join("a").join("b").join(".limitless"));
492        manager.save_config(&LimitlessConfig::default()).unwrap();
493        assert!(manager.config_file.is_file());
494
495        let leftover: Vec<_> = fs::read_dir(&manager.config_dir)
496            .unwrap()
497            .filter_map(|e| e.ok())
498            .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))
499            .collect();
500        assert!(leftover.is_empty(), "temp file left behind");
501    }
502
503    #[test]
504    fn preferred_stack_round_trips() {
505        let (manager, _dir) = manager("stack_rt");
506        let config = LimitlessConfig {
507            preferred_stack: Some(ProjectStack::Rust { version: "1.80.0".into() }),
508            ..LimitlessConfig::default()
509        };
510        manager.save_config(&config).unwrap();
511        assert_eq!(manager.load_config().unwrap(), Some(config));
512    }
513
514    #[test]
515    fn load_stats_returns_defaults_when_missing() {
516        let (manager, _dir) = manager("stats_missing");
517        let stats = manager.load_stats().unwrap();
518        assert_eq!(stats.diagnostics_run, 0);
519        assert_eq!(stats.best_arcade_score, 0);
520    }
521
522    #[test]
523    fn save_then_load_stats_round_trips() {
524        let (manager, _dir) = manager("stats_rt");
525        let mut stats = ArcadeStats::default();
526        stats.record_diagnostic_at(1200, 3);
527        stats.record_fix();
528        stats.record_process_killed();
529        stats.record_arcade_game(900);
530
531        manager.save_stats(&stats).unwrap();
532        assert!(manager.stats_file.is_file());
533        assert_eq!(manager.load_stats().unwrap(), stats);
534    }
535
536    #[test]
537    fn load_stats_errors_on_corrupt_file() {
538        let (manager, _dir) = manager("stats_corrupt");
539        fs::create_dir_all(&manager.config_dir).unwrap();
540        fs::write(&manager.stats_file, "{oops").unwrap();
541        let err = manager.load_stats().unwrap_err();
542        assert!(err.contains("stats.json"), "{err}");
543    }
544
545    #[test]
546    fn cache_round_trips_within_ttl() {
547        let (manager, _dir) = manager("cache_rt");
548        let state = sample_state();
549        manager.cache_diagnostics(&state).unwrap();
550        assert!(manager.cache_file.is_file());
551        assert_eq!(manager.get_cached_diagnostics(), Some(state));
552    }
553
554    #[test]
555    fn cache_expires_after_ttl() {
556        let (manager, _dir) = manager("cache_ttl");
557        let state = sample_state();
558        // Write an entry stamped just past the TTL.
559        let entry = CacheEntry {
560            saved_at: unix_secs_now().saturating_sub(CACHE_TTL_SECS + 1),
561            state,
562        };
563        fs::create_dir_all(&manager.config_dir).unwrap();
564        fs::write(
565            &manager.cache_file,
566            serde_json::to_string_pretty(&entry).unwrap(),
567        )
568        .unwrap();
569        assert!(entry.age_secs() >= CACHE_TTL_SECS);
570        assert_eq!(manager.get_cached_diagnostics(), None);
571    }
572
573    #[test]
574    fn cache_boundary_exactly_at_ttl_still_counts_fresh() {
575        let (manager, _dir) = manager("cache_edge");
576        let entry = CacheEntry {
577            saved_at: unix_secs_now().saturating_sub(CACHE_TTL_SECS - 1),
578            state: sample_state(),
579        };
580        fs::create_dir_all(&manager.config_dir).unwrap();
581        fs::write(
582            &manager.cache_file,
583            serde_json::to_string_pretty(&entry).unwrap(),
584        )
585        .unwrap();
586        assert!(entry.is_fresh());
587        assert!(manager.get_cached_diagnostics().is_some());
588    }
589
590    #[test]
591    fn cache_missing_file_returns_none() {
592        let (manager, _dir) = manager("cache_missing");
593        assert_eq!(manager.get_cached_diagnostics(), None);
594    }
595
596    #[test]
597    fn cache_corrupt_file_returns_none() {
598        let (manager, _dir) = manager("cache_bad");
599        fs::create_dir_all(&manager.config_dir).unwrap();
600        fs::write(&manager.cache_file, "garbage").unwrap();
601        assert_eq!(manager.get_cached_diagnostics(), None);
602    }
603
604    #[test]
605    fn default_manager_uses_home_directory() {
606        let home = home_dir().expect("home dir should exist in tests");
607        let manager = PersistenceManager::default();
608        assert_eq!(manager.config_dir, home.join(".limitless"));
609    }
610
611    #[test]
612    fn load_stats_reads_legacy_progress_wrapper() {
613        let (manager, _dir) = manager("stats_wrapper");
614        let mut wrapped = AchievementProgress::default();
615        wrapped.stats.record_diagnostic(500);
616        wrapped.unlocked.push("Speed Runner".into());
617        let json = serde_json::to_string_pretty(&wrapped).unwrap();
618        // Confirm this is the wrapper shape, not bare stats.
619        assert!(json.contains("\"unlocked\""));
620        fs::create_dir_all(&manager.config_dir).unwrap();
621        fs::write(&manager.stats_file, json).unwrap();
622        assert_eq!(manager.load_stats().unwrap(), wrapped.stats);
623    }
624
625    #[test]
626    fn free_functions_target_the_default_manager() {
627        assert!(init_config().is_ok());
628        assert!(load_stats().is_ok());
629        assert_eq!(get_cached_diagnostics(), None);
630    }
631}