use colored::Colorize;
use crate::models::{CheckStatus, DiagnosticResult, EnvironmentState, HealthStatus};
use crate::modules::diagnostics;
use crate::modules::fixes::{self, Fix, FixCommand};
pub const REPORT_WIDTH: usize = 60;
const INNER_WIDTH: usize = REPORT_WIDTH - 4;
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct FixReport {
pub fixes_applied: u32,
pub fixes_failed: u32,
pub before_score: u32,
pub after_score: u32,
pub issues_remaining: Vec<String>,
pub next_steps: Vec<String>,
}
impl FixReport {
pub fn is_clean(&self) -> bool {
self.issues_remaining.is_empty() && self.fixes_failed == 0
}
pub fn improved(&self) -> bool {
self.after_score > self.before_score
}
}
pub fn build_auto_fixes(
state: &EnvironmentState,
repo_path: &str,
include_deps: bool,
) -> Vec<Fix> {
let mut fixes = Vec::new();
for (port, pid) in &state.blocked_ports {
fixes.push(fixes::kill_ghost_process(*port, *pid));
}
if state.env_example_exists && !state.env_file_exists {
if let Some(fix) = fixes::copy_env_from_example(".env.example", ".env") {
fixes.push(fix);
}
}
if include_deps && !state.dependencies_healthy {
if let Some(fix) = fixes::install_fix_for_stack(&state.detected_stack) {
fixes.push(fix);
}
}
let _ = repo_path;
fixes
}
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()
}
pub fn next_steps(results: &[DiagnosticResult]) -> Vec<String> {
results
.iter()
.filter(|d| d.status != CheckStatus::Pass)
.filter_map(|d| d.remediation.clone())
.collect()
}
pub async fn run_auto_fix_all(state: &EnvironmentState, repo_path: &str) -> FixReport {
run_auto_fix_all_with(state, repo_path, true).await
}
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
}
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}"),
}
}
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;
}
}
pub fn render_auto_fix_report(report: &FixReport) -> String {
render_report_inner(report, true)
}
pub fn render_auto_fix_report_plain(report: &FixReport) -> String {
render_report_inner(report, false)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RowStyle {
Plain,
Border,
Title,
Score,
Status(HealthStatus),
Launch,
Warn,
}
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
}
fn delta_mark(report: &FixReport) -> &'static str {
if !report.issues_remaining.is_empty() {
""
} else if report.improved() {
" 🎉"
} else {
" ✨"
}
}
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(),
}
}
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))
}
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)))
}
fn wrapped_rows(text: &str) -> Vec<String> {
wrap(text, INNER_WIDTH - 4)
.into_iter()
.map(|line| box_row(&line))
.collect()
}
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(),
}
}
#[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());
}
#[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);
}
#[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());
}
#[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();
}
}