use serde::{Deserialize, Serialize};
use std::ffi::OsString;
use crate::{
EnvironmentCommand, EnvironmentCommandRunner, EnvironmentKind, EnvironmentReport,
ExecutionMode, ToolReadiness, ToolRole,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RemediationApproval {
Explicit,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RemediationInteraction {
NonInteractive,
TerminalRequired,
Manual,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnvironmentRemediationOperation {
pub id: String,
pub title: String,
pub detail: String,
pub command: Option<EnvironmentCommand>,
pub approval: RemediationApproval,
pub manual: bool,
pub interaction: RemediationInteraction,
}
impl EnvironmentRemediationOperation {
pub fn command_preview(&self) -> Option<String> {
let command = self.command.as_ref()?;
Some(
std::iter::once(command.program.as_str())
.chain(command.args.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" "),
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnvironmentRemediationPlan {
pub environment: EnvironmentKind,
pub execution_mode: ExecutionMode,
pub operations: Vec<EnvironmentRemediationOperation>,
pub deferred_human_actions: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnvironmentRemediationApproval {
pub plan_id: String,
pub operation_ids: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RemediationExecutionStatus {
Applied,
Skipped,
Failed,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RemediationExecutionStep {
pub operation_id: String,
pub status: RemediationExecutionStatus,
pub detail: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnvironmentRemediationExecution {
pub plan_id: String,
pub steps: Vec<RemediationExecutionStep>,
pub stopped: bool,
}
pub fn execute_approved_remediation(
plan: &EnvironmentRemediationPlan,
approval: &EnvironmentRemediationApproval,
runner: &impl EnvironmentCommandRunner,
mut render: impl FnMut(&EnvironmentCommand) -> cascade_core::CascadeResult<EnvironmentCommand>,
) -> EnvironmentRemediationExecution {
let mut execution = EnvironmentRemediationExecution {
plan_id: approval.plan_id.clone(),
steps: Vec::new(),
stopped: false,
};
for operation in &plan.operations {
if !approval.operation_ids.contains(&operation.id) {
execution.steps.push(execution_step(
operation,
RemediationExecutionStatus::Skipped,
"not selected for approval",
));
continue;
}
if operation.manual || operation.command.is_none() {
execution.steps.push(execution_step(
operation,
RemediationExecutionStatus::Skipped,
"manual review required",
));
continue;
}
let command = match render(operation.command.as_ref().expect("checked above")) {
Ok(command) => command,
Err(error) => {
execution.steps.push(execution_step(
operation,
RemediationExecutionStatus::Failed,
&error.to_string(),
));
execution.stopped = true;
break;
}
};
let args = command.args.iter().map(OsString::from).collect::<Vec<_>>();
match runner.run(&command.program, &args) {
Ok(output) if output.exit_code == Some(0) => execution.steps.push(execution_step(
operation,
RemediationExecutionStatus::Applied,
"command completed successfully",
)),
Ok(output) => {
let detail = if output.stderr.trim().is_empty() {
format!("command exited with {:?}", output.exit_code)
} else {
output.stderr.trim().to_owned()
};
execution.steps.push(execution_step(
operation,
RemediationExecutionStatus::Failed,
&detail,
));
execution.stopped = true;
break;
}
Err(error) => {
execution.steps.push(execution_step(
operation,
RemediationExecutionStatus::Failed,
&error.to_string(),
));
execution.stopped = true;
break;
}
}
}
execution
}
fn execution_step(
operation: &EnvironmentRemediationOperation,
status: RemediationExecutionStatus,
detail: &str,
) -> RemediationExecutionStep {
RemediationExecutionStep {
operation_id: operation.id.clone(),
status,
detail: detail.to_owned(),
}
}
impl EnvironmentRemediationPlan {
pub fn validate_selection(
&self,
operation_ids: &[String],
allow_terminal: bool,
) -> cascade_core::CascadeResult<()> {
for id in operation_ids {
let operation = self
.operations
.iter()
.find(|operation| &operation.id == id)
.ok_or_else(|| {
cascade_core::CascadeError::new(format!("unknown remediation operation `{id}`"))
})?;
if operation.interaction == RemediationInteraction::TerminalRequired && !allow_terminal
{
return Err(cascade_core::CascadeError::new(format!(
"remediation operation `{id}` requires interactive terminal IO and is unavailable through MCP"
)));
}
if operation.interaction == RemediationInteraction::Manual {
return Err(cascade_core::CascadeError::new(format!(
"remediation operation `{id}` is manual and cannot be executed"
)));
}
}
Ok(())
}
pub fn from_report(report: &EnvironmentReport) -> Self {
let mut plan = Self {
environment: report.environment.clone(),
execution_mode: report.execution_mode,
operations: Vec::new(),
deferred_human_actions: Vec::new(),
};
let EnvironmentKind::Wsl { distribution } = &report.environment else {
return plan;
};
if report.execution_mode != ExecutionMode::Native {
return plan;
}
if !distribution.to_ascii_lowercase().contains("ubuntu") {
plan.operations.push(manual_operation(
"review-distribution-packages",
"Install native environment prerequisites",
format!(
"No package planner is verified for WSL distribution `{distribution}`; install the missing native tools with its supported package manager."
),
None,
));
return plan;
}
let needs = |command: &str, role: ToolRole| {
report.tools.iter().any(|tool| {
tool.requirement.command == command
&& tool.requirement.role == role
&& tool.readiness != ToolReadiness::Ready
})
};
if needs("git", ToolRole::Git) || needs("sh", ToolRole::Shell) {
plan.operations.push(command_operation(
"ubuntu-prerequisites",
"Install Ubuntu prerequisites",
"Installs native Git, curl, certificates, and a POSIX shell through apt.",
"sudo",
&["apt-get", "update"],
RemediationInteraction::TerminalRequired,
));
plan.operations.push(command_operation(
"ubuntu-prerequisites-install",
"Install Ubuntu prerequisite packages",
"Uses Ubuntu's package manager; sudo may request the user's password.",
"sudo",
&[
"apt-get",
"install",
"-y",
"git",
"curl",
"ca-certificates",
"bash",
],
RemediationInteraction::TerminalRequired,
));
}
let node_missing = needs("node", ToolRole::AgentRuntime);
if node_missing {
plan.operations.push(command_operation(
"nvm-clone",
"Install NVM without piping a remote script",
"Clones the reviewed NVM release into the user's home directory.",
"sh",
&[
"-lc",
"git clone --branch v0.40.4 --depth 1 https://github.com/nvm-sh/nvm.git \"$HOME/.nvm\"",
],
RemediationInteraction::NonInteractive,
));
plan.operations.push(command_operation(
"node-lts",
"Install Node.js LTS through NVM",
"Loads the cloned NVM installation for this command and installs the current LTS release.",
"sh",
&["-lc", ". \"$HOME/.nvm/nvm.sh\" && nvm install --lts"],
RemediationInteraction::NonInteractive,
));
}
for (command, package, title) in [
("codex", "@openai/codex", "Install Codex in Ubuntu WSL"),
(
"claude",
"@anthropic-ai/claude-code",
"Install Claude Code in Ubuntu WSL",
),
] {
if needs(command, ToolRole::Agent) {
let npm_command = if node_missing {
format!(". \"$HOME/.nvm/nvm.sh\" && nvm use --lts && npm install -g {package}")
} else {
format!("npm install -g {package}")
};
plan.operations.push(command_operation(
&format!("install-{command}"),
title,
"Installs the provider's documented CLI package; account login remains manual.",
"sh",
&["-lc", &npm_command],
RemediationInteraction::NonInteractive,
));
}
}
if needs("python3", ToolRole::AgentRuntime) {
plan.operations.push(command_operation(
"python-runtime",
"Install Python prerequisites for Mistral Vibe",
"Installs Ubuntu Python and pip prerequisites; Vibe requires Python 3.12 or newer and the resulting version must be rechecked.",
"sudo",
&["apt-get", "install", "-y", "python3", "python3-pip"],
RemediationInteraction::TerminalRequired,
));
}
if needs("uv", ToolRole::AgentRuntime) {
plan.operations.push(manual_operation(
"install-uv",
"Install uv for Mistral Vibe",
"Review the selected Python environment before installing uv; Ubuntu externally-managed Python policies differ by release.".to_owned(),
Some(EnvironmentCommand::new(
"python3",
vec!["-m".to_owned(), "pip".to_owned(), "install".to_owned(), "--user".to_owned(), "uv".to_owned()],
)),
));
}
if needs("vibe", ToolRole::Agent) {
plan.operations.push(manual_operation(
"install-vibe",
"Install Mistral Vibe in Ubuntu WSL",
"Verify Python 3.12+ and uv first, then use Mistral's documented manual installation command. Account or API-key setup remains manual.".to_owned(),
Some(EnvironmentCommand::new(
"uv",
vec!["tool".to_owned(), "install".to_owned(), "mistral-vibe".to_owned()],
)),
));
}
if report.tools.iter().any(|tool| {
tool.requirement.role == ToolRole::Cascade && tool.readiness != ToolReadiness::Ready
}) {
plan.operations.push(manual_operation(
"install-cascade",
"Install Cascade in Ubuntu WSL",
"Install a native Cascade release artifact or use an explicit cargo-install path when one is published; no stable alpha artifact command is assumed.".to_owned(),
None,
));
}
if plan.operations.iter().any(|operation| {
matches!(
operation.id.as_str(),
"install-codex" | "install-claude" | "install-vibe"
)
}) {
plan.deferred_human_actions.push(
"Complete provider login, API-key, subscription, or billing setup directly in the selected provider CLI.".to_owned(),
);
}
plan
}
}
fn command_operation(
id: &str,
title: &str,
detail: &str,
program: &str,
args: &[&str],
interaction: RemediationInteraction,
) -> EnvironmentRemediationOperation {
EnvironmentRemediationOperation {
id: id.to_owned(),
title: title.to_owned(),
detail: detail.to_owned(),
command: Some(EnvironmentCommand::new(
program,
args.iter().map(|value| (*value).to_owned()).collect(),
)),
approval: RemediationApproval::Explicit,
manual: false,
interaction,
}
}
fn manual_operation(
id: &str,
title: &str,
detail: String,
command: Option<EnvironmentCommand>,
) -> EnvironmentRemediationOperation {
EnvironmentRemediationOperation {
id: id.to_owned(),
title: title.to_owned(),
detail,
command,
approval: RemediationApproval::Explicit,
manual: true,
interaction: RemediationInteraction::Manual,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{ProbeOutput, RequiredOrigin, ToolReport, ToolRequirement};
use cascade_core::CascadeResult;
use std::cell::RefCell;
use std::ffi::OsString;
struct FakeRunner {
calls: RefCell<Vec<String>>,
fail_program: Option<String>,
}
impl EnvironmentCommandRunner for FakeRunner {
fn run(&self, program: &str, _args: &[OsString]) -> CascadeResult<ProbeOutput> {
self.calls.borrow_mut().push(program.to_owned());
let failed = self.fail_program.as_deref() == Some(program);
Ok(ProbeOutput {
stdout: String::new(),
stderr: if failed {
"installation failed".to_owned()
} else {
String::new()
},
exit_code: Some(if failed { 1 } else { 0 }),
})
}
}
fn missing(command: &str, role: ToolRole) -> ToolReport {
ToolReport::from_detection(
ToolRequirement {
command: command.to_owned(),
role,
required_origin: RequiredOrigin::Native,
},
None,
)
}
fn ubuntu_report(tools: Vec<ToolReport>) -> EnvironmentReport {
EnvironmentReport {
environment: EnvironmentKind::wsl("Ubuntu-24.04").unwrap(),
execution_mode: ExecutionMode::Native,
tools,
issues: Vec::new(),
}
}
#[test]
fn plans_ubuntu_prerequisites_node_and_provider_installs_in_order() {
let plan = EnvironmentRemediationPlan::from_report(&ubuntu_report(vec![
missing("git", ToolRole::Git),
missing("node", ToolRole::AgentRuntime),
missing("codex", ToolRole::Agent),
missing("claude", ToolRole::Agent),
missing("vibe", ToolRole::Agent),
missing("cascade", ToolRole::Cascade),
]));
assert_eq!(plan.operations[0].id, "ubuntu-prerequisites");
assert_eq!(plan.operations[2].id, "nvm-clone");
assert!(
plan.operations
.iter()
.any(|operation| operation.id == "install-codex")
);
assert!(
plan.operations
.iter()
.any(|operation| operation.id == "install-claude")
);
assert!(
plan.operations
.iter()
.any(|operation| operation.id == "install-vibe")
);
assert!(
plan.operations
.iter()
.all(|operation| operation.approval == RemediationApproval::Explicit)
);
assert_eq!(plan.deferred_human_actions.len(), 1);
}
#[test]
fn treats_wrong_origin_as_needing_a_native_install() {
let mut tool = missing("codex", ToolRole::Agent);
tool.readiness = ToolReadiness::WrongOrigin;
let plan = EnvironmentRemediationPlan::from_report(&ubuntu_report(vec![tool]));
assert_eq!(plan.operations[0].id, "install-codex");
}
#[test]
fn does_not_guess_commands_for_unverified_distributions() {
let report = EnvironmentReport {
environment: EnvironmentKind::wsl("Arch").unwrap(),
execution_mode: ExecutionMode::Native,
tools: vec![missing("git", ToolRole::Git)],
issues: Vec::new(),
};
let plan = EnvironmentRemediationPlan::from_report(&report);
assert_eq!(plan.operations.len(), 1);
assert!(plan.operations[0].manual);
assert!(plan.operations[0].command.is_none());
}
#[test]
fn host_and_interop_reports_do_not_propose_native_installs() {
let host = EnvironmentReport {
environment: EnvironmentKind::Host,
execution_mode: ExecutionMode::Native,
tools: vec![missing("git", ToolRole::Git)],
issues: Vec::new(),
};
let mut interop = ubuntu_report(vec![missing("codex", ToolRole::Agent)]);
interop.execution_mode = ExecutionMode::HostInterop;
assert!(
EnvironmentRemediationPlan::from_report(&host)
.operations
.is_empty()
);
assert!(
EnvironmentRemediationPlan::from_report(&interop)
.operations
.is_empty()
);
}
#[test]
fn command_previews_never_include_provider_authentication() {
let plan = EnvironmentRemediationPlan::from_report(&ubuntu_report(vec![
missing("codex", ToolRole::Agent),
missing("claude", ToolRole::Agent),
missing("vibe", ToolRole::Agent),
]));
let commands = plan
.operations
.iter()
.filter_map(EnvironmentRemediationOperation::command_preview)
.collect::<Vec<_>>()
.join("\n");
assert!(!commands.contains("login"));
assert!(!commands.contains("api-key"));
assert!(!commands.contains("billing"));
}
#[test]
fn executor_runs_only_approved_non_manual_operations() {
let plan = EnvironmentRemediationPlan::from_report(&ubuntu_report(vec![
missing("codex", ToolRole::Agent),
missing("vibe", ToolRole::Agent),
]));
let approval = EnvironmentRemediationApproval {
plan_id: "sha256:plan".to_owned(),
operation_ids: vec!["install-codex".to_owned(), "install-vibe".to_owned()],
};
let runner = FakeRunner {
calls: RefCell::new(Vec::new()),
fail_program: None,
};
let result =
execute_approved_remediation(&plan, &approval, &runner, |command| Ok(command.clone()));
assert_eq!(runner.calls.borrow().as_slice(), ["sh"]);
assert_eq!(result.steps[0].status, RemediationExecutionStatus::Applied);
assert_eq!(result.steps[1].status, RemediationExecutionStatus::Skipped);
assert!(!result.stopped);
}
#[test]
fn executor_stops_after_first_failed_command() {
let plan = EnvironmentRemediationPlan::from_report(&ubuntu_report(vec![missing(
"git",
ToolRole::Git,
)]));
let approval = EnvironmentRemediationApproval {
plan_id: "sha256:plan".to_owned(),
operation_ids: plan
.operations
.iter()
.map(|operation| operation.id.clone())
.collect(),
};
let runner = FakeRunner {
calls: RefCell::new(Vec::new()),
fail_program: Some("sudo".to_owned()),
};
let result =
execute_approved_remediation(&plan, &approval, &runner, |command| Ok(command.clone()));
assert!(result.stopped);
assert_eq!(result.steps.len(), 1);
assert_eq!(result.steps[0].status, RemediationExecutionStatus::Failed);
}
#[test]
fn non_interactive_selection_rejects_sudo_and_manual_operations() {
let plan = EnvironmentRemediationPlan::from_report(&ubuntu_report(vec![
missing("git", ToolRole::Git),
missing("vibe", ToolRole::Agent),
]));
assert!(
plan.validate_selection(&["ubuntu-prerequisites".to_owned()], false)
.unwrap_err()
.to_string()
.contains("interactive terminal")
);
assert!(
plan.validate_selection(&["install-vibe".to_owned()], true)
.unwrap_err()
.to_string()
.contains("manual")
);
assert!(
plan.validate_selection(&["unknown".to_owned()], true)
.is_err()
);
}
}