Skip to main content

aft/
format.rs

1//! External tool runner and auto-formatter detection.
2//!
3//! Provides subprocess execution with timeout protection, language-to-formatter
4//! mapping, and the `auto_format` entry point used by `write_format_validate`.
5
6use std::collections::{HashMap, HashSet};
7use std::io::ErrorKind;
8use std::path::{Path, PathBuf};
9use std::process::{Command, Stdio};
10use std::sync::Mutex;
11use std::thread;
12use std::time::{Duration, Instant};
13
14use crate::config::Config;
15use crate::parser::{detect_language, LangId};
16
17/// Result of running an external tool subprocess.
18#[derive(Debug)]
19pub struct ExternalToolResult {
20    pub stdout: String,
21    pub stderr: String,
22    pub exit_code: i32,
23}
24
25/// Errors from external tool execution.
26#[derive(Debug)]
27pub enum FormatError {
28    /// The tool binary was not found on PATH.
29    NotFound { tool: String },
30    /// The tool exceeded its timeout and was killed.
31    Timeout { tool: String, timeout_secs: u32 },
32    /// The tool exited with a non-zero status.
33    Failed { tool: String, stderr: String },
34    /// No formatter is configured for this language.
35    UnsupportedLanguage,
36}
37
38/// A configured formatter/checker that cannot be resolved for configure warnings.
39#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
40pub struct MissingTool {
41    pub kind: String,
42    pub language: String,
43    pub tool: String,
44    pub hint: String,
45}
46
47#[derive(Debug, Clone)]
48struct ToolCandidate {
49    tool: String,
50    source: String,
51    args: Vec<String>,
52    required: bool,
53}
54
55#[derive(Debug, Clone)]
56enum ToolDetection {
57    Found(String, Vec<String>),
58    NotConfigured,
59    NotInstalled { tool: String },
60}
61
62impl std::fmt::Display for FormatError {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        match self {
65            FormatError::NotFound { tool } => write!(f, "formatter not found: {}", tool),
66            FormatError::Timeout { tool, timeout_secs } => {
67                write!(f, "formatter '{}' timed out after {}s", tool, timeout_secs)
68            }
69            FormatError::Failed { tool, stderr } => {
70                write!(f, "formatter '{}' failed: {}", tool, stderr)
71            }
72            FormatError::UnsupportedLanguage => write!(f, "unsupported language for formatting"),
73        }
74    }
75}
76
77/// Spawn a subprocess and wait for completion with timeout protection.
78///
79/// Polls `try_wait()` at 50ms intervals. On timeout, kills the child process
80/// and waits for it to exit. Returns `FormatError::NotFound` when the binary
81/// isn't on PATH.
82pub fn run_external_tool(
83    command: &str,
84    args: &[&str],
85    working_dir: Option<&Path>,
86    timeout_secs: u32,
87) -> Result<ExternalToolResult, FormatError> {
88    let mut cmd = Command::new(command);
89    cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped());
90
91    if let Some(dir) = working_dir {
92        cmd.current_dir(dir);
93    }
94
95    let mut child = match cmd.spawn() {
96        Ok(c) => c,
97        Err(e) if e.kind() == ErrorKind::NotFound => {
98            return Err(FormatError::NotFound {
99                tool: command.to_string(),
100            });
101        }
102        Err(e) => {
103            return Err(FormatError::Failed {
104                tool: command.to_string(),
105                stderr: e.to_string(),
106            });
107        }
108    };
109
110    let deadline = Instant::now() + Duration::from_secs(timeout_secs as u64);
111
112    loop {
113        match child.try_wait() {
114            Ok(Some(status)) => {
115                let stdout = child
116                    .stdout
117                    .take()
118                    .map(|s| std::io::read_to_string(s).unwrap_or_default())
119                    .unwrap_or_default();
120                let stderr = child
121                    .stderr
122                    .take()
123                    .map(|s| std::io::read_to_string(s).unwrap_or_default())
124                    .unwrap_or_default();
125
126                let exit_code = status.code().unwrap_or(-1);
127                if exit_code != 0 {
128                    return Err(FormatError::Failed {
129                        tool: command.to_string(),
130                        stderr,
131                    });
132                }
133
134                return Ok(ExternalToolResult {
135                    stdout,
136                    stderr,
137                    exit_code,
138                });
139            }
140            Ok(None) => {
141                // Still running
142                if Instant::now() >= deadline {
143                    // Kill the process and reap it
144                    let _ = child.kill();
145                    let _ = child.wait();
146                    return Err(FormatError::Timeout {
147                        tool: command.to_string(),
148                        timeout_secs,
149                    });
150                }
151                thread::sleep(Duration::from_millis(50));
152            }
153            Err(e) => {
154                return Err(FormatError::Failed {
155                    tool: command.to_string(),
156                    stderr: format!("try_wait error: {}", e),
157                });
158            }
159        }
160    }
161}
162
163/// TTL for tool availability and resolution cache entries.
164const TOOL_CACHE_TTL: Duration = Duration::from_secs(60);
165
166#[derive(Debug, Clone, PartialEq, Eq, Hash)]
167struct ToolCacheKey {
168    command: String,
169    project_root: PathBuf,
170}
171
172static TOOL_RESOLUTION_CACHE: std::sync::LazyLock<
173    Mutex<HashMap<ToolCacheKey, (Option<PathBuf>, Instant)>>,
174> = std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));
175
176static TOOL_AVAILABILITY_CACHE: std::sync::LazyLock<Mutex<HashMap<String, (bool, Instant)>>> =
177    std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));
178
179fn tool_cache_key(command: &str, project_root: Option<&Path>) -> ToolCacheKey {
180    ToolCacheKey {
181        command: command.to_string(),
182        project_root: project_root.map(Path::to_path_buf).unwrap_or_default(),
183    }
184}
185
186fn availability_cache_key(command: &str, project_root: Option<&Path>) -> String {
187    let root = project_root
188        .map(|path| path.to_string_lossy())
189        .unwrap_or_default();
190    format!("{}\0{}", command, root)
191}
192
193pub fn clear_tool_cache() {
194    if let Ok(mut cache) = TOOL_RESOLUTION_CACHE.lock() {
195        cache.clear();
196    }
197    if let Ok(mut cache) = TOOL_AVAILABILITY_CACHE.lock() {
198        cache.clear();
199    }
200}
201
202/// Resolve a tool by checking node_modules/.bin relative to project_root, then PATH.
203/// Returns the full path to the tool if found, otherwise None.
204fn resolve_tool(command: &str, project_root: Option<&Path>) -> Option<String> {
205    let key = tool_cache_key(command, project_root);
206    if let Ok(cache) = TOOL_RESOLUTION_CACHE.lock() {
207        if let Some((resolved, checked_at)) = cache.get(&key) {
208            if checked_at.elapsed() < TOOL_CACHE_TTL {
209                return resolved
210                    .as_ref()
211                    .map(|path| path.to_string_lossy().to_string());
212            }
213        }
214    }
215
216    let resolved = resolve_tool_uncached(command, project_root);
217    if let Ok(mut cache) = TOOL_RESOLUTION_CACHE.lock() {
218        cache.insert(key, (resolved.clone(), Instant::now()));
219    }
220    resolved.map(|path| path.to_string_lossy().to_string())
221}
222
223fn resolve_tool_uncached(command: &str, project_root: Option<&Path>) -> Option<PathBuf> {
224    // 1. Check node_modules/.bin/<command> relative to project root
225    if let Some(root) = project_root {
226        let local_bin = root.join("node_modules").join(".bin").join(command);
227        if local_bin.exists() {
228            return Some(local_bin);
229        }
230    }
231
232    // 2. Fall back to PATH lookup
233    match Command::new(command)
234        .arg("--version")
235        .stdin(Stdio::null())
236        .stdout(Stdio::null())
237        .stderr(Stdio::null())
238        .spawn()
239    {
240        Ok(mut child) => {
241            let start = Instant::now();
242            let timeout = Duration::from_secs(2);
243            loop {
244                match child.try_wait() {
245                    Ok(Some(status)) => {
246                        return if status.success() {
247                            Some(PathBuf::from(command))
248                        } else {
249                            None
250                        };
251                    }
252                    Ok(None) if start.elapsed() > timeout => {
253                        let _ = child.kill();
254                        let _ = child.wait();
255                        return None;
256                    }
257                    Ok(None) => thread::sleep(Duration::from_millis(50)),
258                    Err(_) => return None,
259                }
260            }
261        }
262        Err(_) => None,
263    }
264}
265
266/// Check if `ruff format` is available with a stable formatter.
267///
268/// Ruff's formatter became stable in v0.1.2. Versions before that output
269/// `NOT_YET_IMPLEMENTED_*` stubs instead of formatted code. We parse the
270/// version from `ruff --version` (format: "ruff X.Y.Z") and require >= 0.1.2.
271/// Falls back to false if ruff is not found or version cannot be parsed.
272fn ruff_format_available(project_root: Option<&Path>) -> bool {
273    let key = availability_cache_key("ruff-format", project_root);
274    if let Ok(cache) = TOOL_AVAILABILITY_CACHE.lock() {
275        if let Some((available, checked_at)) = cache.get(&key) {
276            if checked_at.elapsed() < TOOL_CACHE_TTL {
277                return *available;
278            }
279        }
280    }
281
282    let result = ruff_format_available_uncached(project_root);
283    if let Ok(mut cache) = TOOL_AVAILABILITY_CACHE.lock() {
284        cache.insert(key, (result, Instant::now()));
285    }
286    result
287}
288
289fn ruff_format_available_uncached(project_root: Option<&Path>) -> bool {
290    let command = match resolve_tool("ruff", project_root) {
291        Some(command) => command,
292        None => return false,
293    };
294    let output = match Command::new(&command)
295        .arg("--version")
296        .stdout(Stdio::piped())
297        .stderr(Stdio::null())
298        .output()
299    {
300        Ok(o) => o,
301        Err(_) => return false,
302    };
303
304    let version_str = String::from_utf8_lossy(&output.stdout);
305    // Parse "ruff X.Y.Z" or just "X.Y.Z"
306    let version_part = version_str
307        .trim()
308        .strip_prefix("ruff ")
309        .unwrap_or(version_str.trim());
310
311    let parts: Vec<&str> = version_part.split('.').collect();
312    if parts.len() < 3 {
313        return false;
314    }
315
316    let major: u32 = match parts[0].parse() {
317        Ok(v) => v,
318        Err(_) => return false,
319    };
320    let minor: u32 = match parts[1].parse() {
321        Ok(v) => v,
322        Err(_) => return false,
323    };
324    let patch: u32 = match parts[2].parse() {
325        Ok(v) => v,
326        Err(_) => return false,
327    };
328
329    // Require >= 0.1.2 where ruff format became stable
330    (major, minor, patch) >= (0, 1, 2)
331}
332
333fn resolve_candidate_tool(
334    candidate: &ToolCandidate,
335    project_root: Option<&Path>,
336) -> Option<String> {
337    if candidate.tool == "ruff" && !ruff_format_available(project_root) {
338        return None;
339    }
340
341    resolve_tool(&candidate.tool, project_root)
342}
343
344fn lang_key(lang: LangId) -> &'static str {
345    match lang {
346        LangId::TypeScript | LangId::JavaScript | LangId::Tsx => "typescript",
347        LangId::Python => "python",
348        LangId::Rust => "rust",
349        LangId::Go => "go",
350        LangId::C => "c",
351        LangId::Cpp => "cpp",
352        LangId::Zig => "zig",
353        LangId::CSharp => "csharp",
354        LangId::Bash => "bash",
355        LangId::Html => "html",
356        LangId::Markdown => "markdown",
357    }
358}
359
360fn has_formatter_support(lang: LangId) -> bool {
361    matches!(
362        lang,
363        LangId::TypeScript
364            | LangId::JavaScript
365            | LangId::Tsx
366            | LangId::Python
367            | LangId::Rust
368            | LangId::Go
369    )
370}
371
372fn has_checker_support(lang: LangId) -> bool {
373    matches!(
374        lang,
375        LangId::TypeScript
376            | LangId::JavaScript
377            | LangId::Tsx
378            | LangId::Python
379            | LangId::Rust
380            | LangId::Go
381    )
382}
383
384fn formatter_candidates(lang: LangId, config: &Config, file_str: &str) -> Vec<ToolCandidate> {
385    let project_root = config.project_root.as_deref();
386    if let Some(preferred) = config.formatter.get(lang_key(lang)) {
387        return explicit_formatter_candidate(preferred, file_str);
388    }
389
390    match lang {
391        LangId::TypeScript | LangId::JavaScript | LangId::Tsx => {
392            if has_project_config(project_root, &["biome.json", "biome.jsonc"]) {
393                vec![ToolCandidate {
394                    tool: "biome".to_string(),
395                    source: "biome.json".to_string(),
396                    args: vec![
397                        "format".to_string(),
398                        "--write".to_string(),
399                        file_str.to_string(),
400                    ],
401                    required: true,
402                }]
403            } else if has_project_config(
404                project_root,
405                &[
406                    ".prettierrc",
407                    ".prettierrc.json",
408                    ".prettierrc.yml",
409                    ".prettierrc.yaml",
410                    ".prettierrc.js",
411                    ".prettierrc.cjs",
412                    ".prettierrc.mjs",
413                    ".prettierrc.toml",
414                    "prettier.config.js",
415                    "prettier.config.cjs",
416                    "prettier.config.mjs",
417                ],
418            ) {
419                vec![ToolCandidate {
420                    tool: "prettier".to_string(),
421                    source: "Prettier config".to_string(),
422                    args: vec!["--write".to_string(), file_str.to_string()],
423                    required: true,
424                }]
425            } else if has_project_config(project_root, &["deno.json", "deno.jsonc"]) {
426                vec![ToolCandidate {
427                    tool: "deno".to_string(),
428                    source: "deno.json".to_string(),
429                    args: vec!["fmt".to_string(), file_str.to_string()],
430                    required: true,
431                }]
432            } else {
433                Vec::new()
434            }
435        }
436        LangId::Python => {
437            if has_project_config(project_root, &["ruff.toml", ".ruff.toml"])
438                || has_pyproject_tool(project_root, "ruff")
439            {
440                vec![ToolCandidate {
441                    tool: "ruff".to_string(),
442                    source: "ruff config".to_string(),
443                    args: vec!["format".to_string(), file_str.to_string()],
444                    required: true,
445                }]
446            } else if has_pyproject_tool(project_root, "black") {
447                vec![ToolCandidate {
448                    tool: "black".to_string(),
449                    source: "pyproject.toml".to_string(),
450                    args: vec![file_str.to_string()],
451                    required: true,
452                }]
453            } else {
454                Vec::new()
455            }
456        }
457        LangId::Rust => {
458            if has_project_config(project_root, &["Cargo.toml"]) {
459                vec![ToolCandidate {
460                    tool: "rustfmt".to_string(),
461                    source: "Cargo.toml".to_string(),
462                    args: vec![file_str.to_string()],
463                    required: true,
464                }]
465            } else {
466                Vec::new()
467            }
468        }
469        LangId::Go => {
470            if has_project_config(project_root, &["go.mod"]) {
471                vec![
472                    ToolCandidate {
473                        tool: "goimports".to_string(),
474                        source: "go.mod".to_string(),
475                        args: vec!["-w".to_string(), file_str.to_string()],
476                        required: false,
477                    },
478                    ToolCandidate {
479                        tool: "gofmt".to_string(),
480                        source: "go.mod".to_string(),
481                        args: vec!["-w".to_string(), file_str.to_string()],
482                        required: true,
483                    },
484                ]
485            } else {
486                Vec::new()
487            }
488        }
489        LangId::C | LangId::Cpp | LangId::Zig | LangId::CSharp | LangId::Bash => Vec::new(),
490        LangId::Html => Vec::new(),
491        LangId::Markdown => Vec::new(),
492    }
493}
494
495fn checker_candidates(lang: LangId, config: &Config, file_str: &str) -> Vec<ToolCandidate> {
496    let project_root = config.project_root.as_deref();
497    if let Some(preferred) = config.checker.get(lang_key(lang)) {
498        return explicit_checker_candidate(preferred, file_str);
499    }
500
501    match lang {
502        LangId::TypeScript | LangId::JavaScript | LangId::Tsx => {
503            if has_project_config(project_root, &["biome.json", "biome.jsonc"]) {
504                vec![ToolCandidate {
505                    tool: "biome".to_string(),
506                    source: "biome.json".to_string(),
507                    args: vec!["check".to_string(), file_str.to_string()],
508                    required: true,
509                }]
510            } else if has_project_config(project_root, &["tsconfig.json"]) {
511                vec![ToolCandidate {
512                    tool: "tsc".to_string(),
513                    source: "tsconfig.json".to_string(),
514                    args: vec![
515                        "--noEmit".to_string(),
516                        "--pretty".to_string(),
517                        "false".to_string(),
518                    ],
519                    required: true,
520                }]
521            } else {
522                Vec::new()
523            }
524        }
525        LangId::Python => {
526            if has_project_config(project_root, &["pyrightconfig.json"])
527                || has_pyproject_tool(project_root, "pyright")
528            {
529                vec![ToolCandidate {
530                    tool: "pyright".to_string(),
531                    source: "pyright config".to_string(),
532                    args: vec!["--outputjson".to_string(), file_str.to_string()],
533                    required: true,
534                }]
535            } else if has_project_config(project_root, &["ruff.toml", ".ruff.toml"])
536                || has_pyproject_tool(project_root, "ruff")
537            {
538                vec![ToolCandidate {
539                    tool: "ruff".to_string(),
540                    source: "ruff config".to_string(),
541                    args: vec![
542                        "check".to_string(),
543                        "--output-format=json".to_string(),
544                        file_str.to_string(),
545                    ],
546                    required: true,
547                }]
548            } else {
549                Vec::new()
550            }
551        }
552        LangId::Rust => {
553            if has_project_config(project_root, &["Cargo.toml"]) {
554                vec![ToolCandidate {
555                    tool: "cargo".to_string(),
556                    source: "Cargo.toml".to_string(),
557                    args: vec!["check".to_string(), "--message-format=json".to_string()],
558                    required: true,
559                }]
560            } else {
561                Vec::new()
562            }
563        }
564        LangId::Go => {
565            if has_project_config(project_root, &["go.mod"]) {
566                vec![
567                    ToolCandidate {
568                        tool: "staticcheck".to_string(),
569                        source: "go.mod".to_string(),
570                        args: vec![file_str.to_string()],
571                        required: false,
572                    },
573                    ToolCandidate {
574                        tool: "go".to_string(),
575                        source: "go.mod".to_string(),
576                        args: vec!["vet".to_string(), file_str.to_string()],
577                        required: true,
578                    },
579                ]
580            } else {
581                Vec::new()
582            }
583        }
584        LangId::C | LangId::Cpp | LangId::Zig | LangId::CSharp | LangId::Bash => Vec::new(),
585        LangId::Html => Vec::new(),
586        LangId::Markdown => Vec::new(),
587    }
588}
589
590fn explicit_formatter_candidate(name: &str, file_str: &str) -> Vec<ToolCandidate> {
591    match name {
592        "none" | "off" | "false" => Vec::new(),
593        "biome" => vec![ToolCandidate {
594            tool: name.to_string(),
595            source: "formatter config".to_string(),
596            args: vec![
597                "format".to_string(),
598                "--write".to_string(),
599                file_str.to_string(),
600            ],
601            required: true,
602        }],
603        "prettier" => vec![ToolCandidate {
604            tool: name.to_string(),
605            source: "formatter config".to_string(),
606            args: vec!["--write".to_string(), file_str.to_string()],
607            required: true,
608        }],
609        "deno" => vec![ToolCandidate {
610            tool: name.to_string(),
611            source: "formatter config".to_string(),
612            args: vec!["fmt".to_string(), file_str.to_string()],
613            required: true,
614        }],
615        "ruff" => vec![ToolCandidate {
616            tool: name.to_string(),
617            source: "formatter config".to_string(),
618            args: vec!["format".to_string(), file_str.to_string()],
619            required: true,
620        }],
621        "black" | "rustfmt" => vec![ToolCandidate {
622            tool: name.to_string(),
623            source: "formatter config".to_string(),
624            args: vec![file_str.to_string()],
625            required: true,
626        }],
627        "goimports" | "gofmt" => vec![ToolCandidate {
628            tool: name.to_string(),
629            source: "formatter config".to_string(),
630            args: vec!["-w".to_string(), file_str.to_string()],
631            required: true,
632        }],
633        _ => Vec::new(),
634    }
635}
636
637fn explicit_checker_candidate(name: &str, file_str: &str) -> Vec<ToolCandidate> {
638    match name {
639        "none" | "off" | "false" => Vec::new(),
640        "tsc" => vec![ToolCandidate {
641            tool: name.to_string(),
642            source: "checker config".to_string(),
643            args: vec![
644                "--noEmit".to_string(),
645                "--pretty".to_string(),
646                "false".to_string(),
647            ],
648            required: true,
649        }],
650        "cargo" => vec![ToolCandidate {
651            tool: name.to_string(),
652            source: "checker config".to_string(),
653            args: vec!["check".to_string(), "--message-format=json".to_string()],
654            required: true,
655        }],
656        "go" => vec![ToolCandidate {
657            tool: name.to_string(),
658            source: "checker config".to_string(),
659            args: vec!["vet".to_string(), file_str.to_string()],
660            required: true,
661        }],
662        "biome" => vec![ToolCandidate {
663            tool: name.to_string(),
664            source: "checker config".to_string(),
665            args: vec!["check".to_string(), file_str.to_string()],
666            required: true,
667        }],
668        "pyright" => vec![ToolCandidate {
669            tool: name.to_string(),
670            source: "checker config".to_string(),
671            args: vec!["--outputjson".to_string(), file_str.to_string()],
672            required: true,
673        }],
674        "ruff" => vec![ToolCandidate {
675            tool: name.to_string(),
676            source: "checker config".to_string(),
677            args: vec![
678                "check".to_string(),
679                "--output-format=json".to_string(),
680                file_str.to_string(),
681            ],
682            required: true,
683        }],
684        "staticcheck" => vec![ToolCandidate {
685            tool: name.to_string(),
686            source: "checker config".to_string(),
687            args: vec![file_str.to_string()],
688            required: true,
689        }],
690        _ => Vec::new(),
691    }
692}
693
694fn resolve_tool_candidates(
695    candidates: Vec<ToolCandidate>,
696    project_root: Option<&Path>,
697) -> ToolDetection {
698    if candidates.is_empty() {
699        return ToolDetection::NotConfigured;
700    }
701
702    let mut missing_required = None;
703    for candidate in candidates {
704        if let Some(command) = resolve_candidate_tool(&candidate, project_root) {
705            return ToolDetection::Found(command, candidate.args);
706        }
707        if candidate.required && missing_required.is_none() {
708            missing_required = Some(candidate.tool);
709        }
710    }
711
712    match missing_required {
713        Some(tool) => ToolDetection::NotInstalled { tool },
714        None => ToolDetection::NotConfigured,
715    }
716}
717
718fn checker_command(candidate: &ToolCandidate, resolved: String) -> String {
719    match candidate.tool.as_str() {
720        "tsc" => resolved,
721        "cargo" => "cargo".to_string(),
722        "go" => "go".to_string(),
723        _ => resolved,
724    }
725}
726
727fn checker_args(candidate: &ToolCandidate) -> Vec<String> {
728    if candidate.tool == "tsc" {
729        vec![
730            "--noEmit".to_string(),
731            "--pretty".to_string(),
732            "false".to_string(),
733        ]
734    } else {
735        candidate.args.clone()
736    }
737}
738
739fn detect_formatter_for_path(path: &Path, lang: LangId, config: &Config) -> ToolDetection {
740    let file_str = path.to_string_lossy().to_string();
741    resolve_tool_candidates(
742        formatter_candidates(lang, config, &file_str),
743        config.project_root.as_deref(),
744    )
745}
746
747fn detect_checker_for_path(path: &Path, lang: LangId, config: &Config) -> ToolDetection {
748    let file_str = path.to_string_lossy().to_string();
749    let candidates = checker_candidates(lang, config, &file_str);
750    if candidates.is_empty() {
751        return ToolDetection::NotConfigured;
752    }
753
754    let project_root = config.project_root.as_deref();
755    let mut missing_required = None;
756    for candidate in candidates {
757        if let Some(command) = resolve_candidate_tool(&candidate, project_root) {
758            return ToolDetection::Found(
759                checker_command(&candidate, command),
760                checker_args(&candidate),
761            );
762        }
763        if candidate.required && missing_required.is_none() {
764            missing_required = Some(candidate.tool);
765        }
766    }
767
768    match missing_required {
769        Some(tool) => ToolDetection::NotInstalled { tool },
770        None => ToolDetection::NotConfigured,
771    }
772}
773
774fn languages_in_project(project_root: &Path) -> HashSet<LangId> {
775    crate::callgraph::walk_project_files(project_root)
776        .filter_map(|path| detect_language(&path))
777        .collect()
778}
779
780fn placeholder_file_for_language(project_root: &Path, lang: LangId) -> PathBuf {
781    let filename = match lang {
782        LangId::TypeScript => "aft-tool-detection.ts",
783        LangId::Tsx => "aft-tool-detection.tsx",
784        LangId::JavaScript => "aft-tool-detection.js",
785        LangId::Python => "aft-tool-detection.py",
786        LangId::Rust => "aft_tool_detection.rs",
787        LangId::Go => "aft_tool_detection.go",
788        LangId::C => "aft_tool_detection.c",
789        LangId::Cpp => "aft_tool_detection.cpp",
790        LangId::Zig => "aft_tool_detection.zig",
791        LangId::CSharp => "aft_tool_detection.cs",
792        LangId::Bash => "aft_tool_detection.sh",
793        LangId::Html => "aft-tool-detection.html",
794        LangId::Markdown => "aft-tool-detection.md",
795    };
796    project_root.join(filename)
797}
798
799pub(crate) fn install_hint(tool: &str) -> String {
800    match tool {
801        "biome" => {
802            "Run `bun add -d --workspace-root @biomejs/biome` or install globally.".to_string()
803        }
804        "prettier" => "Run `npm install -D prettier` or install globally.".to_string(),
805        "tsc" => "Run `npm install -D typescript` or install globally.".to_string(),
806        "pyright" | "pyright-langserver" => "Install: `npm install -g pyright`".to_string(),
807        "ruff" => {
808            "Install: `pip install ruff` or your Python package manager equivalent.".to_string()
809        }
810        "black" => {
811            "Install: `pip install black` or your Python package manager equivalent.".to_string()
812        }
813        "rustfmt" => "Install: `rustup component add rustfmt`".to_string(),
814        "rust-analyzer" => "Install: `rustup component add rust-analyzer`".to_string(),
815        "cargo" => "Install Rust from https://rustup.rs/.".to_string(),
816        "go" => "Install Go from https://go.dev/dl/.".to_string(),
817        "gopls" => "Install: `go install golang.org/x/tools/gopls@latest`".to_string(),
818        "bash-language-server" => "Install: `npm install -g bash-language-server`".to_string(),
819        "yaml-language-server" => "Install: `npm install -g yaml-language-server`".to_string(),
820        "typescript-language-server" => {
821            "Install: `npm install -g typescript-language-server typescript`".to_string()
822        }
823        "deno" => "Install Deno from https://deno.com/.".to_string(),
824        "goimports" => "Install: `go install golang.org/x/tools/cmd/goimports@latest`".to_string(),
825        "staticcheck" => {
826            "Install: `go install honnef.co/go/tools/cmd/staticcheck@latest`".to_string()
827        }
828        other => format!("Install `{other}` and ensure it is on PATH."),
829    }
830}
831
832fn configured_tool_hint(tool: &str, source: &str) -> String {
833    format!(
834        "{tool} is configured in {source} but not installed. {}",
835        install_hint(tool)
836    )
837}
838
839fn missing_tool_warning(
840    kind: &str,
841    language: &str,
842    candidate: &ToolCandidate,
843    project_root: Option<&Path>,
844) -> Option<MissingTool> {
845    if !candidate.required || resolve_candidate_tool(candidate, project_root).is_some() {
846        return None;
847    }
848
849    Some(MissingTool {
850        kind: kind.to_string(),
851        language: language.to_string(),
852        tool: candidate.tool.clone(),
853        hint: configured_tool_hint(&candidate.tool, &candidate.source),
854    })
855}
856
857/// Detect configured formatters/checkers that are missing for languages present in the project.
858pub fn detect_missing_tools(project_root: &Path, config: &Config) -> Vec<MissingTool> {
859    let languages = languages_in_project(project_root);
860    let mut warnings = Vec::new();
861    let mut seen = HashSet::new();
862
863    for lang in languages {
864        let language = lang_key(lang);
865        let placeholder = placeholder_file_for_language(project_root, lang);
866        let file_str = placeholder.to_string_lossy().to_string();
867
868        for candidate in formatter_candidates(lang, config, &file_str) {
869            if let Some(warning) = missing_tool_warning(
870                "formatter_not_installed",
871                language,
872                &candidate,
873                config.project_root.as_deref(),
874            ) {
875                if seen.insert((
876                    warning.kind.clone(),
877                    warning.language.clone(),
878                    warning.tool.clone(),
879                )) {
880                    warnings.push(warning);
881                }
882            }
883        }
884
885        for candidate in checker_candidates(lang, config, &file_str) {
886            if let Some(warning) = missing_tool_warning(
887                "checker_not_installed",
888                language,
889                &candidate,
890                config.project_root.as_deref(),
891            ) {
892                if seen.insert((
893                    warning.kind.clone(),
894                    warning.language.clone(),
895                    warning.tool.clone(),
896                )) {
897                    warnings.push(warning);
898                }
899            }
900        }
901    }
902
903    warnings.sort_by(|left, right| {
904        (&left.kind, &left.language, &left.tool).cmp(&(&right.kind, &right.language, &right.tool))
905    });
906    warnings
907}
908
909/// Detect the appropriate formatter command and arguments for a file.
910///
911/// Priority per language:
912/// - TypeScript/JavaScript/TSX: `prettier --write <file>`
913/// - Python: `ruff format <file>` (fallback: `black <file>`)
914/// - Rust: `rustfmt <file>`
915/// - Go: `gofmt -w <file>`
916///
917/// Returns `None` if no formatter is available for the language.
918pub fn detect_formatter(
919    path: &Path,
920    lang: LangId,
921    config: &Config,
922) -> Option<(String, Vec<String>)> {
923    match detect_formatter_for_path(path, lang, config) {
924        ToolDetection::Found(cmd, args) => Some((cmd, args)),
925        ToolDetection::NotConfigured | ToolDetection::NotInstalled { .. } => None,
926    }
927}
928
929/// Check if any of the given config file names exist in the project root.
930fn has_project_config(project_root: Option<&Path>, filenames: &[&str]) -> bool {
931    let root = match project_root {
932        Some(r) => r,
933        None => return false,
934    };
935    filenames.iter().any(|f| root.join(f).exists())
936}
937
938/// Check if pyproject.toml exists and contains a `[tool.<name>]` section.
939fn has_pyproject_tool(project_root: Option<&Path>, tool_name: &str) -> bool {
940    let root = match project_root {
941        Some(r) => r,
942        None => return false,
943    };
944    let pyproject = root.join("pyproject.toml");
945    if !pyproject.exists() {
946        return false;
947    }
948    match std::fs::read_to_string(&pyproject) {
949        Ok(content) => {
950            let pattern = format!("[tool.{}]", tool_name);
951            content.contains(&pattern)
952        }
953        Err(_) => false,
954    }
955}
956
957/// Detect whether a non-zero formatter exit was caused by the formatter
958/// intentionally excluding the path (per its own config) rather than an
959/// actual formatter or input error.
960///
961/// The patterns below come from real stderr output observed during
962/// dogfooding. They're intentionally substring-based and case-insensitive
963/// so minor formatter version differences in wording don't bypass the
964/// check. Each pattern corresponds to a specific formatter's exclusion
965/// signal:
966/// - biome: `"No files were processed in the specified paths."`,
967///   `"ignored by the configuration"`
968/// - prettier: `"No files matching the pattern were found"`
969/// - ruff: `"No Python files found under the given path(s)"`
970///
971/// rustfmt and gofmt/goimports rarely scope-restrict and have no known
972/// stable marker, so they're not detected here. They'll fall through to
973/// the generic `"error"` reason — acceptable because they almost never
974/// emit a path-exclusion exit in practice.
975fn formatter_excluded_path(stderr: &str) -> bool {
976    let s = stderr.to_lowercase();
977    s.contains("no files were processed")
978        || s.contains("ignored by the configuration")
979        || s.contains("no files matching the pattern")
980        || s.contains("no python files found")
981}
982
983/// Auto-format a file using the detected formatter for its language.
984///
985/// Returns `(formatted, skip_reason)`:
986/// - `(true, None)` — file was successfully formatted
987/// - `(false, Some(reason))` — formatting was skipped, reason explains why
988///
989/// Skip reasons:
990/// - `"unsupported_language"` — language has no formatter support in AFT
991/// - `"no_formatter_configured"` — `format_on_edit=false` or no formatter
992///   detected for the language in the project
993/// - `"formatter_not_installed"` — configured formatter binary missing on
994///   PATH and not in project's `node_modules/.bin`
995/// - `"formatter_excluded_path"` — formatter ran but refused to process this
996///   path because the project formatter config (e.g. biome.json `files.includes`,
997///   prettier `.prettierignore`) excludes it. NOT an error in AFT or the user's
998///   formatter — the user told the formatter not to touch this path. Agents
999///   should treat this as informational.
1000/// - `"timeout"` — formatter exceeded `formatter_timeout_secs`
1001/// - `"error"` — formatter exited non-zero with an unrecognized error
1002///   (likely a real bug in the user's input or the formatter itself)
1003pub fn auto_format(path: &Path, config: &Config) -> (bool, Option<String>) {
1004    // Check if formatting is disabled via plugin config
1005    if !config.format_on_edit {
1006        return (false, Some("no_formatter_configured".to_string()));
1007    }
1008
1009    let lang = match detect_language(path) {
1010        Some(l) => l,
1011        None => {
1012            log::debug!("format: {} (skipped: unsupported_language)", path.display());
1013            return (false, Some("unsupported_language".to_string()));
1014        }
1015    };
1016    if !has_formatter_support(lang) {
1017        log::debug!("format: {} (skipped: unsupported_language)", path.display());
1018        return (false, Some("unsupported_language".to_string()));
1019    }
1020
1021    let (cmd, args) = match detect_formatter_for_path(path, lang, config) {
1022        ToolDetection::Found(cmd, args) => (cmd, args),
1023        ToolDetection::NotConfigured => {
1024            log::debug!(
1025                "format: {} (skipped: no_formatter_configured)",
1026                path.display()
1027            );
1028            return (false, Some("no_formatter_configured".to_string()));
1029        }
1030        ToolDetection::NotInstalled { tool } => {
1031            log::warn!(
1032                "format: {} (skipped: formatter_not_installed: {})",
1033                path.display(),
1034                tool
1035            );
1036            return (false, Some("formatter_not_installed".to_string()));
1037        }
1038    };
1039
1040    let arg_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
1041
1042    // Run the formatter in the project root so tool-local config files
1043    // (biome.json, .prettierrc, rustfmt.toml, etc.) are discovered. The
1044    // type-checker path (`validate_full`) already does this via
1045    // `path.parent()`; formatters need the same treatment. Without it,
1046    // formatters silently fall back to built-in defaults when the aft
1047    // process CWD differs from the project root (audit #18).
1048    let working_dir = config.project_root.as_deref();
1049
1050    match run_external_tool(&cmd, &arg_refs, working_dir, config.formatter_timeout_secs) {
1051        Ok(_) => {
1052            log::info!("format: {} ({})", path.display(), cmd);
1053            (true, None)
1054        }
1055        Err(FormatError::Timeout { .. }) => {
1056            log::warn!("format: {} (skipped: timeout)", path.display());
1057            (false, Some("timeout".to_string()))
1058        }
1059        Err(FormatError::NotFound { .. }) => {
1060            log::warn!(
1061                "format: {} (skipped: formatter_not_installed)",
1062                path.display()
1063            );
1064            (false, Some("formatter_not_installed".to_string()))
1065        }
1066        Err(FormatError::Failed { stderr, .. }) => {
1067            // Distinguish "formatter intentionally ignored this path" from
1068            // "formatter actually errored". Many formatters scope themselves
1069            // to a project subtree (biome.json `files.includes`, prettier
1070            // `.prettierignore`, ruff `[tool.ruff]` config) and exit non-zero
1071            // when invoked on a path outside that scope. From AFT's perspective
1072            // that's not an error — the user told the formatter not to touch
1073            // this path. But the previous code returned a generic `"error"`
1074            // skip reason and logged at `debug` (silent under default
1075            // RUST_LOG=info), so the agent had no signal that the file
1076            // landed unformatted. Detect the common stderr fingerprints and
1077            // return a distinct, surfaced skip reason.
1078            if formatter_excluded_path(&stderr) {
1079                log::info!(
1080                    "format: {} (skipped: formatter_excluded_path; stderr: {})",
1081                    path.display(),
1082                    stderr.lines().next().unwrap_or("").trim()
1083                );
1084                return (false, Some("formatter_excluded_path".to_string()));
1085            }
1086            log::warn!(
1087                "format: {} (skipped: error: {})",
1088                path.display(),
1089                stderr.lines().next().unwrap_or("unknown").trim()
1090            );
1091            (false, Some("error".to_string()))
1092        }
1093        Err(FormatError::UnsupportedLanguage) => {
1094            log::debug!("format: {} (skipped: unsupported_language)", path.display());
1095            (false, Some("unsupported_language".to_string()))
1096        }
1097    }
1098}
1099
1100/// Spawn a subprocess and capture output regardless of exit code.
1101///
1102/// Unlike `run_external_tool`, this does NOT treat non-zero exit as an error —
1103/// type checkers return non-zero when they find issues, which is expected.
1104/// Returns `FormatError::NotFound` when the binary isn't on PATH, and
1105/// `FormatError::Timeout` if the deadline is exceeded.
1106pub fn run_external_tool_capture(
1107    command: &str,
1108    args: &[&str],
1109    working_dir: Option<&Path>,
1110    timeout_secs: u32,
1111) -> Result<ExternalToolResult, FormatError> {
1112    let mut cmd = Command::new(command);
1113    cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped());
1114
1115    if let Some(dir) = working_dir {
1116        cmd.current_dir(dir);
1117    }
1118
1119    let mut child = match cmd.spawn() {
1120        Ok(c) => c,
1121        Err(e) if e.kind() == ErrorKind::NotFound => {
1122            return Err(FormatError::NotFound {
1123                tool: command.to_string(),
1124            });
1125        }
1126        Err(e) => {
1127            return Err(FormatError::Failed {
1128                tool: command.to_string(),
1129                stderr: e.to_string(),
1130            });
1131        }
1132    };
1133
1134    let deadline = Instant::now() + Duration::from_secs(timeout_secs as u64);
1135
1136    loop {
1137        match child.try_wait() {
1138            Ok(Some(status)) => {
1139                let stdout = child
1140                    .stdout
1141                    .take()
1142                    .map(|s| std::io::read_to_string(s).unwrap_or_default())
1143                    .unwrap_or_default();
1144                let stderr = child
1145                    .stderr
1146                    .take()
1147                    .map(|s| std::io::read_to_string(s).unwrap_or_default())
1148                    .unwrap_or_default();
1149
1150                return Ok(ExternalToolResult {
1151                    stdout,
1152                    stderr,
1153                    exit_code: status.code().unwrap_or(-1),
1154                });
1155            }
1156            Ok(None) => {
1157                if Instant::now() >= deadline {
1158                    let _ = child.kill();
1159                    let _ = child.wait();
1160                    return Err(FormatError::Timeout {
1161                        tool: command.to_string(),
1162                        timeout_secs,
1163                    });
1164                }
1165                thread::sleep(Duration::from_millis(50));
1166            }
1167            Err(e) => {
1168                return Err(FormatError::Failed {
1169                    tool: command.to_string(),
1170                    stderr: format!("try_wait error: {}", e),
1171                });
1172            }
1173        }
1174    }
1175}
1176
1177// ============================================================================
1178// Type-checker validation (R017)
1179// ============================================================================
1180
1181/// A structured error from a type checker.
1182#[derive(Debug, Clone, serde::Serialize)]
1183pub struct ValidationError {
1184    pub line: u32,
1185    pub column: u32,
1186    pub message: String,
1187    pub severity: String,
1188}
1189
1190/// Detect the appropriate type checker command and arguments for a file.
1191///
1192/// Returns `(command, args)` for the type checker. The `--noEmit` / equivalent
1193/// flags ensure no output files are produced.
1194///
1195/// Supported:
1196/// - TypeScript/JavaScript/TSX → `npx tsc --noEmit` (fallback: `tsc --noEmit`)
1197/// - Python → `pyright`
1198/// - Rust → `cargo check`
1199/// - Go → `go vet`
1200pub fn detect_type_checker(
1201    path: &Path,
1202    lang: LangId,
1203    config: &Config,
1204) -> Option<(String, Vec<String>)> {
1205    match detect_checker_for_path(path, lang, config) {
1206        ToolDetection::Found(cmd, args) => Some((cmd, args)),
1207        ToolDetection::NotConfigured | ToolDetection::NotInstalled { .. } => None,
1208    }
1209}
1210
1211/// Parse type checker output into structured validation errors.
1212///
1213/// Handles output formats from tsc, pyright (JSON), cargo check (JSON), and go vet.
1214/// Filters to errors related to the edited file where feasible.
1215pub fn parse_checker_output(
1216    stdout: &str,
1217    stderr: &str,
1218    file: &Path,
1219    checker: &str,
1220) -> Vec<ValidationError> {
1221    let checker_name = Path::new(checker)
1222        .file_name()
1223        .and_then(|name| name.to_str())
1224        .unwrap_or(checker);
1225    match checker_name {
1226        "npx" | "tsc" => parse_tsc_output(stdout, stderr, file),
1227        "pyright" => parse_pyright_output(stdout, file),
1228        "cargo" => parse_cargo_output(stdout, stderr, file),
1229        "go" => parse_go_vet_output(stderr, file),
1230        _ => Vec::new(),
1231    }
1232}
1233
1234/// Parse tsc output lines like: `path(line,col): error TSxxxx: message`
1235fn parse_tsc_output(stdout: &str, stderr: &str, file: &Path) -> Vec<ValidationError> {
1236    let mut errors = Vec::new();
1237    let file_str = file.to_string_lossy();
1238    // tsc writes diagnostics to stdout (with --pretty false)
1239    let combined = format!("{}{}", stdout, stderr);
1240    for line in combined.lines() {
1241        // Format: path(line,col): severity TSxxxx: message
1242        // or: path(line,col): severity: message
1243        if let Some((loc, rest)) = line.split_once("): ") {
1244            // Check if this error is for our file (compare filename part)
1245            let file_part = loc.split('(').next().unwrap_or("");
1246            if !file_str.ends_with(file_part)
1247                && !file_part.ends_with(&*file_str)
1248                && file_part != &*file_str
1249            {
1250                continue;
1251            }
1252
1253            // Parse (line,col) from the location part
1254            let coords = loc.split('(').last().unwrap_or("");
1255            let parts: Vec<&str> = coords.split(',').collect();
1256            let line_num: u32 = parts.first().and_then(|s| s.parse().ok()).unwrap_or(0);
1257            let col_num: u32 = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
1258
1259            // Parse severity and message
1260            let (severity, message) = if let Some(msg) = rest.strip_prefix("error ") {
1261                ("error".to_string(), msg.to_string())
1262            } else if let Some(msg) = rest.strip_prefix("warning ") {
1263                ("warning".to_string(), msg.to_string())
1264            } else {
1265                ("error".to_string(), rest.to_string())
1266            };
1267
1268            errors.push(ValidationError {
1269                line: line_num,
1270                column: col_num,
1271                message,
1272                severity,
1273            });
1274        }
1275    }
1276    errors
1277}
1278
1279/// Parse pyright JSON output.
1280fn parse_pyright_output(stdout: &str, file: &Path) -> Vec<ValidationError> {
1281    let mut errors = Vec::new();
1282    let file_str = file.to_string_lossy();
1283
1284    // pyright --outputjson emits JSON with generalDiagnostics array
1285    if let Ok(json) = serde_json::from_str::<serde_json::Value>(stdout) {
1286        if let Some(diags) = json.get("generalDiagnostics").and_then(|d| d.as_array()) {
1287            for diag in diags {
1288                // Filter to our file
1289                let diag_file = diag.get("file").and_then(|f| f.as_str()).unwrap_or("");
1290                if !diag_file.is_empty()
1291                    && !file_str.ends_with(diag_file)
1292                    && !diag_file.ends_with(&*file_str)
1293                    && diag_file != &*file_str
1294                {
1295                    continue;
1296                }
1297
1298                let line_num = diag
1299                    .get("range")
1300                    .and_then(|r| r.get("start"))
1301                    .and_then(|s| s.get("line"))
1302                    .and_then(|l| l.as_u64())
1303                    .unwrap_or(0) as u32;
1304                let col_num = diag
1305                    .get("range")
1306                    .and_then(|r| r.get("start"))
1307                    .and_then(|s| s.get("character"))
1308                    .and_then(|c| c.as_u64())
1309                    .unwrap_or(0) as u32;
1310                let message = diag
1311                    .get("message")
1312                    .and_then(|m| m.as_str())
1313                    .unwrap_or("unknown error")
1314                    .to_string();
1315                let severity = diag
1316                    .get("severity")
1317                    .and_then(|s| s.as_str())
1318                    .unwrap_or("error")
1319                    .to_lowercase();
1320
1321                errors.push(ValidationError {
1322                    line: line_num + 1, // pyright uses 0-indexed lines
1323                    column: col_num,
1324                    message,
1325                    severity,
1326                });
1327            }
1328        }
1329    }
1330    errors
1331}
1332
1333/// Parse cargo check JSON output, filtering to errors in the target file.
1334fn parse_cargo_output(stdout: &str, _stderr: &str, file: &Path) -> Vec<ValidationError> {
1335    let mut errors = Vec::new();
1336    let file_str = file.to_string_lossy();
1337
1338    for line in stdout.lines() {
1339        if let Ok(msg) = serde_json::from_str::<serde_json::Value>(line) {
1340            if msg.get("reason").and_then(|r| r.as_str()) != Some("compiler-message") {
1341                continue;
1342            }
1343            let message_obj = match msg.get("message") {
1344                Some(m) => m,
1345                None => continue,
1346            };
1347
1348            let level = message_obj
1349                .get("level")
1350                .and_then(|l| l.as_str())
1351                .unwrap_or("error");
1352
1353            // Only include errors and warnings, skip notes/help
1354            if level != "error" && level != "warning" {
1355                continue;
1356            }
1357
1358            let text = message_obj
1359                .get("message")
1360                .and_then(|m| m.as_str())
1361                .unwrap_or("unknown error")
1362                .to_string();
1363
1364            // Find the primary span for our file
1365            if let Some(spans) = message_obj.get("spans").and_then(|s| s.as_array()) {
1366                for span in spans {
1367                    let span_file = span.get("file_name").and_then(|f| f.as_str()).unwrap_or("");
1368                    let is_primary = span
1369                        .get("is_primary")
1370                        .and_then(|p| p.as_bool())
1371                        .unwrap_or(false);
1372
1373                    if !is_primary {
1374                        continue;
1375                    }
1376
1377                    // Filter to our file
1378                    if !file_str.ends_with(span_file)
1379                        && !span_file.ends_with(&*file_str)
1380                        && span_file != &*file_str
1381                    {
1382                        continue;
1383                    }
1384
1385                    let line_num =
1386                        span.get("line_start").and_then(|l| l.as_u64()).unwrap_or(0) as u32;
1387                    let col_num = span
1388                        .get("column_start")
1389                        .and_then(|c| c.as_u64())
1390                        .unwrap_or(0) as u32;
1391
1392                    errors.push(ValidationError {
1393                        line: line_num,
1394                        column: col_num,
1395                        message: text.clone(),
1396                        severity: level.to_string(),
1397                    });
1398                }
1399            }
1400        }
1401    }
1402    errors
1403}
1404
1405/// Parse go vet output lines like: `path:line:col: message`
1406fn parse_go_vet_output(stderr: &str, file: &Path) -> Vec<ValidationError> {
1407    let mut errors = Vec::new();
1408    let file_str = file.to_string_lossy();
1409
1410    for line in stderr.lines() {
1411        // Format: path:line:col: message  OR  path:line: message
1412        let parts: Vec<&str> = line.splitn(4, ':').collect();
1413        if parts.len() < 3 {
1414            continue;
1415        }
1416
1417        let err_file = parts[0].trim();
1418        if !file_str.ends_with(err_file)
1419            && !err_file.ends_with(&*file_str)
1420            && err_file != &*file_str
1421        {
1422            continue;
1423        }
1424
1425        let line_num: u32 = parts[1].trim().parse().unwrap_or(0);
1426        let (col_num, message) = if parts.len() >= 4 {
1427            if let Ok(col) = parts[2].trim().parse::<u32>() {
1428                (col, parts[3].trim().to_string())
1429            } else {
1430                // parts[2] is part of the message, not a column
1431                (0, format!("{}:{}", parts[2].trim(), parts[3].trim()))
1432            }
1433        } else {
1434            (0, parts[2].trim().to_string())
1435        };
1436
1437        errors.push(ValidationError {
1438            line: line_num,
1439            column: col_num,
1440            message,
1441            severity: "error".to_string(),
1442        });
1443    }
1444    errors
1445}
1446
1447/// Run the project's type checker and return structured validation errors.
1448///
1449/// Returns `(errors, skip_reason)`:
1450/// - `(errors, None)` — checker ran, errors may be empty (= valid code)
1451/// - `([], Some(reason))` — checker was skipped
1452///
1453/// Skip reasons: `"unsupported_language"`, `"no_checker_configured"`,
1454/// `"checker_not_installed"`, `"timeout"`, `"error"`
1455pub fn validate_full(path: &Path, config: &Config) -> (Vec<ValidationError>, Option<String>) {
1456    let lang = match detect_language(path) {
1457        Some(l) => l,
1458        None => {
1459            log::debug!(
1460                "validate: {} (skipped: unsupported_language)",
1461                path.display()
1462            );
1463            return (Vec::new(), Some("unsupported_language".to_string()));
1464        }
1465    };
1466    if !has_checker_support(lang) {
1467        log::debug!(
1468            "validate: {} (skipped: unsupported_language)",
1469            path.display()
1470        );
1471        return (Vec::new(), Some("unsupported_language".to_string()));
1472    }
1473
1474    let (cmd, args) = match detect_checker_for_path(path, lang, config) {
1475        ToolDetection::Found(cmd, args) => (cmd, args),
1476        ToolDetection::NotConfigured => {
1477            log::debug!(
1478                "validate: {} (skipped: no_checker_configured)",
1479                path.display()
1480            );
1481            return (Vec::new(), Some("no_checker_configured".to_string()));
1482        }
1483        ToolDetection::NotInstalled { tool } => {
1484            log::warn!(
1485                "validate: {} (skipped: checker_not_installed: {})",
1486                path.display(),
1487                tool
1488            );
1489            return (Vec::new(), Some("checker_not_installed".to_string()));
1490        }
1491    };
1492
1493    let arg_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
1494
1495    // Type checkers may need to run from the project root
1496    let working_dir = config.project_root.as_deref();
1497
1498    match run_external_tool_capture(
1499        &cmd,
1500        &arg_refs,
1501        working_dir,
1502        config.type_checker_timeout_secs,
1503    ) {
1504        Ok(result) => {
1505            let errors = parse_checker_output(&result.stdout, &result.stderr, path, &cmd);
1506            log::debug!(
1507                "validate: {} ({}, {} errors)",
1508                path.display(),
1509                cmd,
1510                errors.len()
1511            );
1512            (errors, None)
1513        }
1514        Err(FormatError::Timeout { .. }) => {
1515            log::error!("validate: {} (skipped: timeout)", path.display());
1516            (Vec::new(), Some("timeout".to_string()))
1517        }
1518        Err(FormatError::NotFound { .. }) => {
1519            log::warn!(
1520                "validate: {} (skipped: checker_not_installed)",
1521                path.display()
1522            );
1523            (Vec::new(), Some("checker_not_installed".to_string()))
1524        }
1525        Err(FormatError::Failed { stderr, .. }) => {
1526            log::debug!(
1527                "validate: {} (skipped: error: {})",
1528                path.display(),
1529                stderr.lines().next().unwrap_or("unknown")
1530            );
1531            (Vec::new(), Some("error".to_string()))
1532        }
1533        Err(FormatError::UnsupportedLanguage) => {
1534            log::debug!(
1535                "validate: {} (skipped: unsupported_language)",
1536                path.display()
1537            );
1538            (Vec::new(), Some("unsupported_language".to_string()))
1539        }
1540    }
1541}
1542
1543#[cfg(test)]
1544mod tests {
1545    use super::*;
1546    use std::fs;
1547    use std::io::Write;
1548
1549    #[test]
1550    fn run_external_tool_not_found() {
1551        let result = run_external_tool("__nonexistent_tool_xyz__", &[], None, 5);
1552        assert!(result.is_err());
1553        match result.unwrap_err() {
1554            FormatError::NotFound { tool } => {
1555                assert_eq!(tool, "__nonexistent_tool_xyz__");
1556            }
1557            other => panic!("expected NotFound, got: {:?}", other),
1558        }
1559    }
1560
1561    #[test]
1562    fn run_external_tool_timeout_kills_subprocess() {
1563        // Use `sleep 60` as a long-running process, timeout after 1 second
1564        let result = run_external_tool("sleep", &["60"], None, 1);
1565        assert!(result.is_err());
1566        match result.unwrap_err() {
1567            FormatError::Timeout { tool, timeout_secs } => {
1568                assert_eq!(tool, "sleep");
1569                assert_eq!(timeout_secs, 1);
1570            }
1571            other => panic!("expected Timeout, got: {:?}", other),
1572        }
1573    }
1574
1575    #[test]
1576    fn run_external_tool_success() {
1577        let result = run_external_tool("echo", &["hello"], None, 5);
1578        assert!(result.is_ok());
1579        let res = result.unwrap();
1580        assert_eq!(res.exit_code, 0);
1581        assert!(res.stdout.contains("hello"));
1582    }
1583
1584    #[test]
1585    fn run_external_tool_nonzero_exit() {
1586        // `false` always exits with code 1
1587        let result = run_external_tool("false", &[], None, 5);
1588        assert!(result.is_err());
1589        match result.unwrap_err() {
1590            FormatError::Failed { tool, .. } => {
1591                assert_eq!(tool, "false");
1592            }
1593            other => panic!("expected Failed, got: {:?}", other),
1594        }
1595    }
1596
1597    #[test]
1598    fn auto_format_unsupported_language() {
1599        let dir = tempfile::tempdir().unwrap();
1600        let path = dir.path().join("file.txt");
1601        fs::write(&path, "hello").unwrap();
1602
1603        let config = Config::default();
1604        let (formatted, reason) = auto_format(&path, &config);
1605        assert!(!formatted);
1606        assert_eq!(reason.as_deref(), Some("unsupported_language"));
1607    }
1608
1609    #[test]
1610    fn detect_formatter_rust_when_rustfmt_available() {
1611        let dir = tempfile::tempdir().unwrap();
1612        fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();
1613        let path = dir.path().join("test.rs");
1614        let config = Config {
1615            project_root: Some(dir.path().to_path_buf()),
1616            ..Config::default()
1617        };
1618        let result = detect_formatter(&path, LangId::Rust, &config);
1619        if resolve_tool("rustfmt", config.project_root.as_deref()).is_some() {
1620            let (cmd, args) = result.unwrap();
1621            assert_eq!(cmd, "rustfmt");
1622            assert!(args.iter().any(|a| a.ends_with("test.rs")));
1623        } else {
1624            assert!(result.is_none());
1625        }
1626    }
1627
1628    #[test]
1629    fn detect_formatter_go_mapping() {
1630        let dir = tempfile::tempdir().unwrap();
1631        fs::write(dir.path().join("go.mod"), "module test\ngo 1.21").unwrap();
1632        let path = dir.path().join("main.go");
1633        let config = Config {
1634            project_root: Some(dir.path().to_path_buf()),
1635            ..Config::default()
1636        };
1637        let result = detect_formatter(&path, LangId::Go, &config);
1638        if resolve_tool("goimports", config.project_root.as_deref()).is_some() {
1639            let (cmd, args) = result.unwrap();
1640            assert_eq!(cmd, "goimports");
1641            assert!(args.contains(&"-w".to_string()));
1642        } else if resolve_tool("gofmt", config.project_root.as_deref()).is_some() {
1643            let (cmd, args) = result.unwrap();
1644            assert_eq!(cmd, "gofmt");
1645            assert!(args.contains(&"-w".to_string()));
1646        } else {
1647            assert!(result.is_none());
1648        }
1649    }
1650
1651    #[test]
1652    fn detect_formatter_python_mapping() {
1653        let dir = tempfile::tempdir().unwrap();
1654        fs::write(dir.path().join("ruff.toml"), "").unwrap();
1655        let path = dir.path().join("main.py");
1656        let config = Config {
1657            project_root: Some(dir.path().to_path_buf()),
1658            ..Config::default()
1659        };
1660        let result = detect_formatter(&path, LangId::Python, &config);
1661        if ruff_format_available(config.project_root.as_deref()) {
1662            let (cmd, args) = result.unwrap();
1663            assert_eq!(cmd, "ruff");
1664            assert!(args.contains(&"format".to_string()));
1665        } else {
1666            assert!(result.is_none());
1667        }
1668    }
1669
1670    #[test]
1671    fn detect_formatter_no_config_returns_none() {
1672        let path = Path::new("test.ts");
1673        let result = detect_formatter(path, LangId::TypeScript, &Config::default());
1674        assert!(
1675            result.is_none(),
1676            "expected no formatter without project config"
1677        );
1678    }
1679
1680    #[test]
1681    fn detect_formatter_explicit_override() {
1682        // Create a temp dir with a fake node_modules/.bin/biome so resolve_tool finds it
1683        let dir = tempfile::tempdir().unwrap();
1684        let bin_dir = dir.path().join("node_modules").join(".bin");
1685        fs::create_dir_all(&bin_dir).unwrap();
1686        #[cfg(unix)]
1687        {
1688            use std::os::unix::fs::PermissionsExt;
1689            let fake = bin_dir.join("biome");
1690            fs::write(&fake, "#!/bin/sh\necho 1.0.0").unwrap();
1691            fs::set_permissions(&fake, fs::Permissions::from_mode(0o755)).unwrap();
1692        }
1693        #[cfg(not(unix))]
1694        {
1695            fs::write(bin_dir.join("biome.cmd"), "@echo 1.0.0").unwrap();
1696        }
1697
1698        let path = Path::new("test.ts");
1699        let mut config = Config {
1700            project_root: Some(dir.path().to_path_buf()),
1701            ..Config::default()
1702        };
1703        config
1704            .formatter
1705            .insert("typescript".to_string(), "biome".to_string());
1706        let result = detect_formatter(path, LangId::TypeScript, &config);
1707        let (cmd, args) = result.unwrap();
1708        assert!(cmd.contains("biome"), "expected biome in cmd, got: {}", cmd);
1709        assert!(args.contains(&"format".to_string()));
1710        assert!(args.contains(&"--write".to_string()));
1711    }
1712
1713    #[test]
1714    fn resolve_tool_caches_positive_result_until_clear() {
1715        clear_tool_cache();
1716        let dir = tempfile::tempdir().unwrap();
1717        let bin_dir = dir.path().join("node_modules").join(".bin");
1718        fs::create_dir_all(&bin_dir).unwrap();
1719        let tool = bin_dir.join("aft-cache-hit-tool");
1720        fs::write(&tool, "#!/bin/sh\necho cached").unwrap();
1721
1722        let first = resolve_tool("aft-cache-hit-tool", Some(dir.path()));
1723        assert_eq!(first.as_deref(), Some(tool.to_string_lossy().as_ref()));
1724
1725        fs::remove_file(&tool).unwrap();
1726        let cached = resolve_tool("aft-cache-hit-tool", Some(dir.path()));
1727        assert_eq!(cached, first);
1728
1729        clear_tool_cache();
1730        assert!(resolve_tool("aft-cache-hit-tool", Some(dir.path())).is_none());
1731    }
1732
1733    #[test]
1734    fn resolve_tool_caches_negative_result_until_clear() {
1735        clear_tool_cache();
1736        let dir = tempfile::tempdir().unwrap();
1737        let bin_dir = dir.path().join("node_modules").join(".bin");
1738        let tool = bin_dir.join("aft-cache-miss-tool");
1739
1740        assert!(resolve_tool("aft-cache-miss-tool", Some(dir.path())).is_none());
1741
1742        fs::create_dir_all(&bin_dir).unwrap();
1743        fs::write(&tool, "#!/bin/sh\necho cached").unwrap();
1744        assert!(resolve_tool("aft-cache-miss-tool", Some(dir.path())).is_none());
1745
1746        clear_tool_cache();
1747        assert_eq!(
1748            resolve_tool("aft-cache-miss-tool", Some(dir.path())).as_deref(),
1749            Some(tool.to_string_lossy().as_ref())
1750        );
1751    }
1752
1753    #[test]
1754    fn auto_format_happy_path_rustfmt() {
1755        if resolve_tool("rustfmt", None).is_none() {
1756            log::warn!("skipping: rustfmt not available");
1757            return;
1758        }
1759
1760        let dir = tempfile::tempdir().unwrap();
1761        fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();
1762        let path = dir.path().join("test.rs");
1763
1764        let mut f = fs::File::create(&path).unwrap();
1765        writeln!(f, "fn    main()   {{  println!(\"hello\");  }}").unwrap();
1766        drop(f);
1767
1768        let config = Config {
1769            project_root: Some(dir.path().to_path_buf()),
1770            ..Config::default()
1771        };
1772        let (formatted, reason) = auto_format(&path, &config);
1773        assert!(formatted, "expected formatting to succeed");
1774        assert!(reason.is_none());
1775
1776        let content = fs::read_to_string(&path).unwrap();
1777        assert!(
1778            !content.contains("fn    main"),
1779            "expected rustfmt to fix spacing"
1780        );
1781    }
1782
1783    #[test]
1784    fn formatter_excluded_path_detects_biome_messages() {
1785        // Real biome 1.x output when invoked on a path outside files.includes.
1786        let stderr = "format ━━━━━━━━━━━━━━━━━\n\n  × No files were processed in the specified paths.\n\n  i Check your biome.json or biome.jsonc to ensure the paths are not ignored by the configuration.\n";
1787        assert!(
1788            formatter_excluded_path(stderr),
1789            "expected biome exclusion stderr to be detected"
1790        );
1791    }
1792
1793    #[test]
1794    fn formatter_excluded_path_detects_prettier_messages() {
1795        // Real prettier output when given a glob/path that resolves to nothing
1796        // it's allowed to format (after .prettierignore filtering).
1797        let stderr = "[error] No files matching the pattern were found: \"src/scratch.ts\".\n";
1798        assert!(
1799            formatter_excluded_path(stderr),
1800            "expected prettier exclusion stderr to be detected"
1801        );
1802    }
1803
1804    #[test]
1805    fn formatter_excluded_path_detects_ruff_messages() {
1806        // Real ruff output when invoked outside its [tool.ruff] scope.
1807        let stderr = "warning: No Python files found under the given path(s).\n";
1808        assert!(
1809            formatter_excluded_path(stderr),
1810            "expected ruff exclusion stderr to be detected"
1811        );
1812    }
1813
1814    #[test]
1815    fn formatter_excluded_path_is_case_insensitive() {
1816        assert!(formatter_excluded_path("NO FILES WERE PROCESSED"));
1817        assert!(formatter_excluded_path("Ignored By The Configuration"));
1818    }
1819
1820    #[test]
1821    fn formatter_excluded_path_rejects_real_errors() {
1822        // Counter-cases: actual formatter errors must NOT be treated as
1823        // exclusion. This guards against the detection being too greedy.
1824        assert!(!formatter_excluded_path(""));
1825        assert!(!formatter_excluded_path("syntax error: unexpected token"));
1826        assert!(!formatter_excluded_path("formatter crashed: out of memory"));
1827        assert!(!formatter_excluded_path(
1828            "permission denied: /readonly/file"
1829        ));
1830        assert!(!formatter_excluded_path(
1831            "biome internal error: please report"
1832        ));
1833    }
1834
1835    #[test]
1836    fn parse_tsc_output_basic() {
1837        let stdout = "src/app.ts(10,5): error TS2322: Type 'string' is not assignable to type 'number'.\nsrc/app.ts(20,1): error TS2304: Cannot find name 'foo'.\n";
1838        let file = Path::new("src/app.ts");
1839        let errors = parse_tsc_output(stdout, "", file);
1840        assert_eq!(errors.len(), 2);
1841        assert_eq!(errors[0].line, 10);
1842        assert_eq!(errors[0].column, 5);
1843        assert_eq!(errors[0].severity, "error");
1844        assert!(errors[0].message.contains("TS2322"));
1845        assert_eq!(errors[1].line, 20);
1846    }
1847
1848    #[test]
1849    fn parse_tsc_output_filters_other_files() {
1850        let stdout =
1851            "other.ts(1,1): error TS2322: wrong file\nsrc/app.ts(5,3): error TS1234: our file\n";
1852        let file = Path::new("src/app.ts");
1853        let errors = parse_tsc_output(stdout, "", file);
1854        assert_eq!(errors.len(), 1);
1855        assert_eq!(errors[0].line, 5);
1856    }
1857
1858    #[test]
1859    fn parse_cargo_output_basic() {
1860        let json_line = r#"{"reason":"compiler-message","message":{"level":"error","message":"mismatched types","spans":[{"file_name":"src/main.rs","line_start":10,"column_start":5,"is_primary":true}]}}"#;
1861        let file = Path::new("src/main.rs");
1862        let errors = parse_cargo_output(json_line, "", file);
1863        assert_eq!(errors.len(), 1);
1864        assert_eq!(errors[0].line, 10);
1865        assert_eq!(errors[0].column, 5);
1866        assert_eq!(errors[0].severity, "error");
1867        assert!(errors[0].message.contains("mismatched types"));
1868    }
1869
1870    #[test]
1871    fn parse_cargo_output_skips_notes() {
1872        // Notes and help messages should be filtered out
1873        let json_line = r#"{"reason":"compiler-message","message":{"level":"note","message":"expected this","spans":[{"file_name":"src/main.rs","line_start":10,"column_start":5,"is_primary":true}]}}"#;
1874        let file = Path::new("src/main.rs");
1875        let errors = parse_cargo_output(json_line, "", file);
1876        assert_eq!(errors.len(), 0);
1877    }
1878
1879    #[test]
1880    fn parse_cargo_output_filters_other_files() {
1881        let json_line = r#"{"reason":"compiler-message","message":{"level":"error","message":"err","spans":[{"file_name":"src/other.rs","line_start":1,"column_start":1,"is_primary":true}]}}"#;
1882        let file = Path::new("src/main.rs");
1883        let errors = parse_cargo_output(json_line, "", file);
1884        assert_eq!(errors.len(), 0);
1885    }
1886
1887    #[test]
1888    fn parse_go_vet_output_basic() {
1889        let stderr = "main.go:10:5: unreachable code\nmain.go:20: another issue\n";
1890        let file = Path::new("main.go");
1891        let errors = parse_go_vet_output(stderr, file);
1892        assert_eq!(errors.len(), 2);
1893        assert_eq!(errors[0].line, 10);
1894        assert_eq!(errors[0].column, 5);
1895        assert!(errors[0].message.contains("unreachable code"));
1896        assert_eq!(errors[1].line, 20);
1897        assert_eq!(errors[1].column, 0);
1898    }
1899
1900    #[test]
1901    fn parse_pyright_output_basic() {
1902        let stdout = r#"{"generalDiagnostics":[{"file":"test.py","range":{"start":{"line":4,"character":10}},"message":"Type error here","severity":"error"}]}"#;
1903        let file = Path::new("test.py");
1904        let errors = parse_pyright_output(stdout, file);
1905        assert_eq!(errors.len(), 1);
1906        assert_eq!(errors[0].line, 5); // 0-indexed → 1-indexed
1907        assert_eq!(errors[0].column, 10);
1908        assert_eq!(errors[0].severity, "error");
1909        assert!(errors[0].message.contains("Type error here"));
1910    }
1911
1912    #[test]
1913    fn validate_full_unsupported_language() {
1914        let dir = tempfile::tempdir().unwrap();
1915        let path = dir.path().join("file.txt");
1916        fs::write(&path, "hello").unwrap();
1917
1918        let config = Config::default();
1919        let (errors, reason) = validate_full(&path, &config);
1920        assert!(errors.is_empty());
1921        assert_eq!(reason.as_deref(), Some("unsupported_language"));
1922    }
1923
1924    #[test]
1925    fn detect_type_checker_rust() {
1926        let dir = tempfile::tempdir().unwrap();
1927        fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();
1928        let path = dir.path().join("src/main.rs");
1929        let config = Config {
1930            project_root: Some(dir.path().to_path_buf()),
1931            ..Config::default()
1932        };
1933        let result = detect_type_checker(&path, LangId::Rust, &config);
1934        if resolve_tool("cargo", config.project_root.as_deref()).is_some() {
1935            let (cmd, args) = result.unwrap();
1936            assert_eq!(cmd, "cargo");
1937            assert!(args.contains(&"check".to_string()));
1938        } else {
1939            assert!(result.is_none());
1940        }
1941    }
1942
1943    #[test]
1944    fn detect_type_checker_go() {
1945        let dir = tempfile::tempdir().unwrap();
1946        fs::write(dir.path().join("go.mod"), "module test\ngo 1.21").unwrap();
1947        let path = dir.path().join("main.go");
1948        let config = Config {
1949            project_root: Some(dir.path().to_path_buf()),
1950            ..Config::default()
1951        };
1952        let result = detect_type_checker(&path, LangId::Go, &config);
1953        if resolve_tool("go", config.project_root.as_deref()).is_some() {
1954            let (cmd, _args) = result.unwrap();
1955            // Could be staticcheck or go vet depending on what's installed
1956            assert!(cmd == "go" || cmd == "staticcheck");
1957        } else {
1958            assert!(result.is_none());
1959        }
1960    }
1961    #[test]
1962    fn run_external_tool_capture_nonzero_not_error() {
1963        // `false` exits with code 1 — capture should still return Ok
1964        let result = run_external_tool_capture("false", &[], None, 5);
1965        assert!(result.is_ok(), "capture should not error on non-zero exit");
1966        assert_eq!(result.unwrap().exit_code, 1);
1967    }
1968
1969    #[test]
1970    fn run_external_tool_capture_not_found() {
1971        let result = run_external_tool_capture("__nonexistent_xyz__", &[], None, 5);
1972        assert!(result.is_err());
1973        match result.unwrap_err() {
1974            FormatError::NotFound { tool } => assert_eq!(tool, "__nonexistent_xyz__"),
1975            other => panic!("expected NotFound, got: {:?}", other),
1976        }
1977    }
1978}