Skip to main content

rbnx/cmd/
clean.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2// `rbnx clean` — drop build artifacts.
3//
4//   rbnx clean [-p <pkg>]      remove <pkg>/rbnx-build/. Defaults to the
5//                              package containing the current directory.
6//   rbnx clean -f <manifest>   recursively clean every package the manifest
7//                              references (path: + url: + system/*) plus the
8//                              deploy's rbnx-boot/{logs,state.json}.
9//   rbnx clean -f <m> --cache  also wipe rbnx-boot/cache/ (force re-clone).
10
11use anyhow::{Context, Result};
12use robonix_cli::config::Config;
13use robonix_cli::output;
14use serde_yaml::Value;
15use std::io::{self, BufRead, Write};
16use std::path::{Path, PathBuf};
17
18use super::run_package;
19
20/// Ask the user (y/N) whether to retry the failed paths with `sudo rm -rf`.
21/// Returns Ok(()) if the retry succeeded or the user opted out cleanly.
22/// Returns Err if sudo failed or the user declined and we want to surface
23/// that as a non-zero exit.
24fn prompt_sudo_retry(failed: Vec<(PathBuf, std::io::Error)>) -> Result<()> {
25    if failed.is_empty() {
26        return Ok(());
27    }
28    eprintln!();
29    eprintln!("These paths could not be removed (likely docker-build root-owned files):");
30    for (p, e) in &failed {
31        eprintln!("  ✗ {} : {}", p.display(), e);
32    }
33    eprintln!();
34    eprint!(
35        "Retry with `sudo rm -rf` for the {} path(s) above? [y/N] ",
36        failed.len()
37    );
38    io::stderr().flush().ok();
39    let mut line = String::new();
40    io::stdin().lock().read_line(&mut line)?;
41    let yes = matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes");
42    if !yes {
43        anyhow::bail!(
44            "{} path(s) skipped (run `sudo rm -rf <path>` manually if needed)",
45            failed.len()
46        );
47    }
48    let mut cmd = std::process::Command::new("sudo");
49    cmd.arg("rm").arg("-rf");
50    for (p, _) in &failed {
51        cmd.arg(p);
52    }
53    let status = cmd
54        .status()
55        .context("failed to spawn sudo (is it installed?)")?;
56    if !status.success() {
57        anyhow::bail!("sudo rm exited with {:?}", status.code());
58    }
59    Ok(())
60}
61
62pub async fn execute(
63    config: Config,
64    package: Option<PathBuf>,
65    file: Option<PathBuf>,
66    cache: bool,
67    sessions: bool,
68    llm_metrics: bool,
69) -> Result<()> {
70    let wipe = Wipe {
71        cache,
72        sessions,
73        llm_metrics,
74    };
75    match (package, file) {
76        (Some(_), Some(_)) => {
77            anyhow::bail!("pass one of -p / -f, not both")
78        }
79        (Some(pkg), None) => clean_package(&pkg),
80        (None, Some(f)) => clean_deploy(&config, &f, &wipe),
81        (None, None) => {
82            // Default-mode resolution. cwd-local hints in priority order:
83            //   1. ./robonix_manifest.yaml   → deploy clean (sibling of `rbnx boot -f`)
84            //   2. ./package_manifest.yaml or ancestor → package clean
85            //   3. neither → bail with both options surfaced
86            let cwd = std::env::current_dir().context("get cwd")?;
87            let deploy = cwd.join("robonix_manifest.yaml");
88            if deploy.is_file() {
89                return clean_deploy(&config, &deploy, &wipe);
90            }
91            match run_package::find_package_from_cwd() {
92                Ok(pkg) => clean_package(&pkg),
93                Err(_) => anyhow::bail!(
94                    "no robonix_manifest.yaml in {} and no package_manifest.yaml in any parent. \
95                     Pass `-f <manifest>` (deploy) or `-p <pkg>` (package).",
96                    cwd.display()
97                ),
98            }
99        }
100    }
101}
102
103fn clean_package(pkg: &Path) -> Result<()> {
104    let pkg = pkg
105        .canonicalize()
106        .with_context(|| format!("not a directory: {}", pkg.display()))?;
107    let build = pkg.join("rbnx-build");
108    if !build.exists() {
109        output::sub_step(&format!(
110            "nothing to clean: {} (no rbnx-build/)",
111            pkg.display()
112        ));
113        return Ok(());
114    }
115    output::action("Cleaning", &build.display().to_string());
116    if let Err(e) = std::fs::remove_dir_all(&build) {
117        // Common case: docker-build left root-owned files. Ask the user
118        // whether to retry with sudo rather than bailing or silently
119        // running sudo on their behalf.
120        return prompt_sudo_retry(vec![(build, e)]);
121    }
122    Ok(())
123}
124
125/// Which kept `rbnx-boot/` subdirectories `rbnx clean -f` also removes.
126struct Wipe {
127    /// `--cache`: url-fetched package clones.
128    cache: bool,
129    /// `--sessions`: Pilot session transcripts.
130    sessions: bool,
131    /// `--llm-metrics`: per-request model usage records.
132    llm_metrics: bool,
133}
134
135fn clean_deploy(config: &Config, manifest_path: &Path, wipe: &Wipe) -> Result<()> {
136    let manifest_path = manifest_path
137        .canonicalize()
138        .with_context(|| format!("manifest not found: {}", manifest_path.display()))?;
139    let manifest_dir = manifest_path
140        .parent()
141        .context("deploy manifest has no parent directory")?
142        .to_path_buf();
143    let raw = std::fs::read_to_string(&manifest_path)
144        .with_context(|| format!("read {}", manifest_path.display()))?;
145    let root: Value =
146        serde_yaml::from_str(&raw).with_context(|| format!("parse {}", manifest_path.display()))?;
147    let cache_root = manifest_dir.join("rbnx-boot").join("cache");
148
149    output::action("Cleaning deploy", &manifest_path.display().to_string());
150
151    // Collect every package directory referenced by the manifest.
152    let mut pkgs: Vec<PathBuf> = Vec::new();
153    for section in &["primitive", "service", "skill"] {
154        let Some(seq) = root.get(*section).and_then(|v| v.as_sequence()) else {
155            continue;
156        };
157        for entry in seq {
158            let local = entry.get("path").and_then(|v| v.as_str());
159            let url = entry.get("url").and_then(|v| v.as_str());
160            match (local, url) {
161                (Some(p), _) => pkgs.push(manifest_dir.join(p)),
162                // Cache dir = git repo name (one clone per repo), not the
163                // per-instance provider id. See deploy::repo_dir_name.
164                (None, Some(u)) => pkgs.push(cache_root.join(super::deploy::repo_dir_name(u))),
165                _ => {}
166            }
167        }
168    }
169    // system: section — non-builtin entries are real packages under
170    // `<robonix_source>/system/<key>/` (memory/scene/speech/…).
171    if let Some(map) = root.get("system").and_then(|v| v.as_mapping())
172        && let Some(source_root) = config.robonix_source_path.as_ref()
173    {
174        for (key, _) in map {
175            let Some(k) = key.as_str() else { continue };
176            if super::deploy::is_builtin_system(k) {
177                continue;
178            }
179            let pkg = source_root.join("system").join(k);
180            if pkg.exists() {
181                pkgs.push(pkg);
182            }
183        }
184    }
185
186    // Per-package cleanup. Tolerate per-package failures (docker-build
187    // packages often leave root-owned rbnx-build/ that requires sudo).
188    output::step("packages", &format!("{} to inspect", pkgs.len()));
189    let mut failed: Vec<(PathBuf, std::io::Error)> = Vec::new();
190    for p in &pkgs {
191        if !p.exists() {
192            continue;
193        }
194        let build = p.join("rbnx-build");
195        if build.exists() {
196            output::sub_step(&format!("rm -rf {}", build.display()));
197            if let Err(e) = std::fs::remove_dir_all(&build) {
198                failed.push((build, e));
199            }
200        }
201    }
202
203    // Deploy-level cleanup. Walk every entry under <manifest>/rbnx-boot/
204    // and remove it. Skip cache/ unless `--cache` was given (re-cloning
205    // url-fetched packages is expensive), sessions/ unless `--sessions` was
206    // given (it holds the transcripts that restore Pilot sessions), and
207    // llm-metrics/ unless `--llm-metrics` was given (usage records a bill is
208    // computed from).
209    let rbnx_boot = manifest_dir.join("rbnx-boot");
210    if rbnx_boot.exists() {
211        if let Ok(entries) = std::fs::read_dir(&rbnx_boot) {
212            for entry in entries.flatten() {
213                let path = entry.path();
214                let name = entry.file_name();
215                let is_cache = name == "cache";
216                if is_cache && !wipe.cache {
217                    output::sub_step(&format!("keep {} (use --cache to wipe)", path.display()));
218                    continue;
219                }
220                if name == "sessions" && !wipe.sessions {
221                    output::sub_step(&format!("keep {} (use --sessions to wipe)", path.display()));
222                    continue;
223                }
224                if name == "llm-metrics" && !wipe.llm_metrics {
225                    output::sub_step(&format!(
226                        "keep {} (use --llm-metrics to wipe)",
227                        path.display()
228                    ));
229                    continue;
230                }
231                let label = if is_cache { " (cache)" } else { "" };
232                let kind = entry.file_type().ok();
233                if kind.map(|k| k.is_dir()).unwrap_or(false) {
234                    output::sub_step(&format!("rm -rf {}{}", path.display(), label));
235                    if let Err(e) = std::fs::remove_dir_all(&path) {
236                        failed.push((path, e));
237                    }
238                } else {
239                    output::sub_step(&format!("rm {}{}", path.display(), label));
240                    if let Err(e) = std::fs::remove_file(&path) {
241                        failed.push((path, e));
242                    }
243                }
244            }
245        }
246        // If rbnx-boot/ is empty (or only the kept subdirectories remain),
247        // try to rmdir it too. Best-effort — no failure surface.
248        let _ = std::fs::remove_dir(&rbnx_boot);
249    }
250
251    prompt_sudo_retry(failed)
252}
浙ICP备2023005800号-2 浙公网安备33010902005384号