1use serde::{Deserialize, Serialize};
7use std::ffi::OsString;
8
9use crate::{
10 EnvironmentCommand, EnvironmentCommandRunner, EnvironmentKind, EnvironmentReport,
11 ExecutionMode, ToolReadiness, ToolRole,
12};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "kebab-case")]
17pub enum RemediationApproval {
18 Explicit,
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "kebab-case")]
25pub enum RemediationInteraction {
26 NonInteractive,
28 TerminalRequired,
30 Manual,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36pub struct EnvironmentRemediationOperation {
37 pub id: String,
39 pub title: String,
41 pub detail: String,
43 pub command: Option<EnvironmentCommand>,
45 pub approval: RemediationApproval,
47 pub manual: bool,
49 pub interaction: RemediationInteraction,
51}
52
53impl EnvironmentRemediationOperation {
54 pub fn command_preview(&self) -> Option<String> {
56 let command = self.command.as_ref()?;
57 Some(
58 std::iter::once(command.program.as_str())
59 .chain(command.args.iter().map(String::as_str))
60 .collect::<Vec<_>>()
61 .join(" "),
62 )
63 }
64}
65
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68pub struct EnvironmentRemediationPlan {
69 pub environment: EnvironmentKind,
70 pub execution_mode: ExecutionMode,
71 pub operations: Vec<EnvironmentRemediationOperation>,
72 pub deferred_human_actions: Vec<String>,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78pub struct EnvironmentRemediationApproval {
79 pub plan_id: String,
81 pub operation_ids: Vec<String>,
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "kebab-case")]
88pub enum RemediationExecutionStatus {
89 Applied,
90 Skipped,
91 Failed,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96pub struct RemediationExecutionStep {
97 pub operation_id: String,
98 pub status: RemediationExecutionStatus,
99 pub detail: String,
100}
101
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
104pub struct EnvironmentRemediationExecution {
105 pub plan_id: String,
106 pub steps: Vec<RemediationExecutionStep>,
107 pub stopped: bool,
108}
109
110pub fn execute_approved_remediation(
115 plan: &EnvironmentRemediationPlan,
116 approval: &EnvironmentRemediationApproval,
117 runner: &impl EnvironmentCommandRunner,
118 mut render: impl FnMut(&EnvironmentCommand) -> cascade_core::CascadeResult<EnvironmentCommand>,
119) -> EnvironmentRemediationExecution {
120 let mut execution = EnvironmentRemediationExecution {
121 plan_id: approval.plan_id.clone(),
122 steps: Vec::new(),
123 stopped: false,
124 };
125
126 for operation in &plan.operations {
127 if !approval.operation_ids.contains(&operation.id) {
128 execution.steps.push(execution_step(
129 operation,
130 RemediationExecutionStatus::Skipped,
131 "not selected for approval",
132 ));
133 continue;
134 }
135 if operation.manual || operation.command.is_none() {
136 execution.steps.push(execution_step(
137 operation,
138 RemediationExecutionStatus::Skipped,
139 "manual review required",
140 ));
141 continue;
142 }
143 let command = match render(operation.command.as_ref().expect("checked above")) {
144 Ok(command) => command,
145 Err(error) => {
146 execution.steps.push(execution_step(
147 operation,
148 RemediationExecutionStatus::Failed,
149 &error.to_string(),
150 ));
151 execution.stopped = true;
152 break;
153 }
154 };
155 let args = command.args.iter().map(OsString::from).collect::<Vec<_>>();
156 match runner.run(&command.program, &args) {
157 Ok(output) if output.exit_code == Some(0) => execution.steps.push(execution_step(
158 operation,
159 RemediationExecutionStatus::Applied,
160 "command completed successfully",
161 )),
162 Ok(output) => {
163 let detail = if output.stderr.trim().is_empty() {
164 format!("command exited with {:?}", output.exit_code)
165 } else {
166 output.stderr.trim().to_owned()
167 };
168 execution.steps.push(execution_step(
169 operation,
170 RemediationExecutionStatus::Failed,
171 &detail,
172 ));
173 execution.stopped = true;
174 break;
175 }
176 Err(error) => {
177 execution.steps.push(execution_step(
178 operation,
179 RemediationExecutionStatus::Failed,
180 &error.to_string(),
181 ));
182 execution.stopped = true;
183 break;
184 }
185 }
186 }
187 execution
188}
189
190fn execution_step(
191 operation: &EnvironmentRemediationOperation,
192 status: RemediationExecutionStatus,
193 detail: &str,
194) -> RemediationExecutionStep {
195 RemediationExecutionStep {
196 operation_id: operation.id.clone(),
197 status,
198 detail: detail.to_owned(),
199 }
200}
201
202impl EnvironmentRemediationPlan {
203 pub fn validate_selection(
205 &self,
206 operation_ids: &[String],
207 allow_terminal: bool,
208 ) -> cascade_core::CascadeResult<()> {
209 for id in operation_ids {
210 let operation = self
211 .operations
212 .iter()
213 .find(|operation| &operation.id == id)
214 .ok_or_else(|| {
215 cascade_core::CascadeError::new(format!("unknown remediation operation `{id}`"))
216 })?;
217 if operation.interaction == RemediationInteraction::TerminalRequired && !allow_terminal
218 {
219 return Err(cascade_core::CascadeError::new(format!(
220 "remediation operation `{id}` requires interactive terminal IO and is unavailable through MCP"
221 )));
222 }
223 if operation.interaction == RemediationInteraction::Manual {
224 return Err(cascade_core::CascadeError::new(format!(
225 "remediation operation `{id}` is manual and cannot be executed"
226 )));
227 }
228 }
229 Ok(())
230 }
231
232 pub fn from_report(report: &EnvironmentReport) -> Self {
237 let mut plan = Self {
238 environment: report.environment.clone(),
239 execution_mode: report.execution_mode,
240 operations: Vec::new(),
241 deferred_human_actions: Vec::new(),
242 };
243 let EnvironmentKind::Wsl { distribution } = &report.environment else {
244 return plan;
245 };
246 if report.execution_mode != ExecutionMode::Native {
247 return plan;
248 }
249 if !distribution.to_ascii_lowercase().contains("ubuntu") {
250 plan.operations.push(manual_operation(
251 "review-distribution-packages",
252 "Install native environment prerequisites",
253 format!(
254 "No package planner is verified for WSL distribution `{distribution}`; install the missing native tools with its supported package manager."
255 ),
256 None,
257 ));
258 return plan;
259 }
260
261 let needs = |command: &str, role: ToolRole| {
262 report.tools.iter().any(|tool| {
263 tool.requirement.command == command
264 && tool.requirement.role == role
265 && tool.readiness != ToolReadiness::Ready
266 })
267 };
268
269 if needs("git", ToolRole::Git) || needs("sh", ToolRole::Shell) {
270 plan.operations.push(command_operation(
271 "ubuntu-prerequisites",
272 "Install Ubuntu prerequisites",
273 "Installs native Git, curl, certificates, and a POSIX shell through apt.",
274 "sudo",
275 &["apt-get", "update"],
276 RemediationInteraction::TerminalRequired,
277 ));
278 plan.operations.push(command_operation(
279 "ubuntu-prerequisites-install",
280 "Install Ubuntu prerequisite packages",
281 "Uses Ubuntu's package manager; sudo may request the user's password.",
282 "sudo",
283 &[
284 "apt-get",
285 "install",
286 "-y",
287 "git",
288 "curl",
289 "ca-certificates",
290 "bash",
291 ],
292 RemediationInteraction::TerminalRequired,
293 ));
294 }
295
296 let node_missing = needs("node", ToolRole::AgentRuntime);
297 if node_missing {
298 plan.operations.push(command_operation(
299 "nvm-clone",
300 "Install NVM without piping a remote script",
301 "Clones the reviewed NVM release into the user's home directory.",
302 "sh",
303 &[
304 "-lc",
305 "git clone --branch v0.40.4 --depth 1 https://github.com/nvm-sh/nvm.git \"$HOME/.nvm\"",
306 ],
307 RemediationInteraction::NonInteractive,
308 ));
309 plan.operations.push(command_operation(
310 "node-lts",
311 "Install Node.js LTS through NVM",
312 "Loads the cloned NVM installation for this command and installs the current LTS release.",
313 "sh",
314 &["-lc", ". \"$HOME/.nvm/nvm.sh\" && nvm install --lts"],
315 RemediationInteraction::NonInteractive,
316 ));
317 }
318
319 for (command, package, title) in [
320 ("codex", "@openai/codex", "Install Codex in Ubuntu WSL"),
321 (
322 "claude",
323 "@anthropic-ai/claude-code",
324 "Install Claude Code in Ubuntu WSL",
325 ),
326 ] {
327 if needs(command, ToolRole::Agent) {
328 let npm_command = if node_missing {
329 format!(". \"$HOME/.nvm/nvm.sh\" && nvm use --lts && npm install -g {package}")
330 } else {
331 format!("npm install -g {package}")
332 };
333 plan.operations.push(command_operation(
334 &format!("install-{command}"),
335 title,
336 "Installs the provider's documented CLI package; account login remains manual.",
337 "sh",
338 &["-lc", &npm_command],
339 RemediationInteraction::NonInteractive,
340 ));
341 }
342 }
343
344 if needs("python3", ToolRole::AgentRuntime) {
345 plan.operations.push(command_operation(
346 "python-runtime",
347 "Install Python prerequisites for Mistral Vibe",
348 "Installs Ubuntu Python and pip prerequisites; Vibe requires Python 3.12 or newer and the resulting version must be rechecked.",
349 "sudo",
350 &["apt-get", "install", "-y", "python3", "python3-pip"],
351 RemediationInteraction::TerminalRequired,
352 ));
353 }
354 if needs("uv", ToolRole::AgentRuntime) {
355 plan.operations.push(manual_operation(
356 "install-uv",
357 "Install uv for Mistral Vibe",
358 "Review the selected Python environment before installing uv; Ubuntu externally-managed Python policies differ by release.".to_owned(),
359 Some(EnvironmentCommand::new(
360 "python3",
361 vec!["-m".to_owned(), "pip".to_owned(), "install".to_owned(), "--user".to_owned(), "uv".to_owned()],
362 )),
363 ));
364 }
365 if needs("vibe", ToolRole::Agent) {
366 plan.operations.push(manual_operation(
367 "install-vibe",
368 "Install Mistral Vibe in Ubuntu WSL",
369 "Verify Python 3.12+ and uv first, then use Mistral's documented manual installation command. Account or API-key setup remains manual.".to_owned(),
370 Some(EnvironmentCommand::new(
371 "uv",
372 vec!["tool".to_owned(), "install".to_owned(), "mistral-vibe".to_owned()],
373 )),
374 ));
375 }
376
377 if report.tools.iter().any(|tool| {
378 tool.requirement.role == ToolRole::Cascade && tool.readiness != ToolReadiness::Ready
379 }) {
380 plan.operations.push(manual_operation(
381 "install-cascade",
382 "Install Cascade in Ubuntu WSL",
383 "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(),
384 None,
385 ));
386 }
387
388 if plan.operations.iter().any(|operation| {
389 matches!(
390 operation.id.as_str(),
391 "install-codex" | "install-claude" | "install-vibe"
392 )
393 }) {
394 plan.deferred_human_actions.push(
395 "Complete provider login, API-key, subscription, or billing setup directly in the selected provider CLI.".to_owned(),
396 );
397 }
398 plan
399 }
400}
401
402fn command_operation(
403 id: &str,
404 title: &str,
405 detail: &str,
406 program: &str,
407 args: &[&str],
408 interaction: RemediationInteraction,
409) -> EnvironmentRemediationOperation {
410 EnvironmentRemediationOperation {
411 id: id.to_owned(),
412 title: title.to_owned(),
413 detail: detail.to_owned(),
414 command: Some(EnvironmentCommand::new(
415 program,
416 args.iter().map(|value| (*value).to_owned()).collect(),
417 )),
418 approval: RemediationApproval::Explicit,
419 manual: false,
420 interaction,
421 }
422}
423
424fn manual_operation(
425 id: &str,
426 title: &str,
427 detail: String,
428 command: Option<EnvironmentCommand>,
429) -> EnvironmentRemediationOperation {
430 EnvironmentRemediationOperation {
431 id: id.to_owned(),
432 title: title.to_owned(),
433 detail,
434 command,
435 approval: RemediationApproval::Explicit,
436 manual: true,
437 interaction: RemediationInteraction::Manual,
438 }
439}
440
441#[cfg(test)]
442mod tests {
443 use super::*;
444 use crate::{ProbeOutput, RequiredOrigin, ToolReport, ToolRequirement};
445 use cascade_core::CascadeResult;
446 use std::cell::RefCell;
447 use std::ffi::OsString;
448
449 struct FakeRunner {
450 calls: RefCell<Vec<String>>,
451 fail_program: Option<String>,
452 }
453
454 impl EnvironmentCommandRunner for FakeRunner {
455 fn run(&self, program: &str, _args: &[OsString]) -> CascadeResult<ProbeOutput> {
456 self.calls.borrow_mut().push(program.to_owned());
457 let failed = self.fail_program.as_deref() == Some(program);
458 Ok(ProbeOutput {
459 stdout: String::new(),
460 stderr: if failed {
461 "installation failed".to_owned()
462 } else {
463 String::new()
464 },
465 exit_code: Some(if failed { 1 } else { 0 }),
466 })
467 }
468 }
469
470 fn missing(command: &str, role: ToolRole) -> ToolReport {
471 ToolReport::from_detection(
472 ToolRequirement {
473 command: command.to_owned(),
474 role,
475 required_origin: RequiredOrigin::Native,
476 },
477 None,
478 )
479 }
480
481 fn ubuntu_report(tools: Vec<ToolReport>) -> EnvironmentReport {
482 EnvironmentReport {
483 environment: EnvironmentKind::wsl("Ubuntu-24.04").unwrap(),
484 execution_mode: ExecutionMode::Native,
485 tools,
486 issues: Vec::new(),
487 }
488 }
489
490 #[test]
491 fn plans_ubuntu_prerequisites_node_and_provider_installs_in_order() {
492 let plan = EnvironmentRemediationPlan::from_report(&ubuntu_report(vec![
493 missing("git", ToolRole::Git),
494 missing("node", ToolRole::AgentRuntime),
495 missing("codex", ToolRole::Agent),
496 missing("claude", ToolRole::Agent),
497 missing("vibe", ToolRole::Agent),
498 missing("cascade", ToolRole::Cascade),
499 ]));
500
501 assert_eq!(plan.operations[0].id, "ubuntu-prerequisites");
502 assert_eq!(plan.operations[2].id, "nvm-clone");
503 assert!(
504 plan.operations
505 .iter()
506 .any(|operation| operation.id == "install-codex")
507 );
508 assert!(
509 plan.operations
510 .iter()
511 .any(|operation| operation.id == "install-claude")
512 );
513 assert!(
514 plan.operations
515 .iter()
516 .any(|operation| operation.id == "install-vibe")
517 );
518 assert!(
519 plan.operations
520 .iter()
521 .all(|operation| operation.approval == RemediationApproval::Explicit)
522 );
523 assert_eq!(plan.deferred_human_actions.len(), 1);
524 }
525
526 #[test]
527 fn treats_wrong_origin_as_needing_a_native_install() {
528 let mut tool = missing("codex", ToolRole::Agent);
529 tool.readiness = ToolReadiness::WrongOrigin;
530 let plan = EnvironmentRemediationPlan::from_report(&ubuntu_report(vec![tool]));
531 assert_eq!(plan.operations[0].id, "install-codex");
532 }
533
534 #[test]
535 fn does_not_guess_commands_for_unverified_distributions() {
536 let report = EnvironmentReport {
537 environment: EnvironmentKind::wsl("Arch").unwrap(),
538 execution_mode: ExecutionMode::Native,
539 tools: vec![missing("git", ToolRole::Git)],
540 issues: Vec::new(),
541 };
542 let plan = EnvironmentRemediationPlan::from_report(&report);
543 assert_eq!(plan.operations.len(), 1);
544 assert!(plan.operations[0].manual);
545 assert!(plan.operations[0].command.is_none());
546 }
547
548 #[test]
549 fn host_and_interop_reports_do_not_propose_native_installs() {
550 let host = EnvironmentReport {
551 environment: EnvironmentKind::Host,
552 execution_mode: ExecutionMode::Native,
553 tools: vec![missing("git", ToolRole::Git)],
554 issues: Vec::new(),
555 };
556 let mut interop = ubuntu_report(vec![missing("codex", ToolRole::Agent)]);
557 interop.execution_mode = ExecutionMode::HostInterop;
558 assert!(
559 EnvironmentRemediationPlan::from_report(&host)
560 .operations
561 .is_empty()
562 );
563 assert!(
564 EnvironmentRemediationPlan::from_report(&interop)
565 .operations
566 .is_empty()
567 );
568 }
569
570 #[test]
571 fn command_previews_never_include_provider_authentication() {
572 let plan = EnvironmentRemediationPlan::from_report(&ubuntu_report(vec![
573 missing("codex", ToolRole::Agent),
574 missing("claude", ToolRole::Agent),
575 missing("vibe", ToolRole::Agent),
576 ]));
577 let commands = plan
578 .operations
579 .iter()
580 .filter_map(EnvironmentRemediationOperation::command_preview)
581 .collect::<Vec<_>>()
582 .join("\n");
583 assert!(!commands.contains("login"));
584 assert!(!commands.contains("api-key"));
585 assert!(!commands.contains("billing"));
586 }
587
588 #[test]
589 fn executor_runs_only_approved_non_manual_operations() {
590 let plan = EnvironmentRemediationPlan::from_report(&ubuntu_report(vec![
591 missing("codex", ToolRole::Agent),
592 missing("vibe", ToolRole::Agent),
593 ]));
594 let approval = EnvironmentRemediationApproval {
595 plan_id: "sha256:plan".to_owned(),
596 operation_ids: vec!["install-codex".to_owned(), "install-vibe".to_owned()],
597 };
598 let runner = FakeRunner {
599 calls: RefCell::new(Vec::new()),
600 fail_program: None,
601 };
602
603 let result =
604 execute_approved_remediation(&plan, &approval, &runner, |command| Ok(command.clone()));
605
606 assert_eq!(runner.calls.borrow().as_slice(), ["sh"]);
607 assert_eq!(result.steps[0].status, RemediationExecutionStatus::Applied);
608 assert_eq!(result.steps[1].status, RemediationExecutionStatus::Skipped);
609 assert!(!result.stopped);
610 }
611
612 #[test]
613 fn executor_stops_after_first_failed_command() {
614 let plan = EnvironmentRemediationPlan::from_report(&ubuntu_report(vec![missing(
615 "git",
616 ToolRole::Git,
617 )]));
618 let approval = EnvironmentRemediationApproval {
619 plan_id: "sha256:plan".to_owned(),
620 operation_ids: plan
621 .operations
622 .iter()
623 .map(|operation| operation.id.clone())
624 .collect(),
625 };
626 let runner = FakeRunner {
627 calls: RefCell::new(Vec::new()),
628 fail_program: Some("sudo".to_owned()),
629 };
630
631 let result =
632 execute_approved_remediation(&plan, &approval, &runner, |command| Ok(command.clone()));
633
634 assert!(result.stopped);
635 assert_eq!(result.steps.len(), 1);
636 assert_eq!(result.steps[0].status, RemediationExecutionStatus::Failed);
637 }
638
639 #[test]
640 fn non_interactive_selection_rejects_sudo_and_manual_operations() {
641 let plan = EnvironmentRemediationPlan::from_report(&ubuntu_report(vec![
642 missing("git", ToolRole::Git),
643 missing("vibe", ToolRole::Agent),
644 ]));
645 assert!(
646 plan.validate_selection(&["ubuntu-prerequisites".to_owned()], false)
647 .unwrap_err()
648 .to_string()
649 .contains("interactive terminal")
650 );
651 assert!(
652 plan.validate_selection(&["install-vibe".to_owned()], true)
653 .unwrap_err()
654 .to_string()
655 .contains("manual")
656 );
657 assert!(
658 plan.validate_selection(&["unknown".to_owned()], true)
659 .is_err()
660 );
661 }
662}