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
//! Auto-fix orchestration for `limit fix --all`.
//!
//! [`run_auto_fix_all`] applies every *non-destructive* repair that is
//! currently applicable — terminate ghost processes, copy `.env.example` →
//! `.env`, then (unless `--safe`) install missing dependencies — in
//! dependency order, re-runs the full diagnostics afterwards and returns a
//! [`FixReport`] summarising what changed and what still needs a human.
//!
//! # Ordering
//!
//! Fixes run in dependency order:
//!
//! 1. **Kill ghost processes** first — this frees the blocked dev ports.
//! 2. **Copy `.env.example` → `.env`** second — the app can then start up.
//! 3. **Install dependencies** last — the slowest, most disruptive step.
//!
//! ```
//! use limitless_cli::models::{EnvironmentState, ProjectStack};
//! use limitless_cli::modules::auto_fix::build_auto_fixes;
//!
//! let mut state = EnvironmentState::default();
//! state.detected_stack = ProjectStack::Node {
//!     version: "22.9.0".into(),
//!     package_manager: "npm".into(),
//! };
//! state.env_example_exists = true;
//! state.dependencies_healthy = false;
//! state.blocked_ports = vec![(3000, 9921)];
//!
//! let fixes = build_auto_fixes(&state, ".", true);
//! assert_eq!(fixes.len(), 3);
//! assert_eq!(fixes[0].id, "kill-ghost-9921");
//! assert_eq!(fixes[1].id, "copy-env-from-example");
//! assert_eq!(fixes[2].id, "install-dependencies-npm");
//! ```

use colored::Colorize;

use crate::models::{CheckStatus, DiagnosticResult, EnvironmentState, HealthStatus};
use crate::modules::diagnostics;
use crate::modules::fixes::{self, Fix, FixCommand};

// ---------------------------------------------------------------------------
// Report model
// ---------------------------------------------------------------------------

/// Width of the final auto-fix report box, measured in terminal columns.
///
/// ```
/// use limitless_cli::modules::auto_fix::REPORT_WIDTH;
/// assert_eq!(REPORT_WIDTH, 60);
/// ```
pub const REPORT_WIDTH: usize = 60;

/// Inner content width between the two vertical frame bars.
const INNER_WIDTH: usize = REPORT_WIDTH - 4;

/// Result summary produced by [`run_auto_fix_all`].
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct FixReport {
    /// Number of fixes that executed successfully.
    pub fixes_applied: u32,
    /// Number of fixes that failed.
    pub fixes_failed: u32,
    /// Health score (0–100) captured before the fixes ran.
    pub before_score: u32,
    /// Health score (0–100) recalculated after the fixes ran.
    pub after_score: u32,
    /// Human-readable description of every still-failing/warned check.
    pub issues_remaining: Vec<String>,
    /// Concrete manual steps suggested for the remaining issues.
    pub next_steps: Vec<String>,
}

impl FixReport {
    /// Whether every fixable issue was resolved (no remaining issues and no
    /// failed fixes).
    pub fn is_clean(&self) -> bool {
        self.issues_remaining.is_empty() && self.fixes_failed == 0
    }

    /// Whether the health score improved after the fixes ran.
    pub fn improved(&self) -> bool {
        self.after_score > self.before_score
    }
}

// ---------------------------------------------------------------------------
// Fix planning
// ---------------------------------------------------------------------------

/// Builds the ordered, non-destructive fix list for a state snapshot.
///
/// Only three repair families are eligible, so the suite can never overwrite
/// user data:
///
/// 1. Kill each ghost process holding a blocked dev port.
/// 2. Copy `.env.example` → `.env` when the template exists and the target
///    is missing.
/// 3. Install missing dependencies — only when `include_deps` is set (the
///    `--all` / automatic mode; `--safe` clears it) and the stack has a
///    known package manager.
pub fn build_auto_fixes(
    state: &EnvironmentState,
    repo_path: &str,
    include_deps: bool,
) -> Vec<Fix> {
    let mut fixes = Vec::new();

    // 1. Kill ghost processes first: frees the blocked ports.
    for (port, pid) in &state.blocked_ports {
        fixes.push(fixes::kill_ghost_process(*port, *pid));
    }

    // 2. Copy the env template second: lets the app start up.
    if state.env_example_exists && !state.env_file_exists {
        if let Some(fix) = fixes::copy_env_from_example(".env.example", ".env") {
            fixes.push(fix);
        }
    }

    // 3. Install dependencies last: the slowest, most far-reaching step.
    if include_deps && !state.dependencies_healthy {
        if let Some(fix) = fixes::install_fix_for_stack(&state.detected_stack) {
            fixes.push(fix);
        }
    }

    // No config-file creation here: auto-fix only touches data that is clearly
    // safe to create/copy/terminate without asking.
    let _ = repo_path;
    fixes
}

