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
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
//! Core data models for Limitless CLI.
//!
//! Every type defined here is fully `serde`-compatible so environment
//! state and player progress can be persisted to JSON, exchanged between
//! commands (`check`, `dev`, `fix`, `orbit`, `arcade`), and rehydrated on
//! the next run without losing type safety.
//!
//! # Usage example
//!
//! ```
//! use limitless_cli::models::{
//!     ArcadeState, CheckStatus, DiagnosticResult, EnvironmentState, HealthScore,
//!     MentorMessage, ProjectStack, Severity,
//! };
//!
//! let deps_ok = DiagnosticResult::new(
//!     "Dependency Audit",
//!     CheckStatus::Pass,
//!     "All packages resolved",
//! );
//! let audit_fail = DiagnosticResult::new(
//!     "Env Audit",
//!     CheckStatus::Fail,
//!     ".env is missing",
//! ).with_remediation("Copy .env.example to .env and fill in secrets");
//!
//! let health = HealthScore::from_results(&[deps_ok.clone(), audit_fail.clone()]);
//!
//! let env = EnvironmentState {
//!     detected_stack: ProjectStack::Node {
//!         version: "22.9.0".into(),
//!         package_manager: "npm".into(),
//!     },
//!     runtime_version: Some("v22.9.0".into()),
//!     env_file_exists: false,
//!     env_example_exists: true,
//!     dependencies_healthy: true,
//!     blocked_ports: vec![(8080, 4321)],
//!     diagnostics: vec![deps_ok, audit_fail],
//!     health_score: health,
//! };
//!
//! // Serialize the whole environment to JSON and back.
//! let json = serde_json::to_string_pretty(&env).unwrap();
//! let env_back: EnvironmentState = serde_json::from_str(&json).unwrap();
//! assert_eq!(env, env_back);
//! assert!(env.dependencies_healthy);
//!
//! // Mentor-style feedback built from a failing check.
//! let mentor = MentorMessage {
//!     severity: Severity::Critical,
//!     plain_english: "Your project can't find its environment variables.".into(),
//!     technical_detail: "Missing .env file: 4 required vars unresolved.".into(),
//!     suggested_action: "Copy .env.example to .env and restart `limit dev`.".into(),
//! };
//! assert_eq!(mentor.suggested_action, "Copy .env.example to .env and restart `limit dev`.");
//!
//! // Arcade progress is serializable too.
//! let mut arcade = ArcadeState::default();
//! arcade.record_game(1400);
//! arcade.unlock_achievement("first-clear");
//! let json = serde_json::to_string(&arcade).unwrap();
//! let back: ArcadeState = serde_json::from_str(&json).unwrap();
//! assert_eq!(back.high_score, 1400);
//! ```

use serde::{Deserialize, Serialize};

/// The detected application stack for a project.
///
/// Serialized as an internally-tagged JSON object: a `"type"` discriminator
/// plus, for versioned stacks, a `"version"` payload.
///
/// ```
/// use limitless_cli::models::ProjectStack;
///
/// let node = ProjectStack::Node {
///     version: "22.9.0".into(),
///     package_manager: "npm".into(),
/// };
/// let json = serde_json::to_string(&node).unwrap();
/// assert_eq!(
///     json,
///     r#"{"type":"node","version":"22.9.0","package_manager":"npm"}"#
/// );
///
/// let back: ProjectStack = serde_json::from_str(&json).unwrap();
/// assert_eq!(back, node);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ProjectStack {
    /// A Node.js project; carries the runtime version and package manager
    /// when known.
    Node {
        /// Detected runtime version (`.nvmrc`, `.node-version`, or the
        /// `engines.node` field). Empty string when unknown.
        version: String,
        /// Detected package manager from lockfiles (`npm`, `yarn`, `pnpm`,
        /// `bun`). Defaults to `npm`.
        package_manager: String,
    },
    /// A Python project; carries the runtime version when known.
    Python { version: String },
    /// A Rust project; carries the toolchain version when known.
    Rust { version: String },
    /// A Go project; carries the Go version when known.
    Go { version: String },
    /// A Java project; carries the Java/JDK version when known.
    Java { version: String },
    /// A containerized project (Dockerfile / compose file present).
    Docker,
    /// No recognizable stack was detected.
    Unknown,
}

