cascade-environment 0.1.0-alpha.2

Execution-environment detection and planning contracts for Cascade.
Documentation
//! Environment detection requests, reports, and backend contracts.

use cascade_core::{CascadeError, CascadeResult};
use serde::{Deserialize, Serialize};

use crate::{EnvironmentKind, ExecutionMode, ToolReadiness, ToolReport, ToolRequirement};

/// Complete side-effect-free input for one environment detection pass.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DetectionRequest {
    /// Environment whose tool visibility should be inspected.
    pub environment: EnvironmentKind,
    /// Intended native or host-interoperability execution mode.
    pub execution_mode: ExecutionMode,
    /// Backend-declared tools required by the selected configuration.
    pub requirements: Vec<ToolRequirement>,
}

/// Severity of a detection issue that did not prevent report construction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum EnvironmentIssueSeverity {
    Warning,
    Error,
}

/// Structured partial-detection problem suitable for CLI, TUI, and MCP output.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnvironmentIssue {
    /// Stable machine-readable issue code.
    pub code: String,
    /// Whether the issue degrades or prevents readiness.
    pub severity: EnvironmentIssueSeverity,
    /// Human-readable context and remediation direction.
    pub message: String,
    /// Optional command whose probe produced the issue.
    pub command: Option<String>,
}

/// Environment-scoped tool readiness report.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnvironmentReport {
    pub environment: EnvironmentKind,
    pub execution_mode: ExecutionMode,
    pub tools: Vec<ToolReport>,
    pub issues: Vec<EnvironmentIssue>,
}

impl EnvironmentReport {
    /// Returns true only when all requirements are ready and no error issue exists.
    pub fn is_ready(&self) -> bool {
        self.tools
            .iter()
            .all(|tool| tool.readiness == ToolReadiness::Ready)
            && self
                .issues
                .iter()
                .all(|issue| issue.severity != EnvironmentIssueSeverity::Error)
    }
}

/// Read-only boundary implemented by host, WSL, and test detection backends.
pub trait EnvironmentDetector {
    fn detect(&self, request: &DetectionRequest) -> CascadeResult<EnvironmentReport>;
}

/// Deterministic detector used by init, doctor, and MCP orchestration tests.
///
/// It intentionally performs no normalization or command execution. Tests must
/// provide the exact report they expect orchestration to consume.
#[derive(Debug, Clone)]
pub struct StaticEnvironmentDetector {
    report: EnvironmentReport,
}

impl StaticEnvironmentDetector {
    pub fn new(report: EnvironmentReport) -> Self {
        Self { report }
    }
}

impl EnvironmentDetector for StaticEnvironmentDetector {
    fn detect(&self, request: &DetectionRequest) -> CascadeResult<EnvironmentReport> {
        if self.report.environment != request.environment
            || self.report.execution_mode != request.execution_mode
        {
            return Err(CascadeError::new(
                "static environment report does not match detection request",
            ));
        }
        Ok(self.report.clone())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{RequiredOrigin, ToolRole};

    fn request() -> DetectionRequest {
        DetectionRequest {
            environment: EnvironmentKind::wsl("Ubuntu").unwrap(),
            execution_mode: ExecutionMode::Native,
            requirements: vec![ToolRequirement {
                command: "git".to_owned(),
                role: ToolRole::Git,
                required_origin: RequiredOrigin::Native,
            }],
        }
    }

    #[test]
    fn static_detector_returns_matching_report() {
        let request = request();
        let report = EnvironmentReport {
            environment: request.environment.clone(),
            execution_mode: request.execution_mode,
            tools: Vec::new(),
            issues: Vec::new(),
        };

        assert_eq!(
            StaticEnvironmentDetector::new(report.clone())
                .detect(&request)
                .unwrap(),
            report
        );
    }

    #[test]
    fn static_detector_rejects_wrong_environment() {
        let request = request();
        let report = EnvironmentReport {
            environment: EnvironmentKind::Host,
            execution_mode: ExecutionMode::Native,
            tools: Vec::new(),
            issues: Vec::new(),
        };

        assert!(
            StaticEnvironmentDetector::new(report)
                .detect(&request)
                .is_err()
        );
    }

    #[test]
    fn report_readiness_includes_partial_detection_errors() {
        let report = EnvironmentReport {
            environment: EnvironmentKind::Host,
            execution_mode: ExecutionMode::Native,
            tools: Vec::new(),
            issues: vec![EnvironmentIssue {
                code: "probe-failed".to_owned(),
                severity: EnvironmentIssueSeverity::Error,
                message: "Git probe failed".to_owned(),
                command: Some("git".to_owned()),
            }],
        };

        assert!(!report.is_ready());
    }
}