Skip to main content

robonix_cli/
manifest.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2// Manifest parsing and validation for robonix-cli.
3//
4// New (dev-packaging) spec: `package_manifest.yaml` with a single top-level
5// `build` + `start` shell string, a list of `capabilities`, optional
6// `depends`. One package = one `start` body — no `nodes: [...]` list, no
7// `-n` flag.
8//
9// Legacy (pre-dev-packaging) spec still accepted for backward compatibility:
10//   - filename `robonix_manifest.yaml`
11//   - `package.id` (used as identity if `name` is missing)
12//   - `build: { script: <path> }` instead of top-level `build: <string>`
13//   - `nodes: [{id, type, start}, ...]` instead of top-level `start: <string>`
14//     → node `start` blocks are concatenated and run as a single background
15//       process group (best-effort; use the new spec for deterministic order).
16//
17// `node` / `runtime` terminology is gone from the spec — "node" is deprecated
18// in favour of "capability"; "runtime" is "system".
19
20use anyhow::{Context, Result};
21use robonix_scribe::warn;
22use serde::Deserialize;
23use std::collections::{HashMap, HashSet};
24use std::path::{Path, PathBuf};
25
26/// Preferred per-package manifest filename. Legacy `robonix_manifest.yaml`
27/// is also accepted by [`detect_manifest_path`].
28pub const MANIFEST_FILE: &str = "package_manifest.yaml";
29pub const LEGACY_MANIFEST_FILE: &str = "robonix_manifest.yaml";
30pub const SHARED_LIFECYCLE_DRIVER_CONTRACT: &str = "robonix/lifecycle/driver";
31
32/// Cache directory name for a URL-backed deploy package.
33///
34/// The name comes from the repository, not the configured provider id: one
35/// repository can supply more than one configured instance.
36pub fn deploy_repo_dir_name(url: &str) -> String {
37    url.trim_end_matches('/')
38        .trim_end_matches(".git")
39        .rsplit('/')
40        .next()
41        .filter(|segment| !segment.is_empty())
42        .unwrap_or("pkg")
43        .to_string()
44}
45
46/// Single source of truth for which `system:` keys are shipped binaries
47/// rather than packages under `<robonix_source>/system/<key>/`.
48pub const SYSTEM_BUILTINS: &[&str] = &[
49    "atlas", "chronos", "executor", "pilot", "liaison", "soma", "vitals",
50];
51
52pub fn is_builtin_system(name: &str) -> bool {
53    SYSTEM_BUILTINS.contains(&name)
54}
55
56/// The built-in components nothing runs without: the registry, the executor
57/// and the body. The others (chronos, pilot, liaison, vitals) may be disabled.
58pub const SYSTEM_REQUIRED: &[&str] = &["atlas", "executor", "soma"];
59
60/// Whether a deployment entry says `status: disabled`. `enabled`, or no
61/// `status` at all, means on; any other value is a mistake worth stopping
62/// for rather than guessing at.
63pub fn entry_disabled(entry: &serde_yaml::Value, at: &str) -> Result<bool> {
64    match entry.get("status") {
65        None => Ok(false),
66        Some(v) => match v.as_str() {
67            Some("enabled") => Ok(false),
68            Some("disabled") => Ok(true),
69            _ => anyhow::bail!("{at}: status must be `enabled` or `disabled`, not {v:?}"),
70        },
71    }
72}
73
74/// Take the entries marked `status: disabled` out of a deployment, and
75/// name them. [`prepare_deployment_manifest`] does this, so rbnx and soma
76/// both see the deployment without them; rbnx calls it first to report them. A disabled entry stays in the file, `url`, `branch` and
77/// `config` included; nothing builds, starts or updates it until it is
78/// enabled again. Atlas, executor and soma cannot be disabled
79/// ([`SYSTEM_REQUIRED`]): without them nothing else runs.
80pub fn drop_disabled(root: &mut serde_yaml::Value) -> Result<Vec<String>> {
81    let mut dropped = Vec::new();
82    let Some(map) = root.as_mapping_mut() else {
83        return Ok(dropped);
84    };
85    for section in ["primitive", "service", "skill"] {
86        let Some(entries) = map.get_mut(section).and_then(|v| v.as_sequence_mut()) else {
87            continue;
88        };
89        let mut kept = Vec::with_capacity(entries.len());
90        for (i, entry) in std::mem::take(entries).into_iter().enumerate() {
91            let at = format!("{section}[{i}]");
92            if entry_disabled(&entry, &at)? {
93                let name = entry.get("name").and_then(|n| n.as_str()).unwrap_or(&at);
94                dropped.push(format!("{section} {name}"));
95            } else {
96                kept.push(entry);
97            }
98        }
99        *entries = kept;
100    }
101    if let Some(system) = map.get_mut("system").and_then(|v| v.as_mapping_mut()) {
102        let keys: Vec<serde_yaml::Value> = system.keys().cloned().collect();
103        for key in keys {
104            let name = key.as_str().unwrap_or_default().to_string();
105            let at = format!("system.{name}");
106            let entry = &system[&key];
107            if entry_disabled(entry, &at)? {
108                if SYSTEM_REQUIRED.contains(&name.as_str()) {
109                    anyhow::bail!("{at}: atlas, executor and soma cannot be disabled");
110                }
111                system.remove(&key);
112                dropped.push(format!("system {name}"));
113            }
114        }
115    }
116    Ok(dropped)
117}
118
119/// Apply deployment `env:` and expand `$VAR` / `${VAR}` in every scalar.
120///
121/// `rbnx` and Soma call this same entry point before parsing a deployment so
122/// they cannot disagree about paths, selected manifests, or package config.
123pub fn prepare_deployment_manifest(
124    mut root: serde_yaml::Value,
125    robonix_source_path: Option<&Path>,
126) -> Result<serde_yaml::Value> {
127    if std::env::var_os("ROBONIX_SOURCE_PATH").is_none()
128        && let Some(path) = robonix_source_path
129    {
130        // This runs before package child processes start.
131        unsafe { std::env::set_var("ROBONIX_SOURCE_PATH", path) };
132    }
133    let env: HashMap<String, String> = root
134        .get("env")
135        .cloned()
136        .map(serde_yaml::from_value)
137        .transpose()
138        .context("parse top-level env")?
139        .unwrap_or_default();
140    let expanded: Vec<(&String, String)> = env
141        .iter()
142        .map(|(key, value)| (key, expand_deployment_env(value)))
143        .collect();
144    for (key, value) in expanded {
145        unsafe { std::env::set_var(key, value) };
146    }
147    expand_deployment_yaml(&mut root);
148    drop_disabled(&mut root)?;
149    Ok(root)
150}
151
152/// Validate package instance identities in one deployment.
153///
154/// Every primitive, service, and skill entry ``name`` becomes an Atlas provider
155/// id. The ids must therefore be non-empty, whitespace-normalized, and unique
156/// across package sections. Built-in system processes resolve their provider
157/// ids through component-specific configuration and are checked against the
158/// live Atlas registry when package startup begins.
159pub fn validate_deployment_instance_names(root: &serde_yaml::Value) -> Result<()> {
160    let mut seen = HashSet::new();
161    let mut record = |name: &str, location: &str| -> Result<()> {
162        let trimmed = name.trim();
163        if trimmed.is_empty() {
164            anyhow::bail!("{location} must declare a non-empty `name`");
165        }
166        if name != trimmed {
167            anyhow::bail!("{location} `name` must not contain leading or trailing whitespace");
168        }
169        if !seen.insert(name.to_string()) {
170            anyhow::bail!(
171                "duplicate deployment instance name '{name}' at {location}; \
172                 every primitive, service, and skill instance must be unique"
173            );
174        }
175        Ok(())
176    };
177
178    for section in ["primitive", "service", "skill"] {
179        let Some(entries) = root.get(section) else {
180            continue;
181        };
182        let entries = entries
183            .as_sequence()
184            .ok_or_else(|| anyhow::anyhow!("deployment `{section}` must be a list"))?;
185        for (index, entry) in entries.iter().enumerate() {
186            let name = entry
187                .get("name")
188                .and_then(serde_yaml::Value::as_str)
189                .unwrap_or("");
190            record(name, &format!("{section}[{index}]"))?;
191        }
192    }
193    Ok(())
194}
195
196pub fn expand_deployment_env(s: &str) -> String {
197    let mut out = String::with_capacity(s.len());
198    let bytes = s.as_bytes();
199    let mut i = 0;
200    while i < bytes.len() {
201        if bytes[i] == b'$' && i + 1 < bytes.len() {
202            if bytes[i + 1] == b'{' {
203                if let Some(end) = s[i + 2..].find('}') {
204                    out.push_str(&std::env::var(&s[i + 2..i + 2 + end]).unwrap_or_default());
205                    i = i + 2 + end + 1;
206                    continue;
207                }
208            } else if bytes[i + 1].is_ascii_alphabetic() || bytes[i + 1] == b'_' {
209                let start = i + 1;
210                let mut end = start;
211                while end < bytes.len()
212                    && (bytes[end].is_ascii_alphanumeric() || bytes[end] == b'_')
213                {
214                    end += 1;
215                }
216                out.push_str(&std::env::var(&s[start..end]).unwrap_or_default());
217                i = end;
218                continue;
219            }
220        }
221        let ch = s[i..].chars().next().expect("non-empty by loop guard");
222        out.push(ch);
223        i += ch.len_utf8();
224    }
225    out
226}
227
228/// Split deployment-owned package fields from a non-builtin `system:`
229/// package's runtime configuration.
230///
231/// The canonical shape mirrors primitive/service/skill entries:
232/// `manifest:` selects the package manifest and nested `config:` is delivered
233/// through Driver(CMD_INIT). Historical system entries put config keys beside
234/// `manifest`; keep accepting those keys with a migration warning. If both
235/// forms are present, nested `config:` wins on duplicate keys so deployments
236/// can migrate incrementally without changing runtime values.
237pub fn split_system_package_config(
238    value: &serde_yaml::Value,
239) -> Result<(Option<String>, serde_yaml::Value)> {
240    let Some(source) = value.as_mapping() else {
241        return Ok((None, value.clone()));
242    };
243    let mut fields = source.clone();
244    let manifest_key = serde_yaml::Value::String("manifest".to_string());
245    let config_key = serde_yaml::Value::String("config".to_string());
246    let manifest = match fields.remove(&manifest_key) {
247        Some(raw_manifest) => Some(
248            raw_manifest
249                .as_str()
250                .map(str::trim)
251                .filter(|name| !name.is_empty())
252                .ok_or_else(|| {
253                    anyhow::anyhow!("system package `manifest` must be a non-empty string")
254                })?
255                .to_string(),
256        ),
257        None => None,
258    };
259
260    let nested = fields.remove(&config_key);
261    if nested.is_none() {
262        if !fields.is_empty() {
263            warn!(
264                "system package uses deprecated flat runtime config keys; move them under `config:` (flat keys remain supported for compatibility)"
265            );
266        }
267        return Ok((manifest, serde_yaml::Value::Mapping(fields)));
268    }
269
270    let nested = nested.expect("checked as present above");
271    let nested = match nested {
272        serde_yaml::Value::Null => serde_yaml::Mapping::new(),
273        serde_yaml::Value::Mapping(mapping) => mapping,
274        _ => anyhow::bail!("system package `config` must be a mapping"),
275    };
276    if !fields.is_empty() {
277        warn!(
278            "system package mixes deprecated flat runtime config keys with nested `config:`; nested values take precedence"
279        );
280    }
281    for (key, value) in nested {
282        fields.insert(key, value);
283    }
284    Ok((manifest, serde_yaml::Value::Mapping(fields)))
285}
286
287fn expand_deployment_yaml(value: &mut serde_yaml::Value) {
288    match value {
289        serde_yaml::Value::String(s) => *s = expand_deployment_env(s),
290        serde_yaml::Value::Sequence(sequence) => {
291            for item in sequence {
292                expand_deployment_yaml(item);
293            }
294        }
295        serde_yaml::Value::Mapping(mapping) => {
296            for (_, item) in mapping.iter_mut() {
297                expand_deployment_yaml(item);
298            }
299        }
300        _ => {}
301    }
302}
303
304#[derive(Debug, Clone)]
305pub struct DetectedManifest {
306    pub path: PathBuf,
307    pub manifest: Manifest,
308}
309
310#[derive(Debug, Clone)]
311pub struct PackageSummary {
312    pub name: String,
313    pub version: String,
314    pub capabilities: Vec<String>,
315    pub depends: Vec<String>,
316}
317
318#[derive(Debug, Clone, Default)]
319pub struct Manifest {
320    pub manifest_version: u32,
321    pub package: Package,
322    pub build: String,
323    pub start: String,
324    pub stop: String,
325    pub capabilities: Vec<CapabilityRef>,
326    pub depends: Vec<DependsRef>,
327    /// True iff the manifest was parsed from legacy fields (id/nodes/build.script).
328    /// `rbnx` prints a deprecation warning in this case.
329    pub is_legacy: bool,
330}
331
332#[derive(Debug, Clone, Default, Deserialize)]
333pub struct Package {
334    /// New spec: `package.name`. Legacy spec allowed a separate `package.id`
335    /// — if present and `name` is missing, we fall back to `id`.
336    #[serde(default)]
337    pub name: String,
338    #[serde(default)]
339    pub id: Option<String>,
340    #[serde(default)]
341    pub version: String,
342    /// Legacy publisher label retained for manifest compatibility. It is not
343    /// used as package identity or Catalog metadata; new manifests should use
344    /// `name`, `tags`, and `maintainers` instead.
345    #[serde(default)]
346    pub vendor: String,
347    #[serde(default)]
348    pub description: String,
349    #[serde(default)]
350    pub tags: Vec<String>,
351    #[serde(default)]
352    pub maintainers: Vec<String>,
353    #[serde(default)]
354    pub license: String,
355}
356
357/// A contract and the transports served by this package.
358#[derive(Debug, Clone, Deserialize)]
359pub struct CapabilityRef {
360    /// Contract id (matches one of the TOMLs under `capabilities/`).
361    pub name: String,
362    /// Declared transports; empty only for manifests that omit the field.
363    #[serde(default, deserialize_with = "deserialize_transports")]
364    pub transport: Vec<String>,
365    /// Optional path to a package-local TOML that overrides / defines
366    /// this capability (for experimental providers not yet in the official
367    /// capabilities directory). Relative to the package root.
368    #[serde(default, alias = "definition")]
369    pub path: Option<String>,
370}
371
372fn deserialize_transports<'de, D>(deserializer: D) -> std::result::Result<Vec<String>, D::Error>
373where
374    D: serde::Deserializer<'de>,
375{
376    #[derive(Deserialize)]
377    #[serde(untagged)]
378    enum Transports {
379        One(String),
380        Many(Vec<String>),
381    }
382    let transports = match Transports::deserialize(deserializer)? {
383        Transports::One(value) => vec![value],
384        Transports::Many(values) => values,
385    };
386    if transports.is_empty() {
387        return Err(serde::de::Error::custom("transport list must not be empty"));
388    }
389    let mut seen = HashSet::new();
390    for transport in &transports {
391        if !matches!(transport.as_str(), "mcp" | "grpc" | "ros2") {
392            return Err(serde::de::Error::custom(format!(
393                "invalid transport '{transport}'; expected mcp, grpc or ros2"
394            )));
395        }
396        if !seen.insert(transport) {
397            return Err(serde::de::Error::custom(format!(
398                "duplicate transport '{transport}'"
399            )));
400        }
401    }
402    Ok(transports)
403}
404
405/// One entry under a package's `depends:` list. Models a *source / lib*
406/// dependency (think Linux kernel module SOFT_DEPS) — i.e. another
407/// package whose codegen output / Python package this package needs at
408/// build or import time. NOT a boot-order dependency.
409///
410/// `name` is required (the depended-on package's `package.name`).
411/// Exactly one of `path` / `url` should be set:
412///   - `path`: filesystem path relative to this package's manifest dir
413///   - `url`:  git URL (cloned to `<pkg>/rbnx-build/deps/<name>/` on first build)
414///     Neither set means "expect it to already be installed / on PYTHONPATH".
415#[derive(Debug, Clone, Deserialize)]
416pub struct DependsRef {
417    pub name: String,
418    #[serde(default)]
419    pub path: Option<String>,
420    #[serde(default)]
421    pub url: Option<String>,
422    #[serde(default)]
423    pub branch: Option<String>,
424}
425
426// ── raw shape accepting both old and new ────────────────────────────────
427
428#[derive(Debug, Clone, Deserialize, Default)]
429struct RawManifest {
430    #[serde(rename = "manifestVersion", default)]
431    manifest_version: u32,
432    #[serde(default)]
433    package: Package,
434    /// Accept either a plain shell string (new) or `{ script: <path> }` (legacy).
435    #[serde(default)]
436    build: Option<BuildField>,
437    /// New: top-level shell string.
438    #[serde(default)]
439    start: Option<String>,
440    /// Optional package-owned cleanup command, symmetric with `start`.
441    #[serde(default)]
442    stop: Option<String>,
443    /// Legacy: list of nodes, each with its own `start` block.
444    #[serde(default)]
445    nodes: Vec<LegacyNode>,
446    #[serde(default)]
447    capabilities: Vec<CapabilityRef>,
448    #[serde(default)]
449    depends: Vec<DependsRef>,
450    /// Legacy `provider_id:` field. Removed from spec — accepted by serde but
451    /// ignored. rbnx-boot now discovers the provider_id by polling atlas for any provider
452    /// that registered after `start.sh` spawned. Future warning: emit deprecation.
453    #[serde(default)]
454    #[allow(dead_code)]
455    provider_id: Option<String>,
456}
457
458#[derive(Debug, Clone, Deserialize)]
459#[serde(untagged)]
460enum BuildField {
461    Shell(String),
462    Script { script: String },
463}
464
465#[derive(Debug, Clone, Deserialize)]
466struct LegacyNode {
467    #[serde(default)]
468    #[allow(dead_code)]
469    id: String,
470    #[serde(default, rename = "type")]
471    #[allow(dead_code)]
472    node_type: Option<String>,
473    #[serde(default)]
474    start: String,
475}
476
477/// Locate a package's manifest file inside `package_root`.
478///
479/// `override_name` lets a deploy entry select a non-default manifest file
480/// (the `manifest:` field on a deploy `PackageEntry`) so one package can
481/// ship per-deployment-target variants — e.g. `package_manifest.yaml`
482/// (x86 + docker), `package_manifest.jetson-native.yaml`, and
483/// `package_manifest.jetson-docker.yaml`, each with its own build/start —
484/// without changing the manifest schema itself. When set, the named file
485/// MUST exist (a typo'd target should fail loud, not silently fall back to
486/// the default manifest and build the wrong thing). When `None`, the
487/// default `package_manifest.yaml` (then legacy) is used as before.
488pub fn detect_manifest_path(package_root: &Path, override_name: Option<&str>) -> Result<PathBuf> {
489    if let Some(name) = override_name {
490        let p = package_root.join(name);
491        if p.is_file() {
492            return Ok(p);
493        }
494        anyhow::bail!(
495            "manifest override `{name}` not found in {} — the deploy entry's \
496             `manifest:` field names a file the package does not ship",
497            package_root.display()
498        );
499    }
500    let new_path = package_root.join(MANIFEST_FILE);
501    if new_path.exists() {
502        return Ok(new_path);
503    }
504    let legacy = package_root.join(LEGACY_MANIFEST_FILE);
505    if legacy.exists() {
506        return Ok(legacy);
507    }
508    anyhow::bail!("Package does not have {MANIFEST_FILE} (or legacy {LEGACY_MANIFEST_FILE})")
509}
510
511pub fn detect_and_load(
512    package_root: &Path,
513    override_name: Option<&str>,
514) -> Result<DetectedManifest> {
515    let path = detect_manifest_path(package_root, override_name)?;
516    let manifest = load_from_path(&path)?;
517    Ok(DetectedManifest { path, manifest })
518}
519
520pub fn load_from_path(manifest_path: &Path) -> Result<Manifest> {
521    let content = std::fs::read_to_string(manifest_path)
522        .with_context(|| format!("Failed to read manifest: {}", manifest_path.display()))?;
523    let raw: RawManifest = serde_yaml::from_str(&content)
524        .with_context(|| format!("Failed to parse manifest: {}", manifest_path.display()))?;
525    let manifest = normalize(raw, manifest_path);
526    manifest.validate_capabilities(manifest_path.parent().unwrap_or(Path::new(".")))?;
527    Ok(manifest)
528}
529
530fn normalize(raw: RawManifest, manifest_path: &Path) -> Manifest {
531    let mut is_legacy = false;
532    let filename_is_legacy = manifest_path
533        .file_name()
534        .and_then(|n| n.to_str())
535        .map(|s| s == LEGACY_MANIFEST_FILE)
536        .unwrap_or(false);
537
538    // package.name fallback to package.id (legacy used id as canonical name).
539    let mut package = raw.package;
540    if package.name.trim().is_empty()
541        && let Some(id) = &package.id
542        && !id.trim().is_empty()
543    {
544        package.name = id.clone();
545        is_legacy = true;
546    }
547
548    // build: string (new) or { script } (legacy).
549    let build = match raw.build {
550        Some(BuildField::Shell(s)) => s,
551        Some(BuildField::Script { script }) => {
552            is_legacy = true;
553            format!("bash {script}")
554        }
555        None => String::new(),
556    };
557
558    // start: top-level string (new) or concatenate nodes (legacy).
559    let start = match (raw.start, raw.nodes.is_empty()) {
560        (Some(s), _) => s,
561        (None, false) => {
562            is_legacy = true;
563            // Concatenate legacy node start blocks. Each block gets wrapped
564            // in a subshell and backgrounded; a `wait` at the end keeps
565            // `rbnx start` alive until all nodes exit. This is a best-effort
566            // port — for deterministic deploys, migrate to the new spec.
567            let parts: Vec<String> = raw
568                .nodes
569                .iter()
570                .filter(|n| !n.start.trim().is_empty())
571                .map(|n| format!("( {} ) &", n.start.trim()))
572                .collect();
573            if parts.is_empty() {
574                String::new()
575            } else {
576                format!("{}\nwait", parts.join("\n"))
577            }
578        }
579        (None, true) => String::new(),
580    };
581
582    let stop = raw.stop.unwrap_or_default();
583
584    if filename_is_legacy {
585        is_legacy = true;
586    }
587
588    Manifest {
589        manifest_version: raw.manifest_version,
590        package,
591        build,
592        start,
593        stop,
594        capabilities: raw.capabilities,
595        depends: raw.depends,
596        is_legacy,
597    }
598}
599
600impl Manifest {
601    fn validate_capabilities(&self, package_root: &Path) -> Result<()> {
602        let mut names = HashSet::new();
603        for capability in &self.capabilities {
604            if !names.insert(&capability.name) {
605                anyhow::bail!(
606                    "package '{}': repeated capability contract '{}'",
607                    self.package.name,
608                    capability.name
609                );
610            }
611            if capability.transport.is_empty() {
612                crate::output::warning(&format!(
613                    "package '{}': capability '{}' is missing `transport`; declare mcp, grpc or ros2 (or a non-empty list)",
614                    self.package.name, capability.name
615                ));
616            }
617        }
618
619        if self.capabilities.iter().all(|c| c.transport.is_empty()) {
620            return Ok(());
621        }
622        let mut roots = Vec::new();
623        let source = std::env::var_os("ROBONIX_SOURCE_PATH")
624            .map(PathBuf::from)
625            .or_else(|| {
626                package_root
627                    .ancestors()
628                    .find(|root| {
629                        root.join("Cargo.toml").is_file() && root.join("capabilities").is_dir()
630                    })
631                    .map(Path::to_path_buf)
632            })
633            .or_else(|| {
634                let path = crate::Config::config_file_path().ok()?;
635                let content = std::fs::read_to_string(path).ok()?;
636                serde_yaml::from_str::<crate::Config>(&content)
637                    .ok()?
638                    .robonix_source_path
639            });
640        if let Some(source) = source {
641            roots.push(source.join("capabilities"));
642        }
643        roots.push(package_root.join("capabilities"));
644        let roots: Vec<&Path> = roots
645            .iter()
646            .filter(|root| root.is_dir())
647            .map(PathBuf::as_path)
648            .collect();
649        let contracts =
650            robonix_atlas::contract_registry::ContractRegistry::load_from_capability_roots(&roots)?;
651        for capability in &self.capabilities {
652            let local = capability.path.as_ref().map(|path| package_root.join(path));
653            let explicit_mode = if let Some(path) = local.filter(|path| path.is_file()) {
654                let value: toml::Value = toml::from_str(&std::fs::read_to_string(&path)?)
655                    .with_context(|| format!("parse contract {}", path.display()))?;
656                value
657                    .get("mode")
658                    .and_then(|v| v.get("type"))
659                    .and_then(toml::Value::as_str)
660                    .map(str::to_string)
661            } else {
662                None
663            };
664            let Some(mode) = explicit_mode.as_deref().or_else(|| {
665                contracts
666                    .get(&capability.name)
667                    .map(|contract| contract.mode.as_str())
668            }) else {
669                continue;
670            };
671            for transport in &capability.transport {
672                let allowed = match mode {
673                    "rpc" => true,
674                    "rpc_server_stream" | "rpc_client_stream" | "rpc_bidirectional_stream" => {
675                        transport == "grpc"
676                    }
677                    "topic_out" | "topic_in" => transport == "grpc" || transport == "ros2",
678                    _ => false,
679                };
680                if !allowed {
681                    anyhow::bail!(
682                        "package '{}': capability '{}' transport '{}' is incompatible with contract mode '{}'",
683                        self.package.name,
684                        capability.name,
685                        transport,
686                        mode
687                    );
688                }
689            }
690        }
691        Ok(())
692    }
693
694    /// Return the Driver written in `capabilities:`, if any.
695    pub fn explicit_lifecycle_driver_contract(&self) -> Result<Option<&str>> {
696        let drivers = self
697            .capabilities
698            .iter()
699            .filter(|capability| capability.name.ends_with("/driver"))
700            .map(|capability| capability.name.as_str())
701            .collect::<Vec<_>>();
702        if drivers.len() > 1 {
703            anyhow::bail!(
704                "package '{}' declares multiple lifecycle Driver contracts: {}; declare at most one shared or legacy Driver, never both",
705                self.package.name,
706                drivers.join(", ")
707            );
708        }
709        Ok(drivers.first().copied())
710    }
711
712    /// Resolve the lifecycle contract selected by this package manifest.
713    ///
714    /// Omission selects the shared Driver so every current provider has a
715    /// managed lifecycle. An explicitly declared legacy namespace Driver is
716    /// preserved exactly. Runtime launchers may select the exact legacy
717    /// namespace Driver when an older generated package lacks the shared
718    /// binding; if neither binding exists, startup fails.
719    pub fn selected_lifecycle_driver_contract(&self) -> Result<&str> {
720        Ok(self
721            .explicit_lifecycle_driver_contract()?
722            .unwrap_or(SHARED_LIFECYCLE_DRIVER_CONTRACT))
723    }
724
725    pub fn validate_and_summarize(&self) -> Result<PackageSummary> {
726        if self.manifest_version == 0 {
727            anyhow::bail!("Invalid 'manifestVersion': must be >= 1");
728        }
729        let p = &self.package;
730        for (name, val) in [
731            ("package.name", &p.name),
732            ("package.version", &p.version),
733            ("package.description", &p.description),
734            ("package.license", &p.license),
735        ] {
736            if val.trim().is_empty() {
737                anyhow::bail!("Missing '{name}' in manifest");
738            }
739        }
740        // `build` remains optional — packages that ship pre-built binaries
741        // can omit it. `start` is required for `rbnx start` to do anything.
742        if self.start.trim().is_empty() {
743            anyhow::bail!(
744                "manifest.start is required (shell string, run at package root). \
745                 If migrating from the legacy spec with `nodes: [...]`, either \
746                 concatenate their start blocks into one top-level `start:` or \
747                 split into multiple packages."
748            );
749        }
750
751        // Validate lifecycle selection in every package entry point (build,
752        // install, start and validate), before any provider is launched.
753        self.selected_lifecycle_driver_contract()?;
754
755        if self.is_legacy {
756            warn!(
757                "package '{}' uses legacy manifest fields (package.id / nodes[] / \
758                 build.script / robonix_manifest.yaml). These still work but are \
759                 deprecated — migrate to the new spec (package_manifest.yaml with \
760                 top-level build/start strings + capabilities).",
761                self.package.name
762            );
763        }
764
765        Ok(PackageSummary {
766            name: p.name.clone(),
767            version: p.version.clone(),
768            capabilities: self.capabilities.iter().map(|c| c.name.clone()).collect(),
769            depends: self.depends.iter().map(|d| d.name.clone()).collect(),
770        })
771    }
772}
773
774#[cfg(test)]
775mod tests {
776    #[test]
777    fn disabled_entries_leave_the_deployment_and_say_so() {
778        let mut root: serde_yaml::Value = serde_yaml::from_str(
779            "primitive:\n  - {name: cam, path: cam}\n  - {name: arm, path: arm, status: disabled}\n\
780             service:\n  - {name: memory, url: https://x/m.git, status: enabled}\n\
781             skill:\n  - {name: find, url: https://x/f.git, status: disabled}\n\
782             system:\n  atlas: {status: enabled}\n  pilot: {}\n  scene: {status: disabled}\n  vitals: {status: disabled}\n",
783        )
784        .unwrap();
785        let dropped = drop_disabled(&mut root).unwrap();
786        assert_eq!(
787            dropped,
788            [
789                "primitive arm",
790                "skill find",
791                "system scene",
792                "system vitals"
793            ]
794        );
795        assert!(root["system"].get("vitals").is_none() && root["system"].get("atlas").is_some());
796        assert_eq!(root["primitive"].as_sequence().unwrap().len(), 1);
797        assert_eq!(root["service"].as_sequence().unwrap().len(), 1);
798        assert!(root["skill"].as_sequence().unwrap().is_empty());
799        assert!(root["system"].get("scene").is_none() && root["system"].get("pilot").is_some());
800    }
801
802    #[test]
803    fn a_misspelt_status_or_a_disabled_required_component_stops_the_boot() {
804        let mut typo: serde_yaml::Value =
805            serde_yaml::from_str("service:\n  - {name: m, path: m, status: off}\n").unwrap();
806        assert!(
807            drop_disabled(&mut typo)
808                .unwrap_err()
809                .to_string()
810                .contains("service[0]")
811        );
812        for name in SYSTEM_REQUIRED {
813            let mut required: serde_yaml::Value =
814                serde_yaml::from_str(&format!("system:\n  {name}: {{status: disabled}}\n"))
815                    .unwrap();
816            assert!(drop_disabled(&mut required).is_err(), "{name}");
817        }
818    }
819
820    use super::*;
821
822    fn load_transport_manifest(capabilities: &str, mode: Option<&str>) -> Result<Manifest> {
823        let root = std::env::temp_dir().join(format!("rbnx-transport-{}", uuid::Uuid::new_v4()));
824        std::fs::create_dir_all(root.join("capabilities")).unwrap();
825        if let Some(mode) = mode {
826            std::fs::write(
827                root.join("capabilities/example.v1.toml"),
828                format!("[contract]\nid = 'test/contract'\n[mode]\ntype = '{mode}'\n"),
829            )
830            .unwrap();
831        }
832        let path = root.join(MANIFEST_FILE);
833        std::fs::write(
834            &path,
835            format!(
836                "manifestVersion: 1\npackage:\n  name: test.package\n  version: 1.0.0\n  description: Test package\n  license: MIT\nstart: 'true'\ncapabilities:\n{capabilities}\n"
837            ),
838        )
839        .unwrap();
840        let result = load_from_path(&path);
841        std::fs::remove_dir_all(root).unwrap();
842        result
843    }
844
845    #[test]
846    fn capability_transports_accept_scalar_list_and_missing() {
847        for (field, expected) in [
848            ("transport: mcp", vec!["mcp"]),
849            ("transport: [grpc, ros2]", vec!["grpc", "ros2"]),
850            ("", vec![]),
851        ] {
852            let manifest = load_transport_manifest(
853                &format!("  - name: test/contract\n    {field}"),
854                Some("rpc"),
855            )
856            .unwrap();
857            assert_eq!(manifest.manifest_version, 1);
858            assert_eq!(manifest.capabilities[0].transport, expected);
859            manifest.validate_and_summarize().unwrap();
860        }
861    }
862
863    #[test]
864    fn invalid_or_duplicate_transports_are_rejected() {
865        for field in [
866            "transport: http",
867            "transport: [grpc, http]",
868            "transport: []",
869            "transport: [grpc, grpc]",
870            "transport: 42",
871            "transport: null",
872        ] {
873            assert!(
874                load_transport_manifest(&format!("  - name: test/contract\n    {field}"), None)
875                    .is_err(),
876                "{field}"
877            );
878        }
879    }
880
881    #[test]
882    fn repeated_contracts_are_rejected_even_with_different_transports() {
883        let error = load_transport_manifest(
884            "  - {name: test/contract, transport: grpc}\n  - {name: test/contract, transport: ros2}",
885            None,
886        )
887        .unwrap_err();
888        assert!(
889            error
890                .to_string()
891                .contains("repeated capability contract 'test/contract'")
892        );
893    }
894
895    #[test]
896    fn transports_must_fit_contract_mode_when_known() {
897        for (mode, allowed) in [
898            ("rpc", vec!["mcp", "grpc", "ros2"]),
899            ("rpc_server_stream", vec!["grpc"]),
900            ("rpc_client_stream", vec!["grpc"]),
901            ("rpc_bidirectional_stream", vec!["grpc"]),
902            ("topic_out", vec!["grpc", "ros2"]),
903            ("topic_in", vec!["grpc", "ros2"]),
904        ] {
905            for transport in ["mcp", "grpc", "ros2"] {
906                let result = load_transport_manifest(
907                    &format!("  - {{name: test/contract, transport: {transport}}}"),
908                    Some(mode),
909                );
910                if allowed.contains(&transport) {
911                    result.unwrap();
912                } else {
913                    let message = result.unwrap_err().to_string();
914                    assert!(
915                        message.contains("incompatible with contract mode"),
916                        "{message}"
917                    );
918                    assert!(message.contains(mode) && message.contains(transport));
919                }
920            }
921        }
922        load_transport_manifest("  - {name: test/contract, transport: mcp}", None).unwrap();
923    }
924
925    #[test]
926    fn package_vendor_is_backward_compatible() {
927        let raw: RawManifest = serde_yaml::from_str(
928            r#"
929manifestVersion: 1
930package:
931  name: com.robonix.system.scene
932  version: 0.1.0
933  vendor: robonix
934  description: Legacy package metadata example.
935  license: MulanPSL-2.0
936start: bash scripts/start.sh
937capabilities: []
938"#,
939        )
940        .expect("legacy package.vendor must parse");
941
942        let manifest = normalize(raw, Path::new("package_manifest.yaml"));
943
944        assert_eq!(manifest.package.vendor, "robonix");
945        manifest
946            .validate_and_summarize()
947            .expect("package.vendor must not invalidate an otherwise valid manifest");
948    }
949
950    #[test]
951    fn system_package_manifest_is_separate_from_runtime_config() {
952        let value: serde_yaml::Value = serde_yaml::from_str(
953            r#"
954manifest: package_manifest.jetson-native.yaml
955config:
956  camera_provider_id: front_camera
957  web_port: 50107
958"#,
959        )
960        .unwrap();
961
962        let (manifest, config) = split_system_package_config(&value).unwrap();
963
964        assert_eq!(
965            manifest.as_deref(),
966            Some("package_manifest.jetson-native.yaml")
967        );
968        assert_eq!(config["camera_provider_id"], "front_camera");
969        assert_eq!(config["web_port"], 50107);
970        assert!(config.get("manifest").is_none());
971    }
972
973    #[test]
974    fn legacy_system_package_config_is_unchanged() {
975        let value: serde_yaml::Value = serde_yaml::from_str(
976            r#"
977camera_provider_id: front_camera
978web_port: 50107
979"#,
980        )
981        .unwrap();
982
983        let (manifest, config) = split_system_package_config(&value).unwrap();
984
985        assert!(manifest.is_none());
986        assert_eq!(config, value);
987    }
988
989    #[test]
990    fn nested_system_config_wins_during_incremental_migration() {
991        let value: serde_yaml::Value = serde_yaml::from_str(
992            r#"
993manifest: package_manifest.jetson-native.yaml
994camera_provider_id: legacy_camera
995legacy_only: kept
996config:
997  camera_provider_id: front_camera
998  web_port: 50107
999"#,
1000        )
1001        .unwrap();
1002
1003        let (manifest, config) = split_system_package_config(&value).unwrap();
1004
1005        assert_eq!(
1006            manifest.as_deref(),
1007            Some("package_manifest.jetson-native.yaml")
1008        );
1009        assert_eq!(config["camera_provider_id"], "front_camera");
1010        assert_eq!(config["legacy_only"], "kept");
1011        assert_eq!(config["web_port"], 50107);
1012        assert!(config.get("manifest").is_none());
1013        assert!(config.get("config").is_none());
1014    }
1015
1016    #[test]
1017    fn system_package_config_rejects_non_mapping_values() {
1018        let value: serde_yaml::Value = serde_yaml::from_str("config: front_camera\n").unwrap();
1019        let error = split_system_package_config(&value).unwrap_err();
1020        assert!(error.to_string().contains("`config` must be a mapping"));
1021    }
1022
1023    #[test]
1024    fn system_package_manifest_rejects_non_string_values() {
1025        let value: serde_yaml::Value = serde_yaml::from_str("manifest: 42\n").unwrap();
1026        let error = split_system_package_config(&value).unwrap_err();
1027        assert!(error.to_string().contains("must be a non-empty string"));
1028    }
1029
1030    #[test]
1031    fn deployment_instance_names_are_unique_across_sections() {
1032        let valid: serde_yaml::Value = serde_yaml::from_str(
1033            r#"
1034system:
1035  scene: {}
1036primitive:
1037  - name: front_camera
1038    path: camera
1039  - name: wrist_camera
1040    path: camera
1041service:
1042  - name: navigation
1043    path: navigation
1044"#,
1045        )
1046        .unwrap();
1047        validate_deployment_instance_names(&valid).unwrap();
1048
1049        let duplicate: serde_yaml::Value = serde_yaml::from_str(
1050            r#"
1051system:
1052  scene: {}
1053primitive:
1054  - name: scene
1055    path: camera
1056service:
1057  - name: scene
1058    path: scene
1059"#,
1060        )
1061        .unwrap();
1062        let error = validate_deployment_instance_names(&duplicate)
1063            .unwrap_err()
1064            .to_string();
1065        assert!(error.contains("duplicate deployment instance name 'scene'"));
1066    }
1067
1068    #[test]
1069    fn deployment_instance_names_reject_outer_whitespace() {
1070        let manifest: serde_yaml::Value = serde_yaml::from_str(
1071            r#"
1072primitive:
1073  - name: " front_camera "
1074    path: camera
1075"#,
1076        )
1077        .unwrap();
1078        let error = validate_deployment_instance_names(&manifest)
1079            .unwrap_err()
1080            .to_string();
1081        assert!(error.contains("must not contain leading or trailing whitespace"));
1082    }
1083
1084    #[test]
1085    fn deployment_package_instance_name_is_required() {
1086        let manifest: serde_yaml::Value = serde_yaml::from_str(
1087            r#"
1088primitive:
1089  - path: camera
1090"#,
1091        )
1092        .unwrap();
1093        let error = validate_deployment_instance_names(&manifest)
1094            .unwrap_err()
1095            .to_string();
1096        assert!(error.contains("primitive[0] must declare a non-empty `name`"));
1097    }
1098
1099    #[test]
1100    fn lifecycle_driver_omission_selects_shared_and_explicit_legacy_is_preserved() {
1101        let manifest_with = |capabilities: Vec<&str>| Manifest {
1102            package: Package {
1103                name: "test.package".to_string(),
1104                ..Package::default()
1105            },
1106            capabilities: capabilities
1107                .into_iter()
1108                .map(|name| CapabilityRef {
1109                    name: name.to_string(),
1110                    transport: Vec::new(),
1111                    path: None,
1112                })
1113                .collect(),
1114            ..Manifest::default()
1115        };
1116
1117        assert_eq!(
1118            manifest_with(vec![])
1119                .selected_lifecycle_driver_contract()
1120                .unwrap(),
1121            SHARED_LIFECYCLE_DRIVER_CONTRACT
1122        );
1123        assert_eq!(
1124            manifest_with(vec![SHARED_LIFECYCLE_DRIVER_CONTRACT])
1125                .selected_lifecycle_driver_contract()
1126                .unwrap(),
1127            SHARED_LIFECYCLE_DRIVER_CONTRACT
1128        );
1129        assert_eq!(
1130            manifest_with(vec!["robonix/primitive/camera/driver"])
1131                .selected_lifecycle_driver_contract()
1132                .unwrap(),
1133            "robonix/primitive/camera/driver"
1134        );
1135
1136        let error = manifest_with(vec![
1137            SHARED_LIFECYCLE_DRIVER_CONTRACT,
1138            "robonix/primitive/camera/driver",
1139        ])
1140        .selected_lifecycle_driver_contract()
1141        .unwrap_err()
1142        .to_string();
1143        assert!(error.contains("never both"));
1144    }
1145}
浙ICP备2023005800号-2 浙公网安备33010902005384号