limitless-cli 1.0.0

A beginner-friendly environment diagnostic tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
//! Deep developer-environment diagnostics for `limit dev`.
//!
//! Inspects PATH hygiene, key environment variables, installed dev tools,
//! stack-specific context (virtualenvs, Cargo home, lock files) and commonly
//! used dev ports, then folds everything into a single [`EnvironmentState`]
//! snapshot with a [`HealthScore`] and beginner-friendly [`MentorMessage`]s.

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;

// ---------------------------------------------------------------------------
// PATH analysis
// ---------------------------------------------------------------------------

/// The separator the current platform uses to join PATH entries.
pub fn path_separator() -> char {
    if cfg!(windows) {
        ';'
    } else {
        ':'
    }
}

/// Expands a `%VAR%` reference inside a PATH entry (Windows style).
///
/// Entries without a `%NAME%` pair are returned unchanged.
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)
}

/// Resolves a raw PATH entry into the filesystem path it refers to.
pub fn resolve_path_entry(entry: &str) -> PathBuf {
    expand_windows_var(entry)
}

/// The result of analysing a raw PATH string.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathReport {
    /// Number of tokens after splitting, empty ones included.
    pub total_entries: usize,
    /// How many tokens were empty (e.g. a leading/trailing separator).
    pub empty_entries: usize,
    /// Raw entries that resolve to folders which do not exist.
    pub broken_entries: Vec<String>,
    /// Resolved folders that appear on PATH more than once (deduplicated).
    pub duplicate_entries: Vec<PathBuf>,
    /// Whether the special `.` (current directory) entry is present.
    pub has_current_dir: bool,
}

/// Splits and validates a raw PATH string.
///
/// Empty entries are counted but skipped for further checks. Broken and
/// duplicate entries are reported separately so the UI can explain each.
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,
    }
}

// ---------------------------------------------------------------------------
// Environment variable inspection
// ---------------------------------------------------------------------------

/// Looks up the first of two variable names (Windows name first).
pub fn resolve_var(primary: &str, alt: &str) -> Option<String> {
    env::var(primary).ok().or_else(|| env::var(alt).ok())
}

/// Passes through the raw `PATH` value of the current process, if any.
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),
    }
}

/// Checks that `PATH` is set and reports hygiene problems in separate
/// diagnostics (broken entries, duplicates, current-directory entry).
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
}

/// Checks that the user home directory is set and actually exists.
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",
        ),
    }
}

/// Checks that an editor is configured.
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\""),
    }
}

/// Classifies a pair of proxy variables into a status plus a message.
///
/// `None` means the variable is unset. The two values are passed in so the
/// classification can be unit-tested without touching the real environment.
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"),
    }
}

/// Reads the real proxy variables and reports their consistency.
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)
}

// ---------------------------------------------------------------------------
// Installed dev tools
// ---------------------------------------------------------------------------

/// `(command, version flag)` pairs probed by the diagnostics.
pub const CORE_TOOLS: &[(&str, &str)] = &[
    ("rustc", "--version"),
    ("cargo", "--version"),
    ("node", "--version"),
    ("npm", "--version"),
    ("python", "--version"),
    ("go", "version"),
    ("java", "-version"),
];

/// Runs `tool --version` and returns the first non-empty output line.
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())
    }
}

/// One diagnostic per core tool: `Pass` when found, `Fail` when missing.
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()
}

// ---------------------------------------------------------------------------
// Stack-specific context
// ---------------------------------------------------------------------------

/// Checks environment context that only matters for a given stack.
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(),
    }
}

// ---------------------------------------------------------------------------
// Development ports
// ---------------------------------------------------------------------------

/// Ports monitored by `limit dev` (superset of the common dev ports,
/// including databases commonly found in local environments).
const DIAGNOSTIC_PORTS: &[u16] = &[3000, 3001, 5173, 5432, 8000, 8080, 8081, 27017];

// ---------------------------------------------------------------------------
// Dependency audit
// ---------------------------------------------------------------------------

