From 4acb649842f67e9dc9ff5e2b2e05c94d760872e6 Mon Sep 17 00:00:00 2001 From: "minimal-foundry[bot]" <327719912+minimal-foundry[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 20:32:54 +0000 Subject: [PATCH 1/5] feat(minimal): add min box rename and min box prune min box rename renames a box as BOX-010 defines and ends with exit 2 on the daemon's refusal, which names the holder. min box prune reaps the stopped and exited boxes through PruneBoxes, narrowed by --older-than and --parent. Off a terminal it needs --yes and ends with exit 2. --- crates/minimal/src/cli.rs | 55 +++ crates/minimal/src/cmd/boxes.rs | 2 +- crates/minimal/src/cmd/boxes/lifecycle.rs | 465 +++++++++++++++++++++- crates/minimal/src/cmd/mod.rs | 4 + crates/minimal/src/main.rs | 24 ++ 5 files changed, 547 insertions(+), 3 deletions(-) diff --git a/crates/minimal/src/cli.rs b/crates/minimal/src/cli.rs index fe4b794f8..7b3a77c79 100644 --- a/crates/minimal/src/cli.rs +++ b/crates/minimal/src/cli.rs @@ -442,6 +442,13 @@ pub enum BoxCommand { /// files. A running box is refused unless `--force` is given, which /// stops the box at once and then removes it Rm(BoxRmArgs), + /// Give a box a new name. The box keeps its id, its state and its + /// files. A name that a running box on the same host holds is refused + Rename(BoxRenameArgs), + /// Remove every stopped or exited box: its record, its events and its + /// files. A running box is never removed. `--older-than` and `--parent` + /// narrow what is removed. Off a terminal, `--yes` is required + Prune(BoxPruneArgs), } // BOX-158 (BCLI-001, BCLI-051): `min box list [--all] [-o json]`. @@ -494,6 +501,54 @@ pub struct BoxRmArgs { pub force: bool, } +// BOX-010 (BCLI-058): `min box rename `. +#[derive(Debug, Args)] +pub struct BoxRenameArgs { + /// The box: its id, the start of its id, or its name, as `min box list` + /// prints them + pub target: String, + /// The new name for the box + pub new_name: String, +} + +// BOX-021 (BCLI-061, BCLI-005): `min box prune [--older-than ] +// [--parent ] [--yes]`. +#[derive(Debug, Args)] +pub struct BoxPruneArgs { + /// Remove only the boxes that stopped or exited at least this long ago. + /// Takes a whole number of days, hours, minutes or seconds, such as + /// `7d`, `12h`, `30m` or `90s` + #[arg(long, value_name = "AGE", value_parser = parse_box_age)] + pub older_than: Option, + /// Remove only the child boxes of this box: its id, the start of its + /// id, or its name + #[arg(long, value_name = "BOX")] + pub parent: Option, + /// Remove the boxes without asking first + #[arg(long, short)] + pub yes: bool, +} + +/// Parses the `--older-than` age of `min box prune`: a whole number with a +/// `d`, `h`, `m` or `s` unit. +pub(crate) fn parse_box_age(arg: &str) -> Result { + let units: [(char, u64); 4] = [('d', 86_400), ('h', 3_600), ('m', 60), ('s', 1)]; + let invalid = || { + format!( + "`{arg}` is not an age. Use a whole number of days, hours, minutes or \ + seconds, such as 7d, 12h, 30m or 90s." + ) + }; + let unit = arg.chars().last().ok_or_else(invalid)?; + let (_, scale) = units + .iter() + .find(|(suffix, _)| *suffix == unit) + .ok_or_else(invalid)?; + let count: u64 = arg[..arg.len() - 1].parse().map_err(|_| invalid())?; + let secs = count.checked_mul(*scale).ok_or_else(invalid)?; + Ok(std::time::Duration::from_secs(secs)) +} + // BEP-042: `min box audit | --parent [-o jsonl] [--follow]`. #[derive(Debug, Args)] #[command(group(clap::ArgGroup::new("box_or_parent").required(true).args(["target", "parent"])))] diff --git a/crates/minimal/src/cmd/boxes.rs b/crates/minimal/src/cmd/boxes.rs index c6577827f..25a38631e 100644 --- a/crates/minimal/src/cmd/boxes.rs +++ b/crates/minimal/src/cmd/boxes.rs @@ -34,8 +34,8 @@ pub(crate) use attach::*; pub use create::*; pub(crate) use exec::*; pub(crate) use hooks::*; -pub use lifecycle::BoxRunningRefusal; pub(crate) use lifecycle::*; +pub use lifecycle::{BoxRenameRefusal, BoxRunningRefusal, PruneNeedsYes}; pub use list::*; pub use policy::*; pub use show::*; diff --git a/crates/minimal/src/cmd/boxes/lifecycle.rs b/crates/minimal/src/cmd/boxes/lifecycle.rs index cf0962f51..5e78340c9 100644 --- a/crates/minimal/src/cmd/boxes/lifecycle.rs +++ b/crates/minimal/src/cmd/boxes/lifecycle.rs @@ -1,6 +1,7 @@ //! `min session destroy`, `stop` and `rename`: the box lifecycle helpers. -//! `min box stop` (BOX-013, BCLI-059) and `min box rm` (BOX-019, BCLI-060, -//! BCLI-004) live here too. +//! `min box stop` (BOX-013, BCLI-059), `min box rm` (BOX-019, BCLI-060, +//! BCLI-004), `min box rename` (BOX-010, BCLI-058) and `min box prune` +//! (BOX-021, BCLI-061, BCLI-005) live here too. use super::*; @@ -772,6 +773,300 @@ pub(crate) async fn rm_listed_box( }) } +/// The daemon's refusal of a rename (BOX-010): a running box on the host +/// holds the name, or the name is reserved. The text is the daemon's, and +/// names the holder. `min box rename` ends with exit 2 on it (BCLI-058). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BoxRenameRefusal { + pub(crate) message: String, +} + +impl BoxRenameRefusal { + /// The exit code `min box rename` ends with on this refusal. + pub const EXIT_CODE: u8 = 2; + + /// The lead of the daemon's text when a running box holds the name, as + /// `boxes::box_name::RenameRefusal::HeldByRunning` spells it. + const HELD_LEAD: &'static str = "The running session `"; + + /// The refusal a `RenameSession` error carries, or `None` when the + /// error is any other failure. + fn from_error(error: &str) -> Option { + let reserved = boxes::box_name::RenameRefusal::Reserved.to_string(); + let held = error.starts_with(Self::HELD_LEAD) && error.contains(" holds the name `"); + (held || error == reserved).then(|| Self { + message: error.to_owned(), + }) + } +} + +impl std::fmt::Display for BoxRenameRefusal { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for BoxRenameRefusal {} + +/// `min box rename `: renames the box as BOX-010 defines. +/// `` is a box address, looked up on every local host. +pub async fn cmd_box_rename(global: &GlobalArgs, args: BoxRenameArgs) -> Result<(), anyhow::Error> { + ensure_daemon(global)?; + let hosts = crate::cmd::list::local_hosts(global)?; + let resolved = resolve_box_on_hosts(hosts, &args.target, "box rename").await?; + let mut client = gated_box_host_client(&resolved.host).await?; + // The record says whether the box holds its name in the VM host's zone, + // which the hold then moves to the new name. + let record = get_session_record(&mut client, &resolved.box_id.to_string()) + .await + .ok() + .and_then(|resp| resp.record); + let mut out = std::io::stdout().lock(); + rename_listed_box( + &mut client, + &mut out, + resolved.box_id, + &args.target, + &args.new_name, + ) + .await?; + if let Some(record) = record.filter(holds_name) { + let control_sock = box_host_control_sock(&resolved.host); + release_held_box_name( + control_sock.clone(), + record.id, + record.name.as_deref(), + None, + ) + .await; + hold_box_name_with_vm_host(control_sock, &args.new_name, Some(record.id), true).await; + } + Ok(()) +} + +/// Renames the box `id`, which the address `target` resolved to, to +/// `new_name`, as BOX-010 defines. Writes one line to `out`. The daemon's +/// refusal returns as a [`BoxRenameRefusal`]. +pub(crate) async fn rename_listed_box( + client: &mut client::Client, + out: &mut impl std::io::Write, + id: boxes::SessionId, + target: &str, + new_name: &str, +) -> Result<(), anyhow::Error> { + use minimald_rpc::{Errorable, RenameSession, RenameSessionRequest}; + + crate::output::record_box_id(&id.to_string()); + let answer = client + .oneshot_rpc::(RenameSessionRequest { + id, + new_name: new_name.to_owned(), + }) + .await + .context("RenameSession RPC failed")?; + match answer { + Errorable::Ok(_) => { + tracing::info!(verb = "box rename", box_id = %id, outcome = "renamed"); + writeln!(out, "Renamed {target} to {new_name}.")?; + Ok(()) + } + Errorable::Err { error } => { + tracing::info!(verb = "box rename", box_id = %id, outcome = "refused", "{error}"); + match BoxRenameRefusal::from_error(&error) { + Some(refusal) => Err(refusal.into()), + None => Err(box_rpc_error(target, error)), + } + } + } +} + +/// The refusal of `min box prune` off a terminal without `--yes` +/// (BCLI-005). It ends the command with exit 2. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PruneNeedsYes; + +impl PruneNeedsYes { + /// The exit code `min box prune` ends with on this refusal. + pub const EXIT_CODE: u8 = 2; +} + +impl std::fmt::Display for PruneNeedsYes { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str( + "Prune removes boxes. Pass --yes to confirm, or --dry-run to see what it would remove.", + ) + } +} + +impl std::error::Error for PruneNeedsYes {} + +/// How `min box prune` proceeds past its confirmation gate. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum PruneGate { + /// Prune without asking: `--yes`. + Proceed, + /// Ask on the terminal first, default No. + Confirm, +} + +/// Decides whether `min box prune` prunes, asks, or refuses with +/// [`PruneNeedsYes`]. Off a terminal, or under `--no-input`, nothing can +/// answer the question, so only `--yes` prunes. +pub(crate) fn prune_gate( + yes: bool, + no_input: bool, + stdin_is_terminal: bool, +) -> Result { + match (yes, !no_input && stdin_is_terminal) { + (true, _) => Ok(PruneGate::Proceed), + (false, true) => Ok(PruneGate::Confirm), + (false, false) => Err(PruneNeedsYes), + } +} + +/// The `PruneBoxes` request for `min box prune`: BOX-021's `older-than` +/// selector for `--older-than`, and its `parent` selector for `--parent`, +/// which the caller resolved to the box `parent`. +pub(crate) fn box_prune_request( + older_than: Option, + parent: Option, +) -> minimald_rpc::PruneBoxesRequest { + minimald_rpc::PruneBoxesRequest { + older_than_secs: older_than.map(|age| age.as_secs()), + parent, + } +} + +/// `min box prune [--older-than ] [--parent ] [--yes]`: removes +/// the stopped and exited boxes that match, as BOX-021 defines. With +/// `--parent`, only the host that keeps that box is pruned. Without it, +/// every local host that is running is pruned. +pub async fn cmd_box_prune(global: &GlobalArgs, args: BoxPruneArgs) -> Result<(), anyhow::Error> { + let gate = prune_gate(args.yes, global.no_input, std::io::stdin().is_terminal()) + .inspect_err(|_| tracing::info!(verb = "box prune", outcome = "refused", "no --yes"))?; + if gate == PruneGate::Confirm { + let question = match &args.parent { + Some(parent) => format!("Remove every stopped or exited child box of {parent}?"), + None => "Remove every stopped or exited box?".to_owned(), + }; + if !confirm(&question, false)? { + tracing::info!(verb = "box prune", outcome = "declined"); + println!("Nothing was removed."); + return Ok(()); + } + } + ensure_daemon(global)?; + let hosts = crate::cmd::list::local_hosts(global)?; + let (hosts, parent) = match &args.parent { + Some(parent) => { + let resolved = resolve_box_on_hosts(hosts, parent, "box prune").await?; + (vec![resolved.host], Some(resolved.box_id)) + } + None => (hosts, None), + }; + let request = box_prune_request(args.older_than, parent); + let mut out = std::io::stdout().lock(); + let (mut reaped, mut failed) = (0usize, 0usize); + for host in hosts { + let client = if host.selected || parent.is_some() { + Some(gated_box_host_client(&host).await?) + } else { + match client::Client::probe(&host.sock).await { + Ok(mut client) => { + client::ensure_version_match(&mut client).await?; + Some(client) + } + Err(client::ProbeRefusal::NotRunning) => None, + Err(client::ProbeRefusal::Unreachable(e)) => { + return Err(e.context(format!("Could not reach host {}.", host.host))); + } + } + }; + let Some(mut client) = client else { continue }; + let pruned = prune_host(&mut client, &host, &mut out, request.clone()).await?; + reaped += pruned.0; + failed += pruned.1; + } + tracing::info!(verb = "box prune", reaped, failed, outcome = "pruned"); + if failed > 0 { + bail!( + "Prune could not remove {failed} of {} boxes.", + reaped + failed + ); + } + if reaped == 0 { + writeln!( + out, + "No stopped or exited box matched, so nothing was removed." + )?; + } + Ok(()) +} + +/// Prunes the host `client` serves with `request`, writes one line for each +/// box it removed to `out` and one line for each it did not to stderr, and +/// retires the row or the name hold each removed box leaves on the VM host +/// daemon. Returns how many boxes it removed and how many it did not. +pub(crate) async fn prune_host( + client: &mut client::Client, + host: &crate::cmd::list::LocalHost, + out: &mut impl std::io::Write, + request: minimald_rpc::PruneBoxesRequest, +) -> Result<(usize, usize), anyhow::Error> { + use minimald_rpc::{Errorable, PruneBoxes}; + + // The records of the boxes a prune can remove carry the pair each box's + // registration handed back, which the withdrawal after the prune + // presents. The prune reaps the boxes all the same without them. + let mut addresses = std::collections::HashMap::new(); + if host.provider == crate::cmd::list::LOCAL_MINVMD_PROVIDER { + for entry in list_box_records(client, None).await.unwrap_or_default() { + if entry.state == "stopped" || entry.state == "exited" { + let record = get_session_record(client, &entry.box_id.to_string()) + .await + .ok() + .and_then(|resp| resp.record); + addresses.insert(entry.box_id, record.and_then(|r| r.box_addresses)); + } + } + } + let pruned = match client + .oneshot_rpc::(request) + .await + .context("PruneBoxes RPC failed")? + { + Errorable::Ok(pruned) => pruned, + Errorable::Err { error } => bail!("{error}"), + }; + let control_sock = box_host_control_sock(host); + for entry in &pruned.reaped { + let name = entry.name.as_deref(); + let box_addresses = addresses.get(&entry.box_id).copied().flatten(); + withdraw_box_row(control_sock.clone(), name, box_addresses, None).await; + release_held_box_name(control_sock.clone(), entry.box_id, name, box_addresses).await; + } + write_prune_lines(out, &pruned)?; + Ok((pruned.reaped.len(), pruned.failed.len())) +} + +/// The lines `min box prune` prints for one host's answer `pruned`: one on +/// `out` for each box it removed, and one on stderr for each it did not. +fn write_prune_lines( + out: &mut impl std::io::Write, + pruned: &minimald_rpc::PruneBoxesResponse, +) -> std::io::Result<()> { + for entry in &pruned.reaped { + match &entry.name { + Some(name) => writeln!(out, "Removed {name} ({}).", entry.box_id)?, + None => writeln!(out, "Removed {}.", entry.box_id)?, + } + } + for failure in &pruned.failed { + eprintln!("Could not remove {}: {}", failure.box_id, failure.error); + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -1016,4 +1311,170 @@ mod tests { Some("running") ); } + + // BCLI-058: `min box rename` renames the box as BOX-010 defines. A name + // a running box holds is refused with exit 2, and the refusal names the + // holder. The reserved name `self` is refused too. + #[tokio::test] + async fn box_rename_renames_as_box_010() { + let log = minimald::test_harness::captured_log(); + let (_server, _dir, _project, mut client) = daemon_with_boxes(&["web", "api"]).await; + + let web = listed_id(&mut client, "web").await; + let mut out = Vec::new(); + rename_listed_box(&mut client, &mut out, web, "web", "front") + .await + .expect("the rename succeeds"); + assert_eq!(String::from_utf8(out).unwrap(), "Renamed web to front.\n"); + assert_eq!(listed_state(&mut client, "web").await, None); + assert_eq!(listed_id(&mut client, "front").await, web); + assert!( + log.contents().contains("renamed a box"), + "{}", + log.contents() + ); + + // The running box `front` holds the name, so `api` cannot take it. + let api = listed_id(&mut client, "api").await; + let mut out = Vec::new(); + let err = rename_listed_box(&mut client, &mut out, api, "api", "front") + .await + .expect_err("a held name is refused"); + let refusal = err + .downcast_ref::() + .unwrap_or_else(|| panic!("the refusal is typed: {err:#}")); + assert_eq!(BoxRenameRefusal::EXIT_CODE, 2); + let text = refusal.to_string(); + assert!(text.contains(&web.to_string()), "names the holder: {text}"); + assert!(text.contains("`front`"), "names the holder: {text}"); + assert!(out.is_empty()); + assert_eq!(listed_id(&mut client, "api").await, api); + + // `self` is reserved. + let err = rename_listed_box(&mut client, &mut Vec::new(), api, "api", "self") + .await + .expect_err("`self` is refused"); + assert!(err.downcast_ref::().is_some(), "{err:#}"); + + // Any other daemon error is not the refusal. + assert_eq!( + BoxRenameRefusal::from_error("session is already named `api`"), + None + ); + } + + // BCLI-061: `min box prune` asks for BOX-021's prune, with the + // `older-than` selector for `--older-than` and the `parent` selector for + // `--parent`. A running box is never removed. + #[tokio::test] + async fn box_prune_flags_map_to_box_021_selectors() { + // The flags map to the selectors. + let parent = boxes::SessionId::from_bytes([7; 16]); + let age = crate::cli::parse_box_age("7d").unwrap(); + assert_eq!(age.as_secs(), 7 * 86_400); + assert_eq!( + box_prune_request(Some(age), Some(parent)), + minimald_rpc::PruneBoxesRequest { + older_than_secs: Some(7 * 86_400), + parent: Some(parent), + } + ); + assert_eq!( + box_prune_request(None, None), + minimald_rpc::PruneBoxesRequest::default() + ); + for (arg, secs) in [("12h", 43_200), ("30m", 1_800), ("90s", 90), ("0d", 0)] { + assert_eq!(crate::cli::parse_box_age(arg).unwrap().as_secs(), secs); + } + for bad in ["", "7", "d", "7y", "-1d", "1.5h"] { + let err = crate::cli::parse_box_age(bad).expect_err(bad); + assert!(err.contains("such as 7d, 12h, 30m or 90s"), "{err}"); + } + + let (_server, dir, _project, mut client) = daemon_with_boxes(&["web", "api", "db"]).await; + let host = crate::cmd::list::LocalHost { + provider: crate::cmd::list::LOCAL_PROVIDER, + host: "local0".to_owned(), + sock: dir.path().join("ssh.sock"), + selected: true, + }; + let web = listed_id(&mut client, "web").await; + let api = listed_id(&mut client, "api").await; + for id in [web, api] { + stop_listed_box(&mut client, &mut Vec::new(), id, "box", false) + .await + .expect("the stop succeeds"); + } + + // The boxes stopped just now, so an hour's age matches none. + let mut out = Vec::new(); + let pruned = prune_host( + &mut client, + &host, + &mut out, + box_prune_request(Some(std::time::Duration::from_secs(3_600)), None), + ) + .await + .expect("the prune succeeds"); + assert_eq!(pruned, (0, 0)); + assert!(out.is_empty()); + + // No box is a child of `db`, so its parent selector matches none. + let db = listed_id(&mut client, "db").await; + let pruned = prune_host( + &mut client, + &host, + &mut Vec::new(), + box_prune_request(None, Some(db)), + ) + .await + .expect("the prune succeeds"); + assert_eq!(pruned, (0, 0)); + assert_eq!( + listed_state(&mut client, "web").await.as_deref(), + Some("stopped") + ); + + // With no selector, every stopped box goes, and the running one stays. + let mut out = Vec::new(); + let pruned = prune_host(&mut client, &host, &mut out, box_prune_request(None, None)) + .await + .expect("the prune succeeds"); + assert_eq!(pruned, (2, 0)); + let mut lines: Vec = String::from_utf8(out) + .unwrap() + .lines() + .map(str::to_owned) + .collect(); + lines.sort(); + let mut want = vec![ + format!("Removed api ({api})."), + format!("Removed web ({web})."), + ]; + want.sort(); + assert_eq!(lines, want); + assert_eq!(listed_state(&mut client, "web").await, None); + assert_eq!(listed_state(&mut client, "api").await, None); + assert_eq!( + listed_state(&mut client, "db").await.as_deref(), + Some("running") + ); + } + + // BCLI-005: off a terminal, or under `--no-input`, `min box prune` + // without `--yes` is refused with exit 2, naming `--yes`. On a terminal + // it asks, and `--yes` prunes without asking. + #[test] + fn prune_off_tty_needs_yes() { + assert_eq!(prune_gate(false, false, false), Err(PruneNeedsYes)); + assert_eq!(prune_gate(false, true, true), Err(PruneNeedsYes)); + assert_eq!(prune_gate(false, false, true), Ok(PruneGate::Confirm)); + assert_eq!(prune_gate(true, false, false), Ok(PruneGate::Proceed)); + assert_eq!(prune_gate(true, true, true), Ok(PruneGate::Proceed)); + assert_eq!(PruneNeedsYes::EXIT_CODE, 2); + assert_eq!( + PruneNeedsYes.to_string(), + "Prune removes boxes. Pass --yes to confirm, or --dry-run to see what it would remove." + ); + } } diff --git a/crates/minimal/src/cmd/mod.rs b/crates/minimal/src/cmd/mod.rs index dd7998a01..0ea1c0357 100644 --- a/crates/minimal/src/cmd/mod.rs +++ b/crates/minimal/src/cmd/mod.rs @@ -125,6 +125,8 @@ fn command_verb(command: Option<&Command>) -> &'static str { BoxCommand::Show(_) => "box show", BoxCommand::Stop(_) => "box stop", BoxCommand::Rm(_) => "box rm", + BoxCommand::Rename(_) => "box rename", + BoxCommand::Prune(_) => "box prune", }, Some(Command::Net(_)) => "net forward", Some(Command::FinalizeInstall(_)) => "finalize-install", @@ -360,6 +362,8 @@ pub(crate) async fn run_command(cli: Cli) -> Result<(), anyhow::Error> { BoxCommand::Show(args) => cmd_box_show(&cli.global_args, args).await, BoxCommand::Stop(args) => cmd_box_stop(&cli.global_args, args).await, BoxCommand::Rm(args) => cmd_box_rm(&cli.global_args, args).await, + BoxCommand::Rename(args) => cmd_box_rename(&cli.global_args, args).await, + BoxCommand::Prune(args) => cmd_box_prune(&cli.global_args, args).await, }, Some(Command::Net(NetArgs { command: NetCommand::Forward(args), diff --git a/crates/minimal/src/main.rs b/crates/minimal/src/main.rs index 6a3f12a04..c5ef1839e 100644 --- a/crates/minimal/src/main.rs +++ b/crates/minimal/src/main.rs @@ -235,6 +235,14 @@ fn failure_exit_code(e: &anyhow::Error) -> u8 { if e.downcast_ref::().is_some() { return minimal::BoxRunningRefusal::EXIT_CODE; } + // BCLI-058: `min box rename` to a name BOX-010 refuses. + if e.downcast_ref::().is_some() { + return minimal::BoxRenameRefusal::EXIT_CODE; + } + // BCLI-005: `min box prune` off a terminal without `--yes`. + if e.downcast_ref::().is_some() { + return minimal::PruneNeedsYes::EXIT_CODE; + } // BOX-163: a create under a name a running box holds. if e.downcast_ref::().is_some() { return minimald_rpc::HeldNameRefusal::EXIT_CODE; @@ -1054,6 +1062,22 @@ mod tests { assert_eq!(failure_exit_code(&e), 3); } + /// BCLI-005: `min box prune` off a terminal without `--yes` ends with + /// exit 2, and the text names `--yes`. + #[test] + fn prune_off_tty_needs_yes_exits_2() { + let e = anyhow::Error::new(minimal::PruneNeedsYes); + assert_eq!(failure_exit_code(&e), 2); + let mut stderr = Vec::new(); + let code = answer_failure(&e, false, false, &mut stderr); + assert_eq!(code, ExitCode::from(2)); + assert_eq!( + String::from_utf8(stderr).unwrap(), + "error: Prune removes boxes. Pass --yes to confirm, \ + or --dry-run to see what it would remove.\n" + ); + } + /// BCLI-004: `min box rm` of a running box without `--force` ends with /// exit 2 in both output modes. The text mode prints the refusal, which /// names `--force`, on stderr. From 96e10b1535b96eed1d41d52e8f17244fdd428b7f Mon Sep 17 00:00:00 2001 From: "minimal-foundry[bot]" <327719912+minimal-foundry[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 20:39:09 +0000 Subject: [PATCH 2/5] test(minimal): classify the min box prune daemon connection as gated --- crates/minimal/src/tests.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/minimal/src/tests.rs b/crates/minimal/src/tests.rs index 8cf02a1c8..9d006476d 100644 --- a/crates/minimal/src/tests.rs +++ b/crates/minimal/src/tests.rs @@ -278,6 +278,10 @@ fn every_daemon_connection_is_classified() { // the race's loser just reports what the daemon said — so the // harness connection carries no gate to record. "cmd/boxes/lifecycle.rs::a_destroy_of_an_already_destroyed_session_reports_it = ungated", + // `min box prune` probes each host it did not select and checks + // its build before the prune, so a daemon outside the supported + // window removes nothing. + "cmd/boxes/lifecycle.rs::cmd_box_prune = gated", // Not a product path: the stop and remove tests' own connection // to the harness daemon, the same as the destroy-race test. "cmd/boxes/lifecycle.rs::daemon_with_boxes = ungated", From 669a7be6e8603733ef3d340aa12d521783ee0034 Mon Sep 17 00:00:00 2001 From: "minimal-foundry[bot]" <327719912+minimal-foundry[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:25:16 +0000 Subject: [PATCH 3/5] fix(minimal): name the --older-than age in the min box prune question The terminal question said every stopped or exited box, even when --older-than limits the prune to older boxes. --- crates/minimal/src/cmd/boxes/lifecycle.rs | 46 +++++++++++++++++++++-- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/crates/minimal/src/cmd/boxes/lifecycle.rs b/crates/minimal/src/cmd/boxes/lifecycle.rs index 5e78340c9..bd9b0614c 100644 --- a/crates/minimal/src/cmd/boxes/lifecycle.rs +++ b/crates/minimal/src/cmd/boxes/lifecycle.rs @@ -937,6 +937,30 @@ pub(crate) fn box_prune_request( } } +/// The question `min box prune` asks on a terminal. It names each +/// selector the person passed, so it never claims more than the prune +/// removes. The age prints in the largest whole unit `--older-than` takes. +pub(crate) fn prune_question( + older_than: Option, + parent: Option<&str>, +) -> String { + let what = match parent { + Some(parent) => format!("child box of {parent}"), + None => "box".to_owned(), + }; + match older_than { + Some(age) => { + let secs = age.as_secs(); + let (n, unit) = [(86_400, 'd'), (3_600, 'h'), (60, 'm')] + .into_iter() + .find(|(size, _)| secs > 0 && secs % size == 0) + .map_or((secs, 's'), |(size, unit)| (secs / size, unit)); + format!("Remove every {what} that stopped or exited at least {n}{unit} ago?") + } + None => format!("Remove every stopped or exited {what}?"), + } +} + /// `min box prune [--older-than ] [--parent ] [--yes]`: removes /// the stopped and exited boxes that match, as BOX-021 defines. With /// `--parent`, only the host that keeps that box is pruned. Without it, @@ -945,10 +969,7 @@ pub async fn cmd_box_prune(global: &GlobalArgs, args: BoxPruneArgs) -> Result<() let gate = prune_gate(args.yes, global.no_input, std::io::stdin().is_terminal()) .inspect_err(|_| tracing::info!(verb = "box prune", outcome = "refused", "no --yes"))?; if gate == PruneGate::Confirm { - let question = match &args.parent { - Some(parent) => format!("Remove every stopped or exited child box of {parent}?"), - None => "Remove every stopped or exited box?".to_owned(), - }; + let question = prune_question(args.older_than, args.parent.as_deref()); if !confirm(&question, false)? { tracing::info!(verb = "box prune", outcome = "declined"); println!("Nothing was removed."); @@ -1383,6 +1404,23 @@ mod tests { box_prune_request(None, None), minimald_rpc::PruneBoxesRequest::default() ); + // The terminal question names every selector it was given. + assert_eq!( + prune_question(None, None), + "Remove every stopped or exited box?" + ); + assert_eq!( + prune_question(None, Some("api")), + "Remove every stopped or exited child box of api?" + ); + assert_eq!( + prune_question(Some(age), None), + "Remove every box that stopped or exited at least 7d ago?" + ); + assert_eq!( + prune_question(crate::cli::parse_box_age("90s").ok(), Some("api")), + "Remove every child box of api that stopped or exited at least 90s ago?" + ); for (arg, secs) in [("12h", 43_200), ("30m", 1_800), ("90s", 90), ("0d", 0)] { assert_eq!(crate::cli::parse_box_age(arg).unwrap().as_secs(), secs); } From acfcef13cbe3b5c3760ea9b1e188fb075404b8ea Mon Sep 17 00:00:00 2001 From: "minimal-foundry[bot]" <327719912+minimal-foundry[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:49:50 +0000 Subject: [PATCH 4/5] fix(minimal): prune every host past a failed one in min box prune cmd_box_prune stopped at the first host error, so later hosts were never pruned and the summary was skipped. Collect each host's error, name each failed host on stderr, count it in the summary and exit non-zero. The box count now says "1 box" for one. --- crates/minimal/src/cmd/boxes/lifecycle.rs | 185 +++++++++++++++++++--- crates/minimal/src/tests.rs | 2 +- 2 files changed, 164 insertions(+), 23 deletions(-) diff --git a/crates/minimal/src/cmd/boxes/lifecycle.rs b/crates/minimal/src/cmd/boxes/lifecycle.rs index bd9b0614c..db7cdca55 100644 --- a/crates/minimal/src/cmd/boxes/lifecycle.rs +++ b/crates/minimal/src/cmd/boxes/lifecycle.rs @@ -987,35 +987,107 @@ pub async fn cmd_box_prune(global: &GlobalArgs, args: BoxPruneArgs) -> Result<() }; let request = box_prune_request(args.older_than, parent); let mut out = std::io::stdout().lock(); - let (mut reaped, mut failed) = (0usize, 0usize); + let tally = prune_hosts(hosts, parent.is_some(), request, &mut out).await?; + tracing::info!( + verb = "box prune", + reaped = tally.reaped, + failed = tally.failed, + failed_hosts = tally.failed_hosts.len(), + outcome = "pruned" + ); + finish_prune(&tally, &mut out, &mut std::io::stderr().lock()) +} + +/// What `min box prune` did across its hosts: how many boxes it removed and +/// did not, how many hosts it pruned, and each host it could not prune with +/// the reason. +#[derive(Debug, Default)] +pub(crate) struct PruneTally { + pub reaped: usize, + pub failed: usize, + pub pruned_hosts: usize, + pub failed_hosts: Vec<(String, anyhow::Error)>, +} + +/// Prunes each host in `hosts` with `request`. A host that fails does not +/// stop the prune: its error goes in the tally and the next host is pruned. +/// A host that is not selected is probed first, and one that is not running +/// is skipped. Only a write to `out` that fails ends the walk. +pub(crate) async fn prune_hosts( + hosts: Vec, + by_parent: bool, + request: minimald_rpc::PruneBoxesRequest, + out: &mut impl std::io::Write, +) -> Result { + let mut tally = PruneTally::default(); for host in hosts { - let client = if host.selected || parent.is_some() { - Some(gated_box_host_client(&host).await?) + let client = if host.selected || by_parent { + gated_box_host_client(&host).await.map(Some) } else { match client::Client::probe(&host.sock).await { - Ok(mut client) => { - client::ensure_version_match(&mut client).await?; - Some(client) - } - Err(client::ProbeRefusal::NotRunning) => None, - Err(client::ProbeRefusal::Unreachable(e)) => { - return Err(e.context(format!("Could not reach host {}.", host.host))); - } + Ok(mut client) => client::ensure_version_match(&mut client) + .await + .map(|()| Some(client)), + Err(client::ProbeRefusal::NotRunning) => Ok(None), + Err(client::ProbeRefusal::Unreachable(e)) => Err(e), } }; - let Some(mut client) = client else { continue }; - let pruned = prune_host(&mut client, &host, &mut out, request.clone()).await?; - reaped += pruned.0; - failed += pruned.1; + let pruned = match client { + Ok(None) => continue, + Ok(Some(mut client)) => prune_host(&mut client, &host, out, request.clone()).await, + Err(e) => Err(e), + }; + match pruned { + Ok((reaped, failed)) => { + tally.reaped += reaped; + tally.failed += failed; + tally.pruned_hosts += 1; + } + Err(e) => { + tracing::warn!(verb = "box prune", host = %host.host, error = %format!("{e:#}"), "host prune failed"); + tally.failed_hosts.push((host.host, e)); + } + } } - tracing::info!(verb = "box prune", reaped, failed, outcome = "pruned"); - if failed > 0 { - bail!( - "Prune could not remove {failed} of {} boxes.", - reaped + failed - ); + Ok(tally) +} + +/// Ends `min box prune` from its `tally`: one line on `err` for each host it +/// could not prune, then an error that counts the boxes and the hosts that +/// failed. With no failure and nothing removed, it says so on `out`. +pub(crate) fn finish_prune( + tally: &PruneTally, + out: &mut impl std::io::Write, + err: &mut impl std::io::Write, +) -> Result<(), anyhow::Error> { + for (host, e) in &tally.failed_hosts { + writeln!(err, "Could not prune host {host}: {e:#}")?; + } + let plural = + |n: usize, one: &str, many: &str| format!("{n} {}", if n == 1 { one } else { many }); + let mut summary = Vec::new(); + if tally.failed > 0 { + summary.push(format!( + "Prune could not remove {} of {}.", + tally.failed, + plural(tally.reaped + tally.failed, "box", "boxes") + )); + } + if !tally.failed_hosts.is_empty() { + summary.push(format!( + "Prune failed on {} of {}.", + tally.failed_hosts.len(), + plural( + tally.pruned_hosts + tally.failed_hosts.len(), + "host", + "hosts" + ) + )); + } + if !summary.is_empty() { + bail!("{}", summary.join(" ")); } - if reaped == 0 { + if tally.reaped == 0 { writeln!( out, "No stopped or exited box matched, so nothing was removed." @@ -1499,6 +1571,75 @@ mod tests { ); } + // BCLI-061: a host that `min box prune` cannot prune does not stop the + // prune. The other hosts are still pruned, the failed host is named with + // its reason, and the command ends with an error that counts it. + #[tokio::test] + async fn box_prune_goes_on_past_a_failed_host() { + let (_server, dir, _project, mut client) = daemon_with_boxes(&["web", "db"]).await; + let web = listed_id(&mut client, "web").await; + stop_listed_box(&mut client, &mut Vec::new(), web, "box", false) + .await + .expect("the stop succeeds"); + + // A host whose socket accepts and then closes: its probe fails. + let broken_sock = dir.path().join("broken.sock"); + let listener = tokio::net::UnixListener::bind(&broken_sock).unwrap(); + tokio::spawn(async move { + while let Ok((stream, _)) = listener.accept().await { + drop(stream); + } + }); + let hosts = vec![ + crate::cmd::list::LocalHost { + provider: crate::cmd::list::LOCAL_PROVIDER, + host: "broken0".to_owned(), + sock: broken_sock, + selected: false, + }, + crate::cmd::list::LocalHost { + provider: crate::cmd::list::LOCAL_PROVIDER, + host: "local0".to_owned(), + sock: dir.path().join("ssh.sock"), + selected: true, + }, + ]; + + let mut out = Vec::new(); + let tally = prune_hosts(hosts, false, box_prune_request(None, None), &mut out) + .await + .expect("only a write to out can end the walk"); + assert_eq!((tally.reaped, tally.failed, tally.pruned_hosts), (1, 0, 1)); + assert_eq!(tally.failed_hosts.len(), 1); + assert_eq!(tally.failed_hosts[0].0, "broken0"); + assert_eq!( + String::from_utf8(out.clone()).unwrap(), + format!("Removed web ({web}).\n") + ); + assert_eq!(listed_state(&mut client, "web").await, None); + assert_eq!( + listed_state(&mut client, "db").await.as_deref(), + Some("running") + ); + + let mut err = Vec::new(); + let summary = finish_prune(&tally, &mut out, &mut err).expect_err("a host failed"); + let err = String::from_utf8(err).unwrap(); + assert!(err.starts_with("Could not prune host broken0: "), "{err}"); + assert_eq!(err.lines().count(), 1, "{err}"); + assert_eq!(summary.to_string(), "Prune failed on 1 of 2 hosts."); + + // The box count says "box" for one. + let one_failed = PruneTally { + failed: 1, + pruned_hosts: 1, + ..PruneTally::default() + }; + let summary = + finish_prune(&one_failed, &mut Vec::new(), &mut Vec::new()).expect_err("a box failed"); + assert_eq!(summary.to_string(), "Prune could not remove 1 of 1 box."); + } + // BCLI-005: off a terminal, or under `--no-input`, `min box prune` // without `--yes` is refused with exit 2, naming `--yes`. On a terminal // it asks, and `--yes` prunes without asking. diff --git a/crates/minimal/src/tests.rs b/crates/minimal/src/tests.rs index d1d2d4244..ec97563fc 100644 --- a/crates/minimal/src/tests.rs +++ b/crates/minimal/src/tests.rs @@ -281,10 +281,10 @@ fn every_daemon_connection_is_classified() { // `min box prune` probes each host it did not select and checks // its build before the prune, so a daemon outside the supported // window removes nothing. - "cmd/boxes/lifecycle.rs::cmd_box_prune = gated", // Not a product path: the stop and remove tests' own connection // to the harness daemon, the same as the destroy-race test. "cmd/boxes/lifecycle.rs::daemon_with_boxes = ungated", + "cmd/boxes/lifecycle.rs::prune_hosts = gated", // A read-only lookup around an attach the gated `cmd_attach` // already made: it reads the box's pair before, and asks whether // the session is gone after, to withdraw its row or release a From 84a9a6c3fb2804a85c9b502215d8497631e50f9e Mon Sep 17 00:00:00 2001 From: "minimal-foundry[bot]" <327719912+minimal-foundry[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:28:30 +0000 Subject: [PATCH 5/5] fix(minimal): pass alias_hint to answer_failure in prune test --- crates/minimal/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/minimal/src/main.rs b/crates/minimal/src/main.rs index a8260984f..ea506c42a 100644 --- a/crates/minimal/src/main.rs +++ b/crates/minimal/src/main.rs @@ -1105,7 +1105,7 @@ mod tests { let e = anyhow::Error::new(minimal::PruneNeedsYes); assert_eq!(failure_exit_code(&e), 2); let mut stderr = Vec::new(); - let code = answer_failure(&e, false, false, &mut stderr); + let code = answer_failure(&e, false, false, None, &mut stderr); assert_eq!(code, ExitCode::from(2)); assert_eq!( String::from_utf8(stderr).unwrap(),