Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 7 additions & 8 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -345,14 +345,13 @@ on two counts, and both change how you edit it:
the modules it declares, such as [catalog.rs](crates/rocm-core/src/diagnose/catalog.rs)
(each mode's checker and OS scoping) — adding, renaming, or re-scoping a
failure mode means changing the CLI **first**, then the two docs. That feature is what
catches you if you forget. Two sentences in
[SKILL.md](skills/rocm-doctor/SKILL.md) are fixtures too. One is the Phase 0
sentence "requires `contract_version` N or higher": scenario skill-07 parses
it and holds that number (the contract number) equal to what
`rocm fix --json` publishes. The other is the "The other N ... print-only"
sentence, whose number (the print-only count) is checked by
[skill_reference.rs](tests/e2e-cucumber/tests/skill_reference.rs) against the
catalog table. Keep both wordings when editing the skill.
catches you if you forget. Some sentences in
[SKILL.md](skills/rocm-doctor/SKILL.md) are fixtures too: the module doc of
[skill_reference.rs](tests/e2e-cucumber/tests/skill_reference.rs) lists them all
and says which test reads each. Reword them only together with the test that reads
them. One is the Phase 0 sentence "requires `contract_version` N or higher": scenario
skill-07 parses it and holds that number (the contract number) equal to what
`rocm fix --json` publishes.
Raise the contract number only after a release publishes that contract. The
skill is federated from `main`, and the installer that Phase 0 offers installs
the release channel, so an earlier raise would make the published skill stop
Expand Down
15 changes: 9 additions & 6 deletions crates/rocm-core/src/diagnose/catalog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,12 +267,15 @@ mod tests {
/// Every diagnosis must agree with the fix catalog about whether the CLI
/// can apply the fix itself.
///
/// An agent following the rocm-doctor skill branches on `auto_applicable`
/// from `diagnose --json` to decide whether to offer to run `rocm fix` or
/// merely print the plan, while `fix::apply` dispatches on `RECIPES`. The
/// two are written in different files and nothing but this test holds them
/// together, so a drift makes the CLI contradict itself: it would advertise
/// a fix as one it can run and then refuse, or the reverse.
/// An agent following the rocm-doctor skill reads `fix.class` from
/// `diagnose --json` (`auto_applicable` is derived from it) to decide whether
/// `rocm fix` carries the fix out or merely prints the plan, while
/// `fix::apply` dispatches on `RECIPES`. `take_applicability_from_the_catalog`
/// derives `fix.class` and `fix.auto_applicable` from the catalog's class,
/// which is what keeps them in step. This test asserts only the
/// `auto_applicable` half, against the catalog's `applies_itself()` (true for
/// `auto` alone), so a diagnosis that bypassed the derivation would advertise
/// a fix as one the CLI can run and then refuse, or the reverse, and fail here.
///
/// Both OS families are exercised because the checkers build their `Fix`
/// per-OS and only one branch is taken per run, so a Linux-only test would
Expand Down
3 changes: 2 additions & 1 deletion crates/rocm-core/src/fix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,14 @@ use std::io::Write;

pub(crate) use catalog::{COMGR_CONFLICT_NEITHER_OPTION_RECOMMENDED, is_catalog_id};
pub use catalog::{class_on, needs_on};
pub use consent::{DRY_RUN_NOTICE, NON_INTERACTIVE_REFUSAL};
pub use manifest::{
CATALOG_CONTRACT_VERSION, CatalogManifest, ManifestEntry, ManifestPlatform, catalog_manifest,
catalog_manifest_json,
};
pub use options::{FixClass, FixOptions, exit};
pub(crate) use render::format_flags;
pub use render::list_recipes;
pub use render::{fix_plan_text, list_recipes};
// The catalog's test-only oracles, which the `diagnose` module holds its own copies of
// a recipe to.
#[cfg(test)]
Expand Down
12 changes: 9 additions & 3 deletions crates/rocm-core/src/fix/catalog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,13 @@ impl FixRecipe {
/// it does not apply here at all — callers reach the OS gate in [`apply`]
/// before the class is ever acted on, and understating is the safe default.
pub(super) fn class_here(&self) -> FixClass {
self.platform(current_os())
.map_or(FixClass::PrintOnly, |p| p.class)
self.class_on_os(current_os())
}

/// What this recipe does on the platform `os`, [`FixClass::PrintOnly`] when it
/// does not apply there (the same understatement as [`Self::class_here`]).
pub(super) fn class_on_os(&self, os: &str) -> FixClass {
self.platform(os).map_or(FixClass::PrintOnly, |p| p.class)
}

/// The operating systems this applies on, in catalog order.
Expand Down Expand Up @@ -2378,7 +2383,8 @@ mod tests {
// apply() returns 1 only when a platform's class is Auto and the recipe
// has no runner (`Plan::MissingRunner`). `a_recipe_that_acts_has_a_runner`
// keeps that impossible; assert the reachability argument here so
// reference.md's row 1 is accounted for rather than silently untested.
// the manifest's `internal` exit code is accounted for rather than
// silently untested.
assert!(
RECIPES.iter().all(|r| {
!r.applies_on.iter().any(|p| p.class.applies_itself()) || r.runner.is_some()
Expand Down
18 changes: 17 additions & 1 deletion crates/rocm-core/src/fix/consent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,22 @@ use std::time::Duration;
pub(super) const RUN_TIMEOUT: Duration = Duration::from_mins(1);
pub(super) const QUERY_TIMEOUT: Duration = Duration::from_secs(8);

/// What `rocm fix` says on stderr when it is not given `--yes` in a shell with no
/// terminal, where nobody can be asked.
///
/// `pub` only so the eval-fixture generator in `xtask` replays the same text the
/// command prints, from this one constant; hidden from the docs because it is not an
/// API to build on.
#[doc(hidden)]
pub const NON_INTERACTIVE_REFUSAL: &str =
"Non-interactive shell and --yes not passed; refusing to apply.";

/// The line a runner prints after a plan when `--dry-run` stopped it before acting.
///
/// `pub` only for the same reason as [`NON_INTERACTIVE_REFUSAL`].
#[doc(hidden)]
pub const DRY_RUN_NOTICE: &str = "(dry-run; not executed)";

/// Print a failure explanation to stderr, ignoring write failures (closed
/// stderr, full disk) so an I/O error while explaining a failure can't itself
/// panic the process.
Expand Down Expand Up @@ -70,7 +86,7 @@ const fn consent_without_prompt(assume_yes: bool, stdin_is_terminal: bool) -> Op
pub(super) fn confirm(prompt: &str, assume_yes: bool) -> bool {
if let Some(verdict) = consent_without_prompt(assume_yes, std::io::stdin().is_terminal()) {
if !verdict {
fail!("Non-interactive shell and --yes not passed; refusing to apply.");
fail!("{NON_INTERACTIVE_REFUSAL}");
}
return verdict;
}
Expand Down
82 changes: 65 additions & 17 deletions crates/rocm-core/src/fix/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
//! shares, and the refusal printed when a diagnosis position (`#2`) is passed
//! as a fix-id.

use super::catalog::{FixRecipe, RECIPES};
use super::catalog::{FixRecipe, RECIPES, find_recipe};
use super::consent::current_os;
use super::options::FixClass;

Expand Down Expand Up @@ -107,29 +107,53 @@ pub(crate) fn format_flags(
}

pub(super) fn print_recipe(r: &FixRecipe) {
println!("Fix: {} -- {}", r.fix_id, r.title);
println!("OS scope: {}", r.os_scope().join(", "));
println!("Rationale: {}", r.rationale);
for line in recipe_plan_lines(r, current_os()) {
println!("{line}");
}
}

/// Every line of the plan `rocm fix <id>` prints for `r` on the platform `os`, in
/// print order. What `os` changes is the class and the argument a plan names, which
/// are per platform; [`print_recipe`] passes the running one.
fn recipe_plan_lines(r: &FixRecipe, os: &str) -> Vec<String> {
let mut lines = vec![
format!("Fix: {} -- {}", r.fix_id, r.title),
format!("OS scope: {}", r.os_scope().join(", ")),
format!("Rationale: {}", r.rationale),
];
if !r.commands.is_empty() {
println!("Commands:");
for c in r.commands {
println!(" $ {c}");
}
lines.push("Commands:".to_owned());
lines.extend(r.commands.iter().map(|c| format!(" $ {c}")));
}
let platform = r.platform(os);
let flags = format_flags(
r.needs_sudo,
r.needs_reboot,
r.needs_relogin,
r.class_here(),
r.platform(current_os()).and_then(|p| p.needs),
r.class_on_os(os),
platform.and_then(|p| p.needs),
);
println!("Flags: {}", flags.join(", "));
for n in r.notes {
println!("Note: {n}");
}
for line in verify_lines(r) {
println!("{line}");
}
lines.push(format!("Flags: {}", flags.join(", ")));
lines.extend(r.notes.iter().map(|n| format!("Note: {n}")));
lines.extend(verify_lines(r));
lines
}

/// The plan `rocm fix <fix_id>` prints on `os` (`linux`, `windows` or `wsl`), or
/// `None` when there is no such fix.
///
/// It is the lines the command prints before it acts, and not the ones a runner adds
/// after (such as the command it is about to run), which name the user and the
/// machine.
///
/// `pub` only so the eval-fixture generator in `xtask` replays the plan without a
/// second copy of its wording; hidden from the docs because it is not an API to
/// build on.
#[doc(hidden)]
#[must_use]
pub fn fix_plan_text(fix_id: &str, os: &str) -> Option<String> {
let recipe = find_recipe(fix_id)?;
Some(recipe_plan_lines(recipe, os).join("\n") + "\n")
}

/// The `Verify` lines of the plan `print_recipe` prints, in print order: the
Expand Down Expand Up @@ -424,6 +448,30 @@ mod tests {
);
}

/// The plan a replaying tool prints is the one `rocm fix <id>` prints: the
/// class on the asked platform picks the flag, and an unknown id has no plan.
#[test]
fn fix_plan_text_is_the_plan_the_command_prints_for_the_platform() {
let linux = fix_plan_text("fix-4-render-group", "linux").expect("a plan");
assert!(linux.contains("\nOS scope: linux\n"), "{linux}");
assert!(
linux.contains("\nFlags: requires sudo, requires re-login, rocm fix can run it\n"),
"{linux}"
);
assert!(linux.ends_with('\n'));
// fix-4 does not apply on Windows, where the class falls back to print-only.
let windows = fix_plan_text("fix-4-render-group", "windows").expect("a plan");
assert!(windows.contains("manual only"), "{windows}");
assert_eq!(fix_plan_text("fix-0-nope", "linux"), None);
// The argument a plan waits for is per platform, and the flags line says it.
let needs_argument = fix_plan_text("fix-9-igpu-dgpu", "linux").expect("a plan");
assert!(
needs_argument
.contains("\nFlags: needs --device-index before `rocm fix` will run it\n"),
"{needs_argument}"
);
}

#[test]
fn indent_continuation_keeps_multi_line_verify_under_its_label() {
assert_eq!(indent_continuation("a\nb\nc", " "), "a\n b\n c");
Expand Down
59 changes: 31 additions & 28 deletions crates/rocm-core/src/fix/runners.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
//! the catalog in `fix/catalog.rs` names the entry point of each recipe's
//! runner and the running OS decides which variant runs.

use super::consent::{QUERY_TIMEOUT, RUN_TIMEOUT, confirm, fail, relay_output};
use super::consent::{DRY_RUN_NOTICE, QUERY_TIMEOUT, RUN_TIMEOUT, confirm, fail, relay_output};
use super::options::{FixOptions, exit};
use crate::probe_exec::{run, which};
use crate::quoting::ps_single_quote_escape;
Expand Down Expand Up @@ -106,7 +106,7 @@ pub(super) fn run_render_group(opts: &FixOptions) -> i32 {
};
println!("Will run: {program} {}", args.join(" "));
if opts.dry_run {
println!("(dry-run; not executed)");
println!("{DRY_RUN_NOTICE}");
return exit::OK;
}
if !confirm("Add user to render,video groups?", opts.yes) {
Expand Down Expand Up @@ -162,9 +162,10 @@ fn run_unset_override_linux() -> i32 {
///
/// Takes the paths rather than deriving them from `$HOME`, for the same reason
/// [`pin_device_in_rc_file`] takes its rc path: it makes the promise testable
/// without mutating a process-global. And the promise needs testing — fix-2 is
/// flagged `auto_applicable`, so `skills/rocm-doctor/` has to say plainly that
/// this arm still only reports, and something has to hold that true.
/// without mutating a process-global. And the promise needs testing — fix-2 has
/// a runner on every platform and is class `auto` on Windows, so
/// `skills/rocm-doctor/` has to say plainly that this arm still only reports, and
/// something has to hold that true.
fn report_persistent_override(candidates: &[PathBuf]) -> i32 {
let hits: Vec<&PathBuf> = candidates
.iter()
Expand Down Expand Up @@ -219,8 +220,8 @@ fn run_unset_override_windows(opts: &FixOptions) -> i32 {
/// the decline path testable without a real Windows host -- same reason
/// [`pin_device_in_rc_file`] takes its consent as a closure.
///
/// A decline must still exit `5`: `skills/rocm-doctor/reference.md` documents
/// `5` as "user declined", and a caller (human or agent) relies on that to
/// A decline must still exit `5`: the manifest's `exit_codes` publishes `5` as
/// `declined` (`exit::DECLINED`), and a caller (human or agent) relies on that to
/// tell "nothing happened because you said no" apart from "nothing happened
/// because there was nothing to do". Declining just the User scope can't
/// short-circuit straight to `return exit::DECLINED`, though -- if the Machine scope is
Expand Down Expand Up @@ -260,7 +261,7 @@ fn report_and_clear_override_windows(
shown.join(" ")
);
if opts.dry_run {
println!(" (dry-run; not executed)");
println!(" {DRY_RUN_NOTICE}");
} else if consent("Clear HSA_OVERRIDE_GFX_VERSION from User scope?") {
let (rc, out, err) = run("setx", &setx_args, RUN_TIMEOUT);
relay_output(&out, &err);
Expand Down Expand Up @@ -332,7 +333,7 @@ fn run_path_export_linux(opts: &FixOptions) -> i32 {
println!("Plan: append the following line to {}:", rc_file.display());
println!(" {export_line}");
if opts.dry_run {
println!("(dry-run; not executed)");
println!("{DRY_RUN_NOTICE}");
return exit::OK;
}
if !confirm(&format!("Append to {}?", rc_file.display()), opts.yes) {
Expand Down Expand Up @@ -431,7 +432,7 @@ fn path_export_windows(
println!("Plan: prepend {bin_dir} to your User PATH:");
println!(" [Environment]::SetEnvironmentVariable('PATH', '{escaped_new_path}', 'User')");
if opts.dry_run {
println!("(dry-run; not executed)");
println!("{DRY_RUN_NOTICE}");
return exit::OK;
}
if !confirm("Update User PATH?", opts.yes) {
Expand Down Expand Up @@ -493,12 +494,12 @@ fn run_hip_visible_devices_linux(opts: &FixOptions) -> i32 {
/// the rc file already pins a device, honour `--dry-run`, ask for consent, and
/// append.
///
/// Taking the rc path and the consent decision as parameters keeps this — the
/// one auto-fix path on Linux that really mutates a file — testable end to end
/// Taking the rc path and the consent decision as parameters keeps this —
/// unlike the fix-6 PATH runner, which derives both itself — testable end to end
/// against a temp file, with no `$HOME` mutation and no dependency on whether
/// stdin happens to be a terminal. Exit codes are the contract documented in
/// `skills/rocm-doctor/reference.md`: 0 applied/dry-run/already-set, 4 write
/// failed, 5 declined.
/// stdin happens to be a terminal. Exit codes are the `exit` constants in
/// `options.rs`, published as the manifest's `exit_codes`: 0 applied/dry-run/
/// already-set, 4 write failed, 5 declined.
fn pin_device_in_rc_file(
rc_file: &Path,
idx: i64,
Expand All @@ -518,7 +519,7 @@ fn pin_device_in_rc_file(
println!("Plan: append the following line to {}:", rc_file.display());
println!(" {export_line}");
if opts.dry_run {
println!("(dry-run; not executed)");
println!("{DRY_RUN_NOTICE}");
return exit::OK;
}
if !consent() {
Expand Down Expand Up @@ -566,7 +567,7 @@ fn run_hip_visible_devices_windows(opts: &FixOptions) -> i32 {
println!("Plan: persist HIP_VISIBLE_DEVICES in the User env scope:");
println!(" setx HIP_VISIBLE_DEVICES {idx}");
if opts.dry_run {
println!("(dry-run; not executed)");
println!("{DRY_RUN_NOTICE}");
return exit::OK;
}
if !confirm("Set HIP_VISIBLE_DEVICES in the User scope?", opts.yes) {
Expand Down Expand Up @@ -816,18 +817,20 @@ mod tests {

// ── Consent and mutation contract ──────────────────────────────
//
// `skills/rocm-doctor/reference.md` documents six exit codes, and the skill
// tells an agent it may run an auto-fix because the CLI "refuses on a
// non-interactive shell without --yes" and "confirms before mutating".
// The manifest's `exit_codes` (the `exit` constants in `options.rs`) names six
// codes, and `skills/rocm-doctor/SKILL.md` tells an agent to go through
// `--dry-run`, the user's OK and `--yes` because the CLI refuses on a
// non-interactive shell without `--yes` and confirms before mutating.
// Before these tests, codes 1, 4 and 5 were asserted nowhere in the repo and
// no test ever reached a runner that writes to disk: the two that look like
// they cover it don't — `dry_run_never_mutates_...` picks fix-2, whose Linux
// runner takes no FixOptions and never prompts, and diagnose.feature's
// preview scenario picks print-only fix-1, which returns before any runner.
//
// fix-9 is the auto-fix used here because its Linux runner is the one that
// genuinely appends to a file, and `pin_device_in_rc_file` lets that run
// against a temp path with an injected consent verdict.
// fix-9 (class `needs-argument`, applied once `--device-index` is given) is
// used here because its rc path and consent decision are injectable
// (`pin_device_in_rc_file`), so its append can run against a temp path with an
// injected consent verdict.

/// A unique scratch path under the workspace's test-artifact dir, following
/// the convention in `lib.rs`'s tests (no `tempfile` dev-dependency here).
Expand All @@ -854,10 +857,11 @@ mod tests {
}
}

/// `auto_applicable` means "the CLI has a runner", not "the runner mutates".
/// Having a runner is not the same as the `auto` class, and neither means
/// "the runner mutates".
///
/// fix-2's Linux arm only reports where the override is persisted; it never
/// edits dotfiles. `auto_applicable_recipes_have_a_runner` cannot catch a
/// edits dotfiles. `a_recipe_that_acts_has_a_runner` cannot catch a
/// regression here, because fix-2 does have a runner — so without this, a
/// doc promising a `--dry-run` preview the Linux user never gets stays
/// green. That is the drift `skills/rocm-doctor/` exists to prevent.
Expand Down Expand Up @@ -892,9 +896,8 @@ mod tests {

/// The Windows arm of fix-2 does mutate (it runs `setx` to clear the User
/// scope), so unlike the Linux arm above, a decline has to come back as
/// `5`, not `0` -- `skills/rocm-doctor/reference.md` documents `5` as
/// "user declined" and an agent tells that apart from "nothing to do"
/// this way.
/// `5`, not `0` -- the manifest's `exit_codes` publishes `5` as `declined`
/// and an agent tells that apart from "nothing to do" this way.
#[test]
fn windows_decline_on_user_scope_returns_5() {
let code =
Expand Down
6 changes: 3 additions & 3 deletions crates/rocm-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,9 @@ pub use examine::{
Examination, FrameworkProbe, WSL_PLATFORM_NOTE, gfx_is_apu_family, probe_wsl_distro_from_host,
};
pub use fix::{
CATALOG_CONTRACT_VERSION, CatalogManifest, FixOptions, ManifestEntry, ManifestPlatform,
apply as apply_fix, catalog_manifest, catalog_manifest_json, exit as fix_exit,
list_recipes as list_fix_recipes,
CATALOG_CONTRACT_VERSION, CatalogManifest, DRY_RUN_NOTICE, FixOptions, ManifestEntry,
ManifestPlatform, NON_INTERACTIVE_REFUSAL, apply as apply_fix, catalog_manifest,
catalog_manifest_json, exit as fix_exit, fix_plan_text, list_recipes as list_fix_recipes,
};
pub use gfx_target::{
extract_first_gfx_token, gfx_target_has_no_rocm_build, known_therock_families,
Expand Down
Loading
Loading