Skip to main content

limitless_cli/modules/
diagnostics.rs

1//! Deep developer-environment diagnostics for `limit dev`.
2//!
3//! Inspects PATH hygiene, key environment variables, installed dev tools,
4//! stack-specific context (virtualenvs, Cargo home, lock files) and commonly
5//! used dev ports, then folds everything into a single [`EnvironmentState`]
6//! snapshot with a [`HealthScore`] and beginner-friendly [`MentorMessage`]s.
7
8use colored::{ColoredString, Colorize};
9use std::env;
10use std::path::{Path, PathBuf};
11use std::process::Command;
12use std::sync::{Arc, Mutex};
13use std::time::Duration;
14
15use crate::models::{
16    CheckStatus, DiagnosticResult, EnvironmentState, HealthScore, MentorMessage, ProjectStack,
17    Severity,
18};
19use crate::modules::port_watcher;
20use crate::modules::runtime_validator::{validate_installed_runtime, VersionReport};
21use crate::modules::stack_detector::detect_stack;
22
23// ---------------------------------------------------------------------------
24// PATH analysis
25// ---------------------------------------------------------------------------
26
27/// The separator the current platform uses to join PATH entries.
28pub fn path_separator() -> char {
29    if cfg!(windows) {
30        ';'
31    } else {
32        ':'
33    }
34}
35
36/// Expands a `%VAR%` reference inside a PATH entry (Windows style).
37///
38/// Entries without a `%NAME%` pair are returned unchanged.
39pub fn expand_windows_var(entry: &str) -> PathBuf {
40    if let Some(start) = entry.find('%') {
41        if let Some(end) = entry[start + 1..].find('%') {
42            let end = start + 1 + end;
43            if end > start + 1 {
44                let name = &entry[start + 1..end];
45                if let Ok(value) = env::var(name) {
46                    return PathBuf::from(format!(
47                        "{}{}{}",
48                        &entry[..start],
49                        value,
50                        &entry[end + 1..]
51                    ));
52                }
53            }
54        }
55    }
56    PathBuf::from(entry)
57}
58
59/// Resolves a raw PATH entry into the filesystem path it refers to.
60pub fn resolve_path_entry(entry: &str) -> PathBuf {
61    expand_windows_var(entry)
62}
63
64/// The result of analysing a raw PATH string.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct PathReport {
67    /// Number of tokens after splitting, empty ones included.
68    pub total_entries: usize,
69    /// How many tokens were empty (e.g. a leading/trailing separator).
70    pub empty_entries: usize,
71    /// Raw entries that resolve to folders which do not exist.
72    pub broken_entries: Vec<String>,
73    /// Resolved folders that appear on PATH more than once (deduplicated).
74    pub duplicate_entries: Vec<PathBuf>,
75    /// Whether the special `.` (current directory) entry is present.
76    pub has_current_dir: bool,
77}
78
79/// Splits and validates a raw PATH string.
80///
81/// Empty entries are counted but skipped for further checks. Broken and
82/// duplicate entries are reported separately so the UI can explain each.
83pub fn analyze_path(raw: &str) -> PathReport {
84    let sep = path_separator();
85    let tokens: Vec<&str> = raw.split(sep).collect();
86    let total_entries = tokens.len();
87
88    let mut broken_entries = Vec::new();
89    let mut duplicates = Vec::new();
90    let mut seen: Vec<PathBuf> = Vec::new();
91    let mut empty_entries = 0;
92    let mut has_current_dir = false;
93
94    for token in tokens {
95        let trimmed = token.trim();
96        if trimmed.is_empty() {
97            empty_entries += 1;
98            continue;
99        }
100        if trimmed == "." {
101            has_current_dir = true;
102        }
103        let resolved = resolve_path_entry(trimmed);
104        if !resolved.is_dir() {
105            broken_entries.push(trimmed.to_string());
106            continue;
107        }
108        if seen.contains(&resolved) {
109            if !duplicates.contains(&resolved) {
110                duplicates.push(resolved);
111            }
112        } else {
113            seen.push(resolved);
114        }
115    }
116
117    PathReport {
118        total_entries,
119        empty_entries,
120        broken_entries,
121        duplicate_entries: duplicates,
122        has_current_dir,
123    }
124}
125
126// ---------------------------------------------------------------------------
127// Environment variable inspection
128// ---------------------------------------------------------------------------
129
130/// Looks up the first of two variable names (Windows name first).
131pub fn resolve_var(primary: &str, alt: &str) -> Option<String> {
132    env::var(primary).ok().or_else(|| env::var(alt).ok())
133}
134
135/// Passes through the raw `PATH` value of the current process, if any.
136fn raw_path() -> Result<String, CheckStatus> {
137    match env::var("PATH") {
138        Ok(raw) if !raw.trim().is_empty() => Ok(raw),
139        Ok(_) => Err(CheckStatus::Fail),
140        Err(_) => Err(CheckStatus::Fail),
141    }
142}
143
144/// Checks that `PATH` is set and reports hygiene problems in separate
145/// diagnostics (broken entries, duplicates, current-directory entry).
146pub fn path_checks() -> Vec<DiagnosticResult> {
147    let raw = match raw_path() {
148        Ok(raw) => raw,
149        Err(_) => {
150            return vec![DiagnosticResult::new(
151                "PATH set",
152                CheckStatus::Fail,
153                "PATH is not set",
154            )];
155        }
156    };
157
158    let report = analyze_path(&raw);
159    let mut out = vec![DiagnosticResult::new(
160        "PATH set",
161        CheckStatus::Pass,
162        format!("{} entries on PATH", report.total_entries),
163    )];
164
165    if !report.broken_entries.is_empty() {
166        out.push(
167            DiagnosticResult::new(
168                "Broken PATH entries",
169                CheckStatus::Warn,
170                format!(
171                    "{} entries point to folders that do not exist",
172                    report.broken_entries.len()
173                ),
174            )
175            .with_remediation(format!(
176                "Remove or fix: {}",
177                report.broken_entries.join(", ")
178            )),
179        );
180    }
181
182    if !report.duplicate_entries.is_empty() {
183        out.push(
184            DiagnosticResult::new(
185                "Duplicate PATH entries",
186                CheckStatus::Warn,
187                format!(
188                    "{} folders are listed more than once",
189                    report.duplicate_entries.len()
190                ),
191            )
192            .with_remediation("Remove the duplicated folders from your PATH"),
193        );
194    }
195
196    if report.has_current_dir && cfg!(windows) {
197        out.push(
198            DiagnosticResult::new(
199                "PATH current directory",
200                CheckStatus::Warn,
201                "PATH contains the '.' entry; programs in the current folder can run by accident",
202            )
203            .with_remediation("Remove the '.' entry from PATH on Windows"),
204        );
205    }
206
207    out
208}
209
210/// Checks that the user home directory is set and actually exists.
211pub fn check_home() -> DiagnosticResult {
212    match resolve_var("USERPROFILE", "HOME") {
213        Some(home) if Path::new(&home).is_dir() => DiagnosticResult::new(
214            "Home directory",
215            CheckStatus::Pass,
216            format!("{home} exists"),
217        ),
218        Some(home) => DiagnosticResult::new(
219            "Home directory",
220            CheckStatus::Warn,
221            format!("{home} is set but does not exist"),
222        ),
223        None => DiagnosticResult::new(
224            "Home directory",
225            CheckStatus::Fail,
226            "HOME/USERPROFILE is not set",
227        ),
228    }
229}
230
231/// Checks that an editor is configured.
232pub fn check_editor() -> DiagnosticResult {
233    match resolve_var("EDITOR", "VISUAL") {
234        Some(editor) if !editor.trim().is_empty() => DiagnosticResult::new(
235            "Editor",
236            CheckStatus::Pass,
237            format!("EDITOR is set to {editor}"),
238        ),
239        _ => DiagnosticResult::new(
240            "Editor",
241            CheckStatus::Warn,
242            "EDITOR/VISUAL is not set; tools may fall back to a default editor",
243        )
244        .with_remediation("Set EDITOR, e.g. export EDITOR=\"code --wait\""),
245    }
246}
247
248/// Classifies a pair of proxy variables into a status plus a message.
249///
250/// `None` means the variable is unset. The two values are passed in so the
251/// classification can be unit-tested without touching the real environment.
252pub fn proxy_consistency(
253    http: Option<String>,
254    https: Option<String>,
255) -> (CheckStatus, &'static str) {
256    match (http, https) {
257        (Some(_), Some(_)) => (CheckStatus::Pass, "HTTP_PROXY and HTTPS_PROXY are both set"),
258        (Some(_), None) => (
259            CheckStatus::Warn,
260            "HTTP_PROXY is set but HTTPS_PROXY is missing",
261        ),
262        (None, Some(_)) => (
263            CheckStatus::Warn,
264            "HTTPS_PROXY is set but HTTP_PROXY is missing",
265        ),
266        (None, None) => (CheckStatus::Pass, "no proxy variables set"),
267    }
268}
269
270/// Reads the real proxy variables and reports their consistency.
271pub fn check_proxy() -> DiagnosticResult {
272    let http = env::var("HTTP_PROXY")
273        .ok()
274        .or_else(|| env::var("http_proxy").ok());
275    let https = env::var("HTTPS_PROXY")
276        .ok()
277        .or_else(|| env::var("https_proxy").ok());
278    let (status, message) = proxy_consistency(http, https);
279    DiagnosticResult::new("Proxy consistency", status, message)
280}
281
282// ---------------------------------------------------------------------------
283// Installed dev tools
284// ---------------------------------------------------------------------------
285
286/// `(command, version flag)` pairs probed by the diagnostics.
287pub const CORE_TOOLS: &[(&str, &str)] = &[
288    ("rustc", "--version"),
289    ("cargo", "--version"),
290    ("node", "--version"),
291    ("npm", "--version"),
292    ("python", "--version"),
293    ("go", "version"),
294    ("java", "-version"),
295];
296
297/// Runs `tool --version` and returns the first non-empty output line.
298pub fn probe_tool(name: &str, flag: &str) -> Option<String> {
299    let exec_name = if cfg!(windows) && matches!(name, "npm" | "yarn" | "pnpm" | "npx") {
300        format!("{name}.cmd")
301    } else {
302        name.to_string()
303    };
304    let output = Command::new(&exec_name).arg(flag).output().ok()?;
305    let stdout = String::from_utf8_lossy(&output.stdout);
306    let stderr = String::from_utf8_lossy(&output.stderr);
307    let version = stdout
308        .trim()
309        .lines()
310        .next()
311        .or_else(|| stderr.trim().lines().next())?;
312    if version.is_empty() {
313        None
314    } else {
315        Some(version.to_string())
316    }
317}
318
319/// One diagnostic per core tool: `Pass` when found, `Fail` when missing.
320pub fn tools_on_path() -> Vec<DiagnosticResult> {
321    CORE_TOOLS
322        .iter()
323        .map(|(name, flag)| match probe_tool(name, flag) {
324            Some(version) => DiagnosticResult::new(
325                format!("Tool {name}"),
326                CheckStatus::Pass,
327                format!("{name} {version}"),
328            ),
329            None => DiagnosticResult::new(
330                format!("Tool {name}"),
331                CheckStatus::Fail,
332                format!("{name} was not found on PATH"),
333            )
334            .with_remediation(format!("Install {name} and add it to PATH")),
335        })
336        .collect()
337}
338
339// ---------------------------------------------------------------------------
340// Stack-specific context
341// ---------------------------------------------------------------------------
342
343/// Checks environment context that only matters for a given stack.
344pub fn stack_context_checks(stack: &ProjectStack) -> Vec<DiagnosticResult> {
345    match stack {
346        ProjectStack::Python { .. } => match env::var("VIRTUAL_ENV") {
347            Ok(path) => vec![DiagnosticResult::new(
348                "Python virtualenv",
349                CheckStatus::Pass,
350                format!("active virtualenv at {path}"),
351            )],
352            Err(_) => vec![DiagnosticResult::new(
353                "Python virtualenv",
354                CheckStatus::Warn,
355                "no virtualenv is active",
356            )
357            .with_remediation("python -m venv .venv && .venv\\Scripts\\activate")],
358        },
359        ProjectStack::Rust { .. } => match env::var("CARGO_HOME") {
360            Ok(home) => vec![DiagnosticResult::new(
361                "Cargo home",
362                CheckStatus::Pass,
363                format!("CARGO_HOME = {home}"),
364            )],
365            Err(_) => vec![DiagnosticResult::new(
366                "Cargo home",
367                CheckStatus::Pass,
368                "CARGO_HOME unset (defaults to ~/.cargo)",
369            )],
370        },
371        _ => Vec::new(),
372    }
373}
374
375// ---------------------------------------------------------------------------
376// Development ports
377// ---------------------------------------------------------------------------
378
379/// Ports monitored by `limit dev` (superset of the common dev ports,
380/// including databases commonly found in local environments).
381const DIAGNOSTIC_PORTS: &[u16] = &[3000, 3001, 5173, 5432, 8000, 8080, 8081, 27017];
382
383// ---------------------------------------------------------------------------
384// Dependency audit
385// ---------------------------------------------------------------------------
386
387/// Lock files that pin dependency versions, per stack.
388fn lock_files_for(stack: &ProjectStack) -> &'static [&'static str] {
389    match stack {
390        ProjectStack::Node { .. } => &["package-lock.json", "yarn.lock", "pnpm-lock.yaml"],
391        ProjectStack::Python { .. } => &["Pipfile.lock", "poetry.lock", "uv.lock"],
392        ProjectStack::Rust { .. } => &["Cargo.lock"],
393        _ => &[],
394    }
395}
396
397/// Checks that the project manifest exists and that dependencies are pinned
398/// by a lock file.
399pub fn dependency_audit(repo_root: &str, stack: &ProjectStack) -> DiagnosticResult {
400    if lock_files_for(stack).is_empty() {
401        return DiagnosticResult::new(
402            "Dependency audit",
403            CheckStatus::Pass,
404            "no dependency audit needed for this stack",
405        );
406    }
407
408    let root = Path::new(repo_root);
409    let manifest = match stack {
410        ProjectStack::Node { .. } => "package.json",
411        ProjectStack::Python { .. } => "pyproject.toml",
412        ProjectStack::Rust { .. } => "Cargo.toml",
413        _ => unreachable!(),
414    };
415
416    if !root.join(manifest).is_file() {
417        return DiagnosticResult::new(
418            "Dependency audit",
419            CheckStatus::Fail,
420            format!("{manifest} is missing"),
421        )
422        .with_remediation(format!(
423            "Run the initialiser for your stack to create {manifest}"
424        ));
425    }
426
427    let has_lock = lock_files_for(stack)
428        .iter()
429        .any(|lock| root.join(lock).is_file());
430
431    if has_lock {
432        DiagnosticResult::new(
433            "Dependency audit",
434            CheckStatus::Pass,
435            "manifest and lock file are present",
436        )
437    } else {
438        DiagnosticResult::new(
439            "Dependency audit",
440            CheckStatus::Warn,
441            "manifest exists but no lock file is committed",
442        )
443        .with_remediation(
444            "Generate and commit a lock file (e.g. npm install for Node, poetry lock for Python)",
445        )
446    }
447}
448
449// ---------------------------------------------------------------------------
450// Collection and snapshot
451// ---------------------------------------------------------------------------
452
453/// Runs every diagnostic and returns the full list.
454pub fn collect_diagnostics(repo_root: &str) -> Vec<DiagnosticResult> {
455    let stack = detect_stack(repo_root);
456    let mut results = Vec::new();
457    results.extend(path_checks());
458    results.push(check_home());
459    results.push(check_editor());
460    results.push(check_proxy());
461    results.extend(tools_on_path());
462    results.extend(stack_context_checks(&stack));
463    results.push(dependency_audit(repo_root, &stack));
464    results.extend(port_watcher::blocked_port_results(DIAGNOSTIC_PORTS));
465    results
466}
467
468/// Builds a full [`EnvironmentState`] snapshot for a repository root.
469///
470/// Delegates to [`run_full_diagnostics`] so every check runs in parallel with
471/// a per-check timeout.
472///
473/// ```
474/// use limitless_cli::modules::diagnostics::build_snapshot;
475///
476/// let state = build_snapshot(env!("CARGO_MANIFEST_DIR"));
477/// assert!(!state.diagnostics.is_empty());
478/// assert!(state.health_score.validate().is_ok());
479/// ```
480pub fn build_snapshot(repo_root: &str) -> EnvironmentState {
481    run_full_diagnostics(repo_root)
482}
483
484// ---------------------------------------------------------------------------
485// Mentor guidance
486// ---------------------------------------------------------------------------
487
488/// Builds mentor guidance for all non-passing diagnostics, critical first.
489///
490/// Delegates each translation to the [`translator`](crate::modules::translator)
491/// database so the advice stays beginner-friendly and actionable.
492pub fn mentor_messages(results: &[DiagnosticResult]) -> Vec<MentorMessage> {
493    let mut messages: Vec<MentorMessage> = results
494        .iter()
495        .filter(|d| d.status != CheckStatus::Pass)
496        .map(crate::modules::translator::translate_error)
497        .collect();
498    messages.sort_by_key(|m| match m.severity {
499        Severity::Critical => 0,
500        Severity::Warning => 1,
501        Severity::Info => 2,
502    });
503    messages
504}
505
506// ---------------------------------------------------------------------------
507// Parallel orchestration
508// ---------------------------------------------------------------------------
509
510/// Per-check timeout applied inside [`run_checks_parallel`].
511pub const CHECK_TIMEOUT: Duration = Duration::from_secs(5);
512
513/// A single named check that can be scheduled on a worker thread.
514///
515/// The `run` closure must be plain and blocking; the parallel engine wraps it
516/// in a timeout and turns crashes or hangs into a [`CheckStatus::Fail`]
517/// diagnostic instead of propagating them.
518pub struct NamedCheck {
519    /// Display name, used for timeout/crash diagnostics.
520    pub name: &'static str,
521    /// The blocking check to run. May return zero or more diagnostics.
522    pub run: Box<dyn FnOnce() -> Vec<DiagnosticResult> + Send + 'static>,
523}
524
525impl NamedCheck {
526    /// Wraps a single-result check into a [`NamedCheck`].
527    pub fn single(
528        name: &'static str,
529        run: impl FnOnce() -> DiagnosticResult + Send + 'static,
530    ) -> Self {
531        Self {
532            name,
533            run: Box::new(move || vec![run()]),
534        }
535    }
536}
537
538/// Runs one check on a blocking thread under a timeout. A timed-out or
539/// panicking check becomes a single `Fail` diagnostic; a cancelled one
540/// produces nothing.
541async fn guarded_check(
542    name: &'static str,
543    timeout: Duration,
544    run: Box<dyn FnOnce() -> Vec<DiagnosticResult> + Send + 'static>,
545) -> Vec<DiagnosticResult> {
546    match tokio::time::timeout(timeout, tokio::task::spawn_blocking(run)).await {
547        Ok(Ok(results)) => results,
548        Ok(Err(error)) => {
549            vec![DiagnosticResult::new(
550                name,
551                CheckStatus::Fail,
552                format!("{name} check crashed: {error}"),
553            )
554            .with_remediation("Retry the diagnostic run")]
555        }
556        Err(_) => {
557            vec![DiagnosticResult::new(
558                name,
559                CheckStatus::Fail,
560                format!("{name} check timed out after {}s", timeout.as_secs()),
561            )
562            .with_remediation("Retry the diagnostic run")]
563        }
564    }
565}
566
567/// Runs a collection of blocking checks in parallel with a per-check timeout.
568///
569/// Every check is scheduled on a worker thread; results are collected
570/// asynchronously as they finish. Individual failures never abort the batch:
571/// a check that panics or exceeds the timeout contributes a single
572/// [`CheckStatus::Fail`] diagnostic instead.
573///
574/// The order of the returned diagnostics is non-deterministic (checks finish
575/// at different times), so callers must not rely on the vector being sorted.
576///
577/// ```
578/// use limitless_cli::models::CheckStatus;
579/// use limitless_cli::modules::diagnostics::{NamedCheck, run_checks_parallel};
580///
581/// let checks = vec![
582///     NamedCheck::single("Passing", || {
583///         limitless_cli::models::DiagnosticResult::new(
584///             "Passing",
585///             CheckStatus::Pass,
586///             "all good",
587///         )
588///     }),
589/// ];
590/// let results = run_checks_parallel(checks);
591/// assert_eq!(results.len(), 1);
592/// assert!(results[0].is_pass());
593/// ```
594pub fn run_checks_parallel(checks: Vec<NamedCheck>) -> Vec<DiagnosticResult> {
595    run_checks_parallel_with_timeout(checks, CHECK_TIMEOUT)
596}
597
598/// Like [`run_checks_parallel`] but with an explicit timeout (used by tests).
599fn run_checks_parallel_with_timeout(
600    checks: Vec<NamedCheck>,
601    timeout: Duration,
602) -> Vec<DiagnosticResult> {
603    if checks.is_empty() {
604        return Vec::new();
605    }
606
607    std::thread::spawn(move || {
608        let runtime = tokio::runtime::Builder::new_multi_thread()
609            .enable_all()
610            .build()
611            .expect("build diagnostics runtime");
612
613        runtime.block_on(async move {
614            let mut batch = tokio::task::JoinSet::new();
615            for check in checks {
616                batch.spawn(guarded_check(check.name, timeout, check.run));
617            }
618
619            let mut results = Vec::new();
620            while let Some(joined) = batch.join_next().await {
621                match joined {
622                    Ok(per_check) => results.extend(per_check),
623                    Err(error) if error.is_panic() => results.push(
624                        DiagnosticResult::new(
625                            "Parallel check",
626                            CheckStatus::Fail,
627                            format!("a parallel check panicked: {error}"),
628                        )
629                        .with_remediation("Retry the diagnostic run"),
630                    ),
631                    Err(_) => { /* cancelled tasks contribute nothing */ }
632                }
633            }
634            results
635        })
636    })
637    .join()
638    .unwrap_or_else(|_| {
639        vec![DiagnosticResult::new(
640            "Parallel check",
641            CheckStatus::Fail,
642            "the diagnostics runtime crashed before running checks",
643        )]
644    })
645}
646
647/// Converts a [`VersionReport`] into a [`DiagnosticResult`].
648fn version_report_to_diagnostic(report: VersionReport) -> DiagnosticResult {
649    let mut diagnostic = DiagnosticResult::new("Runtime Check", report.status, report.message);
650    if let Some(remediation) = report.remediation {
651        diagnostic.remediation = Some(remediation);
652    }
653    diagnostic
654}
655
656/// Runs *all* checks in parallel and folds them into a full
657/// [`EnvironmentState`].
658///
659/// # Orchestration
660///
661/// 1. The stack is detected **first** (blocking) because every per-stack
662///    check depends on it.
663/// 2. Every check is scheduled concurrently on a worker thread: runtime
664///    validation, env-file audit, port scan, dependency health, PATH
665///    hygiene, installed tools, home/editor/proxy and stack context.
666/// 3. Each check runs under a [`CHECK_TIMEOUT`] (5 s); a timeout or crash is
667///    aggregated as a `Fail` diagnostic rather than aborting the batch.
668/// 4. A [`HealthScore`] is recomputed from the collected diagnostics so the
669///    returned state is always consistent.
670///
671/// Side-effect state (`runtime_version`, `blocked_ports`) is gathered from
672/// the check worker threads, and `dependencies_healthy` mirrors the
673/// "Dependency audit" check (manifest + lock file present).
674///
675/// ```
676/// use limitless_cli::modules::diagnostics::run_full_diagnostics;
677///
678/// let state = run_full_diagnostics(env!("CARGO_MANIFEST_DIR"));
679/// assert!(!state.diagnostics.is_empty());
680/// assert_eq!(state.health_score.total_checks, state.diagnostics.len() as u32);
681/// assert!(state.health_score.validate().is_ok());
682/// ```
683pub fn run_full_diagnostics(repo_path: &str) -> EnvironmentState {
684    // Blocking step: the stack drives every downstream check.
685    let stack = detect_stack(repo_path);
686
687    let runtime_version = Arc::new(Mutex::new(None));
688    let blocked_ports = Arc::new(Mutex::new(Vec::new()));
689
690    let runtime_repo = repo_path.to_string();
691    let runtime_slot = Arc::clone(&runtime_version);
692    let env_repo = repo_path.to_string();
693    let deps_repo = repo_path.to_string();
694    let deps_stack = stack.clone();
695    let ports_slot = Arc::clone(&blocked_ports);
696    let audit_repo = repo_path.to_string();
697    let audit_stack = stack.clone();
698    let context_stack = stack.clone();
699
700    let checks = vec![
701        NamedCheck {
702            name: "Runtime Check",
703            run: Box::new(move || {
704                let mut results = Vec::new();
705                if let Some(report) = validate_installed_runtime(&runtime_repo) {
706                    *runtime_slot.lock().expect("runtime slot") =
707                        Some(report.actual_version.clone());
708                    results.push(version_report_to_diagnostic(report));
709                } else {
710                    results.push(DiagnosticResult::new(
711                        "Runtime Check",
712                        CheckStatus::Pass,
713                        "no runtime version to validate for this stack",
714                    ));
715                }
716                results
717            }),
718        },
719        NamedCheck::single("Env Audit", move || {
720            crate::modules::env_auditor::audit_env_files(&env_repo)
721        }),
722        NamedCheck::single("Dependencies", move || {
723            crate::modules::dependency_checker::check_dependencies(&deps_repo, &deps_stack)
724        }),
725        NamedCheck {
726            name: "Port Scan",
727            run: Box::new(move || {
728                let found = port_watcher::check_blocked_ports(DIAGNOSTIC_PORTS);
729                let mut results = Vec::new();
730                for (port, pid, process) in &found {
731                    ports_slot.lock().expect("ports slot").push((*port, *pid));
732                    results.push(port_watcher::diagnostic_for(*port, *pid, process));
733                }
734                if results.is_empty() {
735                    results.push(DiagnosticResult::new(
736                        "Port Scan",
737                        CheckStatus::Pass,
738                        "no common development ports are in use",
739                    ));
740                }
741                results
742            }),
743        },
744        NamedCheck::single("Dependency audit", move || {
745            dependency_audit(&audit_repo, &audit_stack)
746        }),
747        NamedCheck {
748            name: "PATH",
749            run: Box::new(path_checks),
750        },
751        NamedCheck {
752            name: "Tools",
753            run: Box::new(tools_on_path),
754        },
755        NamedCheck::single("Home directory", check_home),
756        NamedCheck::single("Editor", check_editor),
757        NamedCheck::single("Proxy consistency", check_proxy),
758        NamedCheck {
759            name: "Stack context",
760            run: Box::new(move || stack_context_checks(&context_stack)),
761        },
762    ];
763
764    let diagnostics = run_checks_parallel(checks);
765
766    let dependencies_healthy = diagnostics
767        .iter()
768        .any(|d| d.check_name == "Dependency audit" && d.is_pass());
769
770    let root = Path::new(repo_path);
771    let mut state = EnvironmentState {
772        detected_stack: stack,
773        runtime_version: runtime_version.lock().expect("runtime slot").clone(),
774        env_file_exists: root.join(".env").is_file(),
775        env_example_exists: root.join(".env.example").is_file(),
776        dependencies_healthy,
777        blocked_ports: blocked_ports.lock().expect("ports slot").clone(),
778        diagnostics,
779        health_score: HealthScore::default(),
780    };
781    state.refresh_health();
782    state
783}
784
785// ---------------------------------------------------------------------------
786// Rendering helpers
787// ---------------------------------------------------------------------------
788
789fn status_icon(status: CheckStatus) -> ColoredString {
790    match status {
791        CheckStatus::Pass => "PASS".green().bold(),
792        CheckStatus::Warn => "WARN".yellow().bold(),
793        CheckStatus::Fail => "FAIL".red().bold(),
794    }
795}
796
797/// Renders a 20-cell proportional health bar.
798fn health_bar(score: &HealthScore) -> String {
799    let filled = (score.percentage as usize / 5).min(20);
800    let bar = format!("{}{}", "#".repeat(filled), ".".repeat(20 - filled));
801    match score.overall_status {
802        crate::models::HealthStatus::Healthy => bar.green().to_string(),
803        crate::models::HealthStatus::Caution => bar.yellow().to_string(),
804        crate::models::HealthStatus::Critical => bar.red().to_string(),
805    }
806}
807
808fn show_env_var(label: &str, value: impl AsRef<str>) {
809    println!(
810        "  {} {}",
811        format!("{label}:").bold(),
812        value.as_ref().dimmed()
813    );
814}
815
816// ---------------------------------------------------------------------------
817// Entry point
818// ---------------------------------------------------------------------------
819
820/// Runs the full developer-environment inspection for `limit dev`.
821pub fn run_dev() {
822    let state = build_snapshot(".");
823
824    println!(
825        "{}",
826        "=== Developer Environment Diagnostics ===".bold().cyan()
827    );
828
829    if let Some(runtime) = &state.runtime_version {
830        println!("  {} {}", "Runtime:".bold(), runtime);
831    }
832
833    println!();
834    let path_value = env::var("PATH").unwrap_or_default();
835    let path_report = analyze_path(&path_value);
836    println!(
837        "  {} ({})",
838        "PATH summary:".bold(),
839        path_report.total_entries
840    );
841    if path_report.broken_entries.is_empty() && path_report.duplicate_entries.is_empty() {
842        println!("  {} ", "  no broken or duplicate entries".dimmed());
843    } else {
844        if !path_report.broken_entries.is_empty() {
845            println!(
846                "  {} {}",
847                format!("{} broken entries", path_report.broken_entries.len())
848                    .red()
849                    .bold(),
850                "(point to missing folders)".dimmed()
851            );
852        }
853        if !path_report.duplicate_entries.is_empty() {
854            println!(
855                "  {} {}",
856                format!("{} duplicates", path_report.duplicate_entries.len())
857                    .yellow()
858                    .bold(),
859                "(same folder listed twice)".dimmed()
860            );
861        }
862    }
863
864    println!();
865    println!("  {} {}", "Stack:".bold(), state.detected_stack.label());
866    println!(
867        "  {} {}",
868        "Env files:".bold(),
869        match (state.env_file_exists, state.env_example_exists) {
870            (true, true) => ".env and .env.example found".green().to_string(),
871            (true, false) => ".env found (no .env.example)".yellow().to_string(),
872            (false, true) => ".env.example found (no .env)".yellow().to_string(),
873            (false, false) => "none found".red().to_string(),
874        }
875    );
876    if !state.blocked_ports.is_empty() {
877        println!(
878            "  {} {}",
879            "Blocked ports:".red().bold(),
880            state
881                .blocked_ports
882                .iter()
883                .map(|(port, pid)| format!("{port} (pid {pid})"))
884                .collect::<Vec<_>>()
885                .join(", ")
886        );
887    }
888
889    println!();
890    show_env_var(
891        "HOME",
892        resolve_var("USERPROFILE", "HOME").unwrap_or_default(),
893    );
894    show_env_var("SHELL", resolve_var("SHELL", "COMSPEC").unwrap_or_default());
895    show_env_var(
896        "EDITOR",
897        resolve_var("EDITOR", "VISUAL").unwrap_or_default(),
898    );
899    show_env_var(
900        "LANG",
901        env::var("LANG")
902            .unwrap_or_else(|_| env::var("LC_ALL").unwrap_or_else(|_| "not set".into())),
903    );
904
905    println!();
906    println!("{}", "Checks:".bold());
907    for result in &state.diagnostics {
908        println!(
909            "  {} {}",
910            status_icon(result.status),
911            format!("{} — {}", result.check_name, result.message).dimmed()
912        );
913        if let Some(remediation) = &result.remediation {
914            println!("  {} {}", "      Fix:".cyan().bold(), remediation.dimmed());
915        }
916    }
917
918    println!();
919    let score = &state.health_score;
920    println!(
921        "  {} {} {:?} ({}%)",
922        "Health:".bold(),
923        health_bar(score),
924        score.overall_status,
925        score.percentage
926    );
927    println!(
928        "  {} of {} checks passed ({} warnings, {} failed)",
929        score.passed, score.total_checks, score.warnings, score.failed
930    );
931
932    let mentors = mentor_messages(&state.diagnostics);
933    if !mentors.is_empty() {
934        println!();
935        println!("{}", "Mentor advice:".bold());
936        for message in &mentors {
937            println!(
938                "{}",
939                crate::modules::message_formatter::format_mentor_message(message)
940            );
941        }
942    }
943
944    println!();
945    if state.ready_for_dev() {
946        println!(
947            "  {} {}",
948            "Ready for development:".bold().green(),
949            "yes".green().bold()
950        );
951    } else {
952        println!(
953            "  {} {}",
954            "Ready for development:".bold().yellow(),
955            "no".yellow().bold()
956        );
957    }
958    println!();
959    println!("{}", "Dev diagnostics complete!".green().bold());
960}
961
962#[cfg(test)]
963mod tests {
964    use super::*;
965    use std::fs;
966    use std::time::{SystemTime, UNIX_EPOCH};
967
968    /// A self-cleaning temporary directory.
969    struct TempDir {
970        path: PathBuf,
971    }
972
973    impl TempDir {
974        fn new(label: &str) -> Self {
975            let stamp = SystemTime::now()
976                .duration_since(UNIX_EPOCH)
977                .expect("system clock")
978                .as_nanos();
979            let path = std::env::temp_dir().join(format!("limitless_diag_{label}_{stamp}"));
980            fs::create_dir_all(&path).expect("create temp dir");
981            TempDir { path }
982        }
983
984        fn path(&self) -> &Path {
985            &self.path
986        }
987
988        fn write(self, relative: &str, content: &str) -> Self {
989            let full = self.path.join(relative);
990            if let Some(parent) = full.parent() {
991                fs::create_dir_all(parent).expect("create parent dirs");
992            }
993            fs::write(full, content).expect("write fixture file");
994            self
995        }
996    }
997
998    impl Drop for TempDir {
999        fn drop(&mut self) {
1000            let _ = fs::remove_dir_all(&self.path);
1001        }
1002    }
1003
1004    // --- PATH analysis ----------------------------------------------------
1005
1006    #[test]
1007    fn analyze_path_reports_broken_duplicate_and_current_dir() {
1008        let one = TempDir::new("dir_one");
1009        let two = TempDir::new("dir_two");
1010        let sep = path_separator();
1011        let raw = format!(
1012            "{}{sep}{}{sep}{}{sep}.{sep}missing_folder_xyz",
1013            one.path().display(),
1014            two.path().display(),
1015            two.path().display()
1016        );
1017
1018        let report = analyze_path(&raw);
1019
1020        assert_eq!(report.total_entries, 5);
1021        assert_eq!(report.empty_entries, 0);
1022        assert!(report.has_current_dir);
1023        assert_eq!(
1024            report.broken_entries,
1025            vec!["missing_folder_xyz".to_string()]
1026        );
1027        assert_eq!(report.duplicate_entries, vec![two.path().to_path_buf()]);
1028    }
1029
1030    #[test]
1031    fn analyze_path_counts_empty_entries() {
1032        let sep = path_separator();
1033        let raw = format!("{sep}{sep}");
1034
1035        let report = analyze_path(&raw);
1036
1037        assert_eq!(report.total_entries, 3);
1038        assert_eq!(report.empty_entries, 3);
1039        assert!(report.broken_entries.is_empty());
1040    }
1041
1042    #[test]
1043    fn analyze_path_clean_path_has_no_problems() {
1044        let dir = TempDir::new("clean_dir");
1045        let report = analyze_path(&dir.path().to_string_lossy());
1046
1047        assert!(report.broken_entries.is_empty());
1048        assert!(report.duplicate_entries.is_empty());
1049        assert!(!report.has_current_dir);
1050    }
1051
1052    // --- Proxy consistency ------------------------------------------------
1053
1054    #[test]
1055    fn proxy_consistency_classifies_all_pairs() {
1056        assert_eq!(
1057            proxy_consistency(Some("http://proxy".into()), Some("http://proxy".into())).0,
1058            CheckStatus::Pass
1059        );
1060        assert_eq!(
1061            proxy_consistency(Some("http://proxy".into()), None).0,
1062            CheckStatus::Warn
1063        );
1064        assert_eq!(
1065            proxy_consistency(None, Some("http://proxy".into())).0,
1066            CheckStatus::Warn
1067        );
1068        assert_eq!(proxy_consistency(None, None).0, CheckStatus::Pass);
1069    }
1070
1071    // --- Port probing (delegates to port_watcher) --------------------------
1072
1073    #[test]
1074    fn is_port_in_use_returns_true_when_bound() {
1075        let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).expect("bind ephemeral port");
1076        let port = listener.local_addr().expect("local addr").port();
1077        assert!(port_watcher::is_port_in_use(port));
1078    }
1079
1080    #[test]
1081    fn is_port_in_use_returns_false_when_free() {
1082        let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).expect("bind ephemeral port");
1083        let port = listener.local_addr().expect("local addr").port();
1084        drop(listener);
1085        assert!(!port_watcher::is_port_in_use(port));
1086    }
1087
1088    // --- Dependency audit -------------------------------------------------
1089
1090    #[test]
1091    fn dependency_audit_node_with_lockfile_passes() {
1092        let dir = TempDir::new("node_locked")
1093            .write("package.json", r#"{ "name": "web" }"#)
1094            .write("package-lock.json", "{}");
1095        assert_eq!(
1096            dependency_audit(dir.path().to_str().unwrap(), &stack_node()).status,
1097            CheckStatus::Pass
1098        );
1099    }
1100
1101    #[test]
1102    fn dependency_audit_node_without_lockfile_warns() {
1103        let dir = TempDir::new("node_unlocked").write("package.json", r#"{ "name": "web" }"#);
1104        assert_eq!(
1105            dependency_audit(dir.path().to_str().unwrap(), &stack_node()).status,
1106            CheckStatus::Warn
1107        );
1108    }
1109
1110    #[test]
1111    fn dependency_audit_rust_with_lockfile_passes() {
1112        let dir = TempDir::new("rust_locked")
1113            .write(
1114                "Cargo.toml",
1115                "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n",
1116            )
1117            .write(
1118                "Cargo.lock",
1119                "# This file is automatically @generated by Cargo.",
1120            );
1121        assert_eq!(
1122            dependency_audit(dir.path().to_str().unwrap(), &stack_rust()).status,
1123            CheckStatus::Pass
1124        );
1125    }
1126
1127    #[test]
1128    fn dependency_audit_python_missing_manifest_fails() {
1129        let dir = TempDir::new("python_empty");
1130        assert_eq!(
1131            dependency_audit(dir.path().to_str().unwrap(), &stack_python()).status,
1132            CheckStatus::Fail
1133        );
1134    }
1135
1136    #[test]
1137    fn dependency_audit_unknown_stack_passes() {
1138        let dir = TempDir::new("unknown_stack");
1139        assert_eq!(
1140            dependency_audit(dir.path().to_str().unwrap(), &ProjectStack::Unknown).status,
1141            CheckStatus::Pass
1142        );
1143    }
1144
1145    // --- Snapshot integration ----------------------------------------------
1146
1147    #[test]
1148    fn build_snapshot_assembles_rust_project() {
1149        let dir = TempDir::new("snapshot_rust")
1150            .write(
1151                "Cargo.toml",
1152                "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n",
1153            )
1154            .write("Cargo.lock", "# lock");
1155
1156        let state = build_snapshot(dir.path().to_str().unwrap());
1157
1158        assert_eq!(state.detected_stack, stack_rust());
1159        assert!(state.runtime_version.is_some());
1160        assert!(state.dependencies_healthy);
1161        assert!(!state.diagnostics.is_empty());
1162        assert!(state.health_score.total_checks > 0);
1163        assert!(state.blocked_ports.is_empty() || !state.blocked_ports.is_empty());
1164        // `.env` files are required by `ready_for_dev`, and this fixture has none.
1165        assert!(!state.env_file_exists);
1166    }
1167
1168    #[test]
1169    fn mentor_messages_flatten_passes() {
1170        let results = vec![
1171            DiagnosticResult::new("PATH set", CheckStatus::Pass, "ok"),
1172            DiagnosticResult::new("Tool node", CheckStatus::Fail, "node was not found on PATH")
1173                .with_remediation("Install node via nvm"),
1174            DiagnosticResult::new(
1175                "Duplicate PATH entries",
1176                CheckStatus::Warn,
1177                "1 folder is listed more than once",
1178            ),
1179        ];
1180
1181        let messages = mentor_messages(&results);
1182
1183        assert_eq!(messages.len(), 2);
1184        assert_eq!(messages[0].severity, Severity::Critical);
1185        assert_eq!(messages[1].severity, Severity::Warning);
1186        assert!(messages[0].plain_english.contains("node"));
1187        assert_eq!(messages[0].suggested_action, "Install node via nvm");
1188    }
1189
1190    // --- Parallel orchestration ---------------------------------------------
1191
1192    #[test]
1193    fn run_checks_parallel_aggregates_mock_results() {
1194        let checks = vec![
1195            NamedCheck::single("Good", || {
1196                DiagnosticResult::new("P", CheckStatus::Pass, "ok")
1197            }),
1198            NamedCheck::single("Heads-up", || {
1199                DiagnosticResult::new("W", CheckStatus::Warn, "careful")
1200            }),
1201            NamedCheck::single("Broken", || {
1202                DiagnosticResult::new("F", CheckStatus::Fail, "boom")
1203            }),
1204        ];
1205
1206        let results = run_checks_parallel(checks);
1207
1208        assert_eq!(results.len(), 3);
1209        assert!(results.iter().any(|r| r.is_pass()));
1210        assert!(results.iter().any(|r| r.status == CheckStatus::Warn));
1211        assert!(results.iter().any(|r| r.status == CheckStatus::Fail));
1212    }
1213
1214    #[test]
1215    fn run_checks_parallel_runs_simultaneously() {
1216        let check = |name: &'static str, status: CheckStatus| {
1217            NamedCheck::single(name, move || {
1218                std::thread::sleep(std::time::Duration::from_millis(150));
1219                DiagnosticResult::new(name, status, "done")
1220            })
1221        };
1222        let checks = vec![check("A", CheckStatus::Pass), check("B", CheckStatus::Pass)];
1223
1224        let start = std::time::Instant::now();
1225        let results = run_checks_parallel(checks);
1226        let elapsed = start.elapsed();
1227
1228        assert_eq!(results.len(), 2);
1229        // Running serially the two 150 ms checks would take >= 300 ms.
1230        assert!(
1231            elapsed < std::time::Duration::from_millis(290),
1232            "checks ran serially: {elapsed:?}"
1233        );
1234    }
1235
1236    #[test]
1237    fn run_checks_parallel_times_out_slow_checks() {
1238        let checks = vec![NamedCheck {
1239            name: "Sleepy",
1240            run: Box::new(|| {
1241                std::thread::sleep(std::time::Duration::from_millis(200));
1242                vec![DiagnosticResult::new(
1243                    "Sleepy",
1244                    CheckStatus::Pass,
1245                    "too slow",
1246                )]
1247            }),
1248        }];
1249
1250        let results =
1251            run_checks_parallel_with_timeout(checks, std::time::Duration::from_millis(50));
1252
1253        assert_eq!(results.len(), 1);
1254        let timed_out = &results[0];
1255        assert_eq!(timed_out.check_name, "Sleepy");
1256        assert_eq!(timed_out.status, CheckStatus::Fail);
1257        assert!(timed_out.message.contains("timed out"));
1258    }
1259
1260    #[test]
1261    fn run_checks_parallel_aggregates_panics_as_fail() {
1262        let checks = vec![NamedCheck {
1263            name: "Boom",
1264            run: Box::new(|| panic!("mock check exploded")),
1265        }];
1266
1267        let results = run_checks_parallel(checks);
1268
1269        assert_eq!(results.len(), 1);
1270        assert_eq!(results[0].status, CheckStatus::Fail);
1271        assert!(results[0].message.contains("crashed"));
1272    }
1273
1274    #[test]
1275    fn run_checks_parallel_empty_batch_yields_nothing() {
1276        assert!(run_checks_parallel(Vec::new()).is_empty());
1277    }
1278
1279    #[test]
1280    fn run_full_diagnostics_returns_consistent_state() {
1281        let dir = TempDir::new("full_diag")
1282            .write(
1283                "Cargo.toml",
1284                "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n",
1285            )
1286            .write("Cargo.lock", "# lock");
1287
1288        let state = run_full_diagnostics(dir.path().to_str().unwrap());
1289
1290        assert_eq!(state.detected_stack, stack_rust());
1291        assert!(!state.diagnostics.is_empty());
1292        assert_eq!(
1293            state.health_score.total_checks,
1294            state.diagnostics.len() as u32
1295        );
1296        assert!(state.health_score.validate().is_ok());
1297        assert!(!state.blocked_ports.is_empty() || state.blocked_ports.is_empty());
1298        // The deep dependency check runs; the lock-file audit decides health.
1299        assert!(state.dependencies_healthy);
1300        assert!(state.runtime_version.is_some());
1301    }
1302
1303    fn stack_node() -> ProjectStack {
1304        ProjectStack::Node {
1305            version: String::new(),
1306            package_manager: "npm".to_string(),
1307        }
1308    }
1309
1310    fn stack_python() -> ProjectStack {
1311        ProjectStack::Python {
1312            version: String::new(),
1313        }
1314    }
1315
1316    fn stack_rust() -> ProjectStack {
1317        ProjectStack::Rust {
1318            version: String::new(),
1319        }
1320    }
1321
1322    /// Absolute path to a fixture directory under `tests/fixtures/`.
1323    fn fixture(sub: &str) -> String {
1324        format!("{}/tests/fixtures/{sub}", env!("CARGO_MANIFEST_DIR"))
1325    }
1326
1327    // --- Named coverage tests ----------------------------------------------
1328
1329    #[test]
1330    fn test_env_file_detection() {
1331        // A project with only `.env.example` must warn about the missing `.env`.
1332        let audit = crate::modules::env_auditor::audit_env_files(&fixture("env_sample_project"));
1333        assert_eq!(audit.check_name, "Env Audit");
1334        assert_eq!(audit.status, CheckStatus::Warn);
1335        assert!(audit.message.contains(".env.example"));
1336
1337        // A project with neither env file passes cleanly.
1338        let clean = crate::modules::env_auditor::audit_env_files(&fixture("node_project"));
1339        assert_eq!(clean.status, CheckStatus::Pass);
1340    }
1341
1342    #[test]
1343    fn test_port_blockage_detection() {
1344        let output = "\
1345TCP    0.0.0.0:3000           0.0.0.0:0              LISTENING       9921
1346TCP    127.0.0.1:8080         0.0.0.0:0              LISTENING       12345
1347TCP    127.0.0.1:50001        0.0.0.0:0              ESTABLISHED     55
1348";
1349        let found = port_watcher::parse_netstat(output);
1350        assert!(found.contains(&(3000, 9921)));
1351        assert!(found.contains(&(8080, 12345)));
1352        assert!(!found.iter().any(|(port, _)| *port == 50001));
1353
1354        let tasks = "\
1355\"node.exe\",\"9921\",\"Console\",\"1\",\"30,292 K\"
1356\"python.exe\",\"12345\",\"Console\",\"1\",\"11,240 K\"
1357";
1358        let names = port_watcher::parse_tasklist(tasks);
1359        assert_eq!(names.get(&9921).map(String::as_str), Some("node.exe"));
1360        assert_eq!(names.get(&12345).map(String::as_str), Some("python.exe"));
1361        assert_eq!(names.get(&55), None);
1362    }
1363
1364    #[test]
1365    fn test_dependency_checking() {
1366        // Fresh fixtures have no `node_modules`, so the audit must fail loudly.
1367        let result =
1368            crate::modules::dependency_checker::check_dependencies(&fixture("node_project"), &stack_node());
1369        assert_eq!(result.check_name, "Dependencies");
1370        assert_eq!(result.status, CheckStatus::Fail);
1371        assert!(result.message.contains("node_modules"));
1372
1373        // Unknown stacks never need a dependency audit.
1374        let none = crate::modules::dependency_checker::check_dependencies(
1375            &fixture("unknown_project"),
1376            &ProjectStack::Unknown,
1377        );
1378        assert_eq!(none.status, CheckStatus::Pass);
1379    }
1380
1381    #[test]
1382    fn test_health_score_calculation() {
1383        use crate::models::HealthStatus;
1384        let results = vec![
1385            DiagnosticResult::new("Runtime Check", CheckStatus::Pass, "found"),
1386            DiagnosticResult::new("Dependencies", CheckStatus::Pass, "ok"),
1387            DiagnosticResult::new("Env Audit", CheckStatus::Warn, ".env.example only"),
1388            DiagnosticResult::new("Port Scan", CheckStatus::Fail, "Port 3000 in use"),
1389        ];
1390        let score = HealthScore::from_results(&results);
1391        assert_eq!(score.total_checks, 4);
1392        assert_eq!(score.passed, 2);
1393        assert_eq!(score.warnings, 1);
1394        assert_eq!(score.failed, 1);
1395        assert_eq!(score.percentage, 50);
1396        assert_eq!(score.overall_status, HealthStatus::Critical);
1397        assert!(score.validate().is_ok());
1398        assert!(score.recompute().validate().is_ok());
1399    }
1400
1401    #[test]
1402    fn test_diagnostics_parallelization() {
1403        use std::time::{Duration as StdDuration, Instant};
1404        let checks = vec![
1405            NamedCheck::single("Speed A", || {
1406                std::thread::sleep(StdDuration::from_millis(150));
1407                DiagnosticResult::new("Speed A", CheckStatus::Pass, "fast")
1408            }),
1409            NamedCheck::single("Speed B", || {
1410                std::thread::sleep(StdDuration::from_millis(150));
1411                DiagnosticResult::new("Speed B", CheckStatus::Warn, "warn")
1412            }),
1413            NamedCheck::single("Speed C", || {
1414                DiagnosticResult::new("Speed C", CheckStatus::Fail, "fail")
1415            }),
1416        ];
1417        let start = Instant::now();
1418        let results = run_checks_parallel_with_timeout(checks, StdDuration::from_secs(5));
1419        let elapsed = start.elapsed();
1420
1421        assert_eq!(results.len(), 3);
1422        let names: Vec<&str> = results.iter().map(|r| r.check_name.as_str()).collect();
1423        assert!(names.contains(&"Speed A"));
1424        assert!(names.contains(&"Speed B"));
1425        assert!(names.contains(&"Speed C"));
1426        // Two 150ms checks running in parallel stay well under their 300ms sum.
1427        assert!(
1428            elapsed < StdDuration::from_millis(275),
1429            "checks should overlap, took {elapsed:?}"
1430        );
1431    }
1432}