Skip to main content

cascade_environment/
detection.rs

1//! Environment detection requests, reports, and backend contracts.
2
3use cascade_core::{CascadeError, CascadeResult};
4use serde::{Deserialize, Serialize};
5
6use crate::{EnvironmentKind, ExecutionMode, ToolReadiness, ToolReport, ToolRequirement};
7
8/// Complete side-effect-free input for one environment detection pass.
9#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
10pub struct DetectionRequest {
11    /// Environment whose tool visibility should be inspected.
12    pub environment: EnvironmentKind,
13    /// Intended native or host-interoperability execution mode.
14    pub execution_mode: ExecutionMode,
15    /// Backend-declared tools required by the selected configuration.
16    pub requirements: Vec<ToolRequirement>,
17}
18
19/// Severity of a detection issue that did not prevent report construction.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "kebab-case")]
22pub enum EnvironmentIssueSeverity {
23    Warning,
24    Error,
25}
26
27/// Structured partial-detection problem suitable for CLI, TUI, and MCP output.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29pub struct EnvironmentIssue {
30    /// Stable machine-readable issue code.
31    pub code: String,
32    /// Whether the issue degrades or prevents readiness.
33    pub severity: EnvironmentIssueSeverity,
34    /// Human-readable context and remediation direction.
35    pub message: String,
36    /// Optional command whose probe produced the issue.
37    pub command: Option<String>,
38}
39
40/// Environment-scoped tool readiness report.
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42pub struct EnvironmentReport {
43    pub environment: EnvironmentKind,
44    pub execution_mode: ExecutionMode,
45    pub tools: Vec<ToolReport>,
46    pub issues: Vec<EnvironmentIssue>,
47}
48
49impl EnvironmentReport {
50    /// Returns true only when all requirements are ready and no error issue exists.
51    pub fn is_ready(&self) -> bool {
52        self.tools
53            .iter()
54            .all(|tool| tool.readiness == ToolReadiness::Ready)
55            && self
56                .issues
57                .iter()
58                .all(|issue| issue.severity != EnvironmentIssueSeverity::Error)
59    }
60}
61
62/// Read-only boundary implemented by host, WSL, and test detection backends.
63pub trait EnvironmentDetector {
64    fn detect(&self, request: &DetectionRequest) -> CascadeResult<EnvironmentReport>;
65}
66
67/// Deterministic detector used by init, doctor, and MCP orchestration tests.
68///
69/// It intentionally performs no normalization or command execution. Tests must
70/// provide the exact report they expect orchestration to consume.
71#[derive(Debug, Clone)]
72pub struct StaticEnvironmentDetector {
73    report: EnvironmentReport,
74}
75
76impl StaticEnvironmentDetector {
77    pub fn new(report: EnvironmentReport) -> Self {
78        Self { report }
79    }
80}
81
82impl EnvironmentDetector for StaticEnvironmentDetector {
83    fn detect(&self, request: &DetectionRequest) -> CascadeResult<EnvironmentReport> {
84        if self.report.environment != request.environment
85            || self.report.execution_mode != request.execution_mode
86        {
87            return Err(CascadeError::new(
88                "static environment report does not match detection request",
89            ));
90        }
91        Ok(self.report.clone())
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98    use crate::{RequiredOrigin, ToolRole};
99
100    fn request() -> DetectionRequest {
101        DetectionRequest {
102            environment: EnvironmentKind::wsl("Ubuntu").unwrap(),
103            execution_mode: ExecutionMode::Native,
104            requirements: vec![ToolRequirement {
105                command: "git".to_owned(),
106                role: ToolRole::Git,
107                required_origin: RequiredOrigin::Native,
108            }],
109        }
110    }
111
112    #[test]
113    fn static_detector_returns_matching_report() {
114        let request = request();
115        let report = EnvironmentReport {
116            environment: request.environment.clone(),
117            execution_mode: request.execution_mode,
118            tools: Vec::new(),
119            issues: Vec::new(),
120        };
121
122        assert_eq!(
123            StaticEnvironmentDetector::new(report.clone())
124                .detect(&request)
125                .unwrap(),
126            report
127        );
128    }
129
130    #[test]
131    fn static_detector_rejects_wrong_environment() {
132        let request = request();
133        let report = EnvironmentReport {
134            environment: EnvironmentKind::Host,
135            execution_mode: ExecutionMode::Native,
136            tools: Vec::new(),
137            issues: Vec::new(),
138        };
139
140        assert!(
141            StaticEnvironmentDetector::new(report)
142                .detect(&request)
143                .is_err()
144        );
145    }
146
147    #[test]
148    fn report_readiness_includes_partial_detection_errors() {
149        let report = EnvironmentReport {
150            environment: EnvironmentKind::Host,
151            execution_mode: ExecutionMode::Native,
152            tools: Vec::new(),
153            issues: vec![EnvironmentIssue {
154                code: "probe-failed".to_owned(),
155                severity: EnvironmentIssueSeverity::Error,
156                message: "Git probe failed".to_owned(),
157                command: Some("git".to_owned()),
158            }],
159        };
160
161        assert!(!report.is_ready());
162    }
163}