Skip to main content

limitless_cli/
models.rs

1//! Core data models for Limitless CLI.
2//!
3//! Every type defined here is fully `serde`-compatible so environment
4//! state and player progress can be persisted to JSON, exchanged between
5//! commands (`check`, `dev`, `fix`, `orbit`, `arcade`), and rehydrated on
6//! the next run without losing type safety.
7//!
8//! # Usage example
9//!
10//! ```
11//! use limitless_cli::models::{
12//!     ArcadeState, CheckStatus, DiagnosticResult, EnvironmentState, HealthScore,
13//!     MentorMessage, ProjectStack, Severity,
14//! };
15//!
16//! let deps_ok = DiagnosticResult::new(
17//!     "Dependency Audit",
18//!     CheckStatus::Pass,
19//!     "All packages resolved",
20//! );
21//! let audit_fail = DiagnosticResult::new(
22//!     "Env Audit",
23//!     CheckStatus::Fail,
24//!     ".env is missing",
25//! ).with_remediation("Copy .env.example to .env and fill in secrets");
26//!
27//! let health = HealthScore::from_results(&[deps_ok.clone(), audit_fail.clone()]);
28//!
29//! let env = EnvironmentState {
30//!     detected_stack: ProjectStack::Node {
31//!         version: "22.9.0".into(),
32//!         package_manager: "npm".into(),
33//!     },
34//!     runtime_version: Some("v22.9.0".into()),
35//!     env_file_exists: false,
36//!     env_example_exists: true,
37//!     dependencies_healthy: true,
38//!     blocked_ports: vec![(8080, 4321)],
39//!     diagnostics: vec![deps_ok, audit_fail],
40//!     health_score: health,
41//! };
42//!
43//! // Serialize the whole environment to JSON and back.
44//! let json = serde_json::to_string_pretty(&env).unwrap();
45//! let env_back: EnvironmentState = serde_json::from_str(&json).unwrap();
46//! assert_eq!(env, env_back);
47//! assert!(env.dependencies_healthy);
48//!
49//! // Mentor-style feedback built from a failing check.
50//! let mentor = MentorMessage {
51//!     severity: Severity::Critical,
52//!     plain_english: "Your project can't find its environment variables.".into(),
53//!     technical_detail: "Missing .env file: 4 required vars unresolved.".into(),
54//!     suggested_action: "Copy .env.example to .env and restart `limit dev`.".into(),
55//! };
56//! assert_eq!(mentor.suggested_action, "Copy .env.example to .env and restart `limit dev`.");
57//!
58//! // Arcade progress is serializable too.
59//! let mut arcade = ArcadeState::default();
60//! arcade.record_game(1400);
61//! arcade.unlock_achievement("first-clear");
62//! let json = serde_json::to_string(&arcade).unwrap();
63//! let back: ArcadeState = serde_json::from_str(&json).unwrap();
64//! assert_eq!(back.high_score, 1400);
65//! ```
66
67use serde::{Deserialize, Serialize};
68
69/// The detected application stack for a project.
70///
71/// Serialized as an internally-tagged JSON object: a `"type"` discriminator
72/// plus, for versioned stacks, a `"version"` payload.
73///
74/// ```
75/// use limitless_cli::models::ProjectStack;
76///
77/// let node = ProjectStack::Node {
78///     version: "22.9.0".into(),
79///     package_manager: "npm".into(),
80/// };
81/// let json = serde_json::to_string(&node).unwrap();
82/// assert_eq!(
83///     json,
84///     r#"{"type":"node","version":"22.9.0","package_manager":"npm"}"#
85/// );
86///
87/// let back: ProjectStack = serde_json::from_str(&json).unwrap();
88/// assert_eq!(back, node);
89/// ```
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(tag = "type", rename_all = "snake_case")]
92pub enum ProjectStack {
93    /// A Node.js project; carries the runtime version and package manager
94    /// when known.
95    Node {
96        /// Detected runtime version (`.nvmrc`, `.node-version`, or the
97        /// `engines.node` field). Empty string when unknown.
98        version: String,
99        /// Detected package manager from lockfiles (`npm`, `yarn`, `pnpm`,
100        /// `bun`). Defaults to `npm`.
101        package_manager: String,
102    },
103    /// A Python project; carries the runtime version when known.
104    Python { version: String },
105    /// A Rust project; carries the toolchain version when known.
106    Rust { version: String },
107    /// A Go project; carries the Go version when known.
108    Go { version: String },
109    /// A Java project; carries the Java/JDK version when known.
110    Java { version: String },
111    /// A containerized project (Dockerfile / compose file present).
112    Docker,
113    /// No recognizable stack was detected.
114    Unknown,
115}
116
117impl ProjectStack {
118    /// Human-readable label for the stack, e.g. `"Node (v22.9.0, npm)"`.
119    ///
120    /// ```
121    /// use limitless_cli::models::ProjectStack;
122    /// assert_eq!(
123    ///     ProjectStack::Python { version: "3.12".into() }.label(),
124    ///     "Python (v3.12)"
125    /// );
126    /// assert_eq!(ProjectStack::Docker.label(), "Docker");
127    /// assert_eq!(
128    ///     ProjectStack::Node {
129    ///         version: "22.9.0".into(),
130    ///         package_manager: "pnpm".into(),
131    ///     }
132    ///     .label(),
133    ///     "Node (v22.9.0, pnpm)"
134    /// );
135    /// ```
136    pub fn label(&self) -> String {
137        match self {
138            ProjectStack::Node {
139                version,
140                package_manager,
141            } => {
142                if version.is_empty() {
143                    format!("Node ({package_manager})")
144                } else {
145                    format!("Node (v{version}, {package_manager})")
146                }
147            }
148            ProjectStack::Python { version } => {
149                if version.is_empty() {
150                    "Python".to_string()
151                } else {
152                    format!("Python (v{version})")
153                }
154            }
155            ProjectStack::Rust { version } => {
156                if version.is_empty() {
157                    "Rust".to_string()
158                } else {
159                    format!("Rust (v{version})")
160                }
161            }
162            ProjectStack::Go { version } => {
163                if version.is_empty() {
164                    "Go".to_string()
165                } else {
166                    format!("Go (v{version})")
167                }
168            }
169            ProjectStack::Java { version } => {
170                if version.is_empty() {
171                    "Java".to_string()
172                } else {
173                    format!("Java (v{version})")
174                }
175            }
176            ProjectStack::Docker => "Docker".to_string(),
177            ProjectStack::Unknown => "Unknown".to_string(),
178        }
179    }
180
181    /// Whether the project has a recognized stack.
182    pub fn is_known(&self) -> bool {
183        !matches!(self, ProjectStack::Unknown)
184    }
185}
186
187/// Outcome of a single diagnostic check.
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
189#[serde(rename_all = "lowercase")]
190pub enum CheckStatus {
191    /// Everything is fine.
192    Pass,
193    /// Something might be wrong, but it is not blocking.
194    Warn,
195    /// Something is broken and needs attention.
196    Fail,
197}
198
199/// Aggregate health classification derived from a [`HealthScore`].
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
201#[serde(rename_all = "lowercase")]
202pub enum HealthStatus {
203    /// Most checks passed; the environment is ready.
204    Healthy,
205    /// Some checks warn; the environment is usable but needs attention.
206    Caution,
207    /// Critical checks failed; the environment is not ready for development.
208    Critical,
209}
210
211/// One named diagnostic result with an optional suggested fix.
212///
213/// ```
214/// use limitless_cli::models::{CheckStatus, DiagnosticResult};
215///
216/// let mut result = DiagnosticResult::new(
217///     "Env Audit",
218///     CheckStatus::Warn,
219///     ".env.example is outdated",
220/// );
221/// assert!(!result.is_pass());
222///
223/// result.set_remediation("Update .env.example to match production keys");
224/// assert!(result.remediation.is_some());
225/// ```
226#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
227pub struct DiagnosticResult {
228    /// Short name of the check, e.g. `"Runtime Check"` or `"Env Audit"`.
229    pub check_name: String,
230    /// Outcome of the check.
231    pub status: CheckStatus,
232    /// Human-readable description of what the check found.
233    pub message: String,
234    /// Optional suggested fix. Omitted from JSON when `None`.
235    #[serde(skip_serializing_if = "Option::is_none")]
236    pub remediation: Option<String>,
237}
238
239impl DiagnosticResult {
240    /// Creates a result without a remediation hint.
241    pub fn new(
242        check_name: impl Into<String>,
243        status: CheckStatus,
244        message: impl Into<String>,
245    ) -> Self {
246        Self {
247            check_name: check_name.into(),
248            status,
249            message: message.into(),
250            remediation: None,
251        }
252    }
253
254    /// Builder-style: attaches a remediation hint and returns the result.
255    pub fn with_remediation(mut self, remediation: impl Into<String>) -> Self {
256        self.remediation = Some(remediation.into());
257        self
258    }
259
260    /// Sets (or replaces) the remediation hint in place.
261    pub fn set_remediation(&mut self, remediation: impl Into<String>) {
262        self.remediation = Some(remediation.into());
263    }
264
265    /// Whether this result passed.
266    pub fn is_pass(&self) -> bool {
267        self.status == CheckStatus::Pass
268    }
269}
270
271/// A quantitative summary of environment health.
272///
273/// ```
274/// use limitless_cli::models::{CheckStatus, DiagnosticResult, HealthScore, HealthStatus};
275///
276/// let checks = vec![
277///     DiagnosticResult::new("Runtime Check", CheckStatus::Pass, "Node found"),
278///     DiagnosticResult::new("Env Audit", CheckStatus::Warn, "1 missing var"),
279///     DiagnosticResult::new("Port Scan", CheckStatus::Fail, "8080 blocked"),
280/// ];
281/// let score = HealthScore::from_results(&checks);
282///
283/// assert_eq!(score.total_checks, 3);
284/// assert_eq!(score.percentage, 33);
285/// assert_eq!(score.overall_status, HealthStatus::Critical);
286/// assert!(score.validate().is_ok());
287/// ```
288#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
289pub struct HealthScore {
290    /// Total number of checks performed.
291    pub total_checks: u32,
292    /// Number of checks that passed.
293    pub passed: u32,
294    /// Number of checks that warned.
295    pub warnings: u32,
296    /// Number of checks that failed.
297    pub failed: u32,
298    /// Overall score as a percentage (0–100). `100` when no checks ran.
299    pub percentage: u32,
300    /// Aggregate classification derived from `percentage`.
301    pub overall_status: HealthStatus,
302}
303
304impl HealthScore {
305    /// Computes a [`HealthScore`] from a slice of results.
306    ///
307    /// - `percentage = round(passed / total * 100)`
308    /// - `Healthy` when percentage ≥ 85
309    /// - `Caution` when percentage ≥ 60
310    /// - `Critical` otherwise
311    pub fn from_results(results: &[DiagnosticResult]) -> Self {
312        let passed = results.iter().filter(|r| r.is_pass()).count() as u32;
313        let warnings = results
314            .iter()
315            .filter(|r| r.status == CheckStatus::Warn)
316            .count() as u32;
317        let failed = results.len() as u32 - passed - warnings;
318        Self::from_counts(passed, warnings, failed)
319    }
320
321    /// Computes a [`HealthScore`] from raw check counts.
322    pub fn from_counts(passed: u32, warnings: u32, failed: u32) -> Self {
323        let total = passed + warnings + failed;
324        let percentage = if total == 0 {
325            100
326        } else {
327            (passed as f64 / total as f64 * 100.0).round() as u32
328        };
329
330        let overall_status = match percentage {
331            p if p >= 85 => HealthStatus::Healthy,
332            p if p >= 60 => HealthStatus::Caution,
333            _ => HealthStatus::Critical,
334        };
335
336        Self {
337            total_checks: total,
338            passed,
339            warnings,
340            failed,
341            percentage,
342            overall_status,
343        }
344    }
345
346    /// Recomputes derived fields from `total_checks`, `passed`,
347    /// `warnings`, and `failed`. This is the canonical way to rebuild a
348    /// deserialized score whose `percentage`/`overall_status` may be stale.
349    pub fn recompute(self) -> Self {
350        Self::from_counts(self.passed, self.warnings, self.failed)
351    }
352
353    /// Validates internal consistency. Returns an error message when the
354    /// counts do not sum to `total_checks`, `percentage` is out of range,
355    /// or `percentage` does not match the pass ratio.
356    pub fn validate(&self) -> Result<(), String> {
357        if self.passed + self.warnings + self.failed != self.total_checks {
358            return Err(format!(
359                "counts ({}+{}+{}) do not sum to total_checks ({})",
360                self.passed, self.warnings, self.failed, self.total_checks
361            ));
362        }
363        if self.percentage > 100 {
364            return Err(format!(
365                "percentage {} is out of range 0..=100",
366                self.percentage
367            ));
368        }
369        let expected = if self.total_checks == 0 {
370            100
371        } else {
372            (self.passed as f64 / self.total_checks as f64 * 100.0).round() as u32
373        };
374        if self.percentage != expected {
375            return Err(format!(
376                "percentage {} does not match pass ratio (expected {})",
377                self.percentage, expected
378            ));
379        }
380        Ok(())
381    }
382
383    /// Whether the overall status is [`HealthStatus::Healthy`].
384    pub fn is_healthy(&self) -> bool {
385        self.overall_status == HealthStatus::Healthy
386    }
387}
388
389impl Default for HealthScore {
390    /// An empty environment scores as `100 / Healthy` (nothing to fix).
391    fn default() -> Self {
392        Self {
393            total_checks: 0,
394            passed: 0,
395            warnings: 0,
396            failed: 0,
397            percentage: 100,
398            overall_status: HealthStatus::Healthy,
399        }
400    }
401}
402
403/// A full snapshot of the detected development environment.
404///
405/// ```
406/// use limitless_cli::models::{CheckStatus, DiagnosticResult, EnvironmentState,
407///                             HealthScore, ProjectStack};
408///
409/// let state = EnvironmentState::default();
410/// assert_eq!(state.detected_stack, ProjectStack::Unknown);
411/// assert!(!state.env_file_exists);
412/// assert!(state.health_score.is_healthy());
413///
414/// let mut state = EnvironmentState {
415///     detected_stack: ProjectStack::Rust { version: "1.98.0".into() },
416///     runtime_version: Some("1.98.0".into()),
417///     env_file_exists: true,
418///     env_example_exists: true,
419///     dependencies_healthy: true,
420///     blocked_ports: vec![],
421///     diagnostics: vec![DiagnosticResult::new(
422///         "Dependency Audit", CheckStatus::Pass, "cargo check clean",
423///     )],
424///     health_score: HealthScore::default(),
425/// };
426/// assert!(state.ready_for_dev());
427///
428/// state.blocked_ports.push((5432, 12345));
429/// assert!(!state.ready_for_dev());
430///
431/// let json = serde_json::to_string(&state).unwrap();
432/// let back: EnvironmentState = serde_json::from_str(&json).unwrap();
433/// assert_eq!(state, back);
434/// ```
435#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
436pub struct EnvironmentState {
437    /// Which stack was detected for the current project.
438    pub detected_stack: ProjectStack,
439    /// The detected runtime/toolchain version, when known.
440    #[serde(skip_serializing_if = "Option::is_none")]
441    pub runtime_version: Option<String>,
442    /// Whether a `.env` file exists at the project root.
443    pub env_file_exists: bool,
444    /// Whether a `.env.example` template exists at the project root.
445    pub env_example_exists: bool,
446    /// Whether dependencies resolve/install cleanly.
447    pub dependencies_healthy: bool,
448    /// Ports found blocked while listening, as `(port, pid)` pairs.
449    pub blocked_ports: Vec<(u16, u32)>,
450    /// All diagnostics collected during the last scan.
451    pub diagnostics: Vec<DiagnosticResult>,
452    /// Quantitative health summary of the environment.
453    pub health_score: HealthScore,
454}
455
456impl EnvironmentState {
457    /// Whether the environment is ready for day-to-day development.
458    ///
459    /// Requires a known stack, healthy dependencies, at least one env file
460    /// present, no failed checks, and no blocked ports.
461    pub fn ready_for_dev(&self) -> bool {
462        self.detected_stack.is_known()
463            && self.dependencies_healthy
464            && (self.env_file_exists || self.env_example_exists)
465            && self
466                .diagnostics
467                .iter()
468                .all(|d| d.status != CheckStatus::Fail)
469            && self.blocked_ports.is_empty()
470    }
471
472    /// Number of failing diagnostics.
473    pub fn failed_checks(&self) -> usize {
474        self.diagnostics
475            .iter()
476            .filter(|d| d.status == CheckStatus::Fail)
477            .count()
478    }
479
480    /// Rebuilds `health_score` from the current `diagnostics`.
481    pub fn refresh_health(&mut self) {
482        self.health_score = HealthScore::from_results(&self.diagnostics);
483    }
484}
485
486impl Default for EnvironmentState {
487    /// A blank environment: unknown stack, no files, healthy-by-default.
488    fn default() -> Self {
489        Self {
490            detected_stack: ProjectStack::Unknown,
491            runtime_version: None,
492            env_file_exists: false,
493            env_example_exists: false,
494            dependencies_healthy: false,
495            blocked_ports: Vec::new(),
496            diagnostics: Vec::new(),
497            health_score: HealthScore::default(),
498        }
499    }
500}
501
502/// How urgent a [`MentorMessage`] is.
503#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
504#[serde(rename_all = "snake_case")]
505pub enum Severity {
506    /// Just for your information; no action needed.
507    Info,
508    /// Something might go wrong; recommend checking.
509    Warning,
510    /// Something is broken and blocks development.
511    Critical,
512}
513
514/// A beginner-friendly explanation of a detected issue.
515///
516/// Every message carries a plain-English explanation, the underlying
517/// technical detail, and a concrete suggested action.
518///
519/// ```
520/// use limitless_cli::models::{MentorMessage, Severity};
521///
522/// let msg = MentorMessage {
523///     severity: Severity::Warning,
524///     plain_english: "Your Node version is outdated.".into(),
525///     technical_detail: "Node 18 is EOL; latest LTS is 22.x.".into(),
526///     suggested_action: "Install Node 22 via your version manager.".into(),
527/// };
528/// let json = serde_json::to_string(&msg).unwrap();
529/// let back: MentorMessage = serde_json::from_str(&json).unwrap();
530/// assert_eq!(back.severity, Severity::Warning);
531/// assert_eq!(back.suggested_action, msg.suggested_action);
532/// ```
533#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
534pub struct MentorMessage {
535    /// Urgency level of this message.
536    pub severity: Severity,
537    /// Friendly, jargon-free description of the issue.
538    pub plain_english: String,
539    /// The precise technical reason behind the issue.
540    pub technical_detail: String,
541    /// A concrete step the user can take next.
542    pub suggested_action: String,
543}
544
545impl MentorMessage {
546    /// Whether this message needs immediate attention.
547    pub fn is_critical(&self) -> bool {
548        self.severity == Severity::Critical
549    }
550}
551
552/// Serializable progress state for Arcade mode.
553///
554/// ```
555/// use limitless_cli::models::ArcadeState;
556///
557/// let mut arcade = ArcadeState::default();
558/// let new_record = arcade.record_game(2500);
559/// arcade.unlock_achievement("first-win");
560/// assert!(new_record);
561///
562/// let json = serde_json::to_string(&arcade).unwrap();
563/// let back: ArcadeState = serde_json::from_str(&json).unwrap();
564/// assert_eq!(back.high_score, 2500);
565/// assert_eq!(back.games_played, 1);
566/// assert_eq!(back.achievements, vec!["first-win"]);
567/// ```
568#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
569pub struct ArcadeState {
570    /// The best score achieved so far.
571    pub high_score: u32,
572    /// Total number of games played.
573    pub games_played: u32,
574    /// Names of unlocked achievements (kept unique).
575    pub achievements: Vec<String>,
576}
577
578impl ArcadeState {
579    /// Records a finished game. Returns `true` when a new high score was set.
580    pub fn record_game(&mut self, score: u32) -> bool {
581        self.games_played = self.games_played.saturating_add(1);
582        if score > self.high_score {
583            self.high_score = score;
584            true
585        } else {
586            false
587        }
588    }
589
590    /// Unlocks an achievement. Returns `false` if it was already unlocked.
591    pub fn unlock_achievement(&mut self, name: impl Into<String>) -> bool {
592        let name = name.into();
593        if self.achievements.contains(&name) {
594            false
595        } else {
596            self.achievements.push(name);
597            true
598        }
599    }
600}
601
602#[cfg(test)]
603mod tests {
604    use super::*;
605
606    #[test]
607    fn project_stack_round_trips() {
608        for stack in [
609            ProjectStack::Node {
610                version: "22.9.0".into(),
611                package_manager: "npm".into(),
612            },
613            ProjectStack::Python {
614                version: "3.12".into(),
615            },
616            ProjectStack::Rust {
617                version: "1.98.0".into(),
618            },
619            ProjectStack::Docker,
620            ProjectStack::Unknown,
621        ] {
622            let json = serde_json::to_string(&stack).unwrap();
623            let back: ProjectStack = serde_json::from_str(&json).unwrap();
624            assert_eq!(back, stack);
625        }
626    }
627
628    #[test]
629    fn project_stack_docker_omits_payload() {
630        let json = serde_json::to_string(&ProjectStack::Docker).unwrap();
631        assert_eq!(json, r#"{"type":"docker"}"#);
632    }
633
634    #[test]
635    fn diagnostics_remediation_is_optional_in_json() {
636        let pass = DiagnosticResult::new("Runtime Check", CheckStatus::Pass, "Node found");
637        let fail = DiagnosticResult::new("Env Audit", CheckStatus::Fail, "missing .env")
638            .with_remediation("copy .env.example");
639
640        assert!(pass.remediation.is_none());
641        assert!(fail.remediation.is_some());
642
643        let pass_json = serde_json::to_string(&pass).unwrap();
644        let fail_json = serde_json::to_string(&fail).unwrap();
645
646        assert!(!pass_json.contains("remediation"));
647        assert!(fail_json.contains("remediation"));
648
649        let back: DiagnosticResult = serde_json::from_str(&pass_json).unwrap();
650        assert_eq!(back, pass);
651        let back: DiagnosticResult = serde_json::from_str(&fail_json).unwrap();
652        assert_eq!(back, fail);
653    }
654
655    #[test]
656    fn health_score_computes_counts_and_status() {
657        let checks = vec![
658            DiagnosticResult::new("A", CheckStatus::Pass, "ok"),
659            DiagnosticResult::new("B", CheckStatus::Pass, "ok"),
660            DiagnosticResult::new("C", CheckStatus::Warn, "meh"),
661            DiagnosticResult::new("D", CheckStatus::Fail, "broken"),
662        ];
663
664        let score = HealthScore::from_results(&checks);
665        assert_eq!(score.total_checks, 4);
666        assert_eq!(score.passed, 2);
667        assert_eq!(score.warnings, 1);
668        assert_eq!(score.failed, 1);
669        assert_eq!(score.percentage, 50);
670        assert_eq!(score.overall_status, HealthStatus::Critical);
671        assert!(score.validate().is_ok());
672    }
673
674    #[test]
675    fn health_score_default_is_healthy_empty() {
676        let score = HealthScore::default();
677        assert_eq!(score.total_checks, 0);
678        assert_eq!(score.percentage, 100);
679        assert_eq!(score.overall_status, HealthStatus::Healthy);
680        assert!(score.validate().is_ok());
681    }
682
683    #[test]
684    fn recompute_fixes_stale_serialized_score() {
685        let mut score =
686            HealthScore::from_results(&[DiagnosticResult::new("A", CheckStatus::Fail, "boom")]);
687        score.percentage = 42;
688        assert!(score.validate().is_err());
689
690        let fixed = score.recompute();
691        assert_eq!(fixed.percentage, 0);
692        assert_eq!(fixed.overall_status, HealthStatus::Critical);
693        assert!(fixed.validate().is_ok());
694
695        let json = serde_json::to_string(&fixed).unwrap();
696        let back: HealthScore = serde_json::from_str(&json).unwrap();
697        assert_eq!(back, fixed);
698    }
699
700    #[test]
701    fn environment_state_round_trips_with_blocked_ports() {
702        let state = EnvironmentState {
703            detected_stack: ProjectStack::Node {
704                version: "22.9.0".into(),
705                package_manager: "npm".into(),
706            },
707            runtime_version: Some("v22.9.0".into()),
708            env_file_exists: true,
709            env_example_exists: true,
710            dependencies_healthy: true,
711            blocked_ports: vec![(8080, 4123), (5432, 5555)],
712            diagnostics: vec![DiagnosticResult::new(
713                "Port Scan",
714                CheckStatus::Fail,
715                "8080 is blocked",
716            )],
717            health_score: HealthScore::from_results(&[DiagnosticResult::new(
718                "Port Scan",
719                CheckStatus::Fail,
720                "8080 is blocked",
721            )]),
722        };
723
724        assert!(!state.ready_for_dev());
725
726        let json = serde_json::to_string(&state).unwrap();
727        assert!(json.contains("[8080,4123]"));
728        let back: EnvironmentState = serde_json::from_str(&json).unwrap();
729        assert_eq!(back, state);
730        assert_eq!(back.blocked_ports, vec![(8080, 4123), (5432, 5555)]);
731    }
732
733    #[test]
734    fn mentor_message_round_trips() {
735        let msg = MentorMessage {
736            severity: Severity::Critical,
737            plain_english: "Port 3000 is taken.".into(),
738            technical_detail: "PID 4123 holds port 3000.".into(),
739            suggested_action: "Stop PID 4123 or use another port.".into(),
740        };
741        assert!(msg.is_critical());
742
743        let json = serde_json::to_string(&msg).unwrap();
744        assert!(json.contains(r#""severity":"critical""#));
745        let back: MentorMessage = serde_json::from_str(&json).unwrap();
746        assert_eq!(back, msg);
747    }
748
749    #[test]
750    fn arcade_state_tracks_records_and_achievements() {
751        let mut arcade = ArcadeState::default();
752        assert!(arcade.record_game(1000));
753        assert!(!arcade.record_game(500));
754        assert!(arcade.record_game(2000));
755        assert_eq!(arcade.high_score, 2000);
756        assert_eq!(arcade.games_played, 3);
757
758        assert!(arcade.unlock_achievement("first-win"));
759        assert!(!arcade.unlock_achievement("first-win"));
760        assert_eq!(arcade.achievements, vec!["first-win"]);
761
762        let json = serde_json::to_string(&arcade).unwrap();
763        let back: ArcadeState = serde_json::from_str(&json).unwrap();
764        assert_eq!(back, arcade);
765    }
766}