// ---------------------------------------------------------------------------
// Post-fix analysis
// ---------------------------------------------------------------------------

/// Human-readable messages for every check that is not `Pass`.
pub fn remaining_issues(results: &[DiagnosticResult]) -> Vec<String> {
    results
        .iter()
        .filter(|d| d.status != CheckStatus::Pass)
        .map(|d| format!("{}: {}", d.check_name, d.message))
        .collect()
}

/// Concrete manual steps (remediation hints) for every non-passing check.
pub fn next_steps(results: &[DiagnosticResult]) -> Vec<String> {
    results
        .iter()
        .filter(|d| d.status != CheckStatus::Pass)
        .filter_map(|d| d.remediation.clone())
        .collect()
}

// ---------------------------------------------------------------------------
// Orchestration
// ---------------------------------------------------------------------------

/// Runs the full auto-fix suite: kills ghost processes, copies the env
/// template and installs missing dependencies, then re-runs the diagnostics
/// and reports the outcome.
///
/// All user-facing progress is printed as the fixes run.
pub async fn run_auto_fix_all(state: &EnvironmentState, repo_path: &str) -> FixReport {
    run_auto_fix_all_with(state, repo_path, true).await
}

/// Like [`run_auto_fix_all`] but never installs dependencies (`--safe` mode).
pub async fn run_auto_fix_safe(state: &EnvironmentState, repo_path: &str) -> FixReport {
    run_auto_fix_all_with(state, repo_path, false).await
}

async fn run_auto_fix_all_with(
    state: &EnvironmentState,
    repo_path: &str,
    include_deps: bool,
) -> FixReport {
    let before_score = state.health_score.percentage;
    let fixes = build_auto_fixes(state, repo_path, include_deps);

    println!("{}", "🔧 RUNNING AUTO-FIX SUITE".bold().cyan());

    let mut applied = 0u32;
    let mut failed = 0u32;
    for fix in &fixes {
        println!("  {} {}...", "⏳".dimmed(), action_phrase(fix).bold());
        for line in fix.preview_fix(repo_path).lines() {
            println!("  {}", line.dimmed());
        }
        match fixes::execute_fix(fix, repo_path).await {
            Ok(log) => {
                applied += 1;
                for line in log.lines() {
                    println!("    {line}");
                }
            }
            Err(err) => {
                failed += 1;
                for line in err.lines() {
                    println!("    {}", line.red());
                }
            }
        }
    }

    if fixes.is_empty() {
        println!("  {} No fixable issues detected.", "✓".green().bold());
    }
    println!();

    let after = diagnostics::run_full_diagnostics(repo_path);
    let report = FixReport {
        fixes_applied: applied,
        fixes_failed: failed,
        before_score,
        after_score: after.health_score.percentage,
        issues_remaining: remaining_issues(&after.diagnostics),
        next_steps: next_steps(&after.diagnostics),
    };

    println!("{}", render_auto_fix_report(&report));
    report
}

/// Short, live phrasing for a fix while it is about to run.
fn action_phrase(fix: &Fix) -> String {
    match &fix.command {
        FixCommand::CopyFile { src, dst } => format!("Copying {src} → {dst}"),
        FixCommand::KillProcess { pid } => format!("Terminating process PID {pid}"),
        FixCommand::RunCommand { cmd, args } => {
            format!("Running `{} {}`", cmd, args.join(" "))
        }
        FixCommand::CreateFile { path, .. } => format!("Creating {path}"),
        FixCommand::DeleteFile { path } => format!("Deleting {path}"),
    }
}

// ---------------------------------------------------------------------------
// CLI entry point
// ---------------------------------------------------------------------------

/// Runs `limit fix --all`: builds a fresh snapshot, applies the auto-fix
/// suite and prints the report. When `safe` is set, dependency installs are
/// skipped.
pub async fn run_auto_fix(safe: bool) {
    let state = diagnostics::build_snapshot(".");
    if safe {
        run_auto_fix_safe(&state, ".").await;
    } else {
        run_auto_fix_all(&state, ".").await;
    }
}

// ---------------------------------------------------------------------------
// Report rendering
// ---------------------------------------------------------------------------