impl ProjectStack {
    /// Human-readable label for the stack, e.g. `"Node (v22.9.0, npm)"`.
    ///
    /// ```
    /// use limitless_cli::models::ProjectStack;
    /// assert_eq!(
    ///     ProjectStack::Python { version: "3.12".into() }.label(),
    ///     "Python (v3.12)"
    /// );
    /// assert_eq!(ProjectStack::Docker.label(), "Docker");
    /// assert_eq!(
    ///     ProjectStack::Node {
    ///         version: "22.9.0".into(),
    ///         package_manager: "pnpm".into(),
    ///     }
    ///     .label(),
    ///     "Node (v22.9.0, pnpm)"
    /// );
    /// ```
    pub fn label(&self) -> String {
        match self {
            ProjectStack::Node {
                version,
                package_manager,
            } => {
                if version.is_empty() {
                    format!("Node ({package_manager})")
                } else {
                    format!("Node (v{version}, {package_manager})")
                }
            }
            ProjectStack::Python { version } => {
                if version.is_empty() {
                    "Python".to_string()
                } else {
                    format!("Python (v{version})")
                }
            }
            ProjectStack::Rust { version } => {
                if version.is_empty() {
                    "Rust".to_string()
                } else {
                    format!("Rust (v{version})")
                }
            }
            ProjectStack::Go { version } => {
                if version.is_empty() {
                    "Go".to_string()
                } else {
                    format!("Go (v{version})")
                }
            }
            ProjectStack::Java { version } => {
                if version.is_empty() {
                    "Java".to_string()
                } else {
                    format!("Java (v{version})")
                }
            }
            ProjectStack::Docker => "Docker".to_string(),
            ProjectStack::Unknown => "Unknown".to_string(),
        }
    }

    /// Whether the project has a recognized stack.
    pub fn is_known(&self) -> bool {
        !matches!(self, ProjectStack::Unknown)
    }
}

/// Outcome of a single diagnostic check.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CheckStatus {
    /// Everything is fine.
    Pass,
    /// Something might be wrong, but it is not blocking.
    Warn,
    /// Something is broken and needs attention.
    Fail,
}

/// Aggregate health classification derived from a [`HealthScore`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HealthStatus {
    /// Most checks passed; the environment is ready.
    Healthy,
    /// Some checks warn; the environment is usable but needs attention.
    Caution,
    /// Critical checks failed; the environment is not ready for development.
    Critical,
}

/// One named diagnostic result with an optional suggested fix.
///
/// ```
/// use limitless_cli::models::{CheckStatus, DiagnosticResult};
///
/// let mut result = DiagnosticResult::new(
///     "Env Audit",
///     CheckStatus::Warn,
///     ".env.example is outdated",
/// );
/// assert!(!result.is_pass());
///
/// result.set_remediation("Update .env.example to match production keys");
/// assert!(result.remediation.is_some());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiagnosticResult {
    /// Short name of the check, e.g. `"Runtime Check"` or `"Env Audit"`.
    pub check_name: String,
    /// Outcome of the check.
    pub status: CheckStatus,
    /// Human-readable description of what the check found.
    pub message: String,
    /// Optional suggested fix. Omitted from JSON when `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remediation: Option<String>,
}

impl DiagnosticResult {
    /// Creates a result without a remediation hint.
    pub fn new(
        check_name: impl Into<String>,
        status: CheckStatus,
        message: impl Into<String>,
    ) -> Self {
        Self {
            check_name: check_name.into(),
            status,
            message: message.into(),
            remediation: None,
        }
    }

    /// Builder-style: attaches a remediation hint and returns the result.
    pub fn with_remediation(mut self, remediation: impl Into<String>) -> Self {
        self.remediation = Some(remediation.into());
        self
    }

    /// Sets (or replaces) the remediation hint in place.
    pub fn set_remediation(&mut self, remediation: impl Into<String>) {
        self.remediation = Some(remediation.into());
    }

