Skip to main content

rbnx/cmd/
deploy.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2// `rbnx boot` — bring up the whole robonix stack from a top-level
3// `robonix_manifest.yaml`. (`rbnx boot` is a back-compat alias.)
4//
5// Conventions:
6//   - `system:` Rust binaries (atlas / pilot / executor) are launched with
7//     CLI arguments translated from the manifest block (`--listen`,
8//     `--log`, `--vlm-*`, …). No env-var translation, no YAML config files.
9//   - Package entries (`primitive` / `service`) are launched serially:
10//     spawn → wait for the package to register a provider with a `*/driver`
11//     capability on atlas → call Driver(CMD_INIT, config_json) → wait for
12//     `ok=true`. Only after every primitive's driver returns ok do we move
13//     on to `service:` (which can depend on primitive data being ready).
14//     The package's `config:` block is JSON-encoded and delivered ONLY via
15//     Driver(CMD_INIT)'s config_json field. Omitting Driver is the canonical
16//     way to select the shared lifecycle service. An exact legacy manifest may
17//     use a current shared runtime Driver while it is migrated. A provider
18//     without exactly one lifecycle Driver fails startup.
19//     The provider process never sees a config file or env var.
20//   - `skill:` entries are spawned identically to `service:` — they
21//     need a long-lived process for their MCP tools to be registered
22//     on atlas. The semantic difference (skill = atomic intent
23//     invokable by pilot, service = always-on capability) lives in
24//     the contract namespace (`robonix/skill/*` vs `robonix/service/*`),
25//     not in the lifecycle. The earlier "skill is registered but not
26//     spawned" model lied about what was actually running and forced
27//     manifest authors to put skills like explore in `service:` as a
28//     workaround.
29//
30// Out of scope: crash-restart, health checks beyond Driver(INIT).
31
32use anyhow::{Context, Result};
33use clap::Parser;
34use robonix_atlas::client::AtlasClient;
35use robonix_atlas::pb as atlas_pb;
36use robonix_cli::launch::{
37    CapabilityTransportCheck, PackageRuntimeRecord, ProviderRegistrationSnapshot,
38    RegistrationOutcome, contract_id_to_service_name, driver_register_timeout,
39    resolve_runtime_driver_contract, snapshot_provider_ids, terminate_process_group,
40};
41use robonix_cli::output;
42use robonix_llm_catalog::ModelCatalog;
43use robonix_pilot::config::{Args as PilotArgs, PilotConfig, VlmConfig};
44use serde::Deserialize;
45use sha2::{Digest, Sha256};
46use std::collections::{HashMap, HashSet};
47use std::os::fd::RawFd;
48use std::path::{Path, PathBuf};
49use std::process::Stdio;
50use std::time::{Duration, Instant};
51use tokio::io::AsyncBufReadExt;
52use tokio::process::{Child, Command};
53use tokio::signal::unix::{SignalKind, signal};
54use tonic::Request;
55use tonic::transport::Endpoint;
56use uuid::Uuid;
57
58use robonix_scribe as scribe;
59
60use crate::pb::lifecycle::{DriverRequest, DriverResponse};
61
62use super::teardown;
63
64// Driver.srv command discriminators (mirrors lifecycle/srv/Driver.srv).
65const CMD_INIT: u32 = 0;
66const CMD_ACTIVATE: u32 = 1;
67#[allow(dead_code)]
68const CMD_DEACTIVATE: u32 = 2;
69#[allow(dead_code)]
70const CMD_SHUTDOWN: u32 = 3;
71// Default Driver(CMD_INIT) deadline. Webots CI can override this with
72// ROBONIX_DRIVER_INIT_TIMEOUT_S for real stacks whose lifecycle bringup may
73// exceed 90s on a cold self-hosted runner.
74const DEFAULT_DRIVER_INIT_TIMEOUT: Duration = Duration::from_secs(90);
75const DEPLOY_CONSUMER_ID: &str = "rbnx-cli/deploy";
76
77pub(super) use robonix_cli::manifest::is_builtin_system;
78
79fn driver_init_timeout() -> Duration {
80    std::env::var("ROBONIX_DRIVER_INIT_TIMEOUT_S")
81        .ok()
82        .and_then(|s| s.parse::<u64>().ok())
83        .filter(|secs| *secs > 0)
84        .map(Duration::from_secs)
85        .unwrap_or(DEFAULT_DRIVER_INIT_TIMEOUT)
86}
87
88// ── Deploy manifest schema (subset used by this orchestrator) ───────────
89
90#[derive(Debug, Clone, Deserialize, Default)]
91struct DeployManifest {
92    #[serde(default)]
93    name: String,
94    /// Optional path to the model catalog for this deployment. Overrides the
95    /// user-level `~/.robonix/models.yaml`; `ROBONIX_LLM_CATALOG` overrides
96    /// both.
97    #[serde(default)]
98    model_catalog: Option<String>,
99    #[serde(default)]
100    system: HashMap<String, serde_yaml::Value>,
101    #[serde(default)]
102    primitive: Vec<PackageEntry>,
103    #[serde(default)]
104    service: Vec<PackageEntry>,
105    #[serde(default)]
106    skill: Vec<PackageEntry>,
107}
108
109#[derive(Debug, Clone, Deserialize)]
110struct PackageEntry {
111    /// Package identifier for logs (falls back to the directory basename).
112    #[serde(default)]
113    name: String,
114    /// Local filesystem path (relative to the manifest dir). Mutually
115    /// exclusive with `url`.
116    #[serde(default)]
117    path: Option<String>,
118    /// Git URL for remote packages (e.g. the standalone mapping or nav
119    /// repos too big to ship inside `examples/`). `rbnx boot` clones
120    /// into `<manifest-dir>/rbnx-boot/cache/<name>/` on first run and
121    /// reuses that checkout on subsequent runs. Mutually exclusive with
122    /// `path`.
123    #[serde(default)]
124    url: Option<String>,
125    /// Git branch / tag / commit to check out. Defaults to the default
126    /// branch at clone time. Ignored when `path` is used.
127    #[serde(default)]
128    branch: Option<String>,
129    /// Opaque config block; serialised to JSON and delivered through
130    /// Driver(CMD_INIT). Startup fails if the provider does not declare its
131    /// selected shared or exact compatible legacy lifecycle Driver.
132    #[serde(default)]
133    config: serde_yaml::Value,
134    /// Optional package-manifest filename override. A package may ship
135    /// per-deployment-target manifests (e.g. `package_manifest.yaml` for
136    /// x86+docker, `package_manifest.jetson-native.yaml`,
137    /// `package_manifest.jetson-docker.yaml`), each with its own build/start.
138    /// This selects which one `rbnx build`/`boot` uses for THIS deployment;
139    /// the package-manifest schema itself is unchanged. Defaults to
140    /// `package_manifest.yaml`.
141    #[serde(default)]
142    manifest: Option<String>,
143}
144
145/// Compute a `PackageEntry`'s expected on-disk path. PURE — no I/O,
146/// no logging, no cloning. `path:` entries land at `manifest_dir/path`;
147/// `url:` entries land at `cache_root/<name>` (whether or not it's
148/// been cloned yet). Use `entry_path_exists_on_disk` to check
149/// presence; use the public `cmd::fetch::clone_remote_packages`
150/// (called from `rbnx build`) to actually populate the cache.
151/// Cache directory name for a url-remote package: the git REPO name (last path
152/// segment of the url, minus `.git`), NOT the per-instance provider id.
153///
154/// A single repo can back several providers/instances in one manifest (each
155/// with its own `name`/provider_id); they must share ONE clone. Keying the
156/// cache dir by `name` would clone the same repo once per instance — and the
157/// directory wouldn't reflect what was actually cloned. Key it by the repo.
158///
159/// Compatibility forwarding entry for sibling commands. The implementation
160/// lives in `robonix_cli::manifest` so Soma and rbnx use one rule.
161pub(crate) fn repo_dir_name(url: &str) -> String {
162    robonix_cli::manifest::deploy_repo_dir_name(url)
163}
164
165fn resolve_entry_path(
166    entry: &PackageEntry,
167    cache_root: &Path,
168    manifest_dir: &Path,
169) -> Result<PathBuf> {
170    match (&entry.path, &entry.url) {
171        (Some(p), None) => Ok(manifest_dir.join(p)),
172        (None, Some(url)) => Ok(cache_root.join(repo_dir_name(url))),
173        (Some(_), Some(_)) => {
174            anyhow::bail!("package entry has both `path` and `url`; pick one")
175        }
176        (None, None) => {
177            anyhow::bail!("package entry has neither `path` nor `url`")
178        }
179    }
180}
181
182#[cfg(test)]
183mod tests {
184
185    use super::*;
186    use std::sync::{Mutex, MutexGuard};
187
188    fn git(dir: &Path, args: &[&str]) {
189        let ok = std::process::Command::new("git")
190            .args(args)
191            .current_dir(dir)
192            .output()
193            .expect("git")
194            .status
195            .success();
196        assert!(ok, "git {args:?} failed in {}", dir.display());
197    }
198
199    #[test]
200    fn the_lockfile_records_the_commit_and_whether_the_tree_was_edited() {
201        // A deployment pins packages by branch, so the same manifest is not the
202        // same code twice, and a cache cloned once is reused untouched. One was
203        // found three commits behind its branch with uncommitted edits on top
204        // and nothing about the run said so. The lockfile is what says so.
205        let nonce = std::time::SystemTime::now()
206            .duration_since(std::time::UNIX_EPOCH)
207            .expect("system clock")
208            .as_nanos();
209        let temp = std::env::temp_dir().join(format!("rbnx-lock-{}-{nonce}", std::process::id()));
210        let pkg = temp.join("pkg");
211        std::fs::create_dir_all(&pkg).expect("package directory");
212        git(&pkg, &["init", "-q"]);
213        git(&pkg, &["config", "user.email", "test@example.invalid"]);
214        git(&pkg, &["config", "user.name", "test"]);
215        std::fs::write(pkg.join("f"), "one").expect("file");
216        git(&pkg, &["add", "."]);
217        git(&pkg, &["commit", "-qm", "one"]);
218
219        let deploy: DeployManifest =
220            serde_yaml::from_str("primitive:\n  - name: sample\n    path: pkg\n    branch: main\n")
221                .expect("deployment manifest");
222        let cache_root = temp.join("rbnx-boot/cache");
223        let lock = temp.join("rbnx-boot/deployment.lock");
224
225        write_lockfile(&deploy, &cache_root, &temp);
226        let clean = std::fs::read_to_string(&lock).expect("lockfile");
227        assert!(clean.contains("version: 1"), "{clean}");
228        assert!(clean.contains("name: sample"), "{clean}");
229        // what was asked for and what it resolved to are kept apart
230        assert!(clean.contains("original:"), "{clean}");
231        assert!(clean.contains("branch: main"), "{clean}");
232        assert!(clean.contains("locked:"), "{clean}");
233        let head = std::process::Command::new("git")
234            .args(["rev-parse", "HEAD"])
235            .current_dir(&pkg)
236            .output()
237            .expect("git rev-parse");
238        let head = String::from_utf8_lossy(&head.stdout).trim().to_string();
239        assert!(clean.contains(&format!("commit: {head}")), "{clean}");
240        assert!(
241            !clean.contains("dirty"),
242            "a clean checkout must not be flagged: {clean}"
243        );
244
245        // Deterministic: running again with nothing changed must not rewrite it.
246        let before = std::fs::metadata(&lock)
247            .expect("lock metadata")
248            .modified()
249            .ok();
250        write_lockfile(&deploy, &cache_root, &temp);
251        assert_eq!(std::fs::read_to_string(&lock).expect("lockfile"), clean);
252        assert_eq!(
253            std::fs::metadata(&lock)
254                .expect("lock metadata")
255                .modified()
256                .ok(),
257            before,
258            "an unchanged deployment must not rewrite its lock"
259        );
260
261        // An edited checkout is the case the branch name cannot describe. A
262        // flag alone cannot tell two different edits apart, so it carries a
263        // digest of them.
264        std::fs::write(pkg.join("f"), "two").expect("edit");
265        write_lockfile(&deploy, &cache_root, &temp);
266        let dirty = std::fs::read_to_string(&lock).expect("lockfile");
267        assert!(dirty.contains("dirty: true"), "{dirty}");
268        assert!(dirty.contains("dirty_digest: sha256:"), "{dirty}");
269
270        let first_digest = dirty
271            .lines()
272            .find(|l| l.contains("dirty_digest"))
273            .expect("digest line")
274            .trim()
275            .to_string();
276        std::fs::write(pkg.join("f"), "three").expect("second edit");
277        write_lockfile(&deploy, &cache_root, &temp);
278        let dirty2 = std::fs::read_to_string(&lock).expect("lockfile");
279        assert!(
280            !dirty2.contains(&first_digest),
281            "a different edit must not share a digest: {dirty2}"
282        );
283
284        std::fs::remove_dir_all(&temp).expect("remove test directory");
285    }
286
287    #[test]
288    fn boot_prerequisites_build_scene_with_its_selected_manifest() {
289        let nonce = std::time::SystemTime::now()
290            .duration_since(std::time::UNIX_EPOCH)
291            .expect("system clock")
292            .as_nanos();
293        let temp = std::env::temp_dir().join(format!(
294            "rbnx-system-prerequisite-{}-{nonce}",
295            std::process::id()
296        ));
297        let scene = temp.join("system/scene");
298        std::fs::create_dir_all(&scene).expect("scene package directory");
299        std::fs::create_dir_all(temp.join("system/vitals")).expect("vitals builtin directory");
300        std::fs::write(
301            scene.join("package_manifest.yaml"),
302            r#"manifestVersion: 1
303package:
304  name: com.robonix.system.scene.test
305  version: 0.1.0
306  description: test system package
307  license: MulanPSL-2.0
308build: mkdir -p rbnx-build && echo default > rbnx-build/proof
309start: "true"
310stop: "true"
311"#,
312        )
313        .expect("test package manifest");
314
315        let mut deploy = DeployManifest {
316            system: HashMap::from([
317                ("scene".to_string(), serde_yaml::Value::Null),
318                ("vitals".to_string(), serde_yaml::Value::Null),
319            ]),
320            ..Default::default()
321        };
322        let manifest_dir = temp.join("deployment");
323        let cache_root = manifest_dir.join("rbnx-boot/cache");
324        std::fs::create_dir_all(&cache_root).expect("cache directory");
325
326        check_prerequisites(&deploy, &cache_root, &manifest_dir, Some(&temp))
327            .expect("system-package prerequisite build");
328
329        assert!(scene.join("rbnx-build/proof").is_file());
330        assert!(scene.join("rbnx-build/.rbnx-built").is_file());
331        std::fs::remove_dir_all(scene.join("rbnx-build")).expect("reset build state");
332        let selected = "package_manifest.jetson-native.yaml";
333        let native = std::fs::read_to_string(scene.join("package_manifest.yaml"))
334            .expect("default manifest")
335            .replace("echo default", "echo native");
336        std::fs::write(scene.join(selected), native).expect("native manifest");
337        deploy.system.insert(
338            "scene".to_string(),
339            serde_yaml::from_str(&format!("manifest: {selected}\nconfig: {{}}"))
340                .expect("system package selector"),
341        );
342        check_prerequisites(&deploy, &cache_root, &manifest_dir, Some(&temp))
343            .expect("selected system-package prerequisite build");
344        assert_eq!(
345            std::fs::read_to_string(scene.join("rbnx-build/proof"))
346                .expect("selected build proof")
347                .trim(),
348            "native"
349        );
350        std::fs::remove_dir_all(temp).expect("remove test directory");
351    }
352
353    #[test]
354    fn soma_always_receives_the_selected_boot_manifest() {
355        use serde_yaml::{Mapping, Value};
356
357        let manifest_dir = PathBuf::from("/tmp/ranger-deploy");
358        let selected = manifest_dir.join("robonix_manifest.arm.yaml");
359        let mut soma = Mapping::new();
360        // A stale local value must not make Soma boot the default profile
361        // after `rbnx boot -f <arm-profile>`.
362        soma.insert(
363            Value::String("deployment_manifest".into()),
364            Value::String("robonix_manifest.yaml".into()),
365        );
366        let mut system = HashMap::from([("soma".to_string(), Value::Mapping(soma))]);
367
368        ensure_soma_defaults(&mut system, &manifest_dir, &selected);
369        let args = system_cli_args("soma", system.get("soma"), None);
370        let manifest_arg = args
371            .windows(2)
372            .find(|pair| pair[0] == "--deployment-manifest")
373            .map(|pair| pair[1].as_str());
374
375        assert_eq!(manifest_arg, Some(selected.to_string_lossy().as_ref()));
376    }
377
378    #[test]
379    fn pilot_receives_optional_reasoning_effort() {
380        for effort in [None, Some("high")] {
381            let cfg: serde_yaml::Value =
382                serde_yaml::from_str(&effort.map_or_else(String::new, |value| {
383                    format!("vlm:\n  reasoning_effort: {value}\n")
384                }))
385                .unwrap();
386            let args = system_cli_args("pilot", Some(&cfg), None);
387            let actual = args
388                .windows(2)
389                .find(|pair| pair[0] == "--vlm-reasoning-effort")
390                .map(|pair| pair[1].as_str());
391            assert_eq!(actual, effort);
392        }
393    }
394
395    /// Chronos rejects unknown config keys, so rbnx's own `status` switch stays out.
396    #[test]
397    fn chronos_receives_config_without_status_and_default_atlas() {
398        let cfg: serde_yaml::Value =
399            serde_yaml::from_str("status: enabled\nlisten: 127.0.0.1:50094\n").unwrap();
400        let args = system_cli_args("chronos", Some(&cfg), Some("0.0.0.0:50051"));
401        assert_eq!(
402            args,
403            [
404                "--config-json",
405                r#"{"listen":"127.0.0.1:50094"}"#,
406                "--listen",
407                "127.0.0.1:50094",
408                "--atlas",
409                "0.0.0.0:50051"
410            ]
411        );
412
413        let cfg: serde_yaml::Value =
414            serde_yaml::from_str("atlas_endpoint: 10.0.0.2:50051\n").unwrap();
415        let args = system_cli_args("chronos", Some(&cfg), Some("0.0.0.0:50051"));
416        assert!(!args.iter().any(|arg| arg == "--atlas"), "{args:?}");
417    }
418
419    #[test]
420    fn vitals_receives_typed_manifest_fields() {
421        let cfg: serde_yaml::Value = serde_yaml::from_str(
422            r#"
423listen: 0.0.0.0:50093
424provider_id: vitals
425thresholds_path: config/vitals.yaml
426soma_endpoint: 127.0.0.1:50091
427"#,
428        )
429        .unwrap();
430        let args = system_cli_args("vitals", Some(&cfg), Some("0.0.0.0:50051"));
431
432        for expected in [
433            ["--listen", "0.0.0.0:50093"],
434            ["--atlas", "0.0.0.0:50051"],
435            ["--id", "vitals"],
436            ["--thresholds-path", "config/vitals.yaml"],
437            ["--soma-endpoint", "127.0.0.1:50091"],
438        ] {
439            assert!(
440                args.windows(2)
441                    .any(|pair| pair[0] == expected[0] && pair[1] == expected[1]),
442                "missing {:?} in {:?}",
443                expected,
444                args
445            );
446        }
447    }
448
449    #[test]
450    fn provider_failure_ignores_later_shutdown_noise() {
451        let path = std::env::temp_dir().join(format!(
452            "rbnx-provider-failure-{}.log",
453            uuid::Uuid::new_v4()
454        ));
455        std::fs::write(
456            &path,
457            concat!(
458                "{\"level\":\"info\",\"msg\":\"ready -- awaiting Driver(CMD_INIT)\"}\n",
459                "{\"level\":\"info\",\"msg\":\"[ranger_chassis] state REGISTERED -> ERROR (CAN setup failed: sudo password required)\"}\n",
460                "{\"level\":\"info\",\"msg\":\"shutdown hook completed\"}\n",
461            ),
462        )
463        .unwrap();
464
465        assert_eq!(
466            read_provider_failure(&path).as_deref(),
467            Some("CAN setup failed: sudo password required")
468        );
469        let _ = std::fs::remove_file(path);
470    }
471
472    #[test]
473    fn provider_failure_accepts_error_level_records() {
474        let path = std::env::temp_dir().join(format!(
475            "rbnx-provider-error-level-{}.log",
476            uuid::Uuid::new_v4()
477        ));
478        std::fs::write(
479            &path,
480            "{\"level\":\"error\",\"msg\":\"camera device disconnected\"}\n",
481        )
482        .unwrap();
483
484        assert_eq!(
485            read_provider_failure(&path).as_deref(),
486            Some("camera device disconnected")
487        );
488        let _ = std::fs::remove_file(path);
489    }
490
491    #[test]
492    fn provider_exit_summary_uses_last_structured_message() {
493        let path = std::env::temp_dir().join(format!(
494            "rbnx-provider-exit-summary-{}.log",
495            uuid::Uuid::new_v4()
496        ));
497        std::fs::write(
498            &path,
499            concat!(
500                "{\"level\":\"info\",\"msg\":\"Traceback (most recent call last):\"}\n",
501                "{\"level\":\"info\",\"msg\":\"ImportError: generated contract is missing\"}\n",
502                "{\"level\":\"info\",\"msg\":\"Error: scene process exited with status 1\"}\n",
503            ),
504        )
505        .unwrap();
506
507        assert_eq!(
508            read_provider_exit_summary(&path).as_deref(),
509            Some("Error: scene process exited with status 1")
510        );
511        let _ = std::fs::remove_file(path);
512    }
513
514    #[test]
515    fn pilot_context_preflight_allows_learning_unknown_and_marks_manual_override() {
516        let _env = catalog_env("legacy", PILOT_CATALOG);
517        let known = vec![
518            "--vlm-upstream".into(),
519            "https://api.example/v1".into(),
520            "--vlm-api-key".into(),
521            "test-key".into(),
522            "--vlm-model".into(),
523            "gpt-4o".into(),
524        ];
525        assert!(require_system_args("pilot", &known, false).is_ok());
526
527        let mut unknown = known.clone();
528        unknown[5] = "private-local-planner".into();
529        assert!(require_system_args("pilot", &unknown, false).is_ok());
530        unknown.extend(["--vlm-context-window-tokens".into(), "32768".into()]);
531        assert!(require_system_args("pilot", &unknown, false).is_ok());
532        assert!(system_boot_detail("pilot", &unknown, None).contains("context=32768 (manual)"));
533    }
534
535    #[test]
536    fn pilot_preflight_allows_missing_vlm_args_when_catalog_is_enabled() {
537        let env = catalog_env("preflight", PILOT_CATALOG);
538        let empty: Vec<String> = Vec::new();
539        assert!(require_system_args("pilot", &empty, true).is_ok());
540        assert!(require_system_args("pilot", &empty, false).is_err());
541        let catalog = validate_model_catalog(&env.path, "manifest", &HashMap::new(), true)
542            .expect("valid catalog");
543        assert!(
544            system_boot_detail("pilot", &empty, Some(&catalog))
545                .contains("catalog=catalog/model source=manifest")
546        );
547    }
548
549    static CATALOG_ENV_LOCK: Mutex<()> = Mutex::new(());
550    const PILOT_CATALOG: &str = r#"{"models":[{"id":"catalog/model","provider":"test",
551        "base_url":"http://catalog.example/v1","model":"catalog-model",
552        "api_key_env":"CAT_KEY","features":{"vision":true,"tools":true,"stream":true}}]}"#;
553    const CATALOG_ENV_NAMES: &[&str] = &[
554        "ROBONIX_LLM_CATALOG",
555        "ROBONIX_LLM_KEY_ENVS",
556        "CAT_KEY",
557        "ROBONIX_LLM_FEATURES",
558        "ROBONIX_VLM_UPSTREAM",
559        "ROBONIX_VLM_MODEL",
560        "ROBONIX_VLM_API_KEY",
561        "ROBONIX_VLM_FORMAT",
562        "ROBONIX_VLM_CONTEXT_WINDOW_TOKENS",
563        "VLM_BASE_URL",
564        "VLM_API_KEY",
565        "MEMGRAPH_LLM_BASE_URL",
566        "MEMGRAPH_LLM_API_KEY",
567        "ROBONIX_CONFIG_PATH",
568        "ROBONIX_LLM_METRICS_DIR",
569        "RBNX_BOOT_ID",
570        "UNUSED_PROVIDER_API_KEY",
571        "UNRELATED_CREDENTIAL",
572    ];
573
574    /// Restores process settings after a serialized preflight test.
575    struct CatalogEnv {
576        /// Serializes tests that change model configuration.
577        _lock: MutexGuard<'static, ()>,
578        /// Catalog file owned by this test.
579        path: PathBuf,
580        /// Environment values to restore when the test finishes.
581        saved: Vec<(&'static str, Option<std::ffi::OsString>)>,
582    }
583
584    impl Drop for CatalogEnv {
585        fn drop(&mut self) {
586            unsafe {
587                for (name, value) in &self.saved {
588                    if let Some(value) = value {
589                        std::env::set_var(name, value);
590                    } else {
591                        std::env::remove_var(name);
592                    }
593                }
594            }
595            let _ = std::fs::remove_file(&self.path);
596        }
597    }
598
599    fn catalog_env(name: &str, body: &str) -> CatalogEnv {
600        let lock = CATALOG_ENV_LOCK.lock().expect("catalog env lock");
601        let path =
602            std::env::temp_dir().join(format!("rbnx-catalog-{}-{name}.json", std::process::id()));
603        std::fs::write(&path, body).expect("write catalog");
604        let saved = CATALOG_ENV_NAMES
605            .iter()
606            .map(|&name| (name, std::env::var_os(name)))
607            .collect();
608        unsafe {
609            for name in CATALOG_ENV_NAMES {
610                std::env::remove_var(name);
611            }
612            std::env::set_var("CAT_KEY", "secret");
613        }
614        CatalogEnv {
615            _lock: lock,
616            path,
617            saved,
618        }
619    }
620
621    #[test]
622    fn pilot_child_receives_only_catalog_keys_and_selected_overrides() {
623        let env = catalog_env("child-env", PILOT_CATALOG);
624        unsafe {
625            std::env::set_var("UNUSED_PROVIDER_API_KEY", "unused");
626            std::env::set_var("UNRELATED_CREDENTIAL", "unused");
627            std::env::set_var("RBNX_BOOT_ID", "test-boot");
628            std::env::set_var("ROBONIX_LLM_METRICS_DIR", "/tmp/llm-metrics");
629        }
630        for (explicit_key, config, expected_key) in [
631            (None, "{}", ""),
632            (Some("override"), "{}", "override"),
633            (
634                Some("unused"),
635                "{vlm: {model: catalog/model, api_key: selected}}",
636                "",
637            ),
638        ] {
639            if let Some(key) = explicit_key {
640                unsafe { std::env::set_var("ROBONIX_VLM_API_KEY", key) };
641            }
642            let catalog =
643                validate_model_catalog(&env.path, "manifest", &pilot_system(config), true)
644                    .expect("valid catalog");
645            let mut cmd = Command::new("sh");
646            cmd.arg("-c").arg(concat!(
647                "test \"$CAT_KEY\" = secret && ",
648                "test \"$RBNX_BOOT_ID\" = test-boot && ",
649                "test \"$ROBONIX_LLM_METRICS_DIR\" = /tmp/llm-metrics && ",
650                "test \"$ROBONIX_LLM_KEY_ENVS\" = CAT_KEY && ",
651                "test -n \"$ROBONIX_LLM_CATALOG\" && test -n \"$PATH\" && ",
652                "test \"${UNUSED_PROVIDER_API_KEY+x}\" != x && ",
653                "test \"${UNRELATED_CREDENTIAL+x}\" != x && ",
654                "test \"${ROBONIX_VLM_API_KEY-}\" = \"$1\""
655            ));
656            cmd.arg("probe").arg(expected_key);
657            apply_pilot_catalog_env(&mut cmd, &catalog);
658            let output = cmd.as_std_mut().output().expect("run environment probe");
659            assert!(output.status.success(), "explicit key: {explicit_key:?}");
660        }
661    }
662
663    #[test]
664    fn a_consumer_key_is_forwarded_only_with_its_own_endpoint() {
665        let env = catalog_env("key-endpoint", PILOT_CATALOG);
666        let catalog = validate_model_catalog(&env.path, "manifest", &HashMap::new(), true)
667            .expect("valid catalog");
668        for (endpoint, key, expect_key) in [
669            (
670                Some(("VLM_BASE_URL", "https://vlm.example/v1")),
671                "VLM_API_KEY",
672                true,
673            ),
674            (None, "VLM_API_KEY", false),
675            (
676                Some(("MEMGRAPH_LLM_BASE_URL", "https://memory.example/v1")),
677                "MEMGRAPH_LLM_API_KEY",
678                true,
679            ),
680            (None, "MEMGRAPH_LLM_API_KEY", false),
681        ] {
682            unsafe {
683                std::env::remove_var("VLM_BASE_URL");
684                std::env::remove_var("MEMGRAPH_LLM_BASE_URL");
685                std::env::set_var("VLM_API_KEY", "vlm-key");
686                std::env::set_var("MEMGRAPH_LLM_API_KEY", "memory-key");
687                if let Some((name, value)) = endpoint {
688                    std::env::set_var(name, value);
689                }
690            }
691            let mut cmd = Command::new("env");
692            apply_pilot_catalog_env(&mut cmd, &catalog);
693            let output = cmd.as_std_mut().output().expect("run environment probe");
694            let text = String::from_utf8_lossy(&output.stdout);
695            let prefix = format!("{key}=");
696            let present = text.lines().any(|line| line.starts_with(&prefix));
697            assert_eq!(present, expect_key, "{key} endpoint={endpoint:?}");
698        }
699    }
700
701    fn pilot_system(vlm: &str) -> HashMap<String, serde_yaml::Value> {
702        let mut system = HashMap::new();
703        system.insert(
704            "pilot".into(),
705            serde_yaml::from_str(vlm).expect("pilot block"),
706        );
707        system
708    }
709
710    #[test]
711    fn model_catalog_path_prefers_env_then_manifest() {
712        let _env = catalog_env("path", r#"{"models":[]}"#);
713        unsafe { std::env::set_var("ROBONIX_LLM_CATALOG", "/tmp/env-catalog.json") };
714        let (_, source) = resolve_model_catalog(Some("models.yaml"), Path::new("/tmp/deploy"))
715            .expect("env catalog");
716        assert_eq!(source, "env");
717
718        unsafe { std::env::remove_var("ROBONIX_LLM_CATALOG") };
719        let (path, source) = resolve_model_catalog(Some("models.yaml"), Path::new("/tmp/deploy"))
720            .expect("manifest catalog");
721        assert_eq!(path, PathBuf::from("/tmp/deploy/models.yaml"));
722        assert_eq!(source, "manifest");
723    }
724
725    #[test]
726    fn catalog_validation_resolves_the_pilot_target() {
727        let env = catalog_env("valid", PILOT_CATALOG);
728        let catalog = validate_model_catalog(&env.path, "manifest", &HashMap::new(), true)
729            .expect("valid catalog");
730        assert_eq!(
731            catalog.pilot.unwrap().catalog_id.as_deref(),
732            Some("catalog/model")
733        );
734        assert_eq!(
735            std::env::var("ROBONIX_LLM_KEY_ENVS").as_deref(),
736            Ok("CAT_KEY")
737        );
738    }
739
740    #[test]
741    fn catalog_validation_rejects_an_unresolvable_pilot_catalog() {
742        let env = catalog_env(
743            "no-match",
744            r#"{"models":[{"id":"text/model","provider":"test",
745            "base_url":"http://text.example/v1","model":"text",
746            "features":{"tools":true}}]}"#,
747        );
748        let error = validate_model_catalog(&env.path, "manifest", &HashMap::new(), true)
749            .expect_err("no pilot target");
750        assert!(format!("{error:#}").contains("satisfies"), "{error:#}");
751    }
752
753    #[test]
754    fn catalog_validation_accepts_keyless_local_targets() {
755        let env = catalog_env(
756            "keyless",
757            r#"{"models":[{"id":"local/keyless","provider":"vllm",
758            "base_url":"http://127.0.0.1:8000/v1","model":"local",
759            "features":{"vision":true,"tools":true,"stream":true}}]}"#,
760        );
761        let catalog = validate_model_catalog(&env.path, "manifest", &HashMap::new(), true)
762            .expect("keyless catalog");
763        assert_eq!(
764            catalog.pilot.unwrap().catalog_id.as_deref(),
765            Some("local/keyless")
766        );
767        assert_eq!(std::env::var("ROBONIX_LLM_KEY_ENVS").as_deref(), Ok(""));
768    }
769
770    #[test]
771    fn catalog_validation_leaves_explicit_pilot_config_alone() {
772        let env = catalog_env(
773            "explicit",
774            r#"{"models":[{"id":"text/model","provider":"test",
775            "base_url":"http://text.example/v1","model":"text",
776            "features":{"tools":true}}]}"#,
777        );
778        let system = pilot_system(
779            "vlm: {upstream: http://explicit.example/v1, model: explicit-model, api_key: explicit-key}",
780        );
781        let catalog =
782            validate_model_catalog(&env.path, "manifest", &system, true).expect("explicit pilot");
783        let pilot = catalog.pilot.expect("explicit model");
784        assert!(pilot.catalog_id.is_none());
785        assert_eq!(pilot.model, "explicit-model");
786    }
787
788    #[test]
789    fn catalog_preflight_accepts_an_explicit_key_override() {
790        let env = catalog_env("key-override", PILOT_CATALOG);
791        unsafe { std::env::remove_var("CAT_KEY") };
792        let system = pilot_system("vlm: {model: catalog/model, api_key: explicit-key}");
793        let info = validate_model_catalog(&env.path, "manifest", &system, true)
794            .expect("explicit key must satisfy preflight");
795        assert_eq!(info.pilot.unwrap().api_key, "explicit-key");
796    }
797
798    #[test]
799    fn catalog_preflight_honors_pilot_environment_settings() {
800        let env = catalog_env("env-override", PILOT_CATALOG);
801        unsafe {
802            std::env::set_var("ROBONIX_VLM_UPSTREAM", "http://explicit.example/v1");
803            std::env::set_var("ROBONIX_VLM_MODEL", "env-model");
804            std::env::set_var("ROBONIX_VLM_API_KEY", "env-key");
805            std::env::remove_var("CAT_KEY");
806        }
807        let info = validate_model_catalog(&env.path, "manifest", &HashMap::new(), true)
808            .expect("explicit env must satisfy preflight");
809        let pilot = info.pilot.unwrap();
810        assert_eq!(pilot.model, "env-model");
811        assert!(pilot.catalog_id.is_none());
812    }
813
814    #[test]
815    fn catalog_preflight_rejects_unsupported_protocols() {
816        let mut data: serde_json::Value = serde_json::from_str(PILOT_CATALOG).unwrap();
817        data["models"][0]["protocol"] = "unsupported".into();
818        let env = catalog_env("protocol", &data.to_string());
819        let error = validate_model_catalog(&env.path, "manifest", &HashMap::new(), true)
820            .expect_err("unsupported protocol");
821        assert!(format!("{error:#}").contains("only speaks openai-chat"));
822    }
823
824    #[test]
825    fn catalog_boot_detail_shows_the_actual_model_and_redacts_the_endpoint() {
826        let mut data: serde_json::Value = serde_json::from_str(PILOT_CATALOG).unwrap();
827        data["models"][0]["base_url"] =
828            "https://user:password@provider.example/v1?token=private".into();
829        let env = catalog_env("boot-detail", &data.to_string());
830        let info = validate_model_catalog(&env.path, "manifest", &HashMap::new(), true).unwrap();
831        let detail = system_boot_detail("pilot", &[], Some(&info));
832        assert!(detail.contains("vlm=catalog-model"));
833        assert!(detail.contains("endpoint=https://provider.example/v1"));
834        assert!(detail.contains("catalog=catalog/model source=manifest"));
835        for value in ["password", "private", "secret"] {
836            assert!(!detail.contains(value));
837        }
838    }
839}
840
841/// Boot-time prerequisites check:
842///   - any url-remote package whose cache dir doesn't exist → warn,
843///     clone it inline (so the user isn't blocked) and tell them to
844///     run `rbnx build` for proper bring-up.
845///   - any package whose `rbnx-build/.rbnx-built` sentinel is missing
846///     → warn and run its build.sh inline.
847///
848/// Boot's job is to spawn and atlas-register; fetching and building
849/// belong to `rbnx build`. We do the inline remediation here ONLY so
850/// the user isn't stuck after a fresh clone with no build done — the
851/// warnings are deliberately loud so the right path (build first,
852/// then boot) stays visible.
853fn check_prerequisites(
854    deploy: &DeployManifest,
855    cache_root: &Path,
856    manifest_dir: &Path,
857    robonix_source_path: Option<&Path>,
858) -> Result<()> {
859    use std::collections::BTreeMap;
860    // value: (url, branch, manifest_override)
861    let mut needs_clone: BTreeMap<String, (String, Option<String>, Option<String>)> =
862        BTreeMap::new();
863    // value: (pkg_path, manifest_override)
864    let mut needs_build: BTreeMap<String, (PathBuf, Option<String>)> = BTreeMap::new();
865    for entry in deploy
866        .primitive
867        .iter()
868        .chain(deploy.service.iter())
869        .chain(deploy.skill.iter())
870    {
871        let pkg_path = match resolve_entry_path(entry, cache_root, manifest_dir) {
872            Ok(p) => p,
873            Err(_) => continue, // bad manifest entry; later steps will surface it
874        };
875        let name = if entry.name.is_empty() {
876            pkg_path
877                .file_name()
878                .and_then(|n| n.to_str())
879                .unwrap_or("(unnamed)")
880                .to_string()
881        } else {
882            entry.name.clone()
883        };
884        if !pkg_path.exists()
885            && let Some(url) = entry.url.as_ref()
886        {
887            needs_clone.insert(
888                name.clone(),
889                (url.clone(), entry.branch.clone(), entry.manifest.clone()),
890            );
891            continue;
892        }
893        let stamp = pkg_path.join("rbnx-build").join(".rbnx-built");
894        if !stamp.exists() {
895            needs_build.insert(name, (pkg_path, entry.manifest.clone()));
896        }
897    }
898
899    // Non-builtin `system:` entries are packages too.  They are resolved
900    // from the configured Robonix source tree rather than from an explicit
901    // deployment `path:`, so the package loop above cannot see them.  Build
902    // them during prerequisites just like primitive/service/skill packages;
903    // otherwise `rbnx start` performs the build after spawn and the provider
904    // registration timeout can kill a legitimate first build (Scene model
905    // downloads are a common example).
906
907    if let Some(source_root) = robonix_source_path {
908        for (name, value) in &deploy.system {
909            if is_builtin_system(name.as_str()) {
910                continue;
911            }
912            let pkg_path = source_root.join("system").join(name);
913            if !pkg_path.exists() {
914                continue; // the later system-package loop reports optional packages
915            }
916            let stamp = pkg_path.join("rbnx-build").join(".rbnx-built");
917            if !stamp.exists() {
918                let (manifest_override, _) =
919                    robonix_cli::manifest::split_system_package_config(value)
920                        .with_context(|| format!("parse system/{name} package selector"))?;
921                needs_build.insert(name.clone(), (pkg_path, manifest_override));
922            }
923        }
924    }
925    if needs_clone.is_empty() && needs_build.is_empty() {
926        return Ok(());
927    }
928    output::boot_section("prerequisites");
929    for (name, (url, branch, manifest_ov)) in &needs_clone {
930        output::warning(&format!(
931            "{name}: not in cache — `rbnx build` should run before `rbnx boot`. cloning inline."
932        ));
933        let dest = cache_root.join(repo_dir_name(url));
934        std::fs::create_dir_all(cache_root)?;
935        super::run_package::git_clone_with_retry(url, branch.as_deref(), &dest)?;
936        // Newly-cloned package needs a build too.
937        let stamp = dest.join("rbnx-build").join(".rbnx-built");
938        if !stamp.exists() {
939            needs_build.insert(name.clone(), (dest, manifest_ov.clone()));
940        }
941    }
942    for (name, (pkg_path, manifest_ov)) in &needs_build {
943        output::warning(&format!(
944            "{name}: not built — `rbnx build` should run before `rbnx boot`. building inline."
945        ));
946        crate::cmd::build::build_local_package(pkg_path, false, manifest_ov.as_deref())
947            .with_context(|| format!("inline build of {name} at {} failed", pkg_path.display()))?;
948    }
949    Ok(())
950}
951
952/// One package as it was actually found on disk when the deployment ran.
953struct ResolvedPackage {
954    name: String,
955    /// What the manifest asked for.
956    url: Option<String>,
957    path: Option<String>,
958    branch: Option<String>,
959    /// What that resolved to.
960    commit: Option<String>,
961    dirty_digest: Option<String>,
962}
963
964/// `git rev-parse HEAD`, and a digest of the uncommitted changes if any.
965///
966/// Both are read from the checkout, not from the manifest: a manifest only ever
967/// names a branch, and a branch is not a version. Returns `(None, None)` for
968/// anything that is not a git checkout — a `path:` entry into the source tree
969/// is versioned by whatever contains it.
970///
971/// A dirty tree gets a digest rather than a bare flag. `dirty: true` says the
972/// commit is not the whole story; a digest says *which* not-the-whole-story,
973/// so two machines claiming the same lock can be compared. This is the same
974/// device the project's own reproducibility record uses for its overlays.
975fn git_state(dir: &Path) -> (Option<String>, Option<String>) {
976    let run = |args: &[&str]| -> Option<String> {
977        std::process::Command::new("git")
978            .args(args)
979            .current_dir(dir)
980            .output()
981            .ok()
982            .filter(|o| o.status.success())
983            .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
984    };
985    let head = run(&["rev-parse", "HEAD"])
986        .map(|s| s.trim().to_string())
987        .filter(|s| !s.is_empty());
988    if head.is_none() {
989        return (None, None);
990    }
991    // Tracked edits and the list of untracked files, together: either alone
992    // misses a way the checkout can differ from its commit.
993    let status = run(&["status", "--porcelain"]).unwrap_or_default();
994    if status.trim().is_empty() {
995        return (head, None);
996    }
997    let diff = run(&["diff", "HEAD"]).unwrap_or_default();
998    let mut hasher = Sha256::new();
999    hasher.update(status.as_bytes());
1000    hasher.update(diff.as_bytes());
1001    (head, Some(format!("sha256:{:x}", hasher.finalize())))
1002}
1003
1004/// Write `rbnx-boot/deployment.lock`: what this run actually used.
1005///
1006/// Shaped after the lockfiles that had to solve this already. From
1007/// `flake.lock`, the split between what was asked for and what it resolved to:
1008/// a branch is the request, a commit is the answer, and conflating them is the
1009/// bug this file exists to expose. From `Cargo.lock` and `package-lock.json`, a
1010/// format version, so the file can change without a reader guessing. From all
1011/// three, determinism: entries sorted, no timestamp, so the file changes when
1012/// the deployment changes and not when it merely ran again — a lock that
1013/// rewrites itself on every boot is one nobody reads a diff of.
1014///
1015/// Written, not enforced. A deployment was found three commits behind its
1016/// branch with uncommitted edits on top and no artifact of the run said so.
1017/// This is that artifact; refusing to boot on a moved branch is a separate
1018/// decision that needs a fetch and a policy.
1019fn write_lockfile(deploy: &DeployManifest, cache_root: &Path, manifest_dir: &Path) {
1020    let mut rows: Vec<ResolvedPackage> = Vec::new();
1021    for entry in deploy
1022        .primitive
1023        .iter()
1024        .chain(deploy.service.iter())
1025        .chain(deploy.skill.iter())
1026    {
1027        let Ok(pkg_path) = resolve_entry_path(entry, cache_root, manifest_dir) else {
1028            continue;
1029        };
1030        if !pkg_path.exists() {
1031            continue;
1032        }
1033        let (commit, dirty_digest) = git_state(&pkg_path);
1034        rows.push(ResolvedPackage {
1035            name: if entry.name.is_empty() {
1036                pkg_path
1037                    .file_name()
1038                    .and_then(|n| n.to_str())
1039                    .unwrap_or("(unnamed)")
1040                    .to_string()
1041            } else {
1042                entry.name.clone()
1043            },
1044            url: entry.url.clone(),
1045            path: entry.path.clone(),
1046            branch: entry.branch.clone(),
1047            commit,
1048            dirty_digest,
1049        });
1050    }
1051    // Deterministic order: the file is meant to be diffed.
1052    rows.sort_by(|a, b| a.name.cmp(&b.name));
1053
1054    for row in rows.iter().filter(|r| r.dirty_digest.is_some()) {
1055        output::warning(&format!(
1056            "{}: the cached checkout has uncommitted changes — this run is not \
1057             reproducible from its branch alone",
1058            row.name
1059        ));
1060    }
1061
1062    let mut out = String::from(
1063        "# Generated by `rbnx boot`. Do not edit.\n\
1064         #\n\
1065         # `original` is what the manifest asked for, `locked` is what that\n\
1066         # resolved to on this machine. A manifest pins packages by branch and a\n\
1067         # cache is cloned once, so the two are not the same thing and only this\n\
1068         # file records the second.\n\
1069         version: 1\n\
1070         packages:\n",
1071    );
1072    for row in &rows {
1073        out.push_str(&format!("  - name: {}\n    original:\n", row.name));
1074        if let Some(u) = &row.url {
1075            out.push_str(&format!("      url: {u}\n"));
1076        }
1077        if let Some(p) = &row.path {
1078            out.push_str(&format!("      path: {p}\n"));
1079        }
1080        if let Some(b) = &row.branch {
1081            out.push_str(&format!("      branch: {b}\n"));
1082        }
1083        out.push_str("    locked:\n");
1084        match &row.commit {
1085            Some(c) => out.push_str(&format!("      commit: {c}\n")),
1086            None => out.push_str("      commit: null    # not a git checkout\n"),
1087        }
1088        if let Some(d) = &row.dirty_digest {
1089            out.push_str(&format!("      dirty: true\n      dirty_digest: {d}\n"));
1090        }
1091    }
1092
1093    let path = manifest_dir.join("rbnx-boot").join("deployment.lock");
1094    if let Some(parent) = path.parent() {
1095        let _ = std::fs::create_dir_all(parent);
1096    }
1097    // Only rewrite when something changed, so the file's mtime means something
1098    // and a boot that changed nothing leaves no diff.
1099    if std::fs::read_to_string(&path).ok().as_deref() == Some(out.as_str()) {
1100        return;
1101    }
1102    if let Err(e) = std::fs::write(&path, out) {
1103        output::warning(&format!("could not write {}: {e}", path.display()));
1104    }
1105}
1106
1107/// Apply top-level deployment variables, then expand every scalar in the
1108/// manifest. Build and boot share this preparation path so package locations,
1109/// target-manifest selectors, system settings, and package config all resolve
1110/// against the same environment.
1111pub(super) fn prepare_manifest(
1112    root: serde_yaml::Value,
1113    robonix_source_path: Option<&Path>,
1114) -> Result<serde_yaml::Value> {
1115    let mut root = root;
1116    for entry in robonix_cli::manifest::drop_disabled(&mut root)? {
1117        output::boot_skip(&entry, "disabled");
1118    }
1119    let prepared = robonix_cli::manifest::prepare_deployment_manifest(root, robonix_source_path)?;
1120    robonix_cli::manifest::validate_deployment_instance_names(&prepared)?;
1121    Ok(prepared)
1122}
1123
1124/// Make sure `system.soma` exists in the manifest map as a mapping,
1125/// and resolve any relative file paths inside it against `manifest_dir`.
1126///
1127/// v2 soma has four flat config keys — `atlas_endpoint`, `listen`,
1128/// `provider_id`, `robot_yaml` — and rbnx forwards them via CLI.
1129///
1130/// This helper handles the two "soma implied but not spelled out"
1131/// manifest patterns:
1132///   * `system.soma:` with no body — a bare tag or null.
1133///   * no `system.soma:` at all, but `primitive:` / `skill:` present.
1134///
1135/// In both cases we promote / insert an empty mapping so the rest of
1136/// deploy.rs (system_cli_args, the builtin loop, the stage 2 pipe)
1137/// sees a populated entry. Existing operator-supplied values are
1138/// NEVER overwritten.
1139///
1140/// It also normalises the two path-valued fields inside `system.soma`
1141/// — `robot_yaml` and `config` — from possibly relative to always
1142/// absolute. rbnx passes both straight through to `robonix-soma` as
1143/// CLI flags without chdir-ing, and soma itself only resolves paths
1144/// relative to its `--config` file's parent dir (not the manifest's
1145/// dir), so any relative value written by the operator has to be
1146/// pinned here or soma will try to open it from its own cwd — which
1147/// on systemd-launched Jetsons is `/`, producing errors like
1148/// `read Soma config '/soma_config.local.yaml' … No such file`.
1149///
1150/// Semantics: if the value is absolute it is left untouched (operator
1151/// escape hatch for bind-mounts, /opt paths, etc.); if it's relative
1152/// (including bare filenames like `soma.yaml`) it is joined onto the
1153/// manifest's own directory. Non-string values are ignored — malformed
1154/// manifests will surface the type mismatch at soma CLI parse time
1155/// rather than being silently rewritten here.
1156///
1157/// `robot_yaml` auto-injection: soma refuses to boot without a
1158/// `--robot-yaml` — it needs the robot description before it can
1159/// spawn any primitive in stage 1. Previously we left this to the
1160/// operator, but the failure mode ("missing robot_yaml" → soma exits
1161/// → rbnx sits in `wait_for_soma_stage1` for the full 180s timeout
1162/// before reporting failure) is disproportionately painful for a
1163/// missing default. So: if the operator hasn't set `robot_yaml` and
1164/// a file literally named `soma.yaml` sits next to the manifest, we
1165/// inject that path. If neither is present, we leave the slot empty
1166/// — soma will bail on config parse with a clear error, and the
1167/// stage-1 waiter (see `wait_for_soma_stage1`) will surface soma's
1168/// early exit instead of waiting for the timeout. Operators who
1169/// want a different name still just set `robot_yaml:` explicitly.
1170fn ensure_soma_defaults(
1171    system: &mut HashMap<String, serde_yaml::Value>,
1172    manifest_dir: &Path,
1173    manifest_path: &Path,
1174) {
1175    use serde_yaml::{Mapping, Value};
1176    let entry = system
1177        .entry("soma".to_string())
1178        .or_insert_with(|| Value::Mapping(Mapping::new()));
1179    // Promote a non-mapping value (`soma: ~`, `soma: true`, ...) to an
1180    // empty mapping so operators who wrote `soma:` with no body get a
1181    // usable slot rather than a parse-time surprise.
1182    if !entry.is_mapping() {
1183        *entry = Value::Mapping(Mapping::new());
1184    }
1185    let map = entry
1186        .as_mapping_mut()
1187        .expect("promoted to mapping just above");
1188
1189    // Soma launches primitive and skill packages itself. It therefore must
1190    // read the exact deployment file selected by `rbnx boot -f`, not infer a
1191    // sibling default manifest from robot_yaml. This is intentionally owned
1192    // by the boot command: a stale manifest-local value must not make rbnx
1193    // build one profile while Soma starts another.
1194    map.insert(
1195        Value::String("deployment_manifest".to_string()),
1196        Value::String(manifest_path.to_string_lossy().into_owned()),
1197    );
1198
1199    // Auto-inject `robot_yaml: <manifest_dir>/soma.yaml` when the
1200    // operator didn't set it AND the file exists. We check for the
1201    // key's presence-and-non-emptiness rather than presence alone so
1202    // an unset `${ROBOT_YAML}` (which manifest preparation turns into
1203    // "") still triggers the sidecar lookup. Missing sidecar → leave
1204    // absent (soma's own config-resolve error is the right signal;
1205    // stage-1 waiter surfaces the early exit fast).
1206    let robot_yaml_key = Value::String("robot_yaml".to_string());
1207    let robot_yaml_missing = match map.get(&robot_yaml_key) {
1208        None => true,
1209        Some(Value::Null) => true,
1210        Some(Value::String(s)) if s.is_empty() => true,
1211        _ => false,
1212    };
1213    if robot_yaml_missing {
1214        let sidecar = manifest_dir.join("soma.yaml");
1215        if sidecar.is_file() {
1216            map.insert(
1217                robot_yaml_key,
1218                Value::String(sidecar.to_string_lossy().into_owned()),
1219            );
1220        }
1221    }
1222
1223    for key in ["robot_yaml", "deployment_manifest", "config"] {
1224        let k = Value::String(key.to_string());
1225        let Some(v) = map.get_mut(&k) else { continue };
1226        let Some(s) = v.as_str() else { continue };
1227        // Empty string usually means "${SOME_UNSET_VAR}" got expanded
1228        // away by manifest preparation. Don't paper over that by turning
1229        // it into `manifest_dir/` — leave it empty so soma's own
1230        // "read Soma config '' … No such file" error still fires and
1231        // the operator gets a signal instead of a mystery success.
1232        if s.is_empty() {
1233            continue;
1234        }
1235        let p = Path::new(s);
1236        if p.is_absolute() {
1237            continue;
1238        }
1239        let joined = manifest_dir.join(p);
1240        *v = Value::String(joined.to_string_lossy().into_owned());
1241    }
1242}
1243
1244// ── child-process helpers ───────────────────────────────────────────────
1245
1246struct Spawned {
1247    name: String,
1248    /// "system_builtin" | "system_package" | "primitive" | "service"
1249    kind: String,
1250    child: Child,
1251    pid: u32,
1252    /// Process group id. Each child is spawned with `process_group(0)` so
1253    /// it becomes the leader of a new PGID == its own PID.
1254    pgid: u32,
1255    provider_id: Option<String>,
1256    driver_contract: Option<String>,
1257    /// Lifecycle contract selected by this package's exact manifest. Builtin
1258    /// system processes are not package-managed and leave this unset.
1259    expected_driver_contract: Option<String>,
1260    /// True only for an explicit legacy selection, permitting a current shared
1261    /// runtime Driver while the manifest is migrated.
1262    allow_shared_driver_upgrade: bool,
1263    /// Manifest transport comparison for package-managed processes.
1264    transport_check: Option<CapabilityTransportCheck>,
1265    config_json: Option<String>,
1266    package_dir: Option<PathBuf>,
1267    stop: Option<String>,
1268}
1269
1270fn log_path(log_dir: &Path, name: &str) -> PathBuf {
1271    // `name` is the provider_id — the exact Scribe tag, so `<name>.log` is the
1272    // real file rbnx should point at. No name mangling.
1273    log_dir.join(format!("{name}.log"))
1274}
1275
1276fn apply_pilot_catalog_env(cmd: &mut Command, catalog: &CatalogInfo) {
1277    let key_envs = std::env::var("ROBONIX_LLM_KEY_ENVS").unwrap_or_default();
1278    let mut allowed: HashSet<&str> =
1279        include_str!("../../../../pylib/robonix-api/robonix_api/llm/runtime_env.txt")
1280            .split_whitespace()
1281            .chain(key_envs.split(',').filter(|name| !name.is_empty()))
1282            .collect();
1283    // A key travels only with the endpoint it belongs to, so one component's
1284    // credential does not reach another.
1285    for (endpoint, key) in [
1286        ("VLM_BASE_URL", "VLM_API_KEY"),
1287        ("MEMGRAPH_LLM_BASE_URL", "MEMGRAPH_LLM_API_KEY"),
1288    ] {
1289        if std::env::var_os(endpoint).is_some_and(|value| !value.is_empty()) {
1290            allowed.insert(key);
1291        }
1292    }
1293    // An explicit Pilot key can override a catalog entry's credential.
1294    if std::env::var("ROBONIX_VLM_API_KEY")
1295        .ok()
1296        .is_some_and(|key| {
1297            !key.is_empty()
1298                && catalog
1299                    .pilot
1300                    .as_ref()
1301                    .is_some_and(|pilot| pilot.api_key == key)
1302        })
1303    {
1304        allowed.insert("ROBONIX_VLM_API_KEY");
1305    }
1306    cmd.env_clear().envs(
1307        std::env::vars_os()
1308            .filter(|(name, _)| name.to_str().is_some_and(|name| allowed.contains(name))),
1309    );
1310}
1311
1312async fn spawn_system_binary(
1313    log_dir: &Path,
1314    session_dir: &Path,
1315    name: &str,
1316    bin: &str,
1317    args: &[String],
1318    catalog: Option<&CatalogInfo>,
1319) -> Result<Spawned> {
1320    // Run the installed binary directly.  Stdout / stderr are piped
1321    // through Scribe (tag = binary name, e.g. "executor") so nothing
1322    // escapes to the terminal.  Structured logs from within the binary
1323    // also go through Scribe via the `log` facade auto-init.
1324    let mut cmd = Command::new(bin);
1325    for a in args {
1326        cmd.arg(a);
1327    }
1328    if name == "pilot"
1329        && let Some(catalog) = catalog
1330    {
1331        apply_pilot_catalog_env(&mut cmd, catalog);
1332    }
1333    cmd.stdin(Stdio::null())
1334        .stdout(Stdio::piped())
1335        .stderr(Stdio::piped())
1336        .env("SCRIBE_LOG_DIR", log_dir)
1337        .env("ROBONIX_SESSION_DIR", session_dir)
1338        .process_group(0);
1339    let mut child = cmd.spawn().with_context(|| {
1340        format!(
1341            "failed to spawn system binary `{bin}` — is it installed (try `make install` from the rust/ workspace)?"
1342        )
1343    })?;
1344    let pid = child
1345        .id()
1346        .ok_or_else(|| anyhow::anyhow!("spawned `{bin}` but it had no pid"))?;
1347
1348    // Pipe stdout / stderr into Scribe so raw println!/eprintln! from the
1349    // binary are captured alongside its structured logs.
1350    let stdout = child.stdout.take().expect("stdout not piped");
1351    let stderr = child.stderr.take().expect("stderr not piped");
1352    let tag_out = name.to_string();
1353    let tag_err = name.to_string();
1354    tokio::spawn(async move {
1355        let reader = tokio::io::BufReader::new(stdout);
1356        let mut lines = reader.lines();
1357        while let Ok(Some(line)) = lines.next_line().await {
1358            scribe::ingest(&tag_out, &line);
1359        }
1360    });
1361    tokio::spawn(async move {
1362        let reader = tokio::io::BufReader::new(stderr);
1363        let mut lines = reader.lines();
1364        while let Ok(Some(line)) = lines.next_line().await {
1365            // stderr is not always errors — Python logging defaults to
1366            // stderr for INFO too.  Use `info` to avoid misrepresenting
1367            // the actual severity.
1368            scribe::ingest(&tag_err, &line);
1369        }
1370    });
1371    // Salient detail per builtin: port + role, redact long flag soup
1372    // (--capabilities path lists, --vlm-api-key, …). Full args are
1373    // available in the log file; the boot line stays terse so users
1374    // can scan the bring-up sequence at a glance.
1375    let detail = system_boot_detail(name, args, catalog);
1376    output::boot_ok(name, &detail);
1377    Ok(Spawned {
1378        name: name.to_string(),
1379        kind: "system_builtin".to_string(),
1380        child,
1381        pid,
1382        pgid: pid,
1383        provider_id: None,
1384        driver_contract: None,
1385        expected_driver_contract: None,
1386        allow_shared_driver_upgrade: false,
1387        transport_check: None,
1388        config_json: None,
1389        package_dir: None,
1390        stop: None,
1391    })
1392}
1393
1394/// Fixed fd number rbnx exports as `ROBONIX_SOMA_STAGE_FD` in soma's
1395/// environment. Any fd ≥ 3 works — we pick 3 because it's the first
1396/// non-stdio slot, which keeps `ls /proc/<soma>/fd` readable at a
1397/// glance. Soma reads the trigger line, then closes it.
1398const SOMA_STAGE_FD: RawFd = 3;
1399
1400/// Spawn soma with an inherited pipe on `SOMA_STAGE_FD`. The parent
1401/// keeps the write end and later writes `stage2\n` to it (see
1402/// `write_stage2_trigger` below). Layered on `spawn_system_binary`'s
1403/// stdio+scribe pattern but adds:
1404///   * pipe() to create the trigger channel
1405///   * pre_exec dup2 to move the child's end onto SOMA_STAGE_FD
1406///     (the natural fd from pipe() is unpredictable — some later
1407///     lib open() call could grab it — so we pin it to a known
1408///     number)
1409///   * ROBONIX_SOMA_STAGE_FD env so soma finds it
1410///   * close-on-exec cleared on the child fd (dup2 clears it by
1411///     default, which is what we want)
1412///
1413/// Returns the Spawned handle and the parent's write-end File. Drop
1414/// the File to close the pipe (soma sees EOF and continues without
1415/// stage 2 — matches the `no fd` env-absent path).
1416async fn spawn_soma_binary(
1417    log_dir: &Path,
1418    name: &str,
1419    bin: &str,
1420    args: &[String],
1421) -> Result<(Spawned, std::fs::File)> {
1422    use std::os::fd::{AsRawFd, IntoRawFd, OwnedFd};
1423
1424    // Create the trigger pipe. Parent owns the write end for the
1425    // lifetime of the boot; child inherits the read end. We keep
1426    // the OwnedFd wrappers so an early error path drops the fds
1427    // rather than leaking them.
1428    let (read_fd, write_fd): (OwnedFd, OwnedFd) =
1429        nix::unistd::pipe().context("pipe() for soma stage-2 trigger")?;
1430    let child_raw = read_fd.as_raw_fd();
1431
1432    // tokio::process::Command is a thin wrapper over std::process,
1433    // but pre_exec lives on the std side. We prime the std Command
1434    // via .as_std_mut() below.
1435    let mut cmd = Command::new(bin);
1436    for a in args {
1437        cmd.arg(a);
1438    }
1439    cmd.stdin(Stdio::null())
1440        .stdout(Stdio::piped())
1441        .stderr(Stdio::piped())
1442        .env("SCRIBE_LOG_DIR", log_dir)
1443        .env("ROBONIX_SOMA_STAGE_FD", SOMA_STAGE_FD.to_string())
1444        .process_group(0);
1445
1446    // Hand the child's raw read fd into the closure. We can NOT let
1447    // `read_fd` (the OwnedFd) run its Drop in the parent before the
1448    // child inherits it — that would close the fd. Move ownership
1449    // into the closure and leak/consume it there.
1450    let read_owned = read_fd; // captured
1451    let child_target = SOMA_STAGE_FD;
1452    // Safety: pre_exec runs in the forked child before exec. Only
1453    // async-signal-safe syscalls are permitted; dup2 and close are
1454    // both on that list.
1455    unsafe {
1456        cmd.pre_exec(move || {
1457            // dup2(oldfd, newfd) atomically closes newfd (if open)
1458            // and duplicates oldfd onto it. The new fd has
1459            // CLOEXEC=0 by default, which is what we want (soma
1460            // needs to see it after exec).
1461            let old = read_owned.as_raw_fd();
1462            if old != child_target {
1463                let ret = libc_dup2(old, child_target);
1464                if ret < 0 {
1465                    return Err(std::io::Error::last_os_error());
1466                }
1467                // Original fd number is no longer needed in the
1468                // child; close it so it doesn't linger.
1469                let _ = libc_close(old);
1470            }
1471            Ok(())
1472        });
1473    }
1474
1475    let mut child = cmd.spawn().with_context(|| {
1476        format!(
1477            "failed to spawn system binary `{bin}` — is it installed (try `make install` from the rust/ workspace)?"
1478        )
1479    })?;
1480    let pid = child
1481        .id()
1482        .ok_or_else(|| anyhow::anyhow!("spawned `{bin}` but it had no pid"))?;
1483
1484    // fork() + our pre_exec dup2 have run; the child has its own
1485    // copy on fd 3 and the fork copy of read_owned (whatever number
1486    // pipe() picked). The parent's read_owned has been consumed by
1487    // the closure — the value inside the parent process is a dead
1488    // OwnedFd shell that will drop at the end of pre_exec's scope.
1489    // Nothing left to close on this side; child_raw is only used
1490    // for the debug/log line below.
1491    let _ = child_raw;
1492
1493    // Turn the parent's write-end OwnedFd into a std File so the
1494    // caller can write! into it. into_raw_fd releases ownership;
1495    // File::from_raw_fd takes it back.
1496    let write_raw = write_fd.into_raw_fd();
1497    // Safety: write_raw is a valid, open, owned fd we just released
1498    // from OwnedFd — we're transferring ownership one hop over.
1499    let writer = unsafe { <std::fs::File as std::os::fd::FromRawFd>::from_raw_fd(write_raw) };
1500
1501    // Pipe stdout / stderr into Scribe. (Same pattern as
1502    // spawn_system_binary — kept inline rather than extracted so
1503    // both call sites stay readable.)
1504    let stdout = child.stdout.take().expect("stdout not piped");
1505    let stderr = child.stderr.take().expect("stderr not piped");
1506    let tag_out = name.to_string();
1507    let tag_err = name.to_string();
1508    tokio::spawn(async move {
1509        let reader = tokio::io::BufReader::new(stdout);
1510        let mut lines = reader.lines();
1511        while let Ok(Some(line)) = lines.next_line().await {
1512            scribe::ingest(&tag_out, &line);
1513        }
1514    });
1515    tokio::spawn(async move {
1516        let reader = tokio::io::BufReader::new(stderr);
1517        let mut lines = reader.lines();
1518        while let Ok(Some(line)) = lines.next_line().await {
1519            scribe::ingest(&tag_err, &line);
1520        }
1521    });
1522
1523    let detail = system_boot_detail(name, args, None);
1524    output::boot_ok(name, &detail);
1525    Ok((
1526        Spawned {
1527            name: name.to_string(),
1528            kind: "system_builtin".to_string(),
1529            child,
1530            pid,
1531            pgid: pid,
1532            provider_id: None,
1533            driver_contract: None,
1534            expected_driver_contract: None,
1535            allow_shared_driver_upgrade: false,
1536            transport_check: None,
1537            config_json: None,
1538            package_dir: None,
1539            stop: None,
1540        },
1541        writer,
1542    ))
1543}
1544
1545// Local libc thunks to avoid pulling libc as a direct dep — nix
1546// exposes these via `nix::unistd::dup2` / `close`, but we need
1547// async-signal-safety inside pre_exec and can't rely on nix's
1548// wrappers not allocating on the error path. Raw syscalls are the
1549// safe choice.
1550unsafe extern "C" {
1551    fn dup2(oldfd: i32, newfd: i32) -> i32;
1552    fn close(fd: i32) -> i32;
1553}
1554#[inline]
1555fn libc_dup2(oldfd: RawFd, newfd: RawFd) -> i32 {
1556    unsafe { dup2(oldfd, newfd) }
1557}
1558#[inline]
1559fn libc_close(fd: RawFd) -> i32 {
1560    unsafe { close(fd) }
1561}
1562
1563struct PackageSpawnEnv<'a> {
1564    log_dir: &'a Path,
1565    cache_root: &'a Path,
1566    instances_dir: &'a Path,
1567    manifest_dir: &'a Path,
1568    atlas_endpoint: &'a str,
1569}
1570
1571async fn spawn_package(
1572    component: &str,
1573    entry: &PackageEntry,
1574    env: &PackageSpawnEnv<'_>,
1575) -> Result<Spawned> {
1576    let pkg_path = resolve_entry_path(entry, env.cache_root, env.manifest_dir)?;
1577    let pkg_path = pkg_path
1578        .canonicalize()
1579        .with_context(|| format!("package path not found: {}", pkg_path.display()))?;
1580
1581    let name = if entry.name.is_empty() {
1582        pkg_path
1583            .file_name()
1584            .and_then(|n| n.to_str())
1585            .unwrap_or("package")
1586            .to_string()
1587    } else {
1588        entry.name.clone()
1589    };
1590    let package_manifest =
1591        robonix_cli::manifest::detect_and_load(&pkg_path, entry.manifest.as_deref())
1592            .with_context(|| format!("load package manifest for {}", pkg_path.display()))?;
1593    package_manifest.manifest.validate_and_summarize()?;
1594    let explicit_driver_contract = package_manifest
1595        .manifest
1596        .explicit_lifecycle_driver_contract()?;
1597    let allow_shared_driver_upgrade = explicit_driver_contract.is_some_and(|contract| {
1598        contract != robonix_cli::manifest::SHARED_LIFECYCLE_DRIVER_CONTRACT
1599    });
1600    let expected_driver_contract = Some(
1601        package_manifest
1602            .manifest
1603            .selected_lifecycle_driver_contract()?
1604            .to_string(),
1605    );
1606    let stop = package_manifest.manifest.stop.trim().to_string();
1607    let stop = if stop.is_empty() { None } else { Some(stop) };
1608    // Scribe tag + log-file stem = the provider_id (`entry.name`) verbatim.
1609    // provider_id is unique per deploy (atlas enforces it), so no kind prefix
1610    // is needed for disambiguation — `rbnx logs -t <provider_id>` and the file
1611    // `<provider_id>.log` both key on the same name the user wrote.
1612    let log_name = name.clone();
1613
1614    // Write this instance's config to disk for boot's own bookkeeping
1615    // (debugging via `cat <instances>/<name>.json`, post-mortem
1616    // inspection). Boot itself reads `entry.config` in-memory and
1617    // pushes it via Driver(CMD_INIT, config_json) — see call_driver_cmd
1618    // below. The provider process MUST NOT see this path; we do not export
1619    // it as an env var to the spawned `rbnx start`.
1620    let cfg_json = serde_json::to_value(&entry.config).unwrap_or(serde_json::Value::Null);
1621    let cfg_pretty = serde_json::to_string_pretty(&cfg_json).unwrap_or_else(|_| "{}".into());
1622    let cfg_file = env.instances_dir.join(format!("{name}.json"));
1623    std::fs::write(&cfg_file, &cfg_pretty)
1624        .with_context(|| format!("failed to write {}", cfg_file.display()))?;
1625
1626    // Spawn `rbnx start -p <pkg>` via the currently-running rbnx binary
1627    // itself — i.e. argv[0] of the deploy process. This way deploy doesn't
1628    // need a cargo workspace on disk and version-skew is impossible.
1629    // Stdout / stderr are piped through Scribe (tag = log_name, e.g.
1630    // "service_mapping") so boot-time display stays clean.
1631    let rbnx_bin = std::env::current_exe()
1632        .context("could not resolve current rbnx binary path for `start` re-exec")?;
1633    // Per v0.1 layering: do NOT pass the config file path to the
1634    // spawned `rbnx start` (which would propagate to the provider process
1635    // env). rbnx boot itself drives Driver(CMD_INIT, config_json) over
1636    // gRPC after the provider registers (see `call_driver_cmd` below). The
1637    // cfg_file on disk is for boot's own use — we read it back via
1638    // `entry.config` higher in this module — and atlas-side bookkeeping;
1639    // the provider never sees it.
1640    let _ = &cfg_file; // kept for debug / inspection; not exported
1641    // Tell the provider which atlas to register with — derived from the
1642    // manifest's `system.atlas.listen`, NOT the hard default 127.0.0.1:50051.
1643    // Without this an alt-port deploy (e.g. an isolated CI run) leaves every
1644    // provider dialing 50051 and failing to register. A bind-all listen
1645    // (0.0.0.0) is rewritten to a dialable loopback for the provider; an
1646    // in-container driver further overrides this via ROBONIX_SIM_ATLAS.
1647    let provider_atlas = env.atlas_endpoint.replacen("0.0.0.0", "127.0.0.1", 1);
1648    let mut cmd = Command::new(&rbnx_bin);
1649    cmd.arg("start")
1650        .arg("-p")
1651        .arg(pkg_path.as_os_str())
1652        .arg("--endpoint")
1653        .arg(&provider_atlas)
1654        .env("RBNX_INSTANCE_NAME", &name)
1655        .env("RBNX_INVOCATION_CWD", env.manifest_dir)
1656        // `rbnx start` must keep its package shell in this group.  Otherwise
1657        // ProcessManager creates a nested PGID and boot's failure teardown
1658        // kills only the wrapper, leaving the real package process orphaned.
1659        .env("RBNX_DEPLOY_MANAGED", "1")
1660        .env("SCRIBE_LOG_DIR", env.log_dir)
1661        .stdin(Stdio::null())
1662        .stdout(Stdio::piped())
1663        .stderr(Stdio::piped())
1664        .process_group(0);
1665    // Per-deployment-target package manifest selector (deploy entry's
1666    // `manifest:` field) — `rbnx start` loads this file instead of the
1667    // default package_manifest.yaml so the right start path runs.
1668    if let Some(m) = entry.manifest.as_deref() {
1669        cmd.arg("--manifest").arg(m);
1670    }
1671    // From this spawn to the return below there must be no `.await`. The
1672    // caller pushes the returned process into `children` in the same poll,
1673    // and a boot interrupted by SIGINT/SIGTERM drops the bring-up future only
1674    // at an await point; so a process exists only once it is in `children`,
1675    // where the interrupted-boot teardown stops it. An await added here would
1676    // reopen the gap this closes, and nothing would flag it. A Drop guard on
1677    // `Spawned` that kills its process group would not depend on this. If
1678    // rbnx itself is killed (SIGKILL) or crashes, no teardown runs at all and
1679    // the package outlives it; that needs the child to watch its parent
1680    // (PR_SET_PDEATHSIG), which this does not do.
1681    let mut child = cmd.spawn().with_context(|| {
1682        format!(
1683            "failed to spawn package {name} via `{} start`",
1684            rbnx_bin.display()
1685        )
1686    })?;
1687    let pid = child
1688        .id()
1689        .ok_or_else(|| anyhow::anyhow!("spawned package '{name}' but it had no pid"))?;
1690
1691    // Pipe stdout / stderr into Scribe — tag = provider_id, so the file is
1692    // `<provider_id>.log` (e.g. "mapping.log").
1693    let stdout = child.stdout.take().expect("stdout not piped");
1694    let stderr = child.stderr.take().expect("stderr not piped");
1695    let tag_out = log_name.clone();
1696    let tag_err = log_name.clone();
1697    tokio::spawn(async move {
1698        let reader = tokio::io::BufReader::new(stdout);
1699        let mut lines = reader.lines();
1700        while let Ok(Some(line)) = lines.next_line().await {
1701            scribe::ingest(&tag_out, &line);
1702        }
1703    });
1704    tokio::spawn(async move {
1705        let reader = tokio::io::BufReader::new(stderr);
1706        let mut lines = reader.lines();
1707        while let Ok(Some(line)) = lines.next_line().await {
1708            // stderr is not always errors — Python logging defaults to
1709            // stderr for INFO too.  Use `info` to avoid misrepresenting
1710            // the actual severity.
1711            scribe::ingest(&tag_err, &line);
1712        }
1713    });
1714    // No spawn line here — wait until provider registration and emit one
1715    // boot_ok with the provider_id so each component takes ONE line in the
1716    // boot log instead of three (spawn + waiting + registered).
1717    let kind = match component {
1718        "system" => "system_package",
1719        other => other,
1720    }
1721    .to_string();
1722    Ok(Spawned {
1723        name: log_name,
1724        kind,
1725        child,
1726        pid,
1727        pgid: pid,
1728        provider_id: None,
1729        driver_contract: None,
1730        expected_driver_contract,
1731        allow_shared_driver_upgrade,
1732        transport_check: Some(CapabilityTransportCheck::new(
1733            &name,
1734            &package_manifest.manifest,
1735        )),
1736        config_json: None,
1737        package_dir: Some(pkg_path),
1738        stop,
1739    })
1740}
1741
1742// ── entry point ─────────────────────────────────────────────────────────
1743
1744pub async fn execute(
1745    config: robonix_cli::Config,
1746    manifest_path: PathBuf,
1747    log_dir: Option<PathBuf>,
1748    skip_system: bool,
1749    no_update_check: bool,
1750    verbose: bool,
1751) -> Result<()> {
1752    output::set_boot_verbose(verbose);
1753    let manifest_path = manifest_path
1754        .canonicalize()
1755        .with_context(|| format!("manifest not found: {}", manifest_path.display()))?;
1756    let manifest_dir = manifest_path
1757        .parent()
1758        .context("manifest has no parent directory")?
1759        .to_path_buf();
1760
1761    let raw = std::fs::read_to_string(&manifest_path)
1762        .with_context(|| format!("failed to read {}", manifest_path.display()))?;
1763    let root: serde_yaml::Value = serde_yaml::from_str(&raw)
1764        .with_context(|| format!("failed to parse {}", manifest_path.display()))?;
1765    let root = prepare_manifest(root, config.robonix_source_path.as_deref())
1766        .with_context(|| format!("failed to prepare {}", manifest_path.display()))?;
1767    robonix_cli::manifest::validate_deployment_instance_names(&root).with_context(|| {
1768        format!(
1769            "invalid deployment identities in {}",
1770            manifest_path.display()
1771        )
1772    })?;
1773    let mut deploy: DeployManifest = serde_yaml::from_value(root)
1774        .with_context(|| format!("failed to decode {}", manifest_path.display()))?;
1775    // Banner + boot header FIRST, so the logo/version and what we're booting
1776    // lead the output — before the (possibly slow) remote freshness check.
1777    output::boot_banner();
1778    output::boot_start(
1779        if deploy.name.is_empty() {
1780            "robonix"
1781        } else {
1782            &deploy.name
1783        },
1784        &manifest_path.display().to_string(),
1785    );
1786    // Notice (non-fatal) if any cloned remote provider is behind upstream.
1787    // `--no-update-check` skips the per-package `git fetch` pass entirely.
1788    if !no_update_check {
1789        super::check_remotes::report_outdated(&manifest_path);
1790    }
1791
1792    // Resolve and validate the model catalog before any component is spawned.
1793    // A broken catalog must fail here, not print `[ OK ]` and then take Pilot
1794    // down during config load.
1795    let catalog = if let Some((path, source)) =
1796        resolve_model_catalog(deploy.model_catalog.as_deref(), &manifest_dir)
1797    {
1798        Some(
1799            validate_model_catalog(
1800                &path,
1801                source,
1802                &deploy.system,
1803                !skip_system && deploy.system.contains_key("pilot"),
1804            )
1805            .map_err(|error| {
1806                output::boot_fail("pilot", &format!("{error:#}"));
1807                error
1808            })?,
1809        )
1810    } else {
1811        None
1812    };
1813    let pilot_preflighted = catalog.as_ref().is_some_and(|info| info.pilot.is_some());
1814
1815    // soma owns primitive + skill bring-up (see
1816    // docs/docs/architecture/deployment-and-startup.md). If the manifest
1817    // declares ANY primitive or skill, we MUST start a soma — otherwise those
1818    // packages are silently never spawned (boot looks "OK" because rbnx
1819    // got through atlas/executor/pilot, but the robot stays dead).
1820    //
1821    // Two manifest patterns we want to keep working without forcing
1822    // every existing deploy to add a `system.soma:` block:
1823    //   1. manifest has primitive/skill, no system.soma at all
1824    //      → inject a default soma block.
1825    //   2. manifest has system.soma but didn't set deployments / didn't
1826    //      set start_packages → fill in sane defaults (deployments =
1827    //      [this manifest's dir], start_packages = true).
1828    //
1829    // Both branches route through `ensure_soma_defaults` so the rest of
1830    // deploy.rs (spawning the soma binary in the builtin loop, sending
1831    // the stage 2 trigger after service: bring-up) just sees a
1832    // populated system.soma entry like any other.
1833    //
1834    // Existing operator-supplied values are NEVER overwritten — this
1835    // hole-fills, it does not override intent.
1836    //
1837    // We also run this whenever `system.soma` was explicitly declared,
1838    // even if there are no primitives/skills that would auto-imply
1839    // soma. Rationale: `ensure_soma_defaults` no longer just fills in
1840    // a mapping shell — it also resolves `robot_yaml` / `config`
1841    // relative paths against manifest_dir. An operator who writes
1842    // `system.soma: { config: soma_config.local.yaml }` on its own
1843    // deserves the same path-normalisation as the auto-injected case.
1844    let soma_declared = deploy.system.contains_key("soma");
1845    let soma_implied = !deploy.primitive.is_empty() || !deploy.skill.is_empty();
1846    if (soma_declared || soma_implied) && !skip_system {
1847        ensure_soma_defaults(&mut deploy.system, &manifest_dir, &manifest_path);
1848    }
1849
1850    let log_dir = log_dir.unwrap_or_else(|| manifest_dir.join("rbnx-boot").join("logs"));
1851    // Session state (Pilot transcripts) outlives the logs: boot clears old
1852    // log files, and `rbnx clean` keeps this directory unless asked.
1853    let session_dir = std::env::var_os("ROBONIX_SESSION_DIR")
1854        .map(PathBuf::from)
1855        .unwrap_or_else(|| manifest_dir.join("rbnx-boot").join("sessions"));
1856    // Model usage records outlive the logs for the same reason; every child
1857    // inherits the variable, so set it once here. An existing value wins.
1858    let metrics_dir = std::env::var_os("ROBONIX_LLM_METRICS_DIR")
1859        .map(PathBuf::from)
1860        .unwrap_or_else(|| manifest_dir.join("rbnx-boot").join("llm-metrics"));
1861    std::fs::create_dir_all(&metrics_dir)
1862        .with_context(|| format!("failed to create {}", metrics_dir.display()))?;
1863    // The CLI prepares and clears this directory before Scribe's first log
1864    // call. Do not remove files here: Scribe may already hold open handles.
1865    std::fs::create_dir_all(&log_dir)
1866        .with_context(|| format!("failed to create log dir {}", log_dir.display()))?;
1867
1868    // SCRIBE_CONSOLE_LEVEL is set in main.rs before any scribe call.
1869    // Set SCRIBE_LOG_DIR so boot-time scribe messages (bootstrap,
1870    // child-process pipe forwarding) land in the deploy log dir rather
1871    // than the default ./logs.
1872    // Safety: called before any child spawns, no concurrent access.
1873    unsafe {
1874        std::env::set_var("SCRIBE_LOG_DIR", log_dir.as_os_str());
1875        std::env::set_var("ROBONIX_LLM_METRICS_DIR", metrics_dir.as_os_str());
1876    }
1877    scribe::info(
1878        "bootstrap",
1879        &format!(
1880            "booting {} from {}",
1881            if deploy.name.is_empty() {
1882                "robonix"
1883            } else {
1884                &deploy.name
1885            },
1886            manifest_path.display()
1887        ),
1888    );
1889
1890    let cache_root = manifest_dir.join("rbnx-boot").join("cache");
1891    let instances_dir = manifest_dir.join("rbnx-boot").join("instances");
1892    std::fs::create_dir_all(&instances_dir)
1893        .with_context(|| format!("failed to create instances dir {}", instances_dir.display()))?;
1894
1895    let mut children: Vec<Spawned> = Vec::new();
1896    let state_path = teardown::state_path(&manifest_dir);
1897    let boot_id = Uuid::new_v4().to_string();
1898    // Every wrapper and provider inherits this marker. Persisted teardown
1899    // verifies it against /proc before signalling a PGID, preventing stale
1900    // state from killing an unrelated process after PID reuse.
1901    unsafe { std::env::set_var("RBNX_BOOT_ID", &boot_id) };
1902    let boot_start_time_ticks = robonix_cli::launch::proc_start_time_ticks(std::process::id());
1903    let started_at_ms = std::time::SystemTime::now()
1904        .duration_since(std::time::UNIX_EPOCH)
1905        .map(|d| d.as_millis() as u64)
1906        .unwrap_or(0);
1907    let atlas_endpoint = deploy
1908        .system
1909        .get("atlas")
1910        .and_then(|v| v.as_mapping())
1911        .and_then(|m| m.get(serde_yaml::Value::String("listen".into())))
1912        .and_then(|v| v.as_str())
1913        .unwrap_or("127.0.0.1:50051")
1914        .to_string();
1915    teardown::write_state(
1916        &state_path,
1917        &teardown::BootState {
1918            manifest_path: manifest_path.display().to_string(),
1919            boot_pid: std::process::id(),
1920            boot_start_time_ticks,
1921            boot_id: boot_id.clone(),
1922            started_at_ms,
1923            atlas_endpoint: atlas_endpoint.clone(),
1924            components: Vec::new(),
1925        },
1926    )?;
1927    super::boot_watchdog::spawn(
1928        &state_path,
1929        std::process::id(),
1930        boot_start_time_ticks,
1931        &boot_id,
1932    )?;
1933    let spawn_env = PackageSpawnEnv {
1934        log_dir: &log_dir,
1935        cache_root: &cache_root,
1936        instances_dir: &instances_dir,
1937        manifest_dir: &manifest_dir,
1938        atlas_endpoint: &atlas_endpoint,
1939    };
1940
1941    // Boot is responsible for spawning + atlas registration ONLY.
1942    // Fetching (git clone of url-remote pkgs) and building are
1943    // `rbnx build`'s job. We just verify both have happened; if
1944    // not, warn loudly and remediate inline so the user isn't
1945    // stuck on a fresh clone.
1946    check_prerequisites(
1947        &deploy,
1948        &cache_root,
1949        &manifest_dir,
1950        config.robonix_source_path.as_deref(),
1951    )?;
1952
1953    // Record what this run is about to use, after the caches are settled and
1954    // before anything is spawned.
1955    write_lockfile(&deploy, &cache_root, &manifest_dir);
1956
1957    // Install the SIGINT/SIGTERM handlers BEFORE bringup begins, not after.
1958    // Bringup takes many seconds (git, spawns, waiting for ACTIVE); a Ctrl-C
1959    // in that window used to hit the default disposition and kill rbnx
1960    // outright, orphaning every child already spawned. Racing the bringup
1961    // future against these streams lets us tear the partial stack down
1962    // instead. (SIGKILL can't be trapped — only SIGINT/SIGTERM.) The same
1963    // streams are reused for the post-boot idle wait further down.
1964    let mut sigint = signal(SignalKind::interrupt())?;
1965    let mut sigterm = signal(SignalKind::terminate())?;
1966
1967    // Owns the parent side of the stage-2 trigger pipe (created inside
1968    // `spawn_soma_binary`, drained by `write_stage2_trigger`). Declared
1969    // outside `bringup` so it survives the async-block scope even
1970    // though we only assign into it from inside.
1971    let mut soma_stage_writer: Option<std::fs::File> = None;
1972
1973    let bringup = async {
1974        if !skip_system {
1975            output::boot_section("system");
1976            // System Rust binaries: launched in atlas → executor → pilot order.
1977            // Each is fed CLI flags translated from `system.<name>:` block.
1978            // executor + pilot inherit `--atlas` from `system.atlas.listen`
1979            // unless they declare their own `atlas:` (rare).
1980            let atlas_listen = deploy
1981                .system
1982                .get("atlas")
1983                .and_then(|v| v.as_mapping())
1984                .and_then(|m| m.get(serde_yaml::Value::String("listen".into())))
1985                .and_then(|v| v.as_str())
1986                .map(str::to_string);
1987            let soma_listen = deploy
1988                .system
1989                .get("soma")
1990                .and_then(|v| v.as_mapping())
1991                .and_then(|m| m.get(serde_yaml::Value::String("listen".into())))
1992                .and_then(|v| v.as_str())
1993                .map(|s| s.replacen("0.0.0.0", "127.0.0.1", 1));
1994            // Atlas's contract registry walks every dir in
1995            // --capabilities at startup. We seed it with:
1996            //   1. <robonix_source>/capabilities — the global tree
1997            //   2. <pkg>/capabilities for every primitive/service/skill
1998            //      package whose source dir is on disk and contains a
1999            //      `capabilities/` subdir
2000            // Roots are merged in order; later wins on duplicate id, so
2001            // a package can re-declare a global contract for itself.
2002            // A manifest-level override `system.atlas.capabilities`
2003            // still wins via system_cli_args (clobbers the auto list).
2004            let mut atlas_caps_roots: Vec<String> = Vec::new();
2005            if let Some(root) = config.robonix_source_path.as_ref() {
2006                atlas_caps_roots.push(root.join("capabilities").to_string_lossy().into_owned());
2007            }
2008            for entry in deploy
2009                .primitive
2010                .iter()
2011                .chain(deploy.service.iter())
2012                .chain(deploy.skill.iter())
2013            {
2014                if let Ok(pkg_path) = resolve_entry_path(entry, &cache_root, &manifest_dir) {
2015                    let providers = pkg_path.join("capabilities");
2016                    if providers.is_dir() {
2017                        atlas_caps_roots.push(providers.to_string_lossy().into_owned());
2018                    }
2019                }
2020            }
2021            let atlas_caps_default: Option<String> = if atlas_caps_roots.is_empty() {
2022                None
2023            } else {
2024                Some(atlas_caps_roots.join(","))
2025            };
2026            let bin_map: &[(&str, &str)] = &[
2027                ("atlas", "robonix-atlas"),
2028                ("chronos", "robonix-chronos"),
2029                ("executor", "robonix-executor"),
2030                ("soma", "robonix-soma"),
2031                ("vitals", "robonix-vitals"),
2032                ("pilot", "robonix-pilot"),
2033                ("liaison", "robonix-liaison"),
2034            ];
2035            for (name, bin) in bin_map {
2036                if !deploy.system.contains_key(*name) {
2037                    continue;
2038                }
2039                let mut args =
2040                    system_cli_args(name, deploy.system.get(*name), atlas_listen.as_deref());
2041                if *name == "vitals"
2042                    && !args.iter().any(|arg| arg == "--soma-endpoint")
2043                    && let Some(endpoint) = soma_listen.as_ref()
2044                {
2045                    args.push("--soma-endpoint".into());
2046                    args.push(endpoint.clone());
2047                }
2048                if *name == "atlas"
2049                    && !args.iter().any(|a| a == "--capabilities")
2050                    && let Some(p) = atlas_caps_default.as_ref()
2051                {
2052                    args.push("--capabilities".into());
2053                    args.push(p.clone());
2054                }
2055                // Refuse to spawn if the listen port is already taken — without
2056                // this, the spawned binary silently dies on bind() failure but
2057                // boot keeps going against whoever already owns the port (often
2058                // a stale debug-build atlas/executor/etc from a prior aborted
2059                // run). The fallout is mysterious: register_capability hits an
2060                // atlas that doesn't have your takeover/state-push fixes,
2061                // endpoints route to dead orphan gRPC servers, …
2062                if let Some(listen) = system_listen(name, deploy.system.get(*name))
2063                    && let Err(e) = port_is_free(&listen)
2064                {
2065                    output::boot_fail(
2066                        name,
2067                        &format!(
2068                            "listen address '{listen}' is taken: {e:#}. \
2069                                  Stop the running process (try `bash sim/stop.sh` \
2070                                  or `pkill -f robonix-{name}`) and retry."
2071                        ),
2072                    );
2073                    anyhow::bail!(
2074                        "system/{name}: listen address '{listen}' is already in use; \
2075                         refusing to spawn (would shadow the existing process)"
2076                    );
2077                }
2078
2079                // Required-arg validation before spawn. Without this, an empty
2080                // `${VLM_BASE_URL}` (forgot to source the env file) makes pilot
2081                // start, register_capability briefly, then die with `missing
2082                // required field 'vlm.upstream'`. Boot still printed `[ OK ]`
2083                // because we never re-checked. Fail fast at spawn time and tell
2084                // the user exactly what's missing.
2085                if let Err(e) = require_system_args(name, &args, pilot_preflighted) {
2086                    output::boot_fail(name, &e);
2087                    anyhow::bail!("system/{name}: {e}");
2088                }
2089
2090                let sp = if *name == "soma" {
2091                    // soma needs an inherited pipe fd for the stage-2
2092                    // trigger. Everything else uses the plain spawn path.
2093                    let (sp, writer) = spawn_soma_binary(&log_dir, name, bin, &args).await?;
2094                    soma_stage_writer = Some(writer);
2095                    sp
2096                } else {
2097                    spawn_system_binary(&log_dir, &session_dir, name, bin, &args, catalog.as_ref())
2098                        .await?
2099                };
2100                children.push(sp);
2101                persist_state(
2102                    &state_path,
2103                    &manifest_path,
2104                    &atlas_endpoint,
2105                    started_at_ms,
2106                    &children,
2107                );
2108                tokio::time::sleep(std::time::Duration::from_millis(1500)).await;
2109                if *name == "soma" {
2110                    if !deploy.primitive.is_empty() {
2111                        output::boot_section("primitive");
2112                        if output::boot_verbose() {
2113                            for entry in &deploy.primitive {
2114                                output::boot_wait(&entry.name, "waiting for registration");
2115                            }
2116                        }
2117                    }
2118                    let mut stage1_atlas = AtlasClient::connect_with_retry(
2119                        &atlas_endpoint,
2120                        20,
2121                        Duration::from_millis(500),
2122                    )
2123                    .await
2124                    .with_context(|| {
2125                        format!("connect to atlas at '{atlas_endpoint}' for primitive readiness")
2126                    })?;
2127                    // We just pushed the soma `Spawned` above; grab a
2128                    // mutable borrow on its Child so the stage-1 waiter
2129                    // can `try_wait()` per tick. Without this the waiter
2130                    // sits for the full SOMA_STAGE1_TIMEOUT even when
2131                    // soma exited immediately (e.g. `missing robot_yaml`
2132                    // config error). The unwrap is safe: we just pushed.
2133                    let soma_child = &mut children
2134                        .last_mut()
2135                        .expect("soma Spawned pushed above")
2136                        .child;
2137                    let mut transport_checks = load_transport_checks(&deploy.primitive, &spawn_env);
2138                    wait_for_soma_stage1(
2139                        &mut stage1_atlas,
2140                        &deploy
2141                            .primitive
2142                            .iter()
2143                            .map(|entry| entry.name.clone())
2144                            .collect::<Vec<_>>(),
2145                        soma_child,
2146                        &log_dir,
2147                        &mut transport_checks,
2148                    )
2149                    .await?;
2150
2151                    // soma just finished stage 1 (all primitives ACTIVE). The
2152                    // next thing the operator sees on this terminal is the
2153                    // remaining builtins (pilot, liaison — whichever come
2154                    // after soma in `bin_map`) followed by the non-builtin
2155                    // `system:` entries loop below (memory / scene / speech
2156                    // / …). Both cohorts are *system services*, NOT
2157                    // primitives, but without a fresh section header they
2158                    // visually chain onto the "primitive" header just above
2159                    // and readers routinely mistake pilot for a primitive
2160                    // — the exact confusion this header exists to prevent.
2161                    //
2162                    // Only emit the header if there's actually something
2163                    // downstream to label. Concretely: at least one builtin
2164                    // ordered after soma in `bin_map` is declared in the
2165                    // manifest, OR the manifest has any non-builtin
2166                    // `system:` key that will run in the loop after this
2167                    // for-loop finishes. Otherwise (e.g. an atlas-executor-
2168                    // soma-only deploy) skip the header — dangling section
2169                    // titles with nothing under them are worse than none.
2170                    let builtin_after_soma = bin_map
2171                        .iter()
2172                        .skip_while(|(n, _)| *n != "soma")
2173                        .skip(1) // drop soma itself
2174                        .any(|(n, _)| deploy.system.contains_key(*n));
2175                    let has_non_builtin_system = deploy
2176                        .system
2177                        .keys()
2178                        .any(|k| !bin_map.iter().any(|(n, _)| n == k));
2179                    if builtin_after_soma || has_non_builtin_system {
2180                        output::boot_section("system");
2181                    }
2182                }
2183            }
2184        } else {
2185            output::sub_step("Skipping system bring-up (--skip-system)");
2186        }
2187
2188        // Connect to atlas once; reuse for every primitive/service init dance.
2189        let mut atlas =
2190            AtlasClient::connect_with_retry(&atlas_endpoint, 20, Duration::from_millis(500))
2191                .await
2192                .with_context(|| {
2193                    format!("connect to atlas at '{atlas_endpoint}' for lifecycle init")
2194                })?;
2195
2196        // Non-builtin `system:` keys (memory / speech / …) are real robonix
2197        // packages — same start/init/register flow as primitive/service, just
2198        // resolved by name against `<robonix_source>/system/<key>/`. Builtin
2199        // Rust binaries (atlas/executor/pilot) were spawned above and skipped
2200        // here. A key whose package directory is missing on disk is warned
2201        // and skipped, not fatal — manifests can declare optional services
2202        // that aren't installed yet (e.g. liaison while it's being ported).
2203        // Best-effort boot: a failure on any non-system-builtin package is
2204        // recorded but does NOT bail the whole bring-up. Goal is to get
2205        // atlas + executor + pilot + liaison up so `rbnx chat` can still
2206        // be poked at even when scene / memory / mapping is broken — the
2207        // alternative (the previous fail-fast model) means a single
2208        // package's milvus lock or sensor-init quirk gates every other
2209        // component the operator wants to test.
2210        //
2211        // System builtins (atlas/executor/pilot/liaison) are still
2212        // bail-on-error: nothing else makes sense without those.
2213        let mut failures: Vec<(String, String, String)> = Vec::new(); // (component, name, err)
2214
2215        if !skip_system {
2216            for (key, value) in &deploy.system {
2217                if is_builtin_system(key) {
2218                    continue;
2219                }
2220                let pkg_dir = match config.robonix_source_path.as_ref() {
2221                    Some(root) => root.join("system").join(key),
2222                    None => {
2223                        output::boot_skip(
2224                            key,
2225                            "robonix_source_path unset (`rbnx setup` from repo root)",
2226                        );
2227                        continue;
2228                    }
2229                };
2230                if !pkg_dir.exists() {
2231                    output::boot_skip(key, "not on disk");
2232                    continue;
2233                }
2234                let (manifest_override, runtime_config) =
2235                    robonix_cli::manifest::split_system_package_config(value)
2236                        .with_context(|| format!("parse system/{key} package selector"))?;
2237                let entry = PackageEntry {
2238                    name: key.clone(),
2239                    path: Some(pkg_dir.to_string_lossy().into_owned()),
2240                    url: None,
2241                    branch: None,
2242                    config: runtime_config,
2243                    manifest: manifest_override,
2244                };
2245                match spawn_and_init("system", &entry, &spawn_env, &mut atlas, &mut children).await
2246                {
2247                    Ok(()) => {
2248                        persist_state(
2249                            &state_path,
2250                            &manifest_path,
2251                            &atlas_endpoint,
2252                            started_at_ms,
2253                            &children,
2254                        );
2255                    }
2256                    Err(e) => {
2257                        failures.push(("system".to_string(), key.clone(), format!("{e:#}")));
2258                    }
2259                }
2260            }
2261        }
2262
2263        // primitive: handled by soma's stage 1 (kicked off when soma
2264        //   starts up, finishes before soma declares get_yaml/get_urdf).
2265        // skill:     handled by soma's stage 2 (kicked off by the
2266        //   StageTrigger("stage2") we send below, after non-builtin
2267        //   system services and service: entries have finished
2268        //   bring-up — which is the earliest skills can safely talk
2269        //   to executor/pilot/memory/scene from their MCP tools).
2270        // The deploy.primitive / deploy.skill fields stay in the
2271        // manifest schema because soma reads them; rbnx just doesn't
2272        // launch those processes any more.
2273        if !deploy.service.is_empty() {
2274            output::boot_section("service");
2275        }
2276        for e in &deploy.service {
2277            match spawn_and_init("service", e, &spawn_env, &mut atlas, &mut children).await {
2278                Ok(()) => {
2279                    persist_state(
2280                        &state_path,
2281                        &manifest_path,
2282                        &atlas_endpoint,
2283                        started_at_ms,
2284                        &children,
2285                    );
2286                }
2287                Err(err) => {
2288                    failures.push(("service".to_string(), e.name.clone(), format!("{err:#}")));
2289                }
2290            }
2291        }
2292
2293        // All system + service bring-up done; fire soma's stage 2
2294        // trigger so it spawns + INITs the skill packages. Best
2295        // effort: a soma that never went ACTIVE (or shut down
2296        // between our checks and this NotifyProvider) is a deploy
2297        // problem the operator already sees in earlier boot output;
2298        // we log and continue rather than tearing everything down
2299        // for the skills that never started.
2300        //
2301        // The section is labelled "skill" (not "stage 2") because
2302        // that's what the operator actually sees launching under the
2303        // header — the "stage 2" name is an internal rbnx↔soma pipe
2304        // protocol detail (see `STAGE2_TRIGGER` in soma/main.rs and
2305        // `write_stage2_trigger` below). Keeping the wire word out
2306        // of the terminal UI avoids operators having to learn our
2307        // two-stage bring-up vocabulary just to read boot output.
2308        if deploy.system.contains_key("soma") && !skip_system {
2309            output::boot_section("skill");
2310            if output::boot_verbose() {
2311                for entry in &deploy.skill {
2312                    output::boot_wait(&entry.name, "waiting for registration");
2313                }
2314            }
2315            let mut transport_checks = load_transport_checks(&deploy.skill, &spawn_env);
2316            if let Err(e) = write_stage2_trigger(&mut soma_stage_writer) {
2317                failures.push((
2318                    "system".to_string(),
2319                    "soma".to_string(),
2320                    format!("start skill packages: {e:#}"),
2321                ));
2322            } else if let Err(e) = wait_for_soma_skills(
2323                &mut atlas,
2324                &deploy
2325                    .skill
2326                    .iter()
2327                    .map(|entry| entry.name.clone())
2328                    .collect::<Vec<_>>(),
2329                &mut transport_checks,
2330            )
2331            .await
2332            {
2333                failures.push(("skill".to_string(), "soma".to_string(), format!("{e:#}")));
2334            }
2335        }
2336        Ok(failures)
2337    };
2338
2339    // Race bringup against the signal streams. On a mid-boot signal the
2340    // pinned future is dropped at the end of this scope (cancelling bringup
2341    // at its current await point), which releases its `&mut children` borrow
2342    // so we can tear down whatever was spawned so far.
2343    let mut interrupted_during_boot = false;
2344    let outcome: Result<Vec<(String, String, String)>> = {
2345        tokio::pin!(bringup);
2346        tokio::select! {
2347            o = &mut bringup => o,
2348            _ = sigint.recv() => { interrupted_during_boot = true; Ok(Vec::new()) }
2349            _ = sigterm.recv() => { interrupted_during_boot = true; Ok(Vec::new()) }
2350        }
2351    };
2352
2353    if interrupted_during_boot {
2354        output::action(
2355            "Interrupted",
2356            &format!("tearing down {} partial child(ren)", children.len()),
2357        );
2358        scribe::info(
2359            "bootstrap",
2360            &format!(
2361                "boot interrupted by signal — tearing down {} partial children",
2362                children.len()
2363            ),
2364        );
2365        persist_state(
2366            &state_path,
2367            &manifest_path,
2368            &atlas_endpoint,
2369            started_at_ms,
2370            &children,
2371        );
2372        let providers = component_records(&children);
2373        let complete = teardown::teardown(Some(&atlas_endpoint), &providers, Some(&boot_id)).await;
2374        if !complete {
2375            anyhow::bail!(
2376                "interrupted boot left identity-mismatched process groups; preserving {}",
2377                state_path.display()
2378            );
2379        }
2380        for sp in &mut children {
2381            let _ = sp.child.wait().await;
2382        }
2383        let _ = std::fs::remove_file(&state_path);
2384        return Ok(());
2385    }
2386
2387    let failures = match outcome {
2388        Ok(failures) => failures,
2389        Err(e) => {
2390            output::action("Boot failed", &format!("{e:#}"));
2391            // System-builtin failure is still terminal — no point
2392            // pretending the deploy is usable when atlas itself didn't come
2393            // up. Reap whatever we did spawn before bailing.
2394            persist_state(
2395                &state_path,
2396                &manifest_path,
2397                &atlas_endpoint,
2398                started_at_ms,
2399                &children,
2400            );
2401            let providers = component_records(&children);
2402            let complete =
2403                teardown::teardown(Some(&atlas_endpoint), &providers, Some(&boot_id)).await;
2404            if complete {
2405                let _ = std::fs::remove_file(&state_path);
2406            } else {
2407                return Err(e.context(format!(
2408                    "cleanup refused identity-mismatched process groups; preserving {}",
2409                    state_path.display()
2410                )));
2411            }
2412            return Err(e);
2413        }
2414    };
2415
2416    if !failures.is_empty() {
2417        output::boot_section("failures");
2418        for (component, name, err) in &failures {
2419            // Trim the err to a single line — the full stack already lives
2420            // in the per-package log file we listed in the FAIL line.
2421            let one_line = err.lines().next().unwrap_or(err.as_str());
2422            output::boot_fail(name, &format!("[{component}] {one_line}"));
2423        }
2424        eprintln!();
2425        eprintln!(
2426            "  {} of {} packages failed to start; the rest are running. \
2427             `rbnx caps` to inspect, `rbnx shutdown` to tear down.",
2428            failures.len(),
2429            failures.len() + children.len(),
2430        );
2431    }
2432
2433    output::success(&format!(
2434        "{} component(s) up; logs under {}",
2435        children.len(),
2436        log_dir.display()
2437    ));
2438    if failures.is_empty() {
2439        scribe::info("bootstrap", "all components up — waiting for signal");
2440    } else {
2441        scribe::info(
2442            "bootstrap",
2443            &format!(
2444                "{} component(s) up, {} package(s) failed — waiting for signal",
2445                children.len(),
2446                failures.len()
2447            ),
2448        );
2449    }
2450    output::sub_step("Ctrl-C to tear down (or run `rbnx shutdown` from another shell).");
2451
2452    // Wait for SIGINT / SIGTERM (reusing the streams installed before
2453    // bringup), then shut children down.
2454    tokio::select! {
2455        _ = sigint.recv() => {}
2456        _ = sigterm.recv() => {}
2457    }
2458    output::action("Stopping", &format!("{} child(ren)", children.len()));
2459    scribe::info(
2460        "bootstrap",
2461        &format!(
2462            "shutdown signal received, tearing down {} children",
2463            children.len()
2464        ),
2465    );
2466    let providers = component_records(&children);
2467    let complete = teardown::teardown(Some(&atlas_endpoint), &providers, Some(&boot_id)).await;
2468    if !complete {
2469        anyhow::bail!(
2470            "shutdown refused identity-mismatched process groups; preserving {}",
2471            state_path.display()
2472        );
2473    }
2474    // Best-effort wait so we get clean "exited" lines in our own log.
2475    for sp in &mut children {
2476        let _ = sp.child.wait().await;
2477    }
2478    let _ = std::fs::remove_file(&state_path);
2479    Ok(())
2480}
2481
2482fn component_records(children: &[Spawned]) -> Vec<teardown::ComponentRecord> {
2483    children
2484        .iter()
2485        .map(|s| PackageRuntimeRecord {
2486            name: s.name.clone(),
2487            kind: s.kind.clone(),
2488            pid: s.pid,
2489            pgid: s.pgid,
2490            provider_id: s.provider_id.clone(),
2491            driver_contract: s.driver_contract.clone(),
2492            config_json: s.config_json.clone(),
2493            package_dir: s.package_dir.as_ref().map(|p| p.display().to_string()),
2494            stop: s.stop.clone(),
2495        })
2496        .collect()
2497}
2498
2499fn persist_state(
2500    state_path: &Path,
2501    manifest_path: &Path,
2502    atlas_endpoint: &str,
2503    started_at_ms: u64,
2504    children: &[Spawned],
2505) {
2506    let state = teardown::BootState {
2507        manifest_path: manifest_path.display().to_string(),
2508        boot_pid: std::process::id(),
2509        boot_start_time_ticks: robonix_cli::launch::proc_start_time_ticks(std::process::id()),
2510        boot_id: std::env::var("RBNX_BOOT_ID").unwrap_or_default(),
2511        started_at_ms,
2512        atlas_endpoint: atlas_endpoint.to_string(),
2513        components: component_records(children),
2514    };
2515    if let Err(e) = teardown::write_state(state_path, &state) {
2516        output::sub_step(&format!(
2517            "[boot] warning: failed to persist boot state to {}: {e:#}",
2518            state_path.display()
2519        ));
2520    }
2521}
2522
2523/// Use Pilot's parser so preflight honors the same CLI, env and file settings.
2524fn resolve_pilot_config(args: &[String]) -> Result<VlmConfig> {
2525    let argv = std::iter::once("robonix-pilot").chain(args.iter().map(String::as_str));
2526    let args = PilotArgs::try_parse_from(argv).context("parse Pilot arguments")?;
2527    Ok(PilotConfig::resolve(args)?.vlm)
2528}
2529
2530fn require_system_args(
2531    name: &str,
2532    args: &[String],
2533    pilot_preflighted: bool,
2534) -> std::result::Result<(), String> {
2535    if name != "pilot" || pilot_preflighted {
2536        return Ok(());
2537    }
2538    resolve_pilot_config(args)
2539        .map(|_| ())
2540        .map_err(|error| format!("{error:#}"))
2541}
2542
2543/// Model catalog selected for this deployment.
2544#[derive(Debug, Clone)]
2545struct CatalogInfo {
2546    /// Where the path came from: `env`, `manifest`, or `user`.
2547    source: &'static str,
2548    /// Pilot's validated model configuration, when the deployment starts Pilot.
2549    pilot: Option<VlmConfig>,
2550}
2551
2552/// Resolve the catalog path: `ROBONIX_LLM_CATALOG`, then manifest
2553/// `model_catalog:`, then `~/.robonix/models.yaml`.
2554fn resolve_model_catalog(
2555    manifest_catalog: Option<&str>,
2556    manifest_dir: &Path,
2557) -> Option<(PathBuf, &'static str)> {
2558    if let Ok(value) = std::env::var("ROBONIX_LLM_CATALOG") {
2559        let value = value.trim();
2560        if !value.is_empty() {
2561            return Some((PathBuf::from(value), "env"));
2562        }
2563    }
2564    if let Some(value) = manifest_catalog {
2565        let value = value.trim();
2566        if !value.is_empty() {
2567            let path = Path::new(value);
2568            let path = if path.is_absolute() {
2569                path.to_path_buf()
2570            } else {
2571                manifest_dir.join(path)
2572            };
2573            return Some((path, "manifest"));
2574        }
2575    }
2576    let user = dirs::home_dir()?.join(".robonix").join("models.yaml");
2577    user.is_file().then_some((user, "user"))
2578}
2579
2580/// Load and validate a catalog before any system component is spawned, and
2581/// export the path plus the exact `api_key_env` names for consumers.
2582fn validate_model_catalog(
2583    path: &Path,
2584    source: &'static str,
2585    system: &HashMap<String, serde_yaml::Value>,
2586    validate_pilot: bool,
2587) -> Result<CatalogInfo> {
2588    let catalog = ModelCatalog::load(path)
2589        .with_context(|| format!("load model catalog {}", path.display()))?;
2590    let absolute = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
2591    let mut key_envs: Vec<String> = catalog
2592        .models
2593        .iter()
2594        .filter_map(|model| model.api_key_env.clone())
2595        .collect();
2596    key_envs.sort();
2597    key_envs.dedup();
2598    unsafe {
2599        std::env::set_var("ROBONIX_LLM_CATALOG", &absolute);
2600        std::env::set_var("ROBONIX_LLM_KEY_ENVS", key_envs.join(","));
2601    }
2602
2603    let pilot = if validate_pilot {
2604        let args = system_cli_args("pilot", system.get("pilot"), None);
2605        Some(resolve_pilot_config(&args).context("resolve Pilot configuration")?)
2606    } else {
2607        None
2608    };
2609
2610    Ok(CatalogInfo { source, pilot })
2611}
2612
2613fn system_boot_detail(name: &str, args: &[String], catalog: Option<&CatalogInfo>) -> String {
2614    let port = args
2615        .windows(2)
2616        .find(|pair| pair[0] == "--listen")
2617        .and_then(|pair| pair[1].rsplit(':').next())
2618        .map(|port| format!(":{port}"))
2619        .unwrap_or_default();
2620    if name != "pilot" {
2621        return port;
2622    }
2623    let resolved = catalog
2624        .and_then(|info| info.pilot.clone())
2625        .map(Ok)
2626        .unwrap_or_else(|| resolve_pilot_config(args));
2627    let vlm = match resolved {
2628        Ok(vlm) => vlm,
2629        Err(error) => return format!("{port}  invalid VLM configuration: {error:#}"),
2630    };
2631    let id = vlm
2632        .catalog_id
2633        .as_ref()
2634        .map(|id| format!(" catalog={id}"))
2635        .unwrap_or_default();
2636    let source = if vlm.catalog_id.is_some() {
2637        catalog.map_or("env", |info| info.source)
2638    } else {
2639        "explicit"
2640    };
2641    let capacity = vlm
2642        .context_window_tokens
2643        .map(|tokens| format!("context={tokens} (manual)"))
2644        .unwrap_or_else(|| "context=auto".into());
2645    format!(
2646        "{port}  vlm={} endpoint={}{} source={}  {capacity}",
2647        vlm.model,
2648        vlm.endpoint_for_log(),
2649        id,
2650        source
2651    )
2652}
2653
2654/// Translate a `system.<name>:` block into CLI args for the corresponding
2655/// Rust binary. Per-binary mapping kept narrow — adding a new flag means
2656/// touching exactly this function plus the binary's clap struct.
2657///
2658/// `atlas_listen` is the value of `system.atlas.listen` (already resolved
2659/// elsewhere). Consumers that don't carry their own `atlas:` field inherit
2660/// from this so the manifest doesn't have to repeat the address. An
2661/// explicit per-block `atlas:` still wins.
2662/// Extract the `host:port` string each system binary will try to bind.
2663/// Used by the pre-spawn port-availability check. Returns None for
2664/// services we don't gate on (or whose listen field is absent — caller
2665/// then doesn't pre-check).
2666fn system_listen(name: &str, cfg: Option<&serde_yaml::Value>) -> Option<String> {
2667    let map = cfg?.as_mapping()?;
2668    let s = map
2669        .get(serde_yaml::Value::String("listen".into()))?
2670        .as_str()?;
2671    let trimmed = s.trim();
2672    if trimmed.is_empty() || !is_builtin_system(name) {
2673        return None;
2674    }
2675    Some(trimmed.to_string())
2676}
2677
2678/// Probe a host:port. Returns `Ok(())` when nothing is listening (we can
2679/// safely bind), `Err` describing the live owner otherwise. This is a
2680/// race-prone pre-check (someone else can grab the port between probe
2681/// and spawn) but in practice the failure mode it catches — a stale
2682/// previous-boot daemon — has been alive for minutes, not seconds, so
2683/// a single connect attempt is enough.
2684fn port_is_free(listen: &str) -> std::result::Result<(), anyhow::Error> {
2685    use std::net::{TcpStream, ToSocketAddrs};
2686    let addrs: Vec<_> = listen
2687        .to_socket_addrs()
2688        .with_context(|| format!("parse listen='{listen}' as socket addr"))?
2689        .collect();
2690    for addr in &addrs {
2691        // 200 ms is enough for a local connect; if a daemon is alive on
2692        // 127.0.0.1 the SYN-ACK is sub-ms.
2693        if TcpStream::connect_timeout(addr, std::time::Duration::from_millis(200)).is_ok() {
2694            return Err(anyhow::anyhow!("something is already listening on {addr}"));
2695        }
2696    }
2697    Ok(())
2698}
2699
2700/// Translate supported `system:` manifest fields into CLI args for built-in binaries.
2701fn system_cli_args(
2702    name: &str,
2703    cfg: Option<&serde_yaml::Value>,
2704    atlas_listen: Option<&str>,
2705) -> Vec<String> {
2706    let mut out = Vec::new();
2707    let map = cfg.and_then(|v| v.as_mapping());
2708
2709    // Pass the component's whole manifest config block as one JSON arg. The
2710    // binary parses the keys it needs (e.g. scribe reads `log` via
2711    // robonix_scribe::init_from_config), so new manifest keys flow through
2712    // without per-key plumbing here. The typed flags below remain for the
2713    // fields binaries still read individually.
2714    // `status` is rbnx's own switch; components never see it.
2715    let component_cfg = cfg.map(|v| {
2716        let mut v = v.clone();
2717        if let Some(m) = v.as_mapping_mut() {
2718            m.remove("status");
2719        }
2720        v
2721    });
2722    if let Some(v) = component_cfg.as_ref()
2723        && let Ok(json) = serde_json::to_string(v)
2724    {
2725        out.push("--config-json".into());
2726        out.push(json);
2727    }
2728
2729    let s = |k: &str| -> Option<String> {
2730        map.and_then(|m| {
2731            m.get(serde_yaml::Value::String(k.into()))
2732                .and_then(|v| v.as_str())
2733                .map(|s| s.to_string())
2734        })
2735    };
2736    let nested_str = |outer: &str, inner: &str| -> Option<String> {
2737        map.and_then(|m| m.get(serde_yaml::Value::String(outer.into())))
2738            .and_then(|v| v.as_mapping())
2739            .and_then(|m| m.get(serde_yaml::Value::String(inner.into())))
2740            .and_then(|v| v.as_str())
2741            .map(|s| s.to_string())
2742    };
2743    let nested_tokens = |outer: &str, inner: &str| -> Option<String> {
2744        map.and_then(|m| m.get(serde_yaml::Value::String(outer.into())))
2745            .and_then(|v| v.as_mapping())
2746            .and_then(|m| m.get(serde_yaml::Value::String(inner.into())))
2747            .and_then(|v| v.as_u64())
2748            .map(|tokens| tokens.to_string())
2749    };
2750    let push_pair = |out: &mut Vec<String>, flag: &str, val: Option<String>| {
2751        if let Some(v) = val {
2752            out.push(flag.into());
2753            out.push(v);
2754        }
2755    };
2756    match name {
2757        "atlas" => {
2758            push_pair(&mut out, "--listen", s("listen"));
2759            push_pair(&mut out, "--log", s("log"));
2760            // Atlas walks `<root>/capabilities/**/*.toml` at startup to
2761            // build the contract registry. Honour an explicit override
2762            // from the manifest, otherwise let atlas fall back to its
2763            // own ROBONIX_SOURCE_PATH-derived default (we don't pass
2764            // --capabilities here from rbnx; deploy.rs sets the env var
2765            // on the spawned process so the default path stays correct
2766            // even when manifests don't mention atlas at all).
2767            push_pair(&mut out, "--capabilities", s("capabilities"));
2768        }
2769        "executor" => {
2770            push_pair(&mut out, "--listen", s("listen"));
2771            push_pair(
2772                &mut out,
2773                "--atlas",
2774                s("atlas").or_else(|| atlas_listen.map(str::to_string)),
2775            );
2776            push_pair(&mut out, "--log", s("log"));
2777        }
2778        "pilot" => {
2779            push_pair(&mut out, "--listen", s("listen"));
2780            push_pair(
2781                &mut out,
2782                "--atlas",
2783                s("atlas").or_else(|| atlas_listen.map(str::to_string)),
2784            );
2785            push_pair(&mut out, "--log", s("log"));
2786            // Embedded VLM block.
2787            push_pair(&mut out, "--vlm-upstream", nested_str("vlm", "upstream"));
2788            push_pair(&mut out, "--vlm-api-key", nested_str("vlm", "api_key"));
2789            push_pair(&mut out, "--vlm-model", nested_str("vlm", "model"));
2790            push_pair(
2791                &mut out,
2792                "--vlm-reasoning-effort",
2793                nested_str("vlm", "reasoning_effort"),
2794            );
2795            push_pair(&mut out, "--vlm-format", nested_str("vlm", "api_format"));
2796            push_pair(
2797                &mut out,
2798                "--vlm-context-window-tokens",
2799                nested_tokens("vlm", "context_window_tokens"),
2800            );
2801        }
2802        "liaison" => {
2803            push_pair(&mut out, "--listen", s("listen"));
2804            push_pair(
2805                &mut out,
2806                "--atlas",
2807                s("atlas").or_else(|| atlas_listen.map(str::to_string)),
2808            );
2809            push_pair(&mut out, "--pilot-endpoint", s("pilot_endpoint"));
2810            push_pair(&mut out, "--log", s("log"));
2811        }
2812        "soma" => {
2813            // v2 flat schema: four keys, four CLI flags. rbnx no longer
2814            // passes `--rbnx-bin` (soma calls the on-PATH `rbnx`),
2815            // `--default-robot` / `--deployment` (single robot, deployment
2816            // path derived from --robot-yaml's parent), or
2817            // `--start-packages` (soma always spawns primitives + skills;
2818            // opting out was never actually used). Stage 2 is delivered
2819            // over an inherited pipe fd (see spawn_soma_binary), not
2820            // atlas RPC.
2821            push_pair(&mut out, "--listen", s("listen"));
2822            push_pair(
2823                &mut out,
2824                "--atlas",
2825                s("atlas_endpoint")
2826                    .or_else(|| s("atlas"))
2827                    .or_else(|| atlas_listen.map(str::to_string)),
2828            );
2829            push_pair(&mut out, "--provider-id", s("provider_id"));
2830            push_pair(&mut out, "--robot-yaml", s("robot_yaml"));
2831            push_pair(&mut out, "--deployment-manifest", s("deployment_manifest"));
2832            push_pair(&mut out, "--config", s("config"));
2833            push_pair(&mut out, "--log", s("log"));
2834        }
2835        "chronos" => {
2836            // provider_id and log reach Chronos through --config-json.
2837            push_pair(&mut out, "--listen", s("listen"));
2838            if s("atlas_endpoint").is_none() {
2839                push_pair(&mut out, "--atlas", atlas_listen.map(str::to_string));
2840            }
2841        }
2842        "vitals" => {
2843            push_pair(&mut out, "--listen", s("listen"));
2844            push_pair(
2845                &mut out,
2846                "--atlas",
2847                s("atlas").or_else(|| atlas_listen.map(str::to_string)),
2848            );
2849            push_pair(&mut out, "--id", s("provider_id").or_else(|| s("id")));
2850            push_pair(&mut out, "--thresholds-path", s("thresholds_path"));
2851            push_pair(&mut out, "--soma-endpoint", s("soma_endpoint"));
2852            push_pair(&mut out, "--config", s("config"));
2853            push_pair(&mut out, "--log", s("log"));
2854        }
2855        _ => {}
2856    }
2857    out
2858}
2859
2860/// Spawn one package and wait for its provider to register with Atlas.
2861///
2862/// The selected shared or explicit legacy Driver is verified before
2863/// INIT/ACTIVATE and receives the entry's config. Omission and explicit shared
2864/// selections stay shared-only; only an exact namespace legacy selection may
2865/// accept an upgraded shared runtime Driver.
2866/// Spawn one package and bring it to INACTIVE (skills) or ACTIVE. The process
2867/// joins `children` as soon as it exists, so a Ctrl-C that cancels this future
2868/// mid-way leaves it where the interrupted-boot teardown stops it; a failure
2869/// stops it here and takes it back out.
2870async fn spawn_and_init(
2871    component: &str,
2872    entry: &PackageEntry,
2873    spawn_env: &PackageSpawnEnv<'_>,
2874    atlas: &mut AtlasClient,
2875    children: &mut Vec<Spawned>,
2876) -> Result<()> {
2877    let before = snapshot_provider_ids(atlas)
2878        .await
2879        .with_context(|| format!("[{component}] pre-spawn atlas snapshot"))?;
2880
2881    children.push(spawn_package(component, entry, spawn_env).await?);
2882    let sp = children.last_mut().expect("just pushed");
2883    let result = init_spawned(component, entry, spawn_env, atlas, &before, sp).await;
2884    if result.is_err() {
2885        children.pop();
2886    }
2887    result
2888}
2889
2890async fn init_spawned(
2891    component: &str,
2892    entry: &PackageEntry,
2893    spawn_env: &PackageSpawnEnv<'_>,
2894    atlas: &mut AtlasClient,
2895    before: &ProviderRegistrationSnapshot,
2896    sp: &mut Spawned,
2897) -> Result<()> {
2898    let pkg_label = sp.name.clone();
2899
2900    // One package = one provider. Atlas may reuse a stable provider id on
2901    // takeover, so registration_id (not id alone) correlates this spawn.
2902
2903    // Every error path below terminates the PGID before returning: the caller
2904    // drops this record on error, and the process would otherwise keep what
2905    // the package opened (memsearch's milvus DB lock, executor's gRPC port).
2906    // The provider's SIGTERM handler gets time to run `on_shutdown` before the
2907    // SIGKILL fallback; it may own ROS children in process groups only it
2908    // knows about.
2909    let pgid = sp.pgid;
2910
2911    let registration = match wait_for_registration(
2912        atlas,
2913        before,
2914        &entry.name,
2915        &pkg_label,
2916        component,
2917        spawn_env.log_dir,
2918        &mut sp.child,
2919    )
2920    .await
2921    {
2922        Ok(v) => v,
2923        Err(e) => {
2924            terminate_process_group(pgid, Duration::from_secs(8)).await;
2925            return Err(e);
2926        }
2927    };
2928    let provider_id = registration.provider_id.clone();
2929    if let Some(check) = sp.transport_check.as_mut() {
2930        warn_capability_transports(check, &registration.provider);
2931    }
2932    // The exact-id waiter makes this an internal invariant. Keep the check as
2933    // defense in depth so a future launcher refactor cannot deliver config to
2934    // a provider other than the manifest instance.
2935    if provider_id != entry.name {
2936        let log_file = log_path(spawn_env.log_dir, &pkg_label);
2937        output::boot_fail(
2938            short_label(&pkg_label, component),
2939            &format!(
2940                "deployment instance propagation failed: expected manifest name='{}', \
2941                 observed Capability(id='{}'). Log: {}",
2942                entry.name,
2943                provider_id,
2944                log_file.display()
2945            ),
2946        );
2947        terminate_process_group(pgid, Duration::from_secs(8)).await;
2948        anyhow::bail!(
2949            "[{component}/{pkg_label}] deployment identity invariant failed: manifest name='{}' vs Capability(id='{}')",
2950            entry.name,
2951            provider_id,
2952        );
2953    }
2954
2955    sp.provider_id = Some(provider_id.clone());
2956    let expected_driver_contract = sp
2957        .expected_driver_contract
2958        .as_deref()
2959        .expect("package spawns always carry a lifecycle selection");
2960    let driver_contract = match resolve_runtime_driver_contract(
2961        &provider_id,
2962        &registration.provider_namespace,
2963        expected_driver_contract,
2964        &registration.driver_contracts,
2965        sp.allow_shared_driver_upgrade,
2966    ) {
2967        Ok(contract) => contract,
2968        Err(error) => {
2969            let log_file = log_path(spawn_env.log_dir, &pkg_label);
2970            output::boot_fail(
2971                short_label(&pkg_label, component),
2972                &format!("{error}; log {}", log_file.display()),
2973            );
2974            terminate_process_group(pgid, Duration::from_secs(8)).await;
2975            return Err(error).with_context(|| format!("[{component}/{pkg_label}] lifecycle"));
2976        }
2977    };
2978
2979    if driver_contract != expected_driver_contract {
2980        output::warning(&format!(
2981            "provider '{provider_id}' publishes shared lifecycle Driver '{driver_contract}' for legacy manifest selection '{expected_driver_contract}'; remove the legacy Driver declaration to finish migration"
2982        ));
2983    }
2984
2985    let config_json = serde_json::to_string(&entry.config).with_context(|| {
2986        format!(
2987            "[{component}/{pkg_label}] serialize config for deployment instance '{}'",
2988            entry.name
2989        )
2990    })?;
2991    sp.driver_contract = Some(driver_contract.clone());
2992    sp.config_json = Some(config_json.clone());
2993
2994    let display_label = short_label(&pkg_label, component);
2995    let init_state = match with_spinner(
2996        display_label,
2997        "driver(INIT)…",
2998        call_driver_cmd(
2999            atlas,
3000            &provider_id,
3001            &driver_contract,
3002            component,
3003            &pkg_label,
3004            CMD_INIT,
3005            config_json.clone(),
3006        ),
3007    )
3008    .await
3009    {
3010        Ok(v) => v,
3011        Err(e) => {
3012            terminate_process_group(pgid, Duration::from_secs(8)).await;
3013            return Err(e);
3014        }
3015    };
3016
3017    if component == "skill" {
3018        observe_package_transports(atlas, sp).await;
3019        // Skills stop at INACTIVE post-INIT; the executor sends
3020        // CMD_ACTIVATE on first MCP call (lazy-activate).
3021        output::boot_ok(
3022            display_label,
3023            &format!(
3024                "{}  (skill — awaits executor activate)",
3025                init_state.to_uppercase()
3026            ),
3027        );
3028        return Ok(());
3029    }
3030
3031    let activate_state = match with_spinner(
3032        display_label,
3033        "driver(ACTIVATE)…",
3034        call_driver_cmd(
3035            atlas,
3036            &provider_id,
3037            &driver_contract,
3038            component,
3039            &pkg_label,
3040            CMD_ACTIVATE,
3041            config_json,
3042        ),
3043    )
3044    .await
3045    {
3046        Ok(v) => v,
3047        Err(e) => {
3048            terminate_process_group(pgid, Duration::from_secs(8)).await;
3049            return Err(e);
3050        }
3051    };
3052    // Boot succeeded: provider walked REGISTERED → INACTIVE → ACTIVE. Show
3053    // only the final state — the two intermediate driver calls already
3054    // got their own spinner lines and OK ticks above. provider_id is the
3055    // leftmost label so we don't repeat it here.
3056    let _ = init_state; // intermediate, only kept for the assertion below
3057    observe_package_transports(atlas, sp).await;
3058    output::boot_ok(display_label, &activate_state.to_uppercase());
3059
3060    Ok(())
3061}
3062
3063/// Run `fut` while animating the boot spinner so the user sees the
3064/// `[ ⠙ ] name  msg_prefix N.Ns` line update steadily even when the
3065/// underlying RPC takes a while (Driver(CMD_INIT) for sensor-warm-up
3066/// packages routinely sits at 30+ seconds). Without this the line goes
3067/// silent right after `wait_for_registration` finishes and rbnx looks
3068/// hung between OK lines.
3069async fn with_spinner<F, T>(label: &str, msg_prefix: &str, fut: F) -> T
3070where
3071    F: std::future::Future<Output = T>,
3072{
3073    if output::boot_verbose() {
3074        output::boot_wait(label, msg_prefix);
3075        return fut.await;
3076    }
3077    use std::time::Instant;
3078    let started = Instant::now();
3079    let mut tick = tokio::time::interval(Duration::from_millis(100));
3080    tick.tick().await; // first tick fires immediately; consume so the
3081    // first redraw is delayed by 100 ms (no double-frame at t=0).
3082    tokio::pin!(fut);
3083    let mut frame: usize = 0;
3084    loop {
3085        tokio::select! {
3086            res = &mut fut => return res,
3087            _ = tick.tick() => {
3088                let elapsed = started.elapsed().as_secs_f32();
3089                output::boot_progress(
3090                    label,
3091                    &format!("{msg_prefix} {elapsed:>4.1}s"),
3092                    frame,
3093                );
3094                frame = frame.wrapping_add(1);
3095            }
3096        }
3097    }
3098}
3099
3100fn warn_capability_transports(
3101    check: &mut CapabilityTransportCheck,
3102    provider: &atlas_pb::CapabilityProvider,
3103) {
3104    for warning in check.observe(provider) {
3105        output::warning(&warning);
3106    }
3107}
3108
3109fn load_transport_checks(
3110    entries: &[PackageEntry],
3111    env: &PackageSpawnEnv<'_>,
3112) -> HashMap<String, CapabilityTransportCheck> {
3113    entries
3114        .iter()
3115        .filter_map(|entry| {
3116            let manifest = resolve_entry_path(entry, env.cache_root, env.manifest_dir).and_then(
3117                |path| robonix_cli::manifest::detect_and_load(&path, entry.manifest.as_deref()),
3118            );
3119            match manifest {
3120                Ok(detected) => Some((
3121                    entry.name.clone(),
3122                    CapabilityTransportCheck::new(&entry.name, &detected.manifest),
3123                )),
3124                Err(error) => {
3125                    output::warning(&format!(
3126                        "package '{}': could not read manifest for runtime transport comparison: {error:#}",
3127                        entry.name
3128                    ));
3129                    None
3130                }
3131            }
3132        })
3133        .collect()
3134}
3135
3136async fn observe_package_transports(atlas: &mut AtlasClient, spawned: &mut Spawned) {
3137    let (Some(check), Some(provider_id)) = (
3138        spawned.transport_check.as_mut(),
3139        spawned.provider_id.as_deref(),
3140    ) else {
3141        return;
3142    };
3143    match tokio::time::timeout(
3144        Duration::from_secs(1),
3145        atlas.query_capabilities(provider_id, "", atlas_pb::Transport::Unspecified),
3146    )
3147    .await
3148    {
3149        Ok(Ok(providers)) => {
3150            if let Some(provider) = providers.iter().find(|provider| provider.id == provider_id) {
3151                warn_capability_transports(check, provider);
3152            } else {
3153                output::warning(&format!(
3154                    "package '{provider_id}': no Atlas registration available for runtime transport comparison"
3155                ));
3156            }
3157        }
3158        Ok(Err(error)) => output::warning(&format!(
3159            "package '{provider_id}': could not observe registered capability transports: {error:#}"
3160        )),
3161        Err(_) => output::warning(&format!(
3162            "package '{provider_id}': runtime transport observation timed out after 1s"
3163        )),
3164    }
3165}
3166
3167async fn wait_for_soma_stage1(
3168    atlas: &mut AtlasClient,
3169    primitive_names: &[String],
3170    soma_child: &mut Child,
3171    log_dir: &Path,
3172    transport_checks: &mut HashMap<String, CapabilityTransportCheck>,
3173) -> Result<()> {
3174    const SPINNER_TICK: Duration = Duration::from_millis(100);
3175    const POLLS_PER_TICK: usize = 5; // poll atlas every 500 ms
3176    const SOMA_STAGE1_TIMEOUT: Duration = Duration::from_secs(180);
3177    const SOMA_GET_YAML_CONTRACT: &str = "robonix/system/soma/get_yaml";
3178
3179    let started = Instant::now();
3180    let deadline = started + SOMA_STAGE1_TIMEOUT;
3181    let mut frame: usize = 0;
3182    let mut observed_states: HashMap<String, i32> = HashMap::new();
3183    let mut active_primitives: HashSet<String> = HashSet::new();
3184    let mut reported_failures: HashSet<String> = HashSet::new();
3185    if output::boot_verbose() {
3186        output::boot_wait("primitive", "waiting for Soma-managed providers");
3187    }
3188    loop {
3189        let elapsed_s = started.elapsed().as_secs_f32();
3190        let detail = if primitive_names.is_empty() {
3191            format!("waiting for Soma gRPC readiness… {elapsed_s:>4.1}s")
3192        } else {
3193            format!(
3194                "starting {} primitive package(s)… {elapsed_s:>4.1}s",
3195                primitive_names.len()
3196            )
3197        };
3198        if output::boot_verbose() {
3199            if frame > 0 && frame.is_multiple_of(50) {
3200                output::boot_note("primitive", &detail);
3201            }
3202        } else {
3203            output::boot_progress("primitive", &detail, frame);
3204        }
3205        // Check every tick whether soma is still alive. If it exited
3206        // (typically: `missing robot_yaml`, `read Soma config`, port
3207        // bind failure), surface that immediately with the tail of
3208        // its own log rather than sitting on this spinner for the
3209        // full SOMA_STAGE1_TIMEOUT (180s) which frustrates operators
3210        // and blocks CI. try_wait is non-blocking; Ok(Some(_)) means
3211        // the child has been reaped and the OS-level status is known.
3212        if let Ok(Some(status)) = soma_child.try_wait() {
3213            let mut provider_failures = Vec::new();
3214            for name in primitive_names {
3215                let log_file = log_dir.join(format!("{name}.log"));
3216                if let Some(cause) = read_provider_failure(&log_file) {
3217                    if reported_failures.insert(name.clone()) {
3218                        output::boot_fail(
3219                            name,
3220                            &format!("ERROR; {cause}; log {}", log_file.display()),
3221                        );
3222                    }
3223                    provider_failures.push((name, cause, log_file));
3224                }
3225            }
3226            if !provider_failures.is_empty() {
3227                let names = provider_failures
3228                    .iter()
3229                    .map(|(name, _, _)| name.as_str())
3230                    .collect::<Vec<_>>()
3231                    .join(", ");
3232                let logs = provider_failures
3233                    .iter()
3234                    .map(|(_, _, path)| path.display().to_string())
3235                    .collect::<Vec<_>>()
3236                    .join(", ");
3237                output::boot_fail(
3238                    "primitive",
3239                    &format!("soma exited after provider failure(s): {names}"),
3240                );
3241                anyhow::bail!(
3242                    "Soma exited with {status:?} after provider failure(s): {names}; logs: {logs}"
3243                );
3244            }
3245
3246            let log_file = log_dir.join("soma.log");
3247            let tail = read_log_tail(&log_file, 20);
3248            output::boot_fail(
3249                "primitive",
3250                &format!(
3251                    "soma exited before becoming ACTIVE (status={status:?}); see {}",
3252                    log_file.display()
3253                ),
3254            );
3255            let hint = if tail.is_empty() {
3256                String::new()
3257            } else {
3258                format!("\n--- soma.log tail ---\n{tail}\n--- end ---")
3259            };
3260            anyhow::bail!(
3261                "soma exited with {status:?} before primitive readiness; \
3262                 log: {}{hint}",
3263                log_file.display()
3264            );
3265        }
3266        if frame.is_multiple_of(POLLS_PER_TICK) {
3267            for name in primitive_names {
3268                let providers = atlas
3269                    .query_capabilities(name, "", atlas_pb::Transport::Unspecified)
3270                    .await
3271                    .with_context(|| format!("poll primitive '{name}' during Soma bring-up"))?;
3272                let Some(provider) = providers.into_iter().find(|provider| provider.id == *name)
3273                else {
3274                    continue;
3275                };
3276                if let Some(check) = transport_checks.get_mut(name) {
3277                    warn_capability_transports(check, &provider);
3278                }
3279                let previous = observed_states.insert(name.clone(), provider.state);
3280                if previous != Some(provider.state) {
3281                    let state = lifecycle_state_label(provider.state);
3282                    if provider.state == atlas_pb::LifecycleState::StateActive as i32 {
3283                        output::boot_ok(name, "ACTIVE");
3284                        active_primitives.insert(name.clone());
3285                    } else if provider.state == atlas_pb::LifecycleState::StateError as i32 {
3286                        let log_file = log_dir.join(format!("{name}.log"));
3287                        let detail = read_provider_failure(&log_file).map_or_else(
3288                            || format!("ERROR; log {}", log_file.display()),
3289                            |cause| format!("ERROR; {cause}; log {}", log_file.display()),
3290                        );
3291                        output::boot_fail(name, &detail);
3292                        reported_failures.insert(name.clone());
3293                    } else if output::boot_verbose() {
3294                        output::boot_note(name, state);
3295                    }
3296                }
3297            }
3298            let providers = atlas
3299                .query_capabilities("soma", SOMA_GET_YAML_CONTRACT, atlas_pb::Transport::Grpc)
3300                .await
3301                .context("wait for Soma primitive readiness")?;
3302            if let Some(soma) = providers.into_iter().find(|p| p.id == "soma")
3303                && soma.state == atlas_pb::LifecycleState::StateActive as i32
3304                && soma_grpc_ready(atlas, SOMA_GET_YAML_CONTRACT).await
3305            {
3306                for name in primitive_names {
3307                    if !active_primitives.contains(name) {
3308                        output::boot_ok(name, "ACTIVE");
3309                    }
3310                }
3311                return Ok(());
3312            }
3313        }
3314        if Instant::now() >= deadline {
3315            output::boot_fail(
3316                "primitive",
3317                &format!(
3318                    "timeout after {:?}; service bring-up needs primitives ACTIVE first",
3319                    SOMA_STAGE1_TIMEOUT
3320                ),
3321            );
3322            anyhow::bail!(
3323                "Soma primitive bring-up did not become ready within {:?}; refusing to start service packages before primitives are ready",
3324                SOMA_STAGE1_TIMEOUT
3325            );
3326        }
3327        tokio::time::sleep(SPINNER_TICK).await;
3328        frame = frame.wrapping_add(1);
3329    }
3330}
3331
3332fn lifecycle_state_label(state: i32) -> &'static str {
3333    if state == atlas_pb::LifecycleState::StateRegistered as i32 {
3334        "REGISTERED"
3335    } else if state == atlas_pb::LifecycleState::StateInactive as i32 {
3336        "INACTIVE"
3337    } else if state == atlas_pb::LifecycleState::StateActive as i32 {
3338        "ACTIVE"
3339    } else if state == atlas_pb::LifecycleState::StateError as i32 {
3340        "ERROR"
3341    } else if state == atlas_pb::LifecycleState::StateTerminated as i32 {
3342        "TERMINATED"
3343    } else {
3344        "STARTING"
3345    }
3346}
3347
3348async fn wait_for_soma_skills(
3349    atlas: &mut AtlasClient,
3350    skill_names: &[String],
3351    transport_checks: &mut HashMap<String, CapabilityTransportCheck>,
3352) -> Result<()> {
3353    const TIMEOUT: Duration = Duration::from_secs(180);
3354    if skill_names.is_empty() {
3355        return Ok(());
3356    }
3357    let deadline = Instant::now() + TIMEOUT;
3358    let mut observed_states: HashMap<String, i32> = HashMap::new();
3359    let mut ready: HashSet<String> = HashSet::new();
3360    while Instant::now() < deadline {
3361        for name in skill_names {
3362            let providers = atlas
3363                .query_capabilities(name, "", atlas_pb::Transport::Unspecified)
3364                .await
3365                .with_context(|| format!("poll skill '{name}' during soma bring-up"))?;
3366            let Some(provider) = providers.into_iter().find(|provider| provider.id == *name) else {
3367                continue;
3368            };
3369            if let Some(check) = transport_checks.get_mut(name) {
3370                warn_capability_transports(check, &provider);
3371            }
3372            if observed_states.insert(name.clone(), provider.state) != Some(provider.state) {
3373                let state = lifecycle_state_label(provider.state);
3374                if provider.state == atlas_pb::LifecycleState::StateInactive as i32
3375                    || provider.state == atlas_pb::LifecycleState::StateActive as i32
3376                {
3377                    output::boot_ok(name, state);
3378                    ready.insert(name.clone());
3379                } else if provider.state == atlas_pb::LifecycleState::StateError as i32 {
3380                    output::boot_fail(name, "ERROR; see soma.log and provider log");
3381                    anyhow::bail!("skill '{name}' entered ERROR during Soma bring-up");
3382                } else if output::boot_verbose() {
3383                    output::boot_note(name, state);
3384                }
3385            }
3386        }
3387        if ready.len() == skill_names.len() {
3388            return Ok(());
3389        }
3390        tokio::time::sleep(Duration::from_millis(200)).await;
3391    }
3392    let pending = skill_names
3393        .iter()
3394        .filter(|name| !ready.contains(*name))
3395        .cloned()
3396        .collect::<Vec<_>>();
3397    for name in &pending {
3398        output::boot_fail(
3399            name,
3400            "registration/INIT timeout; see soma.log and provider log",
3401        );
3402    }
3403    anyhow::bail!(
3404        "Soma skill bring-up timed out after {TIMEOUT:?}: {}",
3405        pending.join(", ")
3406    )
3407}
3408
3409/// Read the last `max_lines` lines of a file for embedding into an
3410/// error message. Best-effort: an unreadable/missing file returns an
3411/// empty string rather than an error — the caller already reports the
3412/// path, we just enrich when we can. We read the whole file (soma.log
3413/// is scribe-managed and stays small during boot), split, and take
3414/// the tail — no seek-from-end acrobatics needed for the boot-time
3415/// use case.
3416fn read_log_tail(path: &Path, max_lines: usize) -> String {
3417    let Ok(contents) = std::fs::read_to_string(path) else {
3418        return String::new();
3419    };
3420    let lines: Vec<&str> = contents.lines().collect();
3421    let start = lines.len().saturating_sub(max_lines);
3422    lines[start..].join("\n")
3423}
3424
3425/// Return the provider's actual lifecycle failure rather than whichever
3426/// shutdown record happened to be written last. Scribe records are JSONL;
3427/// providers commonly report lifecycle transitions at info level, so prefer
3428/// `-> ERROR (...)` messages before falling back to an error-level record.
3429fn read_provider_failure(path: &Path) -> Option<String> {
3430    let contents = std::fs::read_to_string(path).ok()?;
3431    let mut error_level_fallback = None;
3432    for line in contents.lines().rev() {
3433        let Ok(record) = serde_json::from_str::<serde_json::Value>(line) else {
3434            continue;
3435        };
3436        let Some(message) = record.get("msg").and_then(|value| value.as_str()) else {
3437            continue;
3438        };
3439        if let Some((_, cause)) = message.split_once(" -> ERROR (") {
3440            return Some(cause.strip_suffix(')').unwrap_or(cause).to_string());
3441        }
3442        if error_level_fallback.is_none()
3443            && record.get("level").and_then(|value| value.as_str()) == Some("error")
3444        {
3445            error_level_fallback = Some(message.to_string());
3446        }
3447    }
3448    error_level_fallback
3449}
3450
3451/// Summarize a package that exited before Atlas registration. Providers often
3452/// forward Python tracebacks through Scribe at info level, so the lifecycle-
3453/// specific parser above may intentionally return None. In that case the last
3454/// structured message is the most useful single-line cause for boot output.
3455fn read_provider_exit_summary(path: &Path) -> Option<String> {
3456    if let Some(cause) = read_provider_failure(path) {
3457        return Some(cause);
3458    }
3459    let contents = std::fs::read_to_string(path).ok()?;
3460    for line in contents.lines().rev() {
3461        if let Ok(record) = serde_json::from_str::<serde_json::Value>(line)
3462            && let Some(message) = record.get("msg").and_then(|value| value.as_str())
3463            && !message.trim().is_empty()
3464        {
3465            return Some(message.trim().to_string());
3466        }
3467        if !line.trim().is_empty() {
3468            return Some(line.trim().to_string());
3469        }
3470    }
3471    None
3472}
3473
3474async fn soma_grpc_ready(atlas: &mut AtlasClient, contract_id: &str) -> bool {
3475    let Ok((channel_id, endpoint, _params)) = atlas
3476        .connect_capability(
3477            DEPLOY_CONSUMER_ID,
3478            "soma",
3479            contract_id,
3480            atlas_pb::Transport::Grpc,
3481        )
3482        .await
3483    else {
3484        return false;
3485    };
3486    let normalized = if endpoint.starts_with("http") {
3487        endpoint
3488    } else {
3489        format!("http://{endpoint}")
3490    };
3491    let ready = match Endpoint::new(normalized.clone()) {
3492        Ok(endpoint) => tokio::time::timeout(Duration::from_secs(1), endpoint.connect())
3493            .await
3494            .is_ok_and(|r| r.is_ok()),
3495        Err(_) => false,
3496    };
3497    let _ = atlas.disconnect_capability(&channel_id).await;
3498    ready
3499}
3500
3501/// Write the `stage2\n` trigger into the pipe rbnx and soma share
3502/// (see `spawn_soma_binary`). This is a one-shot: soma reads the
3503/// line, unblocks its skill-package launcher, and closes its read
3504/// end. rbnx-side we drop the writer here — no reason to hold it
3505/// open, and closing gives soma an immediate EOF on the (very
3506/// unlikely) chance it re-reads.
3507///
3508/// If we don't have a writer (soma wasn't spawned by us, e.g.
3509/// --skip-system), this is a no-op with a warning: someone else
3510/// owns soma's fd and there's nothing rbnx can meaningfully do.
3511fn write_stage2_trigger(writer: &mut Option<std::fs::File>) -> Result<()> {
3512    use std::io::Write;
3513    let Some(mut w) = writer.take() else {
3514        output::boot_skip(
3515            "skill",
3516            "start skipped: no trigger writer (Soma was not spawned by this rbnx)",
3517        );
3518        return Ok(());
3519    };
3520    w.write_all(b"stage2\n")
3521        .context("write 'stage2' to soma stage-trigger pipe")?;
3522    w.flush().context("flush soma stage-trigger pipe")?;
3523    // "written", not "delivered": all we know at this point is that
3524    // the bytes hit the pipe. Actual delivery (soma reads the line,
3525    // spawns skills, and their MCP tools/caps register) is verified
3526    // downstream by the boot-poll cap-wait loop, not here.
3527    Ok(())
3528}
3529
3530/// Issue one Driver(cmd) RPC against a freshly-connected channel, then
3531/// release the channel. Returns the response's `state` string on success;
3532/// bail-errors when ok=false or the RPC itself fails. Used by the boot
3533/// path for both CMD_INIT and CMD_ACTIVATE, with identical timeout / channel
3534/// hygiene.
3535async fn call_driver_cmd(
3536    atlas: &mut AtlasClient,
3537    provider_id: &str,
3538    driver_contract: &str,
3539    component: &str,
3540    pkg_label: &str,
3541    cmd: u32,
3542    config_json: String,
3543) -> Result<String> {
3544    let cmd_name = match cmd {
3545        CMD_INIT => "INIT",
3546        CMD_ACTIVATE => "ACTIVATE",
3547        CMD_DEACTIVATE => "DEACTIVATE",
3548        CMD_SHUTDOWN => "SHUTDOWN",
3549        _ => "?",
3550    };
3551    let (channel_id, endpoint, _params) = atlas
3552        .connect_capability(
3553            DEPLOY_CONSUMER_ID,
3554            provider_id,
3555            driver_contract,
3556            atlas_pb::Transport::Grpc,
3557        )
3558        .await
3559        .with_context(|| {
3560            format!("[{component}/{pkg_label}] ConnectCapability for {driver_contract}")
3561        })?;
3562    let normalized = if endpoint.starts_with("http") {
3563        endpoint
3564    } else {
3565        format!("http://{endpoint}")
3566    };
3567    let result = async {
3568        let driver_timeout = driver_init_timeout();
3569        let channel = Endpoint::new(normalized.clone())
3570            .with_context(|| format!("invalid driver endpoint '{normalized}'"))?
3571            .connect()
3572            .await
3573            .with_context(|| format!("dial driver at '{normalized}'"))?;
3574        let svc_name = contract_id_to_service_name(driver_contract);
3575        let path: tonic::codegen::http::uri::PathAndQuery =
3576            format!("/robonix.contracts.{svc_name}/Driver")
3577                .parse()
3578                .with_context(|| format!("build gRPC path for '{driver_contract}'"))?;
3579        let mut grpc = tonic::client::Grpc::new(channel);
3580        grpc.ready().await.with_context(|| "gRPC ready")?;
3581        let codec: tonic_prost::ProstCodec<DriverRequest, DriverResponse> = Default::default();
3582        let resp = tokio::time::timeout(
3583            driver_timeout,
3584            grpc.unary(
3585                Request::new(DriverRequest {
3586                    command: cmd,
3587                    config_json,
3588                }),
3589                path,
3590                codec,
3591            ),
3592        )
3593        .await
3594        .map_err(|_| {
3595            anyhow::anyhow!(
3596                "Driver(CMD_{cmd_name}) timed out after {}s",
3597                driver_timeout.as_secs()
3598            )
3599        })?
3600        .with_context(|| format!("Driver(CMD_{cmd_name}) RPC failed"))?;
3601        Ok::<_, anyhow::Error>(resp.into_inner())
3602    }
3603    .await;
3604    let _ = atlas.disconnect_capability(&channel_id).await;
3605    let r = result
3606        .map_err(|e| anyhow::anyhow!("[{component}/{pkg_label}] Driver(CMD_{cmd_name}): {e:#}"))?;
3607    if !r.ok {
3608        anyhow::bail!(
3609            "[{component}/{pkg_label}] Driver(CMD_{cmd_name}) returned ok=false (state={}, error={})",
3610            r.state,
3611            r.error
3612        );
3613    }
3614    Ok(r.state)
3615}
3616
3617/// Strip the leading `<component>_` from the boot-log pkg_label.
3618/// `system_memory` → `memory`; `primitive_tiago_chassis` → `tiago_chassis`.
3619/// Keeps boot-output columns narrow (the section header above already
3620/// said which class the entry belongs to).
3621fn short_label<'a>(pkg_label: &'a str, component: &str) -> &'a str {
3622    pkg_label
3623        .strip_prefix(&format!("{component}_"))
3624        .unwrap_or(pkg_label)
3625}
3626
3627/// Poll atlas until a provider NOT in `before` appears. Returns the new
3628/// `provider_id` plus every distinct lifecycle Driver observed after the
3629/// declaration settle window. The caller verifies this list before sending
3630/// config or lifecycle commands.
3631async fn wait_for_registration(
3632    atlas: &mut AtlasClient,
3633    before: &ProviderRegistrationSnapshot,
3634    expected_provider_id: &str,
3635    pkg_label: &str,
3636    component: &str,
3637    log_dir: &Path,
3638    child: &mut Child,
3639) -> Result<RegistrationOutcome> {
3640    if before.contains_key(expected_provider_id) {
3641        anyhow::bail!(
3642            "[{component}/{pkg_label}] deployment instance '{expected_provider_id}' \
3643             was already registered before spawn"
3644        );
3645    }
3646
3647    // Wait for this manifest instance's exact id with a fresh registration
3648    // generation. Unrelated providers can register concurrently and must not
3649    // receive this instance's lifecycle config.
3650    const SPINNER_TICK: Duration = Duration::from_millis(100);
3651    const POLLS_PER_TICK: u32 = 2; // poll atlas every 200 ms
3652    let started = Instant::now();
3653    let register_timeout = driver_register_timeout();
3654    let deadline = started + register_timeout;
3655    let mut frame: usize = 0;
3656    let display_label = short_label(pkg_label, component);
3657    if output::boot_verbose() {
3658        output::boot_wait(display_label, "registering with atlas");
3659    }
3660    loop {
3661        let elapsed_s = started.elapsed().as_secs_f32();
3662        let detail = format!("registering with atlas… {elapsed_s:>4.1}s");
3663        if output::boot_verbose() {
3664            if frame > 0 && frame.is_multiple_of(50) {
3665                output::boot_note(display_label, &detail);
3666            }
3667        } else {
3668            output::boot_progress(display_label, &detail, frame);
3669        }
3670        // A package wrapper that exits before registering can never recover.
3671        // Detect it on every spinner tick instead of waiting out the full
3672        // registration timeout and then continuing with a misleading generic
3673        // timeout. The caller still terminates the package PGID so any child
3674        // processes left behind by a failed start hook are reaped.
3675        match child.try_wait() {
3676            Ok(Some(status)) => {
3677                let log_file = log_path(log_dir, pkg_label);
3678                let cause = read_provider_exit_summary(&log_file)
3679                    .unwrap_or_else(|| "no diagnostic message in provider log".to_string());
3680                output::boot_fail(
3681                    display_label,
3682                    &format!(
3683                        "start process exited ({status}); {cause}; log {}",
3684                        log_file.display()
3685                    ),
3686                );
3687                anyhow::bail!(
3688                    "[{component}/{pkg_label}] start process exited ({status}) before Atlas registration: {cause}. Log: {}",
3689                    log_file.display()
3690                );
3691            }
3692            Ok(None) => {}
3693            Err(error) => {
3694                anyhow::bail!(
3695                    "[{component}/{pkg_label}] inspect start process while waiting for Atlas registration: {error}"
3696                );
3697            }
3698        }
3699        if frame.is_multiple_of(POLLS_PER_TICK as usize) {
3700            let providers = atlas
3701                .query_capabilities("", "", atlas_pb::Transport::Unspecified)
3702                .await
3703                .with_context(|| format!("[{component}/{pkg_label}] poll atlas"))?;
3704            let matched = providers.iter().find(|provider| {
3705                robonix_cli::launch::is_expected_provider_registration(
3706                    provider,
3707                    before,
3708                    expected_provider_id,
3709                )
3710            });
3711            if let Some(first) = matched {
3712                let provider_id = first.id.clone();
3713                let registration_id = first.registration_id.clone();
3714                // RegisterPrimitive/Service/Skill and DeclareCapability are
3715                // two separate RPCs from the package side — Register lands
3716                // first, declares follow within a few hundred ms. Give it
3717                // up to a 1 s settle window so we don't false-fire a missing
3718                // Driver error on a fast poll. Capped by the outer
3719                // `deadline` so we never exceed user-facing timeout.
3720                let settle_until = Instant::now()
3721                    .checked_add(Duration::from_millis(1000))
3722                    .map(|t| t.min(deadline))
3723                    .unwrap_or(deadline);
3724                let mut current: atlas_pb::CapabilityProvider = (*first).clone();
3725                // Consume the complete settle window so a package that
3726                // declares both shared and legacy Drivers cannot hide the
3727                // second declaration behind the first successful poll.
3728                loop {
3729                    if Instant::now() >= settle_until {
3730                        break;
3731                    }
3732                    tokio::time::sleep(Duration::from_millis(100)).await;
3733                    let providers = atlas
3734                        .query_capabilities(&provider_id, "", atlas_pb::Transport::Unspecified)
3735                        .await
3736                        .with_context(|| format!("[{component}/{pkg_label}] re-poll for driver"))?;
3737                    match providers.into_iter().find(|p| p.id == provider_id) {
3738                        Some(p) if p.registration_id == registration_id => current = p,
3739                        Some(p) => {
3740                            let log_file = log_path(log_dir, pkg_label);
3741                            output::boot_fail(
3742                                display_label,
3743                                &format!(
3744                                    "provider '{provider_id}' registration changed during settle — see {}",
3745                                    log_file.display(),
3746                                ),
3747                            );
3748                            anyhow::bail!(
3749                                "[{component}/{pkg_label}] provider '{provider_id}' registration changed during settle ('{registration_id}' -> '{}'). Log: {}",
3750                                p.registration_id,
3751                                log_file.display(),
3752                            );
3753                        }
3754                        None => {
3755                            // Provider vanished between the original match
3756                            // and now (crashed mid-settle, atlas evicted,
3757                            // heartbeat lapsed). Report loudly so downstream
3758                            // boot logic cannot march on against a dead process.
3759                            let log_file = log_path(log_dir, pkg_label);
3760                            output::boot_fail(
3761                                display_label,
3762                                &format!(
3763                                    "provider '{provider_id}' disappeared during settle — see {}",
3764                                    log_file.display()
3765                                ),
3766                            );
3767                            anyhow::bail!(
3768                                "[{component}/{pkg_label}] provider '{provider_id}' \
3769                                 unregistered during settle window. Log: {}",
3770                                log_file.display()
3771                            );
3772                        }
3773                    }
3774                }
3775                let mut driver_contracts = current
3776                    .capabilities
3777                    .iter()
3778                    .filter(|capability| {
3779                        capability.transport == atlas_pb::Transport::Grpc as i32
3780                            && capability.contract_id.ends_with("/driver")
3781                    })
3782                    .map(|capability| capability.contract_id.clone())
3783                    .collect::<Vec<_>>();
3784                driver_contracts.sort();
3785                driver_contracts.dedup();
3786                return Ok(RegistrationOutcome {
3787                    provider: current.clone(),
3788                    provider_id,
3789                    provider_kind: current.kind,
3790                    provider_namespace: current.namespace,
3791                    registration_id: current.registration_id,
3792                    driver_contracts,
3793                });
3794            }
3795        }
3796        if Instant::now() >= deadline {
3797            let log_file = log_path(log_dir, pkg_label);
3798            output::boot_fail(
3799                display_label,
3800                &format!(
3801                    "registration timeout after {:?}; expected instance '{}' — see {}",
3802                    register_timeout,
3803                    expected_provider_id,
3804                    log_file.display()
3805                ),
3806            );
3807            anyhow::bail!(
3808                "[{component}/{pkg_label}] timed out after {:?} — package never registered expected deployment instance '{}' with atlas. Log: {}",
3809                register_timeout,
3810                expected_provider_id,
3811                log_file.display()
3812            );
3813        }
3814        tokio::time::sleep(SPINNER_TICK).await;
3815        frame = frame.wrapping_add(1);
3816    }
3817}
浙ICP备2023005800号-2 浙公网安备33010902005384号