From cef74ba7e13d451e429729145281f4cb30853914 Mon Sep 17 00:00:00 2001 From: Jussi Elo Date: Thu, 5 Nov 2026 09:54:32 +0000 Subject: [PATCH 01/10] fix(uninstall): do not create the folders a dry run then lists for removal `rocm uninstall` started the client file logger before it planned, and the logger creates `/logs`. On a machine ROCm CLI had never touched, `rocm uninstall --dry-run` therefore created the data folder and then reported it as the one thing to remove, so a dry run was not free of side effects and an empty machine looked installed. It happened with the default folders and with ROCM_CLI_DATA_DIR set alike. The `uninstall` command now skips the file logger. Other commands still log as before. Scenario uninstall-06 runs a dry run on a machine with none of the folders and asserts both that the plan says there is nothing to remove and that no folder exists afterwards; a unit test pins which invocations skip the logger. Signed-off-by: Jussi Elo --- README.md | 8 ++- apps/rocm/src/logging.rs | 31 ++++++++++ apps/rocm/src/main.rs | 7 ++- docs/manual-testing.md | 5 ++ docs/testing.md | 5 +- tests/e2e-cucumber/features/uninstall.feature | 14 +++++ .../e2e-cucumber/tests/e2e/uninstall_steps.rs | 58 +++++++++++++++++++ 7 files changed, 121 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 340d3c8a52..9422093d24 100644 --- a/README.md +++ b/README.md @@ -1393,9 +1393,11 @@ rocm uninstall [--yes] [--dry-run] `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. 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. 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/logging.rs b/apps/rocm/src/logging.rs index d6f92624a6..b6174f5af1 100644 --- a/apps/rocm/src/logging.rs +++ b/apps/rocm/src/logging.rs @@ -34,6 +34,18 @@ const MAX_RETAINED_LOGS: usize = 7; /// else (dependency noise stays out of the file). const DEFAULT_FILTER: &str = "warn,rocm=info,rocm_dash_tui=info,rocm_dash_daemon=info"; +/// Whether this invocation opens the client log file at all. +/// +/// `rocm uninstall` does not: it inspects and deletes the folders the logger +/// would create, so starting the logger first made a dry run list a `logs` +/// folder it had just made. In a direct invocation the subcommand is the first +/// argument, because `rocm` has no global flags and does not abbreviate +/// subcommand names; an uninstall reached from `rocm chat` or a freeform +/// request runs under a logger that was already started. +pub fn is_enabled_for(raw_args: &[String]) -> bool { + raw_args.first().is_none_or(|arg| arg != "uninstall") +} + /// Initialize the process-wide `tracing` subscriber, writing to a daily- /// rotated file under `paths.client_log_dir()`. /// @@ -167,6 +179,25 @@ mod tests { ) } + fn args(list: &[&str]) -> Vec { + list.iter().map(|arg| (*arg).to_string()).collect() + } + + #[test] + fn uninstall_is_the_only_invocation_that_skips_the_log_file() { + // The scenario `uninstall-06` proves the behavior (a dry run creates and + // lists nothing); this pins which invocations that applies to. + assert!(!is_enabled_for(&args(&["uninstall"]))); + assert!(!is_enabled_for(&args(&["uninstall", "--dry-run"]))); + assert!(is_enabled_for(&args(&[]))); + assert!(is_enabled_for(&args(&["examine"]))); + assert!(is_enabled_for(&args(&["--help"]))); + // `runtimes uninstall` removes one runtime, not the folders the logger + // writes to, and a longer word is not the subcommand. + assert!(is_enabled_for(&args(&["runtimes", "uninstall", "x"]))); + assert!(is_enabled_for(&args(&["uninstall-all"]))); + } + #[test] fn temp_paths_gives_each_call_its_own_root_even_for_one_label() { crate::test_support::assert_each_call_gets_its_own_root(|| temp_paths("same-label").0); diff --git a/apps/rocm/src/main.rs b/apps/rocm/src/main.rs index b30dc118f7..7b2fb735c3 100644 --- a/apps/rocm/src/main.rs +++ b/apps/rocm/src/main.rs @@ -1661,14 +1661,15 @@ fn run() -> Result<()> { // non-blocking file writer, so an early drop would silently truncate the // log. A failed/missing `AppPaths::discover()` degrades to no logging // rather than a startup failure. - let _log_guard = AppPaths::discover() - .ok() + let raw_args: Vec = std::env::args().skip(1).collect(); + let _log_guard = logging::is_enabled_for(&raw_args) + .then(AppPaths::discover) + .and_then(Result::ok) .and_then(|paths| logging::init(&paths)); maybe_migrate_legacy_dashboard_config(); maybe_notice_legacy_uv_cache(); - let raw_args: Vec = std::env::args().skip(1).collect(); if raw_args.is_empty() { return launch_default(); } diff --git a/docs/manual-testing.md b/docs/manual-testing.md index 6b18e694a1..35407e69d6 100644 --- a/docs/manual-testing.md +++ b/docs/manual-testing.md @@ -1071,6 +1071,11 @@ Expected result: `PATH change left in place` and names it, and the `PATH` change stays. - With `rocm uninstall --keep-binaries`, the review says the `PATH` change stays too, and it does. +- On a home folder ROCm CLI never touched, the dry run says + `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. - 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 525cb9fb99..b843f5294a 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -954,7 +954,10 @@ symlinks. 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: +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: ```bash cargo xtask e2e -- -n "uninstall-" diff --git a/tests/e2e-cucumber/features/uninstall.feature b/tests/e2e-cucumber/features/uninstall.feature index 3e06a03efe..286a59c0c2 100644 --- a/tests/e2e-cucumber/features/uninstall.feature +++ b/tests/e2e-cucumber/features/uninstall.feature @@ -66,3 +66,17 @@ Feature: Uninstall And the uninstall does not name the default install's cache folder And the data folder's own cache folder is gone And the default install's cache folder still holds the user's files + + # `rocm uninstall --dry-run` shows what would be removed without changing + # anything. It once started the file logger first, which created the data + # folder's `logs` folder, and then listed that folder as the one thing to + # remove, so a machine ROCm CLI had never touched looked installed. The + # promise is two-sided: the plan says there is nothing to remove, and the + # folders it would have removed are still absent afterwards. + @id:uninstall-dry-run-on-an-untouched-machine-creates-nothing + Scenario: uninstall-06 - A dry run on a machine ROCm CLI never touched reports nothing to remove and creates nothing + Given ROCm CLI has never created its folders in the user's home + When the user dry-runs an uninstall + Then the uninstall succeeds + And the uninstall reports that nothing would be removed + And ROCm CLI has still not created its folders diff --git a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs index 13871a4cbe..3b818cffb5 100644 --- a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs @@ -283,6 +283,64 @@ async fn default_cache_intact(world: &mut E2eWorld) { ); } +/// Every place the CLI keeps state when only the config and data folders are +/// set: those two, the cache folder inside the data folder, and the default +/// `~/.rocm` that a stray write would land in. The harness's own cache folder +/// is left out because a runner may share it between scenarios. +fn state_folders(world: &E2eWorld) -> Vec { + let paths = world.app_paths(); + vec![ + paths.config_dir, + paths.data_dir.clone(), + paths.data_dir.join("cache"), + home_dir(world).join(".rocm"), + ] +} + +#[given("ROCm CLI has never created its folders in the user's home")] +async fn no_folders_yet(world: &mut E2eWorld) { + // The harness creates the config, data and cache folders empty before each + // scenario; a machine ROCm CLI never touched has none of them. + for sub in ["config", "data", "cache"] { + let folder = root(world).join(sub); + std::fs::remove_dir(&folder) + .unwrap_or_else(|e| panic!("failed to remove the empty {}: {e}", folder.display())); + } + for folder in state_folders(world) { + assert!( + std::fs::symlink_metadata(&folder).is_err(), + "the scenario must start without {}", + folder.display() + ); + } +} + +#[when("the user dry-runs an uninstall")] +async fn dry_run_uninstall(world: &mut E2eWorld) { + run_without_cache_setting(world, &["uninstall", "--keep-binaries", "--dry-run"]); +} + +#[then("the uninstall reports that nothing would be removed")] +async fn reports_nothing_to_remove(world: &mut E2eWorld) { + let stdout = output(world); + assert!( + stdout.contains("Nothing managed by rocm-cli would be removed."), + "a machine with no folders has nothing to remove:\n{stdout}" + ); +} + +#[then("ROCm CLI has still not created its folders")] +async fn still_no_folders(world: &mut E2eWorld) { + for folder in state_folders(world) { + assert!( + std::fs::symlink_metadata(&folder).is_err(), + "the dry run created {}:\n{}", + folder.display(), + output(world) + ); + } +} + fn output(world: &E2eWorld) -> &str { world .cli_output From c37cef0f643411acd272b133f03060dfedc9f424 Mon Sep 17 00:00:00 2001 From: Jussi Elo Date: Thu, 5 Nov 2026 11:35:53 +0000 Subject: [PATCH 02/10] fix(uninstall): correct the dry-run footer and stop answering --force with --force-dev-binaries A dry run ended with "Choose Review uninstall to approve removal.", a control the command line does not have, and it printed that even when there was nothing to remove. A person at a terminal now gets "run it again without --dry-run" when there is something to remove, and nothing when there is not. Output that is captured (the dashboard's /uninstall and the daemon's rocm_command tool run the dry run as a subprocess) names no next step, since the real step belongs to whatever drives it. The assistant's preview has no flag to offer, so it says removal needs approval. The three wordings come from one audience value, chosen from whether the command has a terminal, rather than from strings that can drift. A mistyped --force was answered with "a similar argument exists: --force-dev-binaries", which removes the binaries of a development build, and so were near misses of it. clap ranks every declared flag by name, so --force is now declared, hidden, and refused with a pointer to --yes before anything is planned; near misses land on it instead of on the destructive flag, and a typo of the whole flag is still met with that flag. rocm uninstall --help now ends with examples that start with a dry run. Scenarios uninstall-07 to uninstall-11 cover the footer at a terminal (run again as it says, answering the prompt), outside one, with an empty plan, the --force cases, and the help examples. Every uninstall step now refuses to run without --keep-binaries. Signed-off-by: Jussi Elo --- README.md | 14 +- apps/rocm/src/deletion_properties.rs | 1 + apps/rocm/src/main.rs | 143 +++++++++- apps/rocm/src/uninstall.rs | 14 +- apps/rocm/src/uninstall_plan.rs | 150 +++++++++- docs/manual-testing.md | 16 +- docs/testing.md | 15 +- tests/e2e-cucumber/features/uninstall.feature | 60 ++++ .../e2e-cucumber/tests/e2e/uninstall_steps.rs | 261 +++++++++++++++++- 9 files changed, 642 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 9422093d24..dc7d482e24 100644 --- a/README.md +++ b/README.md @@ -1393,11 +1393,15 @@ rocm uninstall [--yes] [--dry-run] `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 its output is not read at a terminal, +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/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 7b2fb735c3..dd352f5952 100644 --- a/apps/rocm/src/main.rs +++ b/apps/rocm/src/main.rs @@ -771,6 +771,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, @@ -798,6 +802,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, }, } @@ -2268,15 +2277,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, + }) => { + reject_uninstall_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()); @@ -2286,6 +2299,20 @@ fn dispatch(cli: Cli) -> Result<()> { } } +/// `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. +fn reject_uninstall_force(force: bool) -> Result<()> { + if force { + bail!( + "`--force` is not an option of `rocm uninstall`; use `--yes` to skip the confirmation" + ); + } + Ok(()) +} + /// Build the command tree handed to `clap_complete` for shell completions. /// /// clap_complete's AOT generators do not filter `hide = true` subcommands the @@ -3216,6 +3243,104 @@ pub(crate) mod tests { ); } + /// `--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_uninstall_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_uninstall_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_uninstall_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 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 the_preview_marker_is_explained_and_not_contradicted() { let help = Cli::command().render_long_help().to_string(); diff --git a/apps/rocm/src/uninstall.rs b/apps/rocm/src/uninstall.rs index 8c32f9b7bd..b213f2f373 100644 --- a/apps/rocm/src/uninstall.rs +++ b/apps/rocm/src/uninstall.rs @@ -21,7 +21,7 @@ use anyhow::{Context, Result, bail}; use rocm_core::{AppPaths, interactive_terminal}; 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, }; @@ -66,7 +66,14 @@ impl PathEdit { 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(()); @@ -841,7 +848,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 e450fde189..9fd8116b37 100644 --- a/apps/rocm/src/uninstall_plan.rs +++ b/apps/rocm/src/uninstall_plan.rs @@ -268,10 +268,59 @@ 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 the process has a + /// terminal on both streams. + 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 `chat.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 +348,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 +574,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 `chat.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/manual-testing.md b/docs/manual-testing.md index 35407e69d6..c9b687f781 100644 --- a/docs/manual-testing.md +++ b/docs/manual-testing.md @@ -1063,7 +1063,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 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. @@ -1075,7 +1080,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 b843f5294a..f810711fb4 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -955,9 +955,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; output that is not read at 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 `apps/rocm/src/chat.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..fef7df98f4 100644 --- a/tests/e2e-cucumber/features/uninstall.feature +++ b/tests/e2e-cucumber/features/uninstall.feature @@ -80,3 +80,63 @@ 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 + + # Output that is not read at 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 diff --git a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs index 3b818cffb5..bee597f163 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"; @@ -89,24 +90,31 @@ fn run_uninstall_with( keep: &[&str], settings: &[(&str, &str)], ) { + let mut args = vec!["uninstall", "--keep-binaries"]; + if confirmed { + args.push("--yes"); + } + args.extend_from_slice(keep); + 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 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), ]; 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 +459,244 @@ 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}" + ); + } +} + +#[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 '--forc' found"), + "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(|(_, rest)| rest) + .unwrap_or_else(|| panic!("the help has no examples:\n{stdout}")); + 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}" + ); +} From 19fa6f59637069dd6ef164e6dea79ff704899053 Mon Sep 17 00:00:00 2001 From: Jussi Elo Date: Thu, 5 Nov 2026 13:36:19 +0000 Subject: [PATCH 03/10] test(e2e): satisfy clippy::map_unwrap_or in the uninstall help step The step that finds the `EXAMPLES:` block in `rocm uninstall --help` used `map(..).unwrap_or_else(..)`, which the workspace's pedantic lints reject, so the clippy job and both Windows build jobs failed to compile the e2e harness. `map_or_else` keeps the same panic message and behavior. Signed-off-by: Jussi Elo --- tests/e2e-cucumber/tests/e2e/uninstall_steps.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs index bee597f163..e3a5c795fa 100644 --- a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs @@ -681,10 +681,10 @@ async fn ask_for_uninstall_help(world: &mut E2eWorld) { #[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(|(_, rest)| rest) - .unwrap_or_else(|| panic!("the help has no examples:\n{stdout}")); + 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) From f8e3150c77a6ec5e4356742c9b1802d3058d199f Mon Sep 17 00:00:00 2001 From: Jussi Elo Date: Fri, 6 Nov 2026 15:00:59 +0000 Subject: [PATCH 04/10] docs(uninstall): cite the test that backs the assistant's preview as a link, from the file it now lives in The testing guide named the test `lifecycle_read_mutate_split_is_honest` with a bare backticked path, which no link check can see go stale, and the path was already stale: the test moved from chat.rs to tool_policy.rs, so the guide and the two code comments that point at it named the wrong file. The guide now cites tool_policy.rs as a relative Markdown link, which the documentation link check resolves, and the comments name the file the test is in. Signed-off-by: Jussi Elo --- apps/rocm/src/uninstall_plan.rs | 4 ++-- docs/testing.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/rocm/src/uninstall_plan.rs b/apps/rocm/src/uninstall_plan.rs index 9fd8116b37..8aa347a66c 100644 --- a/apps/rocm/src/uninstall_plan.rs +++ b/apps/rocm/src/uninstall_plan.rs @@ -310,7 +310,7 @@ impl PlanAudience { } Self::Captured => None, // The assistant's own uninstall is an approval action; see - // `lifecycle_read_mutate_split_is_honest` in `chat.rs`. + // `lifecycle_read_mutate_split_is_honest` in `tool_policy.rs`. Self::Assistant => Some("Nothing was removed. Removal needs your approval."), } } @@ -647,7 +647,7 @@ mod tests { /// 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 `chat.rs` pins + /// 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. diff --git a/docs/testing.md b/docs/testing.md index f42c41a189..c2d3fde814 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -1045,7 +1045,7 @@ 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 `apps/rocm/src/chat.rs` backs. +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: From cf80f3d10658bf0c73b10256cf95cf94849dbc83 Mon Sep 17 00:00:00 2001 From: Jussi Elo Date: Fri, 6 Nov 2026 16:32:11 +0000 Subject: [PATCH 05/10] test(uninstall): match only the unknown-argument error in the near-miss scenario The scenario asserted clap's exact wording for the unknown-argument error, including the argument it echoes. The exit code 2 and the absence of `--force-dev-binaries` already carry the point, so the step now matches only `unexpected argument`, and a clap upgrade that rewords the message no longer breaks the scenario while it still fails if the destructive flag is suggested again. Signed-off-by: Jussi Elo --- tests/e2e-cucumber/tests/e2e/uninstall_steps.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs index e3a5c795fa..d623537aee 100644 --- a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs @@ -661,7 +661,7 @@ async fn error_does_not_suggest_dev_binaries(world: &mut E2eWorld) { "an unknown flag exits 2\nstderr:\n{stderr}" ); assert!( - stderr.contains("unexpected argument '--forc' found"), + stderr.contains("unexpected argument"), "expected the unknown-argument error on stderr:\n{stderr}" ); assert!( From e0587305f9c3d06eb7bbe42c048f7cff85295f40 Mon Sep 17 00:00:00 2001 From: Jussi Elo Date: Fri, 6 Nov 2026 16:32:20 +0000 Subject: [PATCH 06/10] refactor(uninstall): keep the refusal of the hidden --force beside the uninstall command `reject_uninstall_force` was domain logic in main.rs. It now lives in uninstall.rs, which owns `uninstall()`, as `reject_force`; the dispatch arm in main.rs calls it through the qualified `uninstall::reject_force` and the unit tests in cli.rs import it from there. uninstall.rs rather than uninstall_plan.rs, because the plan module holds the shared plan types and file-removal helpers that storage.rs reuses, while this is argument handling for the `uninstall` command alone. The architecture note for uninstall.rs names it. Signed-off-by: Jussi Elo --- apps/rocm/src/cli.rs | 10 ++++------ apps/rocm/src/main.rs | 16 +--------------- apps/rocm/src/uninstall.rs | 14 ++++++++++++++ docs/architecture.md | 2 +- 4 files changed, 20 insertions(+), 22 deletions(-) diff --git a/apps/rocm/src/cli.rs b/apps/rocm/src/cli.rs index 0ba11b3ba4..200c695643 100644 --- a/apps/rocm/src/cli.rs +++ b/apps/rocm/src/cli.rs @@ -1414,7 +1414,7 @@ impl PermissionsModeArg { #[cfg(test)] mod tests { use super::*; - use crate::{cli_command, device_policy_name, engine_inventory, reject_uninstall_force}; + use crate::{cli_command, device_policy_name, engine_inventory, uninstall::reject_force}; use clap::{CommandFactory, Parser}; use rocm_engine_protocol::DevicePolicy; @@ -2193,20 +2193,18 @@ mod tests { panic!("not an uninstall command"); }; assert!(force.is_some() && !force_dev_binaries); - let refusal = reject_uninstall_force(force.is_some()) - .unwrap_err() - .to_string(); + 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_uninstall_force(false).is_ok()); + 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_uninstall_force(force.is_some()).is_err()); + 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. diff --git a/apps/rocm/src/main.rs b/apps/rocm/src/main.rs index cc47a9fe90..fde5fec54e 100644 --- a/apps/rocm/src/main.rs +++ b/apps/rocm/src/main.rs @@ -946,7 +946,7 @@ fn dispatch(cli: Cli) -> Result<()> { force_dev_binaries, force, }) => { - reject_uninstall_force(force.is_some())?; + uninstall::reject_force(force.is_some())?; uninstall(UninstallOptions { yes, dry_run, @@ -966,20 +966,6 @@ fn dispatch(cli: Cli) -> Result<()> { } } -/// `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. -fn reject_uninstall_force(force: bool) -> Result<()> { - if force { - bail!( - "`--force` is not an option of `rocm uninstall`; use `--yes` to skip the confirmation" - ); - } - Ok(()) -} - /// Build the command tree handed to `clap_complete` for shell completions. /// /// clap_complete's AOT generators do not filter `hide = true` subcommands the diff --git a/apps/rocm/src/uninstall.rs b/apps/rocm/src/uninstall.rs index 4d742b857b..65aa4d7f96 100644 --- a/apps/rocm/src/uninstall.rs +++ b/apps/rocm/src/uninstall.rs @@ -63,6 +63,20 @@ 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)?; diff --git a/docs/architecture.md b/docs/architecture.md index 6fbe61fc53..08afa3b265 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -106,7 +106,7 @@ 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`, `wheel_runtime_key` and `has_nontrivial_directory_contents`, which name and inspect the install a plan targets, stay in `therock.rs`. `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`. - [`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_chat_rocm_command_safety`, which refuses a public-bind, non-loopback or CPU `serve` and 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_chat_rocm_command_safety` here instead of through `chat`. `chat.rs` calls into it and 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.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`), 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.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. - [`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.rs`](../apps/rocm/src/chat.rs) (the deterministic `rocm update` tool summary), 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. From 370bba73cf2382e5f7fd3491c2d0ad0bd4e63aaf Mon Sep 17 00:00:00 2001 From: Jussi Elo Date: Fri, 6 Nov 2026 16:32:29 +0000 Subject: [PATCH 07/10] test(uninstall): make the near-miss guard fail whichever way clap's suggestions change The hidden `--force` works because clap's candidates for a near miss are every declared long name, hidden or not, so `--forc` is steered to `--force` and its refusal instead of to `--force-dev-binaries`. If a clap upgrade stopped suggesting hidden arguments, `--forc` would be answered with the destructive flag again. The guard test already failed on the destructive suggestion; it now also requires the near misses to name `--force`, and the two checks together do not depend on clap's wording around the suggestion. Signed-off-by: Jussi Elo --- apps/rocm/src/cli.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/apps/rocm/src/cli.rs b/apps/rocm/src/cli.rs index 200c695643..2438916efc 100644 --- a/apps/rocm/src/cli.rs +++ b/apps/rocm/src/cli.rs @@ -2226,6 +2226,28 @@ mod tests { 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"]) From ea6653753edb73685dee52a0009d0a5f093a1321 Mon Sep 17 00:00:00 2001 From: Jussi Elo Date: Mon, 9 Nov 2026 14:13:46 +0000 Subject: [PATCH 08/10] docs(uninstall): say the dry-run footer needs stdin and stdout to be terminals `interactive_terminal()` checks stdin and stdout, so a dry run with either one redirected, for example `rocm uninstall --dry-run < /dev/null` at a terminal, is answered for a captured caller and prints no footer. The doc comment on `PlanAudience::for_command` said "a terminal on both streams", and the README, manual-testing.md, testing.md and the comment above uninstall-08 spoke of output that is not read at a terminal. They now name both streams. Signed-off-by: Jussi Elo --- README.md | 4 ++-- apps/rocm/src/uninstall_plan.rs | 6 ++++-- docs/manual-testing.md | 4 ++-- docs/testing.md | 2 +- tests/e2e-cucumber/features/uninstall.feature | 2 +- 5 files changed, 10 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 247406ec45..496b267bbb 100644 --- a/README.md +++ b/README.md @@ -1457,8 +1457,8 @@ do and asks `[y/N]` (default: no) before doing it. Use `--dry-run` to only list, 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 its output is not read at a terminal, -it says nothing about a next step. It does not create the folders it reports on: +`--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`. diff --git a/apps/rocm/src/uninstall_plan.rs b/apps/rocm/src/uninstall_plan.rs index 358643da8b..3282e59119 100644 --- a/apps/rocm/src/uninstall_plan.rs +++ b/apps/rocm/src/uninstall_plan.rs @@ -292,8 +292,10 @@ pub(crate) enum PlanAudience { } impl PlanAudience { - /// The audience for `rocm uninstall` itself, from whether the process has a - /// terminal on both streams. + /// 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 diff --git a/docs/manual-testing.md b/docs/manual-testing.md index 676e2498f2..f70e75ab83 100644 --- a/docs/manual-testing.md +++ b/docs/manual-testing.md @@ -1134,8 +1134,8 @@ Expected result: 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 it lists the same items and - omits that last line (scenario `uninstall-08`). + 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. diff --git a/docs/testing.md b/docs/testing.md index e6b4edbe40..de69d2eca0 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -1217,7 +1217,7 @@ anything is removed, and a dry run on a machine ROCm CLI never touched (`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; output that is not read at a terminal, and an +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 diff --git a/tests/e2e-cucumber/features/uninstall.feature b/tests/e2e-cucumber/features/uninstall.feature index fef7df98f4..03bf56d61e 100644 --- a/tests/e2e-cucumber/features/uninstall.feature +++ b/tests/e2e-cucumber/features/uninstall.feature @@ -97,7 +97,7 @@ Feature: Uninstall Then the uninstall succeeds And the config folder is gone - # Output that is not read at a terminal (a script, the dashboard's + # 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. From 5e7eecb2f6590527369e86d3a8408bf315baab3c Mon Sep 17 00:00:00 2001 From: Jussi Elo Date: Mon, 9 Nov 2026 14:14:07 +0000 Subject: [PATCH 09/10] docs(uninstall): list PlanAudience in the uninstall_plan.rs inventories `PlanAudience` is imported by `uninstall.rs`, which picks it from `interactive_terminal`, and by the `uninstall_case` property in `deletion_properties.rs`, which renders as `Captured`; `chat/mcp_bridge.rs` reaches the `Assistant` audience through `render_uninstall_dry_run` and does not import it. The module doc comment and the `uninstall_plan.rs` entry in docs/architecture.md listed the types the module owns and each consumer's imports, and named neither the type nor those two importers. Signed-off-by: Jussi Elo --- apps/rocm/src/uninstall_plan.rs | 12 ++++++++---- docs/architecture.md | 2 +- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/apps/rocm/src/uninstall_plan.rs b/apps/rocm/src/uninstall_plan.rs index 3282e59119..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 _; diff --git a/docs/architecture.md b/docs/architecture.md index 2ed38789a8..029d6ea30c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -115,7 +115,7 @@ Each per-crate module inventory lists one file per line. Flat inventories (every - [`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()`, 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`), 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_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: From 8bd3b676d3838c13a5ce5d302275ff707da3dcc3 Mon Sep 17 00:00:00 2001 From: Jussi Elo Date: Mon, 9 Nov 2026 14:14:23 +0000 Subject: [PATCH 10/10] test(uninstall): pin the assistant's uninstall preview with a scenario The footer "Nothing was removed. Removal needs your approval." reaches users through the assistant's `rocm_command` tool and was held only by a unit test. Scenario uninstall-12 drives the hidden `rocm mcp-call` entry point without a model, asserts the preview lists the config folder and says removal needs approval without offering a flag, and checks that the folder still holds the user's files. The call is made without `--allow-mutation`, and the isolated environment the other uninstall steps use is now one helper they share. Signed-off-by: Jussi Elo --- tests/e2e-cucumber/features/uninstall.feature | 16 +++ .../e2e-cucumber/tests/e2e/uninstall_steps.rs | 111 ++++++++++++++++-- 2 files changed, 116 insertions(+), 11 deletions(-) diff --git a/tests/e2e-cucumber/features/uninstall.feature b/tests/e2e-cucumber/features/uninstall.feature index 03bf56d61e..63e2568f33 100644 --- a/tests/e2e-cucumber/features/uninstall.feature +++ b/tests/e2e-cucumber/features/uninstall.feature @@ -140,3 +140,19 @@ Feature: Uninstall 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 d623537aee..0dbf34f51c 100644 --- a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs @@ -77,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); } @@ -102,17 +115,11 @@ fn run_uninstall_with( /// every other uninstall here. fn run_uninstall_args(world: &mut E2eWorld, args: &[&str], settings: &[(&str, &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 mut envs = vec![ - ("HOME", home.as_str()), - ("UV_CACHE_DIR", &uv), - ("HF_HOME", &hf), - ]; + 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); world.cli_output = Some(stdout); @@ -617,6 +624,88 @@ async fn dry_run_offers_no_step(world: &mut E2eWorld) { } } +/// 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();