/// Renders the [`FixReport`] as a colorized summary box (ANSI included).
///
/// ```
/// use limitless_cli::modules::auto_fix::{FixReport, render_auto_fix_report_plain};
///
/// let report = FixReport {
///     fixes_applied: 2,
///     fixes_failed: 0,
///     before_score: 50,
///     after_score: 100,
///     issues_remaining: vec![],
///     next_steps: vec![],
/// };
/// let out = render_auto_fix_report_plain(&report);
/// assert!(out.contains("Health Score: 50% → 100%"));
/// assert!(out.contains("System ready for launch!"));
/// ```
pub fn render_auto_fix_report(report: &FixReport) -> String {
    render_report_inner(report, true)
}

/// Same layout as [`render_auto_fix_report`] with all ANSI codes stripped.
pub fn render_auto_fix_report_plain(report: &FixReport) -> String {
    render_report_inner(report, false)
}

/// Per-row styling used while assembling the report box.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RowStyle {
    Plain,
    Border,
    Title,
    Score,
    Status(HealthStatus),
    Launch,
    Warn,
}

/// Maps a health percentage to a [`HealthStatus`], mirroring
/// [`HealthScore::from_counts`].
fn classify(score: u32) -> HealthStatus {
    match score {
        85..=100 => HealthStatus::Healthy,
        60..=84 => HealthStatus::Caution,
        _ => HealthStatus::Critical,
    }
}

fn status_label(status: HealthStatus) -> &'static str {
    match status {
        HealthStatus::Healthy => "Healthy - Ready to Launch!",
        HealthStatus::Caution => "Caution - Some checks need attention",
        HealthStatus::Critical => "Critical - Manual help needed",
    }
}

fn render_report_inner(report: &FixReport, colored: bool) -> String {
    let status = classify(report.after_score);
    let score_row = format!(
        "Health Score: {}% → {}%{}",
        report.before_score,
        report.after_score,
        delta_mark(report)
    );

    let mut rows: Vec<(RowStyle, String)> = Vec::new();
    rows.push((RowStyle::Border, border_line(true)));
    rows.push((RowStyle::Title, box_row("🔧 AUTO-FIX REPORT")));
    rows.push((RowStyle::Border, separator_line()));
    rows.push((RowStyle::Score, box_row(&score_row)));
    rows.push((
        RowStyle::Status(status),
        box_row(&format!("Status: {}", status_label(status))),
    ));

    if report.issues_remaining.is_empty() {
        rows.push((RowStyle::Plain, box_row("")));
        rows.push((RowStyle::Launch, box_row("🚀 System ready for launch! ⚡")));
    } else {
        let n = report.issues_remaining.len();
        rows.push((RowStyle::Plain, box_row("")));
        rows.push((
            RowStyle::Warn,
            box_row(&format!(
                "⚠ {n} issue{} remaining:",
                if n == 1 { "" } else { "s" }
            )),
        ));
        for issue in &report.issues_remaining {
            rows.extend(
                wrapped_rows(&format!("• {issue}"))
                    .into_iter()
                    .map(|row| (RowStyle::Plain, row)),
            );
        }
        if !report.next_steps.is_empty() {
            rows.push((RowStyle::Plain, box_row("")));
            rows.push((RowStyle::Warn, box_row("Next steps:")));
            for step in &report.next_steps {
                rows.extend(
                    wrapped_rows(&format!("• {step}"))
                        .into_iter()
                        .map(|row| (RowStyle::Plain, row)),
                );
            }
        }
    }

    if report.fixes_failed > 0 {
        rows.push((RowStyle::Plain, box_row("")));
        rows.push((
            RowStyle::Warn,
            box_row(&format!(
                "⚠ {} fix{} failed — read the output above",
                report.fixes_failed,
                if report.fixes_failed == 1 { "" } else { "es" }
            )),
        ));
    }

    rows.push((RowStyle::Border, border_line(false)));

    let mut out = String::new();
    for (style, row) in rows {
        out.push_str(&paint(row, style, colored));
        out.push('\n');
    }
    out
}

/// Emoji appended to the score row: 🎉 on a real improvement, ✨ when it was
/// already clean.
fn delta_mark(report: &FixReport) -> &'static str {
    if !report.issues_remaining.is_empty() {
        ""
    } else if report.improved() {
        "  🎉"
    } else {
        "  ✨"
    }
}