    /// Whether this result passed.
    pub fn is_pass(&self) -> bool {
        self.status == CheckStatus::Pass
    }
}

/// A quantitative summary of environment health.
///
/// ```
/// use limitless_cli::models::{CheckStatus, DiagnosticResult, HealthScore, HealthStatus};
///
/// let checks = vec![
///     DiagnosticResult::new("Runtime Check", CheckStatus::Pass, "Node found"),
///     DiagnosticResult::new("Env Audit", CheckStatus::Warn, "1 missing var"),
///     DiagnosticResult::new("Port Scan", CheckStatus::Fail, "8080 blocked"),
/// ];
/// let score = HealthScore::from_results(&checks);
///
/// assert_eq!(score.total_checks, 3);
/// assert_eq!(score.percentage, 33);
/// assert_eq!(score.overall_status, HealthStatus::Critical);
/// assert!(score.validate().is_ok());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct HealthScore {
    /// Total number of checks performed.
    pub total_checks: u32,
    /// Number of checks that passed.
    pub passed: u32,
    /// Number of checks that warned.
    pub warnings: u32,
    /// Number of checks that failed.
    pub failed: u32,
    /// Overall score as a percentage (0–100). `100` when no checks ran.
    pub percentage: u32,
    /// Aggregate classification derived from `percentage`.
    pub overall_status: HealthStatus,
}

impl HealthScore {
    /// Computes a [`HealthScore`] from a slice of results.
    ///
    /// - `percentage = round(passed / total * 100)`
    /// - `Healthy` when percentage ≥ 85
    /// - `Caution` when percentage ≥ 60
    /// - `Critical` otherwise
    pub fn from_results(results: &[DiagnosticResult]) -> Self {
        let passed = results.iter().filter(|r| r.is_pass()).count() as u32;
        let warnings = results
            .iter()
            .filter(|r| r.status == CheckStatus::Warn)
            .count() as u32;
        let failed = results.len() as u32 - passed - warnings;
        Self::from_counts(passed, warnings, failed)
    }

    /// Computes a [`HealthScore`] from raw check counts.
    pub fn from_counts(passed: u32, warnings: u32, failed: u32) -> Self {
        let total = passed + warnings + failed;
        let percentage = if total == 0 {
            100
        } else {
            (passed as f64 / total as f64 * 100.0).round() as u32
        };

        let overall_status = match percentage {
            p if p >= 85 => HealthStatus::Healthy,
            p if p >= 60 => HealthStatus::Caution,
            _ => HealthStatus::Critical,
        };

        Self {
            total_checks: total,
            passed,
            warnings,
            failed,
            percentage,
            overall_status,
        }
    }

    /// Recomputes derived fields from `total_checks`, `passed`,
    /// `warnings`, and `failed`. This is the canonical way to rebuild a
    /// deserialized score whose `percentage`/`overall_status` may be stale.
    pub fn recompute(self) -> Self {
        Self::from_counts(self.passed, self.warnings, self.failed)
    }

    /// Validates internal consistency. Returns an error message when the
    /// counts do not sum to `total_checks`, `percentage` is out of range,
    /// or `percentage` does not match the pass ratio.
    pub fn validate(&self) -> Result<(), String> {
        if self.passed + self.warnings + self.failed != self.total_checks {
            return Err(format!(
                "counts ({}+{}+{}) do not sum to total_checks ({})",
                self.passed, self.warnings, self.failed, self.total_checks
            ));
        }
        if self.percentage > 100 {
            return Err(format!(
                "percentage {} is out of range 0..=100",
                self.percentage
            ));
        }
        let expected = if self.total_checks == 0 {
            100
        } else {
            (self.passed as f64 / self.total_checks as f64 * 100.0).round() as u32
        };
        if self.percentage != expected {
            return Err(format!(
                "percentage {} does not match pass ratio (expected {})",
                self.percentage, expected
            ));
        }
        Ok(())
    }

    /// Whether the overall status is [`HealthStatus::Healthy`].
    pub fn is_healthy(&self) -> bool {
        self.overall_status == HealthStatus::Healthy
    }
}

