use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ProjectStack {
Node {
version: String,
package_manager: String,
},
Python { version: String },
Rust { version: String },
Go { version: String },
Java { version: String },
Docker,
Unknown,
}
impl ProjectStack {
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(),
}
}
pub fn is_known(&self) -> bool {
!matches!(self, ProjectStack::Unknown)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CheckStatus {
Pass,
Warn,
Fail,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HealthStatus {
Healthy,
Caution,
Critical,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiagnosticResult {
pub check_name: String,
pub status: CheckStatus,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub remediation: Option<String>,
}
impl DiagnosticResult {
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,
}
}
pub fn with_remediation(mut self, remediation: impl Into<String>) -> Self {
self.remediation = Some(remediation.into());
self
}
pub fn set_remediation(&mut self, remediation: impl Into<String>) {
self.remediation = Some(remediation.into());
}
pub fn is_pass(&self) -> bool {
self.status == CheckStatus::Pass
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct HealthScore {
pub total_checks: u32,
pub passed: u32,
pub warnings: u32,
pub failed: u32,
pub percentage: u32,
pub overall_status: HealthStatus,
}
impl HealthScore {
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)
}
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,
}
}
pub fn recompute(self) -> Self {
Self::from_counts(self.passed, self.warnings, self.failed)
}
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(())
}
pub fn is_healthy(&self) -> bool {
self.overall_status == HealthStatus::Healthy
}
}
impl Default for HealthScore {
fn default() -> Self {
Self {
total_checks: 0,
passed: 0,
warnings: 0,
failed: 0,
percentage: 100,
overall_status: HealthStatus::Healthy,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnvironmentState {
pub detected_stack: ProjectStack,
#[serde(skip_serializing_if = "Option::is_none")]
pub runtime_version: Option<String>,
pub env_file_exists: bool,
pub env_example_exists: bool,
pub dependencies_healthy: bool,
pub blocked_ports: Vec<(u16, u32)>,
pub diagnostics: Vec<DiagnosticResult>,
pub health_score: HealthScore,
}
impl EnvironmentState {
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()
}
pub fn failed_checks(&self) -> usize {
self.diagnostics
.iter()
.filter(|d| d.status == CheckStatus::Fail)
.count()
}
pub fn refresh_health(&mut self) {
self.health_score = HealthScore::from_results(&self.diagnostics);
}
}
impl Default for EnvironmentState {
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(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Severity {
Info,
Warning,
Critical,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MentorMessage {
pub severity: Severity,
pub plain_english: String,
pub technical_detail: String,
pub suggested_action: String,
}
impl MentorMessage {
pub fn is_critical(&self) -> bool {
self.severity == Severity::Critical
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ArcadeState {
pub high_score: u32,
pub games_played: u32,
pub achievements: Vec<String>,
}
impl ArcadeState {
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
}
}
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);
}
}