cascade-environment 0.1.0-alpha.2

Execution-environment detection and planning contracts for Cascade.
Documentation
//! Environment-owned command adaptation.
//!
//! This module renders a command that is valid at the selected execution
//! boundary. It does not open terminals or choose tabs, panes, or shells.

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

use crate::{EnvironmentKind, ExecutionMode};

/// Structured command before or after environment adaptation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnvironmentCommand {
    pub program: String,
    pub args: Vec<String>,
    pub env: Vec<(String, String)>,
}

impl EnvironmentCommand {
    pub fn new(program: impl Into<String>, args: Vec<String>) -> Self {
        Self {
            program: program.into(),
            args,
            env: Vec::new(),
        }
    }
}

/// Complete input for one side-effect-free command adaptation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnvironmentRenderRequest {
    pub environment: EnvironmentKind,
    pub execution_mode: ExecutionMode,
    pub command: EnvironmentCommand,
}

/// Host-side request for launching a command inside one WSL distribution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WslLaunchRequest {
    /// Optional named distribution; `None` uses the user's default distribution.
    pub distribution: Option<String>,
    /// Native guest execution or Windows-host interoperability.
    pub execution_mode: ExecutionMode,
    /// Working directory passed to WSL before command execution.
    pub cwd: PathBuf,
    /// Inner agent or Cascade supervisor command.
    pub command: EnvironmentCommand,
}

/// Side-effect-free boundary for host, WSL-native, and interoperability rendering.
pub trait EnvironmentCommandRenderer {
    fn render(&self, request: &EnvironmentRenderRequest) -> CascadeResult<EnvironmentCommand>;
}

/// Default renderer for host and WSL execution boundaries.
#[derive(Debug, Clone, Copy, Default)]
pub struct DefaultEnvironmentCommandRenderer;

impl EnvironmentCommandRenderer for DefaultEnvironmentCommandRenderer {
    fn render(&self, request: &EnvironmentRenderRequest) -> CascadeResult<EnvironmentCommand> {
        match (&request.environment, request.execution_mode) {
            (EnvironmentKind::Host, _) => Ok(request.command.clone()),
            (EnvironmentKind::Wsl { .. }, ExecutionMode::HostInterop) => {
                Ok(render_wsl_host_interop_command(&request.command))
            }
            (EnvironmentKind::Wsl { distribution }, ExecutionMode::Native) => {
                if is_host_executable_path(&request.command.program) {
                    return Err(CascadeError::new(format!(
                        "native WSL environment `{distribution}` requires a guest-side executable; `{}` is host-owned",
                        request.command.program
                    )));
                }
                if let Some((_, mcp_command)) = request
                    .command
                    .env
                    .iter()
                    .find(|(key, _)| key == "CASCADE_MCP_COMMAND")
                    && is_host_executable_path(mcp_command)
                {
                    return Err(CascadeError::new(format!(
                        "native WSL environment `{distribution}` requires a guest-side Cascade MCP executable; `{mcp_command}` is host-owned"
                    )));
                }
                Ok(request.command.clone())
            }
        }
    }
}

/// Adapts a host command for WSL interoperability without choosing a shell.
///
/// This path is infallible: bare commands and already guest-visible paths are
/// preserved, while absolute Windows executables are translated to `/mnt/...`.
pub fn render_wsl_host_interop_command(command: &EnvironmentCommand) -> EnvironmentCommand {
    let mut rendered = command.clone();
    if let Some(program) = windows_path_to_wsl(&rendered.program) {
        rendered.program = program;
    }
    rendered
}

/// Renders the complete host-side `wsl` invocation for one inner command.
pub fn render_wsl_launch(request: &WslLaunchRequest) -> CascadeResult<EnvironmentCommand> {
    let distribution = request
        .distribution
        .clone()
        .unwrap_or_else(|| "default".to_owned());
    let inner = DefaultEnvironmentCommandRenderer.render(&EnvironmentRenderRequest {
        environment: EnvironmentKind::Wsl { distribution },
        execution_mode: request.execution_mode,
        command: request.command.clone(),
    })?;
    let mut args = Vec::new();
    if let Some(distribution) = &request.distribution {
        args.extend(["--distribution".to_owned(), distribution.clone()]);
    }
    args.extend([
        "--cd".to_owned(),
        request.cwd.to_string_lossy().into_owned(),
        "--exec".to_owned(),
    ]);
    if !inner.env.is_empty() {
        args.push("env".to_owned());
        args.extend(
            inner
                .env
                .iter()
                .map(|(key, value)| format!("{key}={value}")),
        );
    }
    args.push(inner.program);
    args.extend(inner.args);

    Ok(EnvironmentCommand::new("wsl", args))
}

/// Converts an absolute Windows path to its generic WSL mount path.
///
/// Non-Windows paths return `None`; callers can preserve them unchanged.
pub fn windows_path_to_wsl(value: &str) -> Option<String> {
    let bytes = value.as_bytes();
    if bytes.len() < 3
        || !bytes[0].is_ascii_alphabetic()
        || bytes[1] != b':'
        || !matches!(bytes[2], b'\\' | b'/')
    {
        return None;
    }

    let drive = (bytes[0] as char).to_ascii_lowercase();
    let tail = value[3..].replace('\\', "/");
    Some(format!("/mnt/{drive}/{tail}"))
}

fn is_host_executable_path(program: &str) -> bool {
    windows_path_to_wsl(program).is_some() || is_wsl_mounted_host_path(program)
}