impl Default for HealthScore {
    /// An empty environment scores as `100 / Healthy` (nothing to fix).
    fn default() -> Self {
        Self {
            total_checks: 0,
            passed: 0,
            warnings: 0,
            failed: 0,
            percentage: 100,
            overall_status: HealthStatus::Healthy,
        }
    }
}

/// A full snapshot of the detected development environment.
///
/// ```
/// use limitless_cli::models::{CheckStatus, DiagnosticResult, EnvironmentState,
///                             HealthScore, ProjectStack};
///
/// let state = EnvironmentState::default();
/// assert_eq!(state.detected_stack, ProjectStack::Unknown);
/// assert!(!state.env_file_exists);
/// assert!(state.health_score.is_healthy());
///
/// let mut state = EnvironmentState {
///     detected_stack: ProjectStack::Rust { version: "1.98.0".into() },
///     runtime_version: Some("1.98.0".into()),
///     env_file_exists: true,
///     env_example_exists: true,
///     dependencies_healthy: true,
///     blocked_ports: vec![],
///     diagnostics: vec![DiagnosticResult::new(
///         "Dependency Audit", CheckStatus::Pass, "cargo check clean",
///     )],
///     health_score: HealthScore::default(),
/// };
/// assert!(state.ready_for_dev());
///
/// state.blocked_ports.push((5432, 12345));
/// assert!(!state.ready_for_dev());
///
/// let json = serde_json::to_string(&state).unwrap();
/// let back: EnvironmentState = serde_json::from_str(&json).unwrap();
/// assert_eq!(state, back);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnvironmentState {
    /// Which stack was detected for the current project.
    pub detected_stack: ProjectStack,
    /// The detected runtime/toolchain version, when known.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub runtime_version: Option<String>,
    /// Whether a `.env` file exists at the project root.
    pub env_file_exists: bool,
    /// Whether a `.env.example` template exists at the project root.
    pub env_example_exists: bool,
    /// Whether dependencies resolve/install cleanly.
    pub dependencies_healthy: bool,
    /// Ports found blocked while listening, as `(port, pid)` pairs.
    pub blocked_ports: Vec<(u16, u32)>,
    /// All diagnostics collected during the last scan.
    pub diagnostics: Vec<DiagnosticResult>,
    /// Quantitative health summary of the environment.
    pub health_score: HealthScore,
}

impl EnvironmentState {
    /// Whether the environment is ready for day-to-day development.
    ///
    /// Requires a known stack, healthy dependencies, at least one env file
    /// present, no failed checks, and no blocked ports.
    pub fn ready_for_dev(&self) -> bool {
        self.detected_stack.is_known()
            && self.dependencies_healthy
            && (self.env_file_exists || self.env_example_exists)
            && self
                .diagnostics
                .iter()
                .all(|d| d.status != CheckStatus::Fail)
            && self.blocked_ports.is_empty()
    }

    /// Number of failing diagnostics.
    pub fn failed_checks(&self) -> usize {
        self.diagnostics
            .iter()
            .filter(|d| d.status == CheckStatus::Fail)
            .count()
    }

    /// Rebuilds `health_score` from the current `diagnostics`.
    pub fn refresh_health(&mut self) {
        self.health_score = HealthScore::from_results(&self.diagnostics);
    }
}

impl Default for EnvironmentState {
    /// A blank environment: unknown stack, no files, healthy-by-default.
    fn default() -> Self {
        Self {
            detected_stack: ProjectStack::Unknown,
            runtime_version: None,
            env_file_exists: false,
            env_example_exists: false,
            dependencies_healthy: false,
            blocked_ports: Vec::new(),
            diagnostics: Vec::new(),
            health_score: HealthScore::default(),
        }
    }
}

/// How urgent a [`MentorMessage`] is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Severity {
    /// Just for your information; no action needed.
    Info,
    /// Something might go wrong; recommend checking.
    Warning,
    /// Something is broken and blocks development.
    Critical,
}