/// Lock files that pin dependency versions, per stack.
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"],
        _ => &[],
    }
}

/// Checks that the project manifest exists and that dependencies are pinned
/// by a lock file.
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)",
        )
    }
}

// ---------------------------------------------------------------------------
// Collection and snapshot
// ---------------------------------------------------------------------------

/// Runs every diagnostic and returns the full list.
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
}

/// Builds a full [`EnvironmentState`] snapshot for a repository root.
///
/// Delegates to [`run_full_diagnostics`] so every check runs in parallel with
/// a per-check timeout.
///
/// ```
/// use limitless_cli::modules::diagnostics::build_snapshot;
///
/// let state = build_snapshot(env!("CARGO_MANIFEST_DIR"));
/// assert!(!state.diagnostics.is_empty());
/// assert!(state.health_score.validate().is_ok());
/// ```
pub fn build_snapshot(repo_root: &str) -> EnvironmentState {
    run_full_diagnostics(repo_root)
}

// ---------------------------------------------------------------------------
// Mentor guidance
// ---------------------------------------------------------------------------

/// Builds mentor guidance for all non-passing diagnostics, critical first.
///
/// Delegates each translation to the [`translator`](crate::modules::translator)
/// database so the advice stays beginner-friendly and actionable.
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
}

// ---------------------------------------------------------------------------
// Parallel orchestration
// ---------------------------------------------------------------------------

/// Per-check timeout applied inside [`run_checks_parallel`].
pub const CHECK_TIMEOUT: Duration = Duration::from_secs(5);

/// A single named check that can be scheduled on a worker thread.
///
/// The `run` closure must be plain and blocking; the parallel engine wraps it
/// in a timeout and turns crashes or hangs into a [`CheckStatus::Fail`]
/// diagnostic instead of propagating them.
pub struct NamedCheck {
    /// Display name, used for timeout/crash diagnostics.
    pub name: &'static str,
    /// The blocking check to run. May return zero or more diagnostics.
    pub run: Box<dyn FnOnce() -> Vec<DiagnosticResult> + Send + 'static>,
}

impl NamedCheck {
    /// Wraps a single-result check into a [`NamedCheck`].
    pub fn single(
        name: &'static str,
        run: impl FnOnce() -> DiagnosticResult + Send + 'static,
    ) -> Self {
        Self {
            name,
            run: Box::new(move || vec![run()]),
        }
    }
}

/// Runs one check on a blocking thread under a timeout. A timed-out or
/// panicking check becomes a single `Fail` diagnostic; a cancelled one
/// produces nothing.
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")]
        }
    }
}

/// Runs a collection of blocking checks in parallel with a per-check timeout.
///
/// Every check is scheduled on a worker thread; results are collected
/// asynchronously as they finish. Individual failures never abort the batch:
/// a check that panics or exceeds the timeout contributes a single
/// [`CheckStatus::Fail`] diagnostic instead.
///
/// The order of the returned diagnostics is non-deterministic (checks finish
/// at different times), so callers must not rely on the vector being sorted.
///
/// ```
/// use limitless_cli::models::CheckStatus;
/// use limitless_cli::modules::diagnostics::{NamedCheck, run_checks_parallel};
///
/// let checks = vec![
///     NamedCheck::single("Passing", || {
///         limitless_cli::models::DiagnosticResult::new(
///             "Passing",
///             CheckStatus::Pass,
///             "all good",
///         )
///     }),
/// ];
/// let results = run_checks_parallel(checks);
/// assert_eq!(results.len(), 1);
/// assert!(results[0].is_pass());
/// ```
pub fn run_checks_parallel(checks: Vec<NamedCheck>) -> Vec<DiagnosticResult> {
    run_checks_parallel_with_timeout(checks, CHECK_TIMEOUT)
}

