use colored::{ColoredString, Colorize};
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use crate::models::{
CheckStatus, DiagnosticResult, EnvironmentState, HealthScore, MentorMessage, ProjectStack,
Severity,
};
use crate::modules::port_watcher;
use crate::modules::runtime_validator::{validate_installed_runtime, VersionReport};
use crate::modules::stack_detector::detect_stack;
pub fn path_separator() -> char {
if cfg!(windows) {
';'
} else {
':'
}
}
pub fn expand_windows_var(entry: &str) -> PathBuf {
if let Some(start) = entry.find('%') {
if let Some(end) = entry[start + 1..].find('%') {
let end = start + 1 + end;
if end > start + 1 {
let name = &entry[start + 1..end];
if let Ok(value) = env::var(name) {
return PathBuf::from(format!(
"{}{}{}",
&entry[..start],
value,
&entry[end + 1..]
));
}
}
}
}
PathBuf::from(entry)
}
pub fn resolve_path_entry(entry: &str) -> PathBuf {
expand_windows_var(entry)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathReport {
pub total_entries: usize,
pub empty_entries: usize,
pub broken_entries: Vec<String>,
pub duplicate_entries: Vec<PathBuf>,
pub has_current_dir: bool,
}
pub fn analyze_path(raw: &str) -> PathReport {
let sep = path_separator();
let tokens: Vec<&str> = raw.split(sep).collect();
let total_entries = tokens.len();
let mut broken_entries = Vec::new();
let mut duplicates = Vec::new();
let mut seen: Vec<PathBuf> = Vec::new();
let mut empty_entries = 0;
let mut has_current_dir = false;
for token in tokens {
let trimmed = token.trim();
if trimmed.is_empty() {
empty_entries += 1;
continue;
}
if trimmed == "." {
has_current_dir = true;
}
let resolved = resolve_path_entry(trimmed);
if !resolved.is_dir() {
broken_entries.push(trimmed.to_string());
continue;
}
if seen.contains(&resolved) {
if !duplicates.contains(&resolved) {
duplicates.push(resolved);
}
} else {
seen.push(resolved);
}
}
PathReport {
total_entries,
empty_entries,
broken_entries,
duplicate_entries: duplicates,
has_current_dir,
}
}
pub fn resolve_var(primary: &str, alt: &str) -> Option<String> {
env::var(primary).ok().or_else(|| env::var(alt).ok())
}
fn raw_path() -> Result<String, CheckStatus> {
match env::var("PATH") {
Ok(raw) if !raw.trim().is_empty() => Ok(raw),
Ok(_) => Err(CheckStatus::Fail),
Err(_) => Err(CheckStatus::Fail),
}
}
pub fn path_checks() -> Vec<DiagnosticResult> {
let raw = match raw_path() {
Ok(raw) => raw,
Err(_) => {
return vec![DiagnosticResult::new(
"PATH set",
CheckStatus::Fail,
"PATH is not set",
)];
}
};
let report = analyze_path(&raw);
let mut out = vec![DiagnosticResult::new(
"PATH set",
CheckStatus::Pass,
format!("{} entries on PATH", report.total_entries),
)];
if !report.broken_entries.is_empty() {
out.push(
DiagnosticResult::new(
"Broken PATH entries",
CheckStatus::Warn,
format!(
"{} entries point to folders that do not exist",
report.broken_entries.len()
),
)
.with_remediation(format!(
"Remove or fix: {}",
report.broken_entries.join(", ")
)),
);
}
if !report.duplicate_entries.is_empty() {
out.push(
DiagnosticResult::new(
"Duplicate PATH entries",
CheckStatus::Warn,
format!(
"{} folders are listed more than once",
report.duplicate_entries.len()
),
)
.with_remediation("Remove the duplicated folders from your PATH"),
);
}
if report.has_current_dir && cfg!(windows) {
out.push(
DiagnosticResult::new(
"PATH current directory",
CheckStatus::Warn,
"PATH contains the '.' entry; programs in the current folder can run by accident",
)
.with_remediation("Remove the '.' entry from PATH on Windows"),
);
}
out
}
pub fn check_home() -> DiagnosticResult {
match resolve_var("USERPROFILE", "HOME") {
Some(home) if Path::new(&home).is_dir() => DiagnosticResult::new(
"Home directory",
CheckStatus::Pass,
format!("{home} exists"),
),
Some(home) => DiagnosticResult::new(
"Home directory",
CheckStatus::Warn,
format!("{home} is set but does not exist"),
),
None => DiagnosticResult::new(
"Home directory",
CheckStatus::Fail,
"HOME/USERPROFILE is not set",
),
}
}
pub fn check_editor() -> DiagnosticResult {
match resolve_var("EDITOR", "VISUAL") {
Some(editor) if !editor.trim().is_empty() => DiagnosticResult::new(
"Editor",
CheckStatus::Pass,
format!("EDITOR is set to {editor}"),
),
_ => DiagnosticResult::new(
"Editor",
CheckStatus::Warn,
"EDITOR/VISUAL is not set; tools may fall back to a default editor",
)
.with_remediation("Set EDITOR, e.g. export EDITOR=\"code --wait\""),
}
}
pub fn proxy_consistency(
http: Option<String>,
https: Option<String>,
) -> (CheckStatus, &'static str) {
match (http, https) {
(Some(_), Some(_)) => (CheckStatus::Pass, "HTTP_PROXY and HTTPS_PROXY are both set"),
(Some(_), None) => (
CheckStatus::Warn,
"HTTP_PROXY is set but HTTPS_PROXY is missing",
),
(None, Some(_)) => (
CheckStatus::Warn,
"HTTPS_PROXY is set but HTTP_PROXY is missing",
),
(None, None) => (CheckStatus::Pass, "no proxy variables set"),
}
}
pub fn check_proxy() -> DiagnosticResult {
let http = env::var("HTTP_PROXY")
.ok()
.or_else(|| env::var("http_proxy").ok());
let https = env::var("HTTPS_PROXY")
.ok()
.or_else(|| env::var("https_proxy").ok());
let (status, message) = proxy_consistency(http, https);
DiagnosticResult::new("Proxy consistency", status, message)
}
pub const CORE_TOOLS: &[(&str, &str)] = &[
("rustc", "--version"),
("cargo", "--version"),
("node", "--version"),
("npm", "--version"),
("python", "--version"),
("go", "version"),
("java", "-version"),
];
pub fn probe_tool(name: &str, flag: &str) -> Option<String> {
let exec_name = if cfg!(windows) && matches!(name, "npm" | "yarn" | "pnpm" | "npx") {
format!("{name}.cmd")
} else {
name.to_string()
};
let output = Command::new(&exec_name).arg(flag).output().ok()?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let version = stdout
.trim()
.lines()
.next()
.or_else(|| stderr.trim().lines().next())?;
if version.is_empty() {
None
} else {
Some(version.to_string())
}
}
pub fn tools_on_path() -> Vec<DiagnosticResult> {
CORE_TOOLS
.iter()
.map(|(name, flag)| match probe_tool(name, flag) {
Some(version) => DiagnosticResult::new(
format!("Tool {name}"),
CheckStatus::Pass,
format!("{name} {version}"),
),
None => DiagnosticResult::new(
format!("Tool {name}"),
CheckStatus::Fail,
format!("{name} was not found on PATH"),
)
.with_remediation(format!("Install {name} and add it to PATH")),
})
.collect()
}
pub fn stack_context_checks(stack: &ProjectStack) -> Vec<DiagnosticResult> {
match stack {
ProjectStack::Python { .. } => match env::var("VIRTUAL_ENV") {
Ok(path) => vec![DiagnosticResult::new(
"Python virtualenv",
CheckStatus::Pass,
format!("active virtualenv at {path}"),
)],
Err(_) => vec![DiagnosticResult::new(
"Python virtualenv",
CheckStatus::Warn,
"no virtualenv is active",
)
.with_remediation("python -m venv .venv && .venv\\Scripts\\activate")],
},
ProjectStack::Rust { .. } => match env::var("CARGO_HOME") {
Ok(home) => vec![DiagnosticResult::new(
"Cargo home",
CheckStatus::Pass,
format!("CARGO_HOME = {home}"),
)],
Err(_) => vec![DiagnosticResult::new(
"Cargo home",
CheckStatus::Pass,
"CARGO_HOME unset (defaults to ~/.cargo)",
)],
},
_ => Vec::new(),
}
}
const DIAGNOSTIC_PORTS: &[u16] = &[3000, 3001, 5173, 5432, 8000, 8080, 8081, 27017];
fn lock_files_for(stack: &ProjectStack) -> &'static [&'static str] {
match stack {
ProjectStack::Node { .. } => &["package-lock.json", "yarn.lock", "pnpm-lock.yaml"],
ProjectStack::Python { .. } => &["Pipfile.lock", "poetry.lock", "uv.lock"],
ProjectStack::Rust { .. } => &["Cargo.lock"],
_ => &[],
}
}
pub fn dependency_audit(repo_root: &str, stack: &ProjectStack) -> DiagnosticResult {
if lock_files_for(stack).is_empty() {
return DiagnosticResult::new(
"Dependency audit",
CheckStatus::Pass,
"no dependency audit needed for this stack",
);
}
let root = Path::new(repo_root);
let manifest = match stack {
ProjectStack::Node { .. } => "package.json",
ProjectStack::Python { .. } => "pyproject.toml",
ProjectStack::Rust { .. } => "Cargo.toml",
_ => unreachable!(),
};
if !root.join(manifest).is_file() {
return DiagnosticResult::new(
"Dependency audit",
CheckStatus::Fail,
format!("{manifest} is missing"),
)
.with_remediation(format!(
"Run the initialiser for your stack to create {manifest}"
));
}
let has_lock = lock_files_for(stack)
.iter()
.any(|lock| root.join(lock).is_file());
if has_lock {
DiagnosticResult::new(
"Dependency audit",
CheckStatus::Pass,
"manifest and lock file are present",
)
} else {
DiagnosticResult::new(
"Dependency audit",
CheckStatus::Warn,
"manifest exists but no lock file is committed",
)
.with_remediation(
"Generate and commit a lock file (e.g. npm install for Node, poetry lock for Python)",
)
}
}
pub fn collect_diagnostics(repo_root: &str) -> Vec<DiagnosticResult> {
let stack = detect_stack(repo_root);
let mut results = Vec::new();
results.extend(path_checks());
results.push(check_home());
results.push(check_editor());
results.push(check_proxy());
results.extend(tools_on_path());
results.extend(stack_context_checks(&stack));
results.push(dependency_audit(repo_root, &stack));
results.extend(port_watcher::blocked_port_results(DIAGNOSTIC_PORTS));
results
}
pub fn build_snapshot(repo_root: &str) -> EnvironmentState {
run_full_diagnostics(repo_root)
}
pub fn mentor_messages(results: &[DiagnosticResult]) -> Vec<MentorMessage> {
let mut messages: Vec<MentorMessage> = results
.iter()
.filter(|d| d.status != CheckStatus::Pass)
.map(crate::modules::translator::translate_error)
.collect();
messages.sort_by_key(|m| match m.severity {
Severity::Critical => 0,
Severity::Warning => 1,
Severity::Info => 2,
});
messages
}
pub const CHECK_TIMEOUT: Duration = Duration::from_secs(5);
pub struct NamedCheck {
pub name: &'static str,
pub run: Box<dyn FnOnce() -> Vec<DiagnosticResult> + Send + 'static>,
}
impl NamedCheck {
pub fn single(
name: &'static str,
run: impl FnOnce() -> DiagnosticResult + Send + 'static,
) -> Self {
Self {
name,
run: Box::new(move || vec![run()]),
}
}
}
async fn guarded_check(
name: &'static str,
timeout: Duration,
run: Box<dyn FnOnce() -> Vec<DiagnosticResult> + Send + 'static>,
) -> Vec<DiagnosticResult> {
match tokio::time::timeout(timeout, tokio::task::spawn_blocking(run)).await {
Ok(Ok(results)) => results,
Ok(Err(error)) => {
vec![DiagnosticResult::new(
name,
CheckStatus::Fail,
format!("{name} check crashed: {error}"),
)
.with_remediation("Retry the diagnostic run")]
}
Err(_) => {
vec![DiagnosticResult::new(
name,
CheckStatus::Fail,
format!("{name} check timed out after {}s", timeout.as_secs()),
)
.with_remediation("Retry the diagnostic run")]
}
}
}
pub fn run_checks_parallel(checks: Vec<NamedCheck>) -> Vec<DiagnosticResult> {
run_checks_parallel_with_timeout(checks, CHECK_TIMEOUT)
}
fn run_checks_parallel_with_timeout(
checks: Vec<NamedCheck>,
timeout: Duration,
) -> Vec<DiagnosticResult> {
if checks.is_empty() {
return Vec::new();
}
std::thread::spawn(move || {
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("build diagnostics runtime");
runtime.block_on(async move {
let mut batch = tokio::task::JoinSet::new();
for check in checks {
batch.spawn(guarded_check(check.name, timeout, check.run));
}
let mut results = Vec::new();
while let Some(joined) = batch.join_next().await {
match joined {
Ok(per_check) => results.extend(per_check),
Err(error) if error.is_panic() => results.push(
DiagnosticResult::new(
"Parallel check",
CheckStatus::Fail,
format!("a parallel check panicked: {error}"),
)
.with_remediation("Retry the diagnostic run"),
),
Err(_) => { }
}
}
results
})
})
.join()
.unwrap_or_else(|_| {
vec![DiagnosticResult::new(
"Parallel check",
CheckStatus::Fail,
"the diagnostics runtime crashed before running checks",
)]
})
}
fn version_report_to_diagnostic(report: VersionReport) -> DiagnosticResult {
let mut diagnostic = DiagnosticResult::new("Runtime Check", report.status, report.message);
if let Some(remediation) = report.remediation {
diagnostic.remediation = Some(remediation);
}
diagnostic
}
pub fn run_full_diagnostics(repo_path: &str) -> EnvironmentState {
let stack = detect_stack(repo_path);
let runtime_version = Arc::new(Mutex::new(None));
let blocked_ports = Arc::new(Mutex::new(Vec::new()));
let runtime_repo = repo_path.to_string();
let runtime_slot = Arc::clone(&runtime_version);
let env_repo = repo_path.to_string();
let deps_repo = repo_path.to_string();
let deps_stack = stack.clone();
let ports_slot = Arc::clone(&blocked_ports);
let audit_repo = repo_path.to_string();
let audit_stack = stack.clone();
let context_stack = stack.clone();
let checks = vec![
NamedCheck {
name: "Runtime Check",
run: Box::new(move || {
let mut results = Vec::new();
if let Some(report) = validate_installed_runtime(&runtime_repo) {
*runtime_slot.lock().expect("runtime slot") =
Some(report.actual_version.clone());
results.push(version_report_to_diagnostic(report));
} else {
results.push(DiagnosticResult::new(
"Runtime Check",
CheckStatus::Pass,
"no runtime version to validate for this stack",
));
}
results
}),
},
NamedCheck::single("Env Audit", move || {
crate::modules::env_auditor::audit_env_files(&env_repo)
}),
NamedCheck::single("Dependencies", move || {
crate::modules::dependency_checker::check_dependencies(&deps_repo, &deps_stack)
}),
NamedCheck {
name: "Port Scan",
run: Box::new(move || {
let found = port_watcher::check_blocked_ports(DIAGNOSTIC_PORTS);
let mut results = Vec::new();
for (port, pid, process) in &found {
ports_slot.lock().expect("ports slot").push((*port, *pid));
results.push(port_watcher::diagnostic_for(*port, *pid, process));
}
if results.is_empty() {
results.push(DiagnosticResult::new(
"Port Scan",
CheckStatus::Pass,
"no common development ports are in use",
));
}
results
}),
},
NamedCheck::single("Dependency audit", move || {
dependency_audit(&audit_repo, &audit_stack)
}),
NamedCheck {
name: "PATH",
run: Box::new(path_checks),
},
NamedCheck {
name: "Tools",
run: Box::new(tools_on_path),
},
NamedCheck::single("Home directory", check_home),
NamedCheck::single("Editor", check_editor),
NamedCheck::single("Proxy consistency", check_proxy),
NamedCheck {
name: "Stack context",
run: Box::new(move || stack_context_checks(&context_stack)),
},
];
let diagnostics = run_checks_parallel(checks);
let dependencies_healthy = diagnostics
.iter()
.any(|d| d.check_name == "Dependency audit" && d.is_pass());
let root = Path::new(repo_path);
let mut state = EnvironmentState {
detected_stack: stack,
runtime_version: runtime_version.lock().expect("runtime slot").clone(),
env_file_exists: root.join(".env").is_file(),
env_example_exists: root.join(".env.example").is_file(),
dependencies_healthy,
blocked_ports: blocked_ports.lock().expect("ports slot").clone(),
diagnostics,
health_score: HealthScore::default(),
};
state.refresh_health();
state
}
fn status_icon(status: CheckStatus) -> ColoredString {
match status {
CheckStatus::Pass => "PASS".green().bold(),
CheckStatus::Warn => "WARN".yellow().bold(),
CheckStatus::Fail => "FAIL".red().bold(),
}
}
fn health_bar(score: &HealthScore) -> String {
let filled = (score.percentage as usize / 5).min(20);
let bar = format!("{}{}", "#".repeat(filled), ".".repeat(20 - filled));
match score.overall_status {
crate::models::HealthStatus::Healthy => bar.green().to_string(),
crate::models::HealthStatus::Caution => bar.yellow().to_string(),
crate::models::HealthStatus::Critical => bar.red().to_string(),
}
}
fn show_env_var(label: &str, value: impl AsRef<str>) {
println!(
" {} {}",
format!("{label}:").bold(),
value.as_ref().dimmed()
);
}
pub fn run_dev() {
let state = build_snapshot(".");
println!(
"{}",
"=== Developer Environment Diagnostics ===".bold().cyan()
);
if let Some(runtime) = &state.runtime_version {
println!(" {} {}", "Runtime:".bold(), runtime);
}
println!();
let path_value = env::var("PATH").unwrap_or_default();
let path_report = analyze_path(&path_value);
println!(
" {} ({})",
"PATH summary:".bold(),
path_report.total_entries
);
if path_report.broken_entries.is_empty() && path_report.duplicate_entries.is_empty() {
println!(" {} ", " no broken or duplicate entries".dimmed());
} else {
if !path_report.broken_entries.is_empty() {
println!(
" {} {}",
format!("{} broken entries", path_report.broken_entries.len())
.red()
.bold(),
"(point to missing folders)".dimmed()
);
}
if !path_report.duplicate_entries.is_empty() {
println!(
" {} {}",
format!("{} duplicates", path_report.duplicate_entries.len())
.yellow()
.bold(),
"(same folder listed twice)".dimmed()
);
}
}
println!();
println!(" {} {}", "Stack:".bold(), state.detected_stack.label());
println!(
" {} {}",
"Env files:".bold(),
match (state.env_file_exists, state.env_example_exists) {
(true, true) => ".env and .env.example found".green().to_string(),
(true, false) => ".env found (no .env.example)".yellow().to_string(),
(false, true) => ".env.example found (no .env)".yellow().to_string(),
(false, false) => "none found".red().to_string(),
}
);
if !state.blocked_ports.is_empty() {
println!(
" {} {}",
"Blocked ports:".red().bold(),
state
.blocked_ports
.iter()
.map(|(port, pid)| format!("{port} (pid {pid})"))
.collect::<Vec<_>>()
.join(", ")
);
}
println!();
show_env_var(
"HOME",
resolve_var("USERPROFILE", "HOME").unwrap_or_default(),
);
show_env_var("SHELL", resolve_var("SHELL", "COMSPEC").unwrap_or_default());
show_env_var(
"EDITOR",
resolve_var("EDITOR", "VISUAL").unwrap_or_default(),
);
show_env_var(
"LANG",
env::var("LANG")
.unwrap_or_else(|_| env::var("LC_ALL").unwrap_or_else(|_| "not set".into())),
);
println!();
println!("{}", "Checks:".bold());
for result in &state.diagnostics {
println!(
" {} {}",
status_icon(result.status),
format!("{} — {}", result.check_name, result.message).dimmed()
);
if let Some(remediation) = &result.remediation {
println!(" {} {}", " Fix:".cyan().bold(), remediation.dimmed());
}
}
println!();
let score = &state.health_score;
println!(
" {} {} {:?} ({}%)",
"Health:".bold(),
health_bar(score),
score.overall_status,
score.percentage
);
println!(
" {} of {} checks passed ({} warnings, {} failed)",
score.passed, score.total_checks, score.warnings, score.failed
);
let mentors = mentor_messages(&state.diagnostics);
if !mentors.is_empty() {
println!();
println!("{}", "Mentor advice:".bold());
for message in &mentors {
println!(
"{}",
crate::modules::message_formatter::format_mentor_message(message)
);
}
}
println!();
if state.ready_for_dev() {
println!(
" {} {}",
"Ready for development:".bold().green(),
"yes".green().bold()
);
} else {
println!(
" {} {}",
"Ready for development:".bold().yellow(),
"no".yellow().bold()
);
}
println!();
println!("{}", "Dev diagnostics complete!".green().bold());
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::time::{SystemTime, UNIX_EPOCH};
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(label: &str) -> Self {
let stamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock")
.as_nanos();
let path = std::env::temp_dir().join(format!("limitless_diag_{label}_{stamp}"));
fs::create_dir_all(&path).expect("create temp dir");
TempDir { path }
}
fn path(&self) -> &Path {
&self.path
}
fn write(self, relative: &str, content: &str) -> Self {
let full = self.path.join(relative);
if let Some(parent) = full.parent() {
fs::create_dir_all(parent).expect("create parent dirs");
}
fs::write(full, content).expect("write fixture file");
self
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
#[test]
fn analyze_path_reports_broken_duplicate_and_current_dir() {
let one = TempDir::new("dir_one");
let two = TempDir::new("dir_two");
let sep = path_separator();
let raw = format!(
"{}{sep}{}{sep}{}{sep}.{sep}missing_folder_xyz",
one.path().display(),
two.path().display(),
two.path().display()
);
let report = analyze_path(&raw);
assert_eq!(report.total_entries, 5);
assert_eq!(report.empty_entries, 0);
assert!(report.has_current_dir);
assert_eq!(
report.broken_entries,
vec!["missing_folder_xyz".to_string()]
);
assert_eq!(report.duplicate_entries, vec![two.path().to_path_buf()]);
}
#[test]
fn analyze_path_counts_empty_entries() {
let sep = path_separator();
let raw = format!("{sep}{sep}");
let report = analyze_path(&raw);
assert_eq!(report.total_entries, 3);
assert_eq!(report.empty_entries, 3);
assert!(report.broken_entries.is_empty());
}
#[test]
fn analyze_path_clean_path_has_no_problems() {
let dir = TempDir::new("clean_dir");
let report = analyze_path(&dir.path().to_string_lossy());
assert!(report.broken_entries.is_empty());
assert!(report.duplicate_entries.is_empty());
assert!(!report.has_current_dir);
}
#[test]
fn proxy_consistency_classifies_all_pairs() {
assert_eq!(
proxy_consistency(Some("http://proxy".into()), Some("http://proxy".into())).0,
CheckStatus::Pass
);
assert_eq!(
proxy_consistency(Some("http://proxy".into()), None).0,
CheckStatus::Warn
);
assert_eq!(
proxy_consistency(None, Some("http://proxy".into())).0,
CheckStatus::Warn
);
assert_eq!(proxy_consistency(None, None).0, CheckStatus::Pass);
}
#[test]
fn is_port_in_use_returns_true_when_bound() {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).expect("bind ephemeral port");
let port = listener.local_addr().expect("local addr").port();
assert!(port_watcher::is_port_in_use(port));
}
#[test]
fn is_port_in_use_returns_false_when_free() {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).expect("bind ephemeral port");
let port = listener.local_addr().expect("local addr").port();
drop(listener);
assert!(!port_watcher::is_port_in_use(port));
}
#[test]
fn dependency_audit_node_with_lockfile_passes() {
let dir = TempDir::new("node_locked")
.write("package.json", r#"{ "name": "web" }"#)
.write("package-lock.json", "{}");
assert_eq!(
dependency_audit(dir.path().to_str().unwrap(), &stack_node()).status,
CheckStatus::Pass
);
}
#[test]
fn dependency_audit_node_without_lockfile_warns() {
let dir = TempDir::new("node_unlocked").write("package.json", r#"{ "name": "web" }"#);
assert_eq!(
dependency_audit(dir.path().to_str().unwrap(), &stack_node()).status,
CheckStatus::Warn
);
}
#[test]
fn dependency_audit_rust_with_lockfile_passes() {
let dir = TempDir::new("rust_locked")
.write(
"Cargo.toml",
"[package]\nname = \"demo\"\nversion = \"0.1.0\"\n",
)
.write(
"Cargo.lock",
"# This file is automatically @generated by Cargo.",
);
assert_eq!(
dependency_audit(dir.path().to_str().unwrap(), &stack_rust()).status,
CheckStatus::Pass
);
}
#[test]
fn dependency_audit_python_missing_manifest_fails() {
let dir = TempDir::new("python_empty");
assert_eq!(
dependency_audit(dir.path().to_str().unwrap(), &stack_python()).status,
CheckStatus::Fail
);
}
#[test]
fn dependency_audit_unknown_stack_passes() {
let dir = TempDir::new("unknown_stack");
assert_eq!(
dependency_audit(dir.path().to_str().unwrap(), &ProjectStack::Unknown).status,
CheckStatus::Pass
);
}
#[test]
fn build_snapshot_assembles_rust_project() {
let dir = TempDir::new("snapshot_rust")
.write(
"Cargo.toml",
"[package]\nname = \"demo\"\nversion = \"0.1.0\"\n",
)
.write("Cargo.lock", "# lock");
let state = build_snapshot(dir.path().to_str().unwrap());
assert_eq!(state.detected_stack, stack_rust());
assert!(state.runtime_version.is_some());
assert!(state.dependencies_healthy);
assert!(!state.diagnostics.is_empty());
assert!(state.health_score.total_checks > 0);
assert!(state.blocked_ports.is_empty() || !state.blocked_ports.is_empty());
assert!(!state.env_file_exists);
}
#[test]
fn mentor_messages_flatten_passes() {
let results = vec![
DiagnosticResult::new("PATH set", CheckStatus::Pass, "ok"),
DiagnosticResult::new("Tool node", CheckStatus::Fail, "node was not found on PATH")
.with_remediation("Install node via nvm"),
DiagnosticResult::new(
"Duplicate PATH entries",
CheckStatus::Warn,
"1 folder is listed more than once",
),
];
let messages = mentor_messages(&results);
assert_eq!(messages.len(), 2);
assert_eq!(messages[0].severity, Severity::Critical);
assert_eq!(messages[1].severity, Severity::Warning);
assert!(messages[0].plain_english.contains("node"));
assert_eq!(messages[0].suggested_action, "Install node via nvm");
}
#[test]
fn run_checks_parallel_aggregates_mock_results() {
let checks = vec![
NamedCheck::single("Good", || {
DiagnosticResult::new("P", CheckStatus::Pass, "ok")
}),
NamedCheck::single("Heads-up", || {
DiagnosticResult::new("W", CheckStatus::Warn, "careful")
}),
NamedCheck::single("Broken", || {
DiagnosticResult::new("F", CheckStatus::Fail, "boom")
}),
];
let results = run_checks_parallel(checks);
assert_eq!(results.len(), 3);
assert!(results.iter().any(|r| r.is_pass()));
assert!(results.iter().any(|r| r.status == CheckStatus::Warn));
assert!(results.iter().any(|r| r.status == CheckStatus::Fail));
}
#[test]
fn run_checks_parallel_runs_simultaneously() {
let check = |name: &'static str, status: CheckStatus| {
NamedCheck::single(name, move || {
std::thread::sleep(std::time::Duration::from_millis(150));
DiagnosticResult::new(name, status, "done")
})
};
let checks = vec![check("A", CheckStatus::Pass), check("B", CheckStatus::Pass)];
let start = std::time::Instant::now();
let results = run_checks_parallel(checks);
let elapsed = start.elapsed();
assert_eq!(results.len(), 2);
assert!(
elapsed < std::time::Duration::from_millis(290),
"checks ran serially: {elapsed:?}"
);
}
#[test]
fn run_checks_parallel_times_out_slow_checks() {
let checks = vec![NamedCheck {
name: "Sleepy",
run: Box::new(|| {
std::thread::sleep(std::time::Duration::from_millis(200));
vec![DiagnosticResult::new(
"Sleepy",
CheckStatus::Pass,
"too slow",
)]
}),
}];
let results =
run_checks_parallel_with_timeout(checks, std::time::Duration::from_millis(50));
assert_eq!(results.len(), 1);
let timed_out = &results[0];
assert_eq!(timed_out.check_name, "Sleepy");
assert_eq!(timed_out.status, CheckStatus::Fail);
assert!(timed_out.message.contains("timed out"));
}
#[test]
fn run_checks_parallel_aggregates_panics_as_fail() {
let checks = vec![NamedCheck {
name: "Boom",
run: Box::new(|| panic!("mock check exploded")),
}];
let results = run_checks_parallel(checks);
assert_eq!(results.len(), 1);
assert_eq!(results[0].status, CheckStatus::Fail);
assert!(results[0].message.contains("crashed"));
}
#[test]
fn run_checks_parallel_empty_batch_yields_nothing() {
assert!(run_checks_parallel(Vec::new()).is_empty());
}
#[test]
fn run_full_diagnostics_returns_consistent_state() {
let dir = TempDir::new("full_diag")
.write(
"Cargo.toml",
"[package]\nname = \"demo\"\nversion = \"0.1.0\"\n",
)
.write("Cargo.lock", "# lock");
let state = run_full_diagnostics(dir.path().to_str().unwrap());
assert_eq!(state.detected_stack, stack_rust());
assert!(!state.diagnostics.is_empty());
assert_eq!(
state.health_score.total_checks,
state.diagnostics.len() as u32
);
assert!(state.health_score.validate().is_ok());
assert!(!state.blocked_ports.is_empty() || state.blocked_ports.is_empty());
assert!(state.dependencies_healthy);
assert!(state.runtime_version.is_some());
}
fn stack_node() -> ProjectStack {
ProjectStack::Node {
version: String::new(),
package_manager: "npm".to_string(),
}
}
fn stack_python() -> ProjectStack {
ProjectStack::Python {
version: String::new(),
}
}
fn stack_rust() -> ProjectStack {
ProjectStack::Rust {
version: String::new(),
}
}
fn fixture(sub: &str) -> String {
format!("{}/tests/fixtures/{sub}", env!("CARGO_MANIFEST_DIR"))
}
#[test]
fn test_env_file_detection() {
let audit = crate::modules::env_auditor::audit_env_files(&fixture("env_sample_project"));
assert_eq!(audit.check_name, "Env Audit");
assert_eq!(audit.status, CheckStatus::Warn);
assert!(audit.message.contains(".env.example"));
let clean = crate::modules::env_auditor::audit_env_files(&fixture("node_project"));
assert_eq!(clean.status, CheckStatus::Pass);
}
#[test]
fn test_port_blockage_detection() {
let output = "\
TCP 0.0.0.0:3000 0.0.0.0:0 LISTENING 9921
TCP 127.0.0.1:8080 0.0.0.0:0 LISTENING 12345
TCP 127.0.0.1:50001 0.0.0.0:0 ESTABLISHED 55
";
let found = port_watcher::parse_netstat(output);
assert!(found.contains(&(3000, 9921)));
assert!(found.contains(&(8080, 12345)));
assert!(!found.iter().any(|(port, _)| *port == 50001));
let tasks = "\
\"node.exe\",\"9921\",\"Console\",\"1\",\"30,292 K\"
\"python.exe\",\"12345\",\"Console\",\"1\",\"11,240 K\"
";
let names = port_watcher::parse_tasklist(tasks);
assert_eq!(names.get(&9921).map(String::as_str), Some("node.exe"));
assert_eq!(names.get(&12345).map(String::as_str), Some("python.exe"));
assert_eq!(names.get(&55), None);
}
#[test]
fn test_dependency_checking() {
let result =
crate::modules::dependency_checker::check_dependencies(&fixture("node_project"), &stack_node());
assert_eq!(result.check_name, "Dependencies");
assert_eq!(result.status, CheckStatus::Fail);
assert!(result.message.contains("node_modules"));
let none = crate::modules::dependency_checker::check_dependencies(
&fixture("unknown_project"),
&ProjectStack::Unknown,
);
assert_eq!(none.status, CheckStatus::Pass);
}
#[test]
fn test_health_score_calculation() {
use crate::models::HealthStatus;
let results = vec![
DiagnosticResult::new("Runtime Check", CheckStatus::Pass, "found"),
DiagnosticResult::new("Dependencies", CheckStatus::Pass, "ok"),
DiagnosticResult::new("Env Audit", CheckStatus::Warn, ".env.example only"),
DiagnosticResult::new("Port Scan", CheckStatus::Fail, "Port 3000 in use"),
];
let score = HealthScore::from_results(&results);
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());
assert!(score.recompute().validate().is_ok());
}
#[test]
fn test_diagnostics_parallelization() {
use std::time::{Duration as StdDuration, Instant};
let checks = vec![
NamedCheck::single("Speed A", || {
std::thread::sleep(StdDuration::from_millis(150));
DiagnosticResult::new("Speed A", CheckStatus::Pass, "fast")
}),
NamedCheck::single("Speed B", || {
std::thread::sleep(StdDuration::from_millis(150));
DiagnosticResult::new("Speed B", CheckStatus::Warn, "warn")
}),
NamedCheck::single("Speed C", || {
DiagnosticResult::new("Speed C", CheckStatus::Fail, "fail")
}),
];
let start = Instant::now();
let results = run_checks_parallel_with_timeout(checks, StdDuration::from_secs(5));
let elapsed = start.elapsed();
assert_eq!(results.len(), 3);
let names: Vec<&str> = results.iter().map(|r| r.check_name.as_str()).collect();
assert!(names.contains(&"Speed A"));
assert!(names.contains(&"Speed B"));
assert!(names.contains(&"Speed C"));
assert!(
elapsed < StdDuration::from_millis(275),
"checks should overlap, took {elapsed:?}"
);
}
}