/// A beginner-friendly explanation of a detected issue.
///
/// Every message carries a plain-English explanation, the underlying
/// technical detail, and a concrete suggested action.
///
/// ```
/// use limitless_cli::models::{MentorMessage, Severity};
///
/// let msg = MentorMessage {
///     severity: Severity::Warning,
///     plain_english: "Your Node version is outdated.".into(),
///     technical_detail: "Node 18 is EOL; latest LTS is 22.x.".into(),
///     suggested_action: "Install Node 22 via your version manager.".into(),
/// };
/// let json = serde_json::to_string(&msg).unwrap();
/// let back: MentorMessage = serde_json::from_str(&json).unwrap();
/// assert_eq!(back.severity, Severity::Warning);
/// assert_eq!(back.suggested_action, msg.suggested_action);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MentorMessage {
    /// Urgency level of this message.
    pub severity: Severity,
    /// Friendly, jargon-free description of the issue.
    pub plain_english: String,
    /// The precise technical reason behind the issue.
    pub technical_detail: String,
    /// A concrete step the user can take next.
    pub suggested_action: String,
}

impl MentorMessage {
    /// Whether this message needs immediate attention.
    pub fn is_critical(&self) -> bool {
        self.severity == Severity::Critical
    }
}

/// Serializable progress state for Arcade mode.
///
/// ```
/// use limitless_cli::models::ArcadeState;
///
/// let mut arcade = ArcadeState::default();
/// let new_record = arcade.record_game(2500);
/// arcade.unlock_achievement("first-win");
/// assert!(new_record);
///
/// let json = serde_json::to_string(&arcade).unwrap();
/// let back: ArcadeState = serde_json::from_str(&json).unwrap();
/// assert_eq!(back.high_score, 2500);
/// assert_eq!(back.games_played, 1);
/// assert_eq!(back.achievements, vec!["first-win"]);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ArcadeState {
    /// The best score achieved so far.
    pub high_score: u32,
    /// Total number of games played.
    pub games_played: u32,
    /// Names of unlocked achievements (kept unique).
    pub achievements: Vec<String>,
}

impl ArcadeState {
    /// Records a finished game. Returns `true` when a new high score was set.
    pub fn record_game(&mut self, score: u32) -> bool {
        self.games_played = self.games_played.saturating_add(1);
        if score > self.high_score {
            self.high_score = score;
            true
        } else {
            false
        }
    }