/// Applies ANSI styling to a finished (padded) row when `colored` is set.
fn paint(row: String, style: RowStyle, colored: bool) -> String {
    if !colored {
        return row;
    }
    match style {
        RowStyle::Plain => row.normal().to_string(),
        RowStyle::Border | RowStyle::Title => row.cyan().to_string(),
        RowStyle::Score => row.normal().to_string(),
        RowStyle::Status(HealthStatus::Healthy) => row.green().bold().to_string(),
        RowStyle::Status(HealthStatus::Caution) => row.yellow().bold().to_string(),
        RowStyle::Status(HealthStatus::Critical) => row.red().bold().to_string(),
        RowStyle::Launch => row.green().bold().to_string(),
        RowStyle::Warn => row.yellow().to_string(),
    }
}

/// A top (`┌…┐`), separator (`├…┤`) or bottom (`└…┘`) frame line.
fn border_line(top: bool) -> String {
    let (left, right) = if top { ('┌', '┐') } else { ('└', '┘') };
    format!("{left}{}{right}", "─".repeat(REPORT_WIDTH - 2))
}

fn separator_line() -> String {
    format!("├{}┤", "─".repeat(REPORT_WIDTH - 2))
}

/// A `│ content padded │` row exactly `REPORT_WIDTH` characters wide.
fn box_row(content: &str) -> String {
    format!("│ {} │", pad(content))
}

fn pad(content: &str) -> String {
    let used = content.chars().count();
    format!("{content}{}", " ".repeat(INNER_WIDTH.saturating_sub(used)))
}

/// Renders a `• …` body line wrapped across box rows, indented by 4 columns.
fn wrapped_rows(text: &str) -> Vec<String> {
    wrap(text, INNER_WIDTH - 4)
        .into_iter()
        .map(|line| box_row(&line))
        .collect()
}

/// Word-wraps `text` so every line is at most `width` chars, hard-splitting
/// overlong words and collapsing runs of spaces.
fn wrap(text: &str, width: usize) -> Vec<String> {
    if text.is_empty() || width == 0 {
        return vec![String::new()];
    }

    let mut lines = Vec::new();
    let mut current = String::new();

    for word in text.split(' ') {
        let word_len = word.chars().count();
        if word_len == 0 {
            continue;
        }
        if word_len > width {
            if !current.is_empty() {
                lines.push(std::mem::take(&mut current));
            }
            let mut chunk = String::new();
            for ch in word.chars() {
                if chunk.chars().count() == width {
                    lines.push(std::mem::take(&mut chunk));
                }
                chunk.push(ch);
            }
            current = chunk;
        } else if current.is_empty() {
            current.push_str(word);
        } else if current.chars().count() + 1 + word_len <= width {
            current.push(' ');
            current.push_str(word);
        } else {
            lines.push(std::mem::take(&mut current));
            current.push_str(word);
        }
    }

    if !current.is_empty() {
        lines.push(current);
    }
    if lines.is_empty() {
        lines.push(String::new());
    }
    lines
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::{HealthScore, ProjectStack};
    use std::fs;
    use std::path::PathBuf;
    use std::time::{SystemTime, UNIX_EPOCH};

    struct TempDir {
        path: PathBuf,
    }

    impl TempDir {
        fn new(label: &str) -> Self {
            let stamp = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .expect("system clock")
                .as_nanos();
            let path = std::env::temp_dir().join(format!("limitless_autofix_{label}_{stamp}"));
            fs::create_dir_all(&path).expect("create temp dir");
            TempDir { path }
        }

        fn path(&self) -> &PathBuf {
            &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);
        }
    }

    fn node_state() -> EnvironmentState {
        EnvironmentState {
            detected_stack: ProjectStack::Node {
                version: "18.12.0".into(),
                package_manager: "npm".into(),
            },
            runtime_version: Some("v18.12.0".into()),
            env_file_exists: false,
            env_example_exists: true,
            dependencies_healthy: false,
            blocked_ports: vec![(3000, 9921)],
            diagnostics: vec![],
            health_score: HealthScore::from_counts(1, 0, 2),
        }
    }

    fn empty_state() -> EnvironmentState {
        EnvironmentState {
            detected_stack: ProjectStack::Unknown,
            runtime_version: None,
            env_file_exists: false,
            env_example_exists: false,
            dependencies_healthy: true,
            blocked_ports: vec![],
            diagnostics: vec![],
            health_score: HealthScore::default(),
        }
    }

    // --- Planning ----------------------------------------------------------

    #[test]
    fn build_auto_fixes_orders_kill_then_copy_then_install() {
        let state = node_state();
        let fixes = build_auto_fixes(&state, ".", true);
        let ids: Vec<&str> = fixes.iter().map(|f| f.id.as_str()).collect();
        assert_eq!(
            ids,
            vec![
                "kill-ghost-9921",
                "copy-env-from-example",
                "install-dependencies-npm"
            ]
        );
    }

    #[test]
    fn build_auto_fixes_safe_mode_skips_install() {
        let state = node_state();
        let fixes = build_auto_fixes(&state, ".", false);
        let ids: Vec<&str> = fixes.iter().map(|f| f.id.as_str()).collect();
        assert_eq!(ids, vec!["kill-ghost-9921", "copy-env-from-example"]);
    }

    #[test]
    fn build_auto_fixes_skips_copy_when_env_exists() {
        let mut state = node_state();
        state.env_file_exists = true;
        let fixes = build_auto_fixes(&state, ".", true);
        let ids: Vec<&str> = fixes.iter().map(|f| f.id.as_str()).collect();
        assert_eq!(ids, vec!["kill-ghost-9921", "install-dependencies-npm"]);
    }

    #[test]
    fn build_auto_fixes_skips_kill_when_no_blocked_ports() {
        let mut state = node_state();
        state.blocked_ports = vec![];
        let fixes = build_auto_fixes(&state, ".", true);
        let ids: Vec<&str> = fixes.iter().map(|f| f.id.as_str()).collect();
        assert_eq!(ids, vec!["copy-env-from-example", "install-dependencies-npm"]);
    }

    #[test]
    fn build_auto_fixes_skips_install_for_unknown_stack() {
        let mut state = node_state();
        state.detected_stack = ProjectStack::Unknown;
        let fixes = build_auto_fixes(&state, ".", true);
        let ids: Vec<&str> = fixes.iter().map(|f| f.id.as_str()).collect();
        assert_eq!(ids, vec!["kill-ghost-9921", "copy-env-from-example"]);
    }

    #[test]
    fn build_auto_fixes_empty_when_nothing_applicable() {
        assert!(build_auto_fixes(&empty_state(), ".", true).is_empty());
    }

    // --- Post-fix analysis -------------------------------------------------

    #[test]
    fn remaining_issues_lists_non_passing_checks() {
        let results = vec![
            DiagnosticResult::new("Env Audit", CheckStatus::Pass, "ok"),
            DiagnosticResult::new(
                "Broken PATH entries",
                CheckStatus::Warn,
                "1 entry points to a missing folder",
            ),
            DiagnosticResult::new("Tool node", CheckStatus::Fail, "node not found on PATH"),
        ];
        assert_eq!(
            remaining_issues(&results),
            vec![
                "Broken PATH entries: 1 entry points to a missing folder".to_string(),
                "Tool node: node not found on PATH".to_string()
            ]
        );
    }

    #[test]
    fn next_steps_uses_remediation_of_non_passing_checks() {
        let results = vec![
            DiagnosticResult::new("Env Audit", CheckStatus::Fail, ".env missing")
                .with_remediation("Copy .env.example to .env"),
            DiagnosticResult::new("Editor", CheckStatus::Warn, "EDITOR unset")
                .with_remediation("export EDITOR=\"code --wait\""),
            DiagnosticResult::new("Proxy", CheckStatus::Pass, "fine"),
        ];
        assert_eq!(
            next_steps(&results),
            vec![
                "Copy .env.example to .env".to_string(),
                "export EDITOR=\"code --wait\"".to_string()
            ]
        );
    }

    #[test]
    fn report_classifies_health_and_improvement() {
        let clean = FixReport {
            fixes_applied: 2,
            fixes_failed: 0,
            before_score: 50,
            after_score: 100,
            issues_remaining: vec![],
            next_steps: vec![],
        };
        assert!(clean.is_clean());
        assert!(clean.improved());

        let dirty = FixReport {
            fixes_applied: 1,
            fixes_failed: 1,
            before_score: 50,
            after_score: 70,
            issues_remaining: vec!["Tool node: missing".into()],
            next_steps: vec!["Install node".into()],
        };
        assert!(!dirty.is_clean());
        assert!(dirty.improved());
        assert_eq!(classify(dirty.after_score), HealthStatus::Caution);
        assert_eq!(classify(clean.after_score), HealthStatus::Healthy);
    }

    // --- Execution ---------------------------------------------------------

    #[tokio::test]
    async fn auto_fix_copies_env_and_reports_counts() {
        let dir = TempDir::new("copy_env").write(".env.example", "PORT=3000\n");
        let mut state = empty_state();
        state.env_example_exists = true;
        state.dependencies_healthy = true;
        let repo = dir.path().to_str().unwrap().to_string();

        let report = run_auto_fix_all(&state, &repo).await;

        assert_eq!(report.fixes_applied, 1);
        assert_eq!(report.fixes_failed, 0);
        assert_eq!(report.before_score, 100);
        assert!(report.after_score <= 100);
        let content = fs::read_to_string(dir.path().join(".env")).unwrap();
        assert_eq!(content, "PORT=3000\n");
    }

    #[tokio::test]
    async fn auto_fix_skips_missing_ghost_process() {
        let dir = TempDir::new("kill_skip");
        let mut state = empty_state();
        state.blocked_ports = vec![(3000, 999_999_999)];
        let repo = dir.path().to_str().unwrap().to_string();

        let report = run_auto_fix_all(&state, &repo).await;

        assert_eq!(report.fixes_applied, 1, "skip still counts as applied");
        assert_eq!(report.fixes_failed, 0);
    }

    #[tokio::test]
    async fn auto_fix_does_not_create_env_without_template() {
        let dir = TempDir::new("no_template");
        let repo = dir.path().to_str().unwrap().to_string();

        let report = run_auto_fix_all(&empty_state(), &repo).await;

        assert_eq!(report.fixes_applied, 0);
        assert!(!dir.path().join(".env").exists());
    }

    // --- Rendering ---------------------------------------------------------

    #[test]
    fn report_box_plain_lines_are_exact_width() {
        let clean = FixReport {
            fixes_applied: 2,
            fixes_failed: 0,
            before_score: 50,
            after_score: 100,
            issues_remaining: vec![],
            next_steps: vec![],
        };
        let out = render_auto_fix_report_plain(&clean);
        for line in out.lines() {
            assert_eq!(
                line.chars().count(),
                REPORT_WIDTH,
                "wrong width: {line:?}"
            );
        }
        assert!(!out.contains('\x1b'));
        assert!(out.contains("Health Score: 50% → 100%  🎉"));
        assert!(out.contains("Status: Healthy - Ready to Launch!"));
        assert!(out.contains("🚀 System ready for launch! ⚡"));
    }

    #[test]
    fn report_box_plain_lists_remaining_and_next_steps() {
        let dirty = FixReport {
            fixes_applied: 1,
            fixes_failed: 1,
            before_score: 20,
            after_score: 60,
            issues_remaining: vec![
                "Env Audit: .env file missing".into(),
            ],
            next_steps: vec!["Copy .env.example to .env".into()],
        };
        let out = render_auto_fix_report_plain(&dirty);
        assert!(out.contains("Health Score: 20% → 60%"));
        assert!(out.contains("Status: Caution - Some checks need attention"));
        assert!(out.contains("1 issue remaining:"));
        assert!(out.contains("Env Audit: .env file missing"));
        assert!(out.contains("Next steps:"));
        assert!(out.contains("Copy .env.example to .env"));
        assert!(out.contains("1 fix failed"));
        assert!(!out.contains("System ready for launch"));
    }

    #[test]
    fn report_box_plain_keeps_width_with_long_issues() {
        let report = FixReport {
            fixes_failed: 0,
            fixes_applied: 0,
            before_score: 0,
            after_score: 40,
            issues_remaining: vec![
                "Tool go: go was not found on PATH, which means Go-based tooling cannot run".into(),
            ],
            next_steps: vec!["Install go and add it to PATH before continuing".into()],
        };
        let out = render_auto_fix_report_plain(&report);
        for line in out.lines() {
            assert_eq!(line.chars().count(), REPORT_WIDTH);
        }
        assert!(out.contains("1 issue remaining:"));
    }

    #[test]
    fn report_box_default_render_is_clean() {
        let out = render_auto_fix_report_plain(&FixReport::default());
        assert!(out.contains("System ready for launch! ⚡"));
        assert!(out.contains("Health Score: 0% → 0%  ✨"));
    }

    #[test]
    fn colored_report_box_contains_ansi() {
        colored::control::set_override(true);
        let report = FixReport {
            fixes_applied: 2,
            fixes_failed: 0,
            before_score: 50,
            after_score: 100,
            issues_remaining: vec![],
            next_steps: vec![],
        };
        let out = render_auto_fix_report(&report);
        assert!(out.contains("\x1b["));
        assert!(out.contains("\x1b[0m"));
        colored::control::unset_override();
    }
}