fn is_wsl_mounted_host_path(program: &str) -> bool {
    let normalized = program.replace('\\', "/");
    let mut components = normalized.split('/').filter(|part| !part.is_empty());
    matches!(
        (components.next(), components.next(), components.next()),
        (Some("mnt"), Some(drive), Some(_))
            if drive.len() == 1
                && drive.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    fn request(
        environment: EnvironmentKind,
        execution_mode: ExecutionMode,
        program: &str,
    ) -> EnvironmentRenderRequest {
        EnvironmentRenderRequest {
            environment,
            execution_mode,
            command: EnvironmentCommand {
                program: program.to_owned(),
                args: vec!["agent-run".to_owned(), "repo".to_owned()],
                env: vec![("CASCADE_BRANCH".to_owned(), "dev".to_owned())],
            },
        }
    }

    #[test]
    fn host_rendering_preserves_structured_command() {
        let request = request(EnvironmentKind::Host, ExecutionMode::Native, "cascade");

        assert_eq!(
            DefaultEnvironmentCommandRenderer.render(&request).unwrap(),
            request.command
        );
    }

    #[test]
    fn host_interop_translates_only_windows_executable_boundary() {
        let request = request(
            EnvironmentKind::wsl("Ubuntu").unwrap(),
            ExecutionMode::HostInterop,
            "Z:\\tools\\cascade.exe",
        );
        let rendered = DefaultEnvironmentCommandRenderer.render(&request).unwrap();

        assert_eq!(rendered.program, "/mnt/z/tools/cascade.exe");
        assert_eq!(rendered.args, request.command.args);
        assert_eq!(rendered.env, request.command.env);
    }

    #[test]
    fn native_wsl_preserves_guest_command() {
        let request = request(
            EnvironmentKind::wsl("Ubuntu").unwrap(),
            ExecutionMode::Native,
            "/home/user/.local/bin/cascade",
        );

        assert_eq!(
            DefaultEnvironmentCommandRenderer.render(&request).unwrap(),
            request.command
        );
    }

    #[test]
    fn native_wsl_rejects_windows_and_mounted_host_executables() {
        for program in ["E:\\code\\cascade\\cascade.exe", "/mnt/c/tools/cascade.exe"] {
            let request = request(
                EnvironmentKind::wsl("Ubuntu").unwrap(),
                ExecutionMode::Native,
                program,
            );

            let error = DefaultEnvironmentCommandRenderer
                .render(&request)
                .expect_err("host executable must be rejected");
            assert!(
                error
                    .to_string()
                    .contains("requires a guest-side executable")
            );
        }
    }

    #[test]
    fn native_wsl_rejects_host_owned_mcp_command() {
        let mut request = request(
            EnvironmentKind::wsl("Ubuntu").unwrap(),
            ExecutionMode::Native,
            "codex",
        );
        request.command.env.push((
            "CASCADE_MCP_COMMAND".to_owned(),
            "E:\\tools\\cascade.exe".to_owned(),
        ));

        let error = DefaultEnvironmentCommandRenderer
            .render(&request)
            .expect_err("host MCP executable must be rejected");

        assert!(
            error
                .to_string()
                .contains("guest-side Cascade MCP executable")
        );
    }

    #[test]
    fn wsl_launch_renders_distribution_cwd_environment_and_native_command() {
        let rendered = render_wsl_launch(&WslLaunchRequest {
            distribution: Some("Ubuntu".to_owned()),
            execution_mode: ExecutionMode::Native,
            cwd: PathBuf::from("/home/user/project"),
            command: EnvironmentCommand {
                program: "/home/user/.local/bin/cascade".to_owned(),
                args: vec!["agent-run".to_owned(), "dev".to_owned()],
                env: vec![("CASCADE_MCP_COMMAND".to_owned(), "cascade".to_owned())],
            },
        })
        .unwrap();

        assert_eq!(rendered.program, "wsl");
        assert_eq!(
            rendered.args,
            [
                "--distribution",
                "Ubuntu",
                "--cd",
                "/home/user/project",
                "--exec",
                "env",
                "CASCADE_MCP_COMMAND=cascade",
                "/home/user/.local/bin/cascade",
                "agent-run",
                "dev",
            ]
        );
    }

    #[test]
    fn wsl_launch_preserves_default_distribution_and_host_interop_arguments() {
        let rendered = render_wsl_launch(&WslLaunchRequest {
            distribution: None,
            execution_mode: ExecutionMode::HostInterop,
            cwd: PathBuf::from("C:/code/project"),
            command: EnvironmentCommand::new(
                "E:\\tools\\cascade.exe",
                vec!["agent-run".to_owned(), "C:/code/project".to_owned()],
            ),
        })
        .unwrap();

        assert_eq!(
            rendered.args,
            [
                "--cd",
                "C:/code/project",
                "--exec",
                "/mnt/e/tools/cascade.exe",
                "agent-run",
                "C:/code/project",
            ]
        );
    }

    #[test]
    fn windows_path_conversion_is_drive_and_user_independent() {
        assert_eq!(
            windows_path_to_wsl("Q:/code/project/cascade.exe").as_deref(),
            Some("/mnt/q/code/project/cascade.exe")
        );
        assert!(windows_path_to_wsl("/usr/local/bin/cascade").is_none());
        assert!(windows_path_to_wsl("cascade").is_none());
    }
}