    /// Unlocks an achievement. Returns `false` if it was already unlocked.
    pub fn unlock_achievement(&mut self, name: impl Into<String>) -> bool {
        let name = name.into();
        if self.achievements.contains(&name) {
            false
        } else {
            self.achievements.push(name);
            true
        }
    }
}

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

    #[test]
    fn project_stack_round_trips() {
        for stack in [
            ProjectStack::Node {
                version: "22.9.0".into(),
                package_manager: "npm".into(),
            },
            ProjectStack::Python {
                version: "3.12".into(),
            },
            ProjectStack::Rust {
                version: "1.98.0".into(),
            },
            ProjectStack::Docker,
            ProjectStack::Unknown,
        ] {
            let json = serde_json::to_string(&stack).unwrap();
            let back: ProjectStack = serde_json::from_str(&json).unwrap();
            assert_eq!(back, stack);
        }
    }

    #[test]
    fn project_stack_docker_omits_payload() {
        let json = serde_json::to_string(&ProjectStack::Docker).unwrap();
        assert_eq!(json, r#"{"type":"docker"}"#);
    }

    #[test]
    fn diagnostics_remediation_is_optional_in_json() {
        let pass = DiagnosticResult::new("Runtime Check", CheckStatus::Pass, "Node found");
        let fail = DiagnosticResult::new("Env Audit", CheckStatus::Fail, "missing .env")
            .with_remediation("copy .env.example");

        assert!(pass.remediation.is_none());
        assert!(fail.remediation.is_some());

        let pass_json = serde_json::to_string(&pass).unwrap();
        let fail_json = serde_json::to_string(&fail).unwrap();

        assert!(!pass_json.contains("remediation"));
        assert!(fail_json.contains("remediation"));

        let back: DiagnosticResult = serde_json::from_str(&pass_json).unwrap();
        assert_eq!(back, pass);
        let back: DiagnosticResult = serde_json::from_str(&fail_json).unwrap();
        assert_eq!(back, fail);
    }

    #[test]
    fn health_score_computes_counts_and_status() {
        let checks = vec![
            DiagnosticResult::new("A", CheckStatus::Pass, "ok"),
            DiagnosticResult::new("B", CheckStatus::Pass, "ok"),
            DiagnosticResult::new("C", CheckStatus::Warn, "meh"),
            DiagnosticResult::new("D", CheckStatus::Fail, "broken"),
        ];

        let score = HealthScore::from_results(&checks);
        assert_eq!(score.total_checks, 4);
        assert_eq!(score.passed, 2);
        assert_eq!(score.warnings, 1);
        assert_eq!(score.failed, 1);
        assert_eq!(score.percentage, 50);
        assert_eq!(score.overall_status, HealthStatus::Critical);
        assert!(score.validate().is_ok());
    }

    #[test]
    fn health_score_default_is_healthy_empty() {
        let score = HealthScore::default();
        assert_eq!(score.total_checks, 0);
        assert_eq!(score.percentage, 100);
        assert_eq!(score.overall_status, HealthStatus::Healthy);
        assert!(score.validate().is_ok());
    }

    #[test]
    fn recompute_fixes_stale_serialized_score() {
        let mut score =
            HealthScore::from_results(&[DiagnosticResult::new("A", CheckStatus::Fail, "boom")]);
        score.percentage = 42;
        assert!(score.validate().is_err());

        let fixed = score.recompute();
        assert_eq!(fixed.percentage, 0);
        assert_eq!(fixed.overall_status, HealthStatus::Critical);
        assert!(fixed.validate().is_ok());

        let json = serde_json::to_string(&fixed).unwrap();
        let back: HealthScore = serde_json::from_str(&json).unwrap();
        assert_eq!(back, fixed);
    }

    #[test]
    fn environment_state_round_trips_with_blocked_ports() {
        let state = EnvironmentState {
            detected_stack: ProjectStack::Node {
                version: "22.9.0".into(),
                package_manager: "npm".into(),
            },
            runtime_version: Some("v22.9.0".into()),
            env_file_exists: true,
            env_example_exists: true,
            dependencies_healthy: true,
            blocked_ports: vec![(8080, 4123), (5432, 5555)],
            diagnostics: vec![DiagnosticResult::new(
                "Port Scan",
                CheckStatus::Fail,
                "8080 is blocked",
            )],
            health_score: HealthScore::from_results(&[DiagnosticResult::new(
                "Port Scan",
                CheckStatus::Fail,
                "8080 is blocked",
            )]),
        };

        assert!(!state.ready_for_dev());

        let json = serde_json::to_string(&state).unwrap();
        assert!(json.contains("[8080,4123]"));
        let back: EnvironmentState = serde_json::from_str(&json).unwrap();
        assert_eq!(back, state);
        assert_eq!(back.blocked_ports, vec![(8080, 4123), (5432, 5555)]);
    }

    #[test]
    fn mentor_message_round_trips() {
        let msg = MentorMessage {
            severity: Severity::Critical,
            plain_english: "Port 3000 is taken.".into(),
            technical_detail: "PID 4123 holds port 3000.".into(),
            suggested_action: "Stop PID 4123 or use another port.".into(),
        };
        assert!(msg.is_critical());

        let json = serde_json::to_string(&msg).unwrap();
        assert!(json.contains(r#""severity":"critical""#));
        let back: MentorMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(back, msg);
    }

    #[test]
    fn arcade_state_tracks_records_and_achievements() {
        let mut arcade = ArcadeState::default();
        assert!(arcade.record_game(1000));
        assert!(!arcade.record_game(500));
        assert!(arcade.record_game(2000));
        assert_eq!(arcade.high_score, 2000);
        assert_eq!(arcade.games_played, 3);

        assert!(arcade.unlock_achievement("first-win"));
        assert!(!arcade.unlock_achievement("first-win"));
        assert_eq!(arcade.achievements, vec!["first-win"]);

        let json = serde_json::to_string(&arcade).unwrap();
        let back: ArcadeState = serde_json::from_str(&json).unwrap();
        assert_eq!(back, arcade);
    }
}