Skip to main content

cascade_environment/
backend.rs

1//! Real read-only host and WSL detection backends.
2
3use std::ffi::OsString;
4use std::path::Path;
5
6use cascade_core::{CascadeError, CascadeResult};
7
8use crate::{
9    DetectionRequest, EnvironmentCommandRunner, EnvironmentDetector, EnvironmentIssue,
10    EnvironmentIssueSeverity, EnvironmentKind, EnvironmentReport, ExecutableOrigin, ExecutionMode,
11    ProcessEnvironmentCommandRunner, ResolvedExecutable, ToolReport, evaluate_requirements,
12    parse_executable_path, parse_version_output, parse_wsl_distributions,
13};
14
15/// Host command lookup strategy selected independently from the build host in tests.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum HostPlatform {
18    Windows,
19    Unix,
20}
21
22impl HostPlatform {
23    pub fn current() -> Self {
24        if cfg!(windows) {
25            Self::Windows
26        } else {
27            Self::Unix
28        }
29    }
30}
31
32/// Read-only detector for the environment running Cascade.
33#[derive(Debug, Clone)]
34pub struct HostEnvironmentDetector<R = ProcessEnvironmentCommandRunner> {
35    runner: R,
36    platform: HostPlatform,
37}
38
39impl Default for HostEnvironmentDetector {
40    fn default() -> Self {
41        Self {
42            runner: ProcessEnvironmentCommandRunner,
43            platform: HostPlatform::current(),
44        }
45    }
46}
47
48impl<R> HostEnvironmentDetector<R> {
49    pub fn new(runner: R, platform: HostPlatform) -> Self {
50        Self { runner, platform }
51    }
52}
53
54impl<R: EnvironmentCommandRunner> EnvironmentDetector for HostEnvironmentDetector<R> {
55    fn detect(&self, request: &DetectionRequest) -> CascadeResult<EnvironmentReport> {
56        if request.environment != EnvironmentKind::Host {
57            return Err(CascadeError::new(
58                "host detector requires the host environment",
59            ));
60        }
61
62        let mut resolved = Vec::new();
63        let mut issues = Vec::new();
64        for requirement in &request.requirements {
65            let path_output = self.lookup(&requirement.command);
66            let path = match path_output {
67                Ok(output) if output.succeeded() => parse_executable_path(&output.stdout),
68                Ok(_) => None,
69                Err(error) => {
70                    issues.push(probe_issue(
71                        "executable-probe-failed",
72                        EnvironmentIssueSeverity::Error,
73                        &requirement.command,
74                        error.to_string(),
75                    ));
76                    None
77                }
78            };
79
80            if let Some(path) = path {
81                let version = supports_version_probe(requirement.role)
82                    .then(|| self.version(&path, &requirement.command, &mut issues))
83                    .flatten();
84                resolved.push(ResolvedExecutable {
85                    command: requirement.command.clone(),
86                    path,
87                    origin: ExecutableOrigin::Native,
88                    version,
89                });
90            }
91        }
92
93        Ok(EnvironmentReport {
94            environment: request.environment.clone(),
95            execution_mode: request.execution_mode,
96            tools: evaluate_requirements(&request.requirements, &resolved),
97            issues,
98        })
99    }
100}
101
102impl<R: EnvironmentCommandRunner> HostEnvironmentDetector<R> {
103    fn lookup(&self, command: &str) -> CascadeResult<crate::ProbeOutput> {
104        if Path::new(command).is_file() {
105            return Ok(crate::ProbeOutput {
106                stdout: command.to_owned(),
107                stderr: String::new(),
108                exit_code: Some(0),
109            });
110        }
111        match self.platform {
112            HostPlatform::Windows => {
113                let output = self.runner.run("where", &[OsString::from(command)])?;
114                if output.succeeded() && parse_executable_path(&output.stdout).is_some() {
115                    return Ok(output);
116                }
117                self.runner.run(
118                    "pwsh",
119                    &[
120                        OsString::from("-NoProfile"),
121                        OsString::from("-CommandWithArgs"),
122                        OsString::from(
123                            "$resolved = Get-Command -CommandType Application,ExternalScript -ErrorAction SilentlyContinue -- $args[0]; if ($resolved) { $resolved.Source } else { exit 1 }",
124                        ),
125                        OsString::from(command),
126                    ],
127                )
128            }
129            HostPlatform::Unix => self.runner.run(
130                "sh",
131                &[
132                    OsString::from("-c"),
133                    OsString::from("command -v -- \"$1\""),
134                    OsString::from("cascade-probe"),
135                    OsString::from(command),
136                ],
137            ),
138        }
139    }
140
141    fn version(
142        &self,
143        path: &Path,
144        command: &str,
145        issues: &mut Vec<EnvironmentIssue>,
146    ) -> Option<String> {
147        let version_output = if self.platform == HostPlatform::Windows
148            && path.extension().is_some_and(|extension| extension == "ps1")
149        {
150            self.runner.run(
151                "pwsh",
152                &[
153                    OsString::from("-NoProfile"),
154                    OsString::from("-File"),
155                    path.as_os_str().to_owned(),
156                    OsString::from("--version"),
157                ],
158            )
159        } else {
160            self.runner
161                .run(&path.to_string_lossy(), &[OsString::from("--version")])
162        };
163        match version_output {
164            Ok(output) if output.succeeded() => parse_version_output(&output.stdout),
165            Ok(output) => {
166                issues.push(probe_issue(
167                    "version-probe-failed",
168                    EnvironmentIssueSeverity::Warning,
169                    command,
170                    probe_failure_detail(&output),
171                ));
172                None
173            }
174            Err(error) => {
175                issues.push(probe_issue(
176                    "version-probe-failed",
177                    EnvironmentIssueSeverity::Warning,
178                    command,
179                    error.to_string(),
180                ));
181                None
182            }
183        }
184    }
185}
186
187/// Read-only detector for one named WSL distribution.
188#[derive(Debug, Clone)]
189pub struct WslEnvironmentDetector<R = ProcessEnvironmentCommandRunner> {
190    runner: R,
191}
192
193impl Default for WslEnvironmentDetector {
194    fn default() -> Self {
195        Self {
196            runner: ProcessEnvironmentCommandRunner,
197        }
198    }
199}
200
201impl<R> WslEnvironmentDetector<R> {
202    pub fn new(runner: R) -> Self {
203        Self { runner }
204    }
205}
206
207impl<R: EnvironmentCommandRunner> WslEnvironmentDetector<R> {
208    pub fn list_distributions(&self) -> CascadeResult<Vec<String>> {
209        let output = self.runner.run(
210            "wsl",
211            &[OsString::from("--list"), OsString::from("--quiet")],
212        )?;
213        if !output.succeeded() {
214            return Err(CascadeError::new(format!(
215                "failed to list WSL distributions: {}",
216                probe_failure_detail(&output)
217            )));
218        }
219        Ok(parse_wsl_distributions(&output.stdout))
220    }
221}
222
223impl<R: EnvironmentCommandRunner> EnvironmentDetector for WslEnvironmentDetector<R> {
224    fn detect(&self, request: &DetectionRequest) -> CascadeResult<EnvironmentReport> {
225        let EnvironmentKind::Wsl { distribution } = &request.environment else {
226            return Err(CascadeError::new("WSL detector requires a WSL environment"));
227        };
228        let mut issues = Vec::new();
229        let distributions = match self.list_distributions() {
230            Ok(distributions) => distributions,
231            Err(error) => {
232                issues.push(EnvironmentIssue {
233                    code: "wsl-unavailable".to_owned(),
234                    severity: EnvironmentIssueSeverity::Error,
235                    message: error.to_string(),
236                    command: Some("wsl".to_owned()),
237                });
238                return Ok(empty_report(request, issues));
239            }
240        };
241        if !distributions.iter().any(|value| value == distribution) {
242            issues.push(EnvironmentIssue {
243                code: "wsl-distribution-missing".to_owned(),
244                severity: EnvironmentIssueSeverity::Error,
245                message: format!("WSL distribution `{distribution}` is not installed"),
246                command: Some("wsl".to_owned()),
247            });
248            return Ok(empty_report(request, issues));
249        }
250
251        let mut resolved = Vec::new();
252        for requirement in &request.requirements {
253            let path_output = self.wsl_lookup(distribution, &requirement.command);
254            let path = match path_output {
255                Ok(output) if output.succeeded() => parse_executable_path(&output.stdout),
256                Ok(_) => None,
257                Err(error) => {
258                    issues.push(probe_issue(
259                        "executable-probe-failed",
260                        EnvironmentIssueSeverity::Error,
261                        &requirement.command,
262                        error.to_string(),
263                    ));
264                    None
265                }
266            };
267            if let Some(path) = path {
268                let version = supports_version_probe(requirement.role)
269                    .then(|| {
270                        self.wsl_version(distribution, &path, &requirement.command, &mut issues)
271                    })
272                    .flatten();
273                let origin = crate::classify_wsl_executable(&path);
274                resolved.push(ResolvedExecutable {
275                    command: requirement.command.clone(),
276                    path,
277                    origin,
278                    version,
279                });
280            }
281        }
282
283        let tools = evaluate_requirements(&request.requirements, &resolved);
284        if request.execution_mode == ExecutionMode::Native {
285            for tool in &tools {
286                if tool
287                    .resolved
288                    .as_ref()
289                    .is_some_and(|executable| executable.origin == ExecutableOrigin::HostInherited)
290                {
291                    issues.push(probe_issue(
292                        "host-inherited-tool",
293                        EnvironmentIssueSeverity::Error,
294                        &tool.requirement.command,
295                        "native WSL mode requires a guest-side executable".to_owned(),
296                    ));
297                }
298            }
299        }
300
301        Ok(EnvironmentReport {
302            environment: request.environment.clone(),
303            execution_mode: request.execution_mode,
304            tools,
305            issues,
306        })
307    }
308}
309
310impl<R: EnvironmentCommandRunner> WslEnvironmentDetector<R> {
311    fn wsl_lookup(&self, distribution: &str, command: &str) -> CascadeResult<crate::ProbeOutput> {
312        self.runner.run(
313            "wsl",
314            &[
315                OsString::from("--distribution"),
316                OsString::from(distribution),
317                OsString::from("--exec"),
318                OsString::from("sh"),
319                OsString::from("-c"),
320                OsString::from("command -v -- \"$1\""),
321                OsString::from("cascade-probe"),
322                OsString::from(command),
323            ],
324        )
325    }
326
327    fn wsl_version(
328        &self,
329        distribution: &str,
330        path: &Path,
331        command: &str,
332        issues: &mut Vec<EnvironmentIssue>,
333    ) -> Option<String> {
334        let output = self.runner.run(
335            "wsl",
336            &[
337                OsString::from("--distribution"),
338                OsString::from(distribution),
339                OsString::from("--exec"),
340                path.as_os_str().to_owned(),
341                OsString::from("--version"),
342            ],
343        );
344        match output {
345            Ok(output) if output.succeeded() => parse_version_output(&output.stdout),
346            Ok(output) => {
347                issues.push(probe_issue(
348                    "version-probe-failed",
349                    EnvironmentIssueSeverity::Warning,
350                    command,
351                    probe_failure_detail(&output),
352                ));
353                None
354            }
355            Err(error) => {
356                issues.push(probe_issue(
357                    "version-probe-failed",
358                    EnvironmentIssueSeverity::Warning,
359                    command,
360                    error.to_string(),
361                ));
362                None
363            }
364        }
365    }
366}
367
368fn empty_report(request: &DetectionRequest, issues: Vec<EnvironmentIssue>) -> EnvironmentReport {
369    EnvironmentReport {
370        environment: request.environment.clone(),
371        execution_mode: request.execution_mode,
372        tools: request
373            .requirements
374            .iter()
375            .cloned()
376            .map(|requirement| ToolReport::from_detection(requirement, None))
377            .collect(),
378        issues,
379    }
380}
381
382fn supports_version_probe(role: crate::ToolRole) -> bool {
383    !matches!(role, crate::ToolRole::Terminal | crate::ToolRole::Cascade)
384}
385
386fn probe_issue(
387    code: &str,
388    severity: EnvironmentIssueSeverity,
389    command: &str,
390    detail: String,
391) -> EnvironmentIssue {
392    EnvironmentIssue {
393        code: code.to_owned(),
394        severity,
395        message: format!("probe for `{command}` failed: {detail}"),
396        command: Some(command.to_owned()),
397    }
398}
399
400fn probe_failure_detail(output: &crate::ProbeOutput) -> String {
401    let stderr = output.stderr.trim();
402    if !stderr.is_empty() {
403        return stderr.to_owned();
404    }
405    format!("process exited with status {:?}", output.exit_code)
406}
407
408#[cfg(test)]
409mod tests {
410    use std::collections::VecDeque;
411    use std::sync::{Arc, Mutex};
412
413    use super::*;
414    use crate::{RequiredOrigin, ToolReadiness, ToolRequirement, ToolRole};
415
416    type RecordedCall = (String, Vec<OsString>);
417
418    #[derive(Debug, Clone)]
419    struct FakeRunner {
420        calls: Arc<Mutex<Vec<RecordedCall>>>,
421        outputs: Arc<Mutex<VecDeque<CascadeResult<crate::ProbeOutput>>>>,
422    }
423
424    impl FakeRunner {
425        fn new(outputs: Vec<CascadeResult<crate::ProbeOutput>>) -> Self {
426            Self {
427                calls: Arc::new(Mutex::new(Vec::new())),
428                outputs: Arc::new(Mutex::new(outputs.into())),
429            }
430        }
431
432        fn calls(&self) -> Vec<RecordedCall> {
433            self.calls.lock().unwrap().clone()
434        }
435    }
436
437    impl EnvironmentCommandRunner for FakeRunner {
438        fn run(&self, program: &str, args: &[OsString]) -> CascadeResult<crate::ProbeOutput> {
439            self.calls
440                .lock()
441                .unwrap()
442                .push((program.to_owned(), args.to_vec()));
443            self.outputs
444                .lock()
445                .unwrap()
446                .pop_front()
447                .expect("fake output")
448        }
449    }
450
451    fn output(stdout: &str) -> CascadeResult<crate::ProbeOutput> {
452        Ok(crate::ProbeOutput {
453            stdout: stdout.to_owned(),
454            stderr: String::new(),
455            exit_code: Some(0),
456        })
457    }
458
459    fn requirement(command: &str, origin: RequiredOrigin) -> ToolRequirement {
460        ToolRequirement {
461            command: command.to_owned(),
462            role: ToolRole::Agent,
463            required_origin: origin,
464        }
465    }
466
467    #[test]
468    fn unix_host_lookup_passes_tool_as_positional_argument() {
469        let runner = FakeRunner::new(vec![output("/usr/bin/git\n"), output("git 2.45\n")]);
470        let detector = HostEnvironmentDetector::new(runner.clone(), HostPlatform::Unix);
471        let request = DetectionRequest {
472            environment: EnvironmentKind::Host,
473            execution_mode: ExecutionMode::Native,
474            requirements: vec![requirement("git", RequiredOrigin::Native)],
475        };
476
477        let report = detector.detect(&request).unwrap();
478        let calls = runner.calls();
479
480        assert!(report.is_ready());
481        assert_eq!(calls[0].0, "sh");
482        assert_eq!(calls[0].1.last(), Some(&OsString::from("git")));
483        assert!(!calls[0].1[1].to_string_lossy().contains("git"));
484    }
485
486    #[test]
487    fn windows_host_uses_where_without_platform_dependent_path_parsing() {
488        let runner = FakeRunner::new(vec![
489            output("C:\\tools\\codex.exe\r\n"),
490            output("codex 0.144.5\r\n"),
491        ]);
492        let detector = HostEnvironmentDetector::new(runner.clone(), HostPlatform::Windows);
493        let request = DetectionRequest {
494            environment: EnvironmentKind::Host,
495            execution_mode: ExecutionMode::Native,
496            requirements: vec![requirement("codex", RequiredOrigin::Native)],
497        };
498
499        let report = detector.detect(&request).unwrap();
500
501        assert!(report.is_ready());
502        assert_eq!(runner.calls()[0].0, "where");
503        assert_eq!(
504            report.tools[0].resolved.as_ref().unwrap().origin,
505            ExecutableOrigin::Native
506        );
507    }
508
509    #[test]
510    fn windows_host_falls_back_to_powershell_external_script_resolution() {
511        let runner = FakeRunner::new(vec![
512            Ok(crate::ProbeOutput {
513                stdout: String::new(),
514                stderr: "not found".to_owned(),
515                exit_code: Some(1),
516            }),
517            output("C:\\Users\\user\\AppData\\Roaming\\npm\\codex.ps1\r\n"),
518            output("codex-cli 0.144.5\r\n"),
519        ]);
520        let detector = HostEnvironmentDetector::new(runner.clone(), HostPlatform::Windows);
521        let request = DetectionRequest {
522            environment: EnvironmentKind::Host,
523            execution_mode: ExecutionMode::Native,
524            requirements: vec![requirement("codex", RequiredOrigin::Native)],
525        };
526
527        let report = detector.detect(&request).unwrap();
528        let calls = runner.calls();
529
530        assert!(report.is_ready());
531        assert_eq!(calls[1].0, "pwsh");
532        assert_eq!(calls[1].1[1], OsString::from("-CommandWithArgs"));
533        assert_eq!(calls[2].0, "pwsh");
534        assert_eq!(calls[2].1[1], OsString::from("-File"));
535    }
536
537    #[test]
538    fn wsl_detector_classifies_inherited_tool_and_preserves_failed_version_path() {
539        let runner = FakeRunner::new(vec![
540            output("Ubuntu\n"),
541            output("/mnt/c/tools/codex\n"),
542            Ok(crate::ProbeOutput {
543                stdout: String::new(),
544                stderr: "version unsupported".to_owned(),
545                exit_code: Some(2),
546            }),
547        ]);
548        let detector = WslEnvironmentDetector::new(runner);
549        let request = DetectionRequest {
550            environment: EnvironmentKind::wsl("Ubuntu").unwrap(),
551            execution_mode: ExecutionMode::Native,
552            requirements: vec![requirement("codex", RequiredOrigin::Native)],
553        };
554
555        let report = detector.detect(&request).unwrap();
556
557        assert_eq!(report.tools[0].readiness, ToolReadiness::WrongOrigin);
558        assert!(report.tools[0].resolved.is_some());
559        assert!(
560            report
561                .issues
562                .iter()
563                .any(|issue| issue.code == "version-probe-failed")
564        );
565        assert!(
566            report
567                .issues
568                .iter()
569                .any(|issue| issue.code == "host-inherited-tool")
570        );
571    }
572
573    #[test]
574    fn wsl_detector_reports_unknown_distribution_before_tool_probes() {
575        let runner = FakeRunner::new(vec![output("Debian\n")]);
576        let detector = WslEnvironmentDetector::new(runner.clone());
577        let request = DetectionRequest {
578            environment: EnvironmentKind::wsl("Ubuntu").unwrap(),
579            execution_mode: ExecutionMode::Native,
580            requirements: vec![requirement("git", RequiredOrigin::Native)],
581        };
582
583        let report = detector.detect(&request).unwrap();
584
585        assert_eq!(runner.calls().len(), 1);
586        assert_eq!(report.tools[0].readiness, ToolReadiness::Missing);
587        assert_eq!(report.issues[0].code, "wsl-distribution-missing");
588    }
589
590    #[test]
591    fn missing_wsl_returns_partial_report_instead_of_aborting_detection() {
592        let runner = FakeRunner::new(vec![Err(CascadeError::new("program not found"))]);
593        let detector = WslEnvironmentDetector::new(runner);
594        let request = DetectionRequest {
595            environment: EnvironmentKind::wsl("Ubuntu").unwrap(),
596            execution_mode: ExecutionMode::HostInterop,
597            requirements: vec![requirement("cascade", RequiredOrigin::HostInherited)],
598        };
599
600        let report = detector.detect(&request).unwrap();
601
602        assert_eq!(report.issues[0].code, "wsl-unavailable");
603        assert_eq!(report.tools[0].readiness, ToolReadiness::Missing);
604    }
605}