Skip to main content

limitless_cli/modules/
fixes.rs

1//! Environment-repair engine for `limit fix`.
2//!
3//! Models an actionable repair as a [`Fix`] (a description of *what* changes
4//! and *how*), then applies it through [`execute_fix`]:
5//!
6//! 1. **Validate** the fix is safe (source exists / PID is plausible).
7//! 2. **Preview** the before/after state.
8//! 3. **Execute** the underlying command or file operation.
9//! 4. **Capture** stdout/stderr into the result logs.
10//! 5. **Verify** the fix actually worked (re-check the file system / process).
11//! 6. **Roll back** automatically when a reversible fix fails.
12//!
13//! The four built-in fixes are:
14//!
15//! - [`copy_env_from_example`] — `.env.example` → `.env` (reversible).
16//! - [`kill_ghost_process`] — terminate a process stuck on a port.
17//! - [`install_fix_for_stack`] — `npm install` / `pip install` / `cargo build`.
18//! - [`missing_config_files`] — create `.gitignore` and `.editorconfig`.
19//!
20//! All file operations are **non-destructive by default**: [`execute_fix`]
21//! refuses to overwrite an existing target; pass an overwrite-acknowledging
22//! variant (see [`execute_fix_with`]) after the user has been asked.
23
24use colored::Colorize;
25use std::fs;
26use std::io::ErrorKind;
27use std::path::Path;
28use std::process::Command;
29
30use crate::models::{EnvironmentState, ProjectStack};
31
32// ---------------------------------------------------------------------------
33// Model
34// ---------------------------------------------------------------------------
35
36/// A single, idempotent repair with enough metadata for safe auto-application.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Fix {
39    /// Stable machine-readable identifier (e.g. `"copy-env-from-example"`).
40    pub id: String,
41    /// Short human name shown in the fix list (e.g. "Copy .env.example").
42    pub name: String,
43    /// One-sentence description of what the fix does.
44    pub description: String,
45    /// The concrete action to perform.
46    pub command: FixCommand,
47    /// Whether a failed application can be undone (rollback).
48    pub reversible: bool,
49    /// Whether the CLI must ask the user before applying this fix.
50    pub requires_approval: bool,
51}
52
53impl Fix {
54    fn new(
55        id: impl Into<String>,
56        name: impl Into<String>,
57        description: impl Into<String>,
58        command: FixCommand,
59        reversible: bool,
60        requires_approval: bool,
61    ) -> Self {
62        Self {
63            id: id.into(),
64            name: name.into(),
65            description: description.into(),
66            command,
67            reversible,
68            requires_approval,
69        }
70    }
71}
72
73/// The concrete action a [`Fix`] performs, expressed against the repo root.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum FixCommand {
76    /// Copy `src` (relative to the repo root) to `dst`.
77    CopyFile { src: String, dst: String },
78    /// Run a program with arguments (e.g. `npm install`).
79    RunCommand { cmd: String, args: Vec<String> },
80    /// Write `content` to `path` with `.gitignore`-style defaults.
81    CreateFile { path: String, content: String },
82    /// Terminate the process with the given PID (platform-aware).
83    KillProcess { pid: u32 },
84    /// Remove a file relative to the repo root.
85    DeleteFile { path: String },
86}
87
88// ---------------------------------------------------------------------------
89// Shared constants
90// ---------------------------------------------------------------------------
91
92/// Shown whenever an operation smells like a permission problem.
93const PERMISSION_HINT: &str = "\n  Tip: this looks like a permission error — retry from an \
94                               elevated terminal (sudo on macOS/Linux, \"Run as administrator\" on \
95                               Windows).";
96
97/// Default `.gitignore` coverage for common stacks.
98pub const DEFAULT_GITIGNORE: &str = "node_modules/\ntarget/\n__pycache__/\n.venv/\nvenv/\n\
99.env\n.env.local\n.idea/\n.vscode/\n*.swp\n.DS_Store\n";
100
101/// Default `.editorconfig` with sensible cross-editor settings.
102pub const DEFAULT_EDITORCONFIG: &str = "root = true\n\n\
103[*]\ncharset = utf-8\nend_of_line = lf\nindent_style = space\nindent_size = 2\n\
104insert_final_newline = true\ntrim_trailing_whitespace = true\n";
105
106// ---------------------------------------------------------------------------
107// Built-in fixes (factories)
108// ---------------------------------------------------------------------------
109
110/// Builds the reversible `.env.example → .env` copy fix, if applicable.
111///
112/// Returns `None` when there is no template to copy from.
113///
114/// ```
115/// use limitless_cli::modules::fixes::{copy_env_from_example, FixCommand};
116///
117/// let fix = copy_env_from_example(".env.example", ".env");
118/// let fix = fix.expect("copy fix is always built from explicit paths");
119/// assert_eq!(fix.reversible, true);
120/// assert_eq!(fix.requires_approval, true);
121/// assert!(matches!(fix.command, FixCommand::CopyFile { .. }));
122/// ```
123pub fn copy_env_from_example(src: &str, dst: &str) -> Option<Fix> {
124    let src = src.to_string();
125    let dst = dst.to_string();
126    Some(Fix::new(
127        "copy-env-from-example",
128        format!("Copy {src} to {dst}"),
129        format!("Copies the {src} template into {dst} so the app can read its configuration."),
130        FixCommand::CopyFile { src, dst },
131        true,
132        true,
133    ))
134}
135
136/// Builds the kill-ghost-process fix for a blocked port.
137///
138/// The kill command itself is chosen at execution time per platform
139/// (`taskkill` on Windows, `kill` elsewhere), so this factory is
140/// platform-agnostic.
141///
142/// ```
143/// use limitless_cli::modules::fixes::{kill_ghost_process, FixCommand};
144///
145/// let fix = kill_ghost_process(3000, 9921);
146/// assert_eq!(fix.reversible, false);
147/// assert_eq!(fix.requires_approval, true);
148/// assert!(matches!(fix.command, FixCommand::KillProcess { pid: 9921 }));
149/// ```
150pub fn kill_ghost_process(port: u16, pid: u32) -> Fix {
151    Fix::new(
152        format!("kill-ghost-{pid}"),
153        format!("Kill ghost process {pid}"),
154        format!(
155            "A leftover process (PID {pid}) is still holding port {port}. Killing it frees the \
156             port for your app."
157        ),
158        FixCommand::KillProcess { pid },
159        false,
160        true,
161    )
162}
163
164/// Builds the missing-dependencies install fix for a detected stack.
165///
166/// Returns `None` for stacks with no well-known package manager.
167///
168/// ```
169/// use limitless_cli::models::ProjectStack;
170/// use limitless_cli::modules::fixes::{install_fix_for_stack, FixCommand};
171///
172/// let node = install_fix_for_stack(&ProjectStack::Node {
173///     version: "22.9.0".into(),
174///     package_manager: "npm".into(),
175/// });
176/// let fix = node.expect("Node uses npm");
177/// assert!(matches!(fix.command, FixCommand::RunCommand { ref cmd, .. } if cmd == "npm"));
178/// ```
179pub fn install_fix_for_stack(stack: &ProjectStack) -> Option<Fix> {
180    let (cmd, args, display) = match stack {
181        ProjectStack::Node {
182            package_manager, ..
183        } => {
184            let pm = match package_manager.as_str() {
185                "yarn" => "yarn",
186                "pnpm" => "pnpm",
187                _ => "npm",
188            };
189            (pm, vec!["install".to_string()], package_manager.as_str())
190        }
191        ProjectStack::Python { .. } => (
192            "pip",
193            vec![
194                "install".to_string(),
195                "-r".to_string(),
196                "requirements.txt".to_string(),
197            ],
198            "pip install -r requirements.txt",
199        ),
200        ProjectStack::Rust { .. } => ("cargo", vec!["build".to_string()], "cargo build"),
201        ProjectStack::Go { .. } => (
202            "go",
203            vec!["mod".to_string(), "download".to_string()],
204            "go mod download",
205        ),
206        ProjectStack::Java { .. } => ("mvn", vec!["install".to_string()], "mvn install"),
207        ProjectStack::Docker | ProjectStack::Unknown => return None,
208    };
209    Some(Fix::new(
210        format!("install-dependencies-{cmd}"),
211        format!("{display} for {}", stack.label()),
212        format!("Restores missing packages with `{display}`, so imports and builds resolve again."),
213        FixCommand::RunCommand {
214            cmd: cmd.to_string(),
215            args,
216        },
217        false,
218        true,
219    ))
220}
221
222/// Builds [fixes] that create well-known config files when they are missing
223/// (`.gitignore` and `.editorconfig`). Existing files are never offered for
224/// recreation.
225pub fn missing_config_files(repo_path: &str) -> Vec<Fix> {
226    let root = Path::new(repo_path);
227    let mut fixes = Vec::new();
228
229    if !root.join(".gitignore").is_file() {
230        fixes.push(Fix::new(
231            "create-gitignore",
232            "Create .gitignore",
233            "Adds a starter .gitignore so build artifacts and secrets stay out of version control.",
234            FixCommand::CreateFile {
235                path: ".gitignore".to_string(),
236                content: DEFAULT_GITIGNORE.to_string(),
237            },
238            true,
239            false,
240        ));
241    }
242    if !root.join(".editorconfig").is_file() {
243        fixes.push(Fix::new(
244            "create-editorconfig",
245            "Create .editorconfig",
246            "Adds a starter .editorconfig to keep formatting consistent across editors.",
247            FixCommand::CreateFile {
248                path: ".editorconfig".to_string(),
249                content: DEFAULT_EDITORCONFIG.to_string(),
250            },
251            true,
252            false,
253        ));
254    }
255    fixes
256}
257
258/// Collects every fix applicable to an [`EnvironmentState`] snapshot:
259///
260/// 1. Copy `.env.example` → `.env` when the `.env` is missing.
261/// 2. Kill each ghost process on a blocked port.
262/// 3. Install missing dependencies for the detected stack.
263/// 4. Create missing `.gitignore` / `.editorconfig`.
264pub fn recommended_fixes(state: &EnvironmentState, repo_path: &str) -> Vec<Fix> {
265    let mut fixes = Vec::new();
266
267    if state.env_example_exists && !state.env_file_exists {
268        if let Some(fix) = copy_env_from_example(".env.example", ".env") {
269            fixes.push(fix);
270        }
271    }
272
273    for (port, pid) in &state.blocked_ports {
274        fixes.push(kill_ghost_process(*port, *pid));
275    }
276
277    if !state.dependencies_healthy {
278        if let Some(fix) = install_fix_for_stack(&state.detected_stack) {
279            fixes.push(fix);
280        }
281    }
282
283    fixes.extend(missing_config_files(repo_path));
284    fixes
285}
286
287// ---------------------------------------------------------------------------
288// Preview
289// ---------------------------------------------------------------------------
290
291/// Renders a before/after preview for a fix against `repo_path`.
292///
293/// ```
294/// use limitless_cli::modules::fixes::kill_ghost_process;
295///
296/// let preview = kill_ghost_process(3000, 9921).preview_fix(".");
297/// assert!(preview.contains("Before:"));
298/// assert!(preview.contains("After:"));
299/// ```
300///
301/// This is a thin wrapper over [`preview_fix`] for ergonomic chaining.
302impl Fix {
303    pub fn preview_fix(&self, repo_path: &str) -> String {
304        preview_fix(self, repo_path)
305    }
306}
307
308/// Renders a before/after preview of what `fix` will do in `repo_path`.
309pub fn preview_fix(fix: &Fix, repo_path: &str) -> String {
310    let root = Path::new(repo_path);
311    let state = |rel: &str| {
312        if root.join(rel).exists() {
313            "present"
314        } else {
315            "missing"
316        }
317    };
318
319    match &fix.command {
320        FixCommand::CopyFile { src, dst } => format!(
321            "Before: {src} is {}, {dst} is {}\nAfter:  copies {src} → {dst}",
322            state(src),
323            state(dst)
324        ),
325        FixCommand::CreateFile { path, .. } => {
326            format!(
327                "Before: {path} is {}\nAfter:  creates {path} with starter settings",
328                state(path)
329            )
330        }
331        FixCommand::DeleteFile { path } => {
332            format!("Before: {path} is {}\nAfter:  deletes {path}", state(path))
333        }
334        FixCommand::KillProcess { pid } => format!(
335            "Before: process {pid} is {}\nAfter:  terminates process {pid}",
336            if process_exists(*pid) {
337                "running"
338            } else {
339                "not running"
340            }
341        ),
342        FixCommand::RunCommand { cmd, args } => format!(
343            "Before: dependency state unknown\nAfter:  runs `{} {}`",
344            cmd,
345            args.join(" ")
346        ),
347    }
348}
349
350// ---------------------------------------------------------------------------
351// Execution
352// ---------------------------------------------------------------------------
353
354/// Applies `fix` inside `repo_path`, **refusing to overwrite** existing files.
355///
356/// Returns a human-readable log (preview + executed command + verification)
357/// on success, or a `String` error describing why it failed.
358///
359/// Use [`execute_fix_with`] to acknowledge an overwrite after asking the user.
360pub async fn execute_fix(fix: &Fix, repo_path: &str) -> Result<String, String> {
361    execute_fix_with(fix, repo_path, false).await
362}
363
364/// Applies `fix`, allowing overwrite when `allow_overwrite` is set.
365///
366/// This is the same pipeline as [`execute_fix`] but with the non-destructive
367/// overwrite guard lifted; call it only after the user approved overwriting.
368pub async fn execute_fix_with(
369    fix: &Fix,
370    repo_path: &str,
371    allow_overwrite: bool,
372) -> Result<String, String> {
373    validate_fix(fix)?;
374    let preview = preview_fix(fix, repo_path);
375
376    let result = match &fix.command {
377        FixCommand::CopyFile { src, dst } => run_copy(fix, repo_path, src, dst, allow_overwrite),
378        FixCommand::CreateFile { path, content } => {
379            run_create(fix, repo_path, path, content, allow_overwrite)
380        }
381        FixCommand::DeleteFile { path } => run_delete(fix, repo_path, path),
382        FixCommand::KillProcess { pid } => run_kill(fix, *pid).await,
383        FixCommand::RunCommand { cmd, args } => run_command(fix, cmd, args).await,
384    };
385
386    result.map(|log| format!("{preview}\n{log}"))
387}
388
389/// Rejects fixes that can never be valid (empty paths, PID 0).
390fn validate_fix(fix: &Fix) -> Result<(), String> {
391    match &fix.command {
392        FixCommand::CopyFile { src, dst } => {
393            if src.trim().is_empty() || dst.trim().is_empty() {
394                Err(format!(
395                    "✗ {} — source and destination paths must not be empty.",
396                    fix.name
397                ))
398            } else {
399                Ok(())
400            }
401        }
402        FixCommand::CreateFile { path, .. } | FixCommand::DeleteFile { path } => {
403            if path.trim().is_empty() {
404                Err(format!("✗ {} — file path must not be empty.", fix.name))
405            } else {
406                Ok(())
407            }
408        }
409        FixCommand::KillProcess { pid } => {
410            if *pid == 0 {
411                Err(format!("✗ {} — PID 0 is never a real process.", fix.name))
412            } else {
413                Ok(())
414            }
415        }
416        FixCommand::RunCommand { cmd, .. } => {
417            if cmd.trim().is_empty() {
418                Err(format!("✗ {} — command must not be empty.", fix.name))
419            } else {
420                Ok(())
421            }
422        }
423    }
424}
425
426// --- CopyFile ------------------------------------------------------------
427
428fn run_copy(
429    fix: &Fix,
430    repo_path: &str,
431    src: &str,
432    dst: &str,
433    allow_overwrite: bool,
434) -> Result<String, String> {
435    let root = Path::new(repo_path);
436    let src_path = root.join(src);
437    let dst_path = root.join(dst);
438
439    if !src_path.is_file() {
440        return Err(format!(
441            "✗ {} — source {src} does not exist in {repo_path}.",
442            fix.name
443        ));
444    }
445
446    let backup = read_opt(&dst_path);
447    let existed = backup.is_some();
448    if existed && !allow_overwrite {
449        return Err(format!(
450            "✗ {} — {dst} already exists. No changes were made; ask the user, then re-run \
451             with overwrite enabled.",
452            fix.name
453        ));
454    }
455
456    if let Err(err) = fs::copy(&src_path, &dst_path) {
457        restore(&dst_path, &backup, !existed);
458        return Err(io_fail(&fix.name, &err, &format!("copy {src} → {dst}")));
459    }
460
461    if let Err(why) = verify_copy(&src_path, &dst_path) {
462        restore(&dst_path, &backup, !existed);
463        return Err(format!(
464            "✗ {} — verification failed after the copy ({why}); the previous state was restored.",
465            fix.name
466        ));
467    }
468
469    Ok(format!(
470        "✓ {} — copied {src} → {dst} ({} bytes)\n  ✓ Verified: {dst} matches {src}",
471        fix.name,
472        file_size(&dst_path)
473    ))
474}
475
476// --- CreateFile ----------------------------------------------------------
477
478fn run_create(
479    fix: &Fix,
480    repo_path: &str,
481    path: &str,
482    content: &str,
483    allow_overwrite: bool,
484) -> Result<String, String> {
485    let dst_path = Path::new(repo_path).join(path);
486    let backup = read_opt(&dst_path);
487    let existed = backup.is_some();
488
489    if existed && !allow_overwrite {
490        return Err(format!(
491            "✗ {} — {path} already exists. No changes were made; ask the user, then re-run \
492             with overwrite enabled.",
493            fix.name
494        ));
495    }
496
497    if let Err(err) = fs::write(&dst_path, content) {
498        restore(&dst_path, &backup, !existed);
499        return Err(io_fail(&fix.name, &err, &format!("create {path}")));
500    }
501
502    if let Err(why) = verify_written(&dst_path, content) {
503        restore(&dst_path, &backup, !existed);
504        return Err(format!(
505            "✗ {} — verification failed after writing ({why}); the previous state was restored.",
506            fix.name
507        ));
508    }
509
510    Ok(format!(
511        "✓ {} — created {path} ({} bytes)\n  ✓ Verified: {path} contains the expected content",
512        fix.name,
513        file_size(&dst_path)
514    ))
515}
516
517// --- DeleteFile ----------------------------------------------------------
518
519fn run_delete(fix: &Fix, repo_path: &str, path: &str) -> Result<String, String> {
520    let dst_path = Path::new(repo_path).join(path);
521    if !dst_path.exists() {
522        return Err(format!(
523            "✗ {} — nothing to delete: {path} does not exist.",
524            fix.name
525        ));
526    }
527
528    // Snapshot so the deletion can be rolled back if verification fails.
529    let backup = read_opt(&dst_path);
530    if let Err(err) = fs::remove_file(&dst_path) {
531        return Err(io_fail(&fix.name, &err, &format!("delete {path}")));
532    }
533
534    if let Err(why) = verify_deleted(&dst_path) {
535        restore(&dst_path, &backup, false);
536        return Err(format!(
537            "✗ {} — verification failed after deleting ({why}); the file was restored.",
538            fix.name
539        ));
540    }
541
542    Ok(format!(
543        "✓ {} — deleted {path}\n  ✓ Verified: {path} no longer exists",
544        fix.name
545    ))
546}
547
548// --- KillProcess ---------------------------------------------------------
549
550async fn run_kill(fix: &Fix, pid: u32) -> Result<String, String> {
551    if !process_exists(pid) {
552        return Ok(format!(
553            "✓ {} — skipped: process {pid} is not running.",
554            fix.name
555        ));
556    }
557
558    let (tool, args) = kill_args(pid);
559    let output = match tokio::process::Command::new(tool).args(args).output().await {
560        Ok(output) => output,
561        Err(err) => return Err(describe_spawn_error(&fix.name, tool, &err)),
562    };
563
564    let stderr = String::from_utf8_lossy(&output.stderr);
565    if !output.status.success() {
566        return Err(format!(
567            "✗ {} — could not terminate process {pid}:\n  {} {}",
568            fix.name,
569            stderr.trim(),
570            permission_hint(&stderr)
571        ));
572    }
573
574    let mut still_running = true;
575    for _ in 0..4 {
576        if !process_exists(pid) {
577            still_running = false;
578            break;
579        }
580        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
581    }
582
583    if still_running {
584        return Err(format!(
585            "✗ {} — process {pid} is still running after `{}` was issued.{}",
586            fix.name,
587            kill_display(pid),
588            PERMISSION_HINT
589        ));
590    }
591
592    Ok(format!(
593        "✓ {} — terminated process {pid} via `{}`\n  ✓ Verified: {pid} is no longer running",
594        fix.name,
595        kill_display(pid)
596    ))
597}
598
599/// The process/tool to use and its arguments, per platform.
600fn kill_args(pid: u32) -> (&'static str, Vec<String>) {
601    if cfg!(windows) {
602        (
603            "taskkill",
604            vec!["/PID".to_string(), pid.to_string(), "/F".to_string()],
605        )
606    } else {
607        ("kill", vec![pid.to_string()])
608    }
609}
610
611/// The human-readable version of the kill command for logs.
612fn kill_display(pid: u32) -> String {
613    if cfg!(windows) {
614        format!("taskkill /PID {pid} /F")
615    } else {
616        format!("kill {pid}")
617    }
618}
619
620/// Resolves Windows `.cmd` batch scripts for common dev tool binaries.
621fn resolve_executable(cmd: &str) -> String {
622    if cfg!(windows) && matches!(cmd, "npm" | "yarn" | "pnpm" | "npx") {
623        format!("{cmd}.cmd")
624    } else {
625        cmd.to_string()
626    }
627}
628
629/// Whether a process with `pid` currently exists (best effort).
630#[cfg(target_os = "windows")]
631pub fn process_exists(pid: u32) -> bool {
632    let filter = format!("PID eq {pid}");
633    match Command::new("tasklist")
634        .args(["/FI", &filter, "/NH"])
635        .output()
636    {
637        Ok(output) => {
638            let text = String::from_utf8_lossy(&output.stdout).to_lowercase();
639            output.status.success() && !text.contains("no tasks") && text.contains(&pid.to_string())
640        }
641        Err(_) => false,
642    }
643}
644
645/// Whether a process with `pid` currently exists (best effort).
646#[cfg(not(target_os = "windows"))]
647pub fn process_exists(pid: u32) -> bool {
648    // `kill -0 pid` exits 0 when the process exists (or EPERM), else 1.
649    Command::new("kill")
650        .args(["-0", &pid.to_string()])
651        .status()
652        .map(|status| status.success())
653        .unwrap_or(false)
654}
655
656// --- RunCommand ----------------------------------------------------------
657
658async fn run_command(fix: &Fix, cmd: &str, args: &[String]) -> Result<String, String> {
659    let display = format!("{} {}", cmd, args.join(" "));
660    let exec_cmd = resolve_executable(cmd);
661    let output = match tokio::process::Command::new(&exec_cmd).args(args).output().await {
662        Ok(output) => output,
663        Err(err) => return Err(describe_spawn_error(&fix.name, cmd, &err)),
664    };
665
666    let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
667    let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
668    let mut log = format!("✓ {} — ran `{display}`", fix.name);
669    if !stdout.is_empty() {
670        log.push_str(&format!("\n  stdout: {stdout}"));
671    }
672    if !stderr.is_empty() {
673        log.push_str(&format!("\n  stderr: {stderr}"));
674    }
675
676    if !output.status.success() {
677        let code = output
678            .status
679            .code()
680            .map(|c| c.to_string())
681            .unwrap_or_else(|| "?".to_string());
682        let hint = permission_hint(&stderr);
683        return Err(format!(
684            "✗ {} — `{display}` failed (exit {code})\n  {}{}",
685            fix.name,
686            if stderr.is_empty() { stdout } else { stderr },
687            hint
688        ));
689    }
690
691    log.push_str(&format!("\n  ✓ Verified: `{display}` exited successfully"));
692    Ok(log)
693}
694
695// ---------------------------------------------------------------------------
696// Verification helpers
697// ---------------------------------------------------------------------------
698
699/// Verifies `dst` is a file whose bytes match `src`.
700pub fn verify_copy(src: &Path, dst: &Path) -> Result<(), String> {
701    if !dst.is_file() {
702        return Err(format!("{} was not created", dst.display()));
703    }
704    match (fs::read(src), fs::read(dst)) {
705        (Ok(a), Ok(b)) if a == b => Ok(()),
706        _ => Err(format!(
707            "{} content differs from {}",
708            dst.display(),
709            src.display()
710        )),
711    }
712}
713
714/// Verifies `path` is a file with exactly `expected` content.
715pub fn verify_written(path: &Path, expected: &str) -> Result<(), String> {
716    if !path.is_file() {
717        return Err(format!("{} was not created", path.display()));
718    }
719    let actual = fs::read_to_string(path)
720        .map_err(|err| format!("{} could not be read: {err}", path.display()))?;
721    if actual == expected {
722        Ok(())
723    } else {
724        Err(format!(
725            "{} content does not match the expected template",
726            path.display()
727        ))
728    }
729}
730
731/// Verifies `path` no longer exists.
732pub fn verify_deleted(path: &Path) -> Result<(), String> {
733    if path.exists() {
734        Err(format!("{} still exists", path.display()))
735    } else {
736        Ok(())
737    }
738}
739
740/// Verifies the process with `pid` is gone.
741pub fn verify_process_gone(pid: u32) -> Result<(), String> {
742    if process_exists(pid) {
743        Err(format!("process {pid} is still running"))
744    } else {
745        Ok(())
746    }
747}
748
749// ---------------------------------------------------------------------------
750// Error helpers
751// ---------------------------------------------------------------------------
752
753fn describe_spawn_error(action: &str, cmd: &str, err: &std::io::Error) -> String {
754    match err.kind() {
755        ErrorKind::NotFound => format!(
756            "✗ {action} — `{cmd}` is not installed (or not on PATH). Install it first, then \
757             restart your terminal before retrying."
758        ),
759        ErrorKind::PermissionDenied => {
760            format!("✗ {action} — permission denied starting `{cmd}`.{PERMISSION_HINT}")
761        }
762        _ => format!("✗ {action} — could not start `{cmd}`: {err}"),
763    }
764}
765
766fn io_fail(action: &str, err: &std::io::Error, context: &str) -> String {
767    match err.kind() {
768        ErrorKind::PermissionDenied => {
769            format!("✗ {action} — permission denied while trying to {context}.{PERMISSION_HINT}")
770        }
771        _ => format!("✗ {action} — could not {context}: {err}"),
772    }
773}
774
775fn permission_hint(text: &str) -> String {
776    let lower = text.to_lowercase();
777    if lower.contains("denied")
778        || lower.contains("permission")
779        || lower.contains("access is denied")
780        || lower.contains("sudo")
781    {
782        PERMISSION_HINT.to_string()
783    } else {
784        String::new()
785    }
786}
787
788fn file_size(path: &Path) -> u64 {
789    fs::metadata(path).map(|m| m.len()).unwrap_or(0)
790}
791
792/// Reads `path` into memory, returning `None` when it does not exist.
793fn read_opt(path: &Path) -> Option<Vec<u8>> {
794    fs::read(path).ok()
795}
796
797/// Rolls a failed, reversible operation back:
798/// - restore a backup of the overwritten file, or
799/// - remove the file when this run created it (and verification failed), or
800/// - leave everything alone when there was nothing to undo.
801fn restore(path: &Path, backup: &Option<Vec<u8>>, created_fresh: bool) {
802    match backup {
803        Some(bytes) => {
804            let _ = fs::write(path, bytes);
805        }
806        None if created_fresh => {
807            let _ = fs::remove_file(path);
808        }
809        None => {}
810    }
811}
812
813// ---------------------------------------------------------------------------
814// CLI entry point
815// ---------------------------------------------------------------------------
816
817/// Runs `limit fix`: scans for issues, builds the concrete fixes, asks for
818/// approval and applies them.
819pub async fn run_fix(all: bool) {
820    println!("{}", "=== Auto-Fix ===".bold().cyan());
821    println!();
822
823    let state = crate::modules::diagnostics::build_snapshot(".");
824    let fixes = recommended_fixes(&state, ".");
825
826    if fixes.is_empty() {
827        println!(
828            "  {} No issues detected — nothing to fix.",
829            "✓".green().bold()
830        );
831        println!();
832        println!("{}", "Fix scan complete!".green().bold());
833        return;
834    }
835
836    println!(
837        "  Detected {} fixable issue{}.",
838        fixes.len(),
839        if fixes.len() == 1 { "" } else { "s" }
840    );
841    for (i, fix) in fixes.iter().enumerate() {
842        let dot = if fix.requires_approval {
843            "•".yellow()
844        } else {
845            "•".green()
846        };
847        let tag = if fix.requires_approval {
848            "approval required"
849        } else {
850            "safe"
851        };
852        println!("   {dot} {}. {} — {}", i + 1, fix.name, tag.dimmed());
853    }
854    println!();
855
856    let mut approved: Vec<&Fix> = Vec::new();
857    if all {
858        let message = format!("Apply all {} fixes automatically?", fixes.len());
859        if crate::modules::interactive_prompt::prompt_user_confirmation(&message, true) {
860            approved = fixes.iter().collect();
861        } else {
862            println!("{}", "  Auto-fix cancelled.".yellow().bold());
863            println!();
864            println!("{}", "Fix scan complete!".green().bold());
865            return;
866        }
867    } else {
868        for fix in &fixes {
869            if !fix.requires_approval {
870                approved.push(fix);
871                continue;
872            }
873            let message = format!("{} — {}?", fix.name, fix.description);
874            if crate::modules::interactive_prompt::prompt_user_confirmation(&message, true) {
875                approved.push(fix);
876            } else {
877                println!("  {} skipping {}.", "↷".dimmed(), fix.name.dimmed());
878            }
879        }
880    }
881
882    if approved.is_empty() {
883        println!(
884            "  {} No fixes were approved — nothing changed.",
885            "Note:".yellow()
886        );
887        println!();
888        println!("{}", "Fix scan complete!".green().bold());
889        return;
890    }
891
892    let mut succeeded = 0usize;
893    let mut failed = Vec::new();
894    for fix in approved {
895        println!("  {}", preview_fix(fix, "."));
896        // Approval already obtained above; overwrite may now proceed.
897        match execute_fix_with(fix, ".", true).await {
898            Ok(log) => {
899                println!("  {log}");
900                succeeded += 1;
901            }
902            Err(err) => {
903                println!("  {err}");
904                failed.push((fix.name.clone(), err));
905            }
906        }
907    }
908
909    println!();
910    println!(
911        "  {} {} fix{}, {} failed.",
912        if failed.is_empty() {
913            "✓".green()
914        } else {
915            "⚠".yellow()
916        },
917        succeeded,
918        if succeeded == 1 { "" } else { "es" },
919        failed.len()
920    );
921    for (name, err) in &failed {
922        println!("    • {}: {}", name.yellow(), err);
923    }
924    println!();
925    println!("{}", "Fix scan complete!".green().bold());
926}
927
928#[cfg(test)]
929mod tests {
930    use super::*;
931    use crate::models::{EnvironmentState, ProjectStack};
932    use std::path::PathBuf;
933    use std::time::{SystemTime, UNIX_EPOCH};
934
935    /// A self-cleaning temporary directory for mocked repository fixtures.
936    struct TempDir {
937        path: PathBuf,
938    }
939
940    impl TempDir {
941        fn new(label: &str) -> Self {
942            let stamp = SystemTime::now()
943                .duration_since(UNIX_EPOCH)
944                .expect("system clock")
945                .as_nanos();
946            let path = std::env::temp_dir().join(format!("limitless_fixes_{label}_{stamp}"));
947            fs::create_dir_all(&path).expect("create temp dir");
948            TempDir { path }
949        }
950
951        fn path(&self) -> &Path {
952            &self.path
953        }
954
955        fn write(self, relative: &str, content: &str) -> Self {
956            let full = self.path.join(relative);
957            if let Some(parent) = full.parent() {
958                fs::create_dir_all(parent).expect("create parent dirs");
959            }
960            fs::write(full, content).expect("write fixture file");
961            self
962        }
963    }
964
965    impl Drop for TempDir {
966        fn drop(&mut self) {
967            let _ = fs::remove_dir_all(&self.path);
968        }
969    }
970
971    fn sample_state() -> EnvironmentState {
972        EnvironmentState {
973            detected_stack: ProjectStack::Node {
974                version: "18.12.0".into(),
975                package_manager: "npm".into(),
976            },
977            runtime_version: Some("v18.12.0".into()),
978            env_file_exists: false,
979            env_example_exists: true,
980            dependencies_healthy: false,
981            blocked_ports: vec![(3000, 9921)],
982            diagnostics: Vec::new(),
983            health_score: crate::models::HealthScore::default(),
984        }
985    }
986
987    // --- Factories ---------------------------------------------------------
988
989    #[test]
990    fn copy_env_fix_is_reversible_and_approved() {
991        let fix = copy_env_from_example(".env.example", ".env").unwrap();
992        assert_eq!(fix.id, "copy-env-from-example");
993        assert!(fix.reversible);
994        assert!(fix.requires_approval);
995        assert!(matches!(
996            fix.command,
997            FixCommand::CopyFile { ref src, ref dst } if src == ".env.example" && dst == ".env"
998        ));
999    }
1000
1001    #[test]
1002    fn kill_ghost_targets_the_blocked_pid() {
1003        let fix = kill_ghost_process(3000, 9921);
1004        assert_eq!(fix.id, "kill-ghost-9921");
1005        assert!(!fix.reversible);
1006        assert!(fix.requires_approval);
1007        assert!(matches!(fix.command, FixCommand::KillProcess { pid: 9921 }));
1008    }
1009
1010    #[test]
1011    fn install_fix_maps_each_stack() {
1012        let node = install_fix_for_stack(&ProjectStack::Node {
1013            version: "22.9.0".into(),
1014            package_manager: "npm".into(),
1015        })
1016        .unwrap();
1017        assert!(matches!(
1018            node.command,
1019            FixCommand::RunCommand { ref cmd, ref args } if cmd == "npm" && args == &["install"]
1020        ));
1021
1022        let python = install_fix_for_stack(&ProjectStack::Python {
1023            version: ">=3.12".into(),
1024        })
1025        .unwrap();
1026        assert!(matches!(
1027            python.command,
1028            FixCommand::RunCommand { ref args, .. } if args == &["install", "-r", "requirements.txt"]
1029        ));
1030
1031        let rust = install_fix_for_stack(&ProjectStack::Rust {
1032            version: "1.98.0".into(),
1033        })
1034        .unwrap();
1035        assert!(matches!(
1036            rust.command,
1037            FixCommand::RunCommand { ref cmd, .. } if cmd == "cargo"
1038        ));
1039
1040        assert!(install_fix_for_stack(&ProjectStack::Docker).is_none());
1041        assert!(install_fix_for_stack(&ProjectStack::Unknown).is_none());
1042    }
1043
1044    #[test]
1045    fn missing_config_files_only_for_absent_files() {
1046        let dir = TempDir::new("cfg_missing").write(".gitignore", "node_modules/\n");
1047        let fixes = missing_config_files(dir.path().to_str().unwrap());
1048        let names: Vec<&str> = fixes.iter().map(|f| f.name.as_str()).collect();
1049        assert_eq!(names, vec!["Create .editorconfig"]);
1050    }
1051
1052    #[test]
1053    fn missing_config_files_creates_both_when_absent() {
1054        let dir = TempDir::new("cfg_absent");
1055        let fixes = missing_config_files(dir.path().to_str().unwrap());
1056        assert_eq!(fixes.len(), 2);
1057        assert_eq!(fixes[0].id, "create-gitignore");
1058        assert_eq!(fixes[1].id, "create-editorconfig");
1059        assert!(fixes.iter().all(|f| !f.requires_approval));
1060    }
1061
1062    #[test]
1063    fn recommended_fixes_order_includes_copy_kill_install_create() {
1064        let dir = TempDir::new("rec");
1065        let fixes = recommended_fixes(&sample_state(), dir.path().to_str().unwrap());
1066        let ids: Vec<&str> = fixes.iter().map(|f| f.id.as_str()).collect();
1067        assert_eq!(ids[0], "copy-env-from-example");
1068        assert_eq!(ids[1], "kill-ghost-9921");
1069        assert_eq!(ids[2], "install-dependencies-npm");
1070        assert!(ids.contains(&"create-gitignore"));
1071        assert!(ids.contains(&"create-editorconfig"));
1072    }
1073
1074    #[test]
1075    fn copy_fix_absent_when_no_template_or_env_present() {
1076        let mut state = sample_state();
1077        state.env_example_exists = false;
1078        let dir = TempDir::new("rec_no_copy");
1079        let fixes = recommended_fixes(&state, dir.path().to_str().unwrap());
1080        assert!(!fixes.iter().any(|f| f.id == "copy-env-from-example"));
1081    }
1082
1083    // --- Preview ------------------------------------------------------------
1084
1085    #[test]
1086    fn preview_describes_before_and_after() {
1087        let dir = TempDir::new("preview").write(".env.example", "PORT=3000\n");
1088        let fix = copy_env_from_example(".env.example", ".env").unwrap();
1089        let preview = preview_fix(&fix, dir.path().to_str().unwrap());
1090        assert!(preview.contains("Before: .env.example is present, .env is missing"));
1091        assert!(preview.contains("After:  copies .env.example → .env"));
1092    }
1093
1094    // --- Execution ----------------------------------------------------------
1095
1096    #[tokio::test]
1097    async fn copy_env_executes_and_verifies() {
1098        let dir = TempDir::new("cop").write(".env.example", "API_KEY=abc\nPORT=3000\n");
1099        let fix = copy_env_from_example(".env.example", ".env").unwrap();
1100        let repo = dir.path().to_str().unwrap().to_string();
1101
1102        let log = execute_fix(&fix, &repo).await.unwrap();
1103        assert!(log.contains("✓ Copy .env.example to .env"));
1104        assert!(log.contains("Verified"));
1105        let content = fs::read_to_string(dir.path().join(".env")).unwrap();
1106        assert_eq!(content, "API_KEY=abc\nPORT=3000\n");
1107
1108        // Second run must be refused (non-destructive by default).
1109        let err = execute_fix(&fix, &repo).await.unwrap_err();
1110        assert!(err.contains(".env already exists"), "got: {err}");
1111        // The original is untouched.
1112        let again = fs::read_to_string(dir.path().join(".env")).unwrap();
1113        assert_eq!(again, "API_KEY=abc\nPORT=3000\n");
1114    }
1115
1116    #[tokio::test]
1117    async fn copy_env_refuses_overwrite_unless_approved() {
1118        let dir = TempDir::new("overwrite")
1119            .write(".env.example", "PORT=3000\n")
1120            .write(".env", "PORT=9999\n");
1121        let fix = copy_env_from_example(".env.example", ".env").unwrap();
1122        let repo = dir.path().to_str().unwrap().to_string();
1123
1124        let err = execute_fix(&fix, &repo).await.unwrap_err();
1125        assert!(err.contains("already exists"));
1126
1127        // After explicit approval the overwrite proceeds.
1128        let ok = execute_fix_with(&fix, &repo, true).await.unwrap();
1129        assert!(ok.contains("Verified"));
1130        assert_eq!(
1131            fs::read_to_string(dir.path().join(".env")).unwrap(),
1132            "PORT=3000\n"
1133        );
1134    }
1135
1136    #[tokio::test]
1137    async fn copy_env_missing_source_errors() {
1138        let dir = TempDir::new("no_src");
1139        let fix = copy_env_from_example(".env.example", ".env").unwrap();
1140        let err = execute_fix(&fix, dir.path().to_str().unwrap())
1141            .await
1142            .unwrap_err();
1143        assert!(err.contains("does not exist"));
1144    }
1145
1146    #[tokio::test]
1147    async fn create_file_writes_expected_content_and_verifies() {
1148        let dir = TempDir::new("gitcreate");
1149        let fix = Fix::new(
1150            "create-gitignore",
1151            "Create .gitignore",
1152            "test",
1153            FixCommand::CreateFile {
1154                path: ".gitignore".to_string(),
1155                content: DEFAULT_GITIGNORE.to_string(),
1156            },
1157            true,
1158            false,
1159        );
1160        let repo = dir.path().to_str().unwrap().to_string();
1161        let log = execute_fix(&fix, &repo).await.unwrap();
1162        assert!(log.contains("created .gitignore"), "got: {log}");
1163        assert!(log.contains("Verified"), "got: {log}");
1164        assert_eq!(
1165            fs::read_to_string(dir.path().join(".gitignore")).unwrap(),
1166            DEFAULT_GITIGNORE
1167        );
1168
1169        // Non-destructive: an existing .gitignore blocks recreation.
1170        let err = execute_fix(&fix, &repo).await.unwrap_err();
1171        assert!(err.contains(".gitignore already exists"));
1172
1173        // Overwrite still refuses to clobber unless approved.
1174        let err2 = execute_fix_with(&fix, &repo, false).await.unwrap_err();
1175        assert!(err2.contains("already exists"));
1176    }
1177
1178    #[tokio::test]
1179    async fn create_file_rolls_back_when_verification_fails() {
1180        let dir = TempDir::new("roll").write(".env", "KEEP=me\n");
1181        let fix = Fix::new(
1182            "test-roll",
1183            "Roll me",
1184            "test",
1185            FixCommand::CreateFile {
1186                path: ".env".to_string(),
1187                content: "NEW=value\n".to_string(),
1188            },
1189            true,
1190            false,
1191        );
1192        let repo = dir.path().to_str().unwrap().to_string();
1193
1194        // Without approval the file is untouched.
1195        let _ = execute_fix(&fix, &repo).await.unwrap_err();
1196        assert_eq!(
1197            fs::read_to_string(dir.path().join(".env")).unwrap(),
1198            "KEEP=me\n"
1199        );
1200
1201        // With approval it is overwritten and verified.
1202        let log = execute_fix_with(&fix, &repo, true).await.unwrap();
1203        assert!(log.contains("Verified"));
1204        assert_eq!(
1205            fs::read_to_string(dir.path().join(".env")).unwrap(),
1206            "NEW=value\n"
1207        );
1208    }
1209
1210    #[tokio::test]
1211    async fn delete_file_removes_and_verifies() {
1212        let dir = TempDir::new("del").write("temp.log", "boom\n");
1213        let fix = Fix::new(
1214            "delete-temp",
1215            "Delete temp.log",
1216            "test",
1217            FixCommand::DeleteFile {
1218                path: "temp.log".to_string(),
1219            },
1220            false,
1221            false,
1222        );
1223        let repo = dir.path().to_str().unwrap().to_string();
1224        let log = execute_fix(&fix, &repo).await.unwrap();
1225        assert!(log.contains("deleted temp.log"), "got: {log}");
1226        assert!(log.contains("no longer exists"), "got: {log}");
1227        assert!(!dir.path().join("temp.log").exists());
1228
1229        let err = execute_fix(&fix, &repo).await.unwrap_err();
1230        assert!(err.contains("nothing to delete"));
1231    }
1232
1233    #[tokio::test]
1234    async fn delete_file_rolls_back_when_verification_fails() {
1235        // Verification of a delete can only fail if the delete itself didn't
1236        // happen; simulate it by marking the target directory-like so the
1237        // remove_file must fail, but the backup restore is still exercised.
1238        let dir = TempDir::new("del_roll");
1239        let target = dir.path().join("dir_as_file");
1240        fs::create_dir(&target).expect("place dir in the way");
1241        fs::write(target.join("child"), "x").expect("child");
1242
1243        let fix = Fix::new(
1244            "delete-dir",
1245            "Delete",
1246            "test",
1247            FixCommand::DeleteFile {
1248                path: "dir_as_file".to_string(),
1249            },
1250            true,
1251            false,
1252        );
1253        // On Unix `fs::remove_file` on a directory reports `IsADirectory`;
1254        // on Windows it comes back as `PermissionDenied`. Either way the
1255        // delete must fail and the offending path must survive untouched.
1256        let err = execute_fix(&fix, dir.path().to_str().unwrap())
1257            .await
1258            .unwrap_err();
1259        assert!(err.contains("✗ Delete"), "got: {err}");
1260        assert!(target.exists());
1261        assert!(fs::read_to_string(target.join("child")).is_ok());
1262    }
1263
1264    #[tokio::test]
1265    async fn run_command_captures_output_and_verifies() {
1266        let fix = Fix::new(
1267            "test-run",
1268            "Echo",
1269            "test",
1270            FixCommand::RunCommand {
1271                cmd: "cmd".to_string(),
1272                args: vec!["/C".into(), "echo".into(), "fix-ok".into()],
1273            },
1274            false,
1275            false,
1276        );
1277        let log = execute_fix(&fix, ".").await.unwrap();
1278        assert!(log.contains("ran `cmd /C echo fix-ok`"));
1279        assert!(log.contains("fix-ok"));
1280        assert!(log.contains("Verified"));
1281    }
1282
1283    #[cfg(not(target_os = "windows"))]
1284    #[tokio::test]
1285    async fn run_command_captures_output_and_verifies_unix() {
1286        let fix = Fix::new(
1287            "test-run",
1288            "Echo",
1289            "test",
1290            FixCommand::RunCommand {
1291                cmd: "sh".to_string(),
1292                args: vec!["-c".into(), "echo fix-ok".into()],
1293            },
1294            false,
1295            false,
1296        );
1297        let log = execute_fix(&fix, ".").await.unwrap();
1298        assert!(log.contains("fix-ok"));
1299    }
1300
1301    #[tokio::test]
1302    async fn run_command_not_found_suggests_install() {
1303        let fix = Fix::new(
1304            "test-run",
1305            "Phantom",
1306            "test",
1307            FixCommand::RunCommand {
1308                cmd: "definitely_not_an_installable_command_xyz".to_string(),
1309                args: Vec::new(),
1310            },
1311            false,
1312            false,
1313        );
1314        let err = execute_fix(&fix, ".").await.unwrap_err();
1315        assert!(err.contains("not installed"), "got: {err}");
1316    }
1317
1318    // On Windows there is no `kill -0`; the skip path is exercised through
1319    // `tasklist`. On other platforms a huge PID is virtually never alive.
1320    #[tokio::test]
1321    async fn kill_missing_process_skips_gracefully() {
1322        let fix = kill_ghost_process(3000, 999_999_999);
1323        let log = execute_fix(&fix, ".").await.unwrap();
1324        assert!(log.contains("not running"), "got: {log}");
1325    }
1326
1327    #[tokio::test]
1328    async fn kill_invalid_pid_zero_is_rejected() {
1329        let fix = kill_ghost_process(3000, 0);
1330        let err = execute_fix(&fix, ".").await.unwrap_err();
1331        assert!(err.contains("PID 0"), "got: {err}");
1332    }
1333
1334    // --- Verification helpers ----------------------------------------------
1335
1336    #[test]
1337    fn verify_helpers_report_truth() {
1338        let dir = TempDir::new("verify")
1339            .write("a.txt", "same\n")
1340            .write("b.txt", "same\n");
1341        assert!(verify_copy(&dir.path().join("a.txt"), &dir.path().join("b.txt")).is_ok());
1342        assert!(verify_written(&dir.path().join("a.txt"), "same\n").is_ok());
1343        assert!(verify_written(&dir.path().join("a.txt"), "other\n").is_err());
1344        assert!(verify_deleted(&dir.path().join("gone.txt")).is_ok());
1345        assert!(verify_deleted(&dir.path().join("a.txt")).is_err());
1346        assert!(verify_process_gone(999_999_999).is_ok());
1347    }
1348
1349    #[test]
1350    fn default_templates_cover_common_stacks() {
1351        assert!(DEFAULT_GITIGNORE.contains("node_modules"));
1352        assert!(DEFAULT_GITIGNORE.contains(".env"));
1353        assert!(DEFAULT_EDITORCONFIG.contains("root = true"));
1354    }
1355
1356    // --- Named coverage tests ----------------------------------------------
1357
1358    #[tokio::test]
1359    async fn test_copy_env_file() {
1360        let dir = TempDir::new("named_copy").write(".env.example", "PORT=3000\nSECRET=x\n");
1361        let fix = copy_env_from_example(".env.example", ".env").unwrap();
1362        let repo = dir.path().to_str().unwrap().to_string();
1363
1364        let log = execute_fix(&fix, &repo).await.unwrap();
1365        assert!(log.contains("Copy .env.example to .env"));
1366        assert!(log.contains("Verified"));
1367        assert_eq!(
1368            fs::read_to_string(dir.path().join(".env")).unwrap(),
1369            "PORT=3000\nSECRET=x\n"
1370        );
1371
1372        // Re-running without approval is refused and leaves the file intact.
1373        let err = execute_fix(&fix, &repo).await.unwrap_err();
1374        assert!(err.contains(".env already exists"), "got: {err}");
1375        assert_eq!(
1376            fs::read_to_string(dir.path().join(".env")).unwrap(),
1377            "PORT=3000\nSECRET=x\n"
1378        );
1379    }
1380
1381    #[tokio::test]
1382    async fn test_kill_process() {
1383        let mut child = if cfg!(windows) {
1384            // Kill `ping` directly (not through `cmd /C`) so taskkill reaches
1385            // the process we spawned and nothing is orphaned afterwards.
1386            std::process::Command::new("ping")
1387                .args(["-n", "60", "127.0.0.1"])
1388                .stdout(std::process::Stdio::null())
1389                .stderr(std::process::Stdio::null())
1390                .spawn()
1391                .expect("spawn long-lived child")
1392        } else {
1393            std::process::Command::new("sleep")
1394                .arg("60")
1395                .spawn()
1396                .expect("spawn long-lived child")
1397        };
1398        let pid = child.id();
1399
1400        let fix = kill_ghost_process(3000, pid);
1401        let log = execute_fix(&fix, ".").await.unwrap();
1402        assert!(
1403            log.contains(&pid.to_string()),
1404            "kill log should mention PID {pid}: {log}"
1405        );
1406        assert!(log.contains("Killed") || log.contains("terminated"), "got: {log}");
1407
1408        // The child must actually be gone: a second kill skips gracefully.
1409        let again = execute_fix(
1410            &kill_ghost_process(3000, pid),
1411            ".",
1412        )
1413        .await
1414        .unwrap();
1415        assert!(again.contains("not running"), "got: {again}");
1416
1417        let _ = child.kill();
1418        let _ = child.wait();
1419    }
1420
1421    #[test]
1422    fn test_install_dependencies() {
1423        let node = install_fix_for_stack(&ProjectStack::Node {
1424            version: String::new(),
1425            package_manager: "npm".into(),
1426        })
1427        .expect("Node stacks map to an install fix");
1428        assert!(matches!(
1429            node.command,
1430            FixCommand::RunCommand { ref cmd, .. } if cmd == "npm"
1431        ));
1432        assert!(validate_fix(&node).is_ok());
1433
1434        assert!(install_fix_for_stack(&ProjectStack::Python {
1435            version: String::new(),
1436        })
1437        .is_some());
1438        assert!(install_fix_for_stack(&ProjectStack::Rust {
1439            version: String::new(),
1440        })
1441        .is_some());
1442        assert!(install_fix_for_stack(&ProjectStack::Docker).is_none());
1443        assert!(install_fix_for_stack(&ProjectStack::Unknown).is_none());
1444    }
1445
1446    #[tokio::test]
1447    async fn test_fix_rollback_on_failure() {
1448        // Writing a CreateFile onto a path that is really a directory must
1449        // fail without leaving partial state behind, and the offending path
1450        // must survive untouched.
1451        let dir = TempDir::new("named_roll");
1452        let blocker = dir.path().join("as_dir");
1453        fs::create_dir(&blocker).expect("dir in the way");
1454        fs::write(blocker.join("child"), "y").expect("child file");
1455
1456        let fix = Fix::new(
1457            "create-into-dir",
1458            "Create as_dir",
1459            "test",
1460            FixCommand::CreateFile {
1461                path: "as_dir".to_string(),
1462                content: "DATA\n".to_string(),
1463            },
1464            true,
1465            false,
1466        );
1467        let err = execute_fix_with(&fix, dir.path().to_str().unwrap(), true)
1468            .await
1469            .unwrap_err();
1470        assert!(!err.is_empty());
1471        assert!(blocker.is_dir(), "offending path must survive: {err}");
1472        assert_eq!(
1473            fs::read_to_string(blocker.join("child")).unwrap(),
1474            "y",
1475            "no partial writes inside the blocked path"
1476        );
1477
1478        // A failed copy leaves no destination file behind.
1479        let missing_src = TempDir::new("named_roll_copy");
1480        let copy = copy_env_from_example(".env.example", ".env").unwrap();
1481        let err2 = execute_fix(&copy, missing_src.path().to_str().unwrap())
1482            .await
1483            .unwrap_err();
1484        assert!(err2.contains("does not exist"), "got: {err2}");
1485        assert!(!missing_src.path().join(".env").exists());
1486    }
1487}