Skip to main content

rbnx/cmd/
run_package.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2// Run package commands: build, start (start blocks until process exits).
3//
4// Dev-packaging contract: one package has ONE top-level `start` shell body
5// (not a list of nodes). `rbnx start` just executes that body at the
6// package root — the body itself is responsible for spawning processes
7// and registering capabilities with atlas. No node-id flag.
8
9use super::build;
10use anyhow::{Context, Result};
11use robonix_atlas::client::AtlasClient;
12use robonix_atlas::pb as atlas_pb;
13use robonix_cli::Config;
14use robonix_cli::launch::{
15    CMD_ACTIVATE, CMD_INIT, ProviderRegistrationSnapshot, call_driver_cmd,
16    resolve_runtime_driver_contract, snapshot_provider_ids, wait_for_registration_core,
17};
18use robonix_cli::manifest;
19use robonix_cli::output;
20use robonix_cli::process::ProcessManager;
21use std::path::{Path, PathBuf};
22use std::sync::Arc;
23use std::time::Duration;
24
25/// Directory against which relative `-p` is resolved: **the pwd of the command invocation**.
26/// When `cargo run` runs from `robonix/rust`, the process cwd is not the user's shell cwd — wrappers
27/// should `export RBNX_INVOCATION_CWD="$(pwd)"` before `cd`+`cargo run`. If unset, `std::env::current_dir()` is used.
28pub(crate) const RBNX_INVOCATION_CWD: &str = "RBNX_INVOCATION_CWD";
29
30/// Return the migration warning emitted by `rbnx start` for a non-shared
31/// Driver declaration. Runtime registration later proves whether it is the
32/// provider's exact namespace legacy contract before accepting it.
33///
34/// The warning lives in `rbnx`, rather than in a language SDK, so native and
35/// non-Python providers receive the same guidance. Legacy contracts remain
36/// exact namespace legacy contracts remain supported; the warning only
37/// describes the incremental migration.
38fn lifecycle_driver_migration_warning(
39    package_name: &str,
40    explicit_driver_contract: Option<&str>,
41) -> Option<String> {
42    let Some(driver_contract) = explicit_driver_contract else {
43        // Omission is the canonical author-facing form: current codegen and
44        // the SDK automatically provide the shared lifecycle Driver.
45        return None;
46    };
47    if driver_contract == manifest::SHARED_LIFECYCLE_DRIVER_CONTRACT {
48        return None;
49    }
50    Some(format!(
51        "package '{package_name}' declares non-shared lifecycle contract \
52         '{driver_contract}'; only the exact <provider namespace>/driver form \
53         is backward-compatible and may use a shared runtime Driver. Remove the \
54         legacy declaration to select '{}' automatically; do not declare both",
55        manifest::SHARED_LIFECYCLE_DRIVER_CONTRACT,
56    ))
57}
58
59/// POSIX-shell single-quoted escape, used when we synthesise `export FOO=...`
60/// fragments to inject into a package's `start` body.
61fn shell_escape(value: &str) -> String {
62    format!("'{}'", value.replace('\'', "'\"'\"'"))
63}
64
65fn path_base_for_dash_p() -> Result<PathBuf> {
66    if let Ok(s) = std::env::var(RBNX_INVOCATION_CWD) {
67        Ok(PathBuf::from(s))
68    } else {
69        std::env::current_dir().context("Failed to get current directory")
70    }
71}
72
73/// Resolve `-p` to a filesystem path before `canonicalize`: relative paths and `.` use
74/// [`path_base_for_dash_p`] as the prefix (invocation pwd, or process cwd).
75pub(crate) fn resolve_local_path_for_filesystem(p: &Path) -> Result<PathBuf> {
76    if p.as_os_str() == "." || p.as_os_str() == "./" {
77        return path_base_for_dash_p();
78    }
79    if p.is_absolute() {
80        return Ok(p.to_path_buf());
81    }
82    Ok(path_base_for_dash_p()?.join(p))
83}
84
85/// Walk up from the invocation cwd looking for a directory that contains
86/// a `package_manifest.yaml`. Returns the first match.
87pub(crate) fn find_package_from_cwd() -> Result<PathBuf> {
88    let start = path_base_for_dash_p()?;
89    let mut cur: Option<&Path> = Some(&start);
90    while let Some(d) = cur {
91        if d.join(manifest::MANIFEST_FILE).is_file() {
92            return d
93                .canonicalize()
94                .with_context(|| format!("Failed to canonicalize: {}", d.display()));
95        }
96        cur = d.parent();
97    }
98    anyhow::bail!(
99        "no {} found in {} or any parent; pass -p <path> or `cd` into a package directory",
100        manifest::MANIFEST_FILE,
101        start.display()
102    )
103}
104
105/// Resolve package path from -p (local path) or -g (system-installed name).
106/// When neither is given, walk up from cwd to find a package manifest.
107fn resolve_package_path(
108    config: &Config,
109    path: Option<PathBuf>,
110    global: Option<String>,
111) -> Result<PathBuf> {
112    if let Some(p) = path {
113        let p = resolve_local_path_for_filesystem(&p)?;
114        let canonical = p
115            .canonicalize()
116            .with_context(|| format!("Failed to canonicalize: {}", p.display()))?;
117        if canonical.join(manifest::MANIFEST_FILE).exists() {
118            return Ok(canonical);
119        }
120        anyhow::bail!(
121            "Path {} does not contain {}",
122            canonical.display(),
123            manifest::MANIFEST_FILE
124        );
125    }
126
127    if let Some(name) = global {
128        let db = robonix_cli::PackageDatabase::load(&config.package_storage_path)?;
129        if let Some(pkg) = db.get_package(&name) {
130            return Ok(pkg.path.clone());
131        }
132        anyhow::bail!(
133            "Package '{}' not found in system storage ({})",
134            name,
135            config.package_storage_path.display()
136        );
137    }
138
139    find_package_from_cwd()
140}
141
142/// Resolve package path for `start`: same `-p` rules as `build`, then system-installed name fallback.
143fn resolve_package_path_for_start(config: &Config, spec: &str) -> Result<PathBuf> {
144    let path = resolve_local_path_for_filesystem(Path::new(spec))?;
145    if path.join(manifest::MANIFEST_FILE).is_file()
146        || path.join(manifest::LEGACY_MANIFEST_FILE).is_file()
147    {
148        return path
149            .canonicalize()
150            .with_context(|| format!("Failed to canonicalize: {}", path.display()));
151    }
152
153    let db = robonix_cli::PackageDatabase::load(&config.package_storage_path)?;
154    if let Some(pkg) = db.get_package(spec) {
155        return Ok(pkg.path.clone());
156    }
157
158    anyhow::bail!(
159        "Package '{}' not found at {} (relative -p uses {} or process cwd). Try -g <installed name> or export {}=\"$(pwd)\" before cargo run.",
160        spec,
161        path.display(),
162        RBNX_INVOCATION_CWD,
163        RBNX_INVOCATION_CWD
164    )
165}
166
167pub async fn execute_build(
168    config: Config,
169    file: Option<PathBuf>,
170    path: Option<PathBuf>,
171    global: Option<String>,
172    clean: bool,
173    no_update_check: bool,
174) -> Result<()> {
175    if let Some(file) = file {
176        let manifest_path = resolve_local_path_for_filesystem(&file)?;
177        if !manifest_path.is_file() {
178            anyhow::bail!("deployment manifest not found: {}", manifest_path.display());
179        }
180        return build_deploy_manifest(&manifest_path, &config, clean, no_update_check);
181    }
182
183    // Deploy-manifest mode: if `path` (or cwd, when -p is omitted)
184    // contains a `robonix_manifest.yaml`, build every primitive /
185    // service / skill entry it lists. This lets the user run
186    //   `cd examples/webots && rbnx build`
187    // and get all packages built in one shot rather than chasing
188    // each package directory by hand. The corresponding lookup for
189    // `package_manifest.yaml` (single-package mode) stays as the
190    // fallback below.
191    let candidate_dir = match &path {
192        Some(p) => Some(p.clone()),
193        None => std::env::current_dir().ok(),
194    };
195    if let Some(dir) = candidate_dir {
196        let deploy_manifest = dir.join("robonix_manifest.yaml");
197        if deploy_manifest.is_file() {
198            return build_deploy_manifest(&deploy_manifest, &config, clean, no_update_check);
199        }
200    }
201    let package_root = resolve_package_path(&config, path, global)?;
202    build::execute_local(package_root, clean).await
203}
204
205/// URLs to try for a repository: for GitHub, the `RBNX_GH_MIRROR` prefix
206/// first (default `https://ghfast.top/`, empty to disable), then the URL itself.
207pub(super) fn url_candidates(url: &str) -> Vec<String> {
208    let mirror = std::env::var("RBNX_GH_MIRROR").unwrap_or_else(|_| "https://ghfast.top/".into());
209    let mut urls = Vec::new();
210    if !mirror.is_empty() && url.starts_with("https://github.com/") {
211        urls.push(format!("{}/{url}", mirror.trim_end_matches('/')));
212    }
213    urls.push(url.to_string());
214    urls
215}
216
217/// Build every package referenced by a top-level `robonix_manifest.yaml`.
218/// Two phases:
219///   1. **fetch** — `path:` entries already on disk; `url:` entries
220///      get `git clone --depth 1` into `rbnx-boot/cache/<name>/`
221///      (idempotent — skipped when the cache dir already exists).
222///   2. **build** — for each resolved package, run its `build.sh`.
223///
224/// `rbnx boot` deliberately does NOT do either; it just verifies
225/// both phases happened (warns + remediates if not). This lets
226/// "fetch → build" be a controlled offline step the user can run
227/// when they have network / time, then `rbnx boot` is a fast,
228/// online-optional bring-up.
229/// `git clone --depth 1` with bounded retries.
230///
231/// Clones the repo into `dest`, retrying transient failures. Between attempts
232/// it removes any partial checkout git left behind, because git refuses to
233/// clone into a non-empty directory and a half-written tree would otherwise
234/// turn one flaky network moment into a permanent failure.
235///
236/// Retries exist because a deployment build clones several remotes over
237/// several minutes, and any one of them dying takes the whole build with it.
238/// On a runner whose only route to GitHub is a proxy that drops for stretches
239/// at a time, a single `GnuTLS, handshake failed` mid-build was enough to fail
240/// a run whose next attempt seconds later would have succeeded.
241///
242/// The last attempt's exit status is what the error reports. Returns `Err`
243/// only after every attempt has failed, or if git could not be spawned at all
244/// — a missing git binary is not transient, so that is not retried.
245pub(super) fn git_clone_with_retry(
246    url: &str,
247    branch: Option<&str>,
248    dest: &std::path::Path,
249) -> Result<()> {
250    const ATTEMPTS: u32 = 3;
251    const BACKOFF: std::time::Duration = std::time::Duration::from_secs(5);
252
253    let mut last_code: Option<i32> = None;
254    let mut tried = false;
255    for attempt in 1..=ATTEMPTS {
256        for source in url_candidates(url) {
257            // Only remove what an earlier try of this call left; callers
258            // guarantee `dest` is absent to begin with.
259            if tried {
260                let _ = std::fs::remove_dir_all(dest);
261            }
262            tried = true;
263            let mut clone = std::process::Command::new("git");
264            clone.arg("clone").arg("--depth").arg("1");
265            if let Some(b) = branch {
266                clone.arg("--branch").arg(b);
267            }
268            clone.arg(&source).arg(dest);
269            let status = clone
270                .status()
271                .with_context(|| format!("git clone {source} failed to spawn"))?;
272            if status.success() {
273                // A mirror is only the transport; the checkout records the real origin.
274                if source != url {
275                    let set = std::process::Command::new("git")
276                        .arg("-C")
277                        .arg(dest)
278                        .args(["remote", "set-url", "origin", url])
279                        .status()
280                        .with_context(|| format!("git remote set-url in {}", dest.display()))?;
281                    anyhow::ensure!(
282                        set.success(),
283                        "git remote set-url in {}: {set}",
284                        dest.display()
285                    );
286                }
287                return Ok(());
288            }
289            last_code = status.code();
290        }
291        if attempt < ATTEMPTS {
292            output::warning(&format!(
293                "git clone {url} failed (attempt {attempt}/{ATTEMPTS}); \
294                 retrying in {}s",
295                BACKOFF.as_secs()
296            ));
297            std::thread::sleep(BACKOFF);
298        }
299    }
300    anyhow::bail!("git clone {url} exited with {last_code:?} after {ATTEMPTS} attempts")
301}
302
303fn build_deploy_manifest(
304    manifest_path: &Path,
305    config: &Config,
306    clean: bool,
307    no_update_check: bool,
308) -> Result<()> {
309    use serde_yaml::Value;
310    let manifest_dir = manifest_path
311        .parent()
312        .context("deploy manifest has no parent directory")?
313        .to_path_buf();
314    let raw = std::fs::read_to_string(manifest_path)
315        .with_context(|| format!("read {}", manifest_path.display()))?;
316    let root: Value =
317        serde_yaml::from_str(&raw).with_context(|| format!("parse {}", manifest_path.display()))?;
318    let root = super::deploy::prepare_manifest(root, config.robonix_source_path.as_deref())
319        .with_context(|| format!("prepare {}", manifest_path.display()))?;
320    let cache_root = manifest_dir.join("rbnx-boot").join("cache");
321
322    output::action(
323        "Building",
324        &format!("packages declared in {}", manifest_path.display()),
325    );
326    // Notice (non-fatal) if any cloned remote provider is behind upstream.
327    if !no_update_check {
328        super::check_remotes::report_outdated(manifest_path);
329    }
330
331    // Collect (section, name, pkg_dir, url_to_clone) for every entry.
332    struct Resolved {
333        section: &'static str,
334        name: String,
335        pkg_dir: PathBuf,
336        url_to_clone: Option<(String, Option<String>)>, // (url, branch)
337        // Deploy `manifest:` override — selects a per-target package
338        // manifest variant (e.g. package_manifest.jetson-native.yaml) so
339        // the right build path runs. None = default package_manifest.yaml.
340        manifest_override: Option<String>,
341    }
342    let mut entries: Vec<Resolved> = Vec::new();
343    for section in &["primitive", "service", "skill"] {
344        let Some(seq) = root.get(*section).and_then(|v| v.as_sequence()) else {
345            continue;
346        };
347        for entry in seq {
348            let name = entry
349                .get("name")
350                .and_then(|v| v.as_str())
351                .unwrap_or("(unnamed)")
352                .to_string();
353            let local_path = entry.get("path").and_then(|v| v.as_str());
354            let url = entry.get("url").and_then(|v| v.as_str());
355            let branch = entry
356                .get("branch")
357                .and_then(|v| v.as_str())
358                .map(String::from);
359            let manifest_override = entry
360                .get("manifest")
361                .and_then(|v| v.as_str())
362                .map(String::from);
363            match (local_path, url) {
364                (Some(p), _) => entries.push(Resolved {
365                    section,
366                    name,
367                    pkg_dir: manifest_dir.join(p),
368                    url_to_clone: None,
369                    manifest_override,
370                }),
371                (None, Some(u)) => entries.push(Resolved {
372                    section,
373                    name: name.clone(),
374                    // Cache dir = git repo name (one clone per repo), not the
375                    // per-instance provider id. See deploy::repo_dir_name.
376                    pkg_dir: cache_root.join(super::deploy::repo_dir_name(u)),
377                    url_to_clone: Some((u.to_string(), branch)),
378                    manifest_override,
379                }),
380                (None, None) => {
381                    output::warning(&format!(
382                        "skipping {section}/{name}: entry has neither `path` nor `url`"
383                    ));
384                }
385            }
386        }
387    }
388    // `system:` non-builtin entries are real packages too (memory / scene
389    // / speech / …), they just live under `<robonix_source>/system/<key>/`
390    // instead of being declared with an explicit `path:` / `url:`. The
391    // builtin Rust binaries (atlas / chronos / executor / pilot / liaison / soma / vitals) are
392    // shipped via `cargo install` and skipped here.
393    if let Some(map) = root.get("system").and_then(|v| v.as_mapping()) {
394        let source_root = config.robonix_source_path.as_ref();
395        for (key, value) in map {
396            let Some(key_str) = key.as_str() else {
397                continue;
398            };
399            if super::deploy::is_builtin_system(key_str) {
400                continue;
401            }
402            let Some(source_root) = source_root else {
403                output::warning(&format!(
404                    "skipping system/{key_str}: robonix_source_path unset \
405                     (run `rbnx setup` from the repo root once)"
406                ));
407                continue;
408            };
409            let pkg_dir = source_root.join("system").join(key_str);
410            if !pkg_dir.exists() {
411                output::warning(&format!(
412                    "skipping system/{key_str}: not on disk at {}",
413                    pkg_dir.display()
414                ));
415                continue;
416            }
417            let (manifest_override, _runtime_config) = manifest::split_system_package_config(value)
418                .with_context(|| format!("parse system/{key_str} package selector"))?;
419            entries.push(Resolved {
420                section: "system",
421                name: key_str.to_string(),
422                pkg_dir,
423                url_to_clone: None,
424                manifest_override,
425            });
426        }
427    }
428
429    // Phase 1: fetch. git clone url-remote pkgs into cache.
430    let to_clone: Vec<&Resolved> = entries
431        .iter()
432        .filter(|e| e.url_to_clone.is_some() && !e.pkg_dir.exists())
433        .collect();
434    if !to_clone.is_empty() {
435        output::step("fetch", &format!("{} package(s)", to_clone.len()));
436        std::fs::create_dir_all(&cache_root)?;
437        for r in &to_clone {
438            let (url, branch) = r.url_to_clone.as_ref().unwrap();
439            output::sub_step(&format!("git clone {url} -> {}", r.pkg_dir.display()));
440            git_clone_with_retry(url, branch.as_deref(), &r.pkg_dir)?;
441        }
442    }
443
444    // Phase 2: build. Run build.sh for each resolved pkg.
445    struct Row {
446        section: &'static str,
447        name: String,
448        pkg_name: String, // reverse-domain `package.name` from package_manifest.yaml
449        version: String,
450        location: String, // path relative to manifest_dir, or absolute when outside
451        source: Option<(String, Option<String>)>, // (git url, branch) for url-fetched
452    }
453    let mut built: Vec<Row> = Vec::new();
454    let mut skipped: Vec<(&'static str, String, String)> = Vec::new(); // (section, name, reason)
455    let mut failed: Vec<(&'static str, String, anyhow::Error)> = Vec::new();
456
457    fn read_pkg_meta(pkg_dir: &Path) -> (String, String) {
458        // Best-effort: parse package.name + package.version from manifest.
459        let manifest = pkg_dir.join("package_manifest.yaml");
460        let raw = match std::fs::read_to_string(&manifest) {
461            Ok(s) => s,
462            Err(_) => return (String::new(), String::new()),
463        };
464        let v: serde_yaml::Value = match serde_yaml::from_str(&raw) {
465            Ok(v) => v,
466            Err(_) => return (String::new(), String::new()),
467        };
468        let pkg = v.get("package");
469        let name = pkg
470            .and_then(|p| p.get("name").and_then(|n| n.as_str()))
471            .unwrap_or("")
472            .to_string();
473        let ver = pkg
474            .and_then(|p| p.get("version").and_then(|n| n.as_str()))
475            .unwrap_or("")
476            .to_string();
477        (name, ver)
478    }
479
480    fn rel_to(_base: &Path, p: &Path) -> String {
481        // Always show absolute (realpath) so the user can copy-paste straight
482        // into a shell. The pkg_dir we get is already canonicalize()'d below.
483        p.display().to_string()
484    }
485
486    for r in &entries {
487        if !r.pkg_dir.join("package_manifest.yaml").is_file() {
488            let reason = format!("no package_manifest.yaml at {}", r.pkg_dir.display());
489            output::warning(&format!("skipping {}/{}: {}", r.section, r.name, reason));
490            skipped.push((r.section, r.name.clone(), reason));
491            continue;
492        }
493        let canon = r
494            .pkg_dir
495            .canonicalize()
496            .with_context(|| format!("canonicalize {}", r.pkg_dir.display()))?;
497        output::step(r.section, &r.name);
498        let (pkg_name, version) = read_pkg_meta(&canon);
499        let location = rel_to(&manifest_dir, &canon);
500        match build::build_local_package(&canon, clean, r.manifest_override.as_deref()) {
501            Ok(()) => built.push(Row {
502                section: r.section,
503                name: r.name.clone(),
504                pkg_name,
505                version,
506                location,
507                source: r.url_to_clone.clone(),
508            }),
509            Err(e) => failed.push((r.section, r.name.clone(), e)),
510        }
511    }
512
513    // ── Summary ─────────────────────────────────────────────────────────────
514    let manifest_label = manifest_path
515        .file_name()
516        .and_then(|n| n.to_str())
517        .unwrap_or("manifest");
518    let term_w = crossterm::terminal::size()
519        .map(|(c, _)| c as usize)
520        .unwrap_or(120);
521
522    fn center_title(width: usize, title: &str) -> String {
523        let t = format!(" {title} ");
524        if width <= t.len() {
525            return "═".repeat(width);
526        }
527        let left = (width - t.len()) / 2;
528        let right = width - t.len() - left;
529        format!("{}{t}{}", "═".repeat(left), "═".repeat(right))
530    }
531
532    let h_status = "";
533    let h_sec = "section";
534    let h_name = "name";
535    let h_pkg = "package.name";
536    let h_ver = "version";
537    let h_loc = "location";
538    let w_status = 1;
539    let w_sec = built
540        .iter()
541        .map(|r| r.section.len())
542        .max()
543        .unwrap_or(0)
544        .max(h_sec.len());
545    let w_name = built
546        .iter()
547        .map(|r| r.name.len())
548        .max()
549        .unwrap_or(0)
550        .max(h_name.len());
551    let w_pkg = built
552        .iter()
553        .map(|r| r.pkg_name.len())
554        .max()
555        .unwrap_or(0)
556        .max(h_pkg.len());
557    let w_ver = built
558        .iter()
559        .map(|r| r.version.len())
560        .max()
561        .unwrap_or(0)
562        .max(h_ver.len());
563    // Location: take its natural width so realpaths don't get truncated. The
564    // table simply ends up wider than the terminal — better that the user can
565    // copy-paste a full path than read a half-truncated one.
566    let nat_loc = built
567        .iter()
568        .map(|r| r.location.len())
569        .max()
570        .unwrap_or(0)
571        .max(h_loc.len());
572    let w_loc = nat_loc;
573    let table_w = if built.is_empty() {
574        term_w
575    } else {
576        2 + w_status + 2 + w_sec + 2 + w_name + 2 + w_pkg + 2 + w_ver + 2 + w_loc
577    };
578    let bar_w = table_w.max(term_w);
579    let bar = "═".repeat(bar_w);
580
581    println!();
582    println!("{}", center_title(bar_w, "Build summary"));
583    println!("  Manifest: {}", manifest_path.display());
584    println!(
585        "  Built: {}   Fetched: {}   Skipped: {}   Failed: {}   Total: {}",
586        built.len(),
587        to_clone.len(),
588        skipped.len(),
589        failed.len(),
590        entries.len()
591    );
592
593    if !built.is_empty() {
594        println!();
595        println!(
596            "  {:<ws$}  {:<wsec$}  {:<wn$}  {:<wp$}  {:<wv$}  {:<wl$}",
597            h_status,
598            h_sec,
599            h_name,
600            h_pkg,
601            h_ver,
602            h_loc,
603            ws = w_status,
604            wsec = w_sec,
605            wn = w_name,
606            wp = w_pkg,
607            wv = w_ver,
608            wl = w_loc,
609        );
610        let rule = |w: usize| "─".repeat(w);
611        println!(
612            "  {}  {}  {}  {}  {}  {}",
613            rule(w_status),
614            rule(w_sec),
615            rule(w_name),
616            rule(w_pkg),
617            rule(w_ver),
618            rule(w_loc),
619        );
620        let cont_indent = 2 + w_status + 2 + w_sec + 2 + w_name + 2 + w_pkg + 2 + w_ver + 2;
621        for r in &built {
622            println!(
623                "  {:<ws$}  {:<wsec$}  {:<wn$}  {:<wp$}  {:<wv$}  {}",
624                "✓",
625                r.section,
626                r.name,
627                r.pkg_name,
628                r.version,
629                r.location,
630                ws = w_status,
631                wsec = w_sec,
632                wn = w_name,
633                wp = w_pkg,
634                wv = w_ver,
635            );
636            if let Some((url, branch)) = &r.source {
637                let suffix = match branch {
638                    Some(b) => format!("↳ {url} (branch={b})"),
639                    None => format!("↳ {url}"),
640                };
641                println!("{}{suffix}", " ".repeat(cont_indent));
642            }
643        }
644    }
645    if !skipped.is_empty() {
646        println!();
647        for (section, name, reason) in &skipped {
648            println!("  - {section}/{name}: {reason}");
649        }
650    }
651    if !failed.is_empty() {
652        println!();
653        for (section, name, e) in &failed {
654            println!("  ✗ {section}/{name}: {e:#}");
655        }
656    }
657    println!("{bar}");
658
659    if !failed.is_empty() {
660        anyhow::bail!(
661            "{} package(s) failed to build from {manifest_label}",
662            failed.len()
663        );
664    }
665    Ok(())
666}
667
668pub async fn execute_start(
669    config: &Config,
670    spec: Option<&str>,
671    registry_endpoint: Option<&str>,
672    config_file: Option<&Path>,
673    set_overrides: &[String],
674    manifest_override: Option<&str>,
675) -> Result<()> {
676    let package_root = match spec {
677        Some(s) => resolve_package_path_for_start(config, s)?,
678        None => find_package_from_cwd()?,
679    };
680    let detected = manifest::detect_and_load(&package_root, manifest_override)?;
681    let manifest = &detected.manifest;
682    manifest.validate_and_summarize()?;
683
684    let endpoint = registry_endpoint
685        .map(String::from)
686        .unwrap_or_else(|| "127.0.0.1:50051".to_string());
687
688    // Materialize per-instance config from --config + --set overrides
689    // entirely in memory. The provider process never sees the file — config
690    // is delivered via Driver(CMD_INIT, config_json) only (post-spawn
691    // task below). Empty inputs still deliver Driver(CMD_INIT, "{}") so a
692    // standalone `rbnx start` follows the same lifecycle as `rbnx boot`.
693    let has_explicit_config = config_file.is_some() || !set_overrides.is_empty();
694    // Omission is the canonical shared selection. Only one explicit legacy
695    // selection may opt into a current shared runtime while manifests migrate;
696    // omitted and explicit shared selections never downgrade to legacy.
697    let explicit_driver_contract = manifest.explicit_lifecycle_driver_contract()?;
698    let expected_driver_contract = manifest.selected_lifecycle_driver_contract()?.to_string();
699    let allow_shared_driver_upgrade = explicit_driver_contract
700        .is_some_and(|contract| contract != manifest::SHARED_LIFECYCLE_DRIVER_CONTRACT);
701    let deploy_managed = std::env::var_os("RBNX_DEPLOY_MANAGED").is_some();
702    let materialized_cfg_json = build_start_config_json(config_file, set_overrides)?;
703
704    if let Some(message) =
705        lifecycle_driver_migration_warning(&manifest.package.name, explicit_driver_contract)
706    {
707        output::warning(&message);
708    }
709
710    // Per-package run logs live under <pkg>/rbnx-build/logs (gitignored,
711    // owned by the package itself).  When `rbnx boot` spawns us, it sets
712    // $SCRIBE_LOG_DIR to the deploy log dir — respect that so boot-time
713    // logs stay under `rbnx-boot/logs/` for `rbnx logs` to find.
714    let log_dir = std::env::var("SCRIBE_LOG_DIR")
715        .map(PathBuf::from)
716        .unwrap_or_else(|_| package_root.join("rbnx-build").join("logs"));
717    let process_manager = Arc::new(ProcessManager::new(log_dir.clone())?);
718
719    output::action("Running", &manifest.package.name);
720    output::sub_step(&format!("Atlas endpoint: {}", endpoint));
721    if !manifest.capabilities.is_empty() {
722        output::sub_step(&format!(
723            "Capabilities: {}",
724            manifest
725                .capabilities
726                .iter()
727                .map(|c| c.name.as_str())
728                .collect::<Vec<_>>()
729                .join(", ")
730        ));
731    }
732
733    let mut env = std::collections::HashMap::new();
734    env.insert("ROBONIX_ATLAS".to_string(), endpoint.clone());
735    env.insert("SCRIBE_LOG_DIR".to_string(), log_dir.display().to_string());
736    // The exact selection and compatibility permission are distinct. The
737    // historical marker name is retained across wrapper/container boundaries,
738    // but it is now true only for a legacy manifest that may use shared runtime
739    // stubs. Shared selections never receive downgrade permission.
740    env.insert(
741        "ROBONIX_DRIVER_CONTRACT_ID".to_string(),
742        expected_driver_contract.clone(),
743    );
744    // Always overwrite any inherited marker so an explicit selection can
745    // never accidentally inherit omission's downgrade permission.
746    env.insert(
747        "ROBONIX_DRIVER_ALLOW_OLD_ARTIFACT_FALLBACK".to_string(),
748        if allow_shared_driver_upgrade {
749            "1"
750        } else {
751            "0"
752        }
753        .to_string(),
754    );
755    if has_explicit_config && !deploy_managed {
756        output::sub_step("Config: will deliver via Driver(CMD_INIT) post-register");
757    } else if has_explicit_config && deploy_managed {
758        output::sub_step("Config: deployment owner will deliver Driver(CMD_INIT)");
759    }
760    // Force unbuffered stdout/stderr in any Python child the package's
761    // start body launches. Without this, Python block-buffers stdout
762    // when it's a pipe (which `rbnx boot` always makes it), and a
763    // primitive whose driver is still alive never flushes its
764    // `Driver(cmd=0) received` line until the buffer fills or the
765    // process exits — so a 60-second boot full of "what is happening"
766    // looks like the package wedged at "ready - awaiting Driver".
767    // See `examples/webots/rbnx-boot/logs/primitive_tiago_camera.log`
768    // for the diagnostic this turned up. Override with PYTHONUNBUFFERED=
769    // (empty) in the manifest if a package really wants buffered output.
770    env.entry("PYTHONUNBUFFERED".to_string())
771        .or_insert_with(|| "1".to_string());
772
773    if !manifest.build.trim().is_empty() && !build::build_stamp_path(&package_root).exists() {
774        output::sub_step("No rbnx-build/.rbnx-built — running package build first");
775        build::build_local_package(&package_root, false, manifest_override)?;
776    }
777
778    let exports = env
779        .iter()
780        .map(|(k, v)| format!("export {}={}", k, shell_escape(v)))
781        .collect::<Vec<_>>()
782        .join("; ");
783    let pythonpath_export = generated_pythonpath_export(&package_root);
784    let start_body = manifest.start.trim();
785    let setup_bash = package_root
786        .join("rbnx-build")
787        .join("ws")
788        .join("install")
789        .join("setup.bash");
790    let setup_source = if setup_bash.exists() {
791        format!("source {}", shell_escape(&setup_bash.display().to_string()))
792    } else {
793        String::new()
794    };
795    let prefix_parts: Vec<String> = [setup_source, exports, pythonpath_export]
796        .into_iter()
797        .filter(|s| !s.is_empty())
798        .collect();
799    let start_command = if prefix_parts.is_empty() {
800        start_body.to_string()
801    } else {
802        format!("{}; {start_body}", prefix_parts.join("; "))
803    };
804
805    // A standalone lifecycle owner snapshots Atlas before spawning. Snapshot
806    // failures are fatal: treating them as an empty set could select an
807    // unrelated pre-existing provider and deliver this package's config to it.
808    // `rbnx boot` sets RBNX_DEPLOY_MANAGED and owns this sequence itself.
809    let standalone_lifecycle = if !deploy_managed {
810        let json = materialized_cfg_json
811            .expect("start config materialization always returns a JSON object");
812        let normalized = normalize_atlas_endpoint(&endpoint);
813        let mut atlas = AtlasClient::connect(&normalized)
814            .await
815            .with_context(|| format!("connect Atlas at {normalized} before standalone spawn"))?;
816        let before_snapshot = snapshot_provider_ids(&mut atlas)
817            .await
818            .context("standalone pre-spawn Atlas snapshot")?;
819        Some((
820            atlas,
821            before_snapshot,
822            json,
823            expected_driver_contract.clone(),
824            allow_shared_driver_upgrade,
825        ))
826    } else {
827        None
828    };
829
830    // Scribe tag = the per-INSTANCE provider id, never the package name. A
831    // single package (one `package.name`) can be deployed as N instances, each
832    // with a distinct provider id; tagging by package.name would collide them
833    // all into one log. `rbnx boot` passes the instance's provider id via
834    // RBNX_INSTANCE_NAME (the deploy manifest entry's `name`); fall back to
835    // package.name only for a bare standalone `rbnx start` with no instance.
836    let instance_name =
837        std::env::var("RBNX_INSTANCE_NAME").unwrap_or_else(|_| manifest.package.name.clone());
838    let result = if let Some((mut atlas, before, json, expected_contract, allow_shared_upgrade)) =
839        standalone_lifecycle
840    {
841        // `start_process` blocks for the package lifetime, so run it alongside
842        // registration/lifecycle driving. On lifecycle failure, stop the exact
843        // package process group instead of leaving a REGISTERED/ERROR provider.
844        let manager_for_start = Arc::clone(&process_manager);
845        let package_root_for_start = package_root.clone();
846        let start_command_for_start = start_command.clone();
847        let instance_for_start = instance_name.clone();
848        let mut process_task = tokio::spawn(async move {
849            manager_for_start
850                .start_process(
851                    &instance_for_start,
852                    &instance_for_start,
853                    "package",
854                    &package_root_for_start,
855                    &start_command_for_start,
856                )
857                .await
858        });
859
860        // Wait until ProcessManager has recorded the child so every lifecycle
861        // failure path can terminate it. Surface an early child exit directly.
862        let recorded_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
863        while !process_manager.has_process_record(&instance_name, "package") {
864            if process_task.is_finished() {
865                let process_result = process_task.await.context("package process task failed")?;
866                return match process_result {
867                    Ok(result) => anyhow::bail!(
868                        "package exited before registering with Atlas (PID {})",
869                        result.pid
870                    ),
871                    Err(error) => Err(error),
872                };
873            }
874            if tokio::time::Instant::now() >= recorded_deadline {
875                process_task.abort();
876                anyhow::bail!("package process was not recorded within 5s after spawn");
877            }
878            tokio::time::sleep(Duration::from_millis(25)).await;
879        }
880
881        let lifecycle = drive_standalone_lifecycle(
882            &mut atlas,
883            &before,
884            &instance_name,
885            &expected_contract,
886            allow_shared_upgrade,
887            json,
888        );
889        tokio::pin!(lifecycle);
890        tokio::select! {
891            lifecycle_result = &mut lifecycle => {
892                if let Err(error) = lifecycle_result {
893                    output::warning(&format!("standalone lifecycle failed: {error:#}"));
894                    if let Err(stop_error) = process_manager.stop_process(&instance_name, "package").await {
895                        output::warning(&format!("failed to stop package after lifecycle error: {stop_error:#}"));
896                    }
897                    let _ = process_task.await;
898                    return Err(error);
899                }
900            }
901            process_result = &mut process_task => {
902                let process_result = process_result.context("package process task failed")?;
903                return match process_result {
904                    Ok(result) => anyhow::bail!(
905                        "package exited before completing standalone lifecycle (PID {})",
906                        result.pid
907                    ),
908                    Err(error) => Err(error),
909                };
910            }
911        }
912        process_task
913            .await
914            .context("package process task failed")??
915    } else {
916        process_manager
917            .start_process(
918                &instance_name,
919                &instance_name,
920                "package",
921                &package_root,
922                &start_command,
923            )
924            .await?
925    };
926    output::check(&format!(
927        "{} exited (PID {})",
928        manifest.package.name, result.pid
929    ));
930
931    output::success(&format!("Package {} finished", manifest.package.name));
932    Ok(())
933}
934
935/// Build the package-local Python import path without touching a colcon
936/// workspace. A real `rbnx-build/ws/install/setup.bash`, when present, is
937/// sourced first; this export then prepends generated stubs while preserving
938/// every Python path contributed by that overlay and the parent environment.
939fn generated_pythonpath_export(package_root: &Path) -> String {
940    let codegen_root = package_root.join("rbnx-build").join("codegen");
941    let mut paths = vec![package_root.to_path_buf()];
942    for path in [
943        codegen_root.join("proto_gen"),
944        codegen_root.join("robonix_mcp_types"),
945    ] {
946        if path.is_dir() {
947            paths.push(path);
948        }
949    }
950    let joined = paths
951        .iter()
952        .map(|path| path.display().to_string())
953        .collect::<Vec<_>>()
954        .join(":");
955    format!(
956        "export PYTHONPATH={}:${{PYTHONPATH:-}}",
957        shell_escape(&joined)
958    )
959}
960
961fn normalize_atlas_endpoint(endpoint: &str) -> String {
962    if endpoint.starts_with("http") {
963        endpoint.to_string()
964    } else {
965        format!("http://{endpoint}")
966    }
967}
968
969/// Wait for exactly one new provider, verify that it declares the driver
970/// contract from this package manifest, then drive INIT and (except for
971/// skills) ACTIVATE. Contract verification is mandatory before any config is
972/// sent, so a provider exposing a different lifecycle cannot receive this
973/// package's configuration. Concurrent starts of two instances with the same
974/// driver contract still require a future registration token for full identity
975/// correlation.
976async fn drive_standalone_lifecycle(
977    atlas: &mut AtlasClient,
978    before: &ProviderRegistrationSnapshot,
979    expected_provider_id: &str,
980    expected_driver_contract: &str,
981    allow_shared_driver_upgrade: bool,
982    config_json: String,
983) -> Result<()> {
984    let outcome =
985        wait_for_registration_core(atlas, before, expected_provider_id, "rbnx start").await?;
986    let driver_contract = resolve_runtime_driver_contract(
987        &outcome.provider_id,
988        &outcome.provider_namespace,
989        expected_driver_contract,
990        &outcome.driver_contracts,
991        allow_shared_driver_upgrade,
992    )?;
993    if driver_contract != expected_driver_contract {
994        output::warning(&format!(
995            "provider '{}' publishes shared lifecycle Driver '{}' for legacy manifest selection '{}'; remove the legacy Driver declaration to finish migration",
996            outcome.provider_id, driver_contract, expected_driver_contract,
997        ));
998    }
999
1000    let init_state = call_driver_cmd(
1001        atlas,
1002        &outcome.provider_id,
1003        &driver_contract,
1004        CMD_INIT,
1005        config_json.clone(),
1006        "rbnx start",
1007    )
1008    .await?;
1009    output::sub_step(&format!(
1010        "Driver(CMD_INIT) → {} ok (state={init_state})",
1011        outcome.provider_id
1012    ));
1013    if should_activate_standalone_provider(outcome.provider_kind) {
1014        let state = call_driver_cmd(
1015            atlas,
1016            &outcome.provider_id,
1017            &driver_contract,
1018            CMD_ACTIVATE,
1019            config_json,
1020            "rbnx start",
1021        )
1022        .await?;
1023        output::sub_step(&format!(
1024            "Driver(CMD_ACTIVATE) → {} ok (state={state})",
1025            outcome.provider_id
1026        ));
1027    }
1028    Ok(())
1029}
1030
1031fn should_activate_standalone_provider(provider_kind: i32) -> bool {
1032    provider_kind != atlas_pb::Kind::Skill as i32
1033}
1034
1035/// Materialize a per-instance config from `--config <file>` plus
1036/// repeatable `--set k.v=val` overrides. Returns the merged JSON
1037/// string. When neither input was provided, returns an empty JSON object so
1038/// `rbnx start` still performs the provider lifecycle initialization.
1039///
1040/// Layering: load file (json or yaml) → overlay each `--set` on the
1041/// tree → serialise to a single JSON string. The string is delivered
1042/// to the provider exclusively via Driver(CMD_INIT, config_json). The provider
1043/// process MUST NOT read this through env / disk — that's the v0.1
1044/// invariant `rbnx start` and `rbnx boot` both honour.
1045fn build_start_config_json(config_file: Option<&Path>, sets: &[String]) -> Result<Option<String>> {
1046    if config_file.is_none() && sets.is_empty() {
1047        return Ok(Some("{}".to_string()));
1048    }
1049
1050    let mut value: serde_json::Value = match config_file {
1051        Some(p) => {
1052            let raw = std::fs::read_to_string(p)
1053                .with_context(|| format!("read config file {}", p.display()))?;
1054            // Try JSON first; fall through to YAML.
1055            match serde_json::from_str::<serde_json::Value>(&raw) {
1056                Ok(v) => v,
1057                Err(_) => {
1058                    let y: serde_yaml::Value = serde_yaml::from_str(&raw)
1059                        .with_context(|| format!("parse config {} as JSON or YAML", p.display()))?;
1060                    serde_json::to_value(y)
1061                        .with_context(|| format!("convert {} YAML→JSON", p.display()))?
1062                }
1063            }
1064        }
1065        None => serde_json::Value::Object(serde_json::Map::new()),
1066    };
1067
1068    for s in sets {
1069        let (key, raw_val) = s
1070            .split_once('=')
1071            .with_context(|| format!("--set {s:?}: expected KEY=VALUE"))?;
1072        let parsed: serde_json::Value = serde_json::from_str(raw_val)
1073            .unwrap_or_else(|_| serde_json::Value::String(raw_val.into()));
1074        merge_dotted(&mut value, key, parsed)?;
1075    }
1076
1077    Ok(Some(
1078        serde_json::to_string(&value).unwrap_or_else(|_| "{}".into()),
1079    ))
1080}
1081
1082/// Set `obj[a][b][c] = v` for a dotted key like `"a.b.c"`. Creates
1083/// intermediate objects as needed; bails on a non-object collision.
1084fn merge_dotted(root: &mut serde_json::Value, key: &str, v: serde_json::Value) -> Result<()> {
1085    let parts: Vec<&str> = key.split('.').filter(|p| !p.is_empty()).collect();
1086    if parts.is_empty() {
1087        anyhow::bail!("--set: empty key");
1088    }
1089    if !root.is_object() {
1090        *root = serde_json::Value::Object(serde_json::Map::new());
1091    }
1092    let mut cur = root;
1093    for p in &parts[..parts.len() - 1] {
1094        let map = cur.as_object_mut().ok_or_else(|| {
1095            anyhow::anyhow!("--set {key}: cannot descend into non-object at '{p}'")
1096        })?;
1097        let entry = map
1098            .entry((*p).to_string())
1099            .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
1100        if !entry.is_object() {
1101            *entry = serde_json::Value::Object(serde_json::Map::new());
1102        }
1103        cur = entry;
1104    }
1105    let last = parts[parts.len() - 1];
1106    cur.as_object_mut()
1107        .ok_or_else(|| anyhow::anyhow!("--set {key}: parent is not an object"))?
1108        .insert(last.to_string(), v);
1109    Ok(())
1110}
1111
1112#[cfg(test)]
1113mod tests {
1114    use super::*;
1115    use std::fs;
1116    use std::time::{SystemTime, UNIX_EPOCH};
1117
1118    /// A failing clone must exhaust its attempts, name the exit status, and
1119    /// leave no partial checkout behind. The stale directory seeded here
1120    /// stands in for the tree a network-interrupted clone leaves: without the
1121    /// cleanup between attempts, git refuses to clone into a non-empty
1122    /// directory and every retry fails for the wrong reason.
1123    ///
1124    /// The URL is a local path that does not exist, so git fails immediately
1125    /// and the test needs no network.
1126    #[test]
1127    fn git_clone_with_retry_cleans_partial_checkouts_and_reports_the_last_status() {
1128        let root = temp_root("clone-retry");
1129        let dest = root.join("pkg");
1130        fs::create_dir_all(&dest).expect("dest");
1131        fs::write(dest.join("leftover.txt"), b"partial clone").expect("seed leftover");
1132
1133        let missing = root.join("no-such-repo.git");
1134        let err = git_clone_with_retry(&missing.to_string_lossy(), None, &dest)
1135            .expect_err("clone of a nonexistent repo must fail");
1136
1137        let msg = format!("{err:#}");
1138        assert!(msg.contains("after 3 attempts"), "unexpected error: {msg}");
1139        assert!(
1140            !dest.exists(),
1141            "a failed clone must not leave a partial checkout at {}",
1142            dest.display()
1143        );
1144        let _ = fs::remove_dir_all(&root);
1145    }
1146
1147    fn temp_root(label: &str) -> PathBuf {
1148        let nonce = SystemTime::now()
1149            .duration_since(UNIX_EPOCH)
1150            .unwrap()
1151            .as_nanos();
1152        std::env::temp_dir().join(format!("rbnx-start-{label}-{}-{nonce}", std::process::id()))
1153    }
1154
1155    #[test]
1156    fn generated_pythonpath_is_injected_without_a_setup_stub() {
1157        let root = temp_root("pythonpath");
1158        let proto = root.join("rbnx-build/codegen/proto_gen");
1159        let mcp = root.join("rbnx-build/codegen/robonix_mcp_types");
1160        fs::create_dir_all(&proto).unwrap();
1161        fs::create_dir_all(&mcp).unwrap();
1162
1163        let export = generated_pythonpath_export(&root);
1164
1165        assert!(export.contains(&root.display().to_string()));
1166        assert!(export.contains(&proto.display().to_string()));
1167        assert!(export.contains(&mcp.display().to_string()));
1168        assert!(export.ends_with(":${PYTHONPATH:-}"));
1169        assert!(!root.join("rbnx-build/ws/install/setup.bash").exists());
1170        fs::remove_dir_all(root).unwrap();
1171    }
1172
1173    #[test]
1174    fn start_without_config_still_materializes_empty_init_config() {
1175        let config = build_start_config_json(None, &[]).unwrap();
1176        assert_eq!(config.as_deref(), Some("{}"));
1177    }
1178
1179    #[test]
1180    fn standalone_start_activates_primitive_and_service_but_not_skill() {
1181        assert!(should_activate_standalone_provider(
1182            atlas_pb::Kind::Primitive as i32
1183        ));
1184        assert!(should_activate_standalone_provider(
1185            atlas_pb::Kind::Service as i32
1186        ));
1187        assert!(!should_activate_standalone_provider(
1188            atlas_pb::Kind::Skill as i32
1189        ));
1190    }
1191
1192    #[test]
1193    fn shared_driver_contract_needs_no_migration_warning() {
1194        assert_eq!(
1195            lifecycle_driver_migration_warning("test.scene", Some("robonix/lifecycle/driver"),),
1196            None
1197        );
1198    }
1199
1200    #[test]
1201    fn omitted_driver_is_the_canonical_shared_selection() {
1202        assert_eq!(lifecycle_driver_migration_warning("test.scene", None), None);
1203    }
1204
1205    #[test]
1206    fn legacy_driver_contract_gets_one_actionable_migration_warning() {
1207        let warning = lifecycle_driver_migration_warning(
1208            "test.camera",
1209            Some("robonix/primitive/camera/driver"),
1210        )
1211        .unwrap();
1212        assert!(warning.contains("test.camera"));
1213        assert!(warning.contains("robonix/primitive/camera/driver"));
1214        assert!(warning.contains("robonix/lifecycle/driver"));
1215        assert!(warning.contains("is backward-compatible"));
1216        assert!(warning.contains("exact <provider namespace>/driver"));
1217        assert!(warning.contains("shared runtime Driver"));
1218        assert!(warning.contains("do not declare both"));
1219    }
1220
1221    #[test]
1222    fn system_package_uses_the_deploy_selected_manifest() {
1223        let root = temp_root("system-manifest");
1224        let source_root = root.join("source");
1225        let scene_root = source_root.join("system/scene");
1226        let deploy_root = root.join("deploy");
1227        fs::create_dir_all(&scene_root).unwrap();
1228        fs::create_dir_all(&deploy_root).unwrap();
1229        fs::write(
1230            scene_root.join("package_manifest.yaml"),
1231            r#"manifestVersion: 1
1232package:
1233  name: test.system.scene
1234  version: 0.1.0
1235  vendor: test
1236  description: default target
1237  license: Apache-2.0
1238build: touch default-selected
1239start: "true"
1240"#,
1241        )
1242        .unwrap();
1243        fs::write(
1244            scene_root.join("package_manifest.jetson-native.yaml"),
1245            r#"manifestVersion: 1
1246package:
1247  name: test.system.scene
1248  version: 0.1.0
1249  vendor: test
1250  description: Jetson native target
1251  license: Apache-2.0
1252build: touch jetson-selected
1253start: "true"
1254"#,
1255        )
1256        .unwrap();
1257        let deploy_manifest = deploy_root.join("robonix_manifest.yaml");
1258        fs::write(
1259            &deploy_manifest,
1260            r#"manifestVersion: 1
1261name: system-target-test
1262system:
1263  scene:
1264    manifest: package_manifest.jetson-native.yaml
1265    config:
1266      camera_provider_id: front_camera
1267"#,
1268        )
1269        .unwrap();
1270        let config = Config {
1271            package_storage_path: root.join("packages"),
1272            robonix_source_path: Some(source_root),
1273        };
1274
1275        build_deploy_manifest(&deploy_manifest, &config, false, true).unwrap();
1276
1277        assert!(scene_root.join("jetson-selected").is_file());
1278        assert!(!scene_root.join("default-selected").exists());
1279        fs::remove_dir_all(root).unwrap();
1280    }
1281}
浙ICP备2023005800号-2 浙公网安备33010902005384号