/// Like [`run_checks_parallel`] but with an explicit timeout (used by tests).
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(_) => { /* cancelled tasks contribute nothing */ }
                }
            }
            results
        })
    })
    .join()
    .unwrap_or_else(|_| {
        vec![DiagnosticResult::new(
            "Parallel check",
            CheckStatus::Fail,
            "the diagnostics runtime crashed before running checks",
        )]
    })
}

/// Converts a [`VersionReport`] into a [`DiagnosticResult`].
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
}

/// Runs *all* checks in parallel and folds them into a full
/// [`EnvironmentState`].
///
/// # Orchestration
///
/// 1. The stack is detected **first** (blocking) because every per-stack
///    check depends on it.
/// 2. Every check is scheduled concurrently on a worker thread: runtime
///    validation, env-file audit, port scan, dependency health, PATH
///    hygiene, installed tools, home/editor/proxy and stack context.
/// 3. Each check runs under a [`CHECK_TIMEOUT`] (5 s); a timeout or crash is
///    aggregated as a `Fail` diagnostic rather than aborting the batch.
/// 4. A [`HealthScore`] is recomputed from the collected diagnostics so the
///    returned state is always consistent.
///
/// Side-effect state (`runtime_version`, `blocked_ports`) is gathered from
/// the check worker threads, and `dependencies_healthy` mirrors the
/// "Dependency audit" check (manifest + lock file present).
///
/// ```
/// use limitless_cli::modules::diagnostics::run_full_diagnostics;
///
/// let state = run_full_diagnostics(env!("CARGO_MANIFEST_DIR"));
/// assert!(!state.diagnostics.is_empty());
/// assert_eq!(state.health_score.total_checks, state.diagnostics.len() as u32);
/// assert!(state.health_score.validate().is_ok());
/// ```
pub fn run_full_diagnostics(repo_path: &str) -> EnvironmentState {
    // Blocking step: the stack drives every downstream check.
    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
}

// ---------------------------------------------------------------------------
// Rendering helpers
// ---------------------------------------------------------------------------

fn status_icon(status: CheckStatus) -> ColoredString {
    match status {
        CheckStatus::Pass => "PASS".green().bold(),
        CheckStatus::Warn => "WARN".yellow().bold(),
        CheckStatus::Fail => "FAIL".red().bold(),
    }
}

/// Renders a 20-cell proportional health bar.
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()
    );
}

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------

/// Runs the full developer-environment inspection for `limit dev`.
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};

    /// A self-cleaning temporary directory.
    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);
        }
    }

    // --- PATH analysis ----------------------------------------------------

    #[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);
    }

    // --- Proxy consistency ------------------------------------------------

    #[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);
    }

    // --- Port probing (delegates to port_watcher) --------------------------

    #[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));
    }

    // --- Dependency audit -------------------------------------------------

    #[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
        );
    }

    // --- Snapshot integration ----------------------------------------------

    #[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());
        // `.env` files are required by `ready_for_dev`, and this fixture has none.
        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");
    }

    // --- Parallel orchestration ---------------------------------------------

    #[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);
        // Running serially the two 150 ms checks would take >= 300 ms.
        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());
        // The deep dependency check runs; the lock-file audit decides health.
        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(),
        }
    }

    /// Absolute path to a fixture directory under `tests/fixtures/`.
    fn fixture(sub: &str) -> String {
        format!("{}/tests/fixtures/{sub}", env!("CARGO_MANIFEST_DIR"))
    }

    // --- Named coverage tests ----------------------------------------------

    #[test]
    fn test_env_file_detection() {
        // A project with only `.env.example` must warn about the missing `.env`.
        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"));

        // A project with neither env file passes cleanly.
        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() {
        // Fresh fixtures have no `node_modules`, so the audit must fail loudly.
        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"));

        // Unknown stacks never need a dependency audit.
        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"));
        // Two 150ms checks running in parallel stay well under their 300ms sum.
        assert!(
            elapsed < StdDuration::from_millis(275),
            "checks should overlap, took {elapsed:?}"
        );
    }
}