Skip to main content

limitless_cli/modules/
achievements.rs

1//! **Achievements** — a badge / unlock system for Limitless CLI.
2//!
3//! Usage is tracked in an [`ArcadeStats`] counter bundle; a fixed registry
4//! ([`BADGES`]) maps conditions to five unlockable badges, and
5//! [`check_badges`] reports which ones the current stats satisfy. Progress
6//! is persisted to `~/.limitless/achievements.json` (in the user's home
7//! directory; stats.json there belongs to `crate::modules::config`) through
8//! [`AchievementProgress`], which records newly-unlocked badges and renders
9//! their shareable popup via [`render_badge_popup`].
10//!
11//! ```
12//! use limitless_cli::modules::achievements::{
13//!     AchievementProgress, ArcadeStats, BADGES, check_badges,
14//! };
15//!
16//! // The registry has the five spec'd badges.
17//! assert_eq!(BADGES.len(), 5);
18//!
19//! // Pure condition check over stats.
20//! let mut stats = ArcadeStats::default();
21//! stats.processes_killed = 5;
22//! assert_eq!(check_badges(&stats), vec!["Port Whisperer"]);
23//!
24//! // The store only reports *newly* unlocked badges, once.
25//! let mut progress = AchievementProgress::default();
26//! progress.stats.processes_killed = 5;
27//! assert_eq!(progress.check_unlocked(), vec!["Port Whisperer"]);
28//! assert!(progress.check_unlocked().is_empty());
29//! ```
30
31use std::collections::HashMap;
32use std::fs;
33use std::io;
34use std::path::{Path, PathBuf};
35use std::time::{SystemTime, UNIX_EPOCH};
36
37/// Width in characters of the badge popup frame.
38pub const POPUP_WIDTH: usize = 60;
39
40/// Inner text width between the two vertical frame bars.
41const POPUP_INNER: usize = POPUP_WIDTH - 4;
42
43/// Number of ghost processes [`BadgeCondition::PortWhisperer`] requires.
44pub const GHOST_PROCESS_TARGET: u32 = 5;
45
46/// Number of `.env` files [`BadgeCondition::EnvMaster`] requires.
47pub const ENV_MASTER_TARGET: u32 = 10;
48
49/// Diagnostic duration (ms) [`BadgeCondition::SpeedRunner`] requires.
50pub const SPEED_RUNNER_MS: u32 = 5000;
51
52/// Earliest local hour (inclusive) for [`BadgeCondition::NightOwl`].
53pub const NIGHT_OWL_FROM_HOUR: u32 = 2;
54
55/// Latest local hour (inclusive) for [`BadgeCondition::NightOwl`].
56pub const NIGHT_OWL_TO_HOUR: u32 = 5;
57
58// ---------------------------------------------------------------------------
59// Badge conditions
60// ---------------------------------------------------------------------------
61
62/// A predicate over [`ArcadeStats`] that decides when a badge unlocks.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum BadgeCondition {
65    /// Applying at least one auto-fix.
66    FirstFixExecuted,
67    /// Reaching `count` consecutive perfectly-healthy runs.
68    PerfectHealth { count: u32 },
69    /// Killing at least [`GHOST_PROCESS_TARGET`] ghost processes.
70    PortWhisperer,
71    /// Creating at least [`ENV_MASTER_TARGET`] `.env` files.
72    EnvMaster,
73    /// Reserved: no current data source, never triggered by the shipped
74    /// badges. Kept so the condition vocabulary matches the design spec.
75    DependencyHero,
76    /// Beating `score` points in SyntaxBreaker.
77    ArcadeWin { score: u32 },
78    /// A diagnostic scan completing under [`SPEED_RUNNER_MS`] milliseconds.
79    SpeedRunner,
80    /// Having run Limitless during a local hour in
81    /// [`NIGHT_OWL_FROM_HOUR`]..=[`NIGHT_OWL_TO_HOUR`].
82    NightOwl,
83}
84
85impl BadgeCondition {
86    /// Whether `stats` satisfy this condition.
87    pub fn matches(&self, stats: &ArcadeStats) -> bool {
88        match *self {
89            BadgeCondition::FirstFixExecuted => stats.fixes_applied > 0,
90            BadgeCondition::PerfectHealth { count } => {
91                stats.perfect_health_streak >= count
92            }
93            BadgeCondition::PortWhisperer => stats.processes_killed >= GHOST_PROCESS_TARGET,
94            BadgeCondition::EnvMaster => stats.env_files_created >= ENV_MASTER_TARGET,
95            BadgeCondition::DependencyHero => false,
96            BadgeCondition::ArcadeWin { score } => stats.best_arcade_score > score,
97            BadgeCondition::SpeedRunner => stats
98                .last_diagnostic_time_ms
99                .is_some_and(|t| t < SPEED_RUNNER_MS),
100            BadgeCondition::NightOwl => stats.times_run.iter().any(|(&hour, &count)| {
101                count > 0 && (NIGHT_OWL_FROM_HOUR..=NIGHT_OWL_TO_HOUR).contains(&hour)
102            }),
103        }
104    }
105}
106
107// ---------------------------------------------------------------------------
108// Badge registry
109// ---------------------------------------------------------------------------
110
111/// One unlockable badge. The emoji is a single Unicode scalar so it can be
112/// embedded in share messages and popup frames.
113///
114/// ```
115/// use limitless_cli::modules::achievements::Badge;
116/// let badge = Badge {
117///     id: "port-whisperer",
118///     name: "Port Whisperer",
119///     description: "Kill 5 ghost processes.",
120///     emoji: '\u{1F527}',
121///     unlock_condition: limitless_cli::modules::achievements::BadgeCondition::PortWhisperer,
122/// };
123/// assert_eq!(badge.emoji, '\u{1F527}');
124/// ```
125#[derive(Debug, Clone, PartialEq, Eq)]
126pub struct Badge {
127    /// Stable, kebab-case identifier (used for persistence).
128    pub id: &'static str,
129    /// Human-friendly display name.
130    pub name: &'static str,
131    /// Short flavour text shown inside the popup.
132    pub description: &'static str,
133    /// Single-char emoji shown alongside the name.
134    pub emoji: char,
135    /// What unlocks this badge.
136    pub unlock_condition: BadgeCondition,
137}
138
139/// The full badge database.
140///
141/// ```
142/// use limitless_cli::modules::achievements::BADGES;
143/// assert_eq!(BADGES.len(), 5);
144/// let names: Vec<&str> = BADGES.iter().map(|b| b.name).collect();
145/// assert_eq!(
146///     names,
147///     vec!["Port Whisperer", "Env Master", "Speed Runner",
148///          "Arcade Champion", "Night Owl"]
149/// );
150/// ```
151pub const BADGES: &[Badge] = &[
152    Badge {
153        id: "port-whisperer",
154        name: "Port Whisperer",
155        description: "Kill 5 ghost processes.",
156        emoji: '\u{1F527}',
157        unlock_condition: BadgeCondition::PortWhisperer,
158    },
159    Badge {
160        id: "env-master",
161        name: "Env Master",
162        description: "Create 10 .env files.",
163        emoji: '\u{1F6E1}',
164        unlock_condition: BadgeCondition::EnvMaster,
165    },
166    Badge {
167        id: "speed-runner",
168        name: "Speed Runner",
169        description: "Finish a diagnostic scan in under 5 seconds.",
170        emoji: '\u{1F4A8}',
171        unlock_condition: BadgeCondition::SpeedRunner,
172    },
173    Badge {
174        id: "arcade-champion",
175        name: "Arcade Champion",
176        description: "Score over 500 in SyntaxBreaker.",
177        emoji: '\u{1F3AE}',
178        unlock_condition: BadgeCondition::ArcadeWin { score: 500 },
179    },
180    Badge {
181        id: "night-owl",
182        name: "Night Owl",
183        description: "Run Limitless between 2 AM and 5 AM.",
184        emoji: '\u{1F319}',
185        unlock_condition: BadgeCondition::NightOwl,
186    },
187];
188
189/// Looks up a badge by its stable id.
190pub fn badge_by_id(id: &str) -> Option<&Badge> {
191    BADGES.iter().find(|b| b.id == id)
192}
193
194// ---------------------------------------------------------------------------
195// Usage stats
196// ---------------------------------------------------------------------------
197
198/// Lifetime usage counters that drive badge unlocks.
199///
200/// ```
201/// use limitless_cli::modules::achievements::ArcadeStats;
202/// let mut stats = ArcadeStats::default();
203/// stats.record_diagnostic_at(4200, 3);
204/// stats.record_fix();
205/// stats.record_arcade_game(800);
206/// assert_eq!(stats.diagnostics_run, 1);
207/// assert_eq!(stats.last_diagnostic_time_ms, Some(4200));
208/// assert_eq!(stats.times_run.get(&3), Some(&1));
209/// assert_eq!(stats.best_arcade_score, 800);
210/// ```
211#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
212pub struct ArcadeStats {
213    /// Total diagnostic scans run.
214    pub diagnostics_run: u32,
215    /// Total fixes applied.
216    pub fixes_applied: u32,
217    /// Consecutive runs where every check passed.
218    pub perfect_health_streak: u32,
219    /// Ghost processes killed.
220    pub processes_killed: u32,
221    /// `.env` files created.
222    pub env_files_created: u32,
223    /// Games played in SyntaxBreaker.
224    pub total_arcade_plays: u32,
225    /// Best SyntaxBreaker score.
226    pub best_arcade_score: u32,
227    /// Duration (ms) of the most recent diagnostic scan, for
228    /// [`BadgeCondition::SpeedRunner`]. `None` until the first scan.
229    pub last_diagnostic_time_ms: Option<u32>,
230    /// Map of local hour → number of runs started at that hour, for
231    /// [`BadgeCondition::NightOwl`].
232    pub times_run: HashMap<u32, u32>,
233}
234
235impl ArcadeStats {
236    /// Records a diagnostic scan, its duration, and the current UTC hour.
237    /// Local-hour bookkeeping on non-UTC machines uses the configured offset;
238    /// [`record_diagnostic_at`](ArcadeStats::record_diagnostic_at) is the
239    /// deterministic variant used by tests.
240    pub fn record_diagnostic(&mut self, duration_ms: u32) {
241        self.record_diagnostic_at(duration_ms, utc_hour_now());
242    }
243
244    /// Records a diagnostic scan with an explicit hour-of-day.
245    pub fn record_diagnostic_at(&mut self, duration_ms: u32, hour: u32) {
246        self.diagnostics_run = self.diagnostics_run.saturating_add(1);
247        self.last_diagnostic_time_ms = Some(duration_ms);
248        let slot = self.times_run.entry(hour).or_insert(0);
249        *slot = slot.saturating_add(1);
250    }
251
252    /// Marks the current run as happy, extending the perfect-health streak.
253    pub fn record_perfect_health(&mut self) {
254        self.perfect_health_streak = self.perfect_health_streak.saturating_add(1);
255    }
256
257    /// Ends a streak (a run with a failing check).
258    pub fn reset_perfect_health(&mut self) {
259        self.perfect_health_streak = 0;
260    }
261
262    /// Records an applied fix.
263    pub fn record_fix(&mut self) {
264        self.fixes_applied = self.fixes_applied.saturating_add(1);
265    }
266
267    /// Records a killed ghost process.
268    pub fn record_process_killed(&mut self) {
269        self.processes_killed = self.processes_killed.saturating_add(1);
270    }
271
272    /// Records a created `.env` file.
273    pub fn record_env_created(&mut self) {
274        self.env_files_created = self.env_files_created.saturating_add(1);
275    }
276
277    /// Records a finished SyntaxBreaker game, keeping the best score.
278    pub fn record_arcade_game(&mut self, score: u32) {
279        self.total_arcade_plays = self.total_arcade_plays.saturating_add(1);
280        self.best_arcade_score = self.best_arcade_score.max(score);
281    }
282}
283
284// ---------------------------------------------------------------------------
285// Condition checking
286// ---------------------------------------------------------------------------
287
288/// Every badge name (in registry order) whose condition `stats` satisfies.
289///
290/// ```
291/// use limitless_cli::modules::achievements::{ArcadeStats, check_badges};
292/// let mut stats = ArcadeStats::default();
293/// stats.processes_killed = 5;
294/// stats.env_files_created = 12;
295/// stats.best_arcade_score = 900;
296/// stats.times_run.insert(3, 1);
297/// assert_eq!(
298///     check_badges(&stats),
299///     vec!["Port Whisperer", "Env Master", "Arcade Champion", "Night Owl"]
300/// );
301/// ```
302pub fn check_badges(stats: &ArcadeStats) -> Vec<String> {
303    BADGES
304        .iter()
305        .filter(|badge| badge.unlock_condition.matches(stats))
306        .map(|badge| badge.name.to_string())
307        .collect()
308}
309
310// ---------------------------------------------------------------------------
311// Popup rendering
312// ---------------------------------------------------------------------------
313
314/// The share line displayed at the bottom of an unlock popup.
315///
316/// ```
317/// use limitless_cli::modules::achievements::{badge_by_id, share_text};
318/// let badge = badge_by_id("port-whisperer").unwrap();
319/// assert_eq!(
320///     share_text(badge),
321///     "Share: \"I unlocked \u{1F527} Port Whisperer in Limitless\""
322/// );
323/// ```
324pub fn share_text(badge: &Badge) -> String {
325    format!("Share: \"I unlocked {} {} in Limitless\"", badge.emoji, badge.name)
326}
327
328fn popup_border(top: bool) -> String {
329    let (left, right) = if top { ('┌', '┐') } else { ('└', '┘') };
330    format!("{left}{}{right}", "─".repeat(POPUP_WIDTH - 2))
331}
332
333fn popup_row(content: &str) -> String {
334    format!("│ {} │", pad(content))
335}
336
337fn pad(content: &str) -> String {
338    let used = content.chars().count();
339    format!("{content}{}", " ".repeat(POPUP_INNER.saturating_sub(used)))
340}
341
342fn centered(content: &str) -> String {
343    let used = content.chars().count();
344    if used >= POPUP_INNER {
345        return content.to_string();
346    }
347    let total = POPUP_INNER - used;
348    let left = total / 2;
349    let right = total - left;
350    format!("{}{}{}", " ".repeat(left), content, " ".repeat(right))
351}
352
353/// Renders a celebratory popup for a freshly unlocked badge.
354///
355/// ```
356/// use limitless_cli::modules::achievements::{
357///     badge_by_id, render_badge_popup, POPUP_WIDTH,
358/// };
359/// let popup = render_badge_popup(badge_by_id("env-master").unwrap());
360/// assert!(popup.contains("🎉 BADGE UNLOCKED!"));
361/// assert!(popup.contains("Share: \"I unlocked \u{1F6E1} Env Master in Limitless\""));
362/// for line in popup.lines() {
363///     assert_eq!(line.chars().count(), POPUP_WIDTH);
364/// }
365/// ```
366pub fn render_badge_popup(badge: &Badge) -> String {
367    [
368        popup_border(true),
369        popup_row(&centered("🎉 BADGE UNLOCKED!")),
370        popup_row(""),
371        popup_row(&centered(&format!("{}  {}", badge.emoji, badge.name))),
372        popup_row(&centered(badge.description)),
373        popup_row(""),
374        popup_row(&centered(&share_text(badge))),
375        popup_border(false),
376    ]
377    .join("\n")
378}
379
380// ---------------------------------------------------------------------------
381// Persistence
382// ---------------------------------------------------------------------------
383
384/// Best-effort home directory: `%USERPROFILE%` on Windows, `$HOME` elsewhere.
385pub fn home_dir() -> Option<PathBuf> {
386    std::env::var_os("USERPROFILE")
387        .map(PathBuf::from)
388        .or_else(|| std::env::var_os("HOME").map(PathBuf::from))
389}
390
391/// Where per-user progress lives: `<home>/.limitless/achievements.json`.
392pub fn progress_file_path() -> Option<PathBuf> {
393    home_dir().map(|home| home.join(".limitless").join("achievements.json"))
394}
395
396/// Legacy location that held badge progress before config.rs took over
397/// `stats.json`. Exists only to migrate old installs.
398pub fn legacy_progress_path() -> Option<PathBuf> {
399    home_dir().map(|home| home.join(".limitless").join("stats.json"))
400}
401
402/// Loads progress from the current location, migrating the legacy
403/// `~/.limitless/stats.json` file on first run after an upgrade.
404pub fn load_progress_migrated() -> AchievementProgress {
405    match home_dir() {
406        Some(home) => load_progress_at_home(&home),
407        None => AchievementProgress::default(),
408    }
409}
410
411/// Loads progress relative to an explicit home directory, migrating the legacy
412/// `stats.json` file (which config.rs now owns for bare [`ArcadeStats`]).
413fn load_progress_at_home(home: &Path) -> AchievementProgress {
414    let limitless = home.join(".limitless");
415    let path = limitless.join("achievements.json");
416    let progress = AchievementProgress::load(&path);
417    if !path.exists() {
418        if let Ok(raw) = fs::read_to_string(limitless.join("stats.json")) {
419            if let Ok(mut migrated) = serde_json::from_str::<AchievementProgress>(&raw) {
420                migrated.normalize();
421                let _ = migrated.save(&path);
422                return migrated;
423            }
424        }
425    }
426    progress
427}
428
429/// Persisted badge progress: the lifetime counters plus which badge names
430/// have already been unlocked.
431///
432/// ```
433/// use limitless_cli::modules::achievements::AchievementProgress;
434/// let mut progress = AchievementProgress::default();
435/// progress.stats.processes_killed = 5;
436/// assert_eq!(progress.check_unlocked(), vec!["Port Whisperer"]);
437/// assert!(progress.check_unlocked().is_empty());
438/// ```
439#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
440pub struct AchievementProgress {
441    /// Lifetime usage counters.
442    pub stats: ArcadeStats,
443    /// Badge names already unlocked, kept unique.
444    pub unlocked: Vec<String>,
445}
446
447impl AchievementProgress {
448    /// Loads progress from `path`; missing or corrupt files yield defaults.
449    pub fn load(path: &Path) -> Self {
450        match fs::read_to_string(path) {
451            Ok(raw) => serde_json::from_str::<AchievementProgress>(&raw)
452                .map(|mut p| {
453                    p.normalize();
454                    p
455                })
456                .unwrap_or_default(),
457            Err(_) => Self::default(),
458        }
459    }
460
461    /// Persists progress to `path`, creating parent directories as needed.
462    pub fn save(&self, path: &Path) -> io::Result<()> {
463        if let Some(parent) = path.parent() {
464            if !parent.as_os_str().is_empty() {
465                fs::create_dir_all(parent)?;
466            }
467        }
468        fs::write(path, serde_json::to_string_pretty(self)?)
469    }
470
471    /// Deduplicates `unlocked`, keeping the first occurrence order.
472    pub fn normalize(&mut self) {
473        let mut seen = Vec::with_capacity(self.unlocked.len());
474        self.unlocked.retain(|name| {
475            if seen.contains(name) {
476                false
477            } else {
478                seen.push(name.clone());
479                true
480            }
481        });
482    }
483
484    /// Which badges the current stats satisfy, minus ones already unlocked.
485    pub fn satisfied(&self) -> Vec<String> {
486        check_badges(&self.stats)
487            .into_iter()
488            .filter(|name| !self.unlocked.contains(name))
489            .collect()
490    }
491
492    /// Records and returns the *newly* unlocked badge names (a subset of
493    /// [`check_badges`]). Repeats return nothing until stats change.
494    pub fn check_unlocked(&mut self) -> Vec<String> {
495        let new = self.satisfied();
496        self.unlocked.extend(new.iter().cloned());
497        new
498    }
499}
500
501/// Current hour of day (UTC) derived from the system clock.
502fn utc_hour_now() -> u32 {
503    let secs = SystemTime::now()
504        .duration_since(UNIX_EPOCH)
505        .map(|d| d.as_secs())
506        .unwrap_or(0);
507    ((secs / 3600) % 24) as u32
508}
509
510// ---------------------------------------------------------------------------
511// Tests
512// ---------------------------------------------------------------------------
513
514#[cfg(test)]
515mod tests {
516    use super::*;
517
518    fn stats() -> ArcadeStats {
519        ArcadeStats::default()
520    }
521
522    struct TempDir(PathBuf);
523
524    impl TempDir {
525        fn new(tag: &str) -> Self {
526            let nanos = SystemTime::now()
527                .duration_since(UNIX_EPOCH)
528                .map(|d| d.as_nanos())
529                .unwrap_or(0);
530            let path = std::env::temp_dir().join(format!(
531                "limitless_achievements_{}_{}_{}",
532                tag,
533                std::process::id(),
534                nanos
535            ));
536            fs::create_dir_all(&path).expect("create temp dir");
537            Self(path)
538        }
539
540        fn path(&self) -> &Path {
541            &self.0
542        }
543    }
544
545    impl Drop for TempDir {
546        fn drop(&mut self) {
547            let _ = fs::remove_dir_all(&self.0);
548        }
549    }
550
551    #[test]
552    fn registry_has_all_five_badges_in_order() {
553        let ids: Vec<&str> = BADGES.iter().map(|b| b.id).collect();
554        assert_eq!(
555            ids,
556            vec![
557                "port-whisperer",
558                "env-master",
559                "speed-runner",
560                "arcade-champion",
561                "night-owl",
562            ]
563        );
564        assert_eq!(BADGES.len(), 5);
565        assert!(BADGES[0].name.contains("Port"));
566        assert!(BADGES[4].name.contains("Night"));
567    }
568
569    #[test]
570    fn badge_emojis_are_single_unicode_scalars() {
571        for badge in BADGES {
572            assert_ne!(badge.emoji, '\0', "{}", badge.id);
573            assert!(!badge.emoji.is_ascii(), "{}", badge.id);
574        }
575    }
576
577    #[test]
578    fn badge_ids_are_unique() {
579        let mut ids: Vec<&str> = BADGES.iter().map(|b| b.id).collect();
580        ids.sort_unstable();
581        let mut dedup = ids.clone();
582        dedup.dedup();
583        assert_eq!(ids, dedup);
584    }
585
586    #[test]
587    fn badge_by_id_finds_known_and_misses_unknown() {
588        assert!(badge_by_id("night-owl").is_some());
589        assert_eq!(badge_by_id("night-owl").unwrap().emoji, '\u{1F319}');
590        assert!(badge_by_id("nope").is_none());
591    }
592
593    #[test]
594    fn port_whisperer_threshold() {
595        let mut s = stats();
596        assert!(!BadgeCondition::PortWhisperer.matches(&s));
597        s.processes_killed = GHOST_PROCESS_TARGET - 1;
598        assert!(!BadgeCondition::PortWhisperer.matches(&s));
599        s.processes_killed = GHOST_PROCESS_TARGET;
600        assert!(BadgeCondition::PortWhisperer.matches(&s));
601        s.processes_killed = 99;
602        assert!(BadgeCondition::PortWhisperer.matches(&s));
603    }
604
605    #[test]
606    fn env_master_threshold() {
607        let mut s = stats();
608        s.env_files_created = ENV_MASTER_TARGET - 1;
609        assert!(!BadgeCondition::EnvMaster.matches(&s));
610        s.env_files_created = ENV_MASTER_TARGET;
611        assert!(BadgeCondition::EnvMaster.matches(&s));
612    }
613
614    #[test]
615    fn speed_runner_threshold_is_strictly_below_once_scanned() {
616        let s = stats();
617        assert!(!BadgeCondition::SpeedRunner.matches(&s));
618        let mut s = s;
619        s.last_diagnostic_time_ms = Some(SPEED_RUNNER_MS);
620        assert!(!BadgeCondition::SpeedRunner.matches(&s));
621        s.last_diagnostic_time_ms = Some(SPEED_RUNNER_MS - 1);
622        assert!(BadgeCondition::SpeedRunner.matches(&s));
623    }
624
625    #[test]
626    fn arcade_win_threshold_is_strictly_above() {
627        let mut s = stats();
628        s.best_arcade_score = 500;
629        assert!(!BadgeCondition::ArcadeWin { score: 500 }.matches(&s));
630        s.best_arcade_score = 501;
631        assert!(BadgeCondition::ArcadeWin { score: 500 }.matches(&s));
632    }
633
634    #[test]
635    fn night_owl_only_matches_hours_2_to_5() {
636        let s = stats();
637        assert!(!BadgeCondition::NightOwl.matches(&s));
638        for hour in 0..=23 {
639            let mut probe = stats();
640            probe.times_run.insert(hour, 1);
641            assert_eq!(
642                BadgeCondition::NightOwl.matches(&probe),
643                (NIGHT_OWL_FROM_HOUR..=NIGHT_OWL_TO_HOUR).contains(&hour),
644                "hour {hour}"
645            );
646        }
647    }
648
649    #[test]
650    fn night_owl_requires_a_nonzero_count() {
651        let mut s = stats();
652        s.times_run.insert(3, 0);
653        assert!(!BadgeCondition::NightOwl.matches(&s));
654        s.times_run.insert(3, 1);
655        assert!(BadgeCondition::NightOwl.matches(&s));
656    }
657
658    #[test]
659    fn first_fix_and_perfect_health_match() {
660        let mut s = stats();
661        assert!(!BadgeCondition::FirstFixExecuted.matches(&s));
662        s.record_fix();
663        assert!(BadgeCondition::FirstFixExecuted.matches(&s));
664
665        assert!(!BadgeCondition::PerfectHealth { count: 3 }.matches(&s));
666        for _ in 0..3 {
667            s.record_perfect_health();
668        }
669        assert!(BadgeCondition::PerfectHealth { count: 3 }.matches(&s));
670        s.reset_perfect_health();
671        assert!(!BadgeCondition::PerfectHealth { count: 3 }.matches(&s));
672    }
673
674    #[test]
675    fn dependency_hero_is_reserved() {
676        let mut s = stats();
677        s.fixes_applied = 50;
678        s.processes_killed = 50;
679        s.env_files_created = 50;
680        s.best_arcade_score = 100_000;
681        s.perfect_health_streak = 50;
682        assert!(!BadgeCondition::DependencyHero.matches(&s));
683    }
684
685    #[test]
686    fn check_badges_empty_stats_is_empty() {
687        assert!(check_badges(&stats()).is_empty());
688    }
689
690    #[test]
691    fn check_badges_reports_only_satisfied_in_registry_order() {
692        let mut s = stats();
693        s.processes_killed = 5;
694        s.best_arcade_score = 501;
695        assert_eq!(check_badges(&s), vec!["Port Whisperer", "Arcade Champion"]);
696    }
697
698    #[test]
699    fn check_badges_speed_runner_and_night_owl() {
700        let mut s = stats();
701        s.last_diagnostic_time_ms = Some(4999);
702        s.times_run.insert(2, 1);
703        assert_eq!(check_badges(&s), vec!["Speed Runner", "Night Owl"]);
704    }
705
706    #[test]
707    fn share_text_matches_spec_format() {
708        let badge = badge_by_id("port-whisperer").unwrap();
709        assert_eq!(
710            share_text(badge),
711            "Share: \"I unlocked \u{1F527} Port Whisperer in Limitless\""
712        );
713    }
714
715    #[test]
716    fn popup_renders_header_name_and_share_line() {
717        let popup = render_badge_popup(badge_by_id("env-master").unwrap());
718        assert!(popup.contains("🎉 BADGE UNLOCKED!"));
719        assert!(popup.contains("Env Master"));
720        assert!(popup.contains("Create 10 .env files."));
721        assert!(popup.contains(&share_text(badge_by_id("env-master").unwrap())));
722        assert!(popup.lines().next().unwrap().starts_with('┌'));
723        assert!(popup.lines().last().unwrap().starts_with('└'));
724    }
725
726    #[test]
727    fn popup_rows_have_constant_width() {
728        for badge in BADGES {
729            for line in render_badge_popup(badge).lines() {
730                assert_eq!(line.chars().count(), POPUP_WIDTH, "{}", badge.id);
731            }
732        }
733    }
734
735    #[test]
736    fn popup_is_single_block_with_no_message_wrap() {
737        for badge in BADGES {
738            let popup = render_badge_popup(badge);
739            assert_eq!(popup.lines().count(), 8);
740        }
741    }
742
743    #[test]
744    fn stats_recording_helpers_bump_counters() {
745        let mut s = stats();
746        s.record_diagnostic_at(100, 4);
747        s.record_diagnostic_at(200, 4);
748        s.record_diagnostic_at(300, 10);
749        assert_eq!(s.diagnostics_run, 3);
750        assert_eq!(s.last_diagnostic_time_ms, Some(300));
751        assert_eq!(s.times_run.get(&4), Some(&2));
752        assert_eq!(s.times_run.get(&10), Some(&1));
753        assert_eq!(s.times_run.len(), 2);
754
755        s.record_fix();
756        s.record_process_killed();
757        s.record_env_created();
758        assert_eq!(s.fixes_applied, 1);
759        assert_eq!(s.processes_killed, 1);
760        assert_eq!(s.env_files_created, 1);
761
762        s.record_arcade_game(100);
763        s.record_arcade_game(900);
764        assert_eq!(s.total_arcade_plays, 2);
765        assert_eq!(s.best_arcade_score, 900);
766    }
767
768    #[test]
769    fn record_diagnostic_uses_a_valid_hour() {
770        let mut s = stats();
771        s.record_diagnostic(123);
772        assert_eq!(s.diagnostics_run, 1);
773        assert!(s.times_run.values().all(|&c| c == 1));
774        let (hour, _) = s.times_run.iter().next().unwrap();
775        assert!((0..24).contains(hour));
776    }
777
778    #[test]
779    fn progress_only_reports_newly_unlocked_once() {
780        let mut p = AchievementProgress::default();
781        p.stats.processes_killed = 5;
782        assert_eq!(p.check_unlocked(), vec!["Port Whisperer"]);
783        assert!(p.check_unlocked().is_empty());
784        assert_eq!(p.unlocked, vec!["Port Whisperer"]);
785
786        p.stats.best_arcade_score = 900;
787        assert_eq!(p.check_unlocked(), vec!["Arcade Champion"]);
788    }
789
790    #[test]
791    fn progress_normalize_deduplicates_keeping_order() {
792        let mut p = AchievementProgress {
793            unlocked: vec!["b".into(), "a".into(), "b".into(), "c".into()],
794            ..Default::default()
795        };
796        p.normalize();
797        assert_eq!(p.unlocked, vec!["b", "a", "c"]);
798    }
799
800    #[test]
801    fn satisfied_excludes_already_unlocked() {
802        let mut p = AchievementProgress::default();
803        p.stats.processes_killed = 5;
804        p.unlocked = vec!["Port Whisperer".into()];
805        assert!(p.satisfied().is_empty());
806    }
807
808    #[test]
809    fn progress_round_trips_through_json() {
810        let mut p = AchievementProgress::default();
811        p.stats.diagnostics_run = 7;
812        p.stats.times_run.insert(3, 4);
813        assert_eq!(p.check_unlocked(), vec!["Night Owl"]);
814        p.stats.best_arcade_score = 800;
815        assert_eq!(p.check_unlocked(), vec!["Arcade Champion"]);
816
817        let json = serde_json::to_string(&p).unwrap();
818        let back: AchievementProgress = serde_json::from_str(&json).unwrap();
819        assert_eq!(back, p);
820        assert_eq!(back.unlocked, vec!["Night Owl", "Arcade Champion"]);
821        assert_eq!(back.stats.diagnostics_run, 7);
822        assert_eq!(back.stats.times_run.get(&3), Some(&4));
823    }
824
825    #[test]
826    fn refine_save_and_load_round_trip() {
827        let dir = TempDir::new("roundtrip");
828        let path = dir.path().join("stats.json");
829
830        let mut p = AchievementProgress::default();
831        p.stats.env_files_created = 10;
832        p.check_unlocked();
833        p.save(&path).unwrap();
834        assert!(path.exists());
835
836        let back = AchievementProgress::load(&path);
837        assert_eq!(back.unlocked, vec!["Env Master"]);
838        assert_eq!(back.stats.env_files_created, 10);
839    }
840
841    #[test]
842    fn load_missing_or_corrupt_file_yields_default() {
843        let dir = TempDir::new("missing");
844        let missing = AchievementProgress::load(&dir.path().join("nope.json"));
845        assert!(missing.stats.diagnostics_run == 0 && missing.unlocked.is_empty());
846
847        let path = dir.path().join("bad.json");
848        fs::write(&path, "not json").unwrap();
849        let corrupt = AchievementProgress::load(&path);
850        assert!(corrupt.stats.diagnostics_run == 0 && corrupt.unlocked.is_empty());
851    }
852
853    #[test]
854    fn progress_file_path_points_into_home_dir() {
855        let path = progress_file_path().expect("home dir should exist in tests");
856        assert_eq!(path.file_name().unwrap(), "achievements.json");
857        assert_eq!(path.parent().unwrap().file_name().unwrap(), ".limitless");
858    }
859
860    #[test]
861    fn load_progress_at_home_migrates_legacy_stats_file() {
862        let dir = TempDir::new("migrate");
863        fs::create_dir_all(dir.path().join(".limitless")).unwrap();
864
865        let mut from_the_past = AchievementProgress::default();
866        from_the_past.stats.record_fix();
867        from_the_past.stats.record_diagnostic(700);
868        from_the_past.unlocked.push("Env Master".into());
869        let legacy = dir.path().join(".limitless").join("stats.json");
870        fs::write(&legacy, serde_json::to_string_pretty(&from_the_past).unwrap()).unwrap();
871
872        let migrated = load_progress_at_home(dir.path());
873
874        assert_eq!(migrated, from_the_past);
875        assert!(dir.path().join(".limitless").join("achievements.json").is_file());
876
877        // Migration keeps legacy file intact (config.rs owns stats.json now).
878        assert!(legacy.exists());
879    }
880
881    #[test]
882    fn load_progress_at_home_skips_migration_when_present() {
883        let dir = TempDir::new("skipmig");
884        fs::create_dir_all(dir.path().join(".limitless")).unwrap();
885
886        let mut current = AchievementProgress::default();
887        current.stats.record_diagnostic(900);
888        fs::write(
889            dir.path().join(".limitless").join("achievements.json"),
890            serde_json::to_string_pretty(&current).unwrap(),
891        )
892        .unwrap();
893        // A legacy file that disagrees with the current one must be ignored.
894        let mut stale = AchievementProgress::default();
895        stale.stats.record_diagnostic(100);
896        fs::write(
897            dir.path().join(".limitless").join("stats.json"),
898            serde_json::to_string_pretty(&stale).unwrap(),
899        )
900        .unwrap();
901
902        assert_eq!(load_progress_at_home(dir.path()), current);
903    }
904
905    #[test]
906    fn test_badge_unlock_logic() {
907        // Fresh stats unlock nothing.
908        assert_eq!(check_badges(&ArcadeStats::default()), Vec::<String>::new());
909
910        // Each threshold trips exactly the badge it targets.
911        let near = ArcadeStats {
912            processes_killed: 4,
913            ..ArcadeStats::default()
914        };
915        assert!(!check_badges(&near).contains(&"Port Whisperer".to_string()));
916        let port = ArcadeStats {
917            processes_killed: 5,
918            ..ArcadeStats::default()
919        };
920        assert!(check_badges(&port).contains(&"Port Whisperer".to_string()));
921
922        let env = ArcadeStats {
923            env_files_created: 12,
924            ..ArcadeStats::default()
925        };
926        assert!(check_badges(&env).contains(&"Env Master".to_string()));
927
928        let arcade = ArcadeStats {
929            best_arcade_score: 600,
930            ..ArcadeStats::default()
931        };
932        assert!(check_badges(&arcade).contains(&"Arcade Champion".to_string()));
933
934        // Night Owl unlocks for a run in the 2 AM - 5 AM window.
935        let owl = ArcadeStats {
936            times_run: {
937                let mut m = std::collections::HashMap::new();
938                m.insert(3, 1);
939                m
940            },
941            ..ArcadeStats::default()
942        };
943        assert!(check_badges(&owl).contains(&"Night Owl".to_string()));
944
945        // Only runs between 2:00 and 4:59 count: daytime runs do not.
946        let day = ArcadeStats {
947            times_run: {
948                let mut m = std::collections::HashMap::new();
949                m.insert(14, 1);
950                m
951            },
952            ..ArcadeStats::default()
953        };
954        assert!(!check_badges(&day).contains(&"Night Owl".to_string()));
955
956        // Badges are independent: meeting several thresholds lists several.
957        let combined = ArcadeStats {
958            processes_killed: 5,
959            env_files_created: 12,
960            best_arcade_score: 600,
961            ..ArcadeStats::default()
962        };
963        let unlocked = check_badges(&combined);
964        assert!(unlocked.contains(&"Port Whisperer".to_string()));
965        assert!(unlocked.contains(&"Env Master".to_string()));
966        assert!(unlocked.contains(&"Arcade Champion".to_string()));
967        assert_eq!(unlocked.len(), 3);
968    }
969}