1use colored::Colorize;
38
39use crate::models::{CheckStatus, DiagnosticResult, EnvironmentState, HealthStatus};
40use crate::modules::diagnostics;
41use crate::modules::fixes::{self, Fix, FixCommand};
42
43pub const REPORT_WIDTH: usize = 60;
54
55const INNER_WIDTH: usize = REPORT_WIDTH - 4;
57
58#[derive(Debug, Clone, PartialEq, Eq, Default)]
60pub struct FixReport {
61 pub fixes_applied: u32,
63 pub fixes_failed: u32,
65 pub before_score: u32,
67 pub after_score: u32,
69 pub issues_remaining: Vec<String>,
71 pub next_steps: Vec<String>,
73}
74
75impl FixReport {
76 pub fn is_clean(&self) -> bool {
79 self.issues_remaining.is_empty() && self.fixes_failed == 0
80 }
81
82 pub fn improved(&self) -> bool {
84 self.after_score > self.before_score
85 }
86}
87
88pub fn build_auto_fixes(
104 state: &EnvironmentState,
105 repo_path: &str,
106 include_deps: bool,
107) -> Vec<Fix> {
108 let mut fixes = Vec::new();
109
110 for (port, pid) in &state.blocked_ports {
112 fixes.push(fixes::kill_ghost_process(*port, *pid));
113 }
114
115 if state.env_example_exists && !state.env_file_exists {
117 if let Some(fix) = fixes::copy_env_from_example(".env.example", ".env") {
118 fixes.push(fix);
119 }
120 }
121
122 if include_deps && !state.dependencies_healthy {
124 if let Some(fix) = fixes::install_fix_for_stack(&state.detected_stack) {
125 fixes.push(fix);
126 }
127 }
128
129 let _ = repo_path;
132 fixes
133}
134
135pub fn remaining_issues(results: &[DiagnosticResult]) -> Vec<String> {
141 results
142 .iter()
143 .filter(|d| d.status != CheckStatus::Pass)
144 .map(|d| format!("{}: {}", d.check_name, d.message))
145 .collect()
146}
147
148pub fn next_steps(results: &[DiagnosticResult]) -> Vec<String> {
150 results
151 .iter()
152 .filter(|d| d.status != CheckStatus::Pass)
153 .filter_map(|d| d.remediation.clone())
154 .collect()
155}
156
157pub async fn run_auto_fix_all(state: &EnvironmentState, repo_path: &str) -> FixReport {
167 run_auto_fix_all_with(state, repo_path, true).await
168}
169
170pub async fn run_auto_fix_safe(state: &EnvironmentState, repo_path: &str) -> FixReport {
172 run_auto_fix_all_with(state, repo_path, false).await
173}
174
175async fn run_auto_fix_all_with(
176 state: &EnvironmentState,
177 repo_path: &str,
178 include_deps: bool,
179) -> FixReport {
180 let before_score = state.health_score.percentage;
181 let fixes = build_auto_fixes(state, repo_path, include_deps);
182
183 println!("{}", "🔧 RUNNING AUTO-FIX SUITE".bold().cyan());
184
185 let mut applied = 0u32;
186 let mut failed = 0u32;
187 for fix in &fixes {
188 println!(" {} {}...", "⏳".dimmed(), action_phrase(fix).bold());
189 for line in fix.preview_fix(repo_path).lines() {
190 println!(" {}", line.dimmed());
191 }
192 match fixes::execute_fix(fix, repo_path).await {
193 Ok(log) => {
194 applied += 1;
195 for line in log.lines() {
196 println!(" {line}");
197 }
198 }
199 Err(err) => {
200 failed += 1;
201 for line in err.lines() {
202 println!(" {}", line.red());
203 }
204 }
205 }
206 }
207
208 if fixes.is_empty() {
209 println!(" {} No fixable issues detected.", "✓".green().bold());
210 }
211 println!();
212
213 let after = diagnostics::run_full_diagnostics(repo_path);
214 let report = FixReport {
215 fixes_applied: applied,
216 fixes_failed: failed,
217 before_score,
218 after_score: after.health_score.percentage,
219 issues_remaining: remaining_issues(&after.diagnostics),
220 next_steps: next_steps(&after.diagnostics),
221 };
222
223 println!("{}", render_auto_fix_report(&report));
224 report
225}
226
227fn action_phrase(fix: &Fix) -> String {
229 match &fix.command {
230 FixCommand::CopyFile { src, dst } => format!("Copying {src} → {dst}"),
231 FixCommand::KillProcess { pid } => format!("Terminating process PID {pid}"),
232 FixCommand::RunCommand { cmd, args } => {
233 format!("Running `{} {}`", cmd, args.join(" "))
234 }
235 FixCommand::CreateFile { path, .. } => format!("Creating {path}"),
236 FixCommand::DeleteFile { path } => format!("Deleting {path}"),
237 }
238}
239
240pub async fn run_auto_fix(safe: bool) {
248 let state = diagnostics::build_snapshot(".");
249 if safe {
250 run_auto_fix_safe(&state, ".").await;
251 } else {
252 run_auto_fix_all(&state, ".").await;
253 }
254}
255
256pub fn render_auto_fix_report(report: &FixReport) -> String {
278 render_report_inner(report, true)
279}
280
281pub fn render_auto_fix_report_plain(report: &FixReport) -> String {
283 render_report_inner(report, false)
284}
285
286#[derive(Debug, Clone, Copy, PartialEq, Eq)]
288enum RowStyle {
289 Plain,
290 Border,
291 Title,
292 Score,
293 Status(HealthStatus),
294 Launch,
295 Warn,
296}
297
298fn classify(score: u32) -> HealthStatus {
301 match score {
302 85..=100 => HealthStatus::Healthy,
303 60..=84 => HealthStatus::Caution,
304 _ => HealthStatus::Critical,
305 }
306}
307
308fn status_label(status: HealthStatus) -> &'static str {
309 match status {
310 HealthStatus::Healthy => "Healthy - Ready to Launch!",
311 HealthStatus::Caution => "Caution - Some checks need attention",
312 HealthStatus::Critical => "Critical - Manual help needed",
313 }
314}
315
316fn render_report_inner(report: &FixReport, colored: bool) -> String {
317 let status = classify(report.after_score);
318 let score_row = format!(
319 "Health Score: {}% → {}%{}",
320 report.before_score,
321 report.after_score,
322 delta_mark(report)
323 );
324
325 let mut rows: Vec<(RowStyle, String)> = Vec::new();
326 rows.push((RowStyle::Border, border_line(true)));
327 rows.push((RowStyle::Title, box_row("🔧 AUTO-FIX REPORT")));
328 rows.push((RowStyle::Border, separator_line()));
329 rows.push((RowStyle::Score, box_row(&score_row)));
330 rows.push((
331 RowStyle::Status(status),
332 box_row(&format!("Status: {}", status_label(status))),
333 ));
334
335 if report.issues_remaining.is_empty() {
336 rows.push((RowStyle::Plain, box_row("")));
337 rows.push((RowStyle::Launch, box_row("🚀 System ready for launch! ⚡")));
338 } else {
339 let n = report.issues_remaining.len();
340 rows.push((RowStyle::Plain, box_row("")));
341 rows.push((
342 RowStyle::Warn,
343 box_row(&format!(
344 "⚠ {n} issue{} remaining:",
345 if n == 1 { "" } else { "s" }
346 )),
347 ));
348 for issue in &report.issues_remaining {
349 rows.extend(
350 wrapped_rows(&format!("• {issue}"))
351 .into_iter()
352 .map(|row| (RowStyle::Plain, row)),
353 );
354 }
355 if !report.next_steps.is_empty() {
356 rows.push((RowStyle::Plain, box_row("")));
357 rows.push((RowStyle::Warn, box_row("Next steps:")));
358 for step in &report.next_steps {
359 rows.extend(
360 wrapped_rows(&format!("• {step}"))
361 .into_iter()
362 .map(|row| (RowStyle::Plain, row)),
363 );
364 }
365 }
366 }
367
368 if report.fixes_failed > 0 {
369 rows.push((RowStyle::Plain, box_row("")));
370 rows.push((
371 RowStyle::Warn,
372 box_row(&format!(
373 "⚠ {} fix{} failed — read the output above",
374 report.fixes_failed,
375 if report.fixes_failed == 1 { "" } else { "es" }
376 )),
377 ));
378 }
379
380 rows.push((RowStyle::Border, border_line(false)));
381
382 let mut out = String::new();
383 for (style, row) in rows {
384 out.push_str(&paint(row, style, colored));
385 out.push('\n');
386 }
387 out
388}
389
390fn delta_mark(report: &FixReport) -> &'static str {
393 if !report.issues_remaining.is_empty() {
394 ""
395 } else if report.improved() {
396 " 🎉"
397 } else {
398 " ✨"
399 }
400}
401
402fn paint(row: String, style: RowStyle, colored: bool) -> String {
404 if !colored {
405 return row;
406 }
407 match style {
408 RowStyle::Plain => row.normal().to_string(),
409 RowStyle::Border | RowStyle::Title => row.cyan().to_string(),
410 RowStyle::Score => row.normal().to_string(),
411 RowStyle::Status(HealthStatus::Healthy) => row.green().bold().to_string(),
412 RowStyle::Status(HealthStatus::Caution) => row.yellow().bold().to_string(),
413 RowStyle::Status(HealthStatus::Critical) => row.red().bold().to_string(),
414 RowStyle::Launch => row.green().bold().to_string(),
415 RowStyle::Warn => row.yellow().to_string(),
416 }
417}
418
419fn border_line(top: bool) -> String {
421 let (left, right) = if top { ('┌', '┐') } else { ('└', '┘') };
422 format!("{left}{}{right}", "─".repeat(REPORT_WIDTH - 2))
423}
424
425fn separator_line() -> String {
426 format!("├{}┤", "─".repeat(REPORT_WIDTH - 2))
427}
428
429fn box_row(content: &str) -> String {
431 format!("│ {} │", pad(content))
432}
433
434fn pad(content: &str) -> String {
435 let used = content.chars().count();
436 format!("{content}{}", " ".repeat(INNER_WIDTH.saturating_sub(used)))
437}
438
439fn wrapped_rows(text: &str) -> Vec<String> {
441 wrap(text, INNER_WIDTH - 4)
442 .into_iter()
443 .map(|line| box_row(&line))
444 .collect()
445}
446
447fn wrap(text: &str, width: usize) -> Vec<String> {
450 if text.is_empty() || width == 0 {
451 return vec![String::new()];
452 }
453
454 let mut lines = Vec::new();
455 let mut current = String::new();
456
457 for word in text.split(' ') {
458 let word_len = word.chars().count();
459 if word_len == 0 {
460 continue;
461 }
462 if word_len > width {
463 if !current.is_empty() {
464 lines.push(std::mem::take(&mut current));
465 }
466 let mut chunk = String::new();
467 for ch in word.chars() {
468 if chunk.chars().count() == width {
469 lines.push(std::mem::take(&mut chunk));
470 }
471 chunk.push(ch);
472 }
473 current = chunk;
474 } else if current.is_empty() {
475 current.push_str(word);
476 } else if current.chars().count() + 1 + word_len <= width {
477 current.push(' ');
478 current.push_str(word);
479 } else {
480 lines.push(std::mem::take(&mut current));
481 current.push_str(word);
482 }
483 }
484
485 if !current.is_empty() {
486 lines.push(current);
487 }
488 if lines.is_empty() {
489 lines.push(String::new());
490 }
491 lines
492}
493
494#[cfg(test)]
495mod tests {
496 use super::*;
497 use crate::models::{HealthScore, ProjectStack};
498 use std::fs;
499 use std::path::PathBuf;
500 use std::time::{SystemTime, UNIX_EPOCH};
501
502 struct TempDir {
503 path: PathBuf,
504 }
505
506 impl TempDir {
507 fn new(label: &str) -> Self {
508 let stamp = SystemTime::now()
509 .duration_since(UNIX_EPOCH)
510 .expect("system clock")
511 .as_nanos();
512 let path = std::env::temp_dir().join(format!("limitless_autofix_{label}_{stamp}"));
513 fs::create_dir_all(&path).expect("create temp dir");
514 TempDir { path }
515 }
516
517 fn path(&self) -> &PathBuf {
518 &self.path
519 }
520
521 fn write(self, relative: &str, content: &str) -> Self {
522 let full = self.path.join(relative);
523 if let Some(parent) = full.parent() {
524 fs::create_dir_all(parent).expect("create parent dirs");
525 }
526 fs::write(full, content).expect("write fixture file");
527 self
528 }
529 }
530
531 impl Drop for TempDir {
532 fn drop(&mut self) {
533 let _ = fs::remove_dir_all(&self.path);
534 }
535 }
536
537 fn node_state() -> EnvironmentState {
538 EnvironmentState {
539 detected_stack: ProjectStack::Node {
540 version: "18.12.0".into(),
541 package_manager: "npm".into(),
542 },
543 runtime_version: Some("v18.12.0".into()),
544 env_file_exists: false,
545 env_example_exists: true,
546 dependencies_healthy: false,
547 blocked_ports: vec![(3000, 9921)],
548 diagnostics: vec![],
549 health_score: HealthScore::from_counts(1, 0, 2),
550 }
551 }
552
553 fn empty_state() -> EnvironmentState {
554 EnvironmentState {
555 detected_stack: ProjectStack::Unknown,
556 runtime_version: None,
557 env_file_exists: false,
558 env_example_exists: false,
559 dependencies_healthy: true,
560 blocked_ports: vec![],
561 diagnostics: vec![],
562 health_score: HealthScore::default(),
563 }
564 }
565
566 #[test]
569 fn build_auto_fixes_orders_kill_then_copy_then_install() {
570 let state = node_state();
571 let fixes = build_auto_fixes(&state, ".", true);
572 let ids: Vec<&str> = fixes.iter().map(|f| f.id.as_str()).collect();
573 assert_eq!(
574 ids,
575 vec![
576 "kill-ghost-9921",
577 "copy-env-from-example",
578 "install-dependencies-npm"
579 ]
580 );
581 }
582
583 #[test]
584 fn build_auto_fixes_safe_mode_skips_install() {
585 let state = node_state();
586 let fixes = build_auto_fixes(&state, ".", false);
587 let ids: Vec<&str> = fixes.iter().map(|f| f.id.as_str()).collect();
588 assert_eq!(ids, vec!["kill-ghost-9921", "copy-env-from-example"]);
589 }
590
591 #[test]
592 fn build_auto_fixes_skips_copy_when_env_exists() {
593 let mut state = node_state();
594 state.env_file_exists = true;
595 let fixes = build_auto_fixes(&state, ".", true);
596 let ids: Vec<&str> = fixes.iter().map(|f| f.id.as_str()).collect();
597 assert_eq!(ids, vec!["kill-ghost-9921", "install-dependencies-npm"]);
598 }
599
600 #[test]
601 fn build_auto_fixes_skips_kill_when_no_blocked_ports() {
602 let mut state = node_state();
603 state.blocked_ports = vec![];
604 let fixes = build_auto_fixes(&state, ".", true);
605 let ids: Vec<&str> = fixes.iter().map(|f| f.id.as_str()).collect();
606 assert_eq!(ids, vec!["copy-env-from-example", "install-dependencies-npm"]);
607 }
608
609 #[test]
610 fn build_auto_fixes_skips_install_for_unknown_stack() {
611 let mut state = node_state();
612 state.detected_stack = ProjectStack::Unknown;
613 let fixes = build_auto_fixes(&state, ".", true);
614 let ids: Vec<&str> = fixes.iter().map(|f| f.id.as_str()).collect();
615 assert_eq!(ids, vec!["kill-ghost-9921", "copy-env-from-example"]);
616 }
617
618 #[test]
619 fn build_auto_fixes_empty_when_nothing_applicable() {
620 assert!(build_auto_fixes(&empty_state(), ".", true).is_empty());
621 }
622
623 #[test]
626 fn remaining_issues_lists_non_passing_checks() {
627 let results = vec![
628 DiagnosticResult::new("Env Audit", CheckStatus::Pass, "ok"),
629 DiagnosticResult::new(
630 "Broken PATH entries",
631 CheckStatus::Warn,
632 "1 entry points to a missing folder",
633 ),
634 DiagnosticResult::new("Tool node", CheckStatus::Fail, "node not found on PATH"),
635 ];
636 assert_eq!(
637 remaining_issues(&results),
638 vec![
639 "Broken PATH entries: 1 entry points to a missing folder".to_string(),
640 "Tool node: node not found on PATH".to_string()
641 ]
642 );
643 }
644
645 #[test]
646 fn next_steps_uses_remediation_of_non_passing_checks() {
647 let results = vec![
648 DiagnosticResult::new("Env Audit", CheckStatus::Fail, ".env missing")
649 .with_remediation("Copy .env.example to .env"),
650 DiagnosticResult::new("Editor", CheckStatus::Warn, "EDITOR unset")
651 .with_remediation("export EDITOR=\"code --wait\""),
652 DiagnosticResult::new("Proxy", CheckStatus::Pass, "fine"),
653 ];
654 assert_eq!(
655 next_steps(&results),
656 vec![
657 "Copy .env.example to .env".to_string(),
658 "export EDITOR=\"code --wait\"".to_string()
659 ]
660 );
661 }
662
663 #[test]
664 fn report_classifies_health_and_improvement() {
665 let clean = FixReport {
666 fixes_applied: 2,
667 fixes_failed: 0,
668 before_score: 50,
669 after_score: 100,
670 issues_remaining: vec![],
671 next_steps: vec![],
672 };
673 assert!(clean.is_clean());
674 assert!(clean.improved());
675
676 let dirty = FixReport {
677 fixes_applied: 1,
678 fixes_failed: 1,
679 before_score: 50,
680 after_score: 70,
681 issues_remaining: vec!["Tool node: missing".into()],
682 next_steps: vec!["Install node".into()],
683 };
684 assert!(!dirty.is_clean());
685 assert!(dirty.improved());
686 assert_eq!(classify(dirty.after_score), HealthStatus::Caution);
687 assert_eq!(classify(clean.after_score), HealthStatus::Healthy);
688 }
689
690 #[tokio::test]
693 async fn auto_fix_copies_env_and_reports_counts() {
694 let dir = TempDir::new("copy_env").write(".env.example", "PORT=3000\n");
695 let mut state = empty_state();
696 state.env_example_exists = true;
697 state.dependencies_healthy = true;
698 let repo = dir.path().to_str().unwrap().to_string();
699
700 let report = run_auto_fix_all(&state, &repo).await;
701
702 assert_eq!(report.fixes_applied, 1);
703 assert_eq!(report.fixes_failed, 0);
704 assert_eq!(report.before_score, 100);
705 assert!(report.after_score <= 100);
706 let content = fs::read_to_string(dir.path().join(".env")).unwrap();
707 assert_eq!(content, "PORT=3000\n");
708 }
709
710 #[tokio::test]
711 async fn auto_fix_skips_missing_ghost_process() {
712 let dir = TempDir::new("kill_skip");
713 let mut state = empty_state();
714 state.blocked_ports = vec![(3000, 999_999_999)];
715 let repo = dir.path().to_str().unwrap().to_string();
716
717 let report = run_auto_fix_all(&state, &repo).await;
718
719 assert_eq!(report.fixes_applied, 1, "skip still counts as applied");
720 assert_eq!(report.fixes_failed, 0);
721 }
722
723 #[tokio::test]
724 async fn auto_fix_does_not_create_env_without_template() {
725 let dir = TempDir::new("no_template");
726 let repo = dir.path().to_str().unwrap().to_string();
727
728 let report = run_auto_fix_all(&empty_state(), &repo).await;
729
730 assert_eq!(report.fixes_applied, 0);
731 assert!(!dir.path().join(".env").exists());
732 }
733
734 #[test]
737 fn report_box_plain_lines_are_exact_width() {
738 let clean = FixReport {
739 fixes_applied: 2,
740 fixes_failed: 0,
741 before_score: 50,
742 after_score: 100,
743 issues_remaining: vec![],
744 next_steps: vec![],
745 };
746 let out = render_auto_fix_report_plain(&clean);
747 for line in out.lines() {
748 assert_eq!(
749 line.chars().count(),
750 REPORT_WIDTH,
751 "wrong width: {line:?}"
752 );
753 }
754 assert!(!out.contains('\x1b'));
755 assert!(out.contains("Health Score: 50% → 100% 🎉"));
756 assert!(out.contains("Status: Healthy - Ready to Launch!"));
757 assert!(out.contains("🚀 System ready for launch! ⚡"));
758 }
759
760 #[test]
761 fn report_box_plain_lists_remaining_and_next_steps() {
762 let dirty = FixReport {
763 fixes_applied: 1,
764 fixes_failed: 1,
765 before_score: 20,
766 after_score: 60,
767 issues_remaining: vec![
768 "Env Audit: .env file missing".into(),
769 ],
770 next_steps: vec!["Copy .env.example to .env".into()],
771 };
772 let out = render_auto_fix_report_plain(&dirty);
773 assert!(out.contains("Health Score: 20% → 60%"));
774 assert!(out.contains("Status: Caution - Some checks need attention"));
775 assert!(out.contains("1 issue remaining:"));
776 assert!(out.contains("Env Audit: .env file missing"));
777 assert!(out.contains("Next steps:"));
778 assert!(out.contains("Copy .env.example to .env"));
779 assert!(out.contains("1 fix failed"));
780 assert!(!out.contains("System ready for launch"));
781 }
782
783 #[test]
784 fn report_box_plain_keeps_width_with_long_issues() {
785 let report = FixReport {
786 fixes_failed: 0,
787 fixes_applied: 0,
788 before_score: 0,
789 after_score: 40,
790 issues_remaining: vec![
791 "Tool go: go was not found on PATH, which means Go-based tooling cannot run".into(),
792 ],
793 next_steps: vec!["Install go and add it to PATH before continuing".into()],
794 };
795 let out = render_auto_fix_report_plain(&report);
796 for line in out.lines() {
797 assert_eq!(line.chars().count(), REPORT_WIDTH);
798 }
799 assert!(out.contains("1 issue remaining:"));
800 }
801
802 #[test]
803 fn report_box_default_render_is_clean() {
804 let out = render_auto_fix_report_plain(&FixReport::default());
805 assert!(out.contains("System ready for launch! ⚡"));
806 assert!(out.contains("Health Score: 0% → 0% ✨"));
807 }
808
809 #[test]
810 fn colored_report_box_contains_ansi() {
811 colored::control::set_override(true);
812 let report = FixReport {
813 fixes_applied: 2,
814 fixes_failed: 0,
815 before_score: 50,
816 after_score: 100,
817 issues_remaining: vec![],
818 next_steps: vec![],
819 };
820 let out = render_auto_fix_report(&report);
821 assert!(out.contains("\x1b["));
822 assert!(out.contains("\x1b[0m"));
823 colored::control::unset_override();
824 }
825}