diff --git a/README.md b/README.md index 9473fba23b..496b267bbb 100644 --- a/README.md +++ b/README.md @@ -1454,11 +1454,15 @@ non-zero too, after printing its log. `rocm uninstall` removes four categories of files that ROCm CLI manages on this computer: its binaries, configuration, data, and caches. It lists what it will do and asks `[y/N]` (default: no) before doing it. Use `--dry-run` to only list, -and `--yes` to skip the confirmation. It does not create the folders it reports -on: with `--keep-binaries`, on a computer where ROCm CLI never ran, it says there -is nothing to remove. Outside an interactive terminal, when there is something -to remove, it refuses with exit code 1 and removes nothing unless you pass -`--yes`. Each `--keep-*` flag skips the removal of one category: +and `--yes` to skip the confirmation. There is no `--force`; `--force-dev-binaries` +is a separate opt-in for development builds. At a terminal, a dry run that finds +something to remove ends by saying to run the same command again without +`--dry-run`; with nothing to remove, or when stdin or stdout is not a terminal +(its output is piped or its input is redirected), it says nothing about a next step. It does not create the folders it reports on: +with `--keep-binaries`, on a computer where ROCm CLI never ran, it says there is +nothing to remove. Outside an interactive terminal, when there is something to +remove, it refuses with exit code 1 and removes nothing unless you pass `--yes`. +Each `--keep-*` flag skips the removal of one category: - `--keep-binaries` keeps the installed ROCm CLI binaries. - `--keep-config` keeps your saved settings. diff --git a/apps/rocm/src/cli.rs b/apps/rocm/src/cli.rs index 222a5ef726..68656bdbec 100644 --- a/apps/rocm/src/cli.rs +++ b/apps/rocm/src/cli.rs @@ -641,6 +641,10 @@ rocm logs --search error timeout")] /// PATH change the installer made (its marked shell-profile block, or the /// user PATH entry it recorded adding on Windows), unless other programs /// share the install folder. + #[command(after_help = "EXAMPLES:\n \ +rocm uninstall --dry-run\n \ +rocm uninstall\n \ +rocm uninstall --keep-data --yes")] Uninstall { /// Do not ask for interactive confirmation. Without it, the command /// asks `[y/N]` (default: no) in an interactive terminal; outside one, @@ -668,6 +672,11 @@ rocm logs --search error timeout")] /// Allow removing development binaries inside the current build tree. #[arg(long)] force_dev_binaries: bool, + /// Not an option; accepted only to say so. Without it clap answers a + /// mistyped `--force` (a likely guess for skipping the confirmation) + /// with `--force-dev-binaries`, which removes development binaries. + #[arg(long, hide = true, num_args = 0..=1, default_missing_value = "")] + force: Option, }, } @@ -1412,7 +1421,7 @@ impl PermissionsModeArg { #[cfg(test)] mod tests { use super::*; - use crate::{cli_command, device_policy_name, engine_inventory}; + use crate::{cli_command, device_policy_name, engine_inventory, uninstall::reject_force}; use clap::{CommandFactory, Parser}; use rocm_engine_protocol::DevicePolicy; @@ -2259,6 +2268,124 @@ mod tests { .expect_err("an abbreviated subcommand name must not reach uninstall"); } + /// `--force` is a likely guess for "skip the confirmation", and without a + /// declared `--force` clap answers it, and every near miss of it, with + /// `--force-dev-binaries`, which removes the binaries of a development build. + /// The scenario `uninstall-mistyped-force-is-not-answered-with-a-destructive-flag` + /// proves the real binary's output; this pins the parse behind it. + #[test] + fn a_mistyped_force_never_reaches_the_dev_binaries_flag() { + // `--force` itself parses, so the handler can say what to use instead. + let cli = Cli::try_parse_from(["rocm", "uninstall", "--force"]).unwrap(); + let Some(Command::Uninstall { + force, + force_dev_binaries, + .. + }) = cli.command + else { + panic!("not an uninstall command"); + }; + assert!(force.is_some() && !force_dev_binaries); + let refusal = reject_force(force.is_some()).unwrap_err().to_string(); + assert!(refusal.contains("`--force` is not an option"), "{refusal}"); + assert!(refusal.contains("--yes"), "{refusal}"); + assert!(!refusal.contains("force-dev-binaries"), "{refusal}"); + assert!(reject_force(false).is_ok()); + // `--force=x` is the same mistake, and gets the same answer rather than + // a usage line that lists every flag. + let cli = Cli::try_parse_from(["rocm", "uninstall", "--force=x"]).unwrap(); + let Some(Command::Uninstall { force, .. }) = cli.command else { + panic!("not an uninstall command"); + }; + assert!(reject_force(force.is_some()).is_err()); + + // Near misses and the forms clap suggests from elsewhere in the command + // line never offer the destructive flag. + for args in [ + vec!["uninstall", "--forc"], + vec!["uninstall", "--forcee"], + vec!["uninstall", "--keep-binaries", "--forc"], + vec!["uninstall", "-f"], + vec!["--force", "uninstall"], + ] { + let error = cli_command() + .try_get_matches_from(std::iter::once("rocm").chain(args.iter().copied())) + .unwrap_err(); + let rendered = error.render().to_string(); + assert!( + !rendered.contains("force-dev-binaries"), + "{args:?} was answered with the destructive flag:\n{rendered}" + ); + assert_eq!(error.exit_code(), 2, "{args:?}"); + } + + // The guard depends on clap offering the hidden `--force` as the + // suggestion for a near miss: its candidates are every declared long + // name, hidden or not. If a clap upgrade stopped suggesting hidden + // arguments, `--forc` would be answered with `--force-dev-binaries` + // again, so the near misses must name `--force` and not the + // destructive flag. The two checks together are independent of + // clap's wording around the suggestion. + for args in [ + vec!["uninstall", "--forc"], + vec!["uninstall", "--keep-binaries", "--forc"], + ] { + let rendered = cli_command() + .try_get_matches_from(std::iter::once("rocm").chain(args.iter().copied())) + .unwrap_err() + .render() + .to_string(); + assert!( + rendered.contains("--force") && !rendered.contains("force-dev-binaries"), + "{args:?} must be steered to the declared `--force`, not the destructive flag:\n{rendered}" + ); + } + + // The whole flag misspelled is still met with the flag it was meant to be. + let error = cli_command() + .try_get_matches_from(["rocm", "uninstall", "--force-dev-binary"]) + .unwrap_err() + .render() + .to_string(); + assert!(error.contains("--force-dev-binaries"), "{error}"); + + // It stays out of the help. + let mut command = cli_command(); + let help = command + .find_subcommand_mut("uninstall") + .unwrap() + .render_long_help() + .to_string(); + assert!(!help.contains("Not an option"), "{help}"); + } + + /// The help leads with the safe preview, then the real run, as the tip a + /// person reads before running a command that deletes things. + #[test] + fn uninstall_help_shows_a_dry_run_before_the_real_run() { + let mut command = cli_command(); + let help = command + .find_subcommand_mut("uninstall") + .expect("uninstall subcommand") + .render_long_help() + .to_string(); + let examples = help.split_once("EXAMPLES:").map_or_else( + || panic!("`rocm uninstall --help` has no examples:\n{help}"), + |(_, rest)| rest, + ); + let rows: Vec<&str> = examples + .lines() + .map(str::trim) + .filter(|line| !line.is_empty()) + .collect(); + assert_eq!( + rows.first().copied(), + Some("rocm uninstall --dry-run"), + "{examples}" + ); + assert!(rows.contains(&"rocm uninstall"), "{examples}"); + } + #[test] fn update_rejects_zero_timeout_secs() { let error = Cli::try_parse_from(["rocm", "update", "--json", "--timeout-secs", "0"]) diff --git a/apps/rocm/src/deletion_properties.rs b/apps/rocm/src/deletion_properties.rs index 243e2ab06c..a664dbef0b 100644 --- a/apps/rocm/src/deletion_properties.rs +++ b/apps/rocm/src/deletion_properties.rs @@ -673,6 +673,7 @@ fn uninstall_case( dry_run: true, ..options }, + crate::uninstall_plan::PlanAudience::Captured, ); let planned: BTreeSet = plan.actions.iter().map(|e| e.path.clone()).collect(); prop_assert_eq!(&listed_in_render(&rendered), &planned, "{}", rendered); diff --git a/apps/rocm/src/main.rs b/apps/rocm/src/main.rs index e879060b5c..b141220536 100644 --- a/apps/rocm/src/main.rs +++ b/apps/rocm/src/main.rs @@ -947,15 +947,19 @@ fn dispatch(cli: Cli) -> Result<()> { keep_data, keep_cache, force_dev_binaries, - }) => uninstall(UninstallOptions { - yes, - dry_run, - keep_binaries, - keep_config, - keep_data, - keep_cache, - force_dev_binaries, - }), + force, + }) => { + uninstall::reject_force(force.is_some())?; + uninstall(UninstallOptions { + yes, + dry_run, + keep_binaries, + keep_config, + keep_data, + keep_cache, + force_dev_binaries, + }) + } Some(Command::Completions { shell }) => { let mut cmd = completion_command(); clap_complete::generate(shell, &mut cmd, "rocm", &mut std::io::stdout()); diff --git a/apps/rocm/src/uninstall.rs b/apps/rocm/src/uninstall.rs index aec8c1f57e..65aa4d7f96 100644 --- a/apps/rocm/src/uninstall.rs +++ b/apps/rocm/src/uninstall.rs @@ -18,10 +18,10 @@ use std::io::Write as _; use std::path::{Path, PathBuf}; use anyhow::{Context, Result, bail}; -use rocm_core::{AppPaths, require_yes_or_interactive}; +use rocm_core::{AppPaths, interactive_terminal, require_yes_or_interactive}; use crate::uninstall_plan::{ - UninstallOptions, UninstallPlan, build_uninstall_plan, confirm_uninstall, + PlanAudience, UninstallOptions, UninstallPlan, build_uninstall_plan, confirm_uninstall, is_rocm_install_entry_name, remove_path, render_uninstall_plan, }; @@ -63,10 +63,31 @@ impl PathEdit { } } +/// `rocm uninstall` has no `--force`; the flag is declared (hidden) only so this +/// can answer it. Left undeclared, clap's nearest-name guess for `--force` is +/// `--force-dev-binaries`, which removes development binaries, and a near miss +/// such as `--forc` gets that same suggestion. Declared, those guesses land here +/// instead, before anything is planned or removed. +pub(crate) fn reject_force(force: bool) -> Result<()> { + if force { + bail!( + "`--force` is not an option of `rocm uninstall`; use `--yes` to skip the confirmation" + ); + } + Ok(()) +} + pub(crate) fn uninstall(options: UninstallOptions) -> Result<()> { let paths = AppPaths::discover()?; let plan = build_uninstall_plan(&paths, &options)?; - print!("{}", render_uninstall_plan(&plan, &options)); + print!( + "{}", + render_uninstall_plan( + &plan, + &options, + PlanAudience::for_command(interactive_terminal()) + ) + ); if plan_is_empty(&plan) || options.dry_run { return Ok(()); @@ -837,7 +858,8 @@ mod tests { self_delete: Some(PathBuf::from("/opt/bin/rocm.exe")), ..UninstallPlan::default() }; - let output = render_uninstall_plan(&plan, &UninstallOptions::default()); + let output = + render_uninstall_plan(&plan, &UninstallOptions::default(), PlanAudience::Captured); for expected in [ "2 item(s) would be removed:", " - install record: /opt/bin/.rocm-cli-path-edit", diff --git a/apps/rocm/src/uninstall_plan.rs b/apps/rocm/src/uninstall_plan.rs index ea210c2eae..e553dc9e47 100644 --- a/apps/rocm/src/uninstall_plan.rs +++ b/apps/rocm/src/uninstall_plan.rs @@ -21,22 +21,26 @@ //! describe the `uninstall` command's own, exclusive logic. //! //! This module owns: the plan types (`UninstallOptions`, `UninstallPlan`, -//! `UninstallPlanEntry`), building the plan (`build_uninstall_plan`, +//! `UninstallPlanEntry`), the `PlanAudience` a rendered plan is written for +//! (a person at a terminal, a captured caller, or the assistant's preview), +//! which decides what the dry-run footer says comes next, building the plan (`build_uninstall_plan`, //! `plan_installed_binaries`, and the installed-binary/shared-cache //! discovery helpers behind them), rendering it (`render_uninstall_dry_run`, //! `render_uninstall_plan`), the `[y/N]` confirmation prompt //! (`confirm_uninstall`), and the filesystem removal primitive both //! `uninstall.rs` and `storage.rs` call to carry a plan out (`remove_path`, //! and the entry-resolution helpers behind it). `uninstall.rs` calls into it -//! for `UninstallOptions`/`UninstallPlan`/`build_uninstall_plan`/ +//! for `PlanAudience`/`UninstallOptions`/`UninstallPlan`/`build_uninstall_plan`/ //! `confirm_uninstall`/`is_rocm_install_entry_name`/`remove_path`/ //! `render_uninstall_plan`; `storage.rs` calls into it for //! `UninstallPlan`/`UninstallPlanEntry`/`confirm_uninstall`; `runtimes_cmd.rs` //! calls into it for `confirm_uninstall` (the same `[y/N]` prompt, reused for //! `rocm runtimes uninstall`); `chat/mcp_bridge.rs` calls into it for //! `render_uninstall_dry_run` (the deterministic uninstall-preview tool -//! result); `deletion_properties.rs`'s recursive-deletion property tests call -//! into it for `UninstallOptions`/`build_uninstall_plan`/`remove_path`/ +//! result, which renders for `PlanAudience::Assistant` itself and so does not +//! import the type); `deletion_properties.rs`'s recursive-deletion property +//! tests call into it for `PlanAudience` (the `uninstall_case` property renders +//! as `Captured`)/`UninstallOptions`/`build_uninstall_plan`/`remove_path`/ //! `render_uninstall_plan`. use std::fmt::Write as _; @@ -268,10 +272,61 @@ pub(crate) fn render_uninstall_dry_run(paths: &AppPaths) -> Result { ..UninstallOptions::default() }; let plan = build_uninstall_plan(paths, &options)?; - Ok(render_uninstall_plan(&plan, &options)) + Ok(render_uninstall_plan( + &plan, + &options, + PlanAudience::Assistant, + )) } -pub(crate) fn render_uninstall_plan(plan: &UninstallPlan, options: &UninstallOptions) -> String { +/// Who reads a rendered plan, which decides what its dry-run footer can truthfully +/// say comes next. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum PlanAudience { + /// A person at a terminal ran `rocm uninstall --dry-run` themselves: running + /// the same command again without `--dry-run` is the next step. + Terminal, + /// The output is captured by a caller (a script, the dashboard, the daemon's + /// tool). Whatever drives that caller has its own way to proceed, so there + /// is no next step to name; "run it again" would address the wrong reader. + Captured, + /// The assistant's read-only preview tool: it has no flag to offer, and the + /// removal itself goes through an approval step. + Assistant, +} + +impl PlanAudience { + /// The audience for `rocm uninstall` itself, from whether `interactive_terminal` + /// holds: stdin and stdout are both terminals. A dry run with either one + /// redirected, `--dry-run < /dev/null` at a terminal for one, is `Captured` + /// and prints no footer. + pub(crate) const fn for_command(interactive_terminal: bool) -> Self { + if interactive_terminal { + Self::Terminal + } else { + Self::Captured + } + } + + /// What a dry run says to do next, if anything. + const fn dry_run_footer(self) -> Option<&'static str> { + match self { + Self::Terminal => { + Some("Nothing was removed. To remove these items, run it again without --dry-run.") + } + Self::Captured => None, + // The assistant's own uninstall is an approval action; see + // `lifecycle_read_mutate_split_is_honest` in `tool_policy.rs`. + Self::Assistant => Some("Nothing was removed. Removal needs your approval."), + } + } +} + +pub(crate) fn render_uninstall_plan( + plan: &UninstallPlan, + options: &UninstallOptions, + audience: PlanAudience, +) -> String { let mut output = String::new(); let _ = writeln!(output, "Uninstall review"); let _ = writeln!(output); @@ -299,9 +354,13 @@ pub(crate) fn render_uninstall_plan(plan: &UninstallPlan, options: &UninstallOpt for skipped in &plan.skipped { let _ = writeln!(output, " - {skipped}"); } - if options.dry_run { + // An empty plan has nothing to approve, so a dry run says nothing about a next step. + if options.dry_run + && !uninstall::plan_is_empty(plan) + && let Some(footer) = audience.dry_run_footer() + { let _ = writeln!(output); - let _ = writeln!(output, "Choose Review uninstall to approve removal."); + let _ = writeln!(output, "{footer}"); } output } @@ -521,6 +580,95 @@ mod tests { use super::*; use crate::tests::test_paths; + fn plan_with_a_binary() -> UninstallPlan { + UninstallPlan { + self_delete: Some(PathBuf::from("/opt/bin/rocm")), + ..UninstallPlan::default() + } + } + + fn dry_run() -> UninstallOptions { + UninstallOptions { + dry_run: true, + ..UninstallOptions::default() + } + } + + /// A person at a terminal who dry-runs is told to run the same command again + /// without `--dry-run`: the next step is a rerun, not a control the command + /// line lacks. The scenario `uninstall-07` runs it again at a terminal and + /// checks that the listed folder goes. + #[test] + fn terminal_dry_run_footer_says_to_run_it_again_without_dry_run() { + let output = + render_uninstall_plan(&plan_with_a_binary(), &dry_run(), PlanAudience::Terminal); + assert!( + output.ends_with( + "\nNothing was removed. To remove these items, run it again without --dry-run.\n" + ), + "unexpected footer in:\n{output}" + ); + assert!(!output.contains("Review uninstall"), "{output}"); + } + + /// Output a caller captures is not addressed to someone who can rerun it, so + /// it carries no next step (the dashboard's `/uninstall` and the daemon's + /// `rocm_command` tool run the dry run as a subprocess, where the real step + /// is theirs to offer). + #[test] + fn captured_dry_run_names_no_next_step() { + let output = + render_uninstall_plan(&plan_with_a_binary(), &dry_run(), PlanAudience::Captured); + assert!(!output.contains("Nothing was removed."), "{output}"); + assert!(!output.contains("run it again"), "{output}"); + assert!(output.contains("1 item(s) would be removed:"), "{output}"); + } + + /// The command picks its audience from whether it has a terminal. + #[test] + fn the_command_is_addressed_to_a_terminal_only_when_it_has_one() { + assert_eq!(PlanAudience::for_command(true), PlanAudience::Terminal); + assert_eq!(PlanAudience::for_command(false), PlanAudience::Captured); + } + + /// An empty plan has nothing to approve, so a dry run adds no next step for + /// anyone; a real run adds none either, since its confirmation prompt follows. + #[test] + fn footer_is_only_for_a_dry_run_that_has_something_to_remove() { + for audience in [ + PlanAudience::Terminal, + PlanAudience::Captured, + PlanAudience::Assistant, + ] { + let empty = render_uninstall_plan(&UninstallPlan::default(), &dry_run(), audience); + assert!(!empty.contains("Nothing was removed."), "{empty}"); + let real_run = render_uninstall_plan( + &plan_with_a_binary(), + &UninstallOptions::default(), + audience, + ); + assert!(!real_run.contains("Nothing was removed."), "{real_run}"); + } + } + + /// The assistant's preview has no flag to offer, so it must not point at a + /// command line it cannot run; what it can truthfully say is that removal + /// needs approval (`lifecycle_read_mutate_split_is_honest` in `tool_policy.rs` pins + /// that its own `uninstall` is an approval action). It does not say "these + /// items": the preview always plans with the default options, while the + /// approval carries the user's own. + #[test] + fn assistant_dry_run_footer_names_no_command() { + let output = + render_uninstall_plan(&plan_with_a_binary(), &dry_run(), PlanAudience::Assistant); + assert!( + output.ends_with("\nNothing was removed. Removal needs your approval.\n"), + "unexpected footer in:\n{output}" + ); + assert!(!output.contains("rocm uninstall"), "{output}"); + assert!(!output.contains("these items"), "{output}"); + } + /// A cache that has moved inside a directory uninstall already removes must /// not be reported as "not removed" — the note would be false. #[test] diff --git a/docs/architecture.md b/docs/architecture.md index 487fe32658..029d6ea30c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -114,8 +114,8 @@ Each per-crate module inventory lists one file per line. Flat inventories (every - [`therock/update.rs`](../apps/rocm/src/therock/update.rs) — full domain extraction, a child of `therock.rs` that builds on `therock/family.rs`, `therock/io.rs`, `therock/process.rs`, `therock/python.rs`, `therock/resolve.rs`, `therock/source.rs` and `therock/version.rs`, and on [`runtime_registry.rs`](../apps/rocm/src/runtime_registry.rs) for the manifests (split out of `therock.rs`): whether an installed runtime has something newer, and the bounded startup check that asks. `runtime_update_plan` resolves the latest source for one runtime (`resolve_latest_for_manifest` re-resolves a wheel runtime through `resolve_pip_runtime_with_timeout` and a tarball one through `resolve_tarball_artifact_with_timeout`, on the layout `manifest_source_layout` reads back from the manifest) and `runtime_freshness` classifies it (`RuntimeFreshness`: up to date, update available, repair available when the installed composition is not the one a fresh install would record, or ahead of the index) into a `RuntimeUpdatePlan`. `render_update_report` and `render_update_json` (the form the dashboard's update check parses) present the plans, and `maybe_refresh_startup_update_check` keeps one `StartupUpdateCheckRecord` in the cache so the check runs at most once every twelve hours, under a two-second download timeout. `runtime_key` and `wheel_runtime_key`, which name the install a plan targets, stay in `therock.rs`; whether a replacement's root is installed is `rocm_core::install_root_has_payload`. `render_update_report`, `render_update_json`, `runtime_update_plan` and `maybe_refresh_startup_update_check` are `pub(crate)` and re-exported by `therock.rs`; `RuntimeFreshness`, `runtime_freshness` and `select_startup_update_manifest` are `pub(super)` for the version property tests, and the rest is private. - [`therock/test_support.rs`](../apps/rocm/src/therock/test_support.rs) — test-only (`#[cfg(test)]`), a child of `therock.rs`: fixtures shared by the `therock` child modules' tests and the tests left in `therock.rs` (`test_paths`, `test_runtime_manifest`, `write_test_runtime_manifest`, `family_for_test`). Separate from the crate-level [`test_support.rs`](../apps/rocm/src/test_support.rs), which holds the fixtures every module's tests share, such as `PROCESS_ENV_TEST_LOCK` and the background-helper fixtures `runtime_state` and `set_helper_facts`. - [`tool_policy.rs`](../apps/rocm/src/tool_policy.rs) — the chat assistant's tool-call policy: which `rocm` commands and bridge tools a model may request, which run immediately and which need the user's approval first. It owns `ChatRocmCommandAction` (read-only, or approval with the titles the approval prompt shows) and `ChatToolApprovalRequest`, the validators (`validate_chat_tool_call`, the `validate_chat_*_tool_call` family, `validate_required_chat_string`, `validate_optional_chat_integer`, `reject_control_characters_in_tool_arguments` (which refuses a model-supplied tool name or argument carrying a terminal control character, for every tool except `rocm_command`, whose argv `normalized_chat_rocm_command_args` screens entry by entry), `validate_serve_command_safety`, the four rules a model-proposed `serve` must satisfy (no public bind, no CPU device, a loopback host, `--managed` without `--foreground`), and `validate_chat_rocm_command_safety`, which applies them to a `serve` argv and also refuses a system install folder (`chat_install_prefix_is_system`)), the classifiers (`chat_rocm_command_action`, `chat_rocm_command_action_from_args`, `chat_install_driver_action`, `canonicalize_chat_rocm_command`, `normalized_chat_rocm_command_args`, `chat_tool_call_is_read_only`), `chat_tool_approval_request`, and the readers that turn a tool call into its argv and one-line command (`rocm_chat_tool_requested_args`, `rocm_chat_tool_requested_command`, with `push_optional_json_cli_arg` and `json_string`). It moved verbatim from `chat.rs` with the tests that exercise only these items. It depends on [`rocm_argv.rs`](../apps/rocm/src/rocm_argv.rs), `providers::ChatToolCall`, `service_launch::is_loopback_host`, `services_text::validate_service_id`, `shell_quote::has_terminal_control_character`, `therock::RuntimeVersionSelector` and `driver_install::host_install_driver_only_reports`, none of which imports `chat`, so `freeform_planner.rs` calls `validate_serve_command_safety` and `validate_chat_rocm_command_safety` here instead of through `chat`, and keeps no copy of the serve rules. `chat.rs`'s child modules call into it and `chat.rs` re-exports `validate_chat_tool_call`, `chat_tool_call_is_read_only` and `chat_tool_approval_request` (read by `dash_seam.rs`), and `ChatRocmCommandAction`, `chat_install_driver_action`, `chat_rocm_command_action_from_args` and `rocm_chat_tool_requested_args`, which only other modules' tests read as `crate::chat::` (`driver_plan.rs`, `system_packages.rs`). -- [`uninstall.rs`](../apps/rocm/src/uninstall.rs) — mechanical relocation, owns types: `uninstall()`, plus the installer `PATH` undo and running-executable deletion. The shared plan type and its file-removal helpers live in [`uninstall_plan.rs`](../apps/rocm/src/uninstall_plan.rs) below instead, because [`storage.rs`](../apps/rocm/src/storage.rs) reuses them too. The two modules depend on each other: `uninstall_plan.rs` reads this module's `pub(crate)` `PathEdit`, `PATH_EDIT_RECORD`, `plan_path_edits`, `plan_is_empty`, `removal_count` and `render_extra_plan`. -- [`uninstall_plan.rs`](../apps/rocm/src/uninstall_plan.rs) — mechanical relocation, shares crate-visible types (Phase 6f, ROCMAI-212): the uninstall-plan types (`UninstallOptions`, `UninstallPlan`, `UninstallPlanEntry`), building the plan (`build_uninstall_plan`, `plan_installed_binaries`, and the installed-binary/shared-cache discovery helpers behind them), rendering it (`render_uninstall_dry_run`, `render_uninstall_plan`), the `[y/N]` confirmation prompt (`confirm_uninstall`), and the filesystem removal primitive both [`uninstall.rs`](../apps/rocm/src/uninstall.rs) and [`storage.rs`](../apps/rocm/src/storage.rs) call to carry a plan out (`remove_path`, and the entry-resolution helpers behind it). Kept separate from `uninstall.rs` rather than folded into it, since `uninstall.rs`'s own doc comment and name both describe `uninstall()`'s exclusive logic (the installer `PATH` undo and running-executable deletion), while this module's plan/render/removal helpers are shared with `storage.rs`. `main.rs` (`UninstallOptions`), `uninstall.rs`, `storage.rs`, `runtimes_cmd.rs`, `chat/mcp_bridge.rs`, and [`deletion_properties.rs`](../apps/rocm/src/deletion_properties.rs) (Unix-only property tests) each import the subset of these `pub(crate)` types and helpers they need; see this module's own doc comment for which symbol each one uses. +- [`uninstall.rs`](../apps/rocm/src/uninstall.rs) — mechanical relocation, owns types: `uninstall()`, the refusal of the hidden `--force` (`reject_force`, which `main.rs` calls from the `uninstall` dispatch arm), plus the installer `PATH` undo and running-executable deletion. The shared plan type and its file-removal helpers live in [`uninstall_plan.rs`](../apps/rocm/src/uninstall_plan.rs) below instead, because [`storage.rs`](../apps/rocm/src/storage.rs) reuses them too. The two modules depend on each other: `uninstall_plan.rs` reads this module's `pub(crate)` `PathEdit`, `PATH_EDIT_RECORD`, `plan_path_edits`, `plan_is_empty`, `removal_count` and `render_extra_plan`. +- [`uninstall_plan.rs`](../apps/rocm/src/uninstall_plan.rs) — mechanical relocation, shares crate-visible types (Phase 6f, ROCMAI-212): the uninstall-plan types (`UninstallOptions`, `UninstallPlan`, `UninstallPlanEntry`), the `PlanAudience` a rendered plan is written for (a person at a terminal, a captured caller, or the assistant's preview), which decides what the dry-run footer says comes next, building the plan (`build_uninstall_plan`, `plan_installed_binaries`, and the installed-binary/shared-cache discovery helpers behind them), rendering it (`render_uninstall_dry_run`, which renders for the assistant, and `render_uninstall_plan`), the `[y/N]` confirmation prompt (`confirm_uninstall`), and the filesystem removal primitive both [`uninstall.rs`](../apps/rocm/src/uninstall.rs) and [`storage.rs`](../apps/rocm/src/storage.rs) call to carry a plan out (`remove_path`, and the entry-resolution helpers behind it). Kept separate from `uninstall.rs` rather than folded into it, since `uninstall.rs`'s own doc comment and name both describe `uninstall()`'s exclusive logic (the installer `PATH` undo and running-executable deletion), while this module's plan/render/removal helpers are shared with `storage.rs`. `main.rs` (`UninstallOptions`), `uninstall.rs` (which also imports `PlanAudience` and picks it from `interactive_terminal`), `storage.rs`, `runtimes_cmd.rs`, `chat/mcp_bridge.rs` (which calls `render_uninstall_dry_run` and does not import `PlanAudience`), and [`deletion_properties.rs`](../apps/rocm/src/deletion_properties.rs) (Unix-only property tests, which render as `PlanAudience::Captured`) each import the subset of these `pub(crate)` types and helpers they need; see this module's own doc comment for which symbol each one uses. - [`update_cmd.rs`](../apps/rocm/src/update_cmd.rs) — mechanical relocation, dispatch-adjacent, no owned types (Phase 6f, ROCMAI-210): `rocm update`'s command handler (`update()`, the body of the `update` arm of `dispatch()`) and its rendering/activation logic — the read-only status report (`render_update_text`, `append_update_surfaces`), the predicate deciding whether `update` should route into the mutating path instead of that report (`update_should_preview_or_apply`), applying a runtime update (`apply_runtime_update`, `append_update_activate_summary`), and the update-source/installed-runtime pickers behind it (`select_runtime_update_source`, `select_installed_update_runtime`). `const ROLLBACK_RECOVERY_HINT` stays in `main.rs` as a shared crate-root constant, because callers outside this module also use it ([`runtimes_cmd.rs`](../apps/rocm/src/runtimes_cmd.rs)'s `RuntimesCommand::Activate` handler and [`runtime_install_finalize.rs`](../apps/rocm/src/runtime_install_finalize.rs)'s `render_sdk_install_success`); this module reaches it via its `use crate::{...};` import, the same way `gpu_policy.rs`'s `device_policy_name` stays in `main.rs`. `update()` is `pub(crate)` and called from [`main.rs`](../apps/rocm/src/main.rs)'s `dispatch()` through a re-import (`use crate::update_cmd::update;`), and calls `update_should_preview_or_apply`, `apply_runtime_update` and `render_update_text` itself; `render_update_text` is also `pub(crate)` and read from [`chat/mcp_bridge.rs`](../apps/rocm/src/chat/mcp_bridge.rs) (the read-only `rocm update` handling), while `apply_runtime_update` and `update_should_preview_or_apply` keep the `pub(crate)` they had when `dispatch()` called them directly, though only `update()` calls them now; `select_runtime_update_source` is also `pub(crate)`, read from [`therock_version_proptests.rs`](../apps/rocm/src/therock_version_proptests.rs)'s property tests via `crate::update_cmd::select_runtime_update_source`. `append_update_surfaces`, `append_update_activate_summary`, and `select_installed_update_runtime` have no callers outside this module and stay private. The cluster's regression tests live in `update_cmd.rs`'s own `mod tests`, reaching shared fixtures (`test_paths`, `test_runtime_manifest_for_update`, `write_test_pip_runtime`) through `crate::tests::`/`crate::test_support::` the same way other mechanically relocated modules do. Further `apps/rocm` modules, not part of the `main.rs` split: diff --git a/docs/manual-testing.md b/docs/manual-testing.md index 2171fdd3a5..f70e75ab83 100644 --- a/docs/manual-testing.md +++ b/docs/manual-testing.md @@ -1130,7 +1130,12 @@ Expected result: - The dry run lists the binaries (on Windows, `rocm.exe` is marked as deleted as the command exits) and, under `PATH changes from the installer that would be undone:`, the shell profile - (Linux) or the user `PATH` entry (Windows). It removes nothing. + (Linux) or the user `PATH` entry (Windows). It removes nothing, and at a + terminal ends with `Nothing was removed. To remove these items, run it again + without --dry-run.` Running the same command again without `--dry-run` asks + `[y/N]` and, on yes, removes what was listed (scenario `uninstall-07`). With + its output piped to a file or another command, or its input redirected, it + lists the same items and omits that last line (scenario `uninstall-08`). - After confirming, the install folder holds no `rocm`/`rocmd` files, and a new terminal no longer gets the install folder on `PATH` from the installer's change. @@ -1142,7 +1147,14 @@ Expected result: `Nothing managed by rocm-cli would be removed.` and leaves the home folder empty (scenario `uninstall-06`): run `HOME=$(mktemp -d) rocm uninstall --keep-binaries --dry-run`, then `ls -A` - on that folder. + on that folder. It adds no line about how to remove anything (scenario + `uninstall-09`). +- Passing `--force` to `rocm uninstall` is refused with a message that says it + is not an option and points to `--yes`; a near miss such as `--forc` is an + unknown-argument error (exit 2). Neither + suggests `--force-dev-binaries` (scenario `uninstall-10`). + `rocm uninstall --help` ends with examples that start with a dry run + (scenario `uninstall-11`). - Without `--yes` and without a terminal, the command prints the same review, then refuses with `uninstall requires --yes outside an interactive terminal` and exit code 1, and removes nothing. On Linux or WSL, check it with no diff --git a/docs/testing.md b/docs/testing.md index eb0fb8671f..de69d2eca0 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -1214,9 +1214,18 @@ The `uninstall-NN` E2E scenarios (`features/uninstall.feature`) check the same behaviour through the built binary, confined to the scenario's own folder, including a folder that cannot be checked stopping the uninstall before anything is removed, and a dry run on a machine ROCm CLI never touched -(`uninstall-06`) reporting nothing to remove and creating no folder. The -`uninstall` command does not start the file logger, which would otherwise create -the data folder's `logs` folder before the plan is built: +(`uninstall-06`) reporting nothing to remove and creating no folder. At a +terminal (a pseudo-terminal on the Linux lane), a dry run that lists something +ends by saying to run it again without `--dry-run`, and `uninstall-07` does that +and checks the listed folder goes; a run whose stdin or stdout is not a terminal, and an +empty plan even at one, name no next step (`uninstall-08`, `uninstall-09`). A +mistyped `--force` is refused with a pointer to `--yes`, and a near miss of it +is not answered with `--force-dev-binaries` (`uninstall-10`); the help starts +its examples with a dry run (`uninstall-11`). The assistant's uninstall preview +ends differently, since it has no flag to offer: it says removal needs approval, +which `lifecycle_read_mutate_split_is_honest` in [tool_policy.rs](../apps/rocm/src/tool_policy.rs) backs. +The `uninstall` command does not start the file logger, which would otherwise +create the data folder's `logs` folder before the plan is built: ```bash cargo xtask e2e -- -n "uninstall-" diff --git a/tests/e2e-cucumber/features/uninstall.feature b/tests/e2e-cucumber/features/uninstall.feature index 286a59c0c2..63e2568f33 100644 --- a/tests/e2e-cucumber/features/uninstall.feature +++ b/tests/e2e-cucumber/features/uninstall.feature @@ -80,3 +80,79 @@ Feature: Uninstall Then the uninstall succeeds And the uninstall reports that nothing would be removed And ROCm CLI has still not created its folders + + # A dry run run by a person at a terminal ends by saying to run it again + # without `--dry-run`. It once said "Choose Review uninstall", a control the + # command line does not have. The promise is the line and the state together: + # the dry run removes nothing, and running the same command again, as the + # line says and answering its prompt, removes what was listed. + @id:uninstall-dry-run-at-a-terminal-says-to-run-it-again-to-remove @requires-os:linux + Scenario: uninstall-07 - At a terminal, a dry run removes nothing and running it again without --dry-run removes what it listed + Given the config folder holds the user's files + When the user dry-runs an uninstall of only the config at a terminal + Then the uninstall succeeds + And the dry run says to run it again without --dry-run + And the config folder still holds the user's files + When the user runs it again without --dry-run at a terminal and answers yes + Then the uninstall succeeds + And the config folder is gone + + # A run whose stdin or stdout is not a terminal (a script, the dashboard's + # `/uninstall`, the daemon's `rocm_command` tool) has no one to tell to run it + # again: the real step belongs to whatever drives it. It lists what it would + # remove, offers no step, and removes nothing. + @id:uninstall-dry-run-outside-a-terminal-offers-no-next-step + Scenario: uninstall-08 - Outside a terminal, a dry run lists what it would remove and offers no step to remove it + Given the config folder holds the user's files + When the user dry-runs an uninstall of only the config + Then the uninstall succeeds + And the dry run lists the config folder + And the dry run offers no step to remove anything + And the config folder still holds the user's files + + # With nothing to remove there is nothing to approve, so even a person at a + # terminal is offered no step. A config folder that is kept and still holds + # the user's files shows the "nothing to remove" is true. + @id:uninstall-dry-run-with-nothing-to-remove-offers-no-next-step @requires-os:linux + Scenario: uninstall-09 - At a terminal, a dry run with nothing to remove offers no step to remove it + Given the config folder holds the user's files + When the user dry-runs an uninstall that keeps everything at a terminal + Then the uninstall succeeds + And the uninstall reports that nothing would be removed + And the dry run offers no step to remove anything + And the config folder still holds the user's files + + # `--force` is a natural guess for skipping the confirmation, and the nearest + # real flag by name is `--force-dev-binaries`, which removes the binaries of a + # development build. `--force` is refused with the flag to use instead, a near + # miss of it never suggests the destructive flag, and nothing is removed. + @id:uninstall-mistyped-force-is-not-answered-with-a-destructive-flag + Scenario: uninstall-10 - A mistyped --force is refused without pointing at the flag that removes development binaries + Given the config folder holds the user's files + When the user uninstalls the config with --force + Then the uninstall is refused and told to use --yes instead + And the config folder still holds the user's files + When the user uninstalls the config with a near miss of --force + Then the error does not point at the flag that removes development binaries + And the config folder still holds the user's files + + @id:uninstall-help-shows-a-dry-run-before-the-real-run + Scenario: uninstall-11 - The uninstall help shows a dry run before the real run + When the user asks for the uninstall help + Then the help shows a dry run before the real run + + # The assistant's uninstall preview (the `rocm_command` tool of the chat + # assistant and the dashboard, called here without a model through the hidden + # `rocm mcp-call`) renders the same plan as a dry run, but it has no flag to + # offer, so it says that removal needs approval. It is the one run here that + # cannot pass --keep-binaries: the preview takes no flags and removes nothing, + # and it is made without --allow-mutation, so a call that would remove + # something is refused. + @id:uninstall-assistant-preview-says-removal-needs-approval + Scenario: uninstall-12 - The assistant's uninstall preview lists what it would remove, says removal needs approval, and removes nothing + Given the config folder holds the user's files + When the assistant previews an uninstall + Then the preview succeeds + And the preview lists the config folder + And the preview says removal needs approval + And the config folder still holds the user's files diff --git a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs index 3b818cffb5..0dbf34f51c 100644 --- a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs @@ -14,6 +14,7 @@ use std::path::{Path, PathBuf}; use cucumber::{given, then, when}; use crate::E2eWorld; +use crate::e2e::tui_driver::{TuiSession, default_timeout}; const USER_FILE: &str = "keep.txt"; @@ -76,6 +77,19 @@ async fn cache_behind_looping_link(world: &mut E2eWorld) { E2eWorld::link_directory(&looping, &looping).expect("failed to plant looping link"); } +/// HOME, the uv cache and the Hugging Face cache inside the scenario's own +/// folder, so nothing a run resolves can reach the runner's shared caches. +fn isolated_env(world: &E2eWorld) -> Vec<(&'static str, String)> { + let root = root(world); + let home = root.join("home"); + std::fs::create_dir_all(&home).expect("failed to create isolated HOME"); + vec![ + ("HOME", home.display().to_string()), + ("UV_CACHE_DIR", root.join("uv-cache").display().to_string()), + ("HF_HOME", root.join("hf-home").display().to_string()), + ] +} + fn run_uninstall(world: &mut E2eWorld, keep: &[&str], settings: &[(&str, &str)]) { run_uninstall_with(world, true, keep, settings); } @@ -89,24 +103,25 @@ fn run_uninstall_with( keep: &[&str], settings: &[(&str, &str)], ) { - let root = root(world).to_path_buf(); - let home = root.join("home"); - std::fs::create_dir_all(&home).expect("failed to create isolated HOME"); - let home = home.display().to_string(); - let uv = root.join("uv-cache").display().to_string(); - let hf = root.join("hf-home").display().to_string(); let mut args = vec!["uninstall", "--keep-binaries"]; if confirmed { args.push("--yes"); } args.extend_from_slice(keep); - let mut envs = vec![ - ("HOME", home.as_str()), - ("UV_CACHE_DIR", &uv), - ("HF_HOME", &hf), - ]; + run_uninstall_args(world, &args, settings); +} + +/// Run `rocm` with exactly `args`, confined to the scenario's own folders like +/// every other uninstall here. +fn run_uninstall_args(world: &mut E2eWorld, args: &[&str], settings: &[(&str, &str)]) { + assert_keeps_binaries(args); + let isolated = isolated_env(world); + let mut envs = isolated + .iter() + .map(|(name, value)| (*name, value.as_str())) + .collect::>(); envs.extend_from_slice(settings); - let (stdout, stderr, rc) = crate::run_rocm_with_env(world, &args, &envs); + let (stdout, stderr, rc) = crate::run_rocm_with_env(world, args, &envs); world.cli_output = Some(stdout); world.cli_stderr = Some(stderr); world.cli_rc = Some(rc); @@ -451,3 +466,326 @@ async fn config_intact(world: &mut E2eWorld) { output(world) ); } + +/// Every run here keeps the binaries: the binary under test must survive, and an +/// uninstall that reached it would delete the program the scenario is running. +/// Checked at the point a run starts, so no step can reach it by accident. +fn assert_keeps_binaries(args: &[&str]) { + assert!( + args.contains(&"--keep-binaries"), + "an uninstall in a scenario must pass --keep-binaries: {args:?}" + ); +} + +/// The arguments for uninstalling only the config folder, as a dry run or for real. +fn config_only_args(dry_run: bool) -> Vec<&'static str> { + let mut args = vec![ + "uninstall", + "--keep-binaries", + "--keep-data", + "--keep-cache", + ]; + if dry_run { + args.push("--dry-run"); + } + args +} + +/// Run `rocm` under a pseudo-terminal, confined to the scenario's folders like +/// every other uninstall here, so the command sees a terminal on both streams as +/// a person typing it would. Answers its `[y/N]` prompt when `answer` is given. +async fn run_uninstall_at_terminal(world: &mut E2eWorld, args: &[&str], answer: Option<&str>) { + assert_keeps_binaries(args); + let root = root(world).to_path_buf(); + let home = root.join("home"); + std::fs::create_dir_all(&home).expect("failed to create isolated HOME"); + let home = home.display().to_string(); + let uv = root.join("uv-cache").display().to_string(); + let hf = root.join("hf-home").display().to_string(); + let config = config_dir(world).display().to_string(); + let mut session = TuiSession::spawn_with_env( + world, + args, + &[ + ("HOME", home.as_str()), + ("UV_CACHE_DIR", uv.as_str()), + ("HF_HOME", hf.as_str()), + ("ROCM_CLI_CONFIG_DIR", config.as_str()), + ], + ) + .unwrap_or_else(|e| panic!("failed to run {args:?} at a terminal: {e}")); + if let Some(answer) = answer { + session + .wait_for_screen("[y/N]:", default_timeout()) + .await + .unwrap_or_else(|e| panic!("the confirmation prompt never appeared: {e}")); + session + .send(&format!("{answer}\r")) + .unwrap_or_else(|e| panic!("failed to type the answer: {e}")); + } + let rc = session + .wait_for_exit_code(default_timeout()) + .await + .unwrap_or_else(|e| panic!("the uninstall never exited: {e}")); + world.cli_output = Some(session.screen_text()); + world.cli_stderr = None; + world.cli_rc = Some(rc); + world.tui = Some(session); +} + +#[when("the user dry-runs an uninstall of only the config")] +async fn dry_run_config_only(world: &mut E2eWorld) { + let config = config_dir(world).display().to_string(); + run_uninstall_args( + world, + &config_only_args(true), + &[("ROCM_CLI_CONFIG_DIR", &config)], + ); +} + +#[when("the user dry-runs an uninstall of only the config at a terminal")] +async fn dry_run_config_only_at_terminal(world: &mut E2eWorld) { + run_uninstall_at_terminal(world, &config_only_args(true), None).await; +} + +#[when("the user runs it again without --dry-run at a terminal and answers yes")] +async fn run_it_again_and_confirm(world: &mut E2eWorld) { + // The same arguments as the dry run, without `--dry-run`: the step the + // dry run's last line names. + run_uninstall_at_terminal(world, &config_only_args(false), Some("y")).await; +} + +#[when("the user dry-runs an uninstall that keeps everything at a terminal")] +async fn dry_run_keeping_everything_at_terminal(world: &mut E2eWorld) { + run_uninstall_at_terminal( + world, + &[ + "uninstall", + "--keep-binaries", + "--keep-config", + "--keep-data", + "--keep-cache", + "--dry-run", + ], + None, + ) + .await; +} + +#[then("the dry run says to run it again without --dry-run")] +async fn dry_run_says_to_run_it_again(world: &mut E2eWorld) { + let stdout = output(world); + assert!( + stdout.contains( + "Nothing was removed. To remove these items, run it again without --dry-run." + ), + "the dry run must say how to remove what it listed:\n{stdout}" + ); + assert!( + !stdout.contains("Review uninstall"), + "the command line has no such control:\n{stdout}" + ); +} + +#[then("the dry run lists the config folder")] +async fn dry_run_lists_the_config(world: &mut E2eWorld) { + let stdout = output(world); + let config = config_dir(world).display().to_string(); + assert!( + stdout.contains(&format!("config: {config}")), + "the plan must list the config folder ({config}):\n{stdout}" + ); +} + +#[then("the config folder is gone")] +async fn config_gone(world: &mut E2eWorld) { + let config = config_dir(world); + assert!( + std::fs::symlink_metadata(&config).is_err(), + "running it again as the dry run said did not remove {}:\n{}", + config.display(), + output(world) + ); +} + +#[then("the dry run offers no step to remove anything")] +async fn dry_run_offers_no_step(world: &mut E2eWorld) { + let stdout = output(world); + for phrase in [ + "Nothing was removed.", + "run it again", + "Review uninstall", + "approval", + ] { + assert!( + !stdout.contains(phrase), + "this dry run must not offer {phrase:?}:\n{stdout}" + ); + } +} + +/// The assistant's uninstall preview, called without a model through the hidden +/// `rocm mcp-call` entry point the dashboard and chat use for their tools. +/// +/// The one run here that cannot pass `--keep-binaries`: the preview takes no +/// flags, plans every folder and the binary under test, and renders the plan. It +/// removes nothing, and it is made without `--allow-mutation`, so the tool +/// refuses a call that would remove something instead of running it. +#[when("the assistant previews an uninstall")] +async fn assistant_previews_uninstall(world: &mut E2eWorld) { + let config = config_dir(world).display().to_string(); + let isolated = isolated_env(world); + let mut envs = isolated + .iter() + .map(|(name, value)| (*name, value.as_str())) + .collect::>(); + envs.push(("ROCM_CLI_CONFIG_DIR", &config)); + let arguments = serde_json::json!({ "args": ["uninstall", "--dry-run"] }).to_string(); + let (stdout, stderr, rc) = crate::run_rocm_with_env( + world, + &["mcp-call", "rocm_command", "--arguments-json", &arguments], + &envs, + ); + world.cli_output = Some(stdout); + world.cli_stderr = Some(stderr); + world.cli_rc = Some(rc); +} + +/// What the preview printed: the command's own text inside the tool result. +fn preview_text(world: &E2eWorld) -> String { + let result: serde_json::Value = serde_json::from_str(output(world)).unwrap_or_else(|error| { + panic!("the tool result is not JSON ({error}):\n{}", output(world)) + }); + result["structuredContent"]["stdout"] + .as_str() + .unwrap_or_else(|| panic!("the tool result has no command output:\n{}", output(world))) + .to_owned() +} + +#[then("the preview succeeds")] +async fn preview_succeeds(world: &mut E2eWorld) { + let rc = world.cli_rc.expect("no exit code captured"); + assert!( + rc == 0, + "the preview must exit 0, got {rc}\nstdout:\n{}\nstderr:\n{}", + output(world), + world.cli_stderr.as_deref().unwrap_or("") + ); + let result: serde_json::Value = serde_json::from_str(output(world)).expect("tool result JSON"); + assert_eq!( + result["isError"], + serde_json::Value::Bool(false), + "the tool reported an error:\n{}", + output(world) + ); +} + +#[then("the preview lists the config folder")] +async fn preview_lists_the_config(world: &mut E2eWorld) { + let text = preview_text(world); + let config = config_dir(world).display().to_string(); + assert!( + text.contains(&format!("config: {config}")), + "the preview must list the config folder ({config}):\n{text}" + ); +} + +#[then("the preview says removal needs approval")] +async fn preview_says_removal_needs_approval(world: &mut E2eWorld) { + let text = preview_text(world); + assert!( + text.contains("Nothing was removed. Removal needs your approval."), + "the preview must say removal needs approval:\n{text}" + ); + // The preview has no flag to offer, so it must not point at one. + for phrase in ["run it again", "--dry-run.", "Review uninstall"] { + assert!( + !text.contains(phrase), + "the assistant's preview must not offer {phrase:?}:\n{text}" + ); + } +} + +#[when("the user uninstalls the config with --force")] +async fn uninstall_with_force(world: &mut E2eWorld) { + let config = config_dir(world).display().to_string(); + let mut args = config_only_args(false); + args.push("--force"); + run_uninstall_args(world, &args, &[("ROCM_CLI_CONFIG_DIR", &config)]); +} + +#[when("the user uninstalls the config with a near miss of --force")] +async fn uninstall_with_near_miss_of_force(world: &mut E2eWorld) { + let config = config_dir(world).display().to_string(); + let mut args = config_only_args(false); + args.push("--forc"); + run_uninstall_args(world, &args, &[("ROCM_CLI_CONFIG_DIR", &config)]); +} + +#[then("the uninstall is refused and told to use --yes instead")] +async fn refused_and_told_to_use_yes(world: &mut E2eWorld) { + let stderr = world.cli_stderr.as_deref().unwrap_or(""); + assert_eq!( + world.cli_rc, + Some(1), + "a refused --force exits 1\nstderr:\n{stderr}" + ); + assert!( + stderr.contains("`--force` is not an option of `rocm uninstall`") + && stderr.contains("use `--yes` to skip the confirmation"), + "expected the refusal to name --yes:\n{stderr}" + ); + assert!( + !stderr.contains("force-dev-binaries"), + "the refusal must not name the destructive flag:\n{stderr}" + ); +} + +#[then("the error does not point at the flag that removes development binaries")] +async fn error_does_not_suggest_dev_binaries(world: &mut E2eWorld) { + let stderr = world.cli_stderr.as_deref().unwrap_or(""); + assert_eq!( + world.cli_rc, + Some(2), + "an unknown flag exits 2\nstderr:\n{stderr}" + ); + assert!( + stderr.contains("unexpected argument"), + "expected the unknown-argument error on stderr:\n{stderr}" + ); + assert!( + !stderr.contains("force-dev-binaries"), + "the error must not name the destructive flag:\n{stderr}" + ); +} + +#[when("the user asks for the uninstall help")] +async fn ask_for_uninstall_help(world: &mut E2eWorld) { + let (stdout, stderr, rc) = crate::run_rocm_with_env(world, &["uninstall", "--help"], &[]); + world.cli_output = Some(stdout); + world.cli_stderr = Some(stderr); + world.cli_rc = Some(rc); +} + +#[then("the help shows a dry run before the real run")] +async fn help_shows_dry_run_first(world: &mut E2eWorld) { + let stdout = output(world); + let examples = stdout.split_once("EXAMPLES:").map_or_else( + || panic!("the help has no examples:\n{stdout}"), + |(_, rest)| rest, + ); + let rows: Vec<&str> = examples + .lines() + .map(str::trim) + .filter(|row| !row.is_empty()) + .collect(); + assert_eq!( + rows.first().copied(), + Some("rocm uninstall --dry-run"), + "the first example must be the dry run:\n{examples}" + ); + assert!( + rows.contains(&"rocm uninstall"), + "the examples must also show the real run:\n{examples}" + ); +}