From 533c6e2ed19723ff165c82fe27777001f812d7f0 Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Tue, 13 Oct 2026 17:19:26 +0000 Subject: [PATCH 1/9] test: clone the observation class reused across applies #13056 made ObservationError a non-Copy enum, and #13081 then passed the same value to assert_observation twice, so the SDK's integration test binary stopped compiling on Unix. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Hai Nguyen --- crates/nemoclaw-sdk/tests/kubernetes_interruption.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/nemoclaw-sdk/tests/kubernetes_interruption.rs b/crates/nemoclaw-sdk/tests/kubernetes_interruption.rs index 17175ffe8d3..0b538c64abf 100644 --- a/crates/nemoclaw-sdk/tests/kubernetes_interruption.rs +++ b/crates/nemoclaw-sdk/tests/kubernetes_interruption.rs @@ -416,7 +416,7 @@ async fn assert_failed_connection_keeps_its_class( assert_observation( deployment.apply(&original(), &uncancelled()).await, - class, + class.clone(), "the first apply", ); assert_runtime_applies(scripted, 1, "the first apply"); From fbc7f08a641c54c1819a3e7a3eaad8fcb972d3a6 Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Tue, 13 Oct 2026 17:57:01 +0000 Subject: [PATCH 2/9] fix(config): attribute schema messages to nested rules and keyed unions An x-nemoclaw-error message appeared only when the failing keyword sat directly on the annotated node. Rules built from nested properties, items, allOf, or then steps therefore reported a bare keyword such as `not`, `minLength`, or a raw pattern: the managed Kubernetes endpoint and local-field rule, the Podman engine rule, the Kubernetes environment naming rule, and the root Kubernetes services rule never showed their messages. A oneOf of single-key objects would also have reported every error as "must match one allowed object shape". - Diagnostics use the nearest annotated ancestor, bounded by the definition root and the selected variant, and a missing field uses its own annotation. - A union variant is selected by its kind or management constant, by the one key of a closed single-key object, or by a hardware profile. When no key selects a variant, the error lists the declared keys and never the input's. - Partial-document assessment and editor field lookup select variants the same way. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Hai Nguyen --- .../src/partial_document.rs | 123 +++++-- crates/nemoclaw-authoring/src/sdk_schema.rs | 69 +++- crates/nemoclaw-runtime/src/schema.rs | 174 +++++++++- crates/nemoclaw-sdk/src/config/schema.rs | 3 + .../nemoclaw-sdk/src/config/schema/runtime.rs | 305 ++++++++++++++++-- .../nemoclaw-sdk/tests/config_diagnostics.rs | 17 + .../nemoclaw-sdk/tests/config_kubernetes.rs | 53 +++ crates/nemoclaw-sdk/tests/config_schema.rs | 8 + 8 files changed, 682 insertions(+), 70 deletions(-) diff --git a/crates/nemoclaw-authoring/src/partial_document.rs b/crates/nemoclaw-authoring/src/partial_document.rs index 1a64495522b..6ee277b5b0d 100644 --- a/crates/nemoclaw-authoring/src/partial_document.rs +++ b/crates/nemoclaw-authoring/src/partial_document.rs @@ -5,14 +5,18 @@ use std::sync::LazyLock; -use nemoclaw_sdk::config::{Document, parse_yaml_value, schema::input_schema}; +use nemoclaw_sdk::config::{ + Document, parse_yaml_value, + schema::{input_schema, select_variant}, +}; use serde_json::Value; use crate::{Diagnostics, diagnostics::diagnostic}; use jsonschema::error::ValidationErrorKind as Kind; +static INPUT_SCHEMA: LazyLock = LazyLock::new(input_schema); static INPUT_VALIDATOR: LazyLock = LazyLock::new(|| { - jsonschema::validator_for(&input_schema()).expect("SDK input schema must compile") + jsonschema::validator_for(&INPUT_SCHEMA).expect("SDK input schema must compile") }); /// Authored values before SDK defaults or required-field validation. @@ -86,12 +90,7 @@ impl PartialDocument { /// Inspect the current sparse input. Compound rules remain deferred until /// a partial evaluator can prove whether a branch is impossible or incomplete. pub fn assess(&self) -> PartialAssessment { - let mut issues = INPUT_VALIDATOR - .iter_errors(&self.supplied) - .flat_map(|error| tagged_branch(&error).unwrap_or_else(|| vec![issue(&error)])) - .collect::>(); - issues.sort_by(|left, right| (&left.path, &left.rule).cmp(&(&right.path, &right.rule))); - issues.dedup(); + let issues = schema_issues(&INPUT_SCHEMA, &INPUT_VALIDATOR, &self.supplied); if !issues.is_empty() { return PartialAssessment { issues, @@ -131,26 +130,43 @@ fn issue(error: &jsonschema::ValidationError<'_>) -> PartialIssue { } } -/// For a tagged union such as the gateway, whose `management` names its -/// kind, report the errors inside the branch the input selects, so an -/// invalid field is attributed to that field rather than to the whole union. -fn tagged_branch(error: &jsonschema::ValidationError<'_>) -> Option> { +fn schema_issues( + schema: &Value, + validator: &jsonschema::Validator, + supplied: &Value, +) -> Vec { + let mut issues = validator + .iter_errors(supplied) + .flat_map(|error| attributed(schema, &error)) + .collect::>(); + issues.sort_by(|left, right| (&left.path, &left.rule).cmp(&(&right.path, &right.rule))); + issues.dedup(); + issues +} + +fn attributed(schema: &Value, error: &jsonschema::ValidationError<'_>) -> Vec { + tagged_branch(schema, error).unwrap_or_else(|| vec![issue(error)]) +} + +/// For a union whose input names one branch, such as the gateway's +/// `management` or the single key of an externally tagged object, report the +/// errors inside that branch, so an invalid field is attributed to that field +/// rather than to the whole union. Unions nested in the branch resolve the same way. +fn tagged_branch( + schema: &Value, + error: &jsonschema::ValidationError<'_>, +) -> Option> { let Kind::OneOfNotValid { context } = error.kind() else { return None; }; - let tag = ["management", "kind"] - .into_iter() - .find_map(|tag| error.instance().get(tag).and_then(Value::as_str))?; - let schema = input_schema(); - let branches = schema - .pointer(&error.schema_path().to_string())? - .as_array()?; - let selected = branches.iter().zip(context).find(|(branch, _)| { - ["management", "kind"] + let branches = schema.pointer(error.schema_path().as_str())?.as_array()?; + let selected = context.get(select_variant(branches, error.instance())?)?; + Some( + selected .iter() - .any(|key| branch["properties"][key]["const"].as_str() == Some(tag)) - })?; - Some(selected.1.iter().map(issue).collect()) + .flat_map(|error| attributed(schema, error)) + .collect(), + ) } fn classify(kind: &Kind) -> PartialIssueKind { @@ -173,3 +189,62 @@ fn classify(kind: &Kind) -> PartialIssueKind { _ => PartialIssueKind::Invalid, } } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn keyed(key: &str, schema: Value) -> Value { + json!({"type": "object", "properties": {key: schema}, "required": [key], "additionalProperties": false}) + } + + #[test] + fn issues_inside_a_keyed_variant_of_the_selected_branch_name_their_field() { + let schema = json!({ + "type": "object", + "properties": {"gateway": {"oneOf": [ + { + "type": "object", + "properties": { + "management": {"const": "managed"}, + "target": {"oneOf": [ + keyed("docker", json!({"type": "object"})), + keyed("podman", json!({ + "type": "object", + "properties": {"engine": {"type": "string", "minLength": 1}}, + "required": ["engine"] + })), + ]} + }, + "required": ["management"] + }, + { + "type": "object", + "properties": {"management": {"const": "external"}}, + "required": ["management"] + } + ]}} + }); + let validator = jsonschema::validator_for(&schema).unwrap(); + for (podman, kind, rule) in [ + ( + json!({"engine": ""}), + PartialIssueKind::Invalid, + "minLength", + ), + (json!({}), PartialIssueKind::Missing, "required"), + ] { + let supplied = + json!({"gateway": {"management": "managed", "target": {"podman": podman}}}); + assert_eq!( + schema_issues(&schema, &validator, &supplied), + [PartialIssue { + path: "/gateway/target/podman/engine".into(), + kind, + rule: rule.into(), + }] + ); + } + } +} diff --git a/crates/nemoclaw-authoring/src/sdk_schema.rs b/crates/nemoclaw-authoring/src/sdk_schema.rs index 6d1eaa88be6..1918f9a3f3a 100644 --- a/crates/nemoclaw-authoring/src/sdk_schema.rs +++ b/crates/nemoclaw-authoring/src/sdk_schema.rs @@ -6,7 +6,7 @@ use std::sync::OnceLock; use crate::fingerprint::sha256; -use nemoclaw_sdk::config::schema::input_schema; +use nemoclaw_sdk::config::schema::{input_schema, select_variant}; use nemoclaw_sdk::json_schema::schema_accepts; use serde_json::{Value, json}; @@ -88,7 +88,10 @@ pub(crate) fn sdk_schema_identity() -> String { } pub(crate) fn sdk_field_schema_for(values: &Value, path: &str) -> Option<(Value, bool)> { - let root = schema_root(); + field_schema_in(schema_root(), values, path) +} + +fn field_schema_in(root: &Value, values: &Value, path: &str) -> Option<(Value, bool)> { let mut node = root; let mut required = false; let mut current_path = String::new(); @@ -108,6 +111,17 @@ pub(crate) fn sdk_field_schema_for(values: &Value, path: &str) -> Option<(Value, return Some((field, true)); } node = sdk_selected_branch(node, values.pointer(¤t_path)?)?; + } else if node + .get("properties") + .and_then(|properties| properties.get(&name)) + .is_none() + && let Some(branch) = values + .pointer(¤t_path) + .and_then(|value| sdk_selected_branch(node, value)) + { + // A sparse value can still name its branch, such as the single key + // of an externally tagged object, before that branch is complete. + node = branch; } if node .get("properties") @@ -284,10 +298,16 @@ pub(crate) fn sdk_exclusive_required_fields(schema: &Value) -> Option(schema: &'a Value, supplied: &Value) -> Option<&'a Value> { - let (discriminator, _) = sdk_discriminator(schema)?; + let branches = schema.get("oneOf")?.as_array()?; + let Some((discriminator, _)) = sdk_discriminator(schema) else { + return branches.get(select_variant(branches, supplied)?); + }; let selected = supplied.get(&discriminator)?; - schema.get("oneOf")?.as_array()?.iter().find(|branch| { + branches.iter().find(|branch| { branch .get("properties") .and_then(|properties| properties.get(&discriminator)) @@ -345,3 +365,44 @@ fn follow_ref<'a>(root: &'a Value, mut node: &'a Value) -> Option<&'a Value> { } None } + +#[cfg(test)] +mod tests { + use super::*; + + fn keyed(key: &str, schema: Value) -> Value { + json!({"type": "object", "properties": {key: schema}, "required": [key], "additionalProperties": false}) + } + + #[test] + fn a_field_inside_the_supplied_keyed_variant_has_that_variant_schema() { + let root = json!({ + "type": "object", + "properties": {"target": {"$ref": "#/$defs/Target"}}, + "$defs": { + "Target": {"oneOf": [ + keyed("docker", json!({"$ref": "#/$defs/Docker"})), + keyed("podman", json!({"$ref": "#/$defs/Podman"})), + ]}, + "Docker": { + "type": "object", + "properties": {"engine": {"type": "string"}}, + "additionalProperties": false + }, + "Podman": { + "type": "object", + "properties": {"engine": {"type": "string", "minLength": 1}}, + "required": ["engine"], + "additionalProperties": false + } + } + }); + let values = json!({"target": {"podman": {}}}); + let (schema, required) = field_schema_in(&root, &values, "/target/podman/engine").unwrap(); + assert_eq!(schema["minLength"], 1); + assert!(required); + // Another variant's fields do not apply while the input names this one. + let values = json!({"target": {"docker": {}}}); + assert!(field_schema_in(&root, &values, "/target/podman/engine").is_none()); + } +} diff --git a/crates/nemoclaw-runtime/src/schema.rs b/crates/nemoclaw-runtime/src/schema.rs index 91a973a8d2d..7b902feafd8 100644 --- a/crates/nemoclaw-runtime/src/schema.rs +++ b/crates/nemoclaw-runtime/src/schema.rs @@ -81,31 +81,76 @@ pub enum PathSegment { /// Where a runtime specification value first violates the schema. pub fn violation(value: &Value) -> Option> { let error = VALIDATOR.validate(value).err()?; - Some(segments(innermost(&error))) + Some(segments(innermost(&SCHEMA, &error))) +} + +/// The `oneOf` or `anyOf` variant that an instance names, so a diagnostic can +/// describe that variant's fields instead of the whole union: a `kind` or +/// `management` constant, the one key of an externally tagged variant that +/// the instance contains, or a hardware `profile`. +pub fn select_variant(variants: &[Value], instance: &Value) -> Option { + for tag in ["kind", "management"] { + if let Some(value) = instance.get(tag) + && let Some(index) = variants + .iter() + .position(|variant| variant["properties"][tag].get("const") == Some(value)) + { + return Some(index); + } + } + // Several present keys name no single variant. + let mut named = variants + .iter() + .enumerate() + .filter(|(_, variant)| single_key(variant).is_some_and(|key| instance.get(key).is_some())); + if let (Some((index, _)), None) = (named.next(), named.next()) { + return Some(index); + } + variants.iter().position(|variant| { + variant["properties"].get("profile").is_some() && instance.get("profile").is_some() + }) +} + +/// The declared keys of an externally tagged union, when every variant is a +/// single-key object. They are schema names, never input, so diagnostics may +/// show them. +pub fn variant_keys(variants: &[Value]) -> Option> { + let keys = variants + .iter() + .map(single_key) + .collect::>>()?; + (!keys.is_empty()).then_some(keys) +} + +// An externally tagged variant is a closed object with one required property. +// Exclusive forms that only forbid their alternatives do not qualify. +fn single_key(variant: &Value) -> Option<&str> { + let [key] = variant.get("required")?.as_array()?.as_slice() else { + return None; + }; + let key = key.as_str()?; + let properties = variant.get("properties")?.as_object()?; + (variant.get("additionalProperties") == Some(&Value::Bool(false)) + && properties.len() == 1 + && properties.contains_key(key)) + .then_some(key) } // Report the failing variant that the instance selected, not the union. fn innermost<'e, 'a>( + schema: &Value, error: &'e jsonschema::ValidationError<'a>, ) -> &'e jsonschema::ValidationError<'a> { use jsonschema::error::ValidationErrorKind as Kind; if let Kind::OneOfNotValid { context } | Kind::AnyOf { context } = error.kind() - && let Some(variants) = SCHEMA + && let Some(variants) = schema .pointer(error.schema_path().as_str()) .and_then(Value::as_array) + && let Some(errors) = + select_variant(variants, error.instance()).and_then(|index| context.get(index)) + && let Some(error) = errors.first() { - for (variant, errors) in variants.iter().zip(context) { - let matches_kind = variant["properties"]["kind"] - .get("const") - .is_some_and(|kind| error.instance().get("kind") == Some(kind)); - let matches_profile = variant["properties"].get("profile").is_some() - && error.instance().get("profile").is_some(); - if (matches_kind || matches_profile) - && let Some(error) = errors.first() - { - return innermost(error); - } - } + return innermost(schema, error); } error } @@ -156,7 +201,7 @@ fn segments(error: &jsonschema::ValidationError<'_>) -> Vec { } fn diagnostic(error: &jsonschema::ValidationError<'_>) -> ConfigError { - let error = innermost(error); + let error = innermost(&SCHEMA, error); let path: Vec<_> = segments(error) .into_iter() .map(|segment| match segment { @@ -186,3 +231,102 @@ pub fn validate_recipe( } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + fn keyed(key: &str, schema: Value) -> Value { + json!({"type": "object", "properties": {key: schema}, "required": [key], "additionalProperties": false}) + } + + fn targets() -> Vec { + vec![ + keyed("docker", json!({"type": "object"})), + keyed("podman", json!({"type": "object"})), + keyed("kubernetes", json!({"$ref": "#/$defs/Cluster"})), + ] + } + + #[test] + fn a_kind_or_management_constant_selects_its_variant() { + let variants = [ + json!({"properties": {"management": {"const": "managed"}}}), + json!({"properties": {"management": {"const": "external"}}}), + ]; + assert_eq!( + select_variant(&variants, &json!({"management": "external"})), + Some(1) + ); + assert_eq!( + select_variant(&variants, &json!({"management": "other"})), + None + ); + } + + #[test] + fn the_one_key_present_selects_its_single_key_variant() { + let variants = targets(); + assert_eq!(select_variant(&variants, &json!({"podman": {}})), Some(1)); + // An unknown field beside the key still selects the named variant. + assert_eq!( + select_variant(&variants, &json!({"kubernetes": 1, "extra": {}})), + Some(2) + ); + } + + #[test] + fn a_missing_doubled_or_unknown_key_selects_no_variant() { + let variants = targets(); + for instance in [ + json!({}), + json!({"docker": {}, "podman": {}}), + json!({"dokcer": {}}), + json!("docker"), + ] { + assert_eq!(select_variant(&variants, &instance), None, "{instance}"); + } + } + + #[test] + fn exclusive_forms_that_do_not_close_their_object_are_not_keyed_variants() { + let variants = [ + json!({"required": ["inference"], "not": {"required": ["inferenceRef"]}}), + json!({"required": ["inferenceRef"], "not": {"required": ["inference"]}}), + ]; + assert_eq!(select_variant(&variants, &json!({"inference": {}})), None); + } + + #[test] + fn open_variants_that_each_require_one_field_are_not_keyed_variants() { + // Both fields may appear together, so neither one names a variant. + let variants = [ + json!({"properties": {"host": {"minLength": 1}}, "required": ["host"]}), + json!({"properties": {"allowed_ips": {"minItems": 1}}, "required": ["allowed_ips"]}), + ]; + assert_eq!(select_variant(&variants, &json!({"host": ""})), None); + assert_eq!(variant_keys(&variants), None); + } + + #[test] + fn a_violation_inside_a_keyed_variant_is_reported_at_its_field() { + let schema = json!({ + "type": "object", + "properties": {"target": {"oneOf": targets()}}, + "$defs": {"Cluster": { + "type": "object", + "properties": {"endpoint": {"type": "string"}}, + "required": ["endpoint"] + }} + }); + let validator = jsonschema::validator_for(&schema).unwrap(); + let instance = json!({"target": {"kubernetes": {"endpoint": 1}}}); + let error = validator.validate(&instance).unwrap_err(); + let error = innermost(&schema, &error); + assert_eq!( + error.instance_path().as_str(), + "/target/kubernetes/endpoint" + ); + assert_eq!(error.kind().keyword(), "type"); + } +} diff --git a/crates/nemoclaw-sdk/src/config/schema.rs b/crates/nemoclaw-sdk/src/config/schema.rs index 6be5ad9fc18..926e9b3fcaf 100644 --- a/crates/nemoclaw-sdk/src/config/schema.rs +++ b/crates/nemoclaw-sdk/src/config/schema.rs @@ -3,6 +3,9 @@ //! Authored YAML represented as JSON, before Document::defaults runs. pub(crate) mod validation; +// Editors select union variants the same way schema diagnostics do. +pub use nemoclaw_runtime::schema::select_variant; + pub const SCHEMA_PATH: &str = "schemas/nemoclaw-v1alpha1.schema.json"; pub fn input_schema() -> serde_json::Value { diff --git a/crates/nemoclaw-sdk/src/config/schema/runtime.rs b/crates/nemoclaw-sdk/src/config/schema/runtime.rs index ca95b33dd03..5786c6d995b 100644 --- a/crates/nemoclaw-sdk/src/config/schema/runtime.rs +++ b/crates/nemoclaw-sdk/src/config/schema/runtime.rs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 //! Offline validators compiled once from the SDK contract, never from a deployment file. use crate::config::{ConfigError, Document, RouteTuning}; +use nemoclaw_runtime::schema::{select_variant, variant_keys}; use serde::Serialize; use serde_json::{Value, json}; use std::{ @@ -49,41 +50,49 @@ fn check( ) -> Result<(), ConfigError> { validator .validate(value) - .map_err(|error| diagnostic(&error, value, schema, source)) + .map_err(|error| diagnostic(&error, value, schema, source, "")) } +/// `variant` is the schema location of the union variant that the input +/// selected on the way to this error, or empty when it selected none. fn diagnostic( error: &jsonschema::ValidationError<'_>, root: &Value, schema: &Value, source: Option<&str>, + variant: &str, ) -> ConfigError { use jsonschema::error::{TypeKind, ValidationErrorKind as Kind}; - let schema_path = error.schema_path().to_string(); - // Select the declared tagged variant, so errors describe its fields rather than + let schema_path = error.schema_path().as_str(); + let union = match error.kind() { + Kind::OneOfNotValid { context } | Kind::AnyOf { context } => schema + .pointer(schema_path) + .and_then(Value::as_array) + .map(|variants| (variants, context)), + _ => None, + }; + // Select the variant the input names, so errors describe its fields rather than // unrelated alternatives. Never render rejected values or arbitrary map keys. - if let Kind::OneOfNotValid { context } | Kind::AnyOf { context } = error.kind() - && let Some(variants) = schema.pointer(&schema_path).and_then(Value::as_array) + if let Some((variants, context)) = union + && let Some(index) = select_variant(variants, error.instance()) + && let Some(error) = context.get(index).and_then(|errors| errors.first()) { - for (variant, errors) in variants.iter().zip(context) { - let matches_tag = ["kind", "management"].iter().any(|tag| { - variant["properties"][tag] - .get("const") - .is_some_and(|expected| error.instance().get(tag) == Some(expected)) - }); - let matches_profile = variant["properties"].get("profile").is_some() - && error.instance().get("profile").is_some(); - if (matches_tag || matches_profile) - && let Some(error) = errors.first() - { - return diagnostic(error, root, schema, source); - } - } + let variant = format!("{schema_path}/{index}"); + return diagnostic(error, root, schema, source, &variant); } - let parent = schema_path - .rsplit_once('/') - .and_then(|(parent, _)| schema.pointer(parent)); - let constraint = if let Some(message) = parent.and_then(|s| s["x-nemoclaw-error"].as_str()) { + let keyed = union.and_then(|(variants, _)| variant_keys(variants)); + let constraint = if let Some(mut keys) = keyed { + // The input named no single variant: list the declared keys, never the + // input's, unless the union carries its own message. An enclosing + // rule's message describes a different constraint. + let own = schema_path + .rsplit_once('/') + .and_then(|(union, _)| schema.pointer(union)?.get("x-nemoclaw-error")?.as_str()); + own.map(str::to_owned).unwrap_or_else(|| { + keys.sort_unstable(); + format!("must contain exactly one of: {}", keys.join(", ")) + }) + } else if let Some(message) = annotation(schema, error, variant) { message.to_owned() } else { match error.kind() { @@ -106,10 +115,8 @@ fn diagnostic( .collect::>() .join(" or ") ), - Kind::AnyOf { .. } => schema - .pointer(&schema_path) - .and_then(Value::as_array) - .and_then(|variants| { + Kind::AnyOf { .. } => union + .and_then(|(variants, _)| { variants .iter() .map(scalar_constraint) @@ -133,6 +140,46 @@ fn diagnostic( )) } +/// The message of the nearest annotated schema node enclosing the failing +/// keyword, so a rule built from nested `properties`, `items`, `allOf`, or +/// `then` steps keeps its explanation. A missing field prefers its own +/// annotation. Canonical schema locations never cross `$ref`, so the walk ends +/// at a definition root; it also ends at the selected variant's root, so a +/// union's message cannot hide a more specific error inside that variant. +fn annotation<'s>( + schema: &'s Value, + error: &jsonschema::ValidationError<'_>, + variant: &str, +) -> Option<&'s str> { + use jsonschema::error::ValidationErrorKind as Kind; + let message = |pointer: &str| schema.pointer(pointer)?.get("x-nemoclaw-error")?.as_str(); + let path = error.schema_path().as_str(); + if let Kind::Required { property } = error.kind() + && let (Some(object), Some(name)) = (path.strip_suffix("/required"), property.as_str()) + && let Some(found) = message(&format!( + "{object}/properties/{}", + name.replace('~', "~0").replace('/', "~1") + )) + { + return Some(found); + } + let floor = path + .strip_prefix(variant) + .filter(|rest| rest.is_empty() || rest.starts_with('/')) + .map_or(0, |_| variant.len()); + let mut current = path; + while let Some((parent, _)) = current.rsplit_once('/') { + if parent.is_empty() || parent == "/$defs" || parent.len() < floor { + break; + } + if let Some(found) = message(parent) { + return Some(found); + } + current = parent; + } + None +} + fn scalar_constraint(schema: &Value) -> Option { if let Some(value) = schema.get("const") { return Some(value.to_string()); @@ -262,3 +309,207 @@ pub(crate) fn validate_service( pub(crate) fn validate_tuning(tuning: &RouteTuning) -> Result<(), ConfigError> { check(&TUNING, &value(tuning)?, &TUNING_SCHEMA, None) } + +#[cfg(test)] +mod tests { + use super::*; + + // Field names come from the SDK schema, so diagnostics may show them. + fn keyed(key: &str, schema: Value) -> Value { + json!({"type": "object", "properties": {key: schema}, "required": [key], "additionalProperties": false}) + } + + fn targets() -> Value { + json!({ + "type": "object", + "properties": {"gateway": {"$ref": "#/$defs/Target"}}, + "$defs": { + "Target": {"oneOf": [ + keyed("docker", json!({"$ref": "#/$defs/Local"})), + keyed("podman", json!({"$ref": "#/$defs/Local"})), + keyed("kubernetes", json!({"$ref": "#/$defs/Cluster"})), + ]}, + "Local": { + "type": "object", + "properties": {"engine": {"type": "string", "minLength": 1}}, + "additionalProperties": false + }, + "Cluster": { + "type": "object", + "properties": { + "endpoint": {"type": "string", "pattern": "^https://"}, + "namespace": {"type": "string"} + }, + "required": ["endpoint"], + "additionalProperties": false + } + } + }) + } + + fn message(schema: &Value, instance: Value) -> String { + check(&compile(schema), &instance, schema, None) + .unwrap_err() + .to_string() + } + + #[test] + fn an_error_inside_the_named_single_key_variant_names_its_field() { + let error = message( + &targets(), + json!({"gateway": {"kubernetes": {"endpoint": "http://127.0.0.1:1"}}}), + ); + assert_eq!( + error, + "configuration violates schema at gateway.kubernetes.endpoint: required pattern: ^https://" + ); + let error = message(&targets(), json!({"gateway": {"kubernetes": {}}})); + assert_eq!( + error, + r#"configuration violates schema at gateway.kubernetes: required field: "endpoint""# + ); + } + + #[test] + fn a_single_key_union_without_one_known_key_lists_the_declared_keys() { + for instance in [ + json!({"PRIVATE_SENTINEL": {}}), + json!({}), + json!({"docker": {}, "podman": {}}), + json!("PRIVATE_SENTINEL"), + ] { + let error = message(&targets(), json!({"gateway": instance})); + assert_eq!( + error, + "configuration violates schema at gateway: must contain exactly one of: docker, kubernetes, podman", + "{instance}" + ); + } + } + + #[test] + fn a_single_key_union_prefers_its_own_annotation_when_no_key_selects_a_variant() { + let mut schema = targets(); + schema["$defs"]["Target"]["x-nemoclaw-error"] = json!("gateway must name one target"); + let error = message(&schema, json!({"gateway": {"dokcer": {}}})); + assert_eq!( + error, + "configuration violates schema at gateway: gateway must name one target" + ); + assert!(!error.contains("dokcer"), "{error}"); + // The union's message does not hide an error inside the selected variant. + schema["$defs"]["Target"]["oneOf"][2]["properties"]["kubernetes"] = + schema["$defs"]["Cluster"].clone(); + let error = message(&schema, json!({"gateway": {"kubernetes": {"endpoint": 1}}})); + assert_eq!( + error, + "configuration violates schema at gateway.kubernetes.endpoint: must be string" + ); + } + + #[test] + fn an_inline_single_key_union_without_one_known_key_ignores_annotated_ancestors() { + let union = |annotation: Option<&str>| { + let mut runtime = json!({"oneOf": [ + keyed("docker", json!({"type": "object"})), + keyed("podman", json!({"type": "object"})), + ]}); + if let Some(annotation) = annotation { + runtime["x-nemoclaw-error"] = json!(annotation); + } + json!({ + "type": "object", + "properties": {"gateway": { + "type": "object", + "properties": {"runtime": runtime}, + "x-nemoclaw-error": "the gateway must name an endpoint" + }} + }) + }; + for runtime in [json!({"dokcer": {}}), json!({})] { + let instance = json!({"gateway": {"runtime": runtime}}); + assert_eq!( + message(&union(None), instance.clone()), + "configuration violates schema at gateway.runtime: must contain exactly one of: docker, podman", + "{instance}" + ); + assert_eq!( + message(&union(Some("the gateway names one runtime")), instance), + "configuration violates schema at gateway.runtime: the gateway names one runtime" + ); + } + } + + #[test] + fn a_nested_rule_reports_the_nearest_enclosing_annotation() { + let schema = json!({ + "type": "object", + "properties": {"gateway": { + "type": "object", + "properties": {"environment": { + "type": "array", + "items": {"type": "string", "not": {"const": "PATH"}}, + "x-nemoclaw-error": "environment names must not shadow process controls" + }}, + "if": {"required": ["namespace"]}, + "then": { + "properties": {"endpoint": {"pattern": "^https://"}}, + "allOf": [{"not": {"required": ["engine"]}}], + "x-nemoclaw-error": "a cluster target requires HTTPS and excludes engine" + } + }} + }); + for (instance, path, expected) in [ + ( + json!({"environment": ["PATH"]}), + "gateway.environment[0]", + "environment names must not shadow process controls", + ), + ( + json!({"namespace": "agents", "endpoint": "http://127.0.0.1:1"}), + "gateway.endpoint", + "a cluster target requires HTTPS and excludes engine", + ), + ( + json!({"namespace": "agents", "engine": "unix:///run/engine.sock"}), + "gateway", + "a cluster target requires HTTPS and excludes engine", + ), + ] { + assert_eq!( + message(&schema, json!({"gateway": instance})), + format!("configuration violates schema at {path}: {expected}") + ); + } + } + + #[test] + fn a_missing_field_reports_its_own_annotation() { + let schema = json!({ + "type": "object", + "properties": {"gateway": { + "type": "object", + "properties": { + "engine": {"type": "string", "x-nemoclaw-error": "the engine names a local socket"}, + "endpoint": {"type": "string"} + }, + "required": ["engine", "endpoint"], + "x-nemoclaw-error": "the gateway is incomplete" + }} + }); + assert_eq!( + message( + &schema, + json!({"gateway": {"endpoint": "http://127.0.0.1:1"}}) + ), + "configuration violates schema at gateway: the engine names a local socket" + ); + assert_eq!( + message( + &schema, + json!({"gateway": {"engine": "unix:///run/engine.sock"}}) + ), + "configuration violates schema at gateway: the gateway is incomplete" + ); + } +} diff --git a/crates/nemoclaw-sdk/tests/config_diagnostics.rs b/crates/nemoclaw-sdk/tests/config_diagnostics.rs index 116f171fd69..dd5fe0a2965 100644 --- a/crates/nemoclaw-sdk/tests/config_diagnostics.rs +++ b/crates/nemoclaw-sdk/tests/config_diagnostics.rs @@ -167,3 +167,20 @@ fn collection_tags_are_rejected_and_quoted_or_block_tag_text_is_preserved() { literal["spec"]["sandboxes"][0]["harness"]["settings"] ); } + +#[test] +fn a_missing_service_image_reports_the_digest_pin_rule_at_its_service() { + let mut input = source("spark/spark-inline.yaml"); + input["spec"]["services"]["qwen"] + .as_object_mut() + .unwrap() + .remove("image"); + let error = Document::parse(input.to_string().as_bytes()) + .unwrap_err() + .to_string(); + assert!( + error.contains("schema at spec.services.qwen (line") + && error.ends_with(": service image must be pinned by a SHA-256 digest"), + "{error}" + ); +} diff --git a/crates/nemoclaw-sdk/tests/config_kubernetes.rs b/crates/nemoclaw-sdk/tests/config_kubernetes.rs index 016e37d8ca5..cbe1a48c838 100644 --- a/crates/nemoclaw-sdk/tests/config_kubernetes.rs +++ b/crates/nemoclaw-sdk/tests/config_kubernetes.rs @@ -512,3 +512,56 @@ fn kubernetes_does_not_relax_gateway_transport_or_credential_validation() { assert!(Document::parse(input.to_string().as_bytes()).is_err()); } } + +fn schema_error(input: &Value) -> String { + Document::parse(input.to_string().as_bytes()) + .unwrap_err() + .to_string() +} + +#[test] +fn managed_kubernetes_endpoint_and_local_field_errors_state_the_target_rule() { + let rule = "managed Kubernetes requires an explicit HTTPS 127.0.0.1 endpoint with a nonzero port and excludes local engine settings"; + let mut endpoint = managed_document(); + endpoint["spec"]["gateway"]["endpoint"] = json!("http://127.0.0.1:17671"); + let mut local = managed_document(); + local["spec"]["gateway"]["networkCIDR"] = json!("172.30.1.0/24"); + for (input, path) in [(endpoint, "spec.gateway.endpoint"), (local, "spec.gateway")] { + let error = schema_error(&input); + assert!( + error.contains(&format!("schema at {path} (line")) && error.contains(rule), + "{error}" + ); + } +} + +#[test] +fn a_reserved_kubernetes_environment_name_states_the_naming_rule() { + let mut input = managed_document(); + input["spec"]["gateway"]["kubernetes"]["environment"] = json!(["AWS_PROFILE", "KUBECONFIG"]); + let error = schema_error(&input); + assert!( + error.contains("schema at spec.gateway.kubernetes.environment[1] (line") + && error.contains( + "Kubernetes environment names must be unique variable names that do not shadow process, trust, proxy, or cluster controls" + ), + "{error}" + ); + assert!(!error.contains("KUBECONFIG"), "{error}"); +} + +#[test] +fn managed_services_with_a_kubernetes_runtime_state_the_cluster_rule() { + let managed = + Document::parse(include_bytes!("fixtures/config/managed-ollama.yaml").as_slice()).unwrap(); + let mut input = external_document(); + input["spec"]["services"] = serde_json::to_value(managed.spec.services).unwrap(); + let error = schema_error(&input); + assert!( + error.contains("schema at spec.services (line") + && error.contains( + "Kubernetes requires an external gateway or an explicit managed Kubernetes target, and external inference endpoints; managed services are not supported" + ), + "{error}" + ); +} diff --git a/crates/nemoclaw-sdk/tests/config_schema.rs b/crates/nemoclaw-sdk/tests/config_schema.rs index 71b0d3fd52c..a9e19181544 100644 --- a/crates/nemoclaw-sdk/tests/config_schema.rs +++ b/crates/nemoclaw-sdk/tests/config_schema.rs @@ -508,6 +508,14 @@ fn managed_podman_requires_an_explicit_engine() { value["spec"]["gateway"]["engine"] = json!(""); agrees(&validator, &value, false); + let error = Document::parse(value.to_string().as_bytes()) + .unwrap_err() + .to_string(); + assert!( + error.contains("schema at spec.gateway.engine (line") + && error.contains("Podman requires spec.gateway.engine"), + "{error}" + ); } #[test] From eb5ef33128c5beb2d622a0771c61833aa857c28e Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Tue, 13 Oct 2026 18:36:41 +0000 Subject: [PATCH 3/9] refactor(config)!: split credential references into SecretRef and FileRef One Credential type held both bearer values and local file paths: the env value of `tls.*`, `kubeconfig`, and `image.metadata` is a file path, while the gateway, inference provider, and web-search credentials hold the secret itself. The schema and reference could not say which. - SecretRef: external gateway credential, inference provider credential, and web-search integration credential. - FileRef: TLS CA, certificate, and key; managed Kubernetes kubeconfig; sandbox image metadata. Authored YAML stays `{env: NAME}`. Each reference keeps the reserved-name rules and now reports a message naming its kind. The `file` and `kubernetesSecret` forms from #13080 are left out: reading secrets from files changes the credential model, and OpenShell cannot bind a Secret by reference yet. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Hai Nguyen --- crates/nemoclaw-e2e/tests/deployment.rs | 6 +- .../nemoclaw-e2e/tests/export_observations.rs | 2 +- crates/nemoclaw-e2e/tests/kubernetes_live.rs | 14 +-- crates/nemoclaw-e2e/tests/tls.rs | 14 +-- crates/nemoclaw-sdk/src/config/inference.rs | 6 +- .../nemoclaw-sdk/src/config/integrations.rs | 8 +- crates/nemoclaw-sdk/src/config/kubernetes.rs | 4 +- crates/nemoclaw-sdk/src/config/mod.rs | 2 +- .../src/config/schema/validation.rs | 26 ++--- crates/nemoclaw-sdk/src/config/types.rs | 34 ++++--- crates/nemoclaw-sdk/src/config/validation.rs | 10 +- crates/nemoclaw-sdk/src/deployment/export.rs | 4 +- crates/nemoclaw-sdk/src/deployment/mod.rs | 2 +- crates/nemoclaw-sdk/src/deployment/tests.rs | 10 +- .../nemoclaw-sdk/src/inference_discovery.rs | 6 +- crates/nemoclaw-sdk/src/kubernetes/mod.rs | 2 +- crates/nemoclaw-sdk/tests/compile.rs | 12 +-- crates/nemoclaw-sdk/tests/config_choices.rs | 8 +- .../nemoclaw-sdk/tests/config_kubernetes.rs | 85 +++++++++++++++++ .../tests/inference_connection.rs | 4 +- docs/reference/configuration.md | 83 +++++++++------- schemas/nemoclaw-v1alpha1.schema.json | 94 ++++++++++++------- 22 files changed, 286 insertions(+), 150 deletions(-) diff --git a/crates/nemoclaw-e2e/tests/deployment.rs b/crates/nemoclaw-e2e/tests/deployment.rs index 04525624622..fb7d2644d5e 100644 --- a/crates/nemoclaw-e2e/tests/deployment.rs +++ b/crates/nemoclaw-e2e/tests/deployment.rs @@ -957,7 +957,7 @@ async fn destroy_does_not_require_the_inference_credential_or_rewrite_its_refere *document.spec.gateway.endpoint_mut() = fixture.endpoint.clone(); let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; document.spec.inference_providers[0].endpoint = "https://inference.example.test/v1".into(); - document.spec.inference_providers[0].credential = Some(nemoclaw_sdk::config::Credential { + document.spec.inference_providers[0].credential = Some(nemoclaw_sdk::config::SecretRef { env: "NEMOCLAW_TEST_REMOVED_INFERENCE_KEY".into(), }); let cancel = CancellationToken::new(); @@ -1030,7 +1030,7 @@ async fn apply_preserves_bindings_without_generating_inference() { *document.spec.gateway.endpoint_mut() = fixture.endpoint.clone(); let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; document.spec.inference_providers[0].endpoint = "https://unreachable.invalid/v1".into(); - document.spec.inference_providers[0].credential = Some(nemoclaw_sdk::config::Credential { + document.spec.inference_providers[0].credential = Some(nemoclaw_sdk::config::SecretRef { env: "MODEL_TOKEN".into(), }); let deployment = @@ -1540,7 +1540,7 @@ async fn cli_redaction_preserves_failures_and_recovery_with_short_and_colliding_ *document.spec.gateway.endpoint_mut() = fixture.endpoint.clone(); let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; document.spec.inference_providers[0].endpoint = "https://127.0.0.1:9/v1".into(); - document.spec.inference_providers[0].credential = Some(nemoclaw_sdk::config::Credential { + document.spec.inference_providers[0].credential = Some(nemoclaw_sdk::config::SecretRef { env: "NEMOCLAW_TEST_REDACTION_KEY".into(), }); let input = directory.path().join("deployment.yaml"); diff --git a/crates/nemoclaw-e2e/tests/export_observations.rs b/crates/nemoclaw-e2e/tests/export_observations.rs index 4ad73a55cd5..a7d4d565184 100644 --- a/crates/nemoclaw-e2e/tests/export_observations.rs +++ b/crates/nemoclaw-e2e/tests/export_observations.rs @@ -91,7 +91,7 @@ async fn export_uses_provider_observations_without_resolving_inference_credentia *document.spec.gateway.endpoint_mut() = fixture.endpoint.clone(); let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; document.spec.inference_providers[0].endpoint = "https://models.example/v1".into(); - document.spec.inference_providers[0].credential = Some(nemoclaw_sdk::config::Credential { + document.spec.inference_providers[0].credential = Some(nemoclaw_sdk::config::SecretRef { env: "EXPORT_INFERENCE_REFERENCE".into(), }); let cancel = CancellationToken::new(); diff --git a/crates/nemoclaw-e2e/tests/kubernetes_live.rs b/crates/nemoclaw-e2e/tests/kubernetes_live.rs index 01abcd1c29f..9d7b06ff832 100644 --- a/crates/nemoclaw-e2e/tests/kubernetes_live.rs +++ b/crates/nemoclaw-e2e/tests/kubernetes_live.rs @@ -14,7 +14,7 @@ use nemoclaw_sdk::{ ObservationError, bundle::Bundle, compile::{Generations, compile_runtime, compile_teardown, runtime_targets}, - config::{ComputeDriver, Credential, Document, ExternalGateway, Gateway, TLS}, + config::{ComputeDriver, Document, ExternalGateway, FileRef, Gateway, SecretRef, TLS}, kubernetes::{ CA_ENV, CERT_ENV, ClusterTarget, GATEWAY_KIND, KEY_ENV, STATE_ENV, STORAGE_KIND, Spec, TOKEN_ENV, connect, operations::Operations, server, @@ -269,14 +269,16 @@ async fn release_count(client: &kube::Client, namespace: &str, release: &str) -> async fn authenticated_gateway(operations: &Operations, spec: &Spec) { let connection = operations.connect(spec).await.unwrap(); - let reference = |env: &str| Credential { env: env.into() }; + let file = |env: &str| FileRef { env: env.into() }; let gateway = Gateway::External(ExternalGateway { endpoint: connection.endpoint().to_owned(), - credential: Some(reference(TOKEN_ENV)), + credential: Some(SecretRef { + env: TOKEN_ENV.into(), + }), tls: Some(TLS { - ca: reference(CA_ENV), - certificate: reference(CERT_ENV), - key: reference(KEY_ENV), + ca: file(CA_ENV), + certificate: file(CERT_ENV), + key: file(KEY_ENV), }), ..Default::default() }); diff --git a/crates/nemoclaw-e2e/tests/tls.rs b/crates/nemoclaw-e2e/tests/tls.rs index 61bb92348df..0b536da16e5 100644 --- a/crates/nemoclaw-e2e/tests/tls.rs +++ b/crates/nemoclaw-e2e/tests/tls.rs @@ -5,7 +5,7 @@ use nemoclaw_provider::openshell::{OpenShell, Secrets}; use nemoclaw_sdk::{ ObservationError, backend::Backend, - config::{Credential, Gateway, TLS}, + config::{FileRef, Gateway, SecretRef, TLS}, }; use rcgen::{ BasicConstraints, CertificateParams, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyPair, @@ -59,15 +59,17 @@ async fn mutual_tls_and_bearer_references_fail_closed_without_disclosing_credent values.insert(name.into(), path.to_str().unwrap().into()); } values.insert("TOKEN".into(), "secret-sentinel".into()); - let reference = |env: &str| Credential { env: env.into() }; + let file = |env: &str| FileRef { env: env.into() }; let gateway = Gateway::External(nemoclaw_sdk::config::ExternalGateway { engine: String::new(), endpoint: fixture.endpoint.clone(), - credential: Some(reference("TOKEN")), + credential: Some(SecretRef { + env: "TOKEN".into(), + }), tls: Some(TLS { - ca: reference("CA"), - certificate: reference("CERT"), - key: reference("KEY"), + ca: file("CA"), + certificate: file("CERT"), + key: file("KEY"), }), ..Default::default() }); diff --git a/crates/nemoclaw-sdk/src/config/inference.rs b/crates/nemoclaw-sdk/src/config/inference.rs index 252a9791821..462fa2cff98 100644 --- a/crates/nemoclaw-sdk/src/config/inference.rs +++ b/crates/nemoclaw-sdk/src/config/inference.rs @@ -1,13 +1,13 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use super::{ConfigError, Credential, Document, InferenceProvider}; +use super::{ConfigError, Document, InferenceProvider, SecretRef}; /// Upstream connection as used by OpenShell routing, independent of the sandbox /// engine. Credentials remain references. Resolution performs no reachability probe. #[derive(Clone, Debug, PartialEq, Eq)] pub struct InferenceConnection { pub endpoint: String, - pub credential: Option, + pub credential: Option, } impl Document { pub fn has_runtime(&self) -> bool { @@ -57,7 +57,7 @@ impl Document { pub enum InferenceTarget<'a> { External { endpoint: &'a str, - credential: Option<&'a Credential>, + credential: Option<&'a SecretRef>, }, Service { name: &'a str, diff --git a/crates/nemoclaw-sdk/src/config/integrations.rs b/crates/nemoclaw-sdk/src/config/integrations.rs index cdc91b81845..fbf5d009530 100644 --- a/crates/nemoclaw-sdk/src/config/integrations.rs +++ b/crates/nemoclaw-sdk/src/config/integrations.rs @@ -1,6 +1,6 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use super::{AgentTools, ConfigError, Credential, Document, Sandbox}; +use super::{AgentTools, ConfigError, Document, Sandbox, SecretRef}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; @@ -18,7 +18,7 @@ pub struct WebSearch { /// Supported search service. pub provider: SearchProvider, /// Host environment reference. OpenShell supplies the search provider's placeholder to the sandbox. - pub credential: Credential, + pub credential: SecretRef, } /// A definition and its explicitly attached agents in one sandbox. @@ -153,7 +153,7 @@ fn validate_definitions(definitions: &BTreeMap) -> Result<( pub(crate) struct RuntimeWebSearch { pub provider: SearchProvider, pub agent_refs: Vec, - pub credential: Credential, + pub credential: SecretRef, } pub use nemoclaw_openshell::search::{SearchProvider, search_provider_name}; @@ -187,6 +187,6 @@ impl RuntimeWebSearch { "web search requires unique references to configured agents", )); } - super::validation::credential(&Some(self.credential.clone())) + super::schema::validate_definition("SecretRef", &self.credential) } } diff --git a/crates/nemoclaw-sdk/src/config/kubernetes.rs b/crates/nemoclaw-sdk/src/config/kubernetes.rs index 56d1e38c07c..cb87f793d47 100644 --- a/crates/nemoclaw-sdk/src/config/kubernetes.rs +++ b/crates/nemoclaw-sdk/src/config/kubernetes.rs @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use super::Credential; +use super::FileRef; use serde::{Deserialize, Serialize}; /// Explicit existing-cluster target for a managed development gateway. The SDK does not create a cluster or select an ambient context, and installs nothing cluster-wide: Agent Sandbox and a default StorageClass must already exist. `runtime.provider: openshift` selects the OpenShift profile. @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize}; #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ManagedKubernetes { /// Environment reference whose value is the local kubeconfig file path. The file and its credentials remain outside configuration and exported state. Process, loader, trust, proxy, cluster, Python, Helm, OpenTofu, and SDK control variable names are reserved. - pub kubeconfig: Credential, + pub kubeconfig: FileRef, /// Exact kubeconfig context used for every cluster operation. #[schemars( length(min = 1, max = 253), diff --git a/crates/nemoclaw-sdk/src/config/mod.rs b/crates/nemoclaw-sdk/src/config/mod.rs index d0d18361fbd..5458a8f59be 100644 --- a/crates/nemoclaw-sdk/src/config/mod.rs +++ b/crates/nemoclaw-sdk/src/config/mod.rs @@ -336,7 +336,7 @@ impl Gateway { "operation requires a managed local gateway", )) } - pub fn credential(&self) -> Option<&Credential> { + pub fn credential(&self) -> Option<&SecretRef> { match self { Self::Managed(_) => None, Self::External(gateway) => gateway.credential.as_ref(), diff --git a/crates/nemoclaw-sdk/src/config/schema/validation.rs b/crates/nemoclaw-sdk/src/config/schema/validation.rs index 61dd25b5c6e..4e071aad2a1 100644 --- a/crates/nemoclaw-sdk/src/config/schema/validation.rs +++ b/crates/nemoclaw-sdk/src/config/schema/validation.rs @@ -101,18 +101,20 @@ pub(super) fn constrain(root: &mut Value, normalized: bool) { ); } property(&mut defs["Metadata"], "uid", json!({"pattern": c::UUID})); - property( - &mut defs["Credential"], - "env", - json!({ - "pattern": c::ENV, - "not": {"anyOf": [ - {"const": "NEMOCLAW_KUBERNETES_STATE"}, - {"pattern": "^(?:NEMOCLAW_MANAGED_K8S_|HELM_|KUBE_)"} - ]}, - "x-nemoclaw-error": "credential environment reference must be valid and must not shadow managed Kubernetes runtime controls" - }), - ); + for (name, kind) in [("SecretRef", "secret"), ("FileRef", "file")] { + property( + &mut defs[name], + "env", + json!({ + "pattern": c::ENV, + "not": {"anyOf": [ + {"const": "NEMOCLAW_KUBERNETES_STATE"}, + {"pattern": "^(?:NEMOCLAW_MANAGED_K8S_|HELM_|KUBE_)"} + ]}, + "x-nemoclaw-error": format!("{kind} reference must name a valid environment variable that does not shadow managed Kubernetes runtime controls") + }), + ); + } property( &mut defs["ManagedKubernetes"], "kubeconfig", diff --git a/crates/nemoclaw-sdk/src/config/types.rs b/crates/nemoclaw-sdk/src/config/types.rs index 4aaa28d2879..0250d5d682b 100644 --- a/crates/nemoclaw-sdk/src/config/types.rs +++ b/crates/nemoclaw-sdk/src/config/types.rs @@ -76,10 +76,20 @@ pub struct Spec { #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] #[schemars(!default)] #[serde(default, deny_unknown_fields)] -/// A reference to a caller-provided environment variable; the configuration contains no credential value. -pub struct Credential { +/// Environment variable whose value is a bearer or API credential; the configuration holds no credential value. +pub struct SecretRef { #[serde(rename = "env")] - /// Uppercase environment variable name. For TLS and kubeconfig fields, its value is a local file path; otherwise it is a bearer/API credential. NEMOCLAW_KUBERNETES_STATE and the NEMOCLAW_MANAGED_K8S_, HELM_, and KUBE_ prefixes are reserved for runtime controls. + /// Uppercase name of the caller environment variable that holds the credential. NEMOCLAW_KUBERNETES_STATE and the NEMOCLAW_MANAGED_K8S_, HELM_, and KUBE_ prefixes are reserved for runtime controls. + pub env: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[schemars(!default)] +#[serde(default, deny_unknown_fields)] +/// Environment variable whose value is the path of a local file; the configuration holds neither the path nor the file. +pub struct FileRef { + #[serde(rename = "env")] + /// Uppercase name of the caller environment variable that holds the local file path. NEMOCLAW_KUBERNETES_STATE and the NEMOCLAW_MANAGED_K8S_, HELM_, and KUBE_ prefixes are reserved for runtime controls. pub env: String, } @@ -90,13 +100,13 @@ pub struct Credential { pub struct TLS { #[serde(rename = "ca")] /// Environment variable whose value names the local CA certificate file. - pub ca: Credential, + pub ca: FileRef, #[serde(rename = "certificate")] /// Environment variable whose value names the local client certificate file. - pub certificate: Credential, + pub certificate: FileRef, #[serde(rename = "key")] /// Environment variable whose value names the local client private-key file. - pub key: Credential, + pub key: FileRef, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] @@ -173,9 +183,9 @@ pub struct ExternalGateway { /// Gateway HTTP(S) origin, without a path. pub endpoint: String, #[serde(rename = "credential", skip_serializing_if = "Option::is_none")] - #[schemars(default, with = "Credential")] + #[schemars(default, with = "SecretRef")] /// Optional bearer credential reference for an external HTTPS gateway. - pub credential: Option, + pub credential: Option, #[serde(rename = "tls", skip_serializing_if = "Option::is_none")] #[schemars(default, with = "TLS")] /// Optional mutual TLS references for an external HTTPS gateway. @@ -202,9 +212,9 @@ pub struct InferenceProvider { #[schemars(extend("x-nemoclaw-required" = "Without serviceRef"))] pub endpoint: String, #[serde(rename = "credential", skip_serializing_if = "Option::is_none")] - #[schemars(default, with = "Credential")] + #[schemars(default, with = "SecretRef")] /// Optional API credential reference for an external HTTPS endpoint. Excluded by serviceRef. - pub credential: Option, + pub credential: Option, #[serde( rename = "serviceRef", default, @@ -280,9 +290,9 @@ pub struct Image { /// Immutable image reference. Kubernetes and OpenShift require an explicit nonempty reference. For other drivers, omitted or empty selects the generic SDK agent image pin; verify that it contains the selected Fabric adapter. pub ref_: String, #[serde(default, skip_serializing_if = "Option::is_none")] - #[schemars(default, with = "Credential")] + #[schemars(default, with = "FileRef")] /// Environment reference to the absolute path of a local OCI metadata bundle for `ref`; required for Kubernetes and OpenShift, where no local engine can be inspected. Destroy does not read it. Its index, manifest, configuration, and Fabric catalog are verified against `ref` before use. The bundle holds no image layers or credentials. Docker and Podman inspect their engine instead. - pub metadata: Option, + pub metadata: Option, } #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] diff --git a/crates/nemoclaw-sdk/src/config/validation.rs b/crates/nemoclaw-sdk/src/config/validation.rs index d51d23fc831..cee2af5c5c0 100644 --- a/crates/nemoclaw-sdk/src/config/validation.rs +++ b/crates/nemoclaw-sdk/src/config/validation.rs @@ -11,12 +11,6 @@ pub(crate) fn require(valid: bool, reason: &'static str) -> Result<(), ConfigErr Err(ConfigError::new(reason)) } } -pub(super) fn credential(value: &Option) -> Result<(), ConfigError> { - if let Some(credential) = value { - schema::validate_definition("Credential", credential)?; - } - Ok(()) -} pub use nemoclaw_backend::validate_endpoint; @@ -50,7 +44,9 @@ impl Document { || sandbox.image.metadata.is_none(), "image.metadata is available only for Kubernetes and OpenShift; Docker and Podman use engine image inspection", )?; - credential(&sandbox.image.metadata)?; + if let Some(metadata) = &sandbox.image.metadata { + schema::validate_definition("FileRef", metadata)?; + } require( sandbox_names.insert(&sandbox.name), "sandbox names must be unique", diff --git a/crates/nemoclaw-sdk/src/deployment/export.rs b/crates/nemoclaw-sdk/src/deployment/export.rs index 2bef243b426..b59dc6ab5ff 100644 --- a/crates/nemoclaw-sdk/src/deployment/export.rs +++ b/crates/nemoclaw-sdk/src/deployment/export.rs @@ -388,7 +388,7 @@ fn export_provider(document: &mut Document, expected: &Row, observed: &Row) -> R return Err(Error::Conflict("managed inference registration drifted")); } let provider = document.selected_provider_mut(&expected["name"])?; - provider.credential = (!observed["credential_env"].is_empty()).then(|| Credential { + provider.credential = (!observed["credential_env"].is_empty()).then(|| SecretRef { env: observed["credential_env"].clone(), }); Ok(()) @@ -752,7 +752,7 @@ mod tests { Document::parse(include_str!("../../tests/fixtures/config/local.yaml").as_bytes()) .unwrap(); document.spec.inference_providers[0].endpoint = "https://models.example/v1".into(); - document.spec.inference_providers[0].credential = Some(Credential { + document.spec.inference_providers[0].credential = Some(SecretRef { env: "OLD_KEY".into(), }); let expected = provider_row(&document); diff --git a/crates/nemoclaw-sdk/src/deployment/mod.rs b/crates/nemoclaw-sdk/src/deployment/mod.rs index d3ce857ac3c..d728e8453b7 100644 --- a/crates/nemoclaw-sdk/src/deployment/mod.rs +++ b/crates/nemoclaw-sdk/src/deployment/mod.rs @@ -20,7 +20,7 @@ use crate::{ backend::Row, bundle::Bundle, compile::{self, Target}, - config::{Credential, Document}, + config::{Document, SecretRef}, state::{Record, StateBinding, Store, atomic_write, save_json}, }; use plan::{Plan, check_destroy_plan, check_plan}; diff --git a/crates/nemoclaw-sdk/src/deployment/tests.rs b/crates/nemoclaw-sdk/src/deployment/tests.rs index 0f1c56f1c1e..e8b538d981a 100644 --- a/crates/nemoclaw-sdk/src/deployment/tests.rs +++ b/crates/nemoclaw-sdk/src/deployment/tests.rs @@ -126,7 +126,7 @@ fn kubernetes_environment_is_operation_scoped_and_stable_across_export_directori } } let (mut document, _) = kubernetes_context(); - document.spec.inference_providers[0].credential = Some(Credential { + document.spec.inference_providers[0].credential = Some(SecretRef { env: "UNREAD_INFERENCE_KEY".into(), }); let temporary = tempfile::tempdir().unwrap(); @@ -443,7 +443,7 @@ fn credential_references_cannot_override_opentofu_control_variables() { let mut document = Document::parse(include_str!("../../tests/fixtures/config/local.yaml").as_bytes()).unwrap(); document.spec.inference_providers[0].endpoint = "https://example.com/v1".into(); - document.spec.inference_providers[0].credential = Some(Credential { + document.spec.inference_providers[0].credential = Some(SecretRef { env: "TF_CLI_CONFIG_FILE".into(), }); assert!(command_environment(&document, &Values, Path::new("state")).is_err()); @@ -513,7 +513,7 @@ async fn schema_commands_do_not_require_inference_credentials() { Deployment::new(&state_path, bundle_directory.path()).with_secrets(secrets.clone()); let mut document = Document::parse(include_str!("../../tests/fixtures/config/local.yaml").as_bytes()).unwrap(); - document.spec.inference_providers[0].credential = Some(Credential { + document.spec.inference_providers[0].credential = Some(SecretRef { env: "TEST_INFERENCE_CREDENTIAL".into(), }); let cancel = CancellationToken::new(); @@ -633,7 +633,7 @@ fn gateway_observation_resolves_only_gateway_credentials() { } })) .unwrap(); - document.spec.inference_providers[0].credential = Some(Credential { + document.spec.inference_providers[0].credential = Some(SecretRef { env: "INFERENCE_TOKEN".into(), }); document.spec.sandboxes[0].integrations = serde_json::from_value(json!({ @@ -649,7 +649,7 @@ fn gateway_observation_resolves_only_gateway_credentials() { assert!(!environment.contains_key("SEARCH_KEY")); assert!(command_environment(&document, &GatewayValues, Path::new("state")).is_err()); if let Gateway::External(gateway) = &mut document.spec.gateway { - gateway.credential = Some(Credential { + gateway.credential = Some(SecretRef { env: "TF_CLI_CONFIG_FILE".into(), }); } diff --git a/crates/nemoclaw-sdk/src/inference_discovery.rs b/crates/nemoclaw-sdk/src/inference_discovery.rs index 3778835c7cd..dd8755284b2 100644 --- a/crates/nemoclaw-sdk/src/inference_discovery.rs +++ b/crates/nemoclaw-sdk/src/inference_discovery.rs @@ -4,7 +4,7 @@ //! Inference catalog requests and observations, and direct credential availability. use crate::{ Error, ObservationError, Secrets, - config::{Credential, Document, InferenceApi, InferenceProvider, InferenceTarget}, + config::{Document, InferenceApi, InferenceProvider, InferenceTarget, SecretRef}, discovery::ObservationStatus, }; use serde::{Deserialize, Serialize}; @@ -45,8 +45,8 @@ impl EndpointRequest { crate::config::validate_endpoint(&self.endpoint, false)?; if let Some(reference) = &self.credential_env { crate::config::schema::validate_definition( - "Credential", - &Credential { + "SecretRef", + &SecretRef { env: reference.clone(), }, )?; diff --git a/crates/nemoclaw-sdk/src/kubernetes/mod.rs b/crates/nemoclaw-sdk/src/kubernetes/mod.rs index 86058b3505c..45ef0e87cf2 100644 --- a/crates/nemoclaw-sdk/src/kubernetes/mod.rs +++ b/crates/nemoclaw-sdk/src/kubernetes/mod.rs @@ -168,7 +168,7 @@ impl Spec { runtime: crate::config::Runtime { provider }, endpoint: get("endpoint")?, kubernetes: Some(crate::config::ManagedKubernetes { - kubeconfig: crate::config::Credential { + kubeconfig: crate::config::FileRef { env: get("kubeconfig_env")?, }, context: get("context")?, diff --git a/crates/nemoclaw-sdk/tests/compile.rs b/crates/nemoclaw-sdk/tests/compile.rs index f0b12d6a713..d76a1d538e4 100644 --- a/crates/nemoclaw-sdk/tests/compile.rs +++ b/crates/nemoclaw-sdk/tests/compile.rs @@ -134,7 +134,7 @@ fn ownership_generations() -> BTreeMap { #[test] fn compiled_resources_preserve_ownership_connections_and_dependency_order() { - use nemoclaw_sdk::config::{Credential, TLS}; + use nemoclaw_sdk::config::{FileRef, SecretRef, TLS}; use serde_json::json; let mut document = Document::parse(include_str!("fixtures/config/local.yaml").as_bytes()).unwrap(); @@ -142,24 +142,24 @@ fn compiled_resources_preserve_ownership_connections_and_dependency_order() { let nemoclaw_sdk::config::Gateway::External(gateway) = &mut document.spec.gateway else { panic!("expected external gateway"); }; - gateway.credential = Some(Credential { + gateway.credential = Some(SecretRef { env: "GATEWAY_TOKEN".into(), }); gateway.tls = Some(TLS { - ca: Credential { + ca: FileRef { env: "GATEWAY_CA".into(), }, - certificate: Credential { + certificate: FileRef { env: "GATEWAY_CERT".into(), }, - key: Credential { + key: FileRef { env: "GATEWAY_KEY".into(), }, }); let provider = &mut document.spec.inference_providers[0]; provider.name = "remote".into(); provider.endpoint = "https://models.example.test/v1".into(); - provider.credential = Some(Credential { + provider.credential = Some(SecretRef { env: "MODEL_TOKEN".into(), }); let sandbox = &mut document.spec.sandboxes[0]; diff --git a/crates/nemoclaw-sdk/tests/config_choices.rs b/crates/nemoclaw-sdk/tests/config_choices.rs index 5d2ef789f05..dedab329ace 100644 --- a/crates/nemoclaw-sdk/tests/config_choices.rs +++ b/crates/nemoclaw-sdk/tests/config_choices.rs @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 use nemoclaw_sdk::{ - config::{Credential, Document, InferenceProvider, InferenceProviderKind, InferenceTarget}, + config::{Document, InferenceProvider, InferenceProviderKind, InferenceTarget, SecretRef}, services::{ ServiceDefinition, installers::vllm::{HardwareProfile, Service, ServiceHardware, VllmLaunchMode}, @@ -83,7 +83,7 @@ fn service_inference_target_preserves_the_service_name() { fn service_inference_target_rejects_credentials_without_exposing_the_reference() { let provider = InferenceProvider { service_ref: Some("model".into()), - credential: Some(Credential { + credential: Some(SecretRef { env: "SECRET_REF".into(), }), ..provider() @@ -95,7 +95,7 @@ fn service_inference_target_rejects_credentials_without_exposing_the_reference() #[test] fn external_inference_target_rejects_credentials_without_an_endpoint() { let provider = InferenceProvider { - credential: Some(Credential { + credential: Some(SecretRef { env: "SECRET_REF".into(), }), ..provider() @@ -107,7 +107,7 @@ fn external_inference_target_rejects_credentials_without_an_endpoint() { fn external_inference_target_accepts_an_endpoint_with_credentials() { let provider = InferenceProvider { endpoint: "https://example.com/v1".into(), - credential: Some(Credential { + credential: Some(SecretRef { env: "SECRET_REF".into(), }), ..provider() diff --git a/crates/nemoclaw-sdk/tests/config_kubernetes.rs b/crates/nemoclaw-sdk/tests/config_kubernetes.rs index cbe1a48c838..4f0781a2598 100644 --- a/crates/nemoclaw-sdk/tests/config_kubernetes.rs +++ b/crates/nemoclaw-sdk/tests/config_kubernetes.rs @@ -550,6 +550,91 @@ fn a_reserved_kubernetes_environment_name_states_the_naming_rule() { assert!(!error.contains("KUBECONFIG"), "{error}"); } +#[test] +fn a_reserved_reference_name_states_whether_the_reference_holds_a_secret_or_a_file_path() { + let secret = "secret reference must name a valid environment variable that does not shadow managed Kubernetes runtime controls"; + let file = "file reference must name a valid environment variable that does not shadow managed Kubernetes runtime controls"; + let mut external = external_document(); + external["spec"]["gateway"]["endpoint"] = json!("https://openshell.example.com"); + external["spec"]["gateway"]["credential"] = json!({"env": "GATEWAY_TOKEN"}); + external["spec"]["gateway"]["tls"] = json!({ + "ca": {"env": "GATEWAY_CA"}, + "certificate": {"env": "GATEWAY_CERT"}, + "key": {"env": "GATEWAY_KEY"} + }); + external["spec"]["inferenceProviders"][0]["endpoint"] = json!("https://inference.example/v1"); + external["spec"]["inferenceProviders"][0]["credential"] = json!({"env": "HOSTED_API_KEY"}); + external["spec"]["sandboxes"][0]["integrations"] = json!({ + "search": {"kind": "webSearch", "provider": "brave", "credential": {"env": "SEARCH_KEY"}} + }); + external["spec"]["sandboxes"][0]["agent"]["integrationRefs"] = json!(["search"]); + Document::parse(external.to_string().as_bytes()).unwrap(); + for (mut input, pointer, path, rule) in [ + ( + external.clone(), + "/spec/gateway/credential", + "spec.gateway.credential.env", + secret, + ), + ( + external.clone(), + "/spec/inferenceProviders/0/credential", + "spec.inferenceProviders[0].credential.env", + secret, + ), + ( + external.clone(), + "/spec/sandboxes/0/integrations/search/credential", + "spec.sandboxes[0].integrations.search.credential.env", + secret, + ), + ( + external.clone(), + "/spec/gateway/tls/ca", + "spec.gateway.tls.ca.env", + file, + ), + ( + external.clone(), + "/spec/gateway/tls/certificate", + "spec.gateway.tls.certificate.env", + file, + ), + ( + external.clone(), + "/spec/gateway/tls/key", + "spec.gateway.tls.key.env", + file, + ), + ( + external, + "/spec/sandboxes/0/image/metadata", + "spec.sandboxes[0].image.metadata.env", + file, + ), + ( + managed_document(), + "/spec/gateway/kubernetes/kubeconfig", + "spec.gateway.kubernetes.kubeconfig.env", + file, + ), + ] { + *input.pointer_mut(pointer).unwrap() = json!({"env": "KUBE_TOKEN"}); + let error = schema_error(&input); + assert!( + error.contains(&format!("schema at {path} (line")) && error.contains(rule), + "{error}" + ); + assert!(!error.contains("KUBE_TOKEN"), "{error}"); + let error = serde_json::from_value::(input) + .unwrap() + .validate() + .unwrap_err() + .to_string(); + assert!(error.contains(rule), "{error}"); + } +} + #[test] fn managed_services_with_a_kubernetes_runtime_state_the_cluster_rule() { let managed = diff --git a/crates/nemoclaw-sdk/tests/inference_connection.rs b/crates/nemoclaw-sdk/tests/inference_connection.rs index 1c53fd6dc11..6a962342638 100644 --- a/crates/nemoclaw-sdk/tests/inference_connection.rs +++ b/crates/nemoclaw-sdk/tests/inference_connection.rs @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 use nemoclaw_sdk::config::ComputeDriver; -use nemoclaw_sdk::config::{Credential, Document}; +use nemoclaw_sdk::config::{Document, SecretRef}; #[test] fn missing_inference_provider_does_not_panic() { @@ -34,7 +34,7 @@ fn inference_connection_is_resolved_independently_of_the_sandbox_engine() { let mut remote = Document::parse(include_str!("fixtures/config/local.yaml").as_bytes()).unwrap(); remote.spec.inference_providers[0].endpoint = "https://inference.example.test:9443/v1".into(); - remote.spec.inference_providers[0].credential = Some(Credential { + remote.spec.inference_providers[0].credential = Some(SecretRef { env: "MODEL_TOKEN".into(), }); let first = remote.inference_connection().unwrap(); diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index f1aa04e510c..c79dab9e7d6 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -160,33 +160,6 @@ Paths: | `cudagraphMode` | string | Yes | — | CUDA graph execution mode. Constraints: `"NONE"` or `"FULL_DECODE_ONLY"`. | | `mode` | integer | Yes | — | Compilation mode understood by the pinned vLLM image. Constraints: minimum 0; maximum 3. | -## Credential - -A reference to a caller-provided environment variable; the configuration contains no credential value. - -Guide: [Configuration and credentials](../usage.md#configuration-and-credentials). - -Paths: - -- `spec.gateway.credential` -- `spec.gateway.kubernetes.kubeconfig` -- `spec.gateway.tls.ca` -- `spec.gateway.tls.certificate` -- `spec.gateway.tls.key` -- `spec.inferenceProviders[].credential` -- `spec.inferences.{key}.routes[].provider.credential` -- `spec.integrations.{key}.credential` -- `spec.sandboxes[].agent.inference.routes[].provider.credential` -- `spec.sandboxes[].agent.integrations.{key}.credential` -- `spec.sandboxes[].image.metadata` -- `spec.sandboxes[].inferenceProviders[].credential` -- `spec.sandboxes[].inferences.{key}.routes[].provider.credential` -- `spec.sandboxes[].integrations.{key}.credential` - -| Field | Input type | Required | Default | Description and constraints | -|---|---|---|---|---| -| `env` | string | Yes | — | Uppercase environment variable name. For TLS and kubeconfig fields, its value is a local file path; otherwise it is a bearer/API credential. NEMOCLAW_KUBERNETES_STATE and the NEMOCLAW_MANAGED_K8S_, HELM_, and KUBE_ prefixes are reserved for runtime controls. Constraints: pattern `^[A-Z_][A-Z0-9_]{0,127}$`. | - ## DedicatedHardware Requirements for one NVIDIA GPU with dedicated memory on Linux AMD64. Declaring requirements does not qualify a model or host. @@ -282,6 +255,24 @@ Paths: | `sha256` | string | Yes | — | Lowercase SHA-256 of the complete file. Constraints: pattern `^[a-f0-9]{64}$`. | | `size` | integer | Yes | — | Expected file length in bytes; zero is rejected. Constraints: minimum 1. | +## FileRef + +Environment variable whose value is the path of a local file; the configuration holds neither the path nor the file. + +Guide: [Configuration and credentials](../usage.md#configuration-and-credentials). + +Paths: + +- `spec.gateway.kubernetes.kubeconfig` +- `spec.gateway.tls.ca` +- `spec.gateway.tls.certificate` +- `spec.gateway.tls.key` +- `spec.sandboxes[].image.metadata` + +| Field | Input type | Required | Default | Description and constraints | +|---|---|---|---|---| +| `env` | string | Yes | — | Uppercase name of the caller environment variable that holds the local file path. NEMOCLAW_KUBERNETES_STATE and the NEMOCLAW_MANAGED_K8S_, HELM_, and KUBE_ prefixes are reserved for runtime controls. Constraints: pattern `^[A-Z_][A-Z0-9_]{0,127}$`. | + ## Gateway Install a local or explicitly configured Kubernetes gateway, or connect to an existing gateway. @@ -318,7 +309,7 @@ An existing gateway managed outside this deployment. | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| -| `credential` | [Credential](#credential) | No | — | Optional bearer credential reference for an external HTTPS gateway. | +| `credential` | [SecretRef](#secretref) | No | — | Optional bearer credential reference for an external HTTPS gateway. | | `endpoint` | string | Yes | — | Gateway HTTP(S) origin, without a path. Constraints: pattern `^https?://`. | | `engine` | string | No | — | Engine containing Docker or Podman sandbox images, used only for image metadata inspection. Required for their deployment planning; omission permits retained-state teardown. Kubernetes and OpenShift use image.metadata instead. | | `management` | string | Yes | — | Whether this deployment manages the gateway. Constraints: `"external"`. | @@ -370,7 +361,7 @@ Paths: | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| -| `metadata` | [Credential](#credential) | No | — | Environment reference to the absolute path of a local OCI metadata bundle for `ref`; required for Kubernetes and OpenShift, where no local engine can be inspected. Destroy does not read it. Its index, manifest, configuration, and Fabric catalog are verified against `ref` before use. The bundle holds no image layers or credentials. Docker and Podman inspect their engine instead. | +| `metadata` | [FileRef](#fileref) | No | — | Environment reference to the absolute path of a local OCI metadata bundle for `ref`; required for Kubernetes and OpenShift, where no local engine can be inspected. Destroy does not read it. Its index, manifest, configuration, and Fabric catalog are verified against `ref` before use. The bundle holds no image layers or credentials. Docker and Podman inspect their engine instead. | | `ref` | string | For Kubernetes sandboxes | — | Immutable image reference. Kubernetes and OpenShift require an explicit nonempty reference. For other drivers, omitted or empty selects the generic SDK agent image pin; verify that it contains the selected Fabric adapter. Constraints: `""` or pattern `^[a-zA-Z0-9][a-zA-Z0-9._:/-]*@sha256:[a-f0-9]{64}$`. Kubernetes and OpenShift require an explicit immutable image reference. For other drivers, omitted or empty selects the generic SDK agent image pin; verify that it contains the selected Fabric adapter. | ## ImagePullPolicy @@ -440,7 +431,7 @@ Paths: | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| | `api` | [InferenceApi](#inferenceapi) | No | — | Request API. Omission selects anthropic-messages for Anthropic providers and openai-completions for OpenAI providers; explicit values are preserved for Fabric validation. | -| `credential` | [Credential](#credential) | No | — | Optional API credential reference for an external HTTPS endpoint. Excluded by serviceRef. | +| `credential` | [SecretRef](#secretref) | No | — | Optional API credential reference for an external HTTPS endpoint. Excluded by serviceRef. | | `endpoint` | string | Without serviceRef | — | Inference HTTP(S) URL owned outside the deployment. Required without serviceRef and excluded with serviceRef. | | `name` | string | Yes | — | Provider name referenced by model choices. Constraints: pattern `^[a-z][a-z0-9-]{0,39}$`. | | `provider` | string | Yes | — | OpenShell provider implementation. Must match the selected API family. Constraints: `"openai"` or `"anthropic"`. | @@ -490,7 +481,7 @@ Web search with gateway-held credentials and explicit agent grants. | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| -| `credential` | [Credential](#credential) | Yes | — | Host environment reference. OpenShell supplies the search provider's placeholder to the sandbox. | +| `credential` | [SecretRef](#secretref) | Yes | — | Host environment reference. OpenShell supplies the search provider's placeholder to the sandbox. | | `kind` | string | Yes | — | Integration implementation selected by this definition. Constraints: `"webSearch"`. | | `provider` | [SearchProvider](#searchprovider) | Yes | — | Supported search service. | @@ -523,7 +514,7 @@ Paths: | `authentication` | [KubernetesAuthentication](#kubernetesauthentication) | Yes | — | Explicit generated development authentication profile; this is not a production identity service. | | `context` | string | Yes | — | Exact kubeconfig context used for every cluster operation. Constraints: pattern `^[^\x00-\x20\x7f]+$(?![\s\S])`; minimum characters 1; maximum characters 253. | | `environment` | array of string | No | — | Caller environment variables that the kubeconfig's exec credential plugin needs, such as `AWS_PROFILE` for an EKS cluster. Cluster operations receive only platform variables and these; they are resolved like credential references and never written to configuration or state. Constraints: maximum items 32; items: pattern `^[A-Z_][A-Z0-9_]{0,127}$`. | -| `kubeconfig` | [Credential](#credential) | Yes | — | Environment reference whose value is the local kubeconfig file path. The file and its credentials remain outside configuration and exported state. Process, loader, trust, proxy, cluster, Python, Helm, OpenTofu, and SDK control variable names are reserved. | +| `kubeconfig` | [FileRef](#fileref) | Yes | — | Environment reference whose value is the local kubeconfig file path. The file and its credentials remain outside configuration and exported state. Process, loader, trust, proxy, cluster, Python, Helm, OpenTofu, and SDK control variable names are reserved. | | `namespace` | string | Yes | — | Namespace for this deployment's gateway and generated development authentication resources. Constraints: pattern `^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$(?![\s\S])`; minimum characters 1; maximum characters 63. | ## Manifest @@ -983,6 +974,28 @@ Accepted input: string. Constraints: `"brave"` or `"tavily"`. +## SecretRef + +Environment variable whose value is a bearer or API credential; the configuration holds no credential value. + +Guide: [Configuration and credentials](../usage.md#configuration-and-credentials). + +Paths: + +- `spec.gateway.credential` +- `spec.inferenceProviders[].credential` +- `spec.inferences.{key}.routes[].provider.credential` +- `spec.integrations.{key}.credential` +- `spec.sandboxes[].agent.inference.routes[].provider.credential` +- `spec.sandboxes[].agent.integrations.{key}.credential` +- `spec.sandboxes[].inferenceProviders[].credential` +- `spec.sandboxes[].inferences.{key}.routes[].provider.credential` +- `spec.sandboxes[].integrations.{key}.credential` + +| Field | Input type | Required | Default | Description and constraints | +|---|---|---|---|---| +| `env` | string | Yes | — | Uppercase name of the caller environment variable that holds the credential. NEMOCLAW_KUBERNETES_STATE and the NEMOCLAW_MANAGED_K8S_, HELM_, and KUBE_ prefixes are reserved for runtime controls. Constraints: pattern `^[A-Z_][A-Z0-9_]{0,127}$`. | + ## ServiceAuthentication Generated bearer authentication for a managed inference service. @@ -1222,9 +1235,9 @@ Paths: | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| -| `ca` | [Credential](#credential) | Yes | — | Environment variable whose value names the local CA certificate file. | -| `certificate` | [Credential](#credential) | Yes | — | Environment variable whose value names the local client certificate file. | -| `key` | [Credential](#credential) | Yes | — | Environment variable whose value names the local client private-key file. | +| `ca` | [FileRef](#fileref) | Yes | — | Environment variable whose value names the local CA certificate file. | +| `certificate` | [FileRef](#fileref) | Yes | — | Environment variable whose value names the local client certificate file. | +| `key` | [FileRef](#fileref) | Yes | — | Environment variable whose value names the local client private-key file. | ## Tool diff --git a/schemas/nemoclaw-v1alpha1.schema.json b/schemas/nemoclaw-v1alpha1.schema.json index cbd23daab23..6fd70ed6f98 100644 --- a/schemas/nemoclaw-v1alpha1.schema.json +++ b/schemas/nemoclaw-v1alpha1.schema.json @@ -232,32 +232,6 @@ ], "type": "object" }, - "Credential": { - "additionalProperties": false, - "description": "A reference to a caller-provided environment variable; the configuration contains no credential value.", - "properties": { - "env": { - "description": "Uppercase environment variable name. For TLS and kubeconfig fields, its value is a local file path; otherwise it is a bearer/API credential. NEMOCLAW_KUBERNETES_STATE and the NEMOCLAW_MANAGED_K8S_, HELM_, and KUBE_ prefixes are reserved for runtime controls.", - "not": { - "anyOf": [ - { - "const": "NEMOCLAW_KUBERNETES_STATE" - }, - { - "pattern": "^(?:NEMOCLAW_MANAGED_K8S_|HELM_|KUBE_)" - } - ] - }, - "pattern": "^[A-Z_][A-Z0-9_]{0,127}$", - "type": "string", - "x-nemoclaw-error": "credential environment reference must be valid and must not shadow managed Kubernetes runtime controls" - } - }, - "required": [ - "env" - ], - "type": "object" - }, "DedicatedHardware": { "additionalProperties": false, "description": "Requirements for one NVIDIA GPU with dedicated memory on Linux AMD64. Declaring requirements does not qualify a model or host.", @@ -416,6 +390,32 @@ ], "type": "object" }, + "FileRef": { + "additionalProperties": false, + "description": "Environment variable whose value is the path of a local file; the configuration holds neither the path nor the file.", + "properties": { + "env": { + "description": "Uppercase name of the caller environment variable that holds the local file path. NEMOCLAW_KUBERNETES_STATE and the NEMOCLAW_MANAGED_K8S_, HELM_, and KUBE_ prefixes are reserved for runtime controls.", + "not": { + "anyOf": [ + { + "const": "NEMOCLAW_KUBERNETES_STATE" + }, + { + "pattern": "^(?:NEMOCLAW_MANAGED_K8S_|HELM_|KUBE_)" + } + ] + }, + "pattern": "^[A-Z_][A-Z0-9_]{0,127}$", + "type": "string", + "x-nemoclaw-error": "file reference must name a valid environment variable that does not shadow managed Kubernetes runtime controls" + } + }, + "required": [ + "env" + ], + "type": "object" + }, "Gateway": { "description": "Install a local or explicitly configured Kubernetes gateway, or connect to an existing gateway.", "oneOf": [ @@ -606,7 +606,7 @@ }, "properties": { "credential": { - "$ref": "#/$defs/Credential", + "$ref": "#/$defs/SecretRef", "description": "Optional bearer credential reference for an external HTTPS gateway." }, "endpoint": { @@ -718,7 +718,7 @@ "description": "Sandbox image identity.", "properties": { "metadata": { - "$ref": "#/$defs/Credential", + "$ref": "#/$defs/FileRef", "description": "Environment reference to the absolute path of a local OCI metadata bundle for `ref`; required for Kubernetes and OpenShift, where no local engine can be inspected. Destroy does not read it. Its index, manifest, configuration, and Fabric catalog are verified against `ref` before use. The bundle holds no image layers or credentials. Docker and Podman inspect their engine instead." }, "ref": { @@ -888,7 +888,7 @@ "description": "Request API. Omission selects anthropic-messages for Anthropic providers and openai-completions for OpenAI providers; explicit values are preserved for Fabric validation." }, "credential": { - "$ref": "#/$defs/Credential", + "$ref": "#/$defs/SecretRef", "description": "Optional API credential reference for an external HTTPS endpoint. Excluded by serviceRef." }, "endpoint": { @@ -1020,7 +1020,7 @@ "description": "Web search with gateway-held credentials and explicit agent grants.", "properties": { "credential": { - "$ref": "#/$defs/Credential", + "$ref": "#/$defs/SecretRef", "description": "Host environment reference. OpenShell supplies the search provider's placeholder to the sandbox." }, "kind": { @@ -1137,7 +1137,7 @@ "x-nemoclaw-error": "Kubernetes environment names must be unique variable names that do not shadow process, trust, proxy, or cluster controls" }, "kubeconfig": { - "$ref": "#/$defs/Credential", + "$ref": "#/$defs/FileRef", "description": "Environment reference whose value is the local kubeconfig file path. The file and its credentials remain outside configuration and exported state. Process, loader, trust, proxy, cluster, Python, Helm, OpenTofu, and SDK control variable names are reserved.", "properties": { "env": { @@ -2305,6 +2305,32 @@ ], "type": "string" }, + "SecretRef": { + "additionalProperties": false, + "description": "Environment variable whose value is a bearer or API credential; the configuration holds no credential value.", + "properties": { + "env": { + "description": "Uppercase name of the caller environment variable that holds the credential. NEMOCLAW_KUBERNETES_STATE and the NEMOCLAW_MANAGED_K8S_, HELM_, and KUBE_ prefixes are reserved for runtime controls.", + "not": { + "anyOf": [ + { + "const": "NEMOCLAW_KUBERNETES_STATE" + }, + { + "pattern": "^(?:NEMOCLAW_MANAGED_K8S_|HELM_|KUBE_)" + } + ] + }, + "pattern": "^[A-Z_][A-Z0-9_]{0,127}$", + "type": "string", + "x-nemoclaw-error": "secret reference must name a valid environment variable that does not shadow managed Kubernetes runtime controls" + } + }, + "required": [ + "env" + ], + "type": "object" + }, "ServiceAuthentication": { "description": "Generated bearer authentication for a managed inference service.", "enum": [ @@ -3269,15 +3295,15 @@ "description": "Gateway mutual TLS file references. All three references are required when TLS is declared.", "properties": { "ca": { - "$ref": "#/$defs/Credential", + "$ref": "#/$defs/FileRef", "description": "Environment variable whose value names the local CA certificate file." }, "certificate": { - "$ref": "#/$defs/Credential", + "$ref": "#/$defs/FileRef", "description": "Environment variable whose value names the local client certificate file." }, "key": { - "$ref": "#/$defs/Credential", + "$ref": "#/$defs/FileRef", "description": "Environment variable whose value names the local client private-key file." } }, From 464d175f5f5c7c6e1c0238a28e9b27a65c705e21 Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Tue, 13 Oct 2026 20:27:46 +0000 Subject: [PATCH 4/9] refactor(config)!: select the gateway backend with one tagged target Three inputs had to agree to select a backend: `runtime.provider`, whether `gateway.kubernetes` was present, and the flat `engine`, `image`, `imagePullPolicy`, and `networkCIDR` fields. Root-level conditionals enforced their pairing, editors offered Docker's socket on a Kubernetes gateway, and moving a document between backends failed at several unrelated locations. `spec.gateway.target` now holds exactly one key: - Managed `docker`: `endpoint`, `engine`, `imagePullPolicy` (IfNotPresent or Never), and `networkCidr`, each defaulted as before. - Managed `podman`: the same fields; `engine` is required and `imagePullPolicy` also accepts Always. - Managed `kubernetes`: `distribution` (kubernetes or openshift), a required HTTPS loopback `endpoint`, and the existing cluster fields. The openshift distribution reads the namespace's SCC UID range, records that identity, passes it as Helm security-context values, and binds the compute driver as openshift. - External `docker` or `podman` take an optional image-inspection `engine`; external `kubernetes` takes no settings, because the gateway reports only the kubernetes driver. Plan still checks the key against the reported driver. `gateway.runtime.provider` is removed, the managed `endpoint` moves into its target, and `networkCIDR` is spelled `networkCidr` like `ServicePlacement`. `gateway.image` leaves the authored contract: its only valid value was the SDK's digest, so defaulted and exported documents broke after each OpenShell update. The SDK now resolves the pinned image internally; the resolved image stays bound in provider state, so a pin change still needs the original bundle or a separate deployment. Compiled output is unchanged: the internal gateway settings keep their serialized layout, so typed state rows, service specifications, spec labels, Helm targets, and digests of equivalent documents match the earlier shape byte for byte across every example. Fields at their earlier locations report where they moved. Onboarding asks for the target key where it asked for the runtime, with the same choices first. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Hai Nguyen --- .../examples/print_journey_tree.rs | 2 +- .../nemoclaw-authoring/src/journey_state.rs | 33 +- .../src/journey_state/answer.rs | 51 +- .../src/journey_state/authored_values.rs | 117 ++- .../src/journey_state/observations.rs | 54 +- .../src/journey_state/paths.rs | 22 + .../journey_state/resolver/sdk_questions.rs | 71 +- crates/nemoclaw-authoring/src/sdk_schema.rs | 65 +- .../src/target_assessment.rs | 32 +- .../tests/deployment_journey.rs | 15 +- .../tests/discovery_queries.rs | 10 +- .../tests/environment_observations.rs | 27 +- .../tests/journey_guidance.rs | 12 +- .../tests/journey_resolution.rs | 349 +++++++-- .../tests/onboarding_journey_presets.rs | 12 +- crates/nemoclaw-authoring/tests/support.rs | 11 +- .../tests/target_assessment.rs | 86 +- crates/nemoclaw-build/src/ci/live.rs | 10 +- crates/nemoclaw-build/src/schema/reference.rs | 23 +- crates/nemoclaw-build/tests/ci.rs | 10 +- crates/nemoclaw-cli/src/args.rs | 12 +- .../fixtures/hermes-nvidia-hosted/v1.yaml | 11 +- .../fixtures/openclaw-nvidia-hosted/v1.yaml | 11 +- crates/nemoclaw-e2e/src/image_runtime.rs | 8 +- crates/nemoclaw-e2e/tests/brev.rs | 4 +- crates/nemoclaw-e2e/tests/deployment.rs | 6 +- crates/nemoclaw-e2e/tests/dummy_agent.rs | 13 +- crates/nemoclaw-e2e/tests/fabric_live.rs | 2 +- crates/nemoclaw-e2e/tests/helm_recovery.rs | 7 +- crates/nemoclaw-e2e/tests/hosted_parity.rs | 29 +- crates/nemoclaw-e2e/tests/kubernetes_live.rs | 33 +- crates/nemoclaw-e2e/tests/managed_gateway.rs | 4 +- crates/nemoclaw-e2e/tests/model_live.rs | 10 +- crates/nemoclaw-e2e/tests/remote_service.rs | 6 +- .../tests/service_images/managed.rs | 2 +- .../tests/service_images/support.rs | 2 +- crates/nemoclaw-e2e/tests/tls.rs | 1 - crates/nemoclaw-onboarding/README.md | 12 +- crates/nemoclaw-onboarding/src/lib.rs | 8 +- crates/nemoclaw-onboarding/src/tui/labels.rs | 24 +- crates/nemoclaw-onboarding/src/tui/tests.rs | 19 +- crates/nemoclaw-onboarding/src/tui/text.json | 31 +- crates/nemoclaw-openshell/src/capabilities.rs | 2 +- crates/nemoclaw-openshell/src/observation.rs | 12 +- .../tests/contract/discovery.rs | 2 +- .../tests/managed_gateway_live.rs | 2 +- crates/nemoclaw-sdk/src/compile.rs | 2 +- crates/nemoclaw-sdk/src/compile_runtime.rs | 26 +- crates/nemoclaw-sdk/src/compile_teardown.rs | 3 +- crates/nemoclaw-sdk/src/config/kubernetes.rs | 22 +- crates/nemoclaw-sdk/src/config/mod.rs | 161 ++-- crates/nemoclaw-sdk/src/config/schema.rs | 2 +- .../nemoclaw-sdk/src/config/schema/runtime.rs | 93 ++- .../src/config/schema/validation.rs | 300 ++++--- crates/nemoclaw-sdk/src/config/types.rs | 146 ++-- crates/nemoclaw-sdk/src/config/validation.rs | 42 +- .../src/deployment/runtime/tests.rs | 16 +- crates/nemoclaw-sdk/src/deployment/tests.rs | 18 +- crates/nemoclaw-sdk/src/discovery.rs | 17 +- crates/nemoclaw-sdk/src/discovery_graph.rs | 4 +- crates/nemoclaw-sdk/src/docker_compute.rs | 17 +- crates/nemoclaw-sdk/src/kubernetes/mod.rs | 21 +- .../nemoclaw-sdk/src/kubernetes/operations.rs | 2 +- crates/nemoclaw-sdk/src/managed/mod.rs | 2 + crates/nemoclaw-sdk/src/managed/settings.rs | 268 +++++++ crates/nemoclaw-sdk/src/managed/spec.rs | 9 +- .../src/services/installers/ollama/mod.rs | 2 +- crates/nemoclaw-sdk/src/services/placement.rs | 14 +- crates/nemoclaw-sdk/src/services/registry.rs | 17 +- crates/nemoclaw-sdk/src/state/tests.rs | 8 +- crates/nemoclaw-sdk/tests/compile.rs | 20 +- crates/nemoclaw-sdk/tests/config.rs | 35 +- crates/nemoclaw-sdk/tests/config_input.rs | 38 +- crates/nemoclaw-sdk/tests/config_kinds.rs | 108 ++- .../nemoclaw-sdk/tests/config_kubernetes.rs | 318 +++++--- crates/nemoclaw-sdk/tests/config_openshift.rs | 144 +++- crates/nemoclaw-sdk/tests/config_scenarios.rs | 18 +- crates/nemoclaw-sdk/tests/config_schema.rs | 449 +++++++++-- .../nemoclaw-sdk/tests/config_validation.rs | 5 +- crates/nemoclaw-sdk/tests/fabric_planner.rs | 10 +- .../tests/fixtures/config/fabric-claude.yaml | 4 +- .../tests/fixtures/config/fabric-pi.yaml | 4 +- .../tests/fixtures/config/fabric.yaml | 4 +- .../tests/fixtures/config/local.yaml | 4 +- .../tests/fixtures/config/managed-ollama.yaml | 11 +- .../tests/fixtures/config/spark.yaml | 11 +- .../discovery_graph/external-service.json | 2 +- .../fixtures/discovery_graph/openclaw.json | 2 +- .../tests/fixtures/discovery_graph/spark.json | 2 +- .../tests/inference_connection.rs | 24 +- .../nemoclaw-sdk/tests/kubernetes_compile.rs | 2 +- .../tests/kubernetes_managed_compile.rs | 24 +- crates/nemoclaw-sdk/tests/managed_podman.rs | 4 +- crates/nemoclaw-sdk/tests/ollama_proxy.rs | 10 +- .../nemoclaw-sdk/tests/resource_management.rs | 4 +- crates/nemoclaw-sdk/tests/runtime_compile.rs | 4 +- .../nemoclaw-sdk/tests/service_references.rs | 3 +- .../tests/support/scripted_tofu.rs | 8 +- .../tests/contract/capabilities.rs | 2 +- docs/build.md | 2 +- docs/contributing/configuration-schema.md | 2 + docs/contributing/live-tests.md | 2 +- docs/design/architecture.md | 2 +- docs/design/authoring-domain.md | 7 +- docs/design/onboarding-journeys.md | 10 +- docs/get-started.md | 6 +- docs/inference.md | 2 +- docs/kubernetes.md | 40 +- docs/provider.md | 2 +- docs/reference/configuration.md | 187 ++++- docs/usage.md | 42 +- examples/explicit-policy.yaml | 4 +- examples/fabric-claude.yaml | 4 +- examples/fabric-codex.yaml | 4 +- examples/fabric-hermes.yaml | 4 +- examples/fabric-mini-swe-agent.yaml | 4 +- examples/fabric-nooa-bench.yaml | 4 +- examples/fabric-nooa.yaml | 4 +- examples/fabric-openclaw.yaml | 4 +- examples/fabric-pi.yaml | 4 +- examples/fabric-remote-agent.yaml | 4 +- examples/fabric.yaml | 4 +- examples/full-featured-openclaw.yaml | 12 +- examples/hermes-auth.yaml | 4 +- examples/hermes-interfaces.yaml | 4 +- examples/inference-tuning.yaml | 4 +- examples/kubernetes/external-gateway.yaml | 4 +- examples/kubernetes/hosted-nvidia.yaml | 4 +- examples/kubernetes/managed-development.yaml | 19 +- examples/local.yaml | 4 +- examples/managed-hermes.yaml | 12 +- examples/managed-ollama-gpu.yaml | 12 +- examples/managed-ollama.yaml | 12 +- examples/managed-podman.yaml | 8 +- examples/multiple-sandboxes.yaml | 4 +- examples/nemotron-amd64.yaml | 4 +- examples/onboarding/openclaw.yaml | 4 +- examples/openclaw-dashboard.yaml | 8 +- examples/openshift/external-gateway.yaml | 5 +- examples/openshift/managed-development.yaml | 20 +- examples/spark/deepagents-team.yaml | 8 +- examples/spark/local-and-hosted.yaml | 8 +- examples/spark/pi-small.yaml | 8 +- examples/spark/remote-vllm.yaml | 4 +- examples/spark/shared-model.yaml | 8 +- examples/spark/spark-inline.yaml | 12 +- examples/spark/two-models.yaml | 8 +- examples/spark/vllm.yaml | 12 +- examples/station/shared-model.yaml | 12 +- examples/station/vllm.yaml | 12 +- schemas/nemoclaw-v1alpha1.schema.json | 735 ++++++++---------- 151 files changed, 3393 insertions(+), 1697 deletions(-) create mode 100644 crates/nemoclaw-sdk/src/managed/settings.rs diff --git a/crates/nemoclaw-authoring/examples/print_journey_tree.rs b/crates/nemoclaw-authoring/examples/print_journey_tree.rs index 4f65af96ee1..069a912cdab 100644 --- a/crates/nemoclaw-authoring/examples/print_journey_tree.rs +++ b/crates/nemoclaw-authoring/examples/print_journey_tree.rs @@ -50,7 +50,7 @@ fn main() -> Result<(), Box> { .ask([ "/metadata/name", "/spec/sandboxes/0/harness/kind", - "/spec/gateway/runtime/provider", + "/spec/gateway/target", "/spec/inferenceProviders/0/provider", "/spec/inferenceProviders/0/api", "/spec/sandboxes/0/agent/inference/routes/0/overrides/model", diff --git a/crates/nemoclaw-authoring/src/journey_state.rs b/crates/nemoclaw-authoring/src/journey_state.rs index 442b9d9bf1b..936b7f4da25 100644 --- a/crates/nemoclaw-authoring/src/journey_state.rs +++ b/crates/nemoclaw-authoring/src/journey_state.rs @@ -25,15 +25,15 @@ use crate::{ }, sdk_schema::{ finite_choices, sdk_discriminator, sdk_exclusive_required_fields, sdk_field_possible, - sdk_field_schema, sdk_field_schema_for, sdk_selected_branch, + sdk_field_schema, sdk_field_schema_for, sdk_selected_branch, sdk_variant_key, + sdk_variant_keys, }, settings::SettingQuestion, }; const ROUTE_SELECTION: &str = "route:selection"; const ROUTES: &str = "/spec/sandboxes/0/agent/inference/routes"; -const RUNTIME_PROVIDER: &str = "/spec/gateway/runtime/provider"; -const GATEWAY_ENGINE_PATH: &str = "/spec/gateway/engine"; +const GATEWAY_TARGET: &str = "/spec/gateway/target"; /// Why an applicable decision is still open. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -52,13 +52,16 @@ pub enum JourneyQuestionKind { } /// The operation represented by a question. IDs remain stable UI keys; this -/// target carries the meaning needed to apply and record an answer. +/// target carries the meaning needed to apply and record an answer. A +/// `VariantKey` answer selects the key of an externally tagged union, such as +/// the gateway target. #[derive(Clone, Debug, PartialEq, Eq)] enum QuestionTarget { DeploymentName, Harness, SdkField { path: String, role: SdkFieldRole }, StructuralForm { path: String }, + VariantKey { path: String }, RouteSelection { routes: Vec<(String, usize)> }, InferencePreset { route: usize }, AdapterSetting { adapter: String, pointer: String }, @@ -71,7 +74,6 @@ enum SdkFieldRole { Plain, ProviderApi, ProviderEndpoint, - RuntimeProvider, GatewayManagement, GatewayEngine, } @@ -96,11 +98,14 @@ impl QuestionTarget { && segments[1] == "spec" && segments[2] == "inferenceProviders" && segments[3].parse::().is_ok(); - let role = if path == RUNTIME_PROVIDER { - SdkFieldRole::RuntimeProvider - } else if path == "/spec/gateway/management" { + let target_field = path + .strip_prefix(GATEWAY_TARGET) + .and_then(|rest| rest.strip_prefix('/')) + .and_then(|rest| rest.split_once('/')) + .map(|(_, field)| field); + let role = if path == "/spec/gateway/management" { SdkFieldRole::GatewayManagement - } else if path == GATEWAY_ENGINE_PATH { + } else if target_field == Some("engine") { SdkFieldRole::GatewayEngine } else if provider_field && segments[4] == "api" { SdkFieldRole::ProviderApi @@ -285,9 +290,9 @@ impl JourneyState { } /// Keep the `candidates` this machine has that `observations` show as - /// available. A runtime they offer becomes the suggestion when it is the - /// only one, and choosing a runtime targets the engine that answered for it. - /// A managed gateway's runtime that none answered for is reported first. + /// available. A gateway target they offer becomes the suggestion when it is + /// the only one, and choosing a target uses the engine that answered for it. + /// A managed gateway's target that none answered for is reported first. pub fn use_local_engines( &mut self, candidates: &[DiscoveryRequest], @@ -346,6 +351,6 @@ use authored_values::AuthoredValues; use decision_record::DecisionRecord; use journey_position::JourneyPosition; use paths::{ - escape_pointer, harness_kind, harness_path, native_value, routes_path, scalar_question, - settings_path, + escape_pointer, harness_kind, harness_path, managed_target_engine, native_value, routes_path, + scalar_question, settings_path, }; diff --git a/crates/nemoclaw-authoring/src/journey_state/answer.rs b/crates/nemoclaw-authoring/src/journey_state/answer.rs index 31c97f5759f..2a5b097b4b2 100644 --- a/crates/nemoclaw-authoring/src/journey_state/answer.rs +++ b/crates/nemoclaw-authoring/src/journey_state/answer.rs @@ -104,6 +104,16 @@ impl JourneyState { .selected_forms .insert(path.into(), selected); } + QuestionTarget::VariantKey { path } => { + candidate + .authored + .put_variant_key(path, value.as_ref().and_then(Value::as_str))?; + if path == GATEWAY_TARGET { + candidate.authored.sync_gateway_engine_for_target( + candidate.answered_engines.as_deref().unwrap_or_default(), + )?; + } + } QuestionTarget::RouteSelection { routes } => { let name = value .as_ref() @@ -171,11 +181,8 @@ impl JourneyState { if *role == SdkFieldRole::GatewayEngine { candidate.authored.generated_gateway_engine = false; } - if matches!( - role, - SdkFieldRole::RuntimeProvider | SdkFieldRole::GatewayManagement - ) { - candidate.authored.sync_gateway_engine_for_runtime( + if *role == SdkFieldRole::GatewayManagement { + candidate.authored.sync_gateway_engine_for_target( candidate.answered_engines.as_deref().unwrap_or_default(), )?; } @@ -293,6 +300,20 @@ impl JourneyState { .put_sdk_field(&format!("{path}/{}", escape_pointer(&selected)), None)?; Some(Value::String(selected)) } + QuestionTarget::VariantKey { path } => { + let Some((schema, _)) = sdk_field_schema_for(&self.authored.values, path) else { + return Err(diagnostic( + "journey", + "This question is no longer applicable.", + )); + }; + previous + .authored + .values + .pointer(path) + .and_then(|supplied| sdk_variant_key(&schema, supplied)) + .map(Value::String) + } QuestionTarget::WorkflowSetting { .. } => { previous.definition.ask.insert(id.into()); native_value( @@ -330,14 +351,22 @@ impl JourneyState { } }; let mut question = previous.resolve(capabilities)?.question(id).cloned(); - if question.is_none() - && let QuestionTarget::SdkField { path, .. } = &target - { + if question.is_none() { // An implicit missing-field question disappears after its first // answer. Recreate the gap in this temporary copy to recover its - // current schema without changing the accepted document. - previous.authored.put_sdk_field(path, None)?; - question = previous.resolve(capabilities)?.question(id).cloned(); + // current schema without changing the accepted document; a union + // that names no key is the gap of a key question. + let gap = match &target { + QuestionTarget::SdkField { path, .. } => Some((path, None)), + QuestionTarget::VariantKey { path } => { + Some((path, Some(Value::Object(Map::new())))) + } + _ => None, + }; + if let Some((path, value)) = gap { + previous.authored.put_sdk_field(path, value)?; + question = previous.resolve(capabilities)?.question(id).cloned(); + } } let mut question = question .ok_or_else(|| diagnostic("journey", "This question is no longer applicable."))?; diff --git a/crates/nemoclaw-authoring/src/journey_state/authored_values.rs b/crates/nemoclaw-authoring/src/journey_state/authored_values.rs index 095e72eb387..74323e30685 100644 --- a/crates/nemoclaw-authoring/src/journey_state/authored_values.rs +++ b/crates/nemoclaw-authoring/src/journey_state/authored_values.rs @@ -218,65 +218,120 @@ impl AuthoredValues { } /// Remove sibling fields that the SDK schema defined before a write but no - /// longer defines, such as fields of the previous gateway form. + /// longer defines, such as fields of the previous gateway form. Objects + /// that both forms define lose the nested fields only the previous one did, + /// such as a managed target's network under an external gateway. pub(super) fn remove_inactive_siblings(&mut self, pointer: &str, before: &Value) { let Some((parent, _)) = pointer.rsplit_once('/') else { return; }; - let Some(siblings) = self.values.pointer(parent).and_then(Value::as_object) else { + self.remove_inactive_fields(parent, pointer, before, 0); + } + + fn remove_inactive_fields( + &mut self, + parent: &str, + written: &str, + before: &Value, + depth: usize, + ) { + let Some(fields) = self.values.pointer(parent).and_then(Value::as_object) else { return; }; - let inactive = siblings - .keys() - .filter(|key| { - let field = format!("{parent}/{}", escape_pointer(key)); - field != pointer - && sdk_field_schema_for(before, &field).is_some() - && sdk_field_schema_for(&self.values, &field).is_none() - }) - .cloned() - .collect::>(); - if let Some(siblings) = self + let mut inactive = Vec::new(); + let mut active_objects = Vec::new(); + for (key, value) in fields { + let field = format!("{parent}/{}", escape_pointer(key)); + if field == written || sdk_field_schema_for(before, &field).is_none() { + continue; + } + if sdk_field_schema_for(&self.values, &field).is_none() { + inactive.push(key.clone()); + } else if value.is_object() && depth < 16 { + active_objects.push(field); + } + } + if let Some(fields) = self .values .pointer_mut(parent) .and_then(Value::as_object_mut) { for key in inactive { - siblings.remove(&key); + fields.remove(&key); } } + for object in active_objects { + self.remove_inactive_fields(&object, written, before, depth + 1); + } } - /// Target a managed gateway at the local engine that answered for the - /// chosen runtime. Without one, a generated engine is withdrawn rather - /// than left pointing at another runtime's engine. - pub(super) fn sync_gateway_engine_for_runtime( + /// Select `key` of the externally tagged union at `pointer`, or omit the + /// union. Settings of the previous key carry over when the new key's + /// schema defines and accepts them, such as the engine field both targets + /// define. + pub(super) fn put_variant_key( &mut self, - answered_engines: &[DiscoveryRequest], + pointer: &str, + key: Option<&str>, ) -> Result<(), Diagnostics> { - if self + let Some(key) = key else { + return self.put_sdk_field(pointer, None); + }; + let previous = self .values - .pointer("/spec/gateway/management") - .and_then(Value::as_str) - != Some("managed") - { + .pointer(pointer) + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + if previous.len() == 1 && previous.get(key).is_some_and(Value::is_object) { return Ok(()); } - if self.values.pointer(GATEWAY_ENGINE_PATH).is_some() && !self.generated_gateway_engine { + let settings = previous + .get(key) + .or_else(|| { + (previous.len() == 1) + .then(|| previous.values().next()) + .flatten() + }) + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + self.put_sdk_field(pointer, Some(serde_json::json!({ key: {} })))?; + let selected = format!("{pointer}/{}", escape_pointer(key)); + let carried = settings + .into_iter() + .filter(|(name, value)| { + sdk_field_schema_for( + &self.values, + &format!("{selected}/{}", escape_pointer(name)), + ) + .is_some_and(|(schema, _)| schema_accepts(&schema, value) == Some(true)) + }) + .collect::>(); + self.put_sdk_field(&selected, Some(Value::Object(carried))) + } + + /// Point a managed gateway's target at the local engine that answered for + /// it. Without one, a generated engine is withdrawn rather than left + /// pointing at another target's engine. + pub(super) fn sync_gateway_engine_for_target( + &mut self, + answered_engines: &[DiscoveryRequest], + ) -> Result<(), Diagnostics> { + let Some((target, path)) = managed_target_engine(&self.values) else { + return Ok(()); + }; + if self.values.pointer(&path).is_some() && !self.generated_gateway_engine { return Ok(()); } - let runtime = self - .values - .pointer(RUNTIME_PROVIDER) - .and_then(Value::as_str); let engine = answered_engines .iter() - .find(|request| Some(request.compute_driver.as_str()) == runtime) + .find(|request| request.compute_driver.as_str() == target) .map(|request| Value::String(request.engine.clone())); if engine.is_none() && !self.generated_gateway_engine { return Ok(()); } self.generated_gateway_engine = engine.is_some(); - self.put_sdk_field(GATEWAY_ENGINE_PATH, engine) + self.put_sdk_field(&path, engine) } } diff --git a/crates/nemoclaw-authoring/src/journey_state/observations.rs b/crates/nemoclaw-authoring/src/journey_state/observations.rs index 7ceb86b4d41..76791c1eca7 100644 --- a/crates/nemoclaw-authoring/src/journey_state/observations.rs +++ b/crates/nemoclaw-authoring/src/journey_state/observations.rs @@ -14,20 +14,20 @@ impl JourneyState { observations: &DiscoveryObservations, ) -> Result { let mut resolution = self.resolve(capabilities)?; - // A host that can run only one local runtime makes it the suggestion, + // A host that can run only one local target makes it the suggestion, // even over a supplied value; the user still decides. let answered = self.answered_engines.as_deref().unwrap_or_default(); - let mut runtimes: Vec<&str> = Vec::new(); + let mut targets: Vec<&str> = Vec::new(); for engine in answered { - if !runtimes.contains(&engine.compute_driver.as_str()) { - runtimes.push(engine.compute_driver.as_str()); + if !targets.contains(&engine.compute_driver.as_str()) { + targets.push(engine.compute_driver.as_str()); } } - if let [only] = runtimes.as_slice() + if let [only] = targets.as_slice() && let Some(question) = resolution .questions .iter_mut() - .find(|question| question.id == RUNTIME_PROVIDER) + .find(|question| question.id == GATEWAY_TARGET) { question.suggestion = Some(Value::String((*only).into())); } @@ -36,20 +36,21 @@ impl JourneyState { { resolution.target_assessment = Some(crate::assess_target(document, observations)?); } - // Without an engine for its runtime, a managed gateway falls back to the - // SDK's default socket, whose read reports a mismatch rather than the - // cause. That default is Docker's socket, so it is not offered as the - // engine either: accepting it would author a socket no engine answered on. - if let Some(runtime) = self.runtime_without_local_engine() { + // Without an engine for its target, a managed gateway reports that cause + // first. Only a Docker target has a default engine, Docker's standard + // socket, and its read would report a mismatch rather than the cause. + // That default is not offered as the engine either: accepting it would + // author a socket no engine answered on. + if let Some((target, engine)) = self.target_without_local_engine() { if let Some(question) = resolution .questions .iter_mut() - .find(|question| question.id == GATEWAY_ENGINE_PATH) + .find(|question| question.id == engine) { question.suggestion = None; } let reason = format!( - "No {runtime} engine answered on this machine. Start it, or set spec.gateway.engine to its socket." + "No {target} engine answered on this machine. Start it, or set spec.gateway.target.{target}.engine to its socket." ); // Podman has no default engine, so its document stays incomplete // and no target was assessed; the cause is still the first thing @@ -131,24 +132,17 @@ impl JourneyState { Ok(resolution) } - /// The chosen runtime of a managed gateway without an authored engine, when - /// this machine was asked and no engine answered for that runtime. - fn runtime_without_local_engine(&self) -> Option<&str> { + /// The chosen local target of a managed gateway without an authored + /// engine, and that engine's pointer, when this machine was asked and no + /// engine answered for that target. + fn target_without_local_engine(&self) -> Option<(String, String)> { let answered = self.answered_engines.as_deref()?; - let values = &self.authored.values; - if values - .pointer("/spec/gateway/management") - .and_then(Value::as_str) - != Some("managed") - || values.pointer(GATEWAY_ENGINE_PATH).is_some() - { - return None; - } - let runtime = values.pointer(RUNTIME_PROVIDER).and_then(Value::as_str)?; - (!answered - .iter() - .any(|engine| engine.compute_driver.as_str() == runtime)) - .then_some(runtime) + let (target, engine) = managed_target_engine(&self.authored.values)?; + (self.authored.values.pointer(&engine).is_none() + && !answered + .iter() + .any(|observed| observed.compute_driver.as_str() == target)) + .then_some((target, engine)) } /// Accept remaining suggestions as one explicit, fact-gated action. diff --git a/crates/nemoclaw-authoring/src/journey_state/paths.rs b/crates/nemoclaw-authoring/src/journey_state/paths.rs index 899c4f21e39..aa83bc0ec99 100644 --- a/crates/nemoclaw-authoring/src/journey_state/paths.rs +++ b/crates/nemoclaw-authoring/src/journey_state/paths.rs @@ -55,6 +55,28 @@ pub(super) fn settings_path(values: &Value) -> Option { harness_path(values).map(|path| format!("{path}/settings")) } +/// The managed gateway's target key and the pointer to its engine, when the +/// selected target runs on a local engine. A cluster target has no engine. +pub(super) fn managed_target_engine(values: &Value) -> Option<(String, String)> { + if values + .pointer("/spec/gateway/management") + .and_then(Value::as_str) + != Some("managed") + { + return None; + } + let [key] = values + .pointer(GATEWAY_TARGET)? + .as_object()? + .keys() + .collect::>()[..] + else { + return None; + }; + let engine = format!("{GATEWAY_TARGET}/{}/engine", escape_pointer(key)); + sdk_field_schema_for(values, &engine).map(|_| (key.clone(), engine)) +} + pub(super) fn escape_pointer(segment: &str) -> String { segment.replace('~', "~0").replace('/', "~1") } diff --git a/crates/nemoclaw-authoring/src/journey_state/resolver/sdk_questions.rs b/crates/nemoclaw-authoring/src/journey_state/resolver/sdk_questions.rs index 06f820d861d..25d4d2c7437 100644 --- a/crates/nemoclaw-authoring/src/journey_state/resolver/sdk_questions.rs +++ b/crates/nemoclaw-authoring/src/journey_state/resolver/sdk_questions.rs @@ -69,25 +69,40 @@ impl QuestionResolver<'_> { else { continue; }; - let schema = policy.sdk_schema(field, schema); - let value = self.authored.values.pointer(field); - let valid = value.is_some_and(|value| schema_accepts(&schema, value) == Some(true)); - if value.is_none() || !valid || !self.decisions.accepted.contains(field) { + let supplied = self.authored.values.pointer(field); + let (target, schema, value) = match variant_key_field(&schema, supplied) { + Some((schema, key)) => ( + QuestionTarget::VariantKey { + path: field.clone(), + }, + schema, + key, + ), + None => ( + QuestionTarget::sdk(field.clone()), + policy.sdk_schema(field, schema), + supplied.cloned(), + ), + }; + let valid = value + .as_ref() + .is_some_and(|value| schema_accepts(&schema, value) == Some(true)); + if supplied.is_none() || !valid || !self.decisions.accepted.contains(field) { questions.push(JourneyQuestion { - target: QuestionTarget::sdk(field.clone()), + target, kind: JourneyQuestionKind::Field, reopened_because: None, id: field.clone(), - reason: if value.is_some() && !valid { + reason: if supplied.is_some() && !valid { JourneyQuestionReason::InvalidSupplied - } else if value.is_none() { + } else if supplied.is_none() { JourneyQuestionReason::Missing } else { JourneyQuestionReason::ExplicitAsk }, required, choices: finite_choices(&schema), - suggestion: value.cloned().or_else(|| schema.get("default").cloned()), + suggestion: value.or_else(|| schema.get("default").cloned()), schema, title: None, description: None, @@ -120,6 +135,30 @@ impl QuestionResolver<'_> { else { continue; }; + if let Some((schema, key)) = variant_key_field(&schema, supplied) { + if self.authored.values.pointer(parent).is_some() { + questions.push(JourneyQuestion { + target: QuestionTarget::VariantKey { + path: issue.path().into(), + }, + kind: JourneyQuestionKind::Field, + reopened_because: None, + id: issue.path().into(), + reason: if supplied.is_some() { + JourneyQuestionReason::InvalidSupplied + } else { + JourneyQuestionReason::Missing + }, + required: required || issue.kind() == PartialIssueKind::Missing, + choices: finite_choices(&schema), + suggestion: key, + schema, + title: None, + description: None, + }); + } + continue; + } if issue.kind() == PartialIssueKind::Deferred && sdk_discriminator(&schema).is_none() && sdk_exclusive_required_fields(&schema).is_none() @@ -162,3 +201,19 @@ impl QuestionResolver<'_> { } } } + +/// An externally tagged union is asked as the choice of its key: the question +/// offers the SDK's keys, and its value is the key that the supplied object +/// names or, when nothing is supplied, the key that the union's default names. +fn variant_key_field(schema: &Value, supplied: Option<&Value>) -> Option<(Value, Option)> { + let keys = sdk_variant_keys(schema)?; + let key = supplied + .or_else(|| schema.get("default")) + .and_then(|value| sdk_variant_key(schema, value)) + .map(Value::String); + let mut field = serde_json::json!({"type": "string", "enum": keys}); + if let Some(description) = schema.get("description") { + field["description"] = description.clone(); + } + Some((field, key)) +} diff --git a/crates/nemoclaw-authoring/src/sdk_schema.rs b/crates/nemoclaw-authoring/src/sdk_schema.rs index 1918f9a3f3a..46da898b139 100644 --- a/crates/nemoclaw-authoring/src/sdk_schema.rs +++ b/crates/nemoclaw-authoring/src/sdk_schema.rs @@ -6,7 +6,7 @@ use std::sync::OnceLock; use crate::fingerprint::sha256; -use nemoclaw_sdk::config::schema::{input_schema, select_variant}; +use nemoclaw_sdk::config::schema::{input_schema, select_variant, variant_keys}; use nemoclaw_sdk::json_schema::schema_accepts; use serde_json::{Value, json}; @@ -155,6 +155,12 @@ fn field_schema_in(root: &Value, values: &Value, path: &str) -> Option<(Value, b current_path.push_str(part); } let mut field = follow_ref(root, node)?.clone(); + // A default beside a reference belongs to this use of the definition. + if let Some(default) = node.get("default") + && let Some(object) = field.as_object_mut() + { + object.insert("default".into(), default.clone()); + } attach_definitions(root, &mut field); Some((field, required)) } @@ -316,6 +322,29 @@ pub(crate) fn sdk_selected_branch<'a>(schema: &'a Value, supplied: &Value) -> Op }) } +/// The keys of an externally tagged union, in schema order: every `oneOf` +/// branch is an object that SDK diagnostics select by its one required key. +pub(crate) fn sdk_variant_keys(schema: &Value) -> Option> { + let branches = schema.get("oneOf")?.as_array()?; + Some( + variant_keys(branches)? + .into_iter() + .map(str::to_owned) + .collect(), + ) +} + +/// The key of an externally tagged union that a supplied object names, when +/// it names exactly one of the union's keys and nothing else. +pub(crate) fn sdk_variant_key(schema: &Value, supplied: &Value) -> Option { + let [key] = supplied.as_object()?.keys().collect::>()[..] else { + return None; + }; + sdk_variant_keys(schema)? + .into_iter() + .find(|known| known == key) +} + /// Finite values advertised by a field schema. Free input remains possible /// when this list is empty or the question kind explicitly allows it. pub(crate) fn finite_choices(schema: &Value) -> Vec { @@ -405,4 +434,38 @@ mod tests { let values = json!({"target": {"docker": {}}}); assert!(field_schema_in(&root, &values, "/target/podman/engine").is_none()); } + + #[test] + fn only_a_union_of_single_key_objects_offers_its_keys() { + let keyed_union = json!({"oneOf": [ + keyed("docker", json!({"type": "object"})), + keyed("podman", json!({"type": "object"})), + ]}); + assert_eq!( + sdk_variant_keys(&keyed_union), + Some(vec!["docker".to_owned(), "podman".to_owned()]) + ); + assert_eq!( + sdk_variant_key(&keyed_union, &json!({"podman": {"engine": "x"}})), + Some("podman".to_owned()) + ); + for supplied in [ + json!({}), + json!({"dockr": {}}), + json!({"docker": {}, "podman": {}}), + ] { + assert_eq!(sdk_variant_key(&keyed_union, &supplied), None, "{supplied}"); + } + // A constant discriminator and open objects are not keyed unions. + let tagged = json!({"oneOf": [ + {"properties": {"kind": {"const": "a"}}, "required": ["kind"]}, + {"properties": {"kind": {"const": "b"}}, "required": ["kind"]}, + ]}); + let open = json!({"oneOf": [ + {"properties": {"a": {}}, "required": ["a"]}, + {"properties": {"b": {}}, "required": ["b"]}, + ]}); + assert_eq!(sdk_variant_keys(&tagged), None); + assert_eq!(sdk_variant_keys(&open), None); + } } diff --git a/crates/nemoclaw-authoring/src/target_assessment.rs b/crates/nemoclaw-authoring/src/target_assessment.rs index 426b4a46833..9672eeee2b4 100644 --- a/crates/nemoclaw-authoring/src/target_assessment.rs +++ b/crates/nemoclaw-authoring/src/target_assessment.rs @@ -3,7 +3,7 @@ use crate::{Diagnostics, diagnostics::diagnostic}; use nemoclaw_sdk::{ - config::{Document, Gateway}, + config::Document, discovery::{DiscoveryObservations, DiscoveryQuery, ObservationStatus, plan_queries}, fabric_capabilities::Support, }; @@ -23,9 +23,10 @@ pub enum CompatibilityStatus { Conflict, } -/// Compatibility applies to the packaged adapter and, for managed gateways, -/// the selected execution engine. External image stores do not establish the -/// gateway's platform, deployment readiness, or successful inference. +/// Compatibility applies to the packaged adapter and, for managed Docker and +/// Podman gateways, the selected execution engine. External image stores do +/// not establish the gateway's platform, deployment readiness, or successful +/// inference. #[derive(Clone, Debug, PartialEq, Eq)] pub struct DiscoveryAssessment { pub status: CompatibilityStatus, @@ -41,10 +42,7 @@ pub(crate) fn target_of(document: &Document) -> Result { )); }; Ok(Target { - engine: match &document.spec.gateway { - Gateway::Managed(gateway) => gateway.engine.clone(), - Gateway::External(gateway) => gateway.engine.clone(), - }, + engine: document.spec.gateway.image_engine().to_owned(), managed_gateway: document.spec.gateway.as_managed().is_some(), }) } @@ -72,13 +70,19 @@ pub fn assess_target( } let mut reasons = Vec::new(); let mut conflict = false; - // An external gateway's engine only supplies image metadata. Do not - // infer its execution platform or prerequisites from that image store. - let engine_available = if !key.managed_gateway { + let driver = document.spec.gateway.compute_driver(); + // A cluster has no engine: image metadata bundles replace inspection, and + // operations check the cluster's prerequisites. An external gateway's + // engine only supplies image metadata. Do not infer its execution + // platform or prerequisites from that image store. + let engine_available = if driver.is_kubernetes() { + true + } else if !key.managed_gateway { if key.engine.is_empty() { - reasons.push( - "Set spec.gateway.engine to inspect the external gateway's sandbox image.".into(), - ); + reasons.push(format!( + "Set spec.gateway.target.{}.engine to inspect the external gateway's sandbox image.", + driver.as_str() + )); false } else { true diff --git a/crates/nemoclaw-authoring/tests/deployment_journey.rs b/crates/nemoclaw-authoring/tests/deployment_journey.rs index 0dc97c682ec..f6b05d03cfc 100644 --- a/crates/nemoclaw-authoring/tests/deployment_journey.rs +++ b/crates/nemoclaw-authoring/tests/deployment_journey.rs @@ -62,13 +62,14 @@ fn supplied_deployment_field_is_asked_before_unrelated_required_answers() { fn unknown_supplied_deployment_field_can_be_removed() { let capabilities = Capabilities::available(); let mut supplied = example("onboarding/openclaw.yaml").supplied().clone(); - supplied["spec"]["gateway"]["enginee"] = json!("unix:///var/run/docker.sock"); + supplied["spec"]["gateway"]["target"]["docker"]["enginee"] = + json!("unix:///var/run/docker.sock"); let base = PartialDocument::from_yaml(supplied.to_string().as_bytes()).unwrap(); let mut state = JourneyDefinition::new("unknown-deployment-field", base) .ask([JourneyScope::DeploymentFields]) .start(&capabilities) .unwrap(); - let path = "/spec/gateway/enginee"; + let path = "/spec/gateway/target/docker/enginee"; let question = state .resolve(&capabilities) .unwrap() @@ -110,7 +111,11 @@ fn external_gateway_questions_preserve_deployment_and_reject_invalid_or_stale_an let mut state = journey("fabric-pi.yaml"); let resolution = state.resolve(&capabilities).unwrap(); assert!(resolution.question("/spec/gateway/endpoint").is_some()); - assert!(resolution.question("/spec/gateway/engine").is_none()); + assert!( + resolution + .question("/spec/gateway/target/docker/engine") + .is_none() + ); assert!(resolution.question("/metadata/uid").is_none()); let before = state.values().clone(); assert!( @@ -175,13 +180,13 @@ fn managed_service_questions_use_sdk_types_and_keep_recipe_as_one_value() { fn optional_supplied_deployment_field_can_be_omitted_through_the_shared_question() { let capabilities = Capabilities::available(); let mut supplied = example("onboarding/openclaw.yaml").supplied().clone(); - supplied["spec"]["gateway"]["imagePullPolicy"] = json!("Never"); + supplied["spec"]["gateway"]["target"]["docker"]["imagePullPolicy"] = json!("Never"); let base = PartialDocument::from_yaml(supplied.to_string().as_bytes()).unwrap(); let mut state = JourneyDefinition::new("optional-deployment", base) .ask([JourneyScope::DeploymentFields]) .start(&capabilities) .unwrap(); - let path = "/spec/gateway/imagePullPolicy"; + let path = "/spec/gateway/target/docker/imagePullPolicy"; let resolution = state.resolve(&capabilities).unwrap(); let question = resolution.question(path).expect("deployment question"); assert!(!question.required()); diff --git a/crates/nemoclaw-authoring/tests/discovery_queries.rs b/crates/nemoclaw-authoring/tests/discovery_queries.rs index 90515760d49..7f211e4c296 100644 --- a/crates/nemoclaw-authoring/tests/discovery_queries.rs +++ b/crates/nemoclaw-authoring/tests/discovery_queries.rs @@ -44,7 +44,7 @@ fn an_external_gateway_reads_only_its_image_store_like_plan() { document.spec.gateway = serde_json::from_value(serde_json::json!({ "management": "external", "endpoint": "https://gateway.example:8080", - "engine": "ssh://images@example.com", + "target": {"docker": {"engine": "ssh://images@example.com"}}, })) .unwrap(); let mut expected = plan_queries(&document).unwrap(); @@ -89,10 +89,10 @@ fn hardware_of_service_engines_is_the_first_named_exclusion() { } /// An external gateway with no engine has nowhere to read its image from. Plan -/// still compiles the read, with an empty engine, so that it can fail with -/// "set spec.gateway.engine". Onboarding makes no read, because it never -/// targets a local daemon for an unresolved engine, and reports the missing -/// engine itself. +/// still compiles the read, with an empty engine, so that it can fail with a +/// message that names the target's engine. Onboarding makes no read, because +/// it never targets a local daemon for an unresolved engine, and reports the +/// missing engine itself. #[test] fn an_unresolved_engine_is_the_second_named_exclusion() { let document = document("../../examples/spark/remote-vllm.yaml"); diff --git a/crates/nemoclaw-authoring/tests/environment_observations.rs b/crates/nemoclaw-authoring/tests/environment_observations.rs index 3bc9bd0a1e8..0b331816cd0 100644 --- a/crates/nemoclaw-authoring/tests/environment_observations.rs +++ b/crates/nemoclaw-authoring/tests/environment_observations.rs @@ -24,7 +24,7 @@ struct RecordedHost { observations: DiscoveryObservations, } -const RUNTIME: &str = "/spec/gateway/runtime/provider"; +const TARGET: &str = "/spec/gateway/target"; const PODMAN_ONLY: &str = include_str!("fixtures/observations/podman-only.json"); @@ -65,32 +65,32 @@ fn host(docker: ObservationStatus, podman: ObservationStatus) -> RecordedHost { } } -/// The runtime the journey suggests for a template that names `template`, once +/// The target the journey suggests for a template that names `template`, once /// the environment queries have been answered by `host`. -fn suggested_runtime(host: &RecordedHost, template: &str) -> Option { +fn suggested_target(host: &RecordedHost, template: &str) -> Option { let capabilities = Capabilities::available(); let yaml = String::from_utf8(include_bytes!("../../../examples/onboarding/openclaw.yaml").to_vec()) .unwrap(); - // The example names its runtime exactly once. - let yaml = yaml.replace("provider: docker", &format!("provider: {template}")); + // The example names its target exactly once. + let yaml = yaml.replace("docker: {}", &format!("{template}: {{}}")); let base = PartialDocument::from_yaml(yaml.as_bytes()).unwrap(); let mut state = JourneyDefinition::new("runtime", base) - .ask([RUNTIME]) + .ask([TARGET]) .start(&capabilities) .unwrap(); state.use_local_engines(&host.candidates, &host.observations); state .resolve_with_observations(&capabilities, &host.observations) .unwrap() - .question(RUNTIME) + .question(TARGET) .unwrap() .suggestion() .cloned() } #[test] -fn the_suggested_runtime_is_the_only_engine_that_answered_else_the_templates() { +fn the_suggested_target_is_the_only_engine_that_answered_else_the_templates() { use ObservationStatus::{Available, Unavailable}; // (host, docker's answer, podman's answer, template, expected suggestion) let rows = [ @@ -105,7 +105,7 @@ fn the_suggested_runtime_is_the_only_engine_that_answered_else_the_templates() { ]; for (name, docker, podman, template, expected) in rows { assert_eq!( - suggested_runtime(&host(docker, podman), template), + suggested_target(&host(docker, podman), template), Some(json!(expected)), "{name} with a {template} template" ); @@ -115,21 +115,18 @@ fn the_suggested_runtime_is_the_only_engine_that_answered_else_the_templates() { #[test] fn a_recorded_host_with_only_podman_overrides_a_docker_template() { let recorded = serde_json::from_str::(PODMAN_ONLY).unwrap(); - assert_eq!( - suggested_runtime(&recorded, "docker"), - Some(json!("podman")) - ); + assert_eq!(suggested_target(&recorded, "docker"), Some(json!("podman"))); } #[test] -fn a_host_that_named_no_engines_keeps_the_templates_runtime() { +fn a_host_that_named_no_engines_keeps_the_templates_target() { let nothing = RecordedHost { candidates: Vec::new(), observations: DiscoveryObservations::new(), }; for template in ["docker", "podman"] { assert_eq!( - suggested_runtime(¬hing, template), + suggested_target(¬hing, template), Some(json!(template)), "{template} template" ); diff --git a/crates/nemoclaw-authoring/tests/journey_guidance.rs b/crates/nemoclaw-authoring/tests/journey_guidance.rs index c6eab9bf02f..2d1facd78b5 100644 --- a/crates/nemoclaw-authoring/tests/journey_guidance.rs +++ b/crates/nemoclaw-authoring/tests/journey_guidance.rs @@ -133,7 +133,9 @@ fn every_advertised_harness_keeps_provider_protocol_choices() { fn changing_a_model_preserves_an_explicit_target_engine() { let capabilities = Capabilities::available(); let mut values = supplied(); - values["spec"]["gateway"]["engine"] = json!("unix:///tmp/owned-discovery-fixture.sock"); + let engine = "/spec/gateway/target/docker/engine"; + values["spec"]["gateway"]["target"]["docker"]["engine"] = + json!("unix:///tmp/owned-discovery-fixture.sock"); let mut state = journey(values, &capabilities); state .answer( @@ -147,7 +149,7 @@ fn changing_a_model_preserves_an_explicit_target_engine() { .answer(&capabilities, model, Some(json!("updated-model"))) .unwrap(); assert_eq!( - state.values().pointer("/spec/gateway/engine"), + state.values().pointer(engine), Some(&json!("unix:///tmp/owned-discovery-fixture.sock")) ); } @@ -299,7 +301,11 @@ fn missing_adapter_schema_keeps_independent_deployment_questions_available() { .unwrap(); let resolution = state.resolve(&capabilities).unwrap(); - assert!(resolution.question("/spec/gateway/image").is_some()); + assert!( + resolution + .question("/spec/gateway/target/docker/engine") + .is_some() + ); assert!( resolution .unverified() diff --git a/crates/nemoclaw-authoring/tests/journey_resolution.rs b/crates/nemoclaw-authoring/tests/journey_resolution.rs index 326408cd16e..ab28790576f 100644 --- a/crates/nemoclaw-authoring/tests/journey_resolution.rs +++ b/crates/nemoclaw-authoring/tests/journey_resolution.rs @@ -9,6 +9,8 @@ use nemoclaw_sdk::discovery::DiscoveryObservations; use nemoclaw_sdk::fabric_catalog::FabricCatalog; use serde_json::json; +const TARGET: &str = "/spec/gateway/target"; + fn minimum() -> PartialDocument { PartialDocument::from_yaml( b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nspec:\n sandboxes:\n - {}\n", @@ -508,12 +510,12 @@ fn invalid_optional_sdk_leaf_can_be_omitted_without_guidance() { let mut values: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - values["spec"]["gateway"]["runtime"]["provider"] = json!("unsupported"); + values["spec"]["gateway"]["target"]["docker"]["engine"] = json!("unsupported"); let base = PartialDocument::from_yaml(values.to_string().as_bytes()).unwrap(); let mut state = JourneyDefinition::new("repair-optional", base) .start(&capabilities) .unwrap(); - let path = "/spec/gateway/runtime/provider"; + let path = "/spec/gateway/target/docker/engine"; let question = state .resolve(&capabilities) .unwrap() @@ -1348,23 +1350,115 @@ fn discovered_models_extend_the_current_route_question_without_restricting_custo } #[test] -fn runtime_question_uses_finite_sdk_schema_choices() { +fn target_question_offers_the_sdk_target_keys() { let capabilities = Capabilities::available(); let base = PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); let state = JourneyDefinition::new("runtime", base) - .ask(["/spec/gateway/runtime/provider"]) + .ask([TARGET]) .start(&capabilities) .unwrap(); let question = state .resolve(&capabilities) .unwrap() - .question("/spec/gateway/runtime/provider") + .question(TARGET) .unwrap() .clone(); - assert!(question.choices().contains(&json!("docker"))); - assert!(question.choices().contains(&json!("podman"))); + assert_eq!( + question.choices(), + &[json!("docker"), json!("podman"), json!("kubernetes")] + ); + // The template names Docker, which is the current answer. + assert_eq!(question.suggestion(), Some(&json!("docker"))); + assert_eq!(question.reason(), JourneyQuestionReason::ExplicitAsk); +} + +#[test] +fn a_target_without_one_known_key_is_a_repair_question() { + let capabilities = Capabilities::available(); + for target in [ + json!({}), + json!({"dockr": {}}), + json!({"docker": {}, "podman": {}}), + ] { + let mut values: serde_json::Value = + serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) + .unwrap(); + values["spec"]["gateway"]["target"] = target.clone(); + let base = PartialDocument::from_yaml(values.to_string().as_bytes()).unwrap(); + let mut state = JourneyDefinition::new("repair-target", base) + .start(&capabilities) + .unwrap(); + let question = state + .resolve(&capabilities) + .unwrap() + .question(TARGET) + .cloned() + .unwrap_or_else(|| panic!("{target}: no target question")); + assert_eq!( + question.reason(), + JourneyQuestionReason::InvalidSupplied, + "{target}" + ); + assert_eq!(question.suggestion(), None, "{target}"); + state + .answer(&capabilities, TARGET, Some(json!("docker"))) + .unwrap(); + assert_eq!(state.values().pointer(TARGET), Some(&json!({"docker": {}}))); + assert!( + state + .resolve(&capabilities) + .unwrap() + .assessment() + .document() + .is_some(), + "{target}" + ); + // The answered repair question can be revisited. + state + .answer(&capabilities, TARGET, Some(json!("podman"))) + .unwrap(); + assert_eq!(state.values().pointer(TARGET), Some(&json!({"podman": {}}))); + } +} + +#[test] +fn switching_the_target_keeps_settings_the_new_target_defines() { + let capabilities = Capabilities::available(); + let mut values: serde_json::Value = + serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) + .unwrap(); + values["spec"]["gateway"]["target"] = json!({"docker": { + "endpoint": "http://127.0.0.1:17682", + "engine": "unix:///srv/engine.sock", + "networkCidr": "10.200.0.0/24" + }}); + let base = PartialDocument::from_yaml(values.to_string().as_bytes()).unwrap(); + let mut state = JourneyDefinition::new("switch-target", base) + .ask([TARGET]) + .start(&capabilities) + .unwrap(); + state + .answer(&capabilities, TARGET, Some(json!("podman"))) + .unwrap(); + // Podman defines every Docker setting, and an authored engine stays authored. + assert_eq!( + state.values().pointer(TARGET), + Some(&json!({"podman": { + "endpoint": "http://127.0.0.1:17682", + "engine": "unix:///srv/engine.sock", + "networkCidr": "10.200.0.0/24" + }})) + ); + state + .answer(&capabilities, TARGET, Some(json!("kubernetes"))) + .unwrap(); + // A cluster rejects a local HTTP endpoint and defines no engine or network. + assert_eq!( + state.values().pointer(TARGET), + Some(&json!({"kubernetes": {}})) + ); } #[test] @@ -1374,7 +1468,7 @@ fn choosing_podman_updates_the_matching_managed_gateway_default() { PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); let mut state = JourneyDefinition::new("runtime", base) - .ask(["/spec/gateway/runtime/provider"]) + .ask([TARGET]) .start(&capabilities) .unwrap(); let podman = "unix:///run/user/501/podman/podman.sock"; @@ -1383,15 +1477,11 @@ fn choosing_podman_updates_the_matching_managed_gateway_default() { &[(podman, nemoclaw_sdk::config::ComputeDriver::Podman)], ); state - .answer( - &capabilities, - "/spec/gateway/runtime/provider", - Some(json!("podman")), - ) + .answer(&capabilities, TARGET, Some(json!("podman"))) .unwrap(); assert_eq!( - state.values().pointer("/spec/gateway/engine"), - Some(&json!(podman)) + state.values().pointer(TARGET), + Some(&json!({"podman": {"engine": podman}})) ); assert!( state @@ -1404,37 +1494,39 @@ fn choosing_podman_updates_the_matching_managed_gateway_default() { } #[test] -fn a_runtime_no_local_engine_answered_for_gets_no_guessed_engine() { +fn a_target_no_local_engine_answered_for_gets_no_guessed_engine() { use nemoclaw_sdk::config::ComputeDriver; let capabilities = Capabilities::available(); let base = PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); let mut state = JourneyDefinition::new("runtime", base) - .ask(["/spec/gateway/runtime/provider"]) + .ask([TARGET]) .start(&capabilities) .unwrap(); let docker = "unix:///home/me/.colima/docker.sock"; crate::support::found_local_engines(&mut state, &[(docker, ComputeDriver::Docker)]); - let runtime = "/spec/gateway/runtime/provider"; state - .answer(&capabilities, runtime, Some(json!("docker"))) + .answer(&capabilities, TARGET, Some(json!("docker"))) .unwrap(); assert_eq!( - state.values().pointer("/spec/gateway/engine"), + state.values().pointer("/spec/gateway/target/docker/engine"), Some(&json!(docker)) ); // Only Docker answered: Podman gets no engine, not Docker's. state - .answer(&capabilities, runtime, Some(json!("podman"))) + .answer(&capabilities, TARGET, Some(json!("podman"))) .unwrap(); - assert_eq!(state.values().pointer("/spec/gateway/engine"), None); + assert_eq!(state.values().pointer(TARGET), Some(&json!({"podman": {}}))); } -/// A journey whose machine was asked about its engines and answered only for Docker. -fn docker_only_journey( +/// A journey whose machine was asked about its engines and answered only with +/// `engine` for `driver`. +fn journey_answered_only_by( capabilities: &Capabilities, ask: &[&str], + engine: &str, + driver: nemoclaw_sdk::config::ComputeDriver, ) -> (nemoclaw_authoring::JourneyState, DiscoveryObservations) { let base = PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) @@ -1443,16 +1535,23 @@ fn docker_only_journey( .ask(ask.iter().copied()) .start(capabilities) .unwrap(); - let observations = crate::support::found_local_engines( - &mut state, - &[( - "unix:///home/me/.colima/docker.sock", - nemoclaw_sdk::config::ComputeDriver::Docker, - )], - ); + let observations = crate::support::found_local_engines(&mut state, &[(engine, driver)]); (state, observations) } +/// A journey whose machine was asked about its engines and answered only for Docker. +fn docker_only_journey( + capabilities: &Capabilities, + ask: &[&str], +) -> (nemoclaw_authoring::JourneyState, DiscoveryObservations) { + journey_answered_only_by( + capabilities, + ask, + "unix:///home/me/.colima/docker.sock", + nemoclaw_sdk::config::ComputeDriver::Docker, + ) +} + fn first_target_reason( state: &nemoclaw_authoring::JourneyState, capabilities: &Capabilities, @@ -1466,26 +1565,46 @@ fn first_target_reason( } #[test] -fn a_runtime_no_local_engine_answered_for_is_reported_first() { +fn a_target_no_local_engine_answered_for_is_reported_first() { let capabilities = Capabilities::available(); - let (mut state, observations) = - docker_only_journey(&capabilities, &["/spec/gateway/runtime/provider"]); + let (mut state, observations) = docker_only_journey(&capabilities, &[TARGET]); state - .answer( - &capabilities, - "/spec/gateway/runtime/provider", - Some(json!("podman")), + .answer(&capabilities, TARGET, Some(json!("podman"))) + .unwrap(); + assert_eq!( + first_target_reason(&state, &capabilities, &observations).as_deref(), + Some( + "No podman engine answered on this machine. Start it, or set spec.gateway.target.podman.engine to its socket." ) + ); +} + +#[test] +fn a_podman_target_without_a_local_engine_has_no_engine_to_accept() { + let capabilities = Capabilities::available(); + let engine = "/spec/gateway/target/podman/engine"; + let (mut state, observations) = docker_only_journey(&capabilities, &[TARGET, engine]); + state + .answer(&capabilities, TARGET, Some(json!("podman"))) + .unwrap(); + let resolution = state + .resolve_with_observations(&capabilities, &observations) .unwrap(); + // Podman's engine has no default, so there is nothing to accept in its + // place, and it cannot be omitted. + let question = resolution.question(engine).unwrap(); + assert_eq!(question.suggestion(), None); + assert!(question.required()); + assert!(state.answer(&capabilities, engine, None).is_err()); + assert_eq!(state.values().pointer(engine), None); assert_eq!( first_target_reason(&state, &capabilities, &observations).as_deref(), Some( - "No podman engine answered on this machine. Start it, or set spec.gateway.engine to its socket." + "No podman engine answered on this machine. Start it, or set spec.gateway.target.podman.engine to its socket." ) ); } -/// Answer `id` with whatever the journey suggests, as pressing Enter does. fn accept_suggestion( state: &mut nemoclaw_authoring::JourneyState, capabilities: &Capabilities, @@ -1503,43 +1622,120 @@ fn accept_suggestion( } #[test] -fn accepting_suggestions_never_points_a_runtime_without_a_local_engine_at_dockers_socket() { +fn accepting_suggestions_never_points_a_docker_target_without_a_local_engine_at_its_default_socket() +{ let capabilities = Capabilities::available(); - let engine = "/spec/gateway/engine"; - let (mut state, observations) = - docker_only_journey(&capabilities, &["/spec/gateway/runtime/provider", engine]); + let engine = "/spec/gateway/target/docker/engine"; + let (mut state, observations) = journey_answered_only_by( + &capabilities, + &[TARGET, engine], + "unix:///run/user/501/podman/podman.sock", + nemoclaw_sdk::config::ComputeDriver::Podman, + ); state - .answer( - &capabilities, - "/spec/gateway/runtime/provider", - Some(json!("podman")), - ) + .answer(&capabilities, TARGET, Some(json!("docker"))) .unwrap(); + // Docker's engine default is its standard socket, where nothing answered. + assert_eq!( + state + .resolve_with_observations(&capabilities, &observations) + .unwrap() + .question(engine) + .unwrap() + .suggestion(), + None + ); accept_suggestion(&mut state, &capabilities, &observations, engine); assert_eq!(state.values().pointer(engine), None); assert_eq!( first_target_reason(&state, &capabilities, &observations).as_deref(), Some( - "No podman engine answered on this machine. Start it, or set spec.gateway.engine to its socket." + "No docker engine answered on this machine. Start it, or set spec.gateway.target.docker.engine to its socket." ) ); } +#[test] +fn an_engine_the_user_answered_stays_when_the_target_changes() { + let capabilities = Capabilities::available(); + let engine = "/spec/gateway/target/docker/engine"; + let (mut state, _) = docker_only_journey(&capabilities, &[TARGET, engine]); + state + .answer(&capabilities, TARGET, Some(json!("docker"))) + .unwrap(); + assert_eq!( + state.values().pointer(engine), + Some(&json!("unix:///home/me/.colima/docker.sock")) + ); + // The answer replaces the engine the machine supplied, so it is authored. + let authored = "unix:///srv/engine.sock"; + state + .answer(&capabilities, engine, Some(json!(authored))) + .unwrap(); + state + .answer(&capabilities, TARGET, Some(json!("podman"))) + .unwrap(); + assert_eq!( + state.values().pointer(TARGET), + Some(&json!({"podman": {"engine": authored}})) + ); +} + +#[test] +fn reselecting_a_target_whose_settings_are_not_an_object_starts_them_empty() { + let capabilities = Capabilities::available(); + let mut values: serde_json::Value = + serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) + .unwrap(); + values["spec"]["gateway"]["target"] = json!({"docker": null}); + let base = PartialDocument::from_yaml(values.to_string().as_bytes()).unwrap(); + let mut state = JourneyDefinition::new("reselect-target", base) + .ask([TARGET]) + .start(&capabilities) + .unwrap(); + state + .answer(&capabilities, TARGET, Some(json!("docker"))) + .unwrap(); + assert_eq!(state.values().pointer(TARGET), Some(&json!({"docker": {}}))); +} + +#[test] +fn an_omitted_target_suggests_the_key_that_omission_selects() { + let capabilities = Capabilities::available(); + let mut values: serde_json::Value = + serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) + .unwrap(); + values["spec"]["gateway"] + .as_object_mut() + .unwrap() + .remove("target"); + let base = PartialDocument::from_yaml(values.to_string().as_bytes()).unwrap(); + let state = JourneyDefinition::new("omitted-target", base) + .ask([TARGET]) + .start(&capabilities) + .unwrap(); + let resolution = state.resolve(&capabilities).unwrap(); + let question = resolution.question(TARGET).unwrap(); + assert_eq!(question.reason(), JourneyQuestionReason::Missing); + assert_eq!(question.suggestion(), Some(&json!("docker"))); +} + #[test] fn a_machine_that_was_never_asked_keeps_the_default_engine_suggestion() { let capabilities = Capabilities::available(); let base = PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); + let engine = "/spec/gateway/target/docker/engine"; let state = JourneyDefinition::new("runtime", base) - .ask(["/spec/gateway/engine"]) + .ask([engine]) .start(&capabilities) .unwrap(); assert_eq!( state .resolve_with_observations(&capabilities, &DiscoveryObservations::new()) .unwrap() - .question("/spec/gateway/engine") + .question(engine) .unwrap() .suggestion(), Some(&json!("unix:///var/run/docker.sock")) @@ -1549,21 +1745,15 @@ fn a_machine_that_was_never_asked_keeps_the_default_engine_suggestion() { #[test] fn an_explicit_gateway_engine_is_not_reported_as_missing() { let capabilities = Capabilities::available(); - let (mut state, observations) = docker_only_journey( - &capabilities, - &["/spec/gateway/runtime/provider", "/spec/gateway/engine"], - ); + let engine = "/spec/gateway/target/podman/engine"; + let (mut state, observations) = docker_only_journey(&capabilities, &[TARGET, engine]); state - .answer( - &capabilities, - "/spec/gateway/runtime/provider", - Some(json!("podman")), - ) + .answer(&capabilities, TARGET, Some(json!("podman"))) .unwrap(); state .answer( &capabilities, - "/spec/gateway/engine", + engine, Some(json!("unix:///srv/podman.sock")), ) .unwrap(); @@ -2549,7 +2739,7 @@ fn existing_onboarding_fields_resolve_and_materialize_without_a_draft() { let fields = [ "/metadata/name", "/spec/sandboxes/0/harness/kind", - "/spec/gateway/runtime/provider", + TARGET, "/spec/inferenceProviders/0/provider", "/spec/inferenceProviders/0/api", "/spec/sandboxes/0/agent/inference/routes/0/overrides/model", @@ -3552,13 +3742,13 @@ fn switching_gateway_management_drops_fields_from_the_previous_branch() { let mut values: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - // `networkCIDR` is defined only for managed gateways; `engine` is defined - // for both forms. - values["spec"]["gateway"]["networkCIDR"] = json!("10.200.0.0/24"); + // A target's `networkCidr` is defined only for managed gateways; its + // `engine` is defined for both forms. + values["spec"]["gateway"]["target"]["docker"]["networkCidr"] = json!("10.200.0.0/24"); let base = PartialDocument::from_yaml(values.to_string().as_bytes()).unwrap(); let capabilities = Capabilities::available(); let mut journey = JourneyDefinition::new("switch-gateway", base) - .ask(["/spec/gateway/runtime/provider", "/spec/gateway/management"]) + .ask([TARGET, "/spec/gateway/management"]) .omit([ "adapter:nvidia.fabric.openclaw:/agent_name", "adapter:nvidia.fabric.openclaw:/cli", @@ -3576,17 +3766,11 @@ fn switching_gateway_management_drops_fields_from_the_previous_branch() { nemoclaw_sdk::config::ComputeDriver::Podman, )], ); + let engine = "/spec/gateway/target/podman/engine"; journey - .answer( - &capabilities, - "/spec/gateway/runtime/provider", - Some(json!("podman")), - ) + .answer(&capabilities, TARGET, Some(json!("podman"))) .unwrap(); - assert_eq!( - journey.values().pointer("/spec/gateway/engine"), - Some(&podman) - ); + assert_eq!(journey.values().pointer(engine), Some(&podman)); journey .answer( &capabilities, @@ -3594,11 +3778,13 @@ fn switching_gateway_management_drops_fields_from_the_previous_branch() { Some(json!("external")), ) .unwrap(); - assert_eq!(journey.values().pointer("/spec/gateway/networkCIDR"), None); assert_eq!( - journey.values().pointer("/spec/gateway/engine"), - Some(&podman) + journey + .values() + .pointer("/spec/gateway/target/podman/networkCidr"), + None ); + assert_eq!(journey.values().pointer(engine), Some(&podman)); journey .answer( &capabilities, @@ -3620,10 +3806,7 @@ fn switching_gateway_management_drops_fields_from_the_previous_branch() { Some(json!("managed")), ) .unwrap(); - assert_eq!( - journey.values().pointer("/spec/gateway/engine"), - Some(&podman) - ); + assert_eq!(journey.values().pointer(engine), Some(&podman)); assert!(journey.resolve(&capabilities).is_ok()); } diff --git a/crates/nemoclaw-authoring/tests/onboarding_journey_presets.rs b/crates/nemoclaw-authoring/tests/onboarding_journey_presets.rs index c1b9ecd793e..02074fa2902 100644 --- a/crates/nemoclaw-authoring/tests/onboarding_journey_presets.rs +++ b/crates/nemoclaw-authoring/tests/onboarding_journey_presets.rs @@ -168,13 +168,13 @@ fn custom_endpoint_questions_stay_user_facing_without_internal_provider_names() } #[test] -fn switching_runtime_preserves_the_selected_model() { +fn switching_the_target_preserves_the_selected_model() { let capabilities = Capabilities::available(); let base = PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); let mut state = JourneyDefinition::new("runtime", base) - .ask(["/spec/gateway/runtime/provider"]) + .ask(["/spec/gateway/target"]) .start(&capabilities) .unwrap(); let model = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; @@ -185,15 +185,11 @@ fn switching_runtime_preserves_the_selected_model() { &[(podman, nemoclaw_sdk::config::ComputeDriver::Podman)], ); state - .answer( - &capabilities, - "/spec/gateway/runtime/provider", - Some(json!("podman")), - ) + .answer(&capabilities, "/spec/gateway/target", Some(json!("podman"))) .unwrap(); assert_eq!(state.values().pointer(model), Some(&before)); assert_eq!( - state.values().pointer("/spec/gateway/engine"), + state.values().pointer("/spec/gateway/target/podman/engine"), Some(&json!(podman)) ); } diff --git a/crates/nemoclaw-authoring/tests/support.rs b/crates/nemoclaw-authoring/tests/support.rs index 024731ca5cc..98327809292 100644 --- a/crates/nemoclaw-authoring/tests/support.rs +++ b/crates/nemoclaw-authoring/tests/support.rs @@ -3,7 +3,7 @@ //! Helpers shared by the authoring tests. use nemoclaw_sdk::discovery::DiscoveryObservations; use nemoclaw_sdk::{ - config::{ComputeDriver, Document, Gateway}, + config::{ComputeDriver, Document}, discovery::{ DiscoveryObservation, DiscoveryQuery, DiscoveryRequest, EngineObservation, FabricObservation, ObservationStatus, plan_queries, @@ -23,16 +23,13 @@ pub struct Target { pub fn target(document: &Document) -> Target { let sandbox = &document.spec.sandboxes[0]; Target { - engine: match &document.spec.gateway { - Gateway::Managed(gateway) => gateway.engine.clone(), - Gateway::External(gateway) => gateway.engine.clone(), - }, - compute_driver: document.spec.gateway.runtime().provider, + engine: document.spec.gateway.image_engine().to_owned(), + compute_driver: document.spec.gateway.compute_driver(), image: sandbox.image.ref_.clone(), } } -/// The machine answered for `engines`, so choosing their runtime targets them. +/// The machine answered for `engines`, so choosing their target uses them. /// Returns what the machine said. pub fn found_local_engines( state: &mut nemoclaw_authoring::JourneyState, diff --git a/crates/nemoclaw-authoring/tests/target_assessment.rs b/crates/nemoclaw-authoring/tests/target_assessment.rs index 18e45ebcede..bcde4a22002 100644 --- a/crates/nemoclaw-authoring/tests/target_assessment.rs +++ b/crates/nemoclaw-authoring/tests/target_assessment.rs @@ -7,7 +7,7 @@ use nemoclaw_authoring::{ }; use nemoclaw_sdk::discovery::DiscoveryObservations; use nemoclaw_sdk::{ - config::{ComputeDriver, Document, Gateway}, + config::{Document, ManagedGateway, ManagedPodman, ManagedTarget}, discovery::{ DiscoveryObservation, DiscoveryQuery, DiscoveryRequest, EngineObservation, FabricObservation, ObservationStatus, @@ -243,10 +243,13 @@ fn editing_the_target_leaves_only_the_edited_observation_unfound() { before: document(), engine_observed: true, change: |document| { - let Gateway::Managed(gateway) = &mut document.spec.gateway else { - panic!("the example uses a managed gateway") + let Some(ManagedGateway { + target: ManagedTarget::Docker(docker), + }) = document.spec.gateway.as_managed_mut() + else { + panic!("the example uses a managed Docker gateway") }; - gateway.engine = "unix:///another-target.sock".into(); + docker.engine = "unix:///another-target.sock".into(); }, engine_unobserved: true, // The image is read from the gateway's engine. @@ -268,7 +271,19 @@ fn editing_the_target_leaves_only_the_edited_observation_unfound() { before: document(), engine_observed: true, change: |document| { - document.spec.gateway.runtime_mut().provider = ComputeDriver::Podman; + let Some(ManagedGateway { target }) = document.spec.gateway.as_managed_mut() else { + panic!("the example uses a managed gateway") + }; + let ManagedTarget::Docker(docker) = target.clone() else { + panic!("the example uses a Docker target") + }; + // Only the target's driver changes; its engine and settings stay. + *target = ManagedTarget::Podman(ManagedPodman { + endpoint: docker.endpoint, + engine: docker.engine, + image_pull_policy: docker.image_pull_policy, + network_cidr: docker.network_cidr, + }); }, engine_unobserved: true, // The image is read through the same driver. @@ -365,14 +380,13 @@ fn renaming_the_target_keeps_it_compatible() { fn external_document(engine: &str) -> Document { let mut document = document(); + // The image store need not run the gateway's selected compute driver. document.spec.gateway = serde_json::from_value(serde_json::json!({ "management": "external", "endpoint": "https://gateway.example:8080", - "engine": engine, + "target": {"podman": {"engine": engine}}, })) .unwrap(); - // The image store need not run the gateway's selected compute driver. - document.spec.gateway.runtime_mut().provider = ComputeDriver::Podman; document } @@ -404,5 +418,59 @@ fn external_gateway_without_an_image_engine_stays_unverified_and_names_the_missi let document = external_document(""); let assessment = assess_target(&document, &DiscoveryObservations::new()).unwrap(); assert_eq!(assessment.status, CompatibilityStatus::Unverified); - assert_says(&assessment, "spec.gateway.engine"); + assert!( + assessment.reasons.contains( + &"Set spec.gateway.target.podman.engine to inspect the external gateway's sandbox image." + .to_owned() + ), + "{:?}", + assessment.reasons + ); +} + +/// `document` on a Kubernetes target, managed or external, whose sandbox +/// image names its metadata bundle. +fn cluster_document(management: &str) -> Document { + let mut value = serde_json::to_value(document()).unwrap(); + value["spec"]["gateway"] = if management == "managed" { + serde_json::json!({"management": "managed", "target": {"kubernetes": { + "endpoint": "https://127.0.0.1:17671", + "kubeconfig": {"env": "CLUSTER_KUBECONFIG"}, + "context": "explicit-context", + "namespace": "agents", + "authentication": {"profile": "development"} + }}}) + } else { + serde_json::json!({ + "management": "external", + "endpoint": "https://gateway.example:8080", + "target": {"kubernetes": {}} + }) + }; + value["spec"]["sandboxes"][0]["image"]["metadata"] = + serde_json::json!({"env": "IMAGE_METADATA"}); + Document::parse(value.to_string().as_bytes()).unwrap() +} + +#[test] +fn a_kubernetes_target_with_supported_image_metadata_is_compatible_without_an_engine() { + for management in ["external", "managed"] { + let document = cluster_document(management); + let observed = Observed { + engine: None, + fabric: Some(crate::support::installed_image(&document)), + }; + let assessment = observed.assess(&document); + assert_eq!( + assessment.status, + CompatibilityStatus::Compatible, + "{management}: {:?}", + assessment.reasons + ); + assert!( + assessment.reasons.is_empty(), + "{management}: {:?}", + assessment.reasons + ); + } } diff --git a/crates/nemoclaw-build/src/ci/live.rs b/crates/nemoclaw-build/src/ci/live.rs index b1067740617..cb6ae980707 100644 --- a/crates/nemoclaw-build/src/ci/live.rs +++ b/crates/nemoclaw-build/src/ci/live.rs @@ -78,11 +78,11 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - engine: unix:///var/run/docker.sock - endpoint: http://127.0.0.1:{port} - networkCIDR: {subnet} + target: + docker: + engine: unix:///var/run/docker.sock + endpoint: http://127.0.0.1:{port} + networkCidr: {subnet} inferenceProviders: - name: hosted provider: openai diff --git a/crates/nemoclaw-build/src/schema/reference.rs b/crates/nemoclaw-build/src/schema/reference.rs index cdf8e69dd16..4395d22e114 100644 --- a/crates/nemoclaw-build/src/schema/reference.rs +++ b/crates/nemoclaw-build/src/schema/reference.rs @@ -82,7 +82,11 @@ fn section( for path in paths { writeln!(output, "- `{path}`").unwrap(); } - if schema.get("properties").is_none() { + // A closed object without fields declares empty properties. + if schema["properties"] + .as_object() + .is_none_or(serde_json::Map::is_empty) + { writeln!(output, "\nAccepted input: {}.\n", input_type(schema)).unwrap(); let choices = constraints(schema); if !choices.is_empty() { @@ -248,6 +252,10 @@ fn guide(name: &str) -> &'static str { "Integration" | "WebSearch" | "SearchProvider" | "Agent" | "AgentExecution" | "AgentObservability" | "OtlpTracing" | "RelayTracing" | "AgentTools" | "AllowedTool" | "ToolDisclosure" => "[Agent runtimes](../agents.md)", + "ManagedTarget" | "ManagedDocker" | "ManagedPodman" | "ManagedKubernetes" + | "ExternalTarget" | "ExternalEngine" | "ExternalKubernetes" => { + "[Gateway target](../usage.md#choose-the-gateway-target)" + } "ImagePullPolicy" => { "[Container image downloads](../usage.md#control-container-image-downloads)" } @@ -447,6 +455,19 @@ mod tests { assert!(constraints(&json!({"oneOf":[{"type":"object"},{"type":"array"}]})).is_empty()); } + #[test] + fn an_object_without_fields_renders_its_input_type_instead_of_an_empty_table() { + let input = schema( + json!({"settings":{"description":"No settings.", "$ref":"#/$defs/Empty"}}), + json!({"Empty":{"description":"Takes no fields.", "type":"object", + "properties":{}, "additionalProperties":false}}), + ); + let markdown = render_reference(&input).unwrap(); + let section = &markdown[markdown.find("## Empty").unwrap()..]; + assert!(section.contains("Accepted input: object."), "{section}"); + assert!(!section.contains("| Field |"), "{section}"); + } + #[test] fn reference_reflects_field_metadata_and_rejects_missing_descriptions() { let mut input = schema( diff --git a/crates/nemoclaw-build/tests/ci.rs b/crates/nemoclaw-build/tests/ci.rs index c3a8b861744..570ab7ce388 100644 --- a/crates/nemoclaw-build/tests/ci.rs +++ b/crates/nemoclaw-build/tests/ci.rs @@ -128,11 +128,9 @@ fn gateway_documents_are_fresh_and_avoid_ports_and_subnets_in_use() { ); assert_eq!(value["metadata"]["uid"], first.as_str()); assert_eq!(value["spec"]["gateway"]["management"], "managed"); - assert_eq!( - value["spec"]["gateway"]["endpoint"], - "http://127.0.0.1:17950" - ); - assert_eq!(value["spec"]["gateway"]["networkCIDR"], chosen.as_str()); + let docker = &value["spec"]["gateway"]["target"]["docker"]; + assert_eq!(docker["endpoint"], "http://127.0.0.1:17950"); + assert_eq!(docker["networkCidr"], chosen.as_str()); assert_eq!( value["spec"]["sandboxes"][0]["image"]["ref"], "nc-live@sha256:abc" @@ -162,7 +160,7 @@ fn gateway_documents_parse_as_current_configuration() { }); let parsed = nemoclaw_sdk::config::Document::parse(document.as_bytes()).unwrap(); assert_eq!( - parsed.spec.gateway.runtime().provider, + parsed.spec.gateway.compute_driver(), nemoclaw_sdk::config::ComputeDriver::Docker ); } diff --git a/crates/nemoclaw-cli/src/args.rs b/crates/nemoclaw-cli/src/args.rs index d8fefe99c48..3237fc09473 100644 --- a/crates/nemoclaw-cli/src/args.rs +++ b/crates/nemoclaw-cli/src/args.rs @@ -122,11 +122,13 @@ mod tests { let document = Document::parse(include_bytes!("../../../examples/openclaw-dashboard.yaml").as_slice()) .unwrap(); - let nemoclaw_sdk::config::Gateway::External(gateway) = &document.spec.gateway else { - panic!("the walkthrough uses an operator-owned gateway"); - }; assert!( - !gateway.engine.is_empty(), + document.spec.gateway.as_managed().is_none(), + "the walkthrough uses an operator-owned gateway" + ); + let engine = document.spec.gateway.image_engine(); + assert!( + !engine.is_empty(), "supply the engine holding the sandbox image" ); let queries = plan_queries(&document).unwrap(); @@ -138,7 +140,7 @@ mod tests { }) .collect(); assert_eq!(images.len(), document.spec.sandboxes.len()); - assert!(images.iter().all(|engine| *engine == &gateway.engine)); + assert!(images.iter().all(|image_engine| *image_engine == engine)); } #[test] diff --git a/crates/nemoclaw-e2e/fixtures/hermes-nvidia-hosted/v1.yaml b/crates/nemoclaw-e2e/fixtures/hermes-nvidia-hosted/v1.yaml index 0f5f10f88be..b8cee6a0500 100644 --- a/crates/nemoclaw-e2e/fixtures/hermes-nvidia-hosted/v1.yaml +++ b/crates/nemoclaw-e2e/fixtures/hermes-nvidia-hosted/v1.yaml @@ -11,12 +11,11 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - endpoint: http://127.0.0.1:17692 - engine: unix:///var/run/docker.sock - image: ghcr.io/nvidia/openshell/gateway@sha256:ea14aa4db0980fab4769fb6b5509ac42ae3dc8495e645b1ba1fe1ada49892fa6 - networkCIDR: 172.30.187.0/24 + target: + docker: + endpoint: http://127.0.0.1:17692 + engine: unix:///var/run/docker.sock + networkCidr: 172.30.187.0/24 inferenceProviders: - name: hosted-nvidia-prod provider: openai diff --git a/crates/nemoclaw-e2e/fixtures/openclaw-nvidia-hosted/v1.yaml b/crates/nemoclaw-e2e/fixtures/openclaw-nvidia-hosted/v1.yaml index 33553107d3e..c9c6f061a9d 100644 --- a/crates/nemoclaw-e2e/fixtures/openclaw-nvidia-hosted/v1.yaml +++ b/crates/nemoclaw-e2e/fixtures/openclaw-nvidia-hosted/v1.yaml @@ -12,12 +12,11 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - endpoint: http://127.0.0.1:17691 - engine: unix:///var/run/docker.sock - image: ghcr.io/nvidia/openshell/gateway@sha256:ea14aa4db0980fab4769fb6b5509ac42ae3dc8495e645b1ba1fe1ada49892fa6 - networkCIDR: 172.30.60.0/24 + target: + docker: + endpoint: http://127.0.0.1:17691 + engine: unix:///var/run/docker.sock + networkCidr: 172.30.60.0/24 inferenceProviders: - name: hosted-nvidia-prod provider: openai diff --git a/crates/nemoclaw-e2e/src/image_runtime.rs b/crates/nemoclaw-e2e/src/image_runtime.rs index f4063e5bdcc..a1dc48748dd 100644 --- a/crates/nemoclaw-e2e/src/image_runtime.rs +++ b/crates/nemoclaw-e2e/src/image_runtime.rs @@ -3,7 +3,7 @@ use nemoclaw_sdk::{ compile::{Generations, Target}, - config::Document, + config::{Document, ExternalTarget}, image_runtime::RuntimeBinding, }; @@ -113,6 +113,10 @@ pub async fn engine(document: &mut Document) -> transport::Fixture { let nemoclaw_sdk::config::Gateway::External(gateway) = &mut document.spec.gateway else { panic!("fixture requires an external gateway") }; - gateway.engine = fixture.endpoint.clone(); + let (ExternalTarget::Docker(target) | ExternalTarget::Podman(target)) = &mut gateway.target + else { + panic!("fixture requires a Docker or Podman gateway target") + }; + target.engine = fixture.endpoint.clone(); fixture } diff --git a/crates/nemoclaw-e2e/tests/brev.rs b/crates/nemoclaw-e2e/tests/brev.rs index 049db1a8076..b37b3ebfebd 100644 --- a/crates/nemoclaw-e2e/tests/brev.rs +++ b/crates/nemoclaw-e2e/tests/brev.rs @@ -341,7 +341,7 @@ async fn bare_brev_hosted_openclaw_lifecycle() { let document = Document::parse(fs::File::open(&config).unwrap()).unwrap(); assert!(matches!(document.spec.gateway, Gateway::Managed(_))); assert_eq!( - document.spec.gateway.runtime().provider, + document.spec.gateway.compute_driver(), ComputeDriver::Docker ); assert_eq!( @@ -428,7 +428,7 @@ async fn bare_brev_hosted_openclaw_lifecycle() { ) .unwrap(); client - .verify_gateway(document.spec.gateway.runtime().provider) + .verify_gateway(document.spec.gateway.compute_driver()) .await .unwrap(); let (before, binding) = bindings(&directory); diff --git a/crates/nemoclaw-e2e/tests/deployment.rs b/crates/nemoclaw-e2e/tests/deployment.rs index fb7d2644d5e..2fe0edfb267 100644 --- a/crates/nemoclaw-e2e/tests/deployment.rs +++ b/crates/nemoclaw-e2e/tests/deployment.rs @@ -258,9 +258,9 @@ async fn gateway_change_between_plan_and_apply_preserves_resources_and_allows_te "{error}" ); assert!( - error.to_string().contains( - "gateway compute driver is podman, but spec.gateway.runtime.provider is docker" - ), + error + .to_string() + .contains("gateway compute driver is podman, but spec.gateway.target selects docker"), "{error}" ); assert_eq!(fixture.state.lock().unwrap().effects, effects); diff --git a/crates/nemoclaw-e2e/tests/dummy_agent.rs b/crates/nemoclaw-e2e/tests/dummy_agent.rs index 6affea459c0..35b43c53244 100644 --- a/crates/nemoclaw-e2e/tests/dummy_agent.rs +++ b/crates/nemoclaw-e2e/tests/dummy_agent.rs @@ -115,7 +115,7 @@ async fn the_dummy_agent_completes_a_managed_docker_lifecycle() { let document = Document::parse(fs::File::open(&config).unwrap()).unwrap(); assert!(matches!(document.spec.gateway, Gateway::Managed(_))); assert_eq!( - document.spec.gateway.runtime().provider, + document.spec.gateway.compute_driver(), ComputeDriver::Docker ); let sandbox = &document.spec.sandboxes[0]; @@ -131,10 +131,13 @@ async fn the_dummy_agent_completes_a_managed_docker_lifecycle() { .expect("the document sets harness.settings.reply") .to_owned(); let resource = format!("openshell_sandbox.{}", sandbox.name); - let Gateway::Managed(gateway) = &document.spec.gateway else { - unreachable!() - }; - let engine = gateway.engine.clone(); + let engine = document + .spec + .gateway + .as_local_managed() + .expect("the dummy document uses a local managed gateway") + .engine + .to_owned(); let state = KeepOnFailure(Some(tempfile::tempdir().unwrap())); let state_path = state.0.as_ref().unwrap().path().to_owned(); let deployment = Deployment::new(&state_path, &bundle); diff --git a/crates/nemoclaw-e2e/tests/fabric_live.rs b/crates/nemoclaw-e2e/tests/fabric_live.rs index ae405dde8a2..ddec9891a73 100644 --- a/crates/nemoclaw-e2e/tests/fabric_live.rs +++ b/crates/nemoclaw-e2e/tests/fabric_live.rs @@ -275,7 +275,7 @@ async fn dependency_upgrade_survives_apply_process_exit() { ) .unwrap(); client - .verify_gateway(document.spec.gateway.runtime().provider) + .verify_gateway(document.spec.gateway.compute_driver()) .await .unwrap(); let (before, binding) = bindings(&directory); diff --git a/crates/nemoclaw-e2e/tests/helm_recovery.rs b/crates/nemoclaw-e2e/tests/helm_recovery.rs index e55a6cfa79b..fd9702ff110 100644 --- a/crates/nemoclaw-e2e/tests/helm_recovery.rs +++ b/crates/nemoclaw-e2e/tests/helm_recovery.rs @@ -207,11 +207,12 @@ fn document() -> Document { .unwrap(); let mut value = serde_json::to_value(original).unwrap(); value["spec"]["gateway"] = json!({ - "management":"managed", "runtime":{"provider":"kubernetes"}, "endpoint":"https://127.0.0.1:17671", - "kubernetes": { + "management":"managed", + "target": {"kubernetes": { + "endpoint":"https://127.0.0.1:17671", "kubeconfig":{"env":"TEST_KUBECONFIG"}, "context":"test-cluster", "namespace":"test-agents", "authentication":{"profile":"development"} - } + }} }); value["spec"]["sandboxes"][0]["image"]["metadata"] = json!({"env":"TEST_IMAGE_METADATA"}); Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap() diff --git a/crates/nemoclaw-e2e/tests/hosted_parity.rs b/crates/nemoclaw-e2e/tests/hosted_parity.rs index 4f4e6d7cd96..df4f6dcfc86 100644 --- a/crates/nemoclaw-e2e/tests/hosted_parity.rs +++ b/crates/nemoclaw-e2e/tests/hosted_parity.rs @@ -3,7 +3,9 @@ //! Historical intent and deployment lifecycle parity; native inference is not qualified here. -use nemoclaw_sdk::config::{ComputeDriver, Document, Gateway, HarnessKind, InferenceProviderKind}; +use nemoclaw_sdk::config::{ + ComputeDriver, DEFAULT_GATEWAY_IMAGE, Document, Gateway, HarnessKind, InferenceProviderKind, +}; use serde_json::json; // This scenario compares separately authored current intent with a test-only @@ -13,6 +15,19 @@ fn authored_document(raw: &[u8], current: &[u8]) -> Document { Document::parse(current).expect("authored v1 input must use current agent syntax"); let mut projected: serde_json::Value = serde_saphyr::from_str(std::str::from_utf8(raw).unwrap()).unwrap(); + // v0 named the compute driver beside the managed endpoint; current intent + // keys the endpoint by the target the gateway runs on. + let gateway = projected["spec"]["gateway"].as_object_mut().unwrap(); + let runtime = gateway + .remove("runtime") + .expect("raw v0 export requires its historical gateway runtime"); + let endpoint = gateway + .remove("endpoint") + .expect("raw v0 export requires its managed gateway endpoint"); + assert_eq!(gateway["management"], "managed"); + assert_eq!(gateway.len(), 1, "unexpected historical gateway field"); + let target = runtime["provider"].as_str().unwrap(); + gateway.insert("target".into(), json!({target: {"endpoint": endpoint}})); let sandboxes = projected["spec"]["sandboxes"].as_array_mut().unwrap(); assert_eq!(sandboxes.len(), 1, "hosted parity requires one sandbox"); let sandbox = sandboxes[0].as_object_mut().unwrap(); @@ -93,9 +108,15 @@ fn live_inputs_preserve_raw_export_and_require_matching_authored_intent() { fn assert_hosted_document(document: &Document, harness: HarnessKind, runtime_root: &str) { let gateway = &document.spec.gateway; assert!(matches!(gateway, Gateway::Managed(_))); - let gateway = gateway.as_managed().unwrap(); + let gateway = gateway.as_local_managed().unwrap(); assert_eq!(gateway.engine, "unix:///var/run/docker.sock"); - assert_eq!(gateway.image, nemoclaw_sdk::config::DEFAULT_GATEWAY_IMAGE); + // The SDK binds its pinned gateway image when compiling; intent never names it. + let generations = ["workspace", "provider", "sandbox", "managed_gateway"] + .map(|kind| (kind.into(), "a".repeat(32))) + .into(); + let runtime = nemoclaw_sdk::compile::compile_runtime(document, &generations, "0.1.0").unwrap(); + assert!(runtime.to_string().contains(DEFAULT_GATEWAY_IMAGE)); + assert!(!document.yaml().unwrap().contains(DEFAULT_GATEWAY_IMAGE)); let provider = &document.spec.inference_providers[0]; assert_eq!(provider.name, "hosted-nvidia-prod"); @@ -111,7 +132,7 @@ fn assert_hosted_document(document: &Document, harness: HarnessKind, runtime_roo assert!(sandbox.image.ref_.contains("@sha256:")); assert_eq!(sandbox.image.ref_.rsplit(':').next().unwrap().len(), 64); assert_eq!( - document.spec.gateway.runtime().provider, + document.spec.gateway.compute_driver(), ComputeDriver::Docker ); let nemoclaw_sdk::config::NetworkPolicy::Explicit(explicit) = &sandbox.network.policy else { diff --git a/crates/nemoclaw-e2e/tests/kubernetes_live.rs b/crates/nemoclaw-e2e/tests/kubernetes_live.rs index 9d7b06ff832..221c43aae2d 100644 --- a/crates/nemoclaw-e2e/tests/kubernetes_live.rs +++ b/crates/nemoclaw-e2e/tests/kubernetes_live.rs @@ -14,7 +14,10 @@ use nemoclaw_sdk::{ ObservationError, bundle::Bundle, compile::{Generations, compile_runtime, compile_teardown, runtime_targets}, - config::{ComputeDriver, Document, ExternalGateway, FileRef, Gateway, SecretRef, TLS}, + config::{ + ComputeDriver, Document, ExternalGateway, ExternalKubernetes, ExternalTarget, FileRef, + Gateway, SecretRef, TLS, + }, kubernetes::{ CA_ENV, CERT_ENV, ClusterTarget, GATEWAY_KIND, KEY_ENV, STATE_ENV, STORAGE_KIND, Spec, TOKEN_ENV, connect, operations::Operations, server, @@ -280,7 +283,7 @@ async fn authenticated_gateway(operations: &Operations, spec: &Spec) { certificate: file(CERT_ENV), key: file(KEY_ENV), }), - ..Default::default() + target: ExternalTarget::Kubernetes(ExternalKubernetes {}), }); let client = OpenShell::connect( &gateway.connection(), @@ -350,13 +353,13 @@ async fn the_gateway_installs_authenticates_and_is_removed_keeping_storage() { let mut value = serde_json::to_value(original).unwrap(); value["metadata"]["uid"] = json!(owner); value["spec"]["gateway"] = json!({ - "management": "managed", "runtime": {"provider": "kubernetes"}, - "endpoint": format!("https://127.0.0.1:{port}"), - "kubernetes": { + "management": "managed", + "target": {"kubernetes": { + "endpoint": format!("https://127.0.0.1:{port}"), "kubeconfig": {"env": "NEMOCLAW_TEST_KUBECONFIG"}, "context": target.context, "namespace": namespace, "authentication": {"profile": "development"} - } + }} }); value["spec"]["sandboxes"][0]["image"]["metadata"] = json!({"env": "TEST_IMAGE_METADATA"}); let document = Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap(); @@ -489,7 +492,7 @@ async fn the_gateway_installs_authenticates_and_is_removed_keeping_storage() { /// - `NEMOCLAW_TEST_AGENT_IMAGE`: the agent image by digest, loaded into kind /// - `NEMOCLAW_TEST_AGENT_HARNESS`: its Fabric adapter /// - `NEMOCLAW_TEST_AGENT_METADATA`: its metadata bundle -async fn deploy_to_the_health_check(provider: &str, while_applying: impl AsyncFnOnce(&str)) { +async fn deploy_to_the_health_check(distribution: &str, while_applying: impl AsyncFnOnce(&str)) { use nemoclaw_sdk::{CancellationToken, Deployment, Error, config::Document}; let mut uid = [0u8; 16]; getrandom::fill(&mut uid).unwrap(); @@ -519,14 +522,14 @@ metadata: spec: gateway: management: managed - runtime: - provider: {provider} - endpoint: https://127.0.0.1:{port} - kubernetes: - kubeconfig: {{env: NEMOCLAW_TEST_KUBECONFIG}} - context: {context} - namespace: {namespace} - authentication: {{profile: development}} + target: + kubernetes: + distribution: {distribution} + endpoint: https://127.0.0.1:{port} + kubeconfig: {{env: NEMOCLAW_TEST_KUBECONFIG}} + context: {context} + namespace: {namespace} + authentication: {{profile: development}} inferenceProviders: - name: hosted provider: openai diff --git a/crates/nemoclaw-e2e/tests/managed_gateway.rs b/crates/nemoclaw-e2e/tests/managed_gateway.rs index 4c18a57586f..4357c8aded4 100644 --- a/crates/nemoclaw-e2e/tests/managed_gateway.rs +++ b/crates/nemoclaw-e2e/tests/managed_gateway.rs @@ -60,7 +60,7 @@ async fn managed_gateway_plan_apply_noop_destroy_and_recovery_use_real_opentofu( let deployment = Deployment::new(&directory, &path("NEMOCLAW_TEST_BUNDLE")); let cancel = CancellationToken::new(); let engine = nemoclaw_provider::docker::Engine::connect( - &document.spec.gateway.as_managed().unwrap().engine, + document.spec.gateway.as_local_managed().unwrap().engine, ) .unwrap(); let name = format!("{}-gateway", document.workspace()); @@ -101,7 +101,7 @@ async fn managed_gateway_plan_apply_noop_destroy_and_recovery_use_real_opentofu( .expect("runtime apply must record provider-owned readiness") .clone(); assert_eq!(readiness["instances"][0]["attributes"]["compatible"], true); - let docker = document.spec.gateway.runtime().provider == ComputeDriver::Docker; + let docker = document.spec.gateway.compute_driver() == ComputeDriver::Docker; let compute = if docker { "docker_container.managed_gateway_runtime" } else { diff --git a/crates/nemoclaw-e2e/tests/model_live.rs b/crates/nemoclaw-e2e/tests/model_live.rs index 95ed9369400..5032bc052df 100644 --- a/crates/nemoclaw-e2e/tests/model_live.rs +++ b/crates/nemoclaw-e2e/tests/model_live.rs @@ -112,7 +112,15 @@ async fn exercise(fresh: bool) { ); // The service runs on its explicit placement, or on the managed gateway's engine. let endpoint = desired.placement.as_ref().map_or_else( - || document.spec.gateway.as_managed().unwrap().engine.clone(), + || { + document + .spec + .gateway + .as_local_managed() + .unwrap() + .engine + .to_owned() + }, |placement| placement.engine.clone(), ); let engine = Engine::connect(&endpoint).unwrap(); diff --git a/crates/nemoclaw-e2e/tests/remote_service.rs b/crates/nemoclaw-e2e/tests/remote_service.rs index ed961ce7fd1..018a483fb63 100644 --- a/crates/nemoclaw-e2e/tests/remote_service.rs +++ b/crates/nemoclaw-e2e/tests/remote_service.rs @@ -115,8 +115,8 @@ impl Scenario { value["spec"]["services"]["qwen"]["imagePullPolicy"] = json!("IfNotPresent"); } value["spec"]["sandboxes"][0]["harness"]["kind"] = harness.into(); - value["spec"]["gateway"] = json!({"management":"external","endpoint":gateway.endpoint}); - value["spec"]["gateway"]["runtime"]["provider"] = json!("podman"); + value["spec"]["gateway"] = + json!({"management":"external","endpoint":gateway.endpoint,"target":{"podman":{}}}); value["spec"]["services"]["qwen"]["placement"] = json!({"engine":"ssh://operator@gpu-box","networkCidr":"172.30.119.0/24"}); value["spec"]["services"]["qwen"]["publication"] = @@ -128,7 +128,7 @@ impl Scenario { let mut image_document = Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap(); let image_engine = nemoclaw_e2e::image_runtime::engine(&mut image_document).await; - value["spec"]["gateway"]["engine"] = json!(image_engine.endpoint); + value["spec"]["gateway"]["target"]["podman"]["engine"] = json!(image_engine.endpoint); save(root, "config.yaml", &value); let mut files = json!({}); let mut stats = json!({}); diff --git a/crates/nemoclaw-e2e/tests/service_images/managed.rs b/crates/nemoclaw-e2e/tests/service_images/managed.rs index 818b71d64c1..f3c15e9b734 100644 --- a/crates/nemoclaw-e2e/tests/service_images/managed.rs +++ b/crates/nemoclaw-e2e/tests/service_images/managed.rs @@ -257,7 +257,7 @@ impl ManagedService { ); assert_ne!( service["placement"]["engine"], - document["spec"]["gateway"]["engine"] + document["spec"]["gateway"]["target"]["docker"]["engine"] ); let remote = self.engine(); let ports = remote["container"]["HostConfig"]["PortBindings"] diff --git a/crates/nemoclaw-e2e/tests/service_images/support.rs b/crates/nemoclaw-e2e/tests/service_images/support.rs index 9a486e78243..957a2c881b4 100644 --- a/crates/nemoclaw-e2e/tests/service_images/support.rs +++ b/crates/nemoclaw-e2e/tests/service_images/support.rs @@ -234,7 +234,7 @@ impl Scenario { )) .unwrap(); value["metadata"]["uid"] = json!(self.uid); - value["spec"]["gateway"] = json!({"management":"external","endpoint":self.gateway.endpoint,"engine":self._metadata.endpoint}); + value["spec"]["gateway"] = json!({"management":"external","endpoint":self.gateway.endpoint,"target":{"docker":{"engine":self._metadata.endpoint}}}); value["spec"]["inferenceProviders"] = json!([{"name":"local","provider":"openai","api":"openai-completions","serviceRef":"shared"}]); value["spec"]["services"] = json!({"shared":{"kind":"ollamaProxy","engine":"unix:///var/run/docker.sock","image":self.proxy_image,"imagePullPolicy":"Never","endpoint":self.endpoint,"upstream":{"endpoint":self.upstream,"model":{"name":"llama3:fixture","digest":"a".repeat(64)}}}}); let mut sandbox = value["spec"]["sandboxes"][0].clone(); diff --git a/crates/nemoclaw-e2e/tests/tls.rs b/crates/nemoclaw-e2e/tests/tls.rs index 0b536da16e5..f2756b24dfd 100644 --- a/crates/nemoclaw-e2e/tests/tls.rs +++ b/crates/nemoclaw-e2e/tests/tls.rs @@ -61,7 +61,6 @@ async fn mutual_tls_and_bearer_references_fail_closed_without_disclosing_credent values.insert("TOKEN".into(), "secret-sentinel".into()); let file = |env: &str| FileRef { env: env.into() }; let gateway = Gateway::External(nemoclaw_sdk::config::ExternalGateway { - engine: String::new(), endpoint: fixture.endpoint.clone(), credential: Some(SecretRef { env: "TOKEN".into(), diff --git a/crates/nemoclaw-onboarding/README.md b/crates/nemoclaw-onboarding/README.md index 85d7e01c376..1abf6892797 100644 --- a/crates/nemoclaw-onboarding/README.md +++ b/crates/nemoclaw-onboarding/README.md @@ -24,7 +24,7 @@ nemoclaw onboard examples/onboarding/openclaw.yaml --output my-deployment.yaml Omit the template to use the built-in defaults. Those defaults come from the example YAML template. -The journey definition asks for deployment name, harness, runtime, inference preset, API, and model, then covers applicable Fabric and deployment settings. +The journey definition asks for deployment name, harness, gateway target, inference preset, API, and model, then covers applicable Fabric and deployment settings. The template's choices are preselected; Enter accepts an answer. The authoring resolver recomputes applicable questions after each answer and follows the definition's order for explicitly asked fields. You can go back to change an answer. @@ -65,9 +65,9 @@ Loading a template preserves its deployment fields, references, and native setti ## Target checks -For a managed gateway, Podman requires a supported local rootless Linux target. The questionnaire records the selected runtime without treating the author's workstation as that target. +For a managed gateway, the `podman` gateway target key requires a supported local rootless Linux host. The questionnaire records the selected gateway target key without treating the author's workstation as that host. When a verified bundle supplies target observations, a confirmed compatibility conflict blocks saving through the authoring resolver. Missing or unknown observations remain unverified; review the target requirements before applying the saved desired state. -An external gateway runs on its own host, and the questionnaire preserves its selected runtime. +An external gateway runs on its own host, and the questionnaire preserves its selected gateway target key. The preset does not configure Podman Machine or a remote Linux host. The CLI reads the target while you answer: @@ -79,10 +79,10 @@ nemoclaw onboard examples/onboarding/openclaw.yaml --output my-deployment.yaml Onboarding reads the selected Fabric image and the inference model catalog through the same functions the provider's plan data sources use; it needs no bundle and starts no OpenTofu process. For a managed gateway, it also checks engine prerequisites and reads hardware advertisements. Hardware observations do not affect questions or readiness yet. -For an external gateway, set `spec.gateway.engine` in the template to the engine containing the selected immutable sandbox image. +For an external Docker or Podman gateway, set `engine` under `spec.gateway.target.docker` or `spec.gateway.target.podman` in the template to the engine containing the selected immutable sandbox image. Onboarding uses that engine only to inspect the image; the image store's compute driver and hardware do not describe the external gateway. Observations for a different engine or image are ignored. -Omitting `spec.gateway.engine` leaves image discovery unverified and does not select a local socket; the saved deployment still needs it before planning. +Omitting that engine leaves image discovery unverified and does not select a local socket; the saved deployment still needs it before planning. Image compatibility does not verify the external gateway's execution platform or readiness. Independent reads run concurrently, and duplicate requests are read once. It reads the model catalog when a model question opens for a new endpoint request. @@ -162,7 +162,7 @@ Plan and apply perform the deployment's resource, capacity, ownership, and readi The questionnaire also offers: -- Docker and rootless Podman runtimes +- Docker and rootless Podman gateway targets - NVIDIA Endpoints, OpenRouter, OpenAI, Anthropic, Google Gemini, Nous Research, and custom OpenAI- or Anthropic-compatible endpoints - Provider transport APIs, model suggestions, and manual model identifiers diff --git a/crates/nemoclaw-onboarding/src/lib.rs b/crates/nemoclaw-onboarding/src/lib.rs index 989dcde34f8..81b5fce9439 100644 --- a/crates/nemoclaw-onboarding/src/lib.rs +++ b/crates/nemoclaw-onboarding/src/lib.rs @@ -72,7 +72,7 @@ fn load_journey( .ask([ "/metadata/name", "/spec/sandboxes/0/harness/kind", - "/spec/gateway/runtime/provider", + "/spec/gateway/target", "inference:preset", ]) .ask([JourneyScope::InferenceApi]) @@ -120,11 +120,7 @@ mod tests { let resolution = journey.resolve(&capabilities).unwrap(); assert!(resolution.question("/metadata/name").is_some()); assert!(resolution.question("inference:preset").is_some()); - assert!( - resolution - .question("/spec/gateway/runtime/provider") - .is_some() - ); + assert!(resolution.question("/spec/gateway/target").is_some()); } #[test] diff --git a/crates/nemoclaw-onboarding/src/tui/labels.rs b/crates/nemoclaw-onboarding/src/tui/labels.rs index 12c6582ed54..e5360358100 100644 --- a/crates/nemoclaw-onboarding/src/tui/labels.rs +++ b/crates/nemoclaw-onboarding/src/tui/labels.rs @@ -21,7 +21,8 @@ struct QuestionText { } /// Friendly text for questions and choices from `text.json`, keyed by -/// question ID with `*` standing for array indices and adapter IDs. Entries +/// question ID with `*` standing for array indices, service names, gateway +/// target keys, and adapter IDs. Entries /// override the titles and descriptions advertised by the SDK and Fabric /// schemas. Describe Fabric adapter and model settings in the Fabric adapter /// descriptors instead, so every client receives the same text. @@ -33,7 +34,8 @@ fn text() -> &'static Text { } /// Map keys for a question ID, most specific first: the ID itself, then with -/// array indices and service names replaced by `*`, then also the adapter ID. +/// array indices, service names, and gateway target keys replaced by `*`, then +/// also the adapter ID. fn keys(id: &str) -> [String; 3] { let parts = id.split('/').collect::>(); let indices = parts @@ -41,7 +43,11 @@ fn keys(id: &str) -> [String; 3] { .enumerate() .map(|(index, part)| { let service = index > 0 && parts[index - 1] == "services"; - if service || (!part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit())) { + let target = index > 1 && parts[index - 2..index] == ["gateway", "target"]; + if service + || target + || (!part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit())) + { "*" } else { part @@ -180,7 +186,7 @@ fn acronyms(text: &str) -> String { .join(" ") } -/// `timeout_seconds` and `networkCIDR` become "Timeout seconds" and "Network CIDR". +/// `timeout_seconds` and `networkCidr` become "Timeout seconds" and "Network CIDR". fn words(part: &str) -> String { let mut text = String::new(); let mut previous_lower = false; @@ -244,6 +250,12 @@ mod tests { keys("/spec/services/qwen/serving/port")[1], "/spec/services/*/serving/port" ); + assert_eq!( + keys("/spec/gateway/target/podman/engine")[1], + "/spec/gateway/target/*/engine" + ); + // The target key question itself names no key. + assert_eq!(keys("/spec/gateway/target")[1], "/spec/gateway/target"); assert_eq!( keys("adapter:nvidia.fabric.openclaw:/native_config/cron")[2], "adapter:*:/native_config/cron" @@ -260,8 +272,8 @@ mod tests { assert_eq!(readable("adapter:x:/base_url"), "Base URL"); assert_eq!(readable("adapter:x:/cli"), "CLI"); assert_eq!( - readable("/spec/gateway/networkCIDR"), - "Gateway: network CIDR" + readable("/spec/gateway/target/docker/networkCidr"), + "Docker: network CIDR" ); } } diff --git a/crates/nemoclaw-onboarding/src/tui/tests.rs b/crates/nemoclaw-onboarding/src/tui/tests.rs index 8b81ab91622..38a209332f5 100644 --- a/crates/nemoclaw-onboarding/src/tui/tests.rs +++ b/crates/nemoclaw-onboarding/src/tui/tests.rs @@ -588,7 +588,7 @@ fn tui_preserves_podman_as_an_authored_target_choice() { if wizard .question() .unwrap() - .is_some_and(|question| question.id() == "/spec/gateway/runtime/provider") + .is_some_and(|question| question.id() == "/spec/gateway/target") { break; } @@ -605,7 +605,7 @@ fn tui_preserves_podman_as_an_authored_target_choice() { assert!(wizard.error.is_none()); assert_eq!( wizard.state().values().pointer(question.id()), - Some(&serde_json::json!("podman")) + Some(&serde_json::json!({"podman": {}})) ); } @@ -618,7 +618,7 @@ struct RecordedHost { } #[tokio::test] -async fn enter_accepts_the_runtime_this_machine_can_run_and_targets_its_engine() { +async fn enter_accepts_the_target_this_machine_can_run_and_uses_its_engine() { let capabilities = Capabilities::available(); let state = load_journey(Source::Defaults, &capabilities).unwrap(); // Only Podman answered when this machine was read, but the template says Docker. @@ -653,7 +653,7 @@ async fn enter_accepts_the_runtime_this_machine_can_run_and_targets_its_engine() if wizard .question() .unwrap() - .is_some_and(|question| question.id() == "/spec/gateway/runtime/provider") + .is_some_and(|question| question.id() == "/spec/gateway/target") { break; } @@ -662,15 +662,8 @@ async fn enter_accepts_the_runtime_this_machine_can_run_and_targets_its_engine() wizard.advance(); assert!(wizard.error.is_none(), "{:?}", wizard.error); assert_eq!( - wizard - .state() - .values() - .pointer("/spec/gateway/runtime/provider"), - Some(&serde_json::json!("podman")) - ); - assert_eq!( - wizard.state().values().pointer("/spec/gateway/engine"), - Some(&serde_json::json!(podman)) + wizard.state().values().pointer("/spec/gateway/target"), + Some(&serde_json::json!({"podman": {"engine": podman}})) ); } diff --git a/crates/nemoclaw-onboarding/src/tui/text.json b/crates/nemoclaw-onboarding/src/tui/text.json index 710584b12f5..fe6db00b224 100644 --- a/crates/nemoclaw-onboarding/src/tui/text.json +++ b/crates/nemoclaw-onboarding/src/tui/text.json @@ -7,16 +7,20 @@ "/spec/gateway/endpoint": { "title": "Gateway endpoint" }, - "/spec/gateway/engine": { - "title": "Gateway engine socket" - }, - "/spec/gateway/image": { - "title": "Gateway image" - }, "/spec/gateway/management": { "title": "How should NemoClaw reach its gateway?" }, - "/spec/gateway/networkCIDR": { + "/spec/gateway/target": { + "title": "Where should the sandbox run?", + "description": "The key selects where sandboxes run: a local Docker or Podman engine, or a Kubernetes cluster." + }, + "/spec/gateway/target/*/endpoint": { + "title": "Gateway endpoint" + }, + "/spec/gateway/target/*/engine": { + "title": "Gateway engine socket" + }, + "/spec/gateway/target/*/networkCidr": { "title": "Gateway network (CIDR)" }, "/spec/inferenceProviders/*/api": { @@ -61,10 +65,6 @@ "/spec/sandboxes/*/network/tier": { "title": "Network tier" }, - "/spec/gateway/runtime/provider": { - "title": "Where should the sandbox run?", - "description": "The runtime owns the gateway and local sandbox resources." - }, "/spec/services/*/authentication": { "title": "Service authentication" }, @@ -274,6 +274,11 @@ "managed": "Install and manage a local gateway", "external": "Connect to an existing gateway" }, + "/spec/gateway/target": { + "docker": "Docker", + "podman": "Podman", + "kubernetes": "Kubernetes" + }, "/spec/inferenceProviders/*/api": { "openai-completions": "OpenAI chat completions", "openai-responses": "OpenAI Responses", @@ -298,10 +303,6 @@ "/spec/sandboxes/*/network/tier": { "isolated": "Isolated" }, - "/spec/gateway/runtime/provider": { - "docker": "Docker", - "podman": "Podman" - }, "/spec/services/*/authentication": { "bearer": "Bearer token" }, diff --git a/crates/nemoclaw-openshell/src/capabilities.rs b/crates/nemoclaw-openshell/src/capabilities.rs index 47274be5bf4..fd4aebc0460 100644 --- a/crates/nemoclaw-openshell/src/capabilities.rs +++ b/crates/nemoclaw-openshell/src/capabilities.rs @@ -52,7 +52,7 @@ impl GatewayCapabilities { .collect::>() .join(" / "); format!( - "gateway compute driver is {observed}, but spec.gateway.runtime.provider is {driver}" + "gateway compute driver is {observed}, but spec.gateway.target selects {driver}" ) }), ), diff --git a/crates/nemoclaw-openshell/src/observation.rs b/crates/nemoclaw-openshell/src/observation.rs index 3f94c91b2c2..803de27427d 100644 --- a/crates/nemoclaw-openshell/src/observation.rs +++ b/crates/nemoclaw-openshell/src/observation.rs @@ -178,7 +178,7 @@ mod tests { assert_eq!( observed(required, &[&["podman", "selected"]]).incompatibility(["docker"]), Some( - "gateway compute driver is podman / selected, but spec.gateway.runtime.provider is docker" + "gateway compute driver is podman / selected, but spec.gateway.target selects docker" .into() ) ); @@ -197,14 +197,14 @@ mod tests { observed("0.0.1", &[&["docker"]]).incompatibility(["docker", "podman"]), Some(format!( "gateway runs OpenShell 0.0.1, but this build requires {required}; \ - gateway compute driver is docker, but spec.gateway.runtime.provider is podman" + gateway compute driver is docker, but spec.gateway.target selects podman" )) ); assert_eq!( observed("1.0\nforged", &[&["docker\u{7}"]]).incompatibility(["docker"]), Some(format!( "gateway runs OpenShell 1.0\\nforged, but this build requires {required}; \ - gateway compute driver is docker\\u{{7}}, but spec.gateway.runtime.provider is docker" + gateway compute driver is docker\\u{{7}}, but spec.gateway.target selects docker" )) ); let error = observed(required, &[&["podman"]]) @@ -214,7 +214,7 @@ mod tests { assert_eq!( error, "gateway is incompatible with this configuration: gateway compute driver is \ - podman, but spec.gateway.runtime.provider is docker" + podman, but spec.gateway.target selects docker" ); } } @@ -244,7 +244,7 @@ mod discovery_tests { assert_eq!(mismatch.status, ObservationStatus::Unavailable); assert_eq!( mismatch.reason.as_deref(), - Some("gateway compute driver is docker, but spec.gateway.runtime.provider is podman") + Some("gateway compute driver is docker, but spec.gateway.target selects podman") ); let old_version = GatewayObservation::from_result( Ok(GatewayCapabilities { @@ -257,7 +257,7 @@ mod discovery_tests { old_version.reason, Some(format!( "gateway runs OpenShell 0.0.1, but this build requires {}; gateway compute \ - driver is docker, but spec.gateway.runtime.provider is podman", + driver is docker, but spec.gateway.target selects podman", crate::OPENSHELL_VERSION )) ); diff --git a/crates/nemoclaw-provider/tests/contract/discovery.rs b/crates/nemoclaw-provider/tests/contract/discovery.rs index 9b7305f4517..a008654d521 100644 --- a/crates/nemoclaw-provider/tests/contract/discovery.rs +++ b/crates/nemoclaw-provider/tests/contract/discovery.rs @@ -217,7 +217,7 @@ async fn compiled_discovery_requires_runtime_metadata_but_allows_unknown_capabil Some((200,serde_json::to_vec(&body).unwrap())) }).await; let mut value = serde_json::to_value(document).unwrap(); - value["spec"]["gateway"]["engine"] = json!(fixture.endpoint); + value["spec"]["gateway"]["target"]["docker"]["engine"] = json!(fixture.endpoint); let document = Document::parse(value.to_string().as_bytes()).unwrap(); let generations = [ "workspace", diff --git a/crates/nemoclaw-provider/tests/managed_gateway_live.rs b/crates/nemoclaw-provider/tests/managed_gateway_live.rs index 278284655bd..64c6b2f9d9c 100644 --- a/crates/nemoclaw-provider/tests/managed_gateway_live.rs +++ b/crates/nemoclaw-provider/tests/managed_gateway_live.rs @@ -27,7 +27,7 @@ fn gateway_spec(variable: &str) -> Spec { assert!(document.spec.gateway.as_managed().is_some()); assert!(document.spec.services.is_empty()); assert_eq!( - document.spec.gateway.runtime().provider, + document.spec.gateway.compute_driver(), ComputeDriver::Docker ); let mut random = [0_u8; 16]; diff --git a/crates/nemoclaw-sdk/src/compile.rs b/crates/nemoclaw-sdk/src/compile.rs index ec67aa1baef..495f25a6ea2 100644 --- a/crates/nemoclaw-sdk/src/compile.rs +++ b/crates/nemoclaw-sdk/src/compile.rs @@ -373,7 +373,7 @@ pub(crate) fn gateway_provider(gateway: &crate::config::Gateway) -> Value { fn graph_base(document: &Document, version: &str) -> Result { let provider = gateway_provider(&document.spec.gateway); - let drivers = [document.spec.gateway.runtime().provider.openshell_driver()]; + let drivers = [document.spec.gateway.compute_driver().openshell_driver()]; let mut graph = json!({ "terraform":{"required_version":format!("= {OPENTOFU_VERSION}"),"required_providers":{ "nemoclaw":{"source":PROVIDER_ADDRESS,"version":format!("= {version}")}, diff --git a/crates/nemoclaw-sdk/src/compile_runtime.rs b/crates/nemoclaw-sdk/src/compile_runtime.rs index c1410abac03..2c31ede8f90 100644 --- a/crates/nemoclaw-sdk/src/compile_runtime.rs +++ b/crates/nemoclaw-sdk/src/compile_runtime.rs @@ -31,10 +31,10 @@ fn runtime_targets_with_plans( if !document.has_runtime() { return Ok(Vec::new()); } - if document.spec.gateway.as_kubernetes().is_some() { - let settings = document.spec.gateway.as_managed().ok_or(Error::State( - "managed Kubernetes gateway settings are missing", - ))?; + if let Some(managed) = document.spec.gateway.as_managed() + && let Some(cluster) = document.spec.gateway.as_kubernetes() + { + let settings = managed.runtime_settings(); let mut targets = [ crate::kubernetes::STORAGE_KIND, crate::kubernetes::AUTH_KIND, @@ -65,28 +65,26 @@ fn runtime_targets_with_plans( }) }) .collect::, Error>>()?; - let namespace = &settings - .kubernetes - .as_ref() - .expect("Kubernetes settings") - .namespace; targets.push(Target { kind: "helm_release".into(), address: crate::kubernetes::gateway::ADDRESS.into(), values: Row::from([ ("name".into(), format!("{}-gateway", document.workspace())), - ("namespace".into(), namespace.clone()), + ("namespace".into(), cluster.namespace.clone()), ("chart".into(), crate::kubernetes::gateway::CHART.into()), ]), }); return Ok(targets); } - let Some(settings) = document.spec.gateway.as_managed() else { + let (Some(settings), Some(local)) = ( + document.spec.gateway.as_managed(), + document.spec.gateway.as_local_managed(), + ) else { return Ok(service_plans.targets().cloned().collect()); }; let gateway = Spec { layout: 2, - compute_driver: document.spec.gateway.runtime().provider, + compute_driver: local.compute_driver, kind: GATEWAY_KIND.into(), name: format!("{}-gateway", document.workspace()), owner: document.metadata.uid.clone(), @@ -99,7 +97,7 @@ fn runtime_targets_with_plans( let target = |kind: &str, spec: &Spec| -> Result { let mut values = spec.gateway_row(kind)?; if (kind != GATEWAY_STORAGE_KIND || storage.layout == 0) - && let Some(policy) = settings.image_pull_policy + && let Some(policy) = local.image_pull_policy { values.insert("image_pull_policy".into(), policy.as_str().into()); } @@ -235,7 +233,7 @@ pub(crate) fn compiled_runtime( let (mut graph, targets) = runtime_graph(document, generations, version)?; crate::docker_compute::configure(&mut graph, &targets)?; if let Some(gateway) = targets.iter().find(|target| target.kind == GATEWAY_KIND) - && document.spec.gateway.runtime().provider == ComputeDriver::Docker + && document.spec.gateway.compute_driver() == ComputeDriver::Docker { // The process must serve its API before the authenticated capability // read; its readiness fails quickly when the container stops. diff --git a/crates/nemoclaw-sdk/src/compile_teardown.rs b/crates/nemoclaw-sdk/src/compile_teardown.rs index 08b7d3eb1f3..64741cf296d 100644 --- a/crates/nemoclaw-sdk/src/compile_teardown.rs +++ b/crates/nemoclaw-sdk/src/compile_teardown.rs @@ -119,7 +119,8 @@ mod tests { .unwrap(); let mut value = serde_json::to_value(document).unwrap(); value["spec"]["services"]["qwen"]["authentication"] = json!("bearer"); - value["spec"]["gateway"]["engine"] = json!("unix:///tmp/${engine}%{literal}.sock"); + value["spec"]["gateway"]["target"]["docker"]["engine"] = + json!("unix:///tmp/${engine}%{literal}.sock"); let document = Document::parse(value.to_string().as_bytes()).unwrap(); let generations = [ "workspace", diff --git a/crates/nemoclaw-sdk/src/config/kubernetes.rs b/crates/nemoclaw-sdk/src/config/kubernetes.rs index cb87f793d47..fc5347a67e1 100644 --- a/crates/nemoclaw-sdk/src/config/kubernetes.rs +++ b/crates/nemoclaw-sdk/src/config/kubernetes.rs @@ -4,10 +4,16 @@ use super::FileRef; use serde::{Deserialize, Serialize}; -/// Explicit existing-cluster target for a managed development gateway. The SDK does not create a cluster or select an ambient context, and installs nothing cluster-wide: Agent Sandbox and a default StorageClass must already exist. `runtime.provider: openshift` selects the OpenShift profile. +/// Explicit existing-cluster target for a managed development gateway. The SDK does not create a cluster or select an ambient context, and installs nothing cluster-wide: Agent Sandbox and a default StorageClass must already exist. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ManagedKubernetes { + /// Cluster distribution. `openshift` makes the SDK wait up to 30 seconds for OpenShift to assign the namespace its SCC UID range, read the first UID and the first supplemental group (the UID when no supplemental groups are assigned), record that namespace identity, pass it to the gateway chart as security-context values, and bind the `openshift` compute driver. Sandboxes use the upstream Kubernetes driver either way. + #[serde(default)] + #[schemars(default)] + pub distribution: KubernetesDistribution, + /// Local HTTPS origin `https://127.0.0.1:PORT` with an explicit nonzero port and no trailing slash. Commands forward that local port to the owned gateway. + pub endpoint: String, /// Environment reference whose value is the local kubeconfig file path. The file and its credentials remain outside configuration and exported state. Process, loader, trust, proxy, cluster, Python, Helm, OpenTofu, and SDK control variable names are reserved. pub kubeconfig: FileRef, /// Exact kubeconfig context used for every cluster operation. @@ -30,6 +36,20 @@ pub struct ManagedKubernetes { pub environment: Vec, } +/// Kubernetes distribution of a managed gateway's cluster. +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema, +)] +#[serde(rename_all = "lowercase")] +#[schemars(inline)] +pub enum KubernetesDistribution { + /// Upstream Kubernetes. + #[default] + Kubernetes, + /// OpenShift, which assigns namespace user and group IDs. + OpenShift, +} + /// Authentication provisioned for a managed Kubernetes gateway. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] #[serde(rename_all = "camelCase", deny_unknown_fields)] diff --git a/crates/nemoclaw-sdk/src/config/mod.rs b/crates/nemoclaw-sdk/src/config/mod.rs index 5458a8f59be..34b03368ef0 100644 --- a/crates/nemoclaw-sdk/src/config/mod.rs +++ b/crates/nemoclaw-sdk/src/config/mod.rs @@ -191,28 +191,33 @@ impl Document { names } pub fn defaults(&mut self) { - let gateway = &mut self.spec.gateway; - if let Gateway::Managed(gateway) = gateway - && gateway.kubernetes.is_none() - { - default_string(&mut gateway.endpoint, constraints::GATEWAY_ENDPOINT); - if gateway.runtime.provider == ComputeDriver::Docker { - default_string(&mut gateway.engine, constraints::GATEWAY_ENGINE); + let network = format!( + "172.30.{}.0/24", + Sha256::digest(self.metadata.uid.as_bytes())[0] + ); + // A cluster target names everything itself. Podman's socket depends on + // the host user, so only Docker's engine has a default. + let local = match &mut self.spec.gateway { + Gateway::Managed(ManagedGateway { + target: ManagedTarget::Docker(docker), + }) => { + default_string(&mut docker.engine, constraints::GATEWAY_ENGINE); + Some((&mut docker.endpoint, &mut docker.network_cidr)) } - default_string(&mut gateway.image, DEFAULT_GATEWAY_IMAGE); - default_string( - &mut gateway.network_cidr, - &format!( - "172.30.{}.0/24", - Sha256::digest(self.metadata.uid.as_bytes())[0] - ), - ); + Gateway::Managed(ManagedGateway { + target: ManagedTarget::Podman(podman), + }) => Some((&mut podman.endpoint, &mut podman.network_cidr)), + _ => None, + }; + if let Some((endpoint, network_cidr)) = local { + default_string(endpoint, constraints::GATEWAY_ENDPOINT); + default_string(network_cidr, &network); } for service in self.spec.services.values_mut() { crate::services::defaults(service); } // Cluster sandboxes have no engine-supplied default image. - if !self.spec.gateway.runtime().provider.is_kubernetes() { + if !self.spec.gateway.compute_driver().is_kubernetes() { for sandbox in &mut self.spec.sandboxes { default_string(&mut sandbox.image.ref_, DEFAULT_AGENT_IMAGE); } @@ -255,23 +260,57 @@ fn network_address( Ok(std::net::Ipv4Addr::from(address).to_string()) } impl ManagedGateway { - pub(crate) fn runtime_settings(&self) -> Self { - let mut settings = self.clone(); - // Acquisition policy is a mutable provider attribute, not container identity. - settings.image_pull_policy = None; - settings + /// Settings of a gateway on a local Docker or Podman engine; `None` for a + /// Kubernetes target. + pub fn local(&self) -> Option> { + match &self.target { + ManagedTarget::Docker(docker) => Some(LocalGateway { + compute_driver: ComputeDriver::Docker, + endpoint: &docker.endpoint, + engine: &docker.engine, + image_pull_policy: docker.image_pull_policy, + network_cidr: &docker.network_cidr, + }), + ManagedTarget::Podman(podman) => Some(LocalGateway { + compute_driver: ComputeDriver::Podman, + endpoint: &podman.endpoint, + engine: &podman.engine, + image_pull_policy: podman.image_pull_policy, + network_cidr: &podman.network_cidr, + }), + ManagedTarget::Kubernetes(_) => None, + } } /// Resolve the first address after the configured network address. /// /// # Errors - /// Returns an error for malformed IPv4 CIDRs or an address overflow. + /// Returns an error for Kubernetes targets, malformed IPv4 CIDRs, or an + /// address overflow. pub fn bridge(&self) -> Result { - if self.kubernetes.is_some() { - return Err(ConfigError::new( + self.local() + .ok_or(ConfigError::new( "Kubernetes gateways have no local engine bridge", - )); - } - bridge_address(&self.network_cidr) + ))? + .bridge() + } +} + +/// Borrowed settings of a managed gateway on a local Docker or Podman engine. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct LocalGateway<'a> { + pub compute_driver: ComputeDriver, + pub endpoint: &'a str, + pub engine: &'a str, + pub image_pull_policy: Option, + pub network_cidr: &'a str, +} +impl LocalGateway<'_> { + /// Resolve the first address after the configured network address. + /// + /// # Errors + /// Returns an error for malformed IPv4 CIDRs or an address overflow. + pub fn bridge(&self) -> Result { + bridge_address(self.network_cidr) } } fn hex(bytes: &[u8]) -> String { @@ -279,31 +318,46 @@ fn hex(bytes: &[u8]) -> String { } impl Gateway { - /// The compute driver this gateway runs every sandbox with. - pub fn runtime(&self) -> &Runtime { - match self { - Self::Managed(gateway) => &gateway.runtime, - Self::External(gateway) => &gateway.runtime, - } - } - /// The compute driver setting, for changing it. - pub fn runtime_mut(&mut self) -> &mut Runtime { + /// The compute driver this gateway runs every sandbox with. A managed + /// OpenShift distribution binds the OpenShift profile; an external gateway + /// reports only the upstream Kubernetes driver. + pub fn compute_driver(&self) -> ComputeDriver { match self { - Self::Managed(gateway) => &mut gateway.runtime, - Self::External(gateway) => &mut gateway.runtime, + Self::Managed(gateway) => match &gateway.target { + ManagedTarget::Docker(_) => ComputeDriver::Docker, + ManagedTarget::Podman(_) => ComputeDriver::Podman, + ManagedTarget::Kubernetes(cluster) => match cluster.distribution { + KubernetesDistribution::Kubernetes => ComputeDriver::Kubernetes, + KubernetesDistribution::OpenShift => ComputeDriver::OpenShift, + }, + }, + Self::External(gateway) => match gateway.target { + ExternalTarget::Docker(_) => ComputeDriver::Docker, + ExternalTarget::Podman(_) => ComputeDriver::Podman, + ExternalTarget::Kubernetes(_) => ComputeDriver::Kubernetes, + }, } } /// The endpoint used to connect to either gateway configuration. pub fn endpoint(&self) -> &str { match self { - Self::Managed(gateway) => &gateway.endpoint, + Self::Managed(gateway) => match &gateway.target { + ManagedTarget::Docker(docker) => &docker.endpoint, + ManagedTarget::Podman(podman) => &podman.endpoint, + ManagedTarget::Kubernetes(cluster) => &cluster.endpoint, + }, Self::External(gateway) => &gateway.endpoint, } } - /// Change the connection endpoint without changing gateway management. + /// Change the connection endpoint without changing gateway management or + /// target. pub fn endpoint_mut(&mut self) -> &mut String { match self { - Self::Managed(gateway) => &mut gateway.endpoint, + Self::Managed(gateway) => match &mut gateway.target { + ManagedTarget::Docker(docker) => &mut docker.endpoint, + ManagedTarget::Podman(podman) => &mut podman.endpoint, + ManagedTarget::Kubernetes(cluster) => &mut cluster.endpoint, + }, Self::External(gateway) => &mut gateway.endpoint, } } @@ -316,13 +370,14 @@ impl Gateway { } /// Explicit existing-cluster settings for a managed Kubernetes gateway. pub fn as_kubernetes(&self) -> Option<&ManagedKubernetes> { - self.as_managed() - .and_then(|gateway| gateway.kubernetes.as_ref()) + match &self.as_managed()?.target { + ManagedTarget::Kubernetes(cluster) => Some(cluster), + ManagedTarget::Docker(_) | ManagedTarget::Podman(_) => None, + } } /// Local Docker or Podman installation settings; excludes Kubernetes targets. - pub fn as_local_managed(&self) -> Option<&ManagedGateway> { - self.as_managed() - .filter(|gateway| gateway.kubernetes.is_none()) + pub fn as_local_managed(&self) -> Option> { + self.as_managed()?.local() } /// Mutable installation settings, when this deployment manages the gateway. pub fn as_managed_mut(&mut self) -> Option<&mut ManagedGateway> { @@ -331,11 +386,23 @@ impl Gateway { Self::External(_) => None, } } - pub(crate) fn managed(&self) -> Result<&ManagedGateway, ConfigError> { + pub(crate) fn managed(&self) -> Result, ConfigError> { self.as_local_managed().ok_or(ConfigError::new( "operation requires a managed local gateway", )) } + /// The engine holding sandbox images: a local managed gateway's engine or + /// the engine named by an external Docker or Podman target. Empty for + /// Kubernetes, where image metadata bundles replace engine inspection. + pub fn image_engine(&self) -> &str { + match self { + Self::Managed(gateway) => gateway.local().map_or("", |local| local.engine), + Self::External(gateway) => match &gateway.target { + ExternalTarget::Docker(target) | ExternalTarget::Podman(target) => &target.engine, + ExternalTarget::Kubernetes(_) => "", + }, + } + } pub fn credential(&self) -> Option<&SecretRef> { match self { Self::Managed(_) => None, diff --git a/crates/nemoclaw-sdk/src/config/schema.rs b/crates/nemoclaw-sdk/src/config/schema.rs index 926e9b3fcaf..c5ff4c76190 100644 --- a/crates/nemoclaw-sdk/src/config/schema.rs +++ b/crates/nemoclaw-sdk/src/config/schema.rs @@ -4,7 +4,7 @@ pub(crate) mod validation; // Editors select union variants the same way schema diagnostics do. -pub use nemoclaw_runtime::schema::select_variant; +pub use nemoclaw_runtime::schema::{select_variant, variant_keys}; pub const SCHEMA_PATH: &str = "schemas/nemoclaw-v1alpha1.schema.json"; diff --git a/crates/nemoclaw-sdk/src/config/schema/runtime.rs b/crates/nemoclaw-sdk/src/config/schema/runtime.rs index 5786c6d995b..ff57e64f3c2 100644 --- a/crates/nemoclaw-sdk/src/config/schema/runtime.rs +++ b/crates/nemoclaw-sdk/src/config/schema/runtime.rs @@ -81,7 +81,18 @@ fn diagnostic( return diagnostic(error, root, schema, source, &variant); } let keyed = union.and_then(|(variants, _)| variant_keys(variants)); - let constraint = if let Some(mut keys) = keyed { + // A union of constants or bounds, such as a string choice, lists them. + let scalar_choices = || { + let (variants, _) = union?; + let alternatives = variants + .iter() + .map(scalar_constraint) + .collect::>>()?; + Some(format!("must be {}", alternatives.join(" or "))) + }; + let constraint = if let Some(message) = removed_fields(schema, error) { + message + } else if let Some(mut keys) = keyed { // The input named no single variant: list the declared keys, never the // input's, unless the union carries its own message. An enclosing // rule's message describes a different constraint. @@ -115,17 +126,16 @@ fn diagnostic( .collect::>() .join(" or ") ), - Kind::AnyOf { .. } => union - .and_then(|(variants, _)| { - variants - .iter() - .map(scalar_constraint) - .collect::>>() - }) - .map(|alternatives| format!("must be {}", alternatives.join(" or "))) + Kind::AnyOf { .. } => scalar_choices() .unwrap_or_else(|| "must match an allowed combination of fields".into()), - Kind::OneOfNotValid { .. } => "must match one allowed object shape".into(), - Kind::AdditionalProperties { .. } => "unknown fields are not allowed".into(), + Kind::OneOfNotValid { .. } => { + scalar_choices().unwrap_or_else(|| "must match one allowed object shape".into()) + } + // A closed object without declared properties reports any field + // as a false schema. + Kind::AdditionalProperties { .. } | Kind::FalseSchema => { + "unknown fields are not allowed".into() + } _ => error.kind().keyword().to_owned(), } }; @@ -180,6 +190,39 @@ fn annotation<'s>( None } +/// The replacements for fields an earlier document shape accepted, when the +/// rejecting object lists them under `x-nemoclaw-removed-fields`, so an +/// earlier document gets every hint at once. `runtime` leads, since it chose +/// where the other fields now live; the rest follow the annotation's order. +/// Only the schema's text is rendered, never arbitrary input keys. +fn removed_fields(schema: &Value, error: &jsonschema::ValidationError<'_>) -> Option { + use jsonschema::error::ValidationErrorKind as Kind; + let Kind::AdditionalProperties { unexpected } = error.kind() else { + return None; + }; + let object = error + .schema_path() + .as_str() + .strip_suffix("/additionalProperties")?; + let removed = schema + .pointer(object)? + .get("x-nemoclaw-removed-fields")? + .as_object()?; + let mut matched = removed + .iter() + .filter(|(field, _)| unexpected.contains(field)) + .filter_map(|(field, message)| Some((field.as_str(), message.as_str()?))) + .collect::>(); + matched.sort_by_key(|(field, _)| *field != "runtime"); + (!matched.is_empty()).then(|| { + matched + .into_iter() + .map(|(_, message)| message) + .collect::>() + .join("; ") + }) +} + fn scalar_constraint(schema: &Value) -> Option { if let Some(value) = schema.get("const") { return Some(value.to_string()); @@ -410,32 +453,32 @@ mod tests { #[test] fn an_inline_single_key_union_without_one_known_key_ignores_annotated_ancestors() { let union = |annotation: Option<&str>| { - let mut runtime = json!({"oneOf": [ + let mut target = json!({"oneOf": [ keyed("docker", json!({"type": "object"})), keyed("podman", json!({"type": "object"})), ]}); if let Some(annotation) = annotation { - runtime["x-nemoclaw-error"] = json!(annotation); + target["x-nemoclaw-error"] = json!(annotation); } json!({ "type": "object", "properties": {"gateway": { "type": "object", - "properties": {"runtime": runtime}, + "properties": {"target": target}, "x-nemoclaw-error": "the gateway must name an endpoint" }} }) }; - for runtime in [json!({"dokcer": {}}), json!({})] { - let instance = json!({"gateway": {"runtime": runtime}}); + for target in [json!({"dokcer": {}}), json!({})] { + let instance = json!({"gateway": {"target": target}}); assert_eq!( message(&union(None), instance.clone()), - "configuration violates schema at gateway.runtime: must contain exactly one of: docker, podman", + "configuration violates schema at gateway.target: must contain exactly one of: docker, podman", "{instance}" ); assert_eq!( - message(&union(Some("the gateway names one runtime")), instance), - "configuration violates schema at gateway.runtime: the gateway names one runtime" + message(&union(Some("the gateway names one target")), instance), + "configuration violates schema at gateway.target: the gateway names one target" ); } } @@ -483,6 +526,18 @@ mod tests { } } + #[test] + fn a_field_that_no_schema_allows_is_unknown() { + let schema = json!({ + "type": "object", + "properties": {"gateway": {"type": "object", "properties": {"target": false}}} + }); + assert_eq!( + message(&schema, json!({"gateway": {"target": {}}})), + "configuration violates schema at gateway.target: unknown fields are not allowed" + ); + } + #[test] fn a_missing_field_reports_its_own_annotation() { let schema = json!({ diff --git a/crates/nemoclaw-sdk/src/config/schema/validation.rs b/crates/nemoclaw-sdk/src/config/schema/validation.rs index 4e071aad2a1..2dea727ad3e 100644 --- a/crates/nemoclaw-sdk/src/config/schema/validation.rs +++ b/crates/nemoclaw-sdk/src/config/schema/validation.rs @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 //! Shared structural contract for authored input and normalized SDK values. -use crate::config::{API_VERSION, DEFAULT_AGENT_IMAGE, DEFAULT_GATEWAY_IMAGE, constraints as c}; +use crate::config::{API_VERSION, DEFAULT_AGENT_IMAGE, constraints as c}; use serde_json::{Value, json}; pub(crate) use nemoclaw_runtime::schema::{at, forbid, property}; @@ -171,12 +171,7 @@ pub(super) fn constrain(root: &mut Value, normalized: bool) { .unwrap() .remove("default"); defs["Image"]["properties"]["ref"]["x-nemoclaw-default-rule"] = json!( - "Kubernetes and OpenShift require an explicit immutable image reference. For other drivers, omitted or empty selects the generic SDK agent image pin; verify that it contains the selected Fabric adapter." - ); - property( - &mut defs["Runtime"], - "provider", - json!({"default": super::super::ComputeDriver::default()}), + "A Kubernetes target requires an explicit immutable image reference. For Docker and Podman targets, omitted or empty selects the generic SDK agent image pin; verify that it contains the selected Fabric adapter." ); optional_string( &mut defs["Network"], @@ -243,91 +238,7 @@ pub(super) fn constrain(root: &mut Value, normalized: bool) { json!({"pattern": c::MODEL}), ); - for gateway in defs["Gateway"]["oneOf"] - .as_array_mut() - .expect("gateway variants") - { - property( - gateway, - "management", - json!({"description": "Whether this deployment manages the gateway."}), - ); - if gateway["properties"]["management"]["const"] == "managed" { - let mut local = json!({"properties": {}, "required": []}); - for (field, rule) in [ - ( - "endpoint", - json!({"anyOf": [{"const": ""}, {"pattern": "^http://127\\.0\\.0\\.1:[0-9]+/?$"}], "default": c::GATEWAY_ENDPOINT}), - ), - ( - "engine", - // Docker's socket is the default for a Docker runtime only; - // the Podman rule below requires an explicit socket. - json!({"anyOf": [{"const":""},{"pattern":"^unix:///"}], "default": c::GATEWAY_ENGINE}), - ), - ( - "image", - json!({"enum": ["", DEFAULT_GATEWAY_IMAGE], "default": DEFAULT_GATEWAY_IMAGE}), - ), - ( - "networkCIDR", - json!({"anyOf": [{"const": ""}, {"pattern": "/24$"}], "x-nemoclaw-default-rule": "Omitted or empty selects 172.30.N.0/24, where N is the first byte of SHA-256(metadata.uid)."}), - ), - ] { - let mut rule = rule; - if normalized { - local["required"].as_array_mut().unwrap().push(json!(field)); - if let Some(choices) = rule.get_mut("anyOf").and_then(Value::as_array_mut) { - choices.retain(|choice| choice.get("const") != Some(&json!(""))); - } - if field == "image" { - rule["enum"] = json!([DEFAULT_GATEWAY_IMAGE]); - } - } - // A default only annotates; the Kubernetes branch still - // excludes these fields. Editors and onboarding read a field's - // default from its own schema, not from a conditional branch. - if let Some(default) = rule.get("default").cloned() { - property(gateway, field, json!({"default": default})); - } - local["properties"][field] = rule; - property( - gateway, - field, - json!({"x-nemoclaw-default-rule": if field == "endpoint" { - "Without kubernetes, omitted or empty selects the local HTTP endpoint. Kubernetes requires an explicit HTTPS loopback endpoint and port." - } else if field == "networkCIDR" { - "Without kubernetes, omitted or empty selects 172.30.N.0/24, where N is the first byte of SHA-256(metadata.uid). Excluded by kubernetes." - } else if field == "engine" { - "With runtime.provider docker, omitted or empty selects Docker's default socket. Podman requires its API service socket. Excluded by kubernetes." - } else { - "Without kubernetes, omitted or empty selects the SDK default. Excluded by kubernetes." - }}), - ); - } - gateway["if"] = json!({"required": ["kubernetes"]}); - gateway["then"] = json!({ - "required": ["endpoint"], - "properties": {"endpoint": {"pattern": c::KUBERNETES_GATEWAY_ENDPOINT}}, - "allOf": [forbid(&["engine", "image", "imagePullPolicy", "networkCIDR"])], - "x-nemoclaw-error": "managed Kubernetes requires an explicit HTTPS 127.0.0.1 endpoint with a nonzero port and excludes local engine settings" - }); - gateway["else"] = local; - // Podman's socket depends on the host user, so it has no default. - gateway["allOf"] = json!([{ - "if": at("runtime/provider", json!({"const":"podman"}), true), - "then": { - "required": ["engine"], - "properties": {"engine": {"minLength": 1}}, - "x-nemoclaw-error": "Podman requires spec.gateway.engine to name its local API service socket." - } - }]); - } else { - property(gateway, "endpoint", json!({"pattern": "^https?://"})); - gateway["if"] = at("endpoint", json!({"pattern": "^http:"}), true); - gateway["then"] = forbid(&["credential", "tls"]); - } - } + constrain_gateway(defs, normalized); let provider = &mut defs["InferenceProvider"]; property(provider, "serviceRef", json!({"pattern": c::SLUG})); @@ -346,42 +257,39 @@ pub(super) fn constrain(root: &mut Value, normalized: bool) { defs["AgentExecution"]["minProperties"] = json!(1); crate::services::constrain_schema(defs, normalized); - root["allOf"] = json!([{ - "if": {"not": at("spec/gateway/runtime/provider", json!({"const":"podman"}), true)}, - "then": at("spec/gateway/imagePullPolicy", json!({"enum":["IfNotPresent", "Never"]}), false) - }]); - root["allOf"].as_array_mut().unwrap().push(json!({ - "if": at("spec/gateway/management", json!({"const":"managed"}), true), - "then": { - "if": at("spec/gateway", json!({"required":["kubernetes"]}), true), - "then": at("spec/gateway/runtime/provider", json!({"enum":["kubernetes", "openshift"]}), true), - "else": at("spec/gateway/runtime/provider", json!({"enum":["docker", "podman"]}), false) - } - })); // Cluster sandboxes need an explicit image, since no local engine supplies // a default; image metadata stands in for engine inspection only there. - root["allOf"].as_array_mut().unwrap().push(json!({ - "if": at("spec/gateway/runtime/provider", json!({"enum":["kubernetes", "openshift"]}), true), - "then": at("spec/sandboxes/[]/image", json!({"required": ["ref", "metadata"], "properties": {"ref": {"pattern": c::IMAGE}}}), true), - "else": at("spec/sandboxes/[]/image", forbid(&["metadata"]), false) - })); - root["allOf"].as_array_mut().unwrap().push(json!({ - "if": at("spec/gateway/runtime/provider", json!({"enum":["kubernetes", "openshift"]}), true), - "then": { - "allOf": [ - {"anyOf": [ - at("spec/gateway/management", json!({"const":"external"}), true), - at("spec/gateway", json!({"required":["management","kubernetes"], "properties":{"management":{"const":"managed"}}}), true) - ]}, - at("spec/services", json!({"maxProperties":0}), false) - ], - "x-nemoclaw-error": "Kubernetes requires an external gateway or an explicit managed Kubernetes target, and external inference endpoints; managed services are not supported" + let cluster = at( + "spec/gateway/target", + json!({"required": ["kubernetes"]}), + true, + ); + let mut explicit = at( + "spec/sandboxes/[]/image", + json!({"required": ["ref", "metadata"], "properties": {"ref": {"pattern": c::IMAGE}}}), + true, + ); + explicit["x-nemoclaw-error"] = json!( + "a Kubernetes target requires each sandbox image.ref pinned by digest and image.metadata" + ); + let mut inspected = at("spec/sandboxes/[]/image", forbid(&["metadata"]), false); + inspected["x-nemoclaw-error"] = json!( + "image.metadata is available only for a spec.gateway.target.kubernetes gateway; Docker and Podman use engine image inspection" + ); + root["allOf"] = json!([ + {"if": cluster.clone(), "then": explicit, "else": inspected}, + { + "if": cluster, + "then": { + "allOf": [at("spec/services", json!({"maxProperties": 0}), false)], + "x-nemoclaw-error": "a Kubernetes target requires external inference endpoints; managed services are not supported" + } } - })); + ]); root["x-nemoclaw-parser-checks"] = json!([ "Document::parse rejects YAML aliases, anchors, merge keys, all explicit tags (including core tags such as !!binary), duplicate keys, multiple documents, and input larger than 1 MiB. It applies the compiled input schema before defaulting; Document::validate applies the normalized schema and semantic checks, including for directly constructed Rust values.", "The parser checks endpoint transport and address policy, managed gateway port bounds, canonical private IPv4 /24 networks, local engine socket syntax, and publication address/port/network agreement.", - "Managed Kubernetes requires explicit kubeconfig environment, context, namespace, and development authentication profile; Agent Sandbox and one default StorageClass must already be installed. Its HTTPS endpoint is exactly 127.0.0.1 with an explicit port from 1 through 65535 and no path. Local engine fields and managed inference services are excluded; gateway.runtime.provider is kubernetes or openshift. OpenShift uses the upstream Kubernetes driver and requires platform-owned OpenShift security prerequisites. Cluster identity, ownership, prerequisite compatibility, and credential files are checked during operations.", + "A managed Kubernetes target requires explicit kubeconfig environment, context, namespace, and development authentication profile; Agent Sandbox and one default StorageClass must already be installed. Its HTTPS endpoint is exactly 127.0.0.1 with an explicit port from 1 through 65535 and no path. A Kubernetes target, managed or external, excludes managed inference services. The openshift distribution uses the upstream Kubernetes driver and requires platform-owned OpenShift security prerequisites. Cluster identity, ownership, prerequisite compatibility, and credential files are checked during operations.", "Explicit sandbox policies are also checked by the pinned OpenShell policy parser and validator, including protocol-specific rule semantics, process identities, filesystem paths, and destination address restrictions.", "Explicit filesystem grants must permit reads of the packaged Fabric runtime and NemoClaw bridge directories; parent and read-write grants count. This parser check does not inspect images, resolve symlinks, or establish runtime permissions.", "The schema requires an explicit default for multiple model choices. Rust checks unique route names, that the default names a route, and that native model and tool fields have valid structural shapes. Fabric validates adapter-specific combinations.", @@ -394,3 +302,151 @@ pub(super) fn constrain(root: &mut Value, normalized: bool) { "Schema validation does not observe hardware, image labels, model weights, credentials, ownership, connectivity, or inference readiness. Those checks run during the relevant SDK operation." ]); } + +/// Gateway variants and their targets. Each target is its own definition, so +/// it states only its own defaults, required fields, and pull policies. +fn constrain_gateway(defs: &mut serde_json::Map, normalized: bool) { + // Earlier documents named these fields directly on the gateway; a + // diagnostic names the replacement instead of only rejecting the field. + let runtime = "spec.gateway.runtime is replaced by the key under spec.gateway.target: docker, podman, or kubernetes"; + let engine = "spec.gateway.engine moved to spec.gateway.target.docker.engine or spec.gateway.target.podman.engine"; + for gateway in defs["Gateway"]["oneOf"] + .as_array_mut() + .expect("gateway variants") + { + property( + gateway, + "management", + json!({"description": "Whether this deployment manages the gateway."}), + ); + if normalized { + gateway["required"] + .as_array_mut() + .unwrap() + .push(json!("target")); + } + let managed = gateway["properties"]["management"]["const"] == "managed"; + if !normalized { + let target = if managed { + json!(super::super::ManagedTarget::default()) + } else { + json!(super::super::ExternalTarget::default()) + }; + property(gateway, "target", json!({"default": target})); + } + if managed { + gateway["x-nemoclaw-removed-fields"] = json!({ + "runtime": runtime, + "endpoint": "spec.gateway.endpoint of a managed gateway moved to the endpoint of its spec.gateway.target key", + "engine": engine, + "image": "spec.gateway.image is removed because the SDK pins the gateway image", + "imagePullPolicy": "spec.gateway.imagePullPolicy moved to spec.gateway.target.docker or spec.gateway.target.podman", + "networkCIDR": "spec.gateway.networkCIDR moved to networkCidr under spec.gateway.target.docker or spec.gateway.target.podman", + "kubernetes": "spec.gateway.kubernetes moved to spec.gateway.target.kubernetes" + }); + } else { + gateway["x-nemoclaw-removed-fields"] = json!({"runtime": runtime, "engine": engine}); + property(gateway, "endpoint", json!({"pattern": "^https?://"})); + gateway["if"] = at("endpoint", json!({"pattern": "^http:"}), true); + gateway["then"] = forbid(&["credential", "tls"]); + } + } + // The generated reference describes each target key by its variant. + for name in ["ManagedTarget", "ExternalTarget"] { + for variant in defs[name]["oneOf"].as_array_mut().expect("target variants") { + let key = variant["required"][0] + .as_str() + .expect("single-key target variant") + .to_owned(); + let description = variant["description"].clone(); + property(variant, &key, json!({"description": description})); + } + } + let endpoint = json!({"pattern": "^http://127\\.0\\.0\\.1:[0-9]+/?$"}); + let network = json!({"pattern": "/24$"}); + for (name, key) in [("ManagedDocker", "docker"), ("ManagedPodman", "podman")] { + let target = &mut defs[name]; + optional_string( + target, + "endpoint", + c::GATEWAY_ENDPOINT, + &endpoint, + normalized, + ); + property( + target, + "endpoint", + json!({"x-nemoclaw-error": "a Docker or Podman gateway endpoint is http://127.0.0.1:PORT with an unprivileged port"}), + ); + optional_string(target, "networkCidr", "", &network, normalized); + let cidr = target["properties"]["networkCidr"].as_object_mut().unwrap(); + cidr.remove("default"); + cidr.insert( + "x-nemoclaw-default-rule".into(), + json!("Omitted or empty selects 172.30.N.0/24, where N is the first byte of SHA-256(metadata.uid)."), + ); + cidr.insert( + "x-nemoclaw-error".into(), + json!("networkCidr must be a canonical private IPv4 /24"), + ); + property( + target, + "imagePullPolicy", + json!({"default": super::super::ImagePullPolicy::default()}), + ); + target["x-nemoclaw-removed-fields"] = json!({ + "image": format!("spec.gateway.target.{key} takes no image because the SDK pins the gateway image"), + "networkCIDR": format!("spec.gateway.target.{key} spells networkCIDR as networkCidr") + }); + } + optional_string( + &mut defs["ManagedDocker"], + "engine", + c::GATEWAY_ENGINE, + &json!({"pattern": "^unix:///"}), + normalized, + ); + // Docker accepts two of the engine policies. Its own choices, rather than + // the shared definition, let editors offer only those. + let choices = defs["ImagePullPolicy"]["oneOf"] + .as_array() + .expect("pull policy choices") + .iter() + .filter(|choice| choice["const"] != "Always") + .cloned() + .collect::>(); + let policy = defs["ManagedDocker"]["properties"]["imagePullPolicy"] + .as_object_mut() + .unwrap(); + policy.remove("$ref"); + policy.insert("oneOf".into(), json!(choices)); + property( + &mut defs["ManagedPodman"], + "engine", + json!({ + "minLength": 1, + "pattern": "^unix:///", + "x-nemoclaw-error": "Podman requires spec.gateway.target.podman.engine to name its local API service socket" + }), + ); + property( + &mut defs["ManagedKubernetes"], + "endpoint", + json!({ + "pattern": c::KUBERNETES_GATEWAY_ENDPOINT, + "x-nemoclaw-error": "managed Kubernetes requires an explicit HTTPS 127.0.0.1 endpoint with a nonzero port and no path" + }), + ); + property( + &mut defs["ManagedKubernetes"], + "distribution", + json!({"default": super::super::KubernetesDistribution::default()}), + ); + // Declared, empty properties make an unknown field an additional property, + // which the removed-field hint can name. + let existing = &mut defs["ExternalKubernetes"]; + existing["properties"] = json!({}); + existing["x-nemoclaw-removed-fields"] = json!({ + "distribution": "distribution applies only to a managed gateway's spec.gateway.target.kubernetes; an existing gateway reports only the kubernetes driver" + }); +} diff --git a/crates/nemoclaw-sdk/src/config/types.rs b/crates/nemoclaw-sdk/src/config/types.rs index 0250d5d682b..75b9b69c2af 100644 --- a/crates/nemoclaw-sdk/src/config/types.rs +++ b/crates/nemoclaw-sdk/src/config/types.rs @@ -114,7 +114,6 @@ pub struct TLS { /// Install a local or explicitly configured Kubernetes gateway, or connect to an existing gateway. pub enum Gateway { /// A gateway installed and managed by this deployment. - /// Managed Podman targets local rootless Linux; rootful, remote, and other platforms are unqualified. #[schemars(title = "Managed gateway")] Managed(ManagedGateway), /// An existing gateway managed outside this deployment. @@ -131,40 +130,72 @@ impl Default for Gateway { #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] #[schemars(!default)] #[serde(default, deny_unknown_fields)] -/// Installation settings for a managed gateway. Without kubernetes, use a local Docker or rootless Linux Podman engine. Kubernetes requires an explicit existing-cluster target and the development authentication profile. +/// Installation settings for a managed gateway: a local Docker or rootless Linux Podman engine, or an explicit existing Kubernetes cluster. pub struct ManagedGateway { - #[serde(rename = "runtime")] #[schemars(default)] - /// Compute driver the gateway runs every sandbox with; omission selects Docker. - pub runtime: Runtime, - #[serde(rename = "endpoint")] + /// Where the gateway runs. The key selects the compute driver for every sandbox; omission selects a local Docker engine. + pub target: ManagedTarget, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "lowercase")] +/// Exactly one target key: docker, podman, or kubernetes. +pub enum ManagedTarget { + /// Install the gateway on a local Docker engine. + Docker(ManagedDocker), + /// Install the gateway on a local rootless Linux Podman engine. Rootful, remote, and other platforms are unqualified. + Podman(ManagedPodman), + /// Install the gateway in an explicit existing Kubernetes cluster. Sandboxes need explicit images with metadata, and managed inference services are excluded. + Kubernetes(super::ManagedKubernetes), +} + +impl Default for ManagedTarget { + fn default() -> Self { + Self::Docker(ManagedDocker::default()) + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[schemars(!default)] +#[serde(default, deny_unknown_fields, rename_all = "camelCase")] +/// Local Docker engine settings for a managed gateway. +pub struct ManagedDocker { + #[serde(skip_serializing_if = "String::is_empty")] #[schemars(default)] - /// Local engine gateways use an HTTP origin with an unprivileged loopback port. Kubernetes requires `https://127.0.0.1:PORT` with an explicit nonzero port and no trailing slash; commands forward that local port to the owned gateway. + /// Gateway HTTP origin with the 127.0.0.1 loopback address and an unprivileged port. pub endpoint: String, - #[serde(rename = "engine", skip_serializing_if = "String::is_empty")] + #[serde(skip_serializing_if = "String::is_empty")] #[schemars(default)] - /// Managed local gateway Unix engine socket; Podman requires its API service socket. Excluded by kubernetes. + /// Docker engine Unix socket. pub engine: String, - #[serde(rename = "image", skip_serializing_if = "String::is_empty")] + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars(default, with = "super::ImagePullPolicy")] + /// Gateway image acquisition before container creation: IfNotPresent (the default) or Never. + pub image_pull_policy: Option, + #[serde(skip_serializing_if = "String::is_empty")] #[schemars(default)] - /// Managed local gateway image pinned by the SDK. Excluded by kubernetes, whose component images are also SDK-pinned. - pub image: String, - #[serde( - rename = "imagePullPolicy", - default, - skip_serializing_if = "Option::is_none" - )] + /// Canonical private IPv4 /24 for the gateway network. + pub network_cidr: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +/// Local rootless Linux Podman engine settings for a managed gateway. +pub struct ManagedPodman { + #[serde(default, skip_serializing_if = "String::is_empty")] + #[schemars(default)] + /// Gateway HTTP origin with the 127.0.0.1 loopback address and an unprivileged port. + pub endpoint: String, + /// Podman API service Unix socket. It depends on the host user, so it has no default. + pub engine: String, + #[serde(default, skip_serializing_if = "Option::is_none")] #[schemars(default, with = "super::ImagePullPolicy")] - /// Image acquisition before local container creation. Docker accepts IfNotPresent (the default) or Never; Podman also accepts Always before creation or restart. Excluded by kubernetes. + /// Gateway image acquisition: Always before creation or restart, IfNotPresent (the default), or Never. pub image_pull_policy: Option, - #[serde(rename = "networkCIDR", skip_serializing_if = "String::is_empty")] + #[serde(default, skip_serializing_if = "String::is_empty")] #[schemars(default)] - /// Canonical private IPv4 /24 for a managed local gateway. Excluded by kubernetes. + /// Canonical private IPv4 /24 for the gateway network. pub network_cidr: String, - #[serde(skip_serializing_if = "Option::is_none")] - #[schemars(default, with = "super::ManagedKubernetes")] - /// Explicit Kubernetes provisioning target. Excludes local engine, image, imagePullPolicy, and networkCIDR settings and requires Kubernetes sandboxes without managed inference services. - pub kubernetes: Option, } #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] @@ -172,14 +203,6 @@ pub struct ManagedGateway { #[serde(default, deny_unknown_fields)] /// Connection settings for an existing gateway. Credentials and TLS require HTTPS. pub struct ExternalGateway { - #[serde(rename = "runtime")] - #[schemars(default)] - /// Compute driver the existing gateway runs; omission selects Docker. Planning checks it against the driver the gateway reports. - pub runtime: Runtime, - /// Engine containing Docker or Podman sandbox images, used only for image metadata inspection. Required for their deployment planning; omission permits retained-state teardown. Kubernetes and OpenShift use image.metadata instead. - #[serde(default, skip_serializing_if = "String::is_empty")] - #[schemars(default)] - pub engine: String, /// Gateway HTTP(S) origin, without a path. pub endpoint: String, #[serde(rename = "credential", skip_serializing_if = "Option::is_none")] @@ -190,8 +213,45 @@ pub struct ExternalGateway { #[schemars(default, with = "TLS")] /// Optional mutual TLS references for an external HTTPS gateway. pub tls: Option, + #[schemars(default)] + /// The key selects the compute driver that runs every sandbox; omission selects Docker. Planning checks it against the driver the gateway reports. + pub target: ExternalTarget, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "lowercase")] +/// Exactly one target key: docker, podman, or kubernetes. +pub enum ExternalTarget { + /// The existing gateway runs sandboxes on Docker. + Docker(ExternalEngine), + /// The existing gateway runs sandboxes on Podman. + Podman(ExternalEngine), + /// The existing gateway runs sandboxes on Kubernetes, including OpenShift. Sandboxes need explicit images with metadata, and managed inference services are excluded. + Kubernetes(ExternalKubernetes), +} + +impl Default for ExternalTarget { + fn default() -> Self { + Self::Docker(ExternalEngine::default()) + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[schemars(!default)] +#[serde(default, deny_unknown_fields)] +/// Engine holding sandbox images for an existing Docker or Podman gateway. +pub struct ExternalEngine { + #[serde(skip_serializing_if = "String::is_empty")] + #[schemars(default)] + /// Engine containing the sandbox images, used only for image metadata inspection. Required for deployment planning; omission permits retained-state teardown. + pub engine: String, } +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +/// An existing Kubernetes or OpenShift gateway takes no target settings; sandbox image metadata replaces engine inspection. +pub struct ExternalKubernetes {} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] #[serde(deny_unknown_fields)] /// Choose an endpoint for external inference or serviceRef for a managed service. @@ -267,8 +327,8 @@ pub struct Sandbox { pub name: String, #[serde(rename = "image")] #[schemars(default)] - #[schemars(extend("x-nemoclaw-required" = "For Kubernetes sandboxes"))] - /// Kubernetes requires an explicit immutable agent image compatible with the gateway's runtime user and group IDs. For other drivers, omission selects the generic SDK agent image pin; verify that it contains the selected Fabric adapter. + #[schemars(extend("x-nemoclaw-required" = "With a Kubernetes target"))] + /// Agent image compatible with the gateway's runtime user and group IDs. A Kubernetes target requires an explicit `ref` and `metadata`; Docker and Podman targets may omit it and use the generic SDK agent image pin. pub image: Image, #[serde(rename = "network")] #[schemars(default)] @@ -286,26 +346,16 @@ pub struct Sandbox { pub struct Image { #[serde(rename = "ref")] #[schemars(default)] - #[schemars(extend("x-nemoclaw-required" = "For Kubernetes sandboxes"))] - /// Immutable image reference. Kubernetes and OpenShift require an explicit nonempty reference. For other drivers, omitted or empty selects the generic SDK agent image pin; verify that it contains the selected Fabric adapter. + #[schemars(extend("x-nemoclaw-required" = "With a Kubernetes target"))] + /// Immutable image reference pinned by digest. pub ref_: String, #[serde(default, skip_serializing_if = "Option::is_none")] #[schemars(default, with = "FileRef")] - /// Environment reference to the absolute path of a local OCI metadata bundle for `ref`; required for Kubernetes and OpenShift, where no local engine can be inspected. Destroy does not read it. Its index, manifest, configuration, and Fabric catalog are verified against `ref` before use. The bundle holds no image layers or credentials. Docker and Podman inspect their engine instead. + #[schemars(extend("x-nemoclaw-required" = "With a Kubernetes target"))] + /// Environment reference to the absolute path of a local OCI metadata bundle for `ref`. A Kubernetes target requires it because no local engine can be inspected; Docker and Podman targets inspect their engine instead and reject it. Destroy does not read it. Its index, manifest, configuration, and Fabric catalog are verified against `ref` before use. The bundle holds no image layers or credentials. pub metadata: Option, } -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] -#[schemars(!default)] -#[serde(default, deny_unknown_fields)] -/// The compute driver an OpenShell gateway runs sandboxes with. One gateway runs one driver. -pub struct Runtime { - #[serde(rename = "provider")] - #[schemars(default)] - /// Docker, Podman, Kubernetes, or OpenShift profile. Kubernetes and OpenShift require an external gateway or an explicit managed cluster target, and external inference endpoints. OpenShift uses the upstream Kubernetes driver with namespace-assigned identities. A managed service with Podman requires explicit service placement. - pub provider: super::ComputeDriver, -} - #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] #[schemars(!default)] #[serde(default, deny_unknown_fields)] diff --git a/crates/nemoclaw-sdk/src/config/validation.rs b/crates/nemoclaw-sdk/src/config/validation.rs index cee2af5c5c0..55566f65e77 100644 --- a/crates/nemoclaw-sdk/src/config/validation.rs +++ b/crates/nemoclaw-sdk/src/config/validation.rs @@ -24,10 +24,23 @@ impl Document { if let Gateway::Managed(gateway) = gateway { gateway.validate_managed()?; } - if let Gateway::External(gateway) = gateway - && !gateway.engine.is_empty() - { - super::validate_engine_endpoint(&gateway.engine)?; + if let Gateway::External(external) = gateway { + let image_store = match &external.target { + ExternalTarget::Docker(target) => Some(( + &target.engine, + "spec.gateway.target.docker.engine must be a unix:/// socket or ssh://[user@]host[:port] without a password, path, or options", + )), + ExternalTarget::Podman(target) => Some(( + &target.engine, + "spec.gateway.target.podman.engine must be a unix:/// socket or ssh://[user@]host[:port] without a password, path, or options", + )), + ExternalTarget::Kubernetes(_) => None, + }; + if let Some((engine, rule)) = image_store + && !engine.is_empty() + { + super::validate_engine_endpoint(engine).map_err(|_| ConfigError::new(rule))?; + } } validate_endpoint(gateway.endpoint(), true)?; self.validate_harness_references()?; @@ -40,9 +53,9 @@ impl Document { let mut sandbox_names = std::collections::BTreeSet::new(); for sandbox in &self.spec.sandboxes { require( - self.spec.gateway.runtime().provider.is_kubernetes() + self.spec.gateway.compute_driver().is_kubernetes() || sandbox.image.metadata.is_none(), - "image.metadata is available only for Kubernetes and OpenShift; Docker and Podman use engine image inspection", + "image.metadata is available only for a spec.gateway.target.kubernetes gateway; Docker and Podman use engine image inspection", )?; if let Some(metadata) = &sandbox.image.metadata { schema::validate_definition("FileRef", metadata)?; @@ -88,7 +101,7 @@ impl Document { crate::services::validate_route( self, provider, - self.spec.gateway.runtime().provider, + self.spec.gateway.compute_driver(), &route.overrides.model, )?; } @@ -99,10 +112,13 @@ impl Document { impl super::ManagedGateway { pub fn validate_managed(&self) -> Result<(), ConfigError> { schema::validate_definition("Gateway", &Gateway::Managed(self.clone()))?; - if self.kubernetes.is_some() { - return validate_endpoint(&self.endpoint, true); + if let super::ManagedTarget::Kubernetes(cluster) = &self.target { + return validate_endpoint(&cluster.endpoint, true); } - let authority = self + let local = self + .local() + .expect("Docker and Podman targets run on a local engine"); + let authority = local .endpoint .strip_prefix("http://") .unwrap_or("") @@ -112,10 +128,10 @@ impl super::ManagedGateway { let bind = authority.parse::().ok(); require( bind.is_some_and(|a| a.port() >= 1024) - && crate::config::validate_engine_endpoint(&self.engine).is_ok(), - "managed gateway requires pinned image, a local engine socket, and unprivileged loopback HTTP port without credentials", + && crate::config::validate_engine_endpoint(local.engine).is_ok(), + "managed gateway requires a local engine socket and unprivileged loopback HTTP port without credentials", )?; - let net = self.network_cidr.parse::().ok(); + let net = local.network_cidr.parse::().ok(); require( net.is_some_and(|n| { n.addr().is_private() && n.prefix_len() == 24 && n.addr() == n.network() diff --git a/crates/nemoclaw-sdk/src/deployment/runtime/tests.rs b/crates/nemoclaw-sdk/src/deployment/runtime/tests.rs index d108a38c32b..d23ea3af94d 100644 --- a/crates/nemoclaw-sdk/src/deployment/runtime/tests.rs +++ b/crates/nemoclaw-sdk/src/deployment/runtime/tests.rs @@ -56,15 +56,13 @@ fn interrupted_kubernetes_platform_apply_cannot_move_to_another_namespace() { record.begin_runtime_apply(&document); assert!(record.validate_pending_intent(&document).is_ok()); let mut changed = document.clone(); - changed - .spec - .gateway - .as_managed_mut() - .unwrap() - .kubernetes - .as_mut() - .unwrap() - .namespace = "another-target".into(); + let Some(crate::config::ManagedGateway { + target: crate::config::ManagedTarget::Kubernetes(cluster), + }) = changed.spec.gateway.as_managed_mut() + else { + panic!("managed Kubernetes example"); + }; + cluster.namespace = "another-target".into(); assert!(record.validate_pending_intent(&changed).is_err()); } diff --git a/crates/nemoclaw-sdk/src/deployment/tests.rs b/crates/nemoclaw-sdk/src/deployment/tests.rs index e8b538d981a..3928925564b 100644 --- a/crates/nemoclaw-sdk/src/deployment/tests.rs +++ b/crates/nemoclaw-sdk/src/deployment/tests.rs @@ -11,11 +11,12 @@ pub(super) fn kubernetes_context() -> (Document, crate::compile::Generations) { .unwrap(); let mut value = serde_json::to_value(original).unwrap(); value["spec"]["gateway"] = json!({ - "management":"managed", "runtime":{"provider":"kubernetes"}, "endpoint":"https://127.0.0.1:17671", - "kubernetes": { + "management":"managed", + "target": {"kubernetes": { + "endpoint":"https://127.0.0.1:17671", "kubeconfig":{"env":"TEST_KUBECONFIG"}, "context":"test-cluster", "namespace":"test-agents", "authentication":{"profile":"development"} - } + }} }); value["spec"]["sandboxes"][0]["image"]["metadata"] = json!({"env":"TEST_IMAGE_METADATA"}); let document = Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap(); @@ -39,7 +40,7 @@ fn a_kubernetes_targets_listed_variables_reach_its_providers() { } let (document, _) = kubernetes_context(); let mut value = serde_json::to_value(&document).unwrap(); - value["spec"]["gateway"]["kubernetes"]["environment"] = json!(["AWS_PROFILE"]); + value["spec"]["gateway"]["target"]["kubernetes"]["environment"] = json!(["AWS_PROFILE"]); let document = Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap(); let temporary = tempfile::tempdir().unwrap(); let deployment = Deployment::new(temporary.path(), Path::new("unused-bundle")) @@ -49,7 +50,8 @@ fn a_kubernetes_targets_listed_variables_reach_its_providers() { .unwrap(); assert_eq!(environment["AWS_PROFILE"], "cluster-admin"); - value["spec"]["gateway"]["kubernetes"]["environment"] = json!(["AWS_PROFILE", "AWS_REGION"]); + value["spec"]["gateway"]["target"]["kubernetes"]["environment"] = + json!(["AWS_PROFILE", "AWS_REGION"]); let unset = Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap(); assert!( deployment @@ -926,8 +928,10 @@ async fn changing_gateway_management_at_the_same_endpoint_preserves_saved_state( Document::parse(include_str!("../../tests/fixtures/config/local.yaml").as_bytes()).unwrap(); let mut managed = external.clone(); managed.spec.gateway = Gateway::Managed(crate::config::ManagedGateway { - endpoint: external.spec.gateway.endpoint().into(), - ..Default::default() + target: crate::config::ManagedTarget::Docker(crate::config::ManagedDocker { + endpoint: external.spec.gateway.endpoint().into(), + ..Default::default() + }), }); managed.defaults(); managed.validate().unwrap(); diff --git a/crates/nemoclaw-sdk/src/discovery.rs b/crates/nemoclaw-sdk/src/discovery.rs index 7016947f870..83fe5dee93d 100644 --- a/crates/nemoclaw-sdk/src/discovery.rs +++ b/crates/nemoclaw-sdk/src/discovery.rs @@ -64,7 +64,7 @@ pub struct CredentialRequest { pub fn plan_queries(document: &Document) -> Result, ConfigError> { let mut queries = vec![DiscoveryQuery::Gateway(GatewayRequest { gateway: document.spec.gateway.clone(), - compute_drivers: vec![document.spec.gateway.runtime().provider], + compute_drivers: vec![document.spec.gateway.compute_driver()], })]; queries.extend( crate::inference_discovery::endpoint_requests(document) @@ -74,7 +74,7 @@ pub fn plan_queries(document: &Document) -> Result, ConfigEr ); let mut engines = crate::services::discovery_engines(document)?; if let Some(gateway) = document.spec.gateway.as_local_managed() { - engines.insert(gateway.engine.clone()); + engines.insert(gateway.engine.into()); } queries.extend( engines @@ -83,19 +83,14 @@ pub fn plan_queries(document: &Document) -> Result, ConfigEr ); // A cluster has no engine to read images from; their metadata bundles // answer instead. - let kubernetes = document.spec.gateway.runtime().provider.is_kubernetes(); - let engine = match &document.spec.gateway { - _ if kubernetes => "", - Gateway::Managed(gateway) => &gateway.engine, - Gateway::External(gateway) => &gateway.engine, - }; + let engine = document.spec.gateway.image_engine(); let platform = document .spec .gateway .as_local_managed() - .map(|_| DiscoveryRequest { - engine: engine.into(), - compute_driver: document.spec.gateway.runtime().provider, + .map(|gateway| DiscoveryRequest { + engine: gateway.engine.into(), + compute_driver: gateway.compute_driver, }); queries.extend(platform.clone().map(DiscoveryQuery::Engine)); let mut sandboxes: Vec<_> = document.spec.sandboxes.iter().collect(); diff --git a/crates/nemoclaw-sdk/src/discovery_graph.rs b/crates/nemoclaw-sdk/src/discovery_graph.rs index ac97ac95095..e5359b92634 100644 --- a/crates/nemoclaw-sdk/src/discovery_graph.rs +++ b/crates/nemoclaw-sdk/src/discovery_graph.rs @@ -162,10 +162,10 @@ pub(crate) fn populate(graph: &mut Value, document: &Document) -> Result<(), Con "error_message": rejection }, { "condition": "${self.runtime_json != \"\"}", - "error_message": if metadata_env.is_some() || document.spec.gateway.runtime().provider.is_kubernetes() { + "error_message": if metadata_env.is_some() || document.spec.gateway.compute_driver().is_kubernetes() { format!("sandbox/{}: image runtime metadata is unavailable. Set image.metadata.env to an absolute metadata bundle path and verify that it matches the immutable image digest. Resources retained.", sandbox.name) } else { - format!("sandbox/{}: image runtime metadata is unavailable. Set spec.gateway.engine to the sandbox image engine, load an image built with its runtime manifest, and use its immutable digest. Resources retained.", sandbox.name) + format!("sandbox/{}: image runtime metadata is unavailable. Set the engine of spec.gateway.target.docker or spec.gateway.target.podman to the sandbox image engine, load an image built with its runtime manifest, and use its immutable digest. Resources retained.", sandbox.name) } }] }); })?; diff --git a/crates/nemoclaw-sdk/src/docker_compute.rs b/crates/nemoclaw-sdk/src/docker_compute.rs index a0875d1ebbe..c30a7a53fec 100644 --- a/crates/nemoclaw-sdk/src/docker_compute.rs +++ b/crates/nemoclaw-sdk/src/docker_compute.rs @@ -663,14 +663,15 @@ mod tests { let mut document = Document::parse(include_bytes!("../tests/fixtures/config/local.yaml").as_slice()) .unwrap(); - document.spec.gateway = source.spec.gateway; - document - .spec - .gateway - .as_managed_mut() - .unwrap() - .image_pull_policy = Some(ImagePullPolicy::Always); - document.spec.gateway.runtime_mut().provider = ComputeDriver::Podman; + let local = source.spec.gateway.as_local_managed().unwrap(); + document.spec.gateway = crate::config::Gateway::Managed(crate::config::ManagedGateway { + target: crate::config::ManagedTarget::Podman(crate::config::ManagedPodman { + endpoint: local.endpoint.into(), + engine: local.engine.into(), + image_pull_policy: Some(ImagePullPolicy::Always), + network_cidr: local.network_cidr.into(), + }), + }); let generations = crate::state::Record::new(document.clone()) .unwrap() .generations; diff --git a/crates/nemoclaw-sdk/src/kubernetes/mod.rs b/crates/nemoclaw-sdk/src/kubernetes/mod.rs index 45ef0e87cf2..91fed16104c 100644 --- a/crates/nemoclaw-sdk/src/kubernetes/mod.rs +++ b/crates/nemoclaw-sdk/src/kubernetes/mod.rs @@ -16,7 +16,7 @@ pub mod operations; pub mod receipt; pub mod storage; -use crate::{Error, ObservationError, config::ManagedGateway}; +use crate::{Error, ObservationError, managed::GatewaySettings}; use kube::config::{KubeConfigOptions, Kubeconfig}; use serde::{Deserialize, Serialize}; use std::path::PathBuf; @@ -44,7 +44,7 @@ pub struct Spec { pub name: String, pub owner: String, pub generation: String, - pub settings: ManagedGateway, + pub settings: GatewaySettings, } impl Spec { @@ -164,10 +164,10 @@ impl Spec { name: get("name")?, owner: get("owner")?, generation: get("generation")?, - settings: ManagedGateway { - runtime: crate::config::Runtime { provider }, + settings: GatewaySettings { + runtime: crate::managed::GatewayRuntime { provider }, endpoint: get("endpoint")?, - kubernetes: Some(crate::config::ManagedKubernetes { + kubernetes: Some(crate::managed::KubernetesSettings { kubeconfig: crate::config::FileRef { env: get("kubeconfig_env")?, }, @@ -254,7 +254,7 @@ pub(crate) fn kubeconfig_path(value: &str) -> Result /// Connect to the target's context. The kubeconfig's exec credential plugins /// run as written, with this process's environment: the caller's in the SDK, -/// and the platform variables plus `gateway.kubernetes.environment` inside +/// and the platform variables plus `gateway.target.kubernetes.environment` inside /// OpenTofu's providers. pub async fn connect(target: &ClusterTarget) -> Result { let kubeconfig = @@ -286,9 +286,10 @@ pub async fn connection( .gateway .as_managed() .ok_or(ObservationError::Query)?; - let target = settings - .kubernetes - .as_ref() + let target = document + .spec + .gateway + .as_kubernetes() .ok_or(ObservationError::Query)?; let spec = Spec { layout: 1, @@ -299,7 +300,7 @@ pub async fn connection( .get(GATEWAY_KIND) .ok_or(ObservationError::Incomplete)? .clone(), - settings: settings.clone(), + settings: settings.runtime_settings(), }; spec.validate()?; let cluster = ClusterTarget { diff --git a/crates/nemoclaw-sdk/src/kubernetes/operations.rs b/crates/nemoclaw-sdk/src/kubernetes/operations.rs index c5a17fbf459..9edd25a7573 100644 --- a/crates/nemoclaw-sdk/src/kubernetes/operations.rs +++ b/crates/nemoclaw-sdk/src/kubernetes/operations.rs @@ -55,7 +55,7 @@ impl Operations { fn target<'a>( &self, spec: &'a Spec, - ) -> Result<&'a crate::config::ManagedKubernetes, ObservationError> { + ) -> Result<&'a crate::managed::KubernetesSettings, ObservationError> { spec.settings .kubernetes .as_ref() diff --git a/crates/nemoclaw-sdk/src/managed/mod.rs b/crates/nemoclaw-sdk/src/managed/mod.rs index 181edeb0add..43a91b418f2 100644 --- a/crates/nemoclaw-sdk/src/managed/mod.rs +++ b/crates/nemoclaw-sdk/src/managed/mod.rs @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +mod settings; mod spec; pub use nemoclaw_docker::Storage; +pub use settings::{GatewayRuntime, GatewaySettings, KubernetesSettings}; pub use spec::*; pub const GATEWAY_STORAGE_KIND: &str = "gateway_storage"; diff --git a/crates/nemoclaw-sdk/src/managed/settings.rs b/crates/nemoclaw-sdk/src/managed/settings.rs new file mode 100644 index 00000000000..cd6eb769ddc --- /dev/null +++ b/crates/nemoclaw-sdk/src/managed/settings.rs @@ -0,0 +1,268 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +//! Runtime settings compiled from a managed gateway's authored target. +//! +//! Service specifications serialize these settings into retained resource +//! values and the labels that bind containers, so their layout stays fixed +//! when the authored configuration changes shape. + +use crate::config::{ + ComputeDriver, ConfigError, DEFAULT_GATEWAY_IMAGE, FileRef, ImagePullPolicy, + KubernetesAuthentication, KubernetesDistribution, LocalGateway, ManagedDocker, ManagedGateway, + ManagedKubernetes, ManagedPodman, ManagedTarget, +}; +use serde::{Deserialize, Serialize}; + +/// A managed gateway's runtime settings, with the SDK-pinned gateway image. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct GatewaySettings { + pub runtime: GatewayRuntime, + pub endpoint: String, + #[serde(skip_serializing_if = "String::is_empty")] + pub engine: String, + #[serde(skip_serializing_if = "String::is_empty")] + pub image: String, + #[serde( + rename = "imagePullPolicy", + default, + skip_serializing_if = "Option::is_none" + )] + pub image_pull_policy: Option, + #[serde(rename = "networkCIDR", skip_serializing_if = "String::is_empty")] + pub network_cidr: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub kubernetes: Option, +} + +/// The compute driver a managed gateway runs every sandbox with. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct GatewayRuntime { + pub provider: ComputeDriver, +} + +/// The cluster a managed Kubernetes gateway is installed in. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct KubernetesSettings { + pub kubeconfig: FileRef, + pub context: String, + pub namespace: String, + pub authentication: KubernetesAuthentication, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub environment: Vec, +} + +impl ManagedGateway { + /// Runtime settings for this gateway's target, with the pinned gateway + /// image on a local engine. The acquisition policy is a mutable provider + /// attribute rather than container identity, so it is left out. + pub(crate) fn runtime_settings(&self) -> GatewaySettings { + let ManagedTarget::Kubernetes(cluster) = &self.target else { + return self + .local() + .expect("Docker and Podman targets run on a local engine") + .runtime_settings(); + }; + GatewaySettings { + runtime: GatewayRuntime { + provider: match cluster.distribution { + KubernetesDistribution::Kubernetes => ComputeDriver::Kubernetes, + KubernetesDistribution::OpenShift => ComputeDriver::OpenShift, + }, + }, + endpoint: cluster.endpoint.clone(), + kubernetes: Some(KubernetesSettings { + kubeconfig: cluster.kubeconfig.clone(), + context: cluster.context.clone(), + namespace: cluster.namespace.clone(), + authentication: cluster.authentication.clone(), + environment: cluster.environment.clone(), + }), + ..GatewaySettings::default() + } + } +} + +impl LocalGateway<'_> { + /// Runtime settings for this gateway, with the pinned gateway image and + /// without the mutable acquisition policy. + pub(crate) fn runtime_settings(&self) -> GatewaySettings { + GatewaySettings { + runtime: GatewayRuntime { + provider: self.compute_driver, + }, + endpoint: self.endpoint.into(), + engine: self.engine.into(), + image: DEFAULT_GATEWAY_IMAGE.into(), + image_pull_policy: None, + network_cidr: self.network_cidr.into(), + kubernetes: None, + } + } +} + +impl GatewaySettings { + /// The authored gateway these settings were compiled from. + /// + /// # Errors + /// Returns an error when the settings pair a cluster with a local engine + /// driver or carry settings their target does not take. + pub fn authored(&self) -> Result { + let provider = self.runtime.provider; + let target = match (&self.kubernetes, provider) { + (None, ComputeDriver::Docker) => ManagedTarget::Docker(ManagedDocker { + endpoint: self.endpoint.clone(), + engine: self.engine.clone(), + image_pull_policy: self.image_pull_policy, + network_cidr: self.network_cidr.clone(), + }), + (None, ComputeDriver::Podman) => ManagedTarget::Podman(ManagedPodman { + endpoint: self.endpoint.clone(), + engine: self.engine.clone(), + image_pull_policy: self.image_pull_policy, + network_cidr: self.network_cidr.clone(), + }), + (Some(cluster), ComputeDriver::Kubernetes | ComputeDriver::OpenShift) + if self.engine.is_empty() + && self.image.is_empty() + && self.image_pull_policy.is_none() + && self.network_cidr.is_empty() => + { + ManagedTarget::Kubernetes(ManagedKubernetes { + distribution: if provider == ComputeDriver::OpenShift { + KubernetesDistribution::OpenShift + } else { + KubernetesDistribution::Kubernetes + }, + endpoint: self.endpoint.clone(), + kubeconfig: cluster.kubeconfig.clone(), + context: cluster.context.clone(), + namespace: cluster.namespace.clone(), + authentication: cluster.authentication.clone(), + environment: cluster.environment.clone(), + }) + } + _ => { + return Err(ConfigError::new( + "managed gateway settings must pair a local engine with Docker or Podman, or a cluster with Kubernetes or OpenShift and no local engine settings", + )); + } + }; + Ok(ManagedGateway { target }) + } + + /// Validate the settings as their authored gateway, with the pinned image + /// on a local engine. The acquisition policy is excluded: the provider + /// supplies it from mutable resource attributes and the engine checks it. + /// + /// # Errors + /// Returns the authored gateway's validation error, or an error for an + /// image other than the SDK pin. + pub fn validate_managed(&self) -> Result<(), ConfigError> { + let identity = Self { + image_pull_policy: None, + ..self.clone() + }; + identity.authored()?.validate_managed()?; + if self.kubernetes.is_none() && self.image != DEFAULT_GATEWAY_IMAGE { + return Err(ConfigError::new( + "managed gateway requires the SDK-pinned gateway image", + )); + } + Ok(()) + } + + /// Resolve the first address after the configured network address. + /// + /// # Errors + /// Returns an error for a Kubernetes gateway, a malformed IPv4 CIDR, or an + /// address overflow. + pub fn bridge(&self) -> Result { + if self.kubernetes.is_some() { + return Err(ConfigError::new( + "Kubernetes gateways have no local engine bridge", + )); + } + crate::config::bridge_address(&self.network_cidr) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::Document; + + fn spark() -> Document { + Document::parse(include_bytes!("../../tests/fixtures/config/spark.yaml").as_slice()) + .unwrap() + } + + /// Service specifications and their labels serialize these settings, so + /// a local target compiles to the layout retained resources already bind. + #[test] + fn local_settings_keep_the_retained_layout_with_the_pinned_image() { + let settings = spark().spec.gateway.managed().unwrap().runtime_settings(); + assert_eq!( + serde_json::to_string(&settings).unwrap(), + format!( + r#"{{"runtime":{{"provider":"docker"}},"endpoint":"http://127.0.0.1:17681","engine":"unix:///var/run/docker.sock","image":"{DEFAULT_GATEWAY_IMAGE}","networkCIDR":"172.30.110.0/24"}}"# + ) + ); + settings.validate_managed().unwrap(); + let other = GatewaySettings { + image: "ghcr.io/nvidia/openshell/gateway@sha256:0000".into(), + ..settings.clone() + }; + assert!(other.validate_managed().is_err()); + // The provider applies the acquisition policy after compilation. + let pulled = GatewaySettings { + image_pull_policy: Some(ImagePullPolicy::Always), + ..settings + }; + pulled.validate_managed().unwrap(); + } + + #[test] + fn cluster_settings_name_the_distribution_driver_and_no_local_engine() { + let cluster = ManagedKubernetes { + distribution: KubernetesDistribution::OpenShift, + endpoint: "https://127.0.0.1:17671".into(), + kubeconfig: FileRef { + env: "CLUSTER_KUBECONFIG".into(), + }, + context: "explicit".into(), + namespace: "agents".into(), + authentication: serde_json::from_value(serde_json::json!({"profile": "development"})) + .unwrap(), + environment: Vec::new(), + }; + let gateway = ManagedGateway { + target: ManagedTarget::Kubernetes(cluster), + }; + let settings = gateway.runtime_settings(); + assert_eq!(settings.runtime.provider, ComputeDriver::OpenShift); + assert!(settings.image.is_empty() && settings.engine.is_empty()); + settings.validate_managed().unwrap(); + assert_eq!(settings.authored().unwrap(), gateway); + for changed in [ + GatewaySettings { + runtime: GatewayRuntime { + provider: ComputeDriver::Docker, + }, + ..settings.clone() + }, + GatewaySettings { + image: DEFAULT_GATEWAY_IMAGE.into(), + ..settings.clone() + }, + GatewaySettings { + network_cidr: "172.30.1.0/24".into(), + ..settings + }, + ] { + assert!(changed.validate_managed().is_err(), "{changed:?}"); + } + } +} diff --git a/crates/nemoclaw-sdk/src/managed/spec.rs b/crates/nemoclaw-sdk/src/managed/spec.rs index ea9ed5e0f2b..49bf788c82d 100644 --- a/crates/nemoclaw-sdk/src/managed/spec.rs +++ b/crates/nemoclaw-sdk/src/managed/spec.rs @@ -5,7 +5,8 @@ use crate::config::ComputeDriver; #[path = "spec_tests.rs"] mod tests; -use crate::{Error, config::ManagedGateway}; +use super::{GatewayRuntime, GatewaySettings}; +use crate::Error; use bollard_stubs::models::ContainerCreateBody; use serde::{Deserialize, Serialize}; use serde_json::json; @@ -31,7 +32,7 @@ pub struct Spec { pub name: String, pub owner: String, pub generation: String, - pub gateway: ManagedGateway, + pub gateway: GatewaySettings, #[serde(default, skip_serializing_if = "Option::is_none")] pub process: Option, } @@ -278,8 +279,8 @@ impl Spec { name: get("name")?, owner: get("owner")?, generation: get("generation")?, - gateway: ManagedGateway { - runtime: crate::config::Runtime { + gateway: GatewaySettings { + runtime: GatewayRuntime { provider: compute_driver, }, endpoint, diff --git a/crates/nemoclaw-sdk/src/services/installers/ollama/mod.rs b/crates/nemoclaw-sdk/src/services/installers/ollama/mod.rs index 24e7d4c2f50..8c46b5de2c6 100644 --- a/crates/nemoclaw-sdk/src/services/installers/ollama/mod.rs +++ b/crates/nemoclaw-sdk/src/services/installers/ollama/mod.rs @@ -88,7 +88,7 @@ impl OllamaProxy { ) -> Result<&'a str, crate::config::ConfigError> { self.engine .as_deref() - .map_or_else(|| Ok(document.spec.gateway.managed()?.engine.as_str()), Ok) + .map_or_else(|| Ok(document.spec.gateway.managed()?.engine), Ok) } pub(crate) fn validate_definition(&self) -> Result<(), crate::config::ConfigError> { diff --git a/crates/nemoclaw-sdk/src/services/placement.rs b/crates/nemoclaw-sdk/src/services/placement.rs index 8a702021b36..52d94054d52 100644 --- a/crates/nemoclaw-sdk/src/services/placement.rs +++ b/crates/nemoclaw-sdk/src/services/placement.rs @@ -82,8 +82,8 @@ impl ResolvedPlacement { let gateway = gateway.managed()?; let bind_address = gateway.bridge()?; Self { - engine: gateway.engine.clone(), - network_cidr: gateway.network_cidr.clone(), + engine: gateway.engine.into(), + network_cidr: gateway.network_cidr.into(), endpoint: format!("http://{bind_address}:{port}/v1"), bind_address, explicit: false, @@ -147,13 +147,15 @@ impl ServicePublication { #[cfg(test)] mod tests { use super::*; - use crate::config::{Gateway, ManagedGateway}; + use crate::config::{Gateway, ManagedDocker, ManagedGateway, ManagedTarget}; fn gateway() -> Gateway { Gateway::Managed(ManagedGateway { - engine: "unix:///var/run/docker.sock".into(), - network_cidr: "10.20.0.0/24".into(), - ..Default::default() + target: ManagedTarget::Docker(ManagedDocker { + engine: "unix:///var/run/docker.sock".into(), + network_cidr: "10.20.0.0/24".into(), + ..Default::default() + }), }) } diff --git a/crates/nemoclaw-sdk/src/services/registry.rs b/crates/nemoclaw-sdk/src/services/registry.rs index 4a103008d1b..aec550b34e4 100644 --- a/crates/nemoclaw-sdk/src/services/registry.rs +++ b/crates/nemoclaw-sdk/src/services/registry.rs @@ -197,10 +197,11 @@ impl ServiceDefinition { fn validate_installation(&self, document: &Document) -> Result<(), ConfigError> { let gateway = &document.spec.gateway; - let local_docker = gateway.as_managed().is_some_and(|gateway| { - gateway.engine.starts_with("unix:///") - && crate::config::validate_engine_endpoint(&gateway.engine).is_ok() - }) && gateway.runtime().provider == ComputeDriver::Docker; + let local_docker = gateway.as_local_managed().is_some_and(|gateway| { + gateway.compute_driver == ComputeDriver::Docker + && gateway.engine.starts_with("unix:///") + && crate::config::validate_engine_endpoint(gateway.engine).is_ok() + }); let (placement, package) = match self { Self::Ollama(service) => (service.published_placement()?, "Ollama"), Self::Vllm(service) => (service.published_placement()?, "vLLM"), @@ -365,8 +366,8 @@ pub(crate) fn discovery_engines(document: &Document) -> Result, document .spec .gateway - .as_managed() - .map(|gateway| gateway.engine.clone()) + .as_local_managed() + .map(|gateway| gateway.engine.to_owned()) }) .ok_or(ConfigError::new("service engine is not configured")) }) @@ -478,8 +479,8 @@ pub(crate) fn validate(document: &Document) -> Result<(), ConfigError> { let gateway = &document.spec.gateway; let mut publications = BTreeSet::new(); let mut networks = BTreeMap::new(); - if let Gateway::Managed(gateway) = gateway { - networks.insert(gateway.engine.clone(), gateway.network_cidr.clone()); + if let Some(gateway) = gateway.as_local_managed() { + networks.insert(gateway.engine.to_owned(), gateway.network_cidr.to_owned()); } for definition in document.spec.services.values() { let Some(allocation) = definition.allocation(gateway)? else { diff --git a/crates/nemoclaw-sdk/src/state/tests.rs b/crates/nemoclaw-sdk/src/state/tests.rs index 276aae5d23d..e1461a35f18 100644 --- a/crates/nemoclaw-sdk/src/state/tests.rs +++ b/crates/nemoclaw-sdk/src/state/tests.rs @@ -391,12 +391,12 @@ fn a_kubernetes_records_generations_reload_and_stay_stable() { ) .unwrap(); value["spec"]["gateway"] = serde_json::json!({ - "management": "managed", "runtime": {"provider": "kubernetes"}, - "endpoint": "https://127.0.0.1:17671", - "kubernetes": { + "management": "managed", + "target": {"kubernetes": { + "endpoint": "https://127.0.0.1:17671", "kubeconfig": {"env": "TEST_KUBECONFIG"}, "context": "test-cluster", "namespace": "test-agents", "authentication": {"profile": "development"} - } + }} }); value["spec"]["sandboxes"][0]["image"]["metadata"] = serde_json::json!({"env": "TEST_IMAGE_METADATA"}); diff --git a/crates/nemoclaw-sdk/tests/compile.rs b/crates/nemoclaw-sdk/tests/compile.rs index d76a1d538e4..82d3df74e2b 100644 --- a/crates/nemoclaw-sdk/tests/compile.rs +++ b/crates/nemoclaw-sdk/tests/compile.rs @@ -46,7 +46,7 @@ fn gateway_capabilities_gate_deployment_and_follow_bootstrap_reconciliation() { fn image_pull_policy_reaches_the_engine_without_changing_runtime_identity() { use nemoclaw_sdk::{ compile::{compile_runtime, runtime_targets}, - config::ImagePullPolicy, + config::{ImagePullPolicy, ManagedGateway, ManagedTarget}, }; let generations = [ ("workspace", "workspace-generation"), @@ -62,12 +62,13 @@ fn image_pull_policy_reaches_the_engine_without_changing_runtime_identity() { let mut document = Document::parse(include_str!("fixtures/config/spark.yaml").as_bytes()).unwrap(); let before = compile_runtime(&document, &generations, "0.1.0").unwrap(); - document - .spec - .gateway - .as_managed_mut() - .unwrap() - .image_pull_policy = Some(ImagePullPolicy::IfNotPresent); + let Some(ManagedGateway { + target: ManagedTarget::Docker(docker), + }) = document.spec.gateway.as_managed_mut() + else { + panic!("expected a managed Docker gateway") + }; + docker.image_pull_policy = Some(ImagePullPolicy::IfNotPresent); let nemoclaw_sdk::services::ServiceDefinition::Vllm(service) = document.spec.services.values_mut().next().unwrap() else { @@ -259,10 +260,7 @@ fn managed_plans_query_selected_engine_and_image_without_probe_resources() { nemoclaw_sdk::compile::compile_runtime(&document, &generations, "0.1.0").unwrap(), ] { let engine = &graph["data"]["nemoclaw_engine_capabilities"]["current"]; - assert_eq!( - engine["engine"], - document.spec.gateway.as_managed().unwrap().engine - ); + assert_eq!(engine["engine"], document.spec.gateway.image_engine()); assert_eq!(engine["compute_driver"], "docker"); assert!( engine.get("depends_on").is_none(), diff --git a/crates/nemoclaw-sdk/tests/config.rs b/crates/nemoclaw-sdk/tests/config.rs index 676f7237501..99f411bcfd0 100644 --- a/crates/nemoclaw-sdk/tests/config.rs +++ b/crates/nemoclaw-sdk/tests/config.rs @@ -2,7 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 use nemoclaw_sdk::config::{HarnessKind, InferenceProviderKind}; -use nemoclaw_sdk::config::{Document, ServiceDefinition, validate_endpoint}; +use nemoclaw_sdk::config::{ + Document, ManagedDocker, ManagedTarget, ServiceDefinition, validate_endpoint, +}; use serde_json::Value; #[test] @@ -50,7 +52,7 @@ fn unsafe_yaml_and_secret_values_are_rejected_without_echoing_input() { "model: qwen3.5:0.8b", "model: '${file(\"secret-do-not-print\")}'", ), - ("provider: docker", "provider: unsupported"), + ("docker: {}", "unsupported: {}"), ("kind: nvidia.fabric.openclaw", "kind: ' '"), ]; for (from, to) in changes { @@ -90,28 +92,24 @@ fn managed_defaults_and_safety_bounds_match_the_qualified_recipe() { Document::parse(include_str!("fixtures/config/spark.yaml").as_bytes()).unwrap(); original.spec.sandboxes[0].image.ref_ = nemoclaw_sdk::config::DEFAULT_AGENT_IMAGE.into(); let mut defaulted = original.clone(); - defaulted.spec.gateway.endpoint_mut().clear(); - defaulted + let network_cidr = original .spec .gateway - .as_managed_mut() + .as_local_managed() .unwrap() - .engine - .clear(); - defaulted - .spec - .gateway - .as_managed_mut() - .unwrap() - .image - .clear(); + .network_cidr + .to_owned(); + defaulted.spec.gateway.as_managed_mut().unwrap().target = + ManagedTarget::Docker(ManagedDocker { + network_cidr, + ..Default::default() + }); let ServiceDefinition::Vllm(service) = defaulted.spec.services.get_mut("qwen").unwrap() else { panic!("expected vLLM service"); }; service.serving = Default::default(); service.memory = Default::default(); defaulted.spec.sandboxes[0].image.ref_.clear(); - *defaulted.spec.gateway.runtime_mut() = Default::default(); defaulted.spec.sandboxes[0].network.policy = Default::default(); defaulted.defaults(); assert_eq!(defaulted, original); @@ -388,11 +386,8 @@ fn harness_selection_does_not_determine_service_ownership() { #[test] fn external_gateways_reject_installation_fields_even_when_empty() { let base = include_str!("fixtures/config/local.yaml"); - for field in ["image", "networkCIDR"] { - let input = base.replace( - "management: external", - &format!("management: external\n {field}: \"\""), - ); + for field in ["image", "networkCidr"] { + let input = base.replace("docker: {}", &format!("docker:\n {field}: \"\"")); assert!( Document::parse(input.as_bytes()).is_err(), "external gateway accepted {field}" diff --git a/crates/nemoclaw-sdk/tests/config_input.rs b/crates/nemoclaw-sdk/tests/config_input.rs index d3a0b9e62ab..58cbbfc1531 100644 --- a/crates/nemoclaw-sdk/tests/config_input.rs +++ b/crates/nemoclaw-sdk/tests/config_input.rs @@ -63,8 +63,8 @@ fn application_references_do_not_enable_yaml_anchors_aliases_or_merges() { #[test] fn omitted_empty_and_zero_values_produce_the_same_defaults() { let mut omitted = input("spark/spark-inline.yaml"); - for key in ["endpoint", "engine", "image", "networkCIDR"] { - omitted["spec"]["gateway"] + for key in ["endpoint", "engine", "networkCidr"] { + omitted["spec"]["gateway"]["target"]["docker"] .as_object_mut() .unwrap() .remove(key); @@ -83,11 +83,10 @@ fn omitted_empty_and_zero_values_produce_the_same_defaults() { } let expected = parse(&omitted).unwrap(); let mut explicit = omitted.clone(); - for key in ["endpoint", "engine", "image", "networkCIDR"] { - explicit["spec"]["gateway"][key] = json!(""); + for key in ["endpoint", "engine", "networkCidr"] { + explicit["spec"]["gateway"]["target"]["docker"][key] = json!(""); } explicit["spec"]["sandboxes"][0]["image"] = json!({"ref": ""}); - explicit["spec"]["gateway"]["runtime"] = json!({"provider": "docker"}); explicit["spec"]["sandboxes"][0]["network"] = json!({"tier": ""}); explicit["spec"]["services"]["qwen"]["serving"] = json!({ "port": 0, "contextTokens": 0, "maxSequences": 0, "batchTokens": 0, @@ -102,7 +101,7 @@ fn omitted_empty_and_zero_values_produce_the_same_defaults() { assert_eq!(parse(&explicit).unwrap(), expected); assert_eq!(parse(&explicit).unwrap().digest(), expected.digest()); for path in [ - "/spec/gateway/endpoint", + "/spec/gateway/target/docker/endpoint", "/spec/sandboxes/0/image", "/spec/services/qwen/serving/port", ] { @@ -112,6 +111,33 @@ fn omitted_empty_and_zero_values_produce_the_same_defaults() { } } +#[test] +fn an_omitted_empty_or_unset_local_target_produces_the_same_defaults() { + let mut omitted = input("local.yaml"); + omitted["spec"]["gateway"] = json!({"management": "managed"}); + let expected = parse(&omitted).unwrap(); + for target in [ + json!({"docker": {}}), + json!({"docker": {"endpoint": "", "engine": "", "networkCidr": ""}}), + ] { + let mut explicit = omitted.clone(); + explicit["spec"]["gateway"]["target"] = target; + let document = parse(&explicit).unwrap(); + assert_eq!(document, expected); + assert_eq!(document.digest(), expected.digest()); + } + for path in [ + "/spec/gateway/target", + "/spec/gateway/target/docker", + "/spec/gateway/target/docker/endpoint", + ] { + let mut invalid = omitted.clone(); + invalid["spec"]["gateway"]["target"] = json!({"docker": {"endpoint": ""}}); + *invalid.pointer_mut(path).unwrap() = Value::Null; + assert!(parse(&invalid).is_err(), "{path}"); + } +} + #[test] fn required_fields_and_mutually_exclusive_provider_forms_are_rejected() { let baseline = input("local.yaml"); diff --git a/crates/nemoclaw-sdk/tests/config_kinds.rs b/crates/nemoclaw-sdk/tests/config_kinds.rs index 24c585b4b7a..2b4129549bb 100644 --- a/crates/nemoclaw-sdk/tests/config_kinds.rs +++ b/crates/nemoclaw-sdk/tests/config_kinds.rs @@ -1,12 +1,16 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use nemoclaw_sdk::config::{Harness, InferenceProvider, Runtime}; +use nemoclaw_sdk::config::{ + ExternalTarget, Harness, InferenceProvider, KubernetesDistribution, ManagedTarget, +}; use serde_json::json; #[test] fn closed_selectors_reject_unknown_values_and_harnesses_reject_malformed_identifiers() { assert!(serde_json::from_value::(json!({"kind":" \t"})).is_err()); - assert!(serde_json::from_value::(json!({"provider":"unknown"})).is_err()); + assert!(serde_json::from_value::(json!({"unknown": {}})).is_err()); + assert!(serde_json::from_value::(json!({"unknown": {}})).is_err()); + assert!(serde_json::from_value::(json!("unknown")).is_err()); assert!( serde_json::from_value::(json!({"name":"model", "provider":"unknown"})) .is_err() @@ -63,49 +67,52 @@ fn selector_names_round_trip_without_changing_wire_values() { } #[test] -fn omitted_runtime_selects_docker_without_changing_intent_digest() { +fn an_omitted_target_selects_docker_without_changing_intent_digest() { use nemoclaw_sdk::config::{ComputeDriver, Document}; let document = Document::parse(include_bytes!("fixtures/config/local.yaml").as_slice()).unwrap(); - for runtime in [json!({}), json!({"provider":"docker"})] { + for target in [None, Some(json!({"docker": {}}))] { let mut input = serde_json::to_value(&document).unwrap(); - input["spec"]["gateway"]["runtime"] = runtime; + let gateway = input["spec"]["gateway"].as_object_mut().unwrap(); + gateway.remove("target"); + if let Some(target) = target { + gateway.insert("target".into(), target); + } let parsed = Document::parse(input.to_string().as_bytes()).unwrap(); - assert_eq!( - parsed.spec.gateway.runtime().provider, - ComputeDriver::Docker - ); + assert_eq!(parsed.spec.gateway.compute_driver(), ComputeDriver::Docker); assert_eq!(parsed.digest(), document.digest()); assert_eq!(parsed.yaml().unwrap(), document.yaml().unwrap()); } } #[test] -fn the_runtime_is_chosen_once_on_the_gateway() { +fn the_target_is_chosen_once_on_the_gateway() { use nemoclaw_sdk::config::{ComputeDriver, Document, schema::input_schema}; let validator = jsonschema::validator_for(&input_schema()).unwrap(); let base: serde_json::Value = serde_saphyr::from_str(include_str!("fixtures/config/local.yaml")).unwrap(); - // Both gateway kinds carry the runtime. - for management in ["managed", "external"] { + // Both gateway kinds name the compute driver by their target key. + for gateway in [ + json!({ + "management": "managed", + "target": {"podman": {"engine": "unix:///run/user/1000/podman/podman.sock"}} + }), + json!({ + "management": "external", + "endpoint": "https://gateway.example:8080", + "target": {"podman": {}} + }), + ] { let mut input = base.clone(); - input["spec"]["gateway"]["management"] = json!(management); - if management == "external" { - input["spec"]["gateway"] = - json!({"management": "external", "endpoint": "https://gateway.example:8080"}); - } else { - input["spec"]["gateway"]["engine"] = json!("unix:///run/user/1000/podman/podman.sock"); - } - input["spec"]["gateway"]["runtime"] = json!({"provider": "podman"}); - assert!(validator.is_valid(&input), "{management}"); + input["spec"]["gateway"] = gateway; + assert!(validator.is_valid(&input), "{input}"); let document = Document::parse(input.to_string().as_bytes()).unwrap(); assert_eq!( - document.spec.gateway.runtime().provider, - ComputeDriver::Podman, - "{management}" + document.spec.gateway.compute_driver(), + ComputeDriver::Podman ); } - // A sandbox no longer selects its own runtime. + // A sandbox does not select its own runtime. let mut input = base; input["spec"]["sandboxes"][0]["runtime"] = json!({"provider": "docker"}); assert!(!validator.is_valid(&input)); @@ -113,18 +120,47 @@ fn the_runtime_is_chosen_once_on_the_gateway() { } #[test] -fn empty_runtime_driver_is_rejected_without_defaulting() { - use nemoclaw_sdk::config::{Document, schema::input_schema}; - assert!(serde_json::from_value::(json!({"provider":""})).is_err()); - let mut input: serde_json::Value = +fn sandbox_images_are_inspected_on_the_engine_the_target_names() { + use nemoclaw_sdk::config::{Document, GATEWAY_ENGINE}; + let base: serde_json::Value = serde_saphyr::from_str(include_str!("fixtures/config/local.yaml")).unwrap(); - input["spec"]["gateway"]["runtime"] = json!({"provider":""}); - assert!( - !jsonschema::validator_for(&input_schema()) - .unwrap() - .is_valid(&input) - ); - assert!(Document::parse(input.to_string().as_bytes()).is_err()); + let podman = "unix:///run/user/1000/podman/podman.sock"; + for (gateway, engine) in [ + (json!({"management": "managed"}), GATEWAY_ENGINE), + ( + json!({"management": "managed", "target": {"podman": {"engine": podman}}}), + podman, + ), + ( + json!({"management": "external", "endpoint": "http://127.0.0.1:17671", + "target": {"podman": {"engine": podman}}}), + podman, + ), + ( + json!({"management": "external", "endpoint": "http://127.0.0.1:17671"}), + "", + ), + ] { + let mut input = base.clone(); + input["spec"]["gateway"] = gateway; + let document = Document::parse(input.to_string().as_bytes()).unwrap(); + assert_eq!(document.spec.gateway.image_engine(), engine, "{input}"); + } +} + +#[test] +fn an_empty_target_is_rejected_without_defaulting() { + use nemoclaw_sdk::config::{Document, schema::input_schema}; + assert!(serde_json::from_value::(json!({})).is_err()); + assert!(serde_json::from_value::(json!("")).is_err()); + let validator = jsonschema::validator_for(&input_schema()).unwrap(); + for target in [json!({}), json!(""), json!(null)] { + let mut input: serde_json::Value = + serde_saphyr::from_str(include_str!("fixtures/config/local.yaml")).unwrap(); + input["spec"]["gateway"]["target"] = target; + assert!(!validator.is_valid(&input), "{input}"); + assert!(Document::parse(input.to_string().as_bytes()).is_err()); + } } #[test] diff --git a/crates/nemoclaw-sdk/tests/config_kubernetes.rs b/crates/nemoclaw-sdk/tests/config_kubernetes.rs index 4f0781a2598..67db19168d4 100644 --- a/crates/nemoclaw-sdk/tests/config_kubernetes.rs +++ b/crates/nemoclaw-sdk/tests/config_kubernetes.rs @@ -1,13 +1,13 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use nemoclaw_sdk::config::{Document, Runtime, schema}; +use nemoclaw_sdk::config::{ComputeDriver, Document, schema}; use serde_json::{Value, json}; fn external_document() -> Value { let document = Document::parse(include_bytes!("fixtures/config/local.yaml").as_slice()).unwrap(); let mut input = serde_json::to_value(document).unwrap(); - input["spec"]["gateway"]["runtime"] = json!({"provider": "kubernetes"}); + input["spec"]["gateway"]["target"] = json!({"kubernetes": {}}); input["spec"]["sandboxes"][0]["image"]["metadata"] = json!({"env":"TEST_IMAGE_METADATA"}); input } @@ -16,14 +16,14 @@ fn managed_document() -> Value { let mut input = external_document(); input["spec"]["gateway"] = json!({ "management": "managed", - "runtime": {"provider": "kubernetes"}, - "endpoint": "https://127.0.0.1:17671", - "kubernetes": { + "target": {"kubernetes": { + "distribution": "kubernetes", + "endpoint": "https://127.0.0.1:17671", "kubeconfig": {"env": "CLUSTER_KUBECONFIG"}, "context": "explicit-context", "namespace": "owned-gateway", "authentication": {"profile": "development"} - } + }} }); input } @@ -35,6 +35,10 @@ fn managed_kubernetes_preserves_explicit_target_and_has_no_local_engine_defaults assert!(jsonschema::is_valid(&schema::input_schema(), &input)); let document = Document::parse(input.to_string().as_bytes()).unwrap(); assert!(document.has_runtime()); + assert_eq!( + document.spec.gateway.compute_driver(), + ComputeDriver::Kubernetes + ); assert!(document.spec.gateway.as_managed().is_some()); assert!(document.spec.gateway.as_local_managed().is_none()); assert_eq!( @@ -62,27 +66,47 @@ fn managed_kubernetes_preserves_explicit_target_and_has_no_local_engine_defaults } } -/// Editors and onboarding read a field's default from its own schema, so a -/// managed local gateway's defaults stay there even though a Kubernetes -/// target excludes those fields. +/// Editors and onboarding read a field's default from its own schema, so each +/// target states only the defaults that apply to it. #[test] -fn a_managed_gateway_schema_still_states_its_local_defaults() { +fn each_target_schema_states_only_its_own_defaults() { let schema = schema::input_schema(); - let managed = schema["$defs"]["Gateway"]["oneOf"] + let definitions = &schema["$defs"]; + let docker = &definitions["ManagedDocker"]["properties"]; + assert_eq!(docker["engine"]["default"], "unix:///var/run/docker.sock"); + assert_eq!(docker["endpoint"]["default"], "http://127.0.0.1:17681"); + let podman = &definitions["ManagedPodman"]["properties"]; + assert_eq!(podman["endpoint"]["default"], "http://127.0.0.1:17681"); + assert!(podman["engine"].get("default").is_none()); + let cluster = &definitions["ManagedKubernetes"]["properties"]; + assert!(cluster["endpoint"].get("default").is_none()); + assert_eq!(cluster["distribution"]["default"], "kubernetes"); + for target in [docker, podman, cluster] { + assert!(target.get("image").is_none()); + } + for policy in [&docker["imagePullPolicy"], &podman["imagePullPolicy"]] { + assert_eq!(policy["default"], "IfNotPresent"); + } + // Editors offer a Docker target only the two policies it accepts, each + // with its description. + assert!(docker["imagePullPolicy"].get("$ref").is_none()); + let choices = docker["imagePullPolicy"]["oneOf"] .as_array() .unwrap() .iter() - .find(|variant| variant["properties"]["management"]["const"] == "managed") - .unwrap(); - assert_eq!( - managed["properties"]["engine"]["default"], - "unix:///var/run/docker.sock" - ); + .map(|choice| (choice["const"].clone(), choice["description"].is_string())) + .collect::>(); assert_eq!( - managed["properties"]["endpoint"]["default"], - "http://127.0.0.1:17681" + choices, + [(json!("IfNotPresent"), true), (json!("Never"), true)] ); - assert!(managed["properties"]["image"]["default"].is_string()); + // An omitted target selects Docker, managed or external. + for gateway in definitions["Gateway"]["oneOf"].as_array().unwrap() { + assert_eq!( + gateway["properties"]["target"]["default"], + json!({"docker": {}}) + ); + } } /// A kubeconfig's exec plugin, such as a cloud CLI, may need the caller's @@ -91,7 +115,8 @@ fn a_managed_gateway_schema_still_states_its_local_defaults() { #[test] fn a_managed_target_names_the_variables_its_kubeconfig_needs() { let mut input = managed_document(); - input["spec"]["gateway"]["kubernetes"]["environment"] = json!(["AWS_PROFILE", "AWS_REGION"]); + input["spec"]["gateway"]["target"]["kubernetes"]["environment"] = + json!(["AWS_PROFILE", "AWS_REGION"]); assert!(jsonschema::is_valid(&schema::input_schema(), &input)); let document = Document::parse(input.to_string().as_bytes()).unwrap(); assert_eq!( @@ -124,11 +149,11 @@ fn listed_variables_cannot_shadow_process_or_runtime_controls() { "AWS_PROFILE AWS_REGION", ] { let mut input = managed_document(); - input["spec"]["gateway"]["kubernetes"]["environment"] = json!([name]); + input["spec"]["gateway"]["target"]["kubernetes"]["environment"] = json!([name]); assert!(!validator.is_valid(&input), "{name}"); } let mut repeated = managed_document(); - repeated["spec"]["gateway"]["kubernetes"]["environment"] = + repeated["spec"]["gateway"]["target"]["kubernetes"]["environment"] = json!(["AWS_PROFILE", "AWS_PROFILE"]); assert!(!validator.is_valid(&repeated)); } @@ -151,7 +176,7 @@ fn agent_sandbox_is_a_platform_prerequisite_not_a_setting() { // Agent Sandbox must already be installed; the deployment never // installs it, so there is nothing to choose. let mut input = managed_document(); - input["spec"]["gateway"]["kubernetes"]["prerequisites"] = + input["spec"]["gateway"]["target"]["kubernetes"]["prerequisites"] = json!({"agentSandbox": {"management": "existing"}}); assert!(!jsonschema::is_valid(&schema::input_schema(), &input)); assert!(Document::parse(input.to_string().as_bytes()).is_err()); @@ -161,13 +186,13 @@ fn agent_sandbox_is_a_platform_prerequisite_not_a_setting() { fn managed_kubernetes_requires_explicit_target_and_authentication_choices() { let validator = jsonschema::validator_for(&schema::input_schema()).unwrap(); for (parent, field) in [ - ("/spec/gateway", "endpoint"), - ("/spec/gateway/kubernetes", "kubeconfig"), - ("/spec/gateway/kubernetes/kubeconfig", "env"), - ("/spec/gateway/kubernetes", "context"), - ("/spec/gateway/kubernetes", "namespace"), - ("/spec/gateway/kubernetes", "authentication"), - ("/spec/gateway/kubernetes/authentication", "profile"), + ("/spec/gateway/target/kubernetes", "endpoint"), + ("/spec/gateway/target/kubernetes", "kubeconfig"), + ("/spec/gateway/target/kubernetes/kubeconfig", "env"), + ("/spec/gateway/target/kubernetes", "context"), + ("/spec/gateway/target/kubernetes", "namespace"), + ("/spec/gateway/target/kubernetes", "authentication"), + ("/spec/gateway/target/kubernetes/authentication", "profile"), ] { let mut input = managed_document(); input @@ -188,46 +213,70 @@ fn managed_kubernetes_requires_explicit_target_and_authentication_choices() { fn managed_kubernetes_rejects_other_transports_targets_and_implicit_authentication() { let validator = jsonschema::validator_for(&schema::input_schema()).unwrap(); for (path, value) in [ - ("/spec/gateway/endpoint", json!("")), - ("/spec/gateway/endpoint", json!("http://127.0.0.1:17671")), - ("/spec/gateway/endpoint", json!("https://localhost:17671")), - ("/spec/gateway/endpoint", json!("https://127.0.0.2:17671")), + ("/spec/gateway/target/kubernetes/endpoint", json!("")), + ( + "/spec/gateway/target/kubernetes/endpoint", + json!("http://127.0.0.1:17671"), + ), ( - "/spec/gateway/endpoint", + "/spec/gateway/target/kubernetes/endpoint", + json!("https://localhost:17671"), + ), + ( + "/spec/gateway/target/kubernetes/endpoint", + json!("https://127.0.0.2:17671"), + ), + ( + "/spec/gateway/target/kubernetes/endpoint", json!("https://gateway.example:17671"), ), - ("/spec/gateway/endpoint", json!("https://127.0.0.1")), - ("/spec/gateway/endpoint", json!("https://127.0.0.1:0")), - ("/spec/gateway/endpoint", json!("https://127.0.0.1:65536")), - ("/spec/gateway/endpoint", json!("https://127.0.0.1:17671/")), ( - "/spec/gateway/endpoint", + "/spec/gateway/target/kubernetes/endpoint", + json!("https://127.0.0.1"), + ), + ( + "/spec/gateway/target/kubernetes/endpoint", + json!("https://127.0.0.1:0"), + ), + ( + "/spec/gateway/target/kubernetes/endpoint", + json!("https://127.0.0.1:65536"), + ), + ( + "/spec/gateway/target/kubernetes/endpoint", + json!("https://127.0.0.1:17671/"), + ), + ( + "/spec/gateway/target/kubernetes/endpoint", json!("https://127.0.0.1:17671?token=value"), ), ( - "/spec/gateway/endpoint", + "/spec/gateway/target/kubernetes/endpoint", json!("https://user:password@127.0.0.1:17671"), ), - ("/spec/gateway/kubernetes/context", json!("")), - ("/spec/gateway/kubernetes/namespace", json!("")), + ("/spec/gateway/target/kubernetes/context", json!("")), + ("/spec/gateway/target/kubernetes/namespace", json!("")), ( - "/spec/gateway/kubernetes/namespace", + "/spec/gateway/target/kubernetes/namespace", json!("Invalid_Namespace"), ), - ("/spec/gateway/kubernetes/kubeconfig/env", json!("")), + ("/spec/gateway/target/kubernetes/kubeconfig/env", json!("")), ( - "/spec/gateway/kubernetes/kubeconfig/env", + "/spec/gateway/target/kubernetes/kubeconfig/env", json!("/private/kubeconfig"), ), ( - "/spec/gateway/kubernetes/authentication/profile", + "/spec/gateway/target/kubernetes/authentication/profile", json!("none"), ), ( - "/spec/gateway/kubernetes/authentication/profile", + "/spec/gateway/target/kubernetes/authentication/profile", json!("production"), ), - ("/spec/gateway/runtime/provider", json!("docker")), + ( + "/spec/gateway/target/kubernetes/distribution", + json!("docker"), + ), ] { let mut input = managed_document(); *input.pointer_mut(path).unwrap() = value; @@ -241,11 +290,6 @@ fn managed_kubernetes_rejects_other_transports_targets_and_implicit_authenticati } } for (field, value) in [ - ("engine", json!("unix:///var/run/docker.sock")), - ("engine", json!("")), - ("networkCIDR", json!("172.30.1.0/24")), - ("image", json!(nemoclaw_sdk::config::DEFAULT_GATEWAY_IMAGE)), - ("imagePullPolicy", json!("Never")), ("credential", json!({"env":"GATEWAY_TOKEN"})), ( "tls", @@ -253,15 +297,10 @@ fn managed_kubernetes_rejects_other_transports_targets_and_implicit_authenticati ), ] { let mut input = managed_document(); - let empty_default = field == "engine" && value == json!(""); input["spec"]["gateway"][field] = value; assert!(!validator.is_valid(&input), "accepted {field}"); assert!(Document::parse(input.to_string().as_bytes()).is_err()); - if let Ok(document) = serde_json::from_value::(input) - && !empty_default - { - assert!(document.validate().is_err(), "accepted direct Rust {field}"); - } + assert!(serde_json::from_value::(input).is_err()); } } @@ -269,7 +308,8 @@ fn managed_kubernetes_rejects_other_transports_targets_and_implicit_authenticati fn managed_kubernetes_accepts_explicit_port_boundaries() { for port in [1, 443, 65535] { let mut input = managed_document(); - input["spec"]["gateway"]["endpoint"] = json!(format!("https://127.0.0.1:{port}")); + input["spec"]["gateway"]["target"]["kubernetes"]["endpoint"] = + json!(format!("https://127.0.0.1:{port}")); Document::parse(input.to_string().as_bytes()).unwrap(); } } @@ -291,7 +331,7 @@ fn authored_credentials_cannot_shadow_managed_kubernetes_runtime_controls() { "NEMOCLAW_MANAGED_K8S_CA", ] { for path in [ - "/spec/gateway/kubernetes/kubeconfig", + "/spec/gateway/target/kubernetes/kubeconfig", "/spec/inferenceProviders/0/credential", ] { let mut input = managed_document(); @@ -356,7 +396,7 @@ fn managed_kubeconfig_reference_cannot_override_process_controls() { "KUBERNETES_SERVICE_PORT_HTTPS", ] { let mut input = managed_document(); - input["spec"]["gateway"]["kubernetes"]["kubeconfig"]["env"] = json!(name); + input["spec"]["gateway"]["target"]["kubernetes"]["kubeconfig"]["env"] = json!(name); assert!( !validator.is_valid(&input), "accepted kubeconfig reference {name}" @@ -380,7 +420,7 @@ fn managed_kubeconfig_reference_cannot_override_process_controls() { "KUBECONFIG_PATH", ] { let mut input = managed_document(); - input["spec"]["gateway"]["kubernetes"]["kubeconfig"]["env"] = json!(name); + input["spec"]["gateway"]["target"]["kubernetes"]["kubeconfig"]["env"] = json!(name); Document::parse(input.to_string().as_bytes()).unwrap(); } } @@ -394,7 +434,7 @@ fn managed_kubeconfig_controls_do_not_restrict_other_credential_references() { "GOOGLE_APPLICATION_CREDENTIALS", ] { let mut input = external_document(); - input["spec"]["gateway"]["runtime"]["provider"] = json!("docker"); + input["spec"]["gateway"]["target"] = json!({"docker": {}}); input["spec"]["sandboxes"][0]["image"] .as_object_mut() .unwrap() @@ -413,9 +453,17 @@ fn a_kubernetes_target_cannot_enter_a_local_engine_spec() { .unwrap(); for fixture in fixtures { let mut raw: Value = serde_json::from_str(fixture["spec"].as_str().unwrap()).unwrap(); - let mut gateway = managed_document()["spec"]["gateway"].clone(); - gateway.as_object_mut().unwrap().remove("management"); - raw["gateway"] = gateway; + // Runtime specifications keep the settings layout that retained resources bind. + raw["gateway"] = json!({ + "runtime": {"provider": "kubernetes"}, + "endpoint": "https://127.0.0.1:17671", + "kubernetes": { + "kubeconfig": {"env": "CLUSTER_KUBECONFIG"}, + "context": "explicit-context", + "namespace": "owned-gateway", + "authentication": {"profile": "development"} + } + }); let spec: nemoclaw_sdk::managed::Spec = serde_json::from_value(raw).unwrap(); // A forged Docker driver must not route an otherwise valid Kubernetes target to an engine. assert!(spec.gateway.validate_managed().is_ok()); @@ -430,7 +478,7 @@ fn kubernetes_selects_the_gateway_driver_and_preserves_it_on_export() { let input = external_document(); let document = Document::parse(input.to_string().as_bytes()).unwrap(); assert_eq!( - document.spec.gateway.runtime().provider.as_str(), + document.spec.gateway.compute_driver().as_str(), "kubernetes" ); assert!(jsonschema::is_valid(&schema::input_schema(), &input)); @@ -438,8 +486,8 @@ fn kubernetes_selects_the_gateway_driver_and_preserves_it_on_export() { let imported = Document::parse(exported.as_bytes()).unwrap(); assert_eq!(imported.digest(), document.digest()); assert_eq!( - imported.spec.gateway.runtime().provider.to_string(), - "kubernetes" + imported.spec.gateway.compute_driver(), + ComputeDriver::Kubernetes ); } @@ -473,17 +521,18 @@ fn directly_constructed_kubernetes_sandboxes_never_default_their_image() { } #[test] -fn kubernetes_rejects_local_managed_gateways_without_an_explicit_target() { +fn a_managed_gateway_without_a_cluster_target_rejects_image_metadata() { let mut input = external_document(); input["spec"]["gateway"] = json!({"management": "managed"}); - assert!(Document::parse(input.to_string().as_bytes()).is_err()); assert!(!jsonschema::is_valid(&schema::input_schema(), &input)); - - let mut document = - Document::parse(include_bytes!("fixtures/config/managed-ollama.yaml").as_slice()).unwrap(); - *document.spec.gateway.runtime_mut() = - serde_json::from_value::(json!({"provider": "kubernetes"})).unwrap(); - assert!(document.validate().is_err()); + let error = schema_error(&input); + assert!( + error.contains("schema at spec.sandboxes[0].image (line") + && error.ends_with( + "): image.metadata is available only for a spec.gateway.target.kubernetes gateway; Docker and Podman use engine image inspection" + ), + "{error}" + ); } #[test] @@ -520,13 +569,21 @@ fn schema_error(input: &Value) -> String { } #[test] -fn managed_kubernetes_endpoint_and_local_field_errors_state_the_target_rule() { - let rule = "managed Kubernetes requires an explicit HTTPS 127.0.0.1 endpoint with a nonzero port and excludes local engine settings"; - let mut endpoint = managed_document(); - endpoint["spec"]["gateway"]["endpoint"] = json!("http://127.0.0.1:17671"); - let mut local = managed_document(); - local["spec"]["gateway"]["networkCIDR"] = json!("172.30.1.0/24"); - for (input, path) in [(endpoint, "spec.gateway.endpoint"), (local, "spec.gateway")] { +fn a_kubernetes_target_requires_an_explicit_https_loopback_endpoint() { + let rule = "managed Kubernetes requires an explicit HTTPS 127.0.0.1 endpoint with a nonzero port and no path"; + Document::parse(managed_document().to_string().as_bytes()).unwrap(); + let mut missing = managed_document(); + missing["spec"]["gateway"]["target"]["kubernetes"] + .as_object_mut() + .unwrap() + .remove("endpoint"); + let mut http = managed_document(); + http["spec"]["gateway"]["target"]["kubernetes"]["endpoint"] = json!("http://127.0.0.1:17671"); + for (input, path) in [ + (missing, "spec.gateway.target.kubernetes"), + (http, "spec.gateway.target.kubernetes.endpoint"), + ] { + assert!(!jsonschema::is_valid(&schema::input_schema(), &input)); let error = schema_error(&input); assert!( error.contains(&format!("schema at {path} (line")) && error.contains(rule), @@ -535,13 +592,76 @@ fn managed_kubernetes_endpoint_and_local_field_errors_state_the_target_rule() { } } +#[test] +fn a_kubernetes_target_excludes_local_engine_settings() { + let validator = jsonschema::validator_for(&schema::input_schema()).unwrap(); + assert!(validator.is_valid(&managed_document())); + for (field, value) in [ + ("engine", json!("unix:///var/run/docker.sock")), + ("networkCidr", json!("172.30.1.0/24")), + ("imagePullPolicy", json!("Never")), + ("image", json!(nemoclaw_sdk::config::DEFAULT_GATEWAY_IMAGE)), + ] { + let mut input = managed_document(); + input["spec"]["gateway"]["target"]["kubernetes"][field] = value; + assert!(!validator.is_valid(&input), "accepted {field}"); + let error = schema_error(&input); + assert!( + error.contains("schema at spec.gateway.target.kubernetes (line"), + "{error}" + ); + } +} + +#[test] +fn an_external_kubernetes_target_requires_image_metadata_and_rejects_services() { + let validator = jsonschema::validator_for(&schema::input_schema()).unwrap(); + let input = external_document(); + assert!(validator.is_valid(&input)); + Document::parse(input.to_string().as_bytes()).unwrap(); + for field in ["ref", "metadata"] { + let mut input = external_document(); + input["spec"]["sandboxes"][0]["image"] + .as_object_mut() + .unwrap() + .remove(field); + assert!(!validator.is_valid(&input), "{field}"); + let error = schema_error(&input); + assert!( + error.contains("schema at spec.sandboxes[0].image (line") + && error.ends_with( + "): a Kubernetes target requires each sandbox image.ref pinned by digest and image.metadata" + ), + "{error}" + ); + } + let managed = + Document::parse(include_bytes!("fixtures/config/managed-ollama.yaml").as_slice()).unwrap(); + for mut input in [external_document(), managed_document()] { + input["spec"]["services"] = serde_json::to_value(&managed.spec.services).unwrap(); + assert!(!validator.is_valid(&input)); + let error = schema_error(&input); + assert!( + error.contains("schema at spec.services (line") + && error.contains("managed services are not supported"), + "{error}" + ); + } + // Docker and Podman inspect their engine instead. + let mut docker = external_document(); + docker["spec"]["gateway"]["target"] = json!({"docker": {}}); + assert!(!validator.is_valid(&docker)); + assert!(Document::parse(docker.to_string().as_bytes()).is_err()); +} + #[test] fn a_reserved_kubernetes_environment_name_states_the_naming_rule() { let mut input = managed_document(); - input["spec"]["gateway"]["kubernetes"]["environment"] = json!(["AWS_PROFILE", "KUBECONFIG"]); + input["spec"]["gateway"]["target"]["kubernetes"]["environment"] = + json!(["AWS_PROFILE", "KUBECONFIG"]); let error = schema_error(&input); assert!( - error.contains("schema at spec.gateway.kubernetes.environment[1] (line") + error.contains("schema at spec.gateway.target.kubernetes.environment[1] (line") && error.contains( "Kubernetes environment names must be unique variable names that do not shadow process, trust, proxy, or cluster controls" ), @@ -614,8 +734,8 @@ fn a_reserved_reference_name_states_whether_the_reference_holds_a_secret_or_a_fi ), ( managed_document(), - "/spec/gateway/kubernetes/kubeconfig", - "spec.gateway.kubernetes.kubeconfig.env", + "/spec/gateway/target/kubernetes/kubeconfig", + "spec.gateway.target.kubernetes.kubeconfig.env", file, ), ] { @@ -634,19 +754,3 @@ fn a_reserved_reference_name_states_whether_the_reference_holds_a_secret_or_a_fi assert!(error.contains(rule), "{error}"); } } - -#[test] -fn managed_services_with_a_kubernetes_runtime_state_the_cluster_rule() { - let managed = - Document::parse(include_bytes!("fixtures/config/managed-ollama.yaml").as_slice()).unwrap(); - let mut input = external_document(); - input["spec"]["services"] = serde_json::to_value(managed.spec.services).unwrap(); - let error = schema_error(&input); - assert!( - error.contains("schema at spec.services (line") - && error.contains( - "Kubernetes requires an external gateway or an explicit managed Kubernetes target, and external inference endpoints; managed services are not supported" - ), - "{error}" - ); -} diff --git a/crates/nemoclaw-sdk/tests/config_openshift.rs b/crates/nemoclaw-sdk/tests/config_openshift.rs index 7ae8857feec..2267a9b3b42 100644 --- a/crates/nemoclaw-sdk/tests/config_openshift.rs +++ b/crates/nemoclaw-sdk/tests/config_openshift.rs @@ -7,20 +7,34 @@ use nemoclaw_sdk::{ }; use serde_json::{Value, json}; -fn input(managed: bool) -> Value { +fn cluster(distribution: Option<&str>) -> Value { let original = Document::parse(include_bytes!("fixtures/config/local.yaml").as_slice()).unwrap(); let mut input = serde_json::to_value(original).unwrap(); - input["spec"]["gateway"]["runtime"] = json!({"provider": "openshift"}); + let mut target = json!({ + "endpoint": "https://127.0.0.1:17671", + "kubeconfig": {"env": "TEST_OPENSHIFT_CONFIG"}, + "context": "explicit-openshift", + "namespace": "owned-agents", + "authentication": {"profile": "development"} + }); + if let Some(distribution) = distribution { + target["distribution"] = json!(distribution); + } + input["spec"]["gateway"] = json!({"management": "managed", "target": {"kubernetes": target}}); input["spec"]["sandboxes"][0]["image"]["metadata"] = json!({"env":"TEST_IMAGE_METADATA"}); - if managed { + input +} + +/// An OpenShift deployment: a managed gateway on the openshift distribution, +/// or an existing gateway, which reports the upstream Kubernetes driver. +fn input(managed: bool) -> Value { + let mut input = cluster(Some("openshift")); + if !managed { input["spec"]["gateway"] = json!({ - "management": "managed", "runtime": {"provider": "openshift"}, "endpoint": "https://127.0.0.1:17671", - "kubernetes": { - "kubeconfig":{"env":"TEST_OPENSHIFT_CONFIG"}, - "context":"explicit-openshift", "namespace":"owned-agents", - "authentication":{"profile":"development"} - } + "management": "external", + "endpoint": "http://127.0.0.1:17671", + "target": {"kubernetes": {}} }); } input @@ -34,14 +48,14 @@ fn openshift_preserves_authored_profile_and_uses_the_upstream_kubernetes_driver( ); assert!(ComputeDriver::OpenShift.is_kubernetes()); assert!(!ComputeDriver::Docker.is_kubernetes()); - for managed in [false, true] { + for (managed, driver) in [ + (false, ComputeDriver::Kubernetes), + (true, ComputeDriver::OpenShift), + ] { let input = input(managed); assert!(jsonschema::is_valid(&schema::input_schema(), &input)); let document = Document::parse(input.to_string().as_bytes()).unwrap(); - assert_eq!( - document.spec.gateway.runtime().provider, - ComputeDriver::OpenShift - ); + assert_eq!(document.spec.gateway.compute_driver(), driver); let exported = document.yaml().unwrap(); let imported = Document::parse(exported.as_bytes()).unwrap(); assert_eq!(imported, document); @@ -54,26 +68,6 @@ fn openshift_preserves_authored_profile_and_uses_the_upstream_kubernetes_driver( } } -#[test] -fn the_runtime_alone_selects_openshift() { - let schema = schema::input_schema(); - // The Kubernetes target has no separate platform field to disagree with. - let mut value = input(true); - value["spec"]["gateway"]["kubernetes"]["distribution"] = json!("openshift"); - assert!(!jsonschema::is_valid(&schema, &value)); - assert!(Document::parse(value.to_string().as_bytes()).is_err()); - // A managed cluster target accepts only the two cluster runtimes. - for provider in ["docker", "podman"] { - let mut value = input(true); - value["spec"]["gateway"]["runtime"]["provider"] = json!(provider); - assert!(!jsonschema::is_valid(&schema, &value), "{provider}"); - assert!( - Document::parse(value.to_string().as_bytes()).is_err(), - "{provider}" - ); - } -} - #[test] fn openshift_never_defaults_an_image_or_uses_a_local_managed_gateway() { for managed in [false, true] { @@ -94,6 +88,88 @@ fn openshift_never_defaults_an_image_or_uses_a_local_managed_gateway() { assert!(Document::parse(value.to_string().as_bytes()).is_err()); } +#[test] +fn the_openshift_distribution_binds_its_driver_and_namespace_identity() { + let generations = [ + "workspace", + "provider", + "sandbox", + "kubernetes_gateway", + "kubernetes_storage", + ] + .map(|kind| (kind.into(), "a".repeat(32))) + .into(); + let identity = "${nemoclaw_kubernetes_auth.runtime.gateway_values}"; + for (distribution, driver) in [ + (None, "kubernetes"), + (Some("kubernetes"), "kubernetes"), + (Some("openshift"), "openshift"), + ] { + let input = cluster(distribution); + assert!(jsonschema::is_valid(&schema::input_schema(), &input)); + let document = Document::parse(input.to_string().as_bytes()).unwrap(); + let targets = runtime_targets(&document, &generations).unwrap(); + for target in targets + .iter() + .filter(|target| target.kind != "helm_release") + { + assert_eq!(target.values["compute_driver"], driver, "{}", target.kind); + } + let platform = compile_runtime(&document, &generations, "0.1.0").unwrap(); + let values = platform["resource"]["helm_release"]["gateway"]["values"] + .as_array() + .unwrap(); + assert_eq!( + values.iter().any(|value| value == identity), + driver == "openshift", + "{distribution:?}" + ); + let exported = Document::parse(document.yaml().unwrap().as_bytes()).unwrap(); + assert_eq!(exported, document); + } +} + +#[test] +fn only_a_managed_kubernetes_target_names_a_distribution() { + // An existing gateway reports only the upstream Kubernetes driver, so a + // distribution could not be checked against it. + let mut input = cluster(None); + input["spec"]["gateway"] = json!({ + "management": "external", + "endpoint": "https://openshell.example.com", + "target": {"kubernetes": {}} + }); + assert!(jsonschema::is_valid(&schema::input_schema(), &input)); + Document::parse(input.to_string().as_bytes()).unwrap(); + input["spec"]["gateway"]["target"]["kubernetes"]["distribution"] = json!("openshift"); + assert!(!jsonschema::is_valid(&schema::input_schema(), &input)); + let error = Document::parse(input.to_string().as_bytes()) + .unwrap_err() + .to_string(); + assert!( + error.starts_with("configuration violates schema at spec.gateway.target.kubernetes (line") + && error.ends_with( + "): distribution applies only to a managed gateway's spec.gateway.target.kubernetes; an existing gateway reports only the kubernetes driver" + ), + "{error}" + ); + // Any other field is unknown there. + input["spec"]["gateway"]["target"]["kubernetes"] = json!({"namespace": "agents"}); + let error = Document::parse(input.to_string().as_bytes()) + .unwrap_err() + .to_string(); + assert!( + error.starts_with("configuration violates schema at spec.gateway.target.kubernetes (line") + && error.ends_with("): unknown fields are not allowed"), + "{error}" + ); + for distribution in ["", "OpenShift", "eks"] { + let input = cluster(Some(distribution)); + assert!(!jsonschema::is_valid(&schema::input_schema(), &input)); + assert!(Document::parse(input.to_string().as_bytes()).is_err()); + } +} + #[test] fn openshift_compiles_platform_identity_and_wire_driver_without_docker() { let generations = [ diff --git a/crates/nemoclaw-sdk/tests/config_scenarios.rs b/crates/nemoclaw-sdk/tests/config_scenarios.rs index 3f8c445e411..314783ba508 100644 --- a/crates/nemoclaw-sdk/tests/config_scenarios.rs +++ b/crates/nemoclaw-sdk/tests/config_scenarios.rs @@ -211,14 +211,17 @@ fn managed_podman_with_an_explicit_gateway_port_should_work() { let desired = normalized(&document); assert_eq!(desired["spec"]["gateway"]["management"], "managed"); assert_eq!( - desired["spec"]["gateway"]["engine"], + desired["spec"]["gateway"]["target"]["podman"]["engine"], "unix:///run/user/1000/podman/podman.sock" ); assert_eq!( - desired["spec"]["gateway"]["endpoint"], + desired["spec"]["gateway"]["target"]["podman"]["endpoint"], "http://127.0.0.1:17891" ); - assert_eq!(desired["spec"]["gateway"]["runtime"]["provider"], "podman"); + assert_eq!( + document.spec.gateway.compute_driver(), + nemoclaw_sdk::config::ComputeDriver::Podman + ); } #[test] @@ -478,13 +481,13 @@ impl DesiredState { } fn sandbox_gpu(mut self) -> Self { - self.value["spec"]["gateway"]["runtime"]["gpu"] = + self.value["spec"]["gateway"]["target"]["docker"]["gpu"] = json!({"required": true, "device": "nvidia.com/gpu=0"}); self } fn host_mount(mut self) -> Self { - self.value["spec"]["gateway"]["runtime"]["hostMounts"] = json!([{ + self.value["spec"]["gateway"]["target"]["docker"]["hostMounts"] = json!([{ "source": "/home/user/project", "target": "/sandbox/project", "readOnly": true @@ -535,7 +538,10 @@ impl DesiredState { } fn gateway_endpoint(mut self, endpoint: &str) -> Self { - self.value["spec"]["gateway"]["endpoint"] = json!(endpoint); + let target = self.value["spec"]["gateway"]["target"] + .as_object_mut() + .unwrap(); + target.values_mut().next().unwrap()["endpoint"] = json!(endpoint); self } diff --git a/crates/nemoclaw-sdk/tests/config_schema.rs b/crates/nemoclaw-sdk/tests/config_schema.rs index a9e19181544..2dc032c7487 100644 --- a/crates/nemoclaw-sdk/tests/config_schema.rs +++ b/crates/nemoclaw-sdk/tests/config_schema.rs @@ -47,7 +47,7 @@ fn agrees_at( fn image_pull_policy_accepts_only_supported_values_on_managed_containers() { let validator = jsonschema::validator_for(&input_schema()).unwrap(); for (file, path) in [ - ("spark/spark-inline.yaml", "/spec/gateway"), + ("spark/spark-inline.yaml", "/spec/gateway/target/docker"), ("spark/spark-inline.yaml", "/spec/services/qwen"), ("managed-ollama.yaml", "/spec/services/ollama-server"), ] { @@ -122,6 +122,8 @@ fn input_schema_rejects_missing_required_fields_and_structural_nulls() { for (parent, key) in [ ("/spec/gateway", "credential"), ("/spec/gateway", "tls"), + ("/spec/gateway", "target"), + ("/spec/gateway/target", "docker"), ("/spec/inferenceProviders/0", "serviceRef"), ("/spec", "services"), ] { @@ -135,8 +137,8 @@ fn input_schema_rejects_missing_required_fields_and_structural_nulls() { fn input_schema_preserves_defaults_strict_objects_and_opaque_pi_metadata() { let validator = jsonschema::validator_for(&input_schema()).unwrap(); let mut value = input("spark/spark-inline.yaml"); - for key in ["endpoint", "engine", "image", "networkCIDR"] { - value["spec"]["gateway"] + for key in ["endpoint", "engine", "networkCidr"] { + value["spec"]["gateway"]["target"]["docker"] .as_object_mut() .unwrap() .remove(key); @@ -196,7 +198,7 @@ fn schema_and_parser_enforce_choices_bounds_and_conditional_forms() { ), ( "local.yaml", - "/spec/gateway/engine", + "/spec/gateway/target/docker/engine", json!("unix:///var/run/docker.sock"), true, ), @@ -208,14 +210,20 @@ fn schema_and_parser_enforce_choices_bounds_and_conditional_forms() { ), ( "local.yaml", - "/spec/gateway/runtime/provider", - json!("podman"), + "/spec/gateway/target", + json!({"podman": {}}), true, ), ( "local.yaml", - "/spec/gateway/runtime/provider", - json!("future"), + "/spec/gateway/target", + json!({"future": {}}), + false, + ), + ( + "local.yaml", + "/spec/gateway/target", + json!({"docker": {}, "podman": {}}), false, ), ( @@ -397,8 +405,8 @@ fn documented_parser_checks_remain_required_after_schema_validation() { ), ( "spark/vllm.yaml", - "/spec/gateway/runtime/provider", - json!("podman"), + "/spec/gateway/target", + json!({"podman": {"engine": "unix:///run/user/1000/podman/podman.sock"}}), ), ] { let mut value = input(file); @@ -450,7 +458,7 @@ fn gateway_variants_reject_fields_owned_by_the_other_mode() { let validator = jsonschema::validator_for(&input_schema()).unwrap(); for (field, value) in [ ("image", json!("")), - ("networkCIDR", json!("")), + ("networkCidr", json!("")), ("imagePullPolicy", json!("Never")), ] { let mut external = input("local.yaml"); @@ -479,56 +487,401 @@ fn a_sandbox_cannot_choose_a_runtime_apart_from_its_gateway() { } #[test] -fn managed_podman_requires_an_explicit_engine() { - let validator = jsonschema::validator_for(&input_schema()).unwrap(); - let mut value = input("managed-podman.yaml"); - value["spec"]["gateway"] - .as_object_mut() - .unwrap() - .remove("engine"); - agrees(&validator, &value, false); +fn schema_errors_identify_the_contract_without_echoing_input_values_or_map_keys() { + let mut value = input("fabric-openclaw.yaml"); + value["spec"]["harnesses"] = json!({"SECRET-MAP-KEY": { + "kind": "openclaw", "execution": {"timeoutSeconds": 0} + }}); let error = Document::parse(value.to_string().as_bytes()) .unwrap_err() .to_string(); - assert!( - error.contains("Podman requires spec.gateway.engine"), - "{error}" + assert!(error.contains("schema"), "{error}"); + assert!(!error.contains("SECRET-MAP-KEY"), "{error}"); +} + +/// The minimal external example with `gateway` in place of its own. +fn with_gateway(gateway: Value) -> Value { + let mut value = input("local.yaml"); + value["spec"]["gateway"] = gateway; + value +} + +fn managed(target: Value) -> Value { + with_gateway(json!({"management": "managed", "target": target})) +} + +fn cluster_target() -> Value { + json!({ + "endpoint": "https://127.0.0.1:17671", + "kubeconfig": {"env": "CLUSTER_KUBECONFIG"}, + "context": "explicit-context", + "namespace": "owned-gateway", + "authentication": {"profile": "development"} + }) +} + +/// A managed Kubernetes document; cluster sandboxes name an explicit image +/// and its metadata bundle. +fn cluster_document() -> Value { + let mut value = managed(json!({"kubernetes": cluster_target()})); + value["spec"]["sandboxes"][0]["image"] = json!({ + "ref": format!("registry.example/agent@sha256:{}", "a".repeat(64)), + "metadata": {"env": "TEST_IMAGE_METADATA"} + }); + value +} + +#[test] +fn each_managed_target_validates_and_receives_only_its_own_defaults() { + use sha2::Digest; + let validator = jsonschema::validator_for(&input_schema()).unwrap(); + let uid = input("local.yaml")["metadata"]["uid"].clone(); + let network = format!( + "172.30.{}.0/24", + sha2::Sha256::digest(uid.as_str().unwrap().as_bytes())[0] ); - let mut document: Document = serde_json::from_value(value.clone()).unwrap(); - document.defaults(); - assert!( - document - .spec - .gateway - .as_managed() - .unwrap() - .engine - .is_empty() + let podman = "unix:///run/user/1000/podman/podman.sock"; + let docker = json!({"docker": { + "endpoint": "http://127.0.0.1:17681", + "engine": "unix:///var/run/docker.sock", + "networkCidr": network + }}); + for (value, expected) in [ + ( + with_gateway(json!({"management": "managed"})), + docker.clone(), + ), + (managed(json!({"docker": {}})), docker), + ( + managed(json!({"podman": {"engine": podman}})), + json!({"podman": { + "endpoint": "http://127.0.0.1:17681", + "engine": podman, + "networkCidr": network + }}), + ), + ] { + agrees(&validator, &value, true); + let document = Document::parse(value.to_string().as_bytes()).unwrap(); + assert_eq!( + serde_json::to_value(&document).unwrap()["spec"]["gateway"], + json!({"management": "managed", "target": expected}) + ); + } + // A cluster target names everything itself; only its distribution has a default. + let value = cluster_document(); + agrees(&validator, &value, true); + let document = Document::parse(value.to_string().as_bytes()).unwrap(); + let mut expected = cluster_target(); + expected["distribution"] = json!("kubernetes"); + assert_eq!( + serde_json::to_value(&document).unwrap()["spec"]["gateway"], + json!({"management": "managed", "target": {"kubernetes": expected}}) ); +} - value["spec"]["gateway"]["engine"] = json!(""); - agrees(&validator, &value, false); +#[test] +fn gateway_fields_at_their_earlier_locations_are_rejected() { + let validator = jsonschema::validator_for(&input_schema()).unwrap(); + let docker = managed(json!({"docker": {}})); + agrees(&validator, &docker, true); + for (field, value) in [ + ("runtime", json!({"provider": "docker"})), + ("endpoint", json!("http://127.0.0.1:17681")), + ("engine", json!("unix:///var/run/docker.sock")), + ("image", json!(nemoclaw_sdk::config::DEFAULT_GATEWAY_IMAGE)), + ("imagePullPolicy", json!("Never")), + ("networkCIDR", json!("172.30.1.0/24")), + ("kubernetes", cluster_target()), + ] { + let mut moved = docker.clone(); + moved["spec"]["gateway"][field] = value; + agrees_at(&validator, &moved, false, "managed", field); + } + for (field, value) in [ + ("networkCIDR", json!("172.30.1.0/24")), + ("image", json!(nemoclaw_sdk::config::DEFAULT_GATEWAY_IMAGE)), + ("runtime", json!({"provider": "docker"})), + ] { + let mut moved = docker.clone(); + moved["spec"]["gateway"]["target"]["docker"][field] = value; + agrees_at(&validator, &moved, false, "target", field); + } + let external = with_gateway(json!({ + "management": "external", + "endpoint": "http://127.0.0.1:17671", + "target": {"docker": {"engine": "unix:///var/run/docker.sock"}} + })); + agrees(&validator, &external, true); + for (field, value) in [ + ("runtime", json!({"provider": "docker"})), + ("engine", json!("unix:///var/run/docker.sock")), + ] { + let mut moved = external.clone(); + moved["spec"]["gateway"][field] = value; + agrees_at(&validator, &moved, false, "external", field); + } +} + +/// The parser's schema diagnostic for `value` as `path: constraint`, without +/// its source position. +fn schema_diagnostic(value: &Value) -> String { let error = Document::parse(value.to_string().as_bytes()) .unwrap_err() .to_string(); - assert!( - error.contains("schema at spec.gateway.engine (line") - && error.contains("Podman requires spec.gateway.engine"), - "{error}" + let (path, constraint) = error + .strip_prefix("configuration violates schema at ") + .and_then(|rest| rest.split_once(" (line ")) + .and_then(|(path, rest)| Some((path, rest.split_once("): ")?.1))) + .unwrap_or_else(|| panic!("not a positioned schema diagnostic: {error}")); + format!("{path}: {constraint}") +} + +#[test] +fn an_earlier_gateway_shape_names_the_field_that_moved() { + let runtime = "spec.gateway.runtime is replaced by the key under spec.gateway.target: docker, podman, or kubernetes"; + let engine = "spec.gateway.engine moved to spec.gateway.target.docker.engine or spec.gateway.target.podman.engine"; + let image = "spec.gateway.image is removed because the SDK pins the gateway image"; + let network = "spec.gateway.networkCIDR moved to networkCidr under spec.gateway.target.docker or spec.gateway.target.podman"; + let external = |field: &str, value: Value| { + let mut gateway = json!({"management": "external", "endpoint": "http://127.0.0.1:17671"}); + gateway[field] = value; + with_gateway(gateway) + }; + let managed = + |field: &str, value: Value| with_gateway(json!({"management": "managed", field: value})); + for (value, message) in [ + (managed("runtime", json!({"provider": "podman"})), runtime), + ( + managed("endpoint", json!("http://127.0.0.1:17681")), + "spec.gateway.endpoint of a managed gateway moved to the endpoint of its spec.gateway.target key", + ), + ( + managed("engine", json!("unix:///var/run/docker.sock")), + engine, + ), + ( + managed("imagePullPolicy", json!("Never")), + "spec.gateway.imagePullPolicy moved to spec.gateway.target.docker or spec.gateway.target.podman", + ), + (managed("networkCIDR", json!("172.30.1.0/24")), network), + ( + managed("kubernetes", cluster_target()), + "spec.gateway.kubernetes moved to spec.gateway.target.kubernetes", + ), + ( + managed("image", json!(nemoclaw_sdk::config::DEFAULT_GATEWAY_IMAGE)), + image, + ), + (external("runtime", json!({"provider": "docker"})), runtime), + ( + external("engine", json!("unix:///var/run/docker.sock")), + engine, + ), + ] { + assert_eq!( + schema_diagnostic(&value), + format!("spec.gateway: {message}") + ); + } + // An earlier document gets every hint at once, starting with the runtime + // that chose where the other fields now live. + let earlier = with_gateway(json!({ + "management": "managed", + "networkCIDR": "172.30.1.0/24", + "image": nemoclaw_sdk::config::DEFAULT_GATEWAY_IMAGE, + "engine": "unix:///var/run/docker.sock", + "runtime": {"provider": "docker"} + })); + assert_eq!( + schema_diagnostic(&earlier), + format!("spec.gateway: {runtime}; {engine}; {image}; {network}") ); + // The same earlier fields moved into a target name their replacement there. + for target in ["docker", "podman"] { + let value = managed( + "target", + json!({target: { + "engine": "unix:///run/user/1000/podman/podman.sock", + "networkCIDR": "172.30.1.0/24", + "image": nemoclaw_sdk::config::DEFAULT_GATEWAY_IMAGE + }}), + ); + assert_eq!( + schema_diagnostic(&value), + format!( + "spec.gateway.target.{target}: spec.gateway.target.{target} takes no image because the SDK pins the gateway image; spec.gateway.target.{target} spells networkCIDR as networkCidr" + ) + ); + } } #[test] -fn schema_errors_identify_the_contract_without_echoing_input_values_or_map_keys() { - let mut value = input("fabric-openclaw.yaml"); - value["spec"]["harnesses"] = json!({"SECRET-MAP-KEY": { - "kind": "openclaw", "execution": {"timeoutSeconds": 0} - }}); - let error = Document::parse(value.to_string().as_bytes()) - .unwrap_err() - .to_string(); - assert!(error.contains("schema"), "{error}"); - assert!(!error.contains("SECRET-MAP-KEY"), "{error}"); +fn a_string_choice_error_lists_its_allowed_values() { + let pull = managed(json!({"podman": { + "engine": "unix:///run/user/1000/podman/podman.sock", + "imagePullPolicy": "Bogus" + }})); + let mut distribution = cluster_document(); + distribution["spec"]["gateway"]["target"]["kubernetes"]["distribution"] = json!("OpenShift"); + let mut profile = cluster_document(); + profile["spec"]["gateway"]["target"]["kubernetes"]["authentication"]["profile"] = + json!("production"); + for (value, expected) in [ + ( + pull, + r#"spec.gateway.target.podman.imagePullPolicy: must be "Always" or "IfNotPresent" or "Never""#, + ), + ( + distribution, + r#"spec.gateway.target.kubernetes.distribution: must be "kubernetes" or "openshift""#, + ), + ( + profile, + r#"spec.gateway.target.kubernetes.authentication.profile: must be "development""#, + ), + ] { + assert_eq!(schema_diagnostic(&value), expected); + } +} + +#[test] +fn a_local_target_endpoint_or_network_error_states_its_rule() { + let endpoint = + "a Docker or Podman gateway endpoint is http://127.0.0.1:PORT with an unprivileged port"; + let network = "networkCidr must be a canonical private IPv4 /24"; + for target in ["docker", "podman"] { + for (field, value, rule) in [ + ("endpoint", "https://127.0.0.1:17681", endpoint), + ("endpoint", "http://localhost:17681", endpoint), + ("networkCidr", "10.0.0.0/16", network), + ] { + let mut settings = json!({field: value}); + if target == "podman" { + settings["engine"] = json!("unix:///run/user/1000/podman/podman.sock"); + } + assert_eq!( + schema_diagnostic(&managed(json!({target: settings}))), + format!("spec.gateway.target.{target}.{field}: {rule}") + ); + } + } +} + +#[test] +fn an_external_image_engine_error_names_its_target_field() { + for target in ["docker", "podman"] { + for engine in ["tcp://127.0.0.1:2375", "ssh://user:secret@host"] { + let value = with_gateway(json!({ + "management": "external", + "endpoint": "http://127.0.0.1:17671", + "target": {target: {"engine": engine}} + })); + let error = Document::parse(value.to_string().as_bytes()) + .unwrap_err() + .to_string(); + assert_eq!( + error, + format!( + "spec.gateway.target.{target}.engine must be a unix:/// socket or ssh://[user@]host[:port] without a password, path, or options" + ) + ); + } + } +} + +#[test] +fn a_podman_target_requires_its_engine() { + let validator = jsonschema::validator_for(&input_schema()).unwrap(); + let podman = |settings: Value| managed(json!({"podman": settings})); + agrees( + &validator, + &podman(json!({"engine": "unix:///run/user/1000/podman/podman.sock"})), + true, + ); + let rule = + "Podman requires spec.gateway.target.podman.engine to name its local API service socket"; + for (settings, path) in [ + (json!({}), "spec.gateway.target.podman"), + (json!({"engine": ""}), "spec.gateway.target.podman.engine"), + ] { + let value = podman(settings); + agrees(&validator, &value, false); + let error = Document::parse(value.to_string().as_bytes()) + .unwrap_err() + .to_string(); + assert!( + error.contains(&format!("schema at {path} (line")) && error.contains(rule), + "{error}" + ); + } + // The socket depends on the host user, so defaults never choose one. + let mut document: Document = serde_json::from_value(podman(json!({"engine": ""}))).unwrap(); + document.defaults(); + assert_eq!( + serde_json::to_value(&document).unwrap()["spec"]["gateway"]["target"]["podman"]["engine"], + "" + ); + assert!(document.validate().is_err()); +} + +#[test] +fn image_pull_policy_follows_the_target_engine() { + let validator = jsonschema::validator_for(&input_schema()).unwrap(); + for (target, supported) in [ + ("docker", &["IfNotPresent", "Never"][..]), + ("podman", &["Always", "IfNotPresent", "Never"][..]), + ] { + for policy in ["Always", "IfNotPresent", "Never", "always", ""] { + let mut settings = json!({"imagePullPolicy": policy}); + if target == "podman" { + settings["engine"] = json!("unix:///run/user/1000/podman/podman.sock"); + } + let value = managed(json!({target: settings})); + let accepted = supported.contains(&policy); + agrees_at(&validator, &value, accepted, target, policy); + if !accepted { + continue; + } + let document = Document::parse(value.to_string().as_bytes()).unwrap(); + assert_eq!( + Document::parse(document.yaml().unwrap().as_bytes()).unwrap(), + document + ); + assert_eq!( + serde_json::to_value(&document).unwrap()["spec"]["gateway"]["target"][target]["imagePullPolicy"], + policy + ); + } + } + assert_eq!( + schema_diagnostic(&managed(json!({"docker": {"imagePullPolicy": "Always"}}))), + r#"spec.gateway.target.docker.imagePullPolicy: must be "IfNotPresent" or "Never""# + ); + let mut cluster = cluster_document(); + agrees(&validator, &cluster, true); + cluster["spec"]["gateway"]["target"]["kubernetes"]["imagePullPolicy"] = json!("Never"); + agrees(&validator, &cluster, false); +} + +#[test] +fn defaulted_and_exported_documents_carry_no_gateway_image() { + use nemoclaw_sdk::config::DEFAULT_GATEWAY_IMAGE; + assert!(!input_schema().to_string().contains(DEFAULT_GATEWAY_IMAGE)); + let directory = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples"); + for path in examples::yaml_files(&directory) { + let document = Document::parse(std::fs::read(&path).unwrap().as_slice()).unwrap(); + for text in [ + serde_json::to_string(&document).unwrap(), + document.yaml().unwrap(), + ] { + assert!( + !text.contains(DEFAULT_GATEWAY_IMAGE) && !text.contains("openshell/gateway@"), + "{}", + path.display() + ); + } + } } #[test] diff --git a/crates/nemoclaw-sdk/tests/config_validation.rs b/crates/nemoclaw-sdk/tests/config_validation.rs index 5e93c3b3a9f..becd8f9d757 100644 --- a/crates/nemoclaw-sdk/tests/config_validation.rs +++ b/crates/nemoclaw-sdk/tests/config_validation.rs @@ -75,7 +75,10 @@ fn directly_constructed_documents_and_services_enforce_normalized_bounds() { #[test] fn normalization_markers_are_accepted_only_before_defaults() { let baseline = document("spark/vllm.yaml"); - for path in ["/spec/gateway/image", "/spec/sandboxes/0/image/ref"] { + for path in [ + "/spec/gateway/target/docker/networkCidr", + "/spec/sandboxes/0/image/ref", + ] { let mut value = serde_json::to_value(&baseline).unwrap(); *value.pointer_mut(path).unwrap() = json!(""); assert!( diff --git a/crates/nemoclaw-sdk/tests/fabric_planner.rs b/crates/nemoclaw-sdk/tests/fabric_planner.rs index 7d0e4eb9a90..4d619541af1 100644 --- a/crates/nemoclaw-sdk/tests/fabric_planner.rs +++ b/crates/nemoclaw-sdk/tests/fabric_planner.rs @@ -363,11 +363,11 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - engine: unix:///var/run/docker.sock - endpoint: http://127.0.0.1:18080 - networkCIDR: 10.231.200.0/24 + target: + docker: + engine: unix:///var/run/docker.sock + endpoint: http://127.0.0.1:18080 + networkCidr: 10.231.200.0/24 inferenceProviders: - name: hosted provider: openai diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/fabric-claude.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/fabric-claude.yaml index 0e7fc3403ca..892a863ea0d 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/fabric-claude.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/fabric-claude.yaml @@ -9,9 +9,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17681 + target: + docker: {} inferenceProviders: - name: local provider: anthropic diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/fabric-pi.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/fabric-pi.yaml index b7f5b2680e2..d2f6db7e90e 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/fabric-pi.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/fabric-pi.yaml @@ -9,9 +9,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17681 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/fabric.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/fabric.yaml index ff1d9e6d182..485f64ff7d7 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/fabric.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/fabric.yaml @@ -9,9 +9,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17681 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/local.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/local.yaml index 08b2650286c..e8565ea5bca 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/local.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/local.yaml @@ -9,9 +9,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17671 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/managed-ollama.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/managed-ollama.yaml index f7181805da0..7c032f43432 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/managed-ollama.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/managed-ollama.yaml @@ -9,12 +9,11 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - endpoint: http://127.0.0.1:17671 - engine: unix:///var/run/docker.sock - image: ghcr.io/nvidia/openshell/gateway@sha256:ea14aa4db0980fab4769fb6b5509ac42ae3dc8495e645b1ba1fe1ada49892fa6 - networkCIDR: 172.20.0.0/24 + target: + docker: + endpoint: http://127.0.0.1:17671 + engine: unix:///var/run/docker.sock + networkCidr: 172.20.0.0/24 services: ollama-server: kind: ollama diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/spark.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/spark.yaml index c5bccd20ab1..99440e8b545 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/spark.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/spark.yaml @@ -9,12 +9,11 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - endpoint: http://127.0.0.1:17681 - engine: unix:///var/run/docker.sock - image: ghcr.io/nvidia/openshell/gateway@sha256:ea14aa4db0980fab4769fb6b5509ac42ae3dc8495e645b1ba1fe1ada49892fa6 - networkCIDR: 172.30.110.0/24 + target: + docker: + endpoint: http://127.0.0.1:17681 + engine: unix:///var/run/docker.sock + networkCidr: 172.30.110.0/24 services: qwen: kind: vllm diff --git a/crates/nemoclaw-sdk/tests/fixtures/discovery_graph/external-service.json b/crates/nemoclaw-sdk/tests/fixtures/discovery_graph/external-service.json index 3d4b6e824c0..99de63213df 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/discovery_graph/external-service.json +++ b/crates/nemoclaw-sdk/tests/fixtures/discovery_graph/external-service.json @@ -12,7 +12,7 @@ }, { "condition": "${self.runtime_json != \"\"}", - "error_message": "sandbox/assistant: image runtime metadata is unavailable. Set spec.gateway.engine to the sandbox image engine, load an image built with its runtime manifest, and use its immutable digest. Resources retained." + "error_message": "sandbox/assistant: image runtime metadata is unavailable. Set the engine of spec.gateway.target.docker or spec.gateway.target.podman to the sandbox image engine, load an image built with its runtime manifest, and use its immutable digest. Resources retained." } ] }, diff --git a/crates/nemoclaw-sdk/tests/fixtures/discovery_graph/openclaw.json b/crates/nemoclaw-sdk/tests/fixtures/discovery_graph/openclaw.json index 784a6606503..76770aea408 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/discovery_graph/openclaw.json +++ b/crates/nemoclaw-sdk/tests/fixtures/discovery_graph/openclaw.json @@ -27,7 +27,7 @@ }, { "condition": "${self.runtime_json != \"\"}", - "error_message": "sandbox/assistant: image runtime metadata is unavailable. Set spec.gateway.engine to the sandbox image engine, load an image built with its runtime manifest, and use its immutable digest. Resources retained." + "error_message": "sandbox/assistant: image runtime metadata is unavailable. Set the engine of spec.gateway.target.docker or spec.gateway.target.podman to the sandbox image engine, load an image built with its runtime manifest, and use its immutable digest. Resources retained." } ] }, diff --git a/crates/nemoclaw-sdk/tests/fixtures/discovery_graph/spark.json b/crates/nemoclaw-sdk/tests/fixtures/discovery_graph/spark.json index 8d55b708e8a..803e0fe2144 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/discovery_graph/spark.json +++ b/crates/nemoclaw-sdk/tests/fixtures/discovery_graph/spark.json @@ -27,7 +27,7 @@ }, { "condition": "${self.runtime_json != \"\"}", - "error_message": "sandbox/assistant: image runtime metadata is unavailable. Set spec.gateway.engine to the sandbox image engine, load an image built with its runtime manifest, and use its immutable digest. Resources retained." + "error_message": "sandbox/assistant: image runtime metadata is unavailable. Set the engine of spec.gateway.target.docker or spec.gateway.target.podman to the sandbox image engine, load an image built with its runtime manifest, and use its immutable digest. Resources retained." } ] }, diff --git a/crates/nemoclaw-sdk/tests/inference_connection.rs b/crates/nemoclaw-sdk/tests/inference_connection.rs index 6a962342638..9231043f0af 100644 --- a/crates/nemoclaw-sdk/tests/inference_connection.rs +++ b/crates/nemoclaw-sdk/tests/inference_connection.rs @@ -1,7 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use nemoclaw_sdk::config::ComputeDriver; -use nemoclaw_sdk::config::{Document, SecretRef}; +use nemoclaw_sdk::config::{ + Document, ExternalEngine, ExternalTarget, Gateway, ManagedDocker, ManagedGateway, + ManagedTarget, SecretRef, +}; #[test] fn missing_inference_provider_does_not_panic() { @@ -14,14 +16,15 @@ fn missing_inference_provider_does_not_panic() { #[test] fn bridge_resolution_rejects_malformed_networks_and_overflow() { - let mut gateway = nemoclaw_sdk::config::ManagedGateway { - network_cidr: "10.0.0.0/24".into(), - ..Default::default() + let gateway = |network: &str| ManagedGateway { + target: ManagedTarget::Docker(ManagedDocker { + network_cidr: network.into(), + ..Default::default() + }), }; - assert_eq!(gateway.bridge().unwrap(), "10.0.0.1"); + assert_eq!(gateway("10.0.0.0/24").bridge().unwrap(), "10.0.0.1"); for network in ["invalid", "::/64", "255.255.255.255/32"] { - gateway.network_cidr = network.into(); - assert!(gateway.bridge().is_err(), "{network}"); + assert!(gateway(network).bridge().is_err(), "{network}"); } } @@ -38,7 +41,10 @@ fn inference_connection_is_resolved_independently_of_the_sandbox_engine() { env: "MODEL_TOKEN".into(), }); let first = remote.inference_connection().unwrap(); - remote.spec.gateway.runtime_mut().provider = ComputeDriver::Podman; + let Gateway::External(gateway) = &mut remote.spec.gateway else { + panic!("expected an external gateway") + }; + gateway.target = ExternalTarget::Podman(ExternalEngine::default()); remote.validate().unwrap(); assert_eq!(remote.inference_connection().unwrap(), first); assert_eq!(first.endpoint, "https://inference.example.test:9443/v1"); diff --git a/crates/nemoclaw-sdk/tests/kubernetes_compile.rs b/crates/nemoclaw-sdk/tests/kubernetes_compile.rs index 84de36e7604..284fac0ad5a 100644 --- a/crates/nemoclaw-sdk/tests/kubernetes_compile.rs +++ b/crates/nemoclaw-sdk/tests/kubernetes_compile.rs @@ -12,7 +12,7 @@ fn kubernetes_compiles_only_openshell_resources_and_checks_the_driver_before_mut let original = Document::parse(include_bytes!("fixtures/config/local.yaml").as_slice()).unwrap(); let mut input = serde_json::to_value(original).unwrap(); - input["spec"]["gateway"]["runtime"] = json!({"provider": "kubernetes"}); + input["spec"]["gateway"]["target"] = json!({"kubernetes": {}}); input["spec"]["sandboxes"][0]["image"]["metadata"] = json!({"env":"TEST_IMAGE_METADATA"}); let document = Document::parse(input.to_string().as_bytes()).unwrap(); let generations = ["workspace", "provider", "sandbox"] diff --git a/crates/nemoclaw-sdk/tests/kubernetes_managed_compile.rs b/crates/nemoclaw-sdk/tests/kubernetes_managed_compile.rs index 1a6cd9fe79b..d06f45ee17c 100644 --- a/crates/nemoclaw-sdk/tests/kubernetes_managed_compile.rs +++ b/crates/nemoclaw-sdk/tests/kubernetes_managed_compile.rs @@ -12,13 +12,13 @@ fn document() -> Document { Document::parse(include_bytes!("fixtures/config/local.yaml").as_slice()).unwrap(); let mut value = serde_json::to_value(original).unwrap(); value["spec"]["gateway"] = json!({ - "management": "managed", "endpoint": "https://127.0.0.1:17671", - "kubernetes": { + "management": "managed", + "target": {"kubernetes": { + "endpoint": "https://127.0.0.1:17671", "kubeconfig": {"env":"TEST_KUBECONFIG"}, "context":"test-cluster", "namespace":"test-agents", "authentication":{"profile":"development"} - } + }} }); - value["spec"]["gateway"]["runtime"] = json!({"provider": "kubernetes"}); value["spec"]["sandboxes"][0]["image"]["metadata"] = json!({"env":"TEST_IMAGE_METADATA"}); Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap() } @@ -120,7 +120,7 @@ fn openshift_chart_values_wait_for_the_observed_namespace_identity() { ); let mut value = serde_json::to_value(document()).unwrap(); - value["spec"]["gateway"]["runtime"]["provider"] = json!("openshift"); + value["spec"]["gateway"]["target"]["kubernetes"]["distribution"] = json!("openshift"); let document = Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap(); let openshift = compile_runtime(&document, &generations, "0.1.0").unwrap(); let values = &openshift["resource"]["helm_release"]["gateway"]["values"]; @@ -269,8 +269,8 @@ fn managed_kubernetes_discovery_never_uses_a_local_container_engine() { fn kubernetes_attributes_reproduce_each_resource_specification() { use nemoclaw_sdk::kubernetes::{AUTH_KIND, GATEWAY_KIND, STORAGE_KIND, Spec}; let mut value = serde_json::to_value(document()).unwrap(); - value["spec"]["gateway"]["kubernetes"]["environment"] = json!(["AWS_PROFILE"]); - value["spec"]["gateway"]["runtime"]["provider"] = json!("openshift"); + value["spec"]["gateway"]["target"]["kubernetes"]["environment"] = json!(["AWS_PROFILE"]); + value["spec"]["gateway"]["target"]["kubernetes"]["distribution"] = json!("openshift"); let generations = [ "workspace", "provider", @@ -295,14 +295,8 @@ fn kubernetes_attributes_reproduce_each_resource_specification() { let kubernetes = spec.settings.kubernetes.as_ref().unwrap(); assert_eq!(kubernetes.context, "test-cluster"); assert_eq!( - document - .spec - .gateway - .as_managed() - .unwrap() - .kubernetes - .as_ref(), - Some(kubernetes) + document.spec.gateway.as_managed(), + Some(&spec.settings.authored().unwrap()) ); assert!(matches!( target.kind.as_str(), diff --git a/crates/nemoclaw-sdk/tests/managed_podman.rs b/crates/nemoclaw-sdk/tests/managed_podman.rs index 6d4e5332b34..9fa3325c478 100644 --- a/crates/nemoclaw-sdk/tests/managed_podman.rs +++ b/crates/nemoclaw-sdk/tests/managed_podman.rs @@ -11,9 +11,7 @@ use serde_json::{Value, json}; fn managed_podman_selects_one_driver_and_mounts_the_declared_socket() { let mut value: Value = serde_saphyr::from_str(include_str!("../../../examples/fabric.yaml")).unwrap(); - value["spec"]["gateway"] = - json!({"management":"managed","engine":"unix:///run/user/1000/podman/podman.sock"}); - value["spec"]["gateway"]["runtime"]["provider"] = json!("podman"); + value["spec"]["gateway"] = json!({"management":"managed","target":{"podman":{"engine":"unix:///run/user/1000/podman/podman.sock"}}}); let doc = Document::parse(value.to_string().as_bytes()).unwrap(); assert!( jsonschema::validator_for(&input_schema()) diff --git a/crates/nemoclaw-sdk/tests/ollama_proxy.rs b/crates/nemoclaw-sdk/tests/ollama_proxy.rs index c5c79569101..dd11c0233c8 100644 --- a/crates/nemoclaw-sdk/tests/ollama_proxy.rs +++ b/crates/nemoclaw-sdk/tests/ollama_proxy.rs @@ -24,9 +24,8 @@ fn input() -> Value { #[test] fn explicit_proxy_engine_works_with_an_external_gateway() { let mut value = input(); - value["spec"]["gateway"] = - json!({"management":"external", "endpoint":"http://127.0.0.1:17671"}); - value["spec"]["gateway"]["runtime"]["provider"] = json!("podman"); + value["spec"]["gateway"] = json!({"management":"external", "endpoint":"http://127.0.0.1:17671", + "target":{"podman":{}}}); value["spec"]["services"]["ollama-auth"]["engine"] = json!("unix:///tmp/proxy-engine.sock"); let document = Document::parse(value.to_string().as_bytes()).unwrap(); assert!( @@ -387,7 +386,7 @@ fn named_proxies_have_distinct_containers_storage_and_credentials() { #[test] fn proxy_requires_a_managed_docker_gateway_and_uses_its_engine() { let mut value = input(); - value["spec"]["gateway"]["engine"] = json!("unix:///tmp/proxy-engine.sock"); + value["spec"]["gateway"]["target"]["docker"]["engine"] = json!("unix:///tmp/proxy-engine.sock"); let document = Document::parse(value.to_string().as_bytes()).unwrap(); let generations = ["workspace", "provider", "sandbox", "ollama_proxy"] .map(|kind| (kind.into(), "a".repeat(32))) @@ -415,7 +414,8 @@ fn proxy_requires_a_managed_docker_gateway_and_uses_its_engine() { .to_string() .contains("managed local Docker gateway") ); - value["spec"]["gateway"]["runtime"]["provider"] = json!("podman"); + let docker = value["spec"]["gateway"]["target"]["docker"].take(); + value["spec"]["gateway"]["target"] = json!({"podman": docker}); assert!( Document::parse(value.to_string().as_bytes()) .unwrap_err() diff --git a/crates/nemoclaw-sdk/tests/resource_management.rs b/crates/nemoclaw-sdk/tests/resource_management.rs index 745c044c13d..17923ca4bc9 100644 --- a/crates/nemoclaw-sdk/tests/resource_management.rs +++ b/crates/nemoclaw-sdk/tests/resource_management.rs @@ -28,13 +28,13 @@ fn ownership_follows_configuration_instead_of_optional_annotations() { ), ( include_str!("../../../examples/managed-ollama-gpu.yaml"), - "/spec/gateway", + "/spec/gateway/target/docker", "network", json!({"management":"managed"}), ), ( include_str!("../../../examples/managed-ollama-gpu.yaml"), - "/spec/gateway", + "/spec/gateway/target/docker", "storage", json!({"management":"managed"}), ), diff --git a/crates/nemoclaw-sdk/tests/runtime_compile.rs b/crates/nemoclaw-sdk/tests/runtime_compile.rs index 820243a7712..a659120a3e2 100644 --- a/crates/nemoclaw-sdk/tests/runtime_compile.rs +++ b/crates/nemoclaw-sdk/tests/runtime_compile.rs @@ -193,8 +193,8 @@ fn remote_service_is_independent_of_the_external_sandbox_gateway() { let document = Document::parse(include_bytes!("fixtures/config/spark.yaml").as_slice()).unwrap(); let mut value = serde_json::to_value(document).unwrap(); - value["spec"]["gateway"] = json!({"management":"external","endpoint":"http://127.0.0.1:17670"}); - value["spec"]["gateway"]["runtime"]["provider"] = json!("podman"); + value["spec"]["gateway"] = json!({"management":"external","endpoint":"http://127.0.0.1:17670", + "target":{"podman":{}}}); value["spec"]["services"]["qwen"]["placement"] = json!({"engine":"ssh://operator@gpu-box","networkCidr":"172.30.119.0/24"}); value["spec"]["services"]["qwen"]["publication"] = diff --git a/crates/nemoclaw-sdk/tests/service_references.rs b/crates/nemoclaw-sdk/tests/service_references.rs index 5e18e492f17..9e541a1d77b 100644 --- a/crates/nemoclaw-sdk/tests/service_references.rs +++ b/crates/nemoclaw-sdk/tests/service_references.rs @@ -74,7 +74,8 @@ fn unconsumed_local_services_cannot_inherit_a_podman_engine() { "endpoint".into(), serde_json::json!("https://inference.example/v1"), ); - value["spec"]["gateway"]["runtime"]["provider"] = serde_json::json!("podman"); + let docker = value["spec"]["gateway"]["target"]["docker"].take(); + value["spec"]["gateway"]["target"] = serde_json::json!({"podman": docker}); assert!(Document::parse(value.to_string().as_bytes()).is_err()); } } diff --git a/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs b/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs index 3bef922b988..99c1637f753 100644 --- a/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs +++ b/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs @@ -270,12 +270,12 @@ pub fn kubernetes_document(name: &str, namespace: &str) -> Document { let mut value = crate::support::fixture("local.yaml"); value["metadata"]["name"] = json!(name); value["spec"]["gateway"] = json!({ - "management": "managed", "runtime": {"provider": "kubernetes"}, - "endpoint": "https://127.0.0.1:17671", - "kubernetes": { + "management": "managed", + "target": {"kubernetes": { + "endpoint": "https://127.0.0.1:17671", "kubeconfig": {"env": "TEST_KUBECONFIG"}, "context": "test-cluster", "namespace": namespace, "authentication": {"profile": "development"} - } + }} }); value["spec"]["sandboxes"][0]["image"]["metadata"] = json!({"env": "TEST_IMAGE_METADATA"}); Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap() diff --git a/crates/openshell-provider/tests/contract/capabilities.rs b/crates/openshell-provider/tests/contract/capabilities.rs index 5df8bab8206..ac926e33c24 100644 --- a/crates/openshell-provider/tests/contract/capabilities.rs +++ b/crates/openshell-provider/tests/contract/capabilities.rs @@ -167,7 +167,7 @@ async fn gateway_capabilities_gate_plans_and_saved_plan_applies() { assert!( normalized.contains(if failure == "driver" { "Gateway is incompatible with this configuration: gateway compute driver is \ - podman, but spec.gateway.runtime.provider is docker." + podman, but spec.gateway.target selects docker." } else { "Gateway capability observation failed" }), diff --git a/docs/build.md b/docs/build.md index 7a35cbd7d1d..678ee3bfc08 100644 --- a/docs/build.md +++ b/docs/build.md @@ -103,7 +103,7 @@ If catalog generation reports a missing runtime manifest, required path, or exec See the [image metadata contract](design/fabric-management.md#image-metadata) before changing the image layout. Plan requires the selected image's runtime metadata to supply its bridge command, environment, default policy, and executable grants. -For an external gateway, also set `spec.gateway.engine` to the engine containing that same immutable sandbox image; NemoClaw does not assume the client host's Docker socket. +For an external Docker or Podman gateway, also set `engine` under its `spec.gateway.target` key to the engine containing that same immutable sandbox image; NemoClaw does not assume the client host's Docker socket. This engine is used only for image inspection and does not authorize managing the external gateway. A missing image, missing metadata, or omitted external engine stops planning with a diagnostic; load a matching image or rebuild it, then retry. diff --git a/docs/contributing/configuration-schema.md b/docs/contributing/configuration-schema.md index d5ab75115b1..f0dd3a807dc 100644 --- a/docs/contributing/configuration-schema.md +++ b/docs/contributing/configuration-schema.md @@ -88,6 +88,8 @@ For a semantic check outside the schema, document the distinction in the generat Schema diagnostics identify document fields, array indices, and constraints without echoing rejected values or unknown properties. Valid names in the declared service, harness, inference, and integration collections identify the failing definition; other map keys appear as `[entry]`. Parsing a document also reports the source line and column for schema failures and YAML syntax errors. +When a field moves or is removed, map its old name to a message naming the replacement in the rejecting object's `x-nemoclaw-removed-fields` annotation; the diagnostic then reports the messages of all such fields in the input instead of an unknown field. +The `spec.gateway` variants list the fields that moved into `spec.gateway.target`; the reference generator does not render this annotation. The parser rejects all explicit YAML tags, including core tags such as `!!binary` and `!!str`; quoted strings containing tag text remain strings. The reference generator renders presence-conditioned scalar bounds beside the containing field table, including the conditional `kvCacheGiB` limits. Keep other conditional behavior in the owning Rust field descriptions when the generator cannot express its schema shape. diff --git a/docs/contributing/live-tests.md b/docs/contributing/live-tests.md index f3caf685b5d..fee25759904 100644 --- a/docs/contributing/live-tests.md +++ b/docs/contributing/live-tests.md @@ -256,7 +256,7 @@ Use an owned native Linux Docker daemon, a fresh deployment UID, an available ga Supply `NVIDIA_INFERENCE_API_KEY` through the process environment; never put its value in YAML, arguments, state, or repository files. The test installs that credential in OpenShell and does not revoke the upstream key. Keep the fixture's provider, sandbox, and agent names; the expected results name those resources. -Build a matching bundle and load the YAML's immutable gateway and agent images, including the Hermes image for the Hermes test, into the selected daemon. +Build a matching bundle and load the gateway image from [versions.json](../../versions.json) and the YAML's immutable agent images, including the Hermes image for the Hermes test, into the selected daemon. A GPU is not required. From the repository root, with absolute paths and one test selected: diff --git a/docs/design/architecture.md b/docs/design/architecture.md index a22172eabe7..eaef20790a7 100644 --- a/docs/design/architecture.md +++ b/docs/design/architecture.md @@ -59,7 +59,7 @@ Confirmed authentication cleanup prevents restoration after successful release r The [Helm removal recovery procedure](../usage.md#recover-an-interrupted-helm-removal) describes the required retained evidence and retry command. Issuer private material stays outside Helm values and OpenTofu state. The provider receives the explicit kubeconfig and context; ambient Helm and Kubernetes provider settings are excluded. -OpenTofu and its providers inherit only platform variables, so a kubeconfig exec plugin gets the caller variables listed in `gateway.kubernetes.environment` and nothing else. +OpenTofu and its providers inherit only platform variables, so a kubeconfig exec plugin gets the caller variables listed in `spec.gateway.target.kubernetes.environment` and nothing else. ## OpenShell SDK Boundary diff --git a/docs/design/authoring-domain.md b/docs/design/authoring-domain.md index 10ec0546303..d6083f0f84c 100644 --- a/docs/design/authoring-domain.md +++ b/docs/design/authoring-domain.md @@ -102,7 +102,8 @@ The private `QuestionTarget` carries that operation and its owner when the quest | Answer target | Effect | | --- | --- | -| SDK field | Write or remove a field under the active SDK schema; apply dependency behavior for API, endpoint, runtime, or gateway roles. | +| SDK field | Write or remove a field under the active SDK schema; apply dependency behavior for API, endpoint, gateway management, or gateway engine roles. | +| Variant key | Select the one key of an externally tagged union, such as `docker`, `podman`, or `kubernetes` at `/spec/gateway/target`; keep the previous key's settings that the new key accepts. | | Harness | Select an adapter and preserve inactive adapter settings for a later switch back. | | Adapter, workflow, or model setting | Edit the active native owner using its Fabric field schema. Model settings belong to the selected route. | | Structural form | Choose an exclusive representation, such as inline harness or `harnessRef`, before its required fields can be filled. | @@ -151,8 +152,8 @@ A read that could not be made is recorded as an unknown observation with its rea They are the SDK's `plan_queries`, the list a plan compiles into its discovery data sources, so onboarding and planning cannot ask different questions, plus the credential checks. Three exclusions are deliberate and tested: only the selected route's inference catalog is read, onboarding reads no hardware for a managed service's engine, and it makes no image read for an external gateway without an engine. `JourneyState::use_local_engines` keeps the candidate engines this machine has that answered; the caller supplies the candidates, so authoring holds no socket paths. -A runtime they offer becomes the suggestion when it is the only one, and choosing a runtime targets the managed gateway at the engine that answered for it. -A runtime no engine answered for gets no engine, and the target assessment's first reason says so unless an engine is authored. +A target key they offer becomes the suggestion when it is the only one, and choosing `docker` or `podman` sets the managed gateway's engine under that key to the engine that answered for it. +A target no engine answered for gets no engine, and the target assessment's first reason says so unless an engine is authored. Hosts are built from the engines they named and what each answered, and one recorded host in `tests/fixtures/observations` pins the replay format. Hardware and gateway observations do not affect questions or readiness yet. `resolve_with_observations` supplements current model suggestions with the matching inference observation and assesses target compatibility with `assess_target`. diff --git a/docs/design/onboarding-journeys.md b/docs/design/onboarding-journeys.md index 52ac90bda02..9868fa97490 100644 --- a/docs/design/onboarding-journeys.md +++ b/docs/design/onboarding-journeys.md @@ -92,7 +92,7 @@ Run `cargo run -p nemoclaw-authoring --example print_journey_tree` from the repo | Minimum viable values | One empty sandbox, with explicit `ask` guidance for the name. | Stops at an unresolved SDK frontier; it does not enumerate every question. | | Minimum inline scaffold | `crates/nemoclaw-authoring/tests/fixtures/minimum-inline.yaml`: inline harness and inference forms, one route, and an external endpoint. | Asks the deployment, sandbox, agent, and route names, gateway management, harness, provider kind, and model. `minimally_supplied_inline_envelope_materializes_through_one_resolver` materializes it after those answers and explicit optional omissions. | | Express | `examples/onboarding/openclaw.yaml`. | Zero questions, with absent optional adapter settings omitted through the `ActiveAdapterSettings` scope. Target compatibility remains a separate assessment. | -| Guided preview | The express template without a route model, with explicit `ask` guidance for the name, harness, runtime, provider, API, and model fields. | Asks each of those fields. | +| Guided preview | The express template without a route model, with explicit `ask` guidance for the name, harness, gateway target, provider, API, and model fields. | Asks each of those fields. | Starting a journey generates a missing deployment uid, so the uid is never a question. These previews do not establish complete coverage of arbitrary partial documents. @@ -116,11 +116,11 @@ These previews do not establish complete coverage of arbitrary partial documents - Deployment fields: guidance can review supplied values before unrelated required answers are complete. Once the SDK document is valid, the same field collector also offers SDK-filled defaults for review. Both cases use SDK field lookup for branch selection, answer schema, and requiredness. An optional supplied deployment value can be omitted interactively. A supplied deployment key that the SDK schema does not define becomes an optional question whose only answer is to remove the key. - Answer safety: changing an SDK discriminator removes supplied fields that only the previous branch defined. An answer that would leave the journey unable to resolve is rejected and the state is unchanged. - Route order: route selection runs after the selected route's model questions. -- SDK field choices are derived from finite schema alternatives. A runtime change fills a managed gateway engine only when the template did not supply one. An explicitly supplied engine remains authored intent. +- SDK field choices are derived from finite schema alternatives. The gateway target is asked at `/spec/gateway/target` as a choice of its key, `docker`, `podman`, or `kubernetes`, and the engine is asked under the chosen key, such as `/spec/gateway/target/podman/engine`. Changing the key keeps the previous key's settings that the new key accepts. A target change fills a managed gateway engine only when the template did not supply one. An explicitly supplied engine remains authored intent. - `JourneyState::resolve_with_observations` combines inference model suggestions and target compatibility from one `DiscoveryObservations` in one resolution used by the TUI for questions and review. Inference observations add model suggestions for the current route without restricting custom text. The request for that read comes from the SDK, as it does for planning, so an omitted API takes the provider's protocol default. A route backed by a managed service has no external catalog to read: it gets no inference suggestions and cannot use bulk acceptance, because its owner checks readiness. Bulk acceptance of remaining suggestions requires an accepted harness, compatible engine and image observations, an advertised selected model. Missing local credentials produce information about interactive plan prompts and non-interactive environment setup. A catalog requiring an absent key provides no model suggestions and an informational note; bulk acceptance still needs catalog compatibility, while individual model entry remains available. Target observations never change the desired state. -- `discovery_queries` reads the engine, image, inference endpoint, and gateway from an SDK-valid `Document`, so those observations arrive after the choices that make the document valid. Before the first question the TUI reads the engines `nemoclaw_discovery::local_engine_candidates` names from this machine's environment: Docker where the Docker client would connect (`DOCKER_HOST`, then `DOCKER_CONTEXT`, then the configured current context) when that is a Unix socket, otherwise its default socket, and Podman at the user's socket under `XDG_RUNTIME_DIR`, then the rootful socket. When exactly one runtime answered, it becomes the suggested runtime, even over a supplied value, and the user still decides. With both or neither, the template's runtime stays the suggestion. Choosing a runtime targets the managed gateway at the engine that answered for it. When no engine answered for the chosen runtime and no engine is authored, the target assessment reports that first, ahead of the result of reading the SDK's default engine. Other target observations never change questions; only inference observations add model choices. Hardware and gateway observations are collected but do not affect questions or readiness yet. +- `discovery_queries` reads the engine, image, inference endpoint, and gateway from an SDK-valid `Document`, so those observations arrive after the choices that make the document valid. Before the first question the TUI reads the engines `nemoclaw_discovery::local_engine_candidates` names from this machine's environment: Docker where the Docker client would connect (`DOCKER_HOST`, then `DOCKER_CONTEXT`, then the configured current context) when that is a Unix socket, otherwise its default socket, and Podman at the user's socket under `XDG_RUNTIME_DIR`, then the rootful socket. When only Docker or only Podman answered, that key becomes the suggested target, even over a supplied value, and the user still decides. With both or neither, the template's target stays the suggestion. Choosing `docker` or `podman` sets the managed gateway's engine to the engine that answered for it. When no engine answered for the chosen target and no engine is authored, the target assessment reports that first, ahead of the result of reading the SDK's default engine. Other target observations never change questions; only inference observations add model choices. Hardware and gateway observations are collected but do not affect questions or readiness yet. - The TUI offers harness choices and settings schemas from the bundled Fabric catalog for the whole run. The selected image's catalog only feeds the target assessment, where a harness the image does not advertise is a conflict that blocks `ready_document`. -- SDK assessment and journey completion are separate: a fully supplied document can be SDK-valid while explicit `ask` questions remain. `JourneyResolution::materialized_document` returns the SDK document only when current questions are answered and Fabric schema gaps are cleared. A definition may additionally require compatible engine and image observations. `ready_document` rejects any observed target conflict and waits for compatible evidence when the definition requires it; unknown evidence otherwise remains unverified. Observations never change the authored document, and the TUI does not reject a runtime choice based on the author's workstation OS. +- SDK assessment and journey completion are separate: a fully supplied document can be SDK-valid while explicit `ask` questions remain. `JourneyResolution::materialized_document` returns the SDK document only when current questions are answered and Fabric schema gaps are cleared. A definition may additionally require compatible engine and image observations. `ready_document` rejects any observed target conflict and waits for compatible evidence when the definition requires it; unknown evidence otherwise remains unverified. Observations never change the authored document, and the TUI does not reject a target choice based on the author's workstation OS. - The executable example TUI loads a sparse `PartialDocument`, runs `JourneyState`, and saves only its `ready_document` result. Resolver errors surface as errors rather than appearing to finish the questionnaire. The default-path and per-example TUI tests exercise this path. ## Alignment to the Intended Model @@ -144,6 +144,6 @@ The prototype has not settled these; the rules above stand until one is decided. - **Question surface:** which optional schema regions belong to the bounded onboarding question surface? - **Harness changes:** when a journey switches harness, does it keep adapter-specific guidance for every harness, or change to another journey definition? - **Unverified targets:** which terminal state should block authoring when SDK-valid YAML exists but Fabric or target compatibility is unverified? -- **Early target observation:** this machine's engines are read before the first question and shape the runtime and engine choices. How can the image catalog be read before the document is SDK-valid, so it can shape the harness choice too? +- **Early target observation:** this machine's engines are read before the first question and shape the target and engine choices. How can the image catalog be read before the document is SDK-valid, so it can shape the harness choice too? When implementation settles a question, change the affected rule above and remove the question. diff --git a/docs/get-started.md b/docs/get-started.md index e98c78daf9c..463f3eaa0dc 100644 --- a/docs/get-started.md +++ b/docs/get-started.md @@ -66,18 +66,18 @@ Edit the copied YAML before executing it: | `metadata.uid` | The fresh UUID printed above, or the one onboarding wrote; retain it for every operation on this deployment | | `metadata.name` | Your deployment label | | `spec.gateway.endpoint` | Your existing gateway's endpoint | -| `spec.gateway.engine` | The Docker or Podman engine containing the immutable sandbox image; replace the example's illustrative socket with that engine's address | +| `spec.gateway.target` key | `docker` or `podman`, matching your gateway's compute driver; see [gateway targets](usage.md#choose-the-gateway-target) | +| `engine` under that key | The Docker or Podman engine containing the immutable sandbox image; replace the example's illustrative socket with that engine's address | | `spec.gateway.credential` and `spec.gateway.tls` | References required by that gateway; omit optional fields when unused | | `spec.inferenceProviders[0].endpoint` | Your upstream inference base URL | | `spec.inferenceProviders[0].provider` and `.api` | The [matching protocol and API](inference.md); the example selects OpenAI Responses | | `spec.inferenceProviders[0].credential` | An environment reference when the endpoint needs a key | | `spec.sandboxes[0].image.ref` | The immutable reference from your image build | -| `spec.gateway.runtime.provider` | `docker` or `podman`, matching your gateway's compute driver | | The primary route's `overrides.model` | The exact model ID served by your endpoint | | Other route `overrides` | Limits and reasoning settings supported by that model; remove optional tuning you have not verified | Keep `gateway.management: external`, sandbox name `assistant`, and loopback dashboard port `18800` to match the access commands. -The explicit `gateway.engine` is used for image inspection; it does not grant NemoClaw ownership of the external gateway. +The `engine` is used only for image inspection; it does not grant NemoClaw ownership of the external gateway. External gateways have no default image engine; use the address of the daemon holding the image, which may be on another host. Update the copied schema comment to `../../schemas/nemoclaw-v1alpha1.schema.json` so editor diagnostics use this checkout's schema. Use the [field reference](reference/configuration.md) for accepted fields. diff --git a/docs/inference.md b/docs/inference.md index 26c00b8aa70..531f70239a1 100644 --- a/docs/inference.md +++ b/docs/inference.md @@ -258,7 +258,7 @@ Changing an existing service to enable authentication follows the normal runtime ## Use External Ollama through a Managed Proxy Run the proxy on the same Linux Docker host as the existing Ollama daemon and installed model. -With a managed Docker gateway, the proxy inherits `gateway.engine`. +With a managed Docker gateway, the proxy inherits `spec.gateway.target.docker.engine`. With an external gateway, declare the proxy service's `engine` as an explicit local Docker Unix socket and make its published endpoint reachable from OpenShell. Ollama must listen only on a loopback address. NemoClaw observes its model inventory and never installs, stops, or deletes the daemon or model. diff --git a/docs/kubernetes.md b/docs/kubernetes.md index e435f3a383a..561fe8ca45d 100644 --- a/docs/kubernetes.md +++ b/docs/kubernetes.md @@ -17,7 +17,7 @@ OpenShift's security policy admitting these pods is untested; [current limits](l The bundle includes the Helm provider that installs the gateway; no Helm CLI is needed. - **Cluster access:** a kubeconfig file and an exact context that can create a namespace and, inside it, Secrets, ConfigMaps, Services, Deployments, StatefulSets and NetworkPolicies. The SDK reads the cluster's CustomResourceDefinitions, StorageClasses and namespaces. - If the kubeconfig runs an exec plugin that needs your environment, such as `aws` for EKS, list those variables in `gateway.kubernetes.environment`, for example `[AWS_PROFILE, AWS_REGION]`. + If the kubeconfig runs an exec plugin that needs your environment, such as `aws` for EKS, list those variables in `spec.gateway.target.kubernetes.environment`, for example `[AWS_PROFILE, AWS_REGION]`. OpenTofu and its providers receive only platform variables such as `PATH` and `HOME`, plus the ones you list. - **Cluster setup, done by the platform operator:** - [Agent Sandbox](https://github.com/kubernetes-sigs/agent-sandbox), with its controller running in `agent-sandbox-system`; CI tests version 0.5.0. @@ -49,26 +49,27 @@ The SDK creates the namespace and a credential key, starts a development token i Start from [the Kubernetes example](../examples/kubernetes/managed-development.yaml) and set: - `metadata.uid` to a new UUID. -- `gateway.kubernetes.kubeconfig` to the environment variable holding the kubeconfig path, and `context` to the exact context. -- `gateway.kubernetes.namespace` to a namespace that does not exist yet; NemoClaw does not take over an existing one. -- `gateway.endpoint` to `https://127.0.0.1:` and a free local port for the port forward. +- Under `spec.gateway.target.kubernetes`, `kubeconfig` to the environment variable holding the kubeconfig path, and `context` to the exact context. +- `namespace` to a namespace that does not exist yet; NemoClaw does not take over an existing one. +- `endpoint` to `https://127.0.0.1:` and a free local port for the port forward. - Each sandbox's `image.ref` and `image.metadata`. ```yaml spec: gateway: management: managed - runtime: - provider: kubernetes - endpoint: https://127.0.0.1:17671 - kubernetes: - kubeconfig: {env: NEMOCLAW_CLUSTER_KUBECONFIG} - context: my-cluster - namespace: nemoclaw-development - authentication: - profile: development + target: + kubernetes: + endpoint: https://127.0.0.1:17671 + kubeconfig: {env: NEMOCLAW_CLUSTER_KUBECONFIG} + context: my-cluster + namespace: nemoclaw-development + authentication: + profile: development ``` +Deployment state binds every setting under `spec.gateway.target`; to change one, create a separate deployment, as described in [Choose the Gateway Target](usage.md#choose-the-gateway-target). + From the directory holding `deployment.yaml`, preview the deployment, then apply it: ```sh @@ -85,21 +86,24 @@ Keep the state directory: it holds the cluster ownership receipt and the develop ## Deploy to OpenShift -Set `gateway.runtime.provider: openshift`; everything else matches the managed Kubernetes deployment above. +Set `distribution: openshift` under `spec.gateway.target.kubernetes`; everything else matches the managed Kubernetes deployment above. Start from [the OpenShift example](../examples/openshift/managed-development.yaml). -OpenShift assigns each namespace a UID and group range and admits only those identities. -After creating the namespace, the SDK waits up to 30 seconds for OpenShift to record that range, then runs the gateway as its first UID and group. +OpenShift's security context constraints (SCC) assign each namespace a UID range and supplemental groups, and admit only those identities. +After creating the namespace, the SDK waits up to 30 seconds for OpenShift to record the UID range, then passes the first UID and a group to the gateway chart as security-context values: the first supplemental group, or the UID when the namespace has no supplemental groups. OpenShell runs each sandbox as the same UID. If the range never appears, apply stops before installing the gateway with `OpenShift did not assign the namespace a UID range`; check that the context points at an OpenShift cluster. The SDK records the range in its receipt, and a later apply refuses a namespace whose range has changed. +The distribution also binds the gateway's compute driver as `openshift`; OpenShell still runs sandboxes with its upstream Kubernetes driver, and nothing else differs from the `kubernetes` distribution. The agent images need no OpenShift variant: any UID can read their workspace seed. ## Use an Existing Gateway -To use an OpenShell gateway someone else runs on the cluster, set `gateway.management: external` with `runtime.provider` set to `kubernetes` or `openshift`. -Give its endpoint, credential and TLS material as environment references, as in [the external gateway example](../examples/kubernetes/external-gateway.yaml). +To use an OpenShell gateway someone else runs on the cluster, set `gateway.management: external` and `target: {kubernetes: {}}`. +An external target takes no `distribution`, also for OpenShift: the gateway reports only the `kubernetes` driver, so a distribution could not be checked. +Plan still checks the target key against that report. +Give the gateway's endpoint, credential and TLS material as environment references, as in [the external gateway example](../examples/kubernetes/external-gateway.yaml). NemoClaw then manages only the sandboxes; it neither installs nor removes the gateway. Sandboxes still need `image.metadata`. diff --git a/docs/provider.md b/docs/provider.md index 689b7011937..2086f8a0664 100644 --- a/docs/provider.md +++ b/docs/provider.md @@ -315,7 +315,7 @@ Catalog identifiers are not restricted to a compiled SDK list. The runtime consumes the same canonical public configuration through Fabric; see [discovered harness configuration](sdk.md#configure-a-discovered-fabric-harness). Generated graphs observe each sandbox image independently of resource creation or image acquisition. -Managed gateways use their configured engine; external gateways require `spec.gateway.engine` for image inspection and do not run managed-gateway prerequisite checks. +Managed gateways use their configured engine; external Docker and Podman gateways require `engine` under their `spec.gateway.target` key for image inspection and do not run managed-gateway prerequisite checks. With `config_json`, image discovery also returns `runtime_json`, the selected adapter and advertised runtime layout, and `binaries_json`, its resolved executable list. The sandbox consumes `runtime_json`; its `policy` block retains authored policy and managed endpoint inputs, resolved against that layout before creation. Provider profiles require a nonempty `binaries` list, which graphs decode from `binaries_json`; search registrations retain their scoped `profile_name`. diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index c79dab9e7d6..4b5a1392d02 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -19,7 +19,7 @@ Empty or zero selects a default only where stated. - Document::parse rejects YAML aliases, anchors, merge keys, all explicit tags (including core tags such as !!binary), duplicate keys, multiple documents, and input larger than 1 MiB. It applies the compiled input schema before defaulting; Document::validate applies the normalized schema and semantic checks, including for directly constructed Rust values. - The parser checks endpoint transport and address policy, managed gateway port bounds, canonical private IPv4 /24 networks, local engine socket syntax, and publication address/port/network agreement. -- Managed Kubernetes requires explicit kubeconfig environment, context, namespace, and development authentication profile; Agent Sandbox and one default StorageClass must already be installed. Its HTTPS endpoint is exactly 127.0.0.1 with an explicit port from 1 through 65535 and no path. Local engine fields and managed inference services are excluded; gateway.runtime.provider is kubernetes or openshift. OpenShift uses the upstream Kubernetes driver and requires platform-owned OpenShift security prerequisites. Cluster identity, ownership, prerequisite compatibility, and credential files are checked during operations. +- A managed Kubernetes target requires explicit kubeconfig environment, context, namespace, and development authentication profile; Agent Sandbox and one default StorageClass must already be installed. Its HTTPS endpoint is exactly 127.0.0.1 with an explicit port from 1 through 65535 and no path. A Kubernetes target, managed or external, excludes managed inference services. The openshift distribution uses the upstream Kubernetes driver and requires platform-owned OpenShift security prerequisites. Cluster identity, ownership, prerequisite compatibility, and credential files are checked during operations. - Explicit sandbox policies are also checked by the pinned OpenShell policy parser and validator, including protocol-specific rule semantics, process identities, filesystem paths, and destination address restrictions. - Explicit filesystem grants must permit reads of the packaged Fabric runtime and NemoClaw bridge directories; parent and read-write grants count. This parser check does not inspect images, resolve symlinks, or establish runtime permissions. - The schema requires an explicit default for multiple model choices. Rust checks unique route names, that the default names a route, and that native model and tool fields have valid structural shapes. Fabric validates adapter-specific combinations. @@ -209,6 +209,33 @@ Paths: |---|---|---|---|---| | `explicit` | [ExplicitPolicy](#explicitpolicy) | Yes | — | Complete sandbox policy in OpenShell YAML field names. | +## ExternalEngine + +Engine holding sandbox images for an existing Docker or Podman gateway. + +Guide: [Gateway target](../usage.md#choose-the-gateway-target). + +Paths: + +- `spec.gateway.target.docker` +- `spec.gateway.target.podman` + +| Field | Input type | Required | Default | Description and constraints | +|---|---|---|---|---| +| `engine` | string | No | — | Engine containing the sandbox images, used only for image metadata inspection. Required for deployment planning; omission permits retained-state teardown. | + +## ExternalKubernetes + +An existing Kubernetes or OpenShift gateway takes no target settings; sandbox image metadata replaces engine inspection. + +Guide: [Gateway target](../usage.md#choose-the-gateway-target). + +Paths: + +- `spec.gateway.target.kubernetes` + +Accepted input: object. + ## ExternalOllama External Ollama daemon observed by the managed proxy installer. @@ -239,6 +266,45 @@ Paths: | `digest` | string | Yes | — | Lowercase 64-character model digest reported by Ollama's /api/tags API. Constraints: pattern `^[a-f0-9]{64}$`. | | `name` | string | Yes | — | Installed Ollama model name including its tag. Constraints: pattern `^[a-z0-9][a-z0-9._-]*:[a-z0-9][a-z0-9._-]*$`. | +## ExternalTarget + +Exactly one target key: docker, podman, or kubernetes. + +Guide: [Gateway target](../usage.md#choose-the-gateway-target). + +Paths: + +- `spec.gateway.target` + +Accepted input: object. + +### Alternative 1 + +The existing gateway runs sandboxes on Docker. + + +| Field | Input type | Required | Default | Description and constraints | +|---|---|---|---|---| +| `docker` | [ExternalEngine](#externalengine) | Yes | — | The existing gateway runs sandboxes on Docker. | + +### Alternative 2 + +The existing gateway runs sandboxes on Podman. + + +| Field | Input type | Required | Default | Description and constraints | +|---|---|---|---|---| +| `podman` | [ExternalEngine](#externalengine) | Yes | — | The existing gateway runs sandboxes on Podman. | + +### Alternative 3 + +The existing gateway runs sandboxes on Kubernetes, including OpenShift. Sandboxes need explicit images with metadata, and managed inference services are excluded. + + +| Field | Input type | Required | Default | Description and constraints | +|---|---|---|---|---| +| `kubernetes` | [ExternalKubernetes](#externalkubernetes) | Yes | — | The existing gateway runs sandboxes on Kubernetes, including OpenShift. Sandboxes need explicit images with metadata, and managed inference services are excluded. | + ## File One immutable file in a model snapshot. @@ -263,7 +329,7 @@ Guide: [Configuration and credentials](../usage.md#configuration-and-credentials Paths: -- `spec.gateway.kubernetes.kubeconfig` +- `spec.gateway.target.kubernetes.kubeconfig` - `spec.gateway.tls.ca` - `spec.gateway.tls.certificate` - `spec.gateway.tls.key` @@ -288,19 +354,12 @@ Accepted input: object. ### Alternative 1 A gateway installed and managed by this deployment. -Managed Podman targets local rootless Linux; rootful, remote, and other platforms are unqualified. | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| -| `endpoint` | string | No | `"http://127.0.0.1:17681"` | Local engine gateways use an HTTP origin with an unprivileged loopback port. Kubernetes requires `https://127.0.0.1:PORT` with an explicit nonzero port and no trailing slash; commands forward that local port to the owned gateway. Without kubernetes, omitted or empty selects the local HTTP endpoint. Kubernetes requires an explicit HTTPS loopback endpoint and port. | -| `engine` | string | No | `"unix:///var/run/docker.sock"` | Managed local gateway Unix engine socket; Podman requires its API service socket. Excluded by kubernetes. With runtime.provider docker, omitted or empty selects Docker's default socket. Podman requires its API service socket. Excluded by kubernetes. | -| `image` | string | No | `"ghcr.io/nvidia/openshell/gateway@sha256:ea14aa4db0980fab4769fb6b5509ac42ae3dc8495e645b1ba1fe1ada49892fa6"` | Managed local gateway image pinned by the SDK. Excluded by kubernetes, whose component images are also SDK-pinned. Without kubernetes, omitted or empty selects the SDK default. Excluded by kubernetes. | -| `imagePullPolicy` | [ImagePullPolicy](#imagepullpolicy) | No | — | Image acquisition before local container creation. Docker accepts IfNotPresent (the default) or Never; Podman also accepts Always before creation or restart. Excluded by kubernetes. | -| `kubernetes` | [ManagedKubernetes](#managedkubernetes) | No | — | Explicit Kubernetes provisioning target. Excludes local engine, image, imagePullPolicy, and networkCIDR settings and requires Kubernetes sandboxes without managed inference services. | | `management` | string | Yes | — | Whether this deployment manages the gateway. Constraints: `"managed"`. | -| `networkCIDR` | string | No | — | Canonical private IPv4 /24 for a managed local gateway. Excluded by kubernetes. Without kubernetes, omitted or empty selects 172.30.N.0/24, where N is the first byte of SHA-256(metadata.uid). Excluded by kubernetes. | -| `runtime` | [Runtime](#runtime) | No | — | Compute driver the gateway runs every sandbox with; omission selects Docker. | +| `target` | [ManagedTarget](#managedtarget) | No | `{"docker":{}}` | Where the gateway runs. The key selects the compute driver for every sandbox; omission selects a local Docker engine. | ### Alternative 2 @@ -311,9 +370,8 @@ An existing gateway managed outside this deployment. |---|---|---|---|---| | `credential` | [SecretRef](#secretref) | No | — | Optional bearer credential reference for an external HTTPS gateway. | | `endpoint` | string | Yes | — | Gateway HTTP(S) origin, without a path. Constraints: pattern `^https?://`. | -| `engine` | string | No | — | Engine containing Docker or Podman sandbox images, used only for image metadata inspection. Required for their deployment planning; omission permits retained-state teardown. Kubernetes and OpenShift use image.metadata instead. | | `management` | string | Yes | — | Whether this deployment manages the gateway. Constraints: `"external"`. | -| `runtime` | [Runtime](#runtime) | No | — | Compute driver the existing gateway runs; omission selects Docker. Planning checks it against the driver the gateway reports. | +| `target` | [ExternalTarget](#externaltarget) | No | `{"docker":{}}` | The key selects the compute driver that runs every sandbox; omission selects Docker. Planning checks it against the driver the gateway reports. | | `tls` | [TLS](#tls) | No | — | Optional mutual TLS references for an external HTTPS gateway. | ## HardwareProfile @@ -361,8 +419,8 @@ Paths: | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| -| `metadata` | [FileRef](#fileref) | No | — | Environment reference to the absolute path of a local OCI metadata bundle for `ref`; required for Kubernetes and OpenShift, where no local engine can be inspected. Destroy does not read it. Its index, manifest, configuration, and Fabric catalog are verified against `ref` before use. The bundle holds no image layers or credentials. Docker and Podman inspect their engine instead. | -| `ref` | string | For Kubernetes sandboxes | — | Immutable image reference. Kubernetes and OpenShift require an explicit nonempty reference. For other drivers, omitted or empty selects the generic SDK agent image pin; verify that it contains the selected Fabric adapter. Constraints: `""` or pattern `^[a-zA-Z0-9][a-zA-Z0-9._:/-]*@sha256:[a-f0-9]{64}$`. Kubernetes and OpenShift require an explicit immutable image reference. For other drivers, omitted or empty selects the generic SDK agent image pin; verify that it contains the selected Fabric adapter. | +| `metadata` | [FileRef](#fileref) | With a Kubernetes target | — | Environment reference to the absolute path of a local OCI metadata bundle for `ref`. A Kubernetes target requires it because no local engine can be inspected; Docker and Podman targets inspect their engine instead and reject it. Destroy does not read it. Its index, manifest, configuration, and Fabric catalog are verified against `ref` before use. The bundle holds no image layers or credentials. | +| `ref` | string | With a Kubernetes target | — | Immutable image reference pinned by digest. Constraints: `""` or pattern `^[a-zA-Z0-9][a-zA-Z0-9._:/-]*@sha256:[a-f0-9]{64}$`. A Kubernetes target requires an explicit immutable image reference. For Docker and Podman targets, omitted or empty selects the generic SDK agent image pin; verify that it contains the selected Fabric adapter. | ## ImagePullPolicy @@ -372,7 +430,7 @@ Guide: [Container image downloads](../usage.md#control-container-image-downloads Paths: -- `spec.gateway.imagePullPolicy` +- `spec.gateway.target.podman.imagePullPolicy` - `spec.services.{key}.imagePullPolicy` Accepted input: string. @@ -493,30 +551,105 @@ Guide: [Configuration and credentials](../usage.md#configuration-and-credentials Paths: -- `spec.gateway.kubernetes.authentication` +- `spec.gateway.target.kubernetes.authentication` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| | `profile` | string | Yes | — | Development generates the scoped local authentication fixture. Existing production issuers use gateway.management: external. Constraints: `"development"`. | +## ManagedDocker + +Local Docker engine settings for a managed gateway. + +Guide: [Gateway target](../usage.md#choose-the-gateway-target). + +Paths: + +- `spec.gateway.target.docker` + +| Field | Input type | Required | Default | Description and constraints | +|---|---|---|---|---| +| `endpoint` | string | No | `"http://127.0.0.1:17681"` | Gateway HTTP origin with the 127.0.0.1 loopback address and an unprivileged port. Constraints: `""` or pattern `^http://127\.0\.0\.1:[0-9]+/?$`. Omitted or empty selects the default. | +| `engine` | string | No | `"unix:///var/run/docker.sock"` | Docker engine Unix socket. Constraints: `""` or pattern `^unix:///`. Omitted or empty selects the default. | +| `imagePullPolicy` | string | No | `"IfNotPresent"` | Gateway image acquisition before container creation: IfNotPresent (the default) or Never. Constraints: `"IfNotPresent"` or `"Never"`. | +| `networkCidr` | string | No | — | Canonical private IPv4 /24 for the gateway network. Constraints: `""` or pattern `/24$`. Omitted or empty selects 172.30.N.0/24, where N is the first byte of SHA-256(metadata.uid). | + ## ManagedKubernetes -Explicit existing-cluster target for a managed development gateway. The SDK does not create a cluster or select an ambient context, and installs nothing cluster-wide: Agent Sandbox and a default StorageClass must already exist. `runtime.provider: openshift` selects the OpenShift profile. +Explicit existing-cluster target for a managed development gateway. The SDK does not create a cluster or select an ambient context, and installs nothing cluster-wide: Agent Sandbox and a default StorageClass must already exist. -Guide: [Configuration and credentials](../usage.md#configuration-and-credentials). +Guide: [Gateway target](../usage.md#choose-the-gateway-target). Paths: -- `spec.gateway.kubernetes` +- `spec.gateway.target.kubernetes` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| | `authentication` | [KubernetesAuthentication](#kubernetesauthentication) | Yes | — | Explicit generated development authentication profile; this is not a production identity service. | | `context` | string | Yes | — | Exact kubeconfig context used for every cluster operation. Constraints: pattern `^[^\x00-\x20\x7f]+$(?![\s\S])`; minimum characters 1; maximum characters 253. | +| `distribution` | string | No | `"kubernetes"` | Cluster distribution. `openshift` makes the SDK wait up to 30 seconds for OpenShift to assign the namespace its SCC UID range, read the first UID and the first supplemental group (the UID when no supplemental groups are assigned), record that namespace identity, pass it to the gateway chart as security-context values, and bind the `openshift` compute driver. Sandboxes use the upstream Kubernetes driver either way. Constraints: `"kubernetes"` or `"openshift"`. | +| `endpoint` | string | Yes | — | Local HTTPS origin `https://127.0.0.1:PORT` with an explicit nonzero port and no trailing slash. Commands forward that local port to the owned gateway. Constraints: pattern `^https://127\.0\.0\.1:(?:[1-9][0-9]{0,3}\|[1-5][0-9]{4}\|6[0-4][0-9]{3}\|65[0-4][0-9]{2}\|655[0-2][0-9]\|6553[0-5])$(?![\s\S])`. | | `environment` | array of string | No | — | Caller environment variables that the kubeconfig's exec credential plugin needs, such as `AWS_PROFILE` for an EKS cluster. Cluster operations receive only platform variables and these; they are resolved like credential references and never written to configuration or state. Constraints: maximum items 32; items: pattern `^[A-Z_][A-Z0-9_]{0,127}$`. | | `kubeconfig` | [FileRef](#fileref) | Yes | — | Environment reference whose value is the local kubeconfig file path. The file and its credentials remain outside configuration and exported state. Process, loader, trust, proxy, cluster, Python, Helm, OpenTofu, and SDK control variable names are reserved. | | `namespace` | string | Yes | — | Namespace for this deployment's gateway and generated development authentication resources. Constraints: pattern `^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$(?![\s\S])`; minimum characters 1; maximum characters 63. | +## ManagedPodman + +Local rootless Linux Podman engine settings for a managed gateway. + +Guide: [Gateway target](../usage.md#choose-the-gateway-target). + +Paths: + +- `spec.gateway.target.podman` + +| Field | Input type | Required | Default | Description and constraints | +|---|---|---|---|---| +| `endpoint` | string | No | `"http://127.0.0.1:17681"` | Gateway HTTP origin with the 127.0.0.1 loopback address and an unprivileged port. Constraints: `""` or pattern `^http://127\.0\.0\.1:[0-9]+/?$`. Omitted or empty selects the default. | +| `engine` | string | Yes | — | Podman API service Unix socket. It depends on the host user, so it has no default. Constraints: pattern `^unix:///`; minimum characters 1. | +| `imagePullPolicy` | [ImagePullPolicy](#imagepullpolicy) | No | `"IfNotPresent"` | Gateway image acquisition: Always before creation or restart, IfNotPresent (the default), or Never. | +| `networkCidr` | string | No | — | Canonical private IPv4 /24 for the gateway network. Constraints: `""` or pattern `/24$`. Omitted or empty selects 172.30.N.0/24, where N is the first byte of SHA-256(metadata.uid). | + +## ManagedTarget + +Exactly one target key: docker, podman, or kubernetes. + +Guide: [Gateway target](../usage.md#choose-the-gateway-target). + +Paths: + +- `spec.gateway.target` + +Accepted input: object. + +### Alternative 1 + +Install the gateway on a local Docker engine. + + +| Field | Input type | Required | Default | Description and constraints | +|---|---|---|---|---| +| `docker` | [ManagedDocker](#manageddocker) | Yes | — | Install the gateway on a local Docker engine. | + +### Alternative 2 + +Install the gateway on a local rootless Linux Podman engine. Rootful, remote, and other platforms are unqualified. + + +| Field | Input type | Required | Default | Description and constraints | +|---|---|---|---|---| +| `podman` | [ManagedPodman](#managedpodman) | Yes | — | Install the gateway on a local rootless Linux Podman engine. Rootful, remote, and other platforms are unqualified. | + +### Alternative 3 + +Install the gateway in an explicit existing Kubernetes cluster. Sandboxes need explicit images with metadata, and managed inference services are excluded. + + +| Field | Input type | Required | Default | Description and constraints | +|---|---|---|---|---| +| `kubernetes` | [ManagedKubernetes](#managedkubernetes) | Yes | — | Install the gateway in an explicit existing Kubernetes cluster. Sandboxes need explicit images with metadata, and managed inference services are excluded. | + ## Manifest Pinned model snapshot inventory. The parser rejects duplicate files and file/directory conflicts. @@ -921,20 +1054,6 @@ Paths: | `provider` | [InferenceProvider](#inferenceprovider) | No | — | Inline inference definition owned by this route. Excludes providerRef and must not shadow an enclosing definition. | | `providerRef` | string | No | — | Name of an enclosing inference provider. Exactly one of providerRef or provider is required. Constraints: pattern `^[a-z][a-z0-9-]{0,39}$`. | -## Runtime - -The compute driver an OpenShell gateway runs sandboxes with. One gateway runs one driver. - -Guide: [Configuration and credentials](../usage.md#configuration-and-credentials). - -Paths: - -- `spec.gateway.runtime` - -| Field | Input type | Required | Default | Description and constraints | -|---|---|---|---|---| -| `provider` | string | No | `"docker"` | Docker, Podman, Kubernetes, or OpenShift profile. Kubernetes and OpenShift require an external gateway or an explicit managed cluster target, and external inference endpoints. OpenShift uses the upstream Kubernetes driver with namespace-assigned identities. A managed service with Podman requires explicit service placement. Constraints: `"docker"` or `"podman"` or `"kubernetes"` or `"openshift"`. | - ## Sandbox The gateway owns sandbox creation and dependency placement. @@ -951,7 +1070,7 @@ Paths: | `harness` | [Harness](#harness) | No | — | Inline harness configuration. Exactly one of harness or harnessRef is required. The sandbox agent uses this harness implementation. | | `harnessRef` | string | No | — | Name of a visible harness configuration. Excludes inline harness. Constraints: pattern `^[a-z][a-z0-9-]{0,39}$`. | | `harnesses` | map of [Harness](#harness) | No | — | Named harness configurations available through harnessRef. Selecting a definition reuses configuration; runtime processes belong to each sandbox. Constraints: keys: pattern `^[a-z][a-z0-9-]{0,39}$`. | -| `image` | [Image](#image) | For Kubernetes sandboxes | — | Kubernetes requires an explicit immutable agent image compatible with the gateway's runtime user and group IDs. For other drivers, omission selects the generic SDK agent image pin; verify that it contains the selected Fabric adapter. | +| `image` | [Image](#image) | With a Kubernetes target | — | Agent image compatible with the gateway's runtime user and group IDs. A Kubernetes target requires an explicit `ref` and `metadata`; Docker and Podman targets may omit it and use the generic SDK agent image pin. | | `inferenceProviders` | array of [InferenceProvider](#inferenceprovider) | No | — | Named inference definitions visible to this sandbox's routes. Names must not shadow deployment definitions. | | `inferences` | map of [Inference](#inference) | No | — | Named inference configurations available through inferenceRef. Definitions resolve providers in their own scope and create no resources until selected. Constraints: keys: pattern `^[a-z][a-z0-9-]{0,39}$`. | | `integrations` | map of [Integration](#integration) | No | — | Named integration definitions selected by this sandbox's agent through integrationRefs. Names must not collide with deployment definitions. Constraints: keys: pattern `^[a-z][a-z0-9-]{0,39}$`. | diff --git a/docs/usage.md b/docs/usage.md index b5a29b1889d..dc5a050c3a0 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -53,12 +53,45 @@ Every declared service is installed and checked, even without an inference consu Services run on the gateway's Docker engine by default, or on another host through [SSH placement](remote-service.md). See [service constraints](inference.md#combine-local-and-hosted-providers) for multiple Ollama/vLLM services and [models](models.md) for hardware contracts and optional [recipes](recipes.md). +## Choose the Gateway Target + +`spec.gateway.target` holds exactly one key, `docker`, `podman`, or `kubernetes`, which selects the compute driver for every sandbox. +Omitting `target` selects `docker`. + +For a managed gateway, the key holds the gateway's settings: + +```yaml +gateway: + management: managed + target: + docker: + endpoint: http://127.0.0.1:17681 + engine: unix:///var/run/docker.sock + networkCidr: 172.30.7.0/24 +``` + +- `docker` and `podman` take a loopback HTTP `endpoint`, the local `engine` socket, `imagePullPolicy`, and `networkCidr`; all are optional except Podman's `engine`. +- `kubernetes` takes a loopback HTTPS `endpoint`, the cluster settings, and an optional `distribution`; see [Deploy to Kubernetes or OpenShift](kubernetes.md). + +For an external gateway, `endpoint`, `credential`, and `tls` stay beside `target`, and the key names the compute driver that gateway runs. +Under `docker` or `podman`, `engine` names the engine holding the sandbox images, which NemoClaw only inspects; `kubernetes` takes no settings. +Plan checks the key against the driver the gateway reports and stops on a mismatch. + +An existing deployment cannot move to another target. +For a managed gateway, deployment state binds the target key and every setting under it except `imagePullPolicy`: the endpoint, engine, `networkCidr`, distribution, and cluster settings. +For an external gateway, it binds `endpoint`. +To change a bound setting, create a separate deployment with a fresh `metadata.uid` and state directory. +To re-author a document for another target, fill in the new key's required fields; for `kubernetes`, give each sandbox an explicit `image.ref` and `image.metadata` and replace `spec.services` with external inference endpoints; for `docker` or `podman`, remove `image.metadata`. + +The SDK pins the gateway image, and the document does not name it. +A Docker or Podman gateway stays bound to the image pin of the bundle that created it, and a managed Kubernetes gateway to that bundle's gateway chart pin: keep operating it with that bundle, or create a separate deployment to use a bundle with a different pin. + ## Use a Managed Podman Gateway Use a local rootless Linux Podman engine through its Unix API socket. Rootful operation, remote Podman engines, and other operating systems are untested ([#12641](https://github.com/NVIDIA/NemoClaw/issues/12641)). -Set `gateway.runtime.provider: podman` and set `gateway.engine` to the local Podman API service's Unix socket. +Set `spec.gateway.target.podman.engine` to the local Podman API service's Unix socket. See [the Podman example](../examples/managed-podman.yaml). The API service is an operator prerequisite; NemoClaw manages its gateway, network, and credential storage through that service. Load the harness image into the selected Podman image store and use the digest reported there. @@ -67,7 +100,6 @@ Rootless operation requires an API that reports `pasta` networking, as required Older APIs that omit this information fail during plan. The host must have a private IPv4 address on its default-route interface. OpenShell uses that address for sandbox-only callbacks while keeping its user API on loopback. -Every managed gateway uses one compute driver; use separate deployments to select different drivers. Managed vLLM with Podman sandboxes still requires explicit SSH Docker placement and publication. Podman's changing compatibility `/info.ID` is not a durable identity. @@ -127,7 +159,7 @@ See [sandbox policy configuration](sandbox-network.md) for changes and [security ## Control Container Image Downloads -Set `imagePullPolicy` beside `image` under `spec.gateway` or `spec.services.`. +Set `imagePullPolicy` under `spec.gateway.target.docker` or `spec.gateway.target.podman`, or beside `image` under `spec.services.`. The service setting applies to `kind: vllm`, `ollama`, and `ollamaProxy`. The setting controls image acquisition on that container's engine, including an SSH Docker engine selected by the service's `placement.engine`. Images still require immutable SHA-256 references. @@ -225,7 +257,7 @@ Use separate deployments when you need independent teardown. | Harness adapter, sandbox image, agent identity, or provider attachments | Changes the immutable sandbox specification; apply refuses replacement; use a separate deployment with a fresh UID and state | | Sandbox network policy | Changes the sandbox specification; follow [policy change constraints](sandbox-network.md) and use a separate deployment when replacement is required | | Managed inference or proxy image or serving specification | Docker-provider reconciliation may replace the container while retaining its independently bound storage; review the plan and [model constraints](models.md) | -| Deployment UID, established gateway endpoint, or bound credential/gateway engine | Cannot retarget the existing state; create a separate deployment | +| Deployment UID, [bound gateway settings](#choose-the-gateway-target), or bound credentials | Cannot retarget the existing state; create a separate deployment | | Remove an unused inference provider definition | Changes the desired document only; the SDK creates registrations for selected definitions, so unused definitions have no resources to delete | | Remove a sandbox, retained storage, or a protected gateway binding | Apply refuses removal; assess a separate deployment and explicit retirement of the original | | Change a credential value behind the same environment reference | Unchanged apply does not detect rotation; see [credential lifecycle](security.md#credentials-and-authentication) | @@ -436,7 +468,7 @@ It does not revoke upstream keys or remove images, external gateways, or engines Finish destroy first: `nemoclaw plan --destroy --state-dir .local/deployment` must print `No resource changes planned.`, then the entries to remove under `Retained resources:`. The commands select objects by UID alone, so confirm that no other deployment, including one copied from the same example, uses this `metadata.uid`. -Run the commands with Docker access to each engine the deployment selects: the managed gateway's `spec.gateway.engine`, each service's `placement.engine`, and each Ollama proxy's `engine`. +Run the commands with Docker access to each engine the deployment selects: the managed gateway's `spec.gateway.target.docker.engine`, each service's `placement.engine`, and each Ollama proxy's `engine`. For SSH placement, connect to that host using the already configured SSH identity; do not substitute the client's local Docker daemon. From any directory, set `deployment_engine` to one of those engines and `deployment_uid` to the UID, then list the deployment's objects: diff --git a/examples/explicit-policy.yaml b/examples/explicit-policy.yaml index 081aa8aecb6..bddf3c41c85 100644 --- a/examples/explicit-policy.yaml +++ b/examples/explicit-policy.yaml @@ -10,9 +10,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17671 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/examples/fabric-claude.yaml b/examples/fabric-claude.yaml index c600238d974..db1e09cc302 100644 --- a/examples/fabric-claude.yaml +++ b/examples/fabric-claude.yaml @@ -12,9 +12,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17681 + target: + docker: {} inferenceProviders: - name: local provider: anthropic diff --git a/examples/fabric-codex.yaml b/examples/fabric-codex.yaml index 3baf1997182..465185d16a4 100644 --- a/examples/fabric-codex.yaml +++ b/examples/fabric-codex.yaml @@ -12,9 +12,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17681 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/examples/fabric-hermes.yaml b/examples/fabric-hermes.yaml index 5f01e1fa509..3c1e0a82439 100644 --- a/examples/fabric-hermes.yaml +++ b/examples/fabric-hermes.yaml @@ -10,9 +10,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17681 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/examples/fabric-mini-swe-agent.yaml b/examples/fabric-mini-swe-agent.yaml index 9641c799f6d..cbd75b293f5 100644 --- a/examples/fabric-mini-swe-agent.yaml +++ b/examples/fabric-mini-swe-agent.yaml @@ -12,9 +12,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17681 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/examples/fabric-nooa-bench.yaml b/examples/fabric-nooa-bench.yaml index 5722f5ff4de..f2fb5679ea1 100644 --- a/examples/fabric-nooa-bench.yaml +++ b/examples/fabric-nooa-bench.yaml @@ -12,9 +12,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17681 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/examples/fabric-nooa.yaml b/examples/fabric-nooa.yaml index 7f93757688b..38fa4e3097f 100644 --- a/examples/fabric-nooa.yaml +++ b/examples/fabric-nooa.yaml @@ -12,9 +12,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17681 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/examples/fabric-openclaw.yaml b/examples/fabric-openclaw.yaml index 9fd1eebab8a..b1271d00d6e 100644 --- a/examples/fabric-openclaw.yaml +++ b/examples/fabric-openclaw.yaml @@ -10,9 +10,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17681 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/examples/fabric-pi.yaml b/examples/fabric-pi.yaml index 125b74a6985..ee4758931b6 100644 --- a/examples/fabric-pi.yaml +++ b/examples/fabric-pi.yaml @@ -12,9 +12,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17681 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/examples/fabric-remote-agent.yaml b/examples/fabric-remote-agent.yaml index 9ef9eaa4aae..35bf78c6e15 100644 --- a/examples/fabric-remote-agent.yaml +++ b/examples/fabric-remote-agent.yaml @@ -12,9 +12,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17681 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/examples/fabric.yaml b/examples/fabric.yaml index eaa71a7ecca..b2f261afb95 100644 --- a/examples/fabric.yaml +++ b/examples/fabric.yaml @@ -10,9 +10,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17681 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/examples/full-featured-openclaw.yaml b/examples/full-featured-openclaw.yaml index 7e60a385928..c9fafffa525 100644 --- a/examples/full-featured-openclaw.yaml +++ b/examples/full-featured-openclaw.yaml @@ -68,13 +68,11 @@ spec: maxSearchLimit: 20 gateway: management: managed - runtime: - provider: docker - endpoint: http://127.0.0.1:17695 - engine: unix:///var/run/docker.sock - image: - ghcr.io/nvidia/openshell/gateway@sha256:ea14aa4db0980fab4769fb6b5509ac42ae3dc8495e645b1ba1fe1ada49892fa6 - networkCIDR: 172.30.121.0/24 + target: + docker: + endpoint: http://127.0.0.1:17695 + engine: unix:///var/run/docker.sock + networkCidr: 172.30.121.0/24 services: nemotron: kind: vllm diff --git a/examples/hermes-auth.yaml b/examples/hermes-auth.yaml index 0e2f9fc7c42..5c57c8cac7a 100644 --- a/examples/hermes-auth.yaml +++ b/examples/hermes-auth.yaml @@ -10,9 +10,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17671 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/examples/hermes-interfaces.yaml b/examples/hermes-interfaces.yaml index ede0fc04225..27776d7634a 100644 --- a/examples/hermes-interfaces.yaml +++ b/examples/hermes-interfaces.yaml @@ -10,9 +10,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17681 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/examples/inference-tuning.yaml b/examples/inference-tuning.yaml index b1594c9e328..12e85ec428f 100644 --- a/examples/inference-tuning.yaml +++ b/examples/inference-tuning.yaml @@ -10,9 +10,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17671 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/examples/kubernetes/external-gateway.yaml b/examples/kubernetes/external-gateway.yaml index 25295997e17..8a77d469674 100644 --- a/examples/kubernetes/external-gateway.yaml +++ b/examples/kubernetes/external-gateway.yaml @@ -14,14 +14,14 @@ spec: # Supply the existing Kubernetes cluster's OpenShell gateway. gateway: management: external - runtime: - provider: kubernetes endpoint: https://openshell.example.com credential: {env: GATEWAY_TOKEN} tls: ca: {env: GATEWAY_CA} certificate: {env: GATEWAY_CERT} key: {env: GATEWAY_KEY} + target: + kubernetes: {} inferenceProviders: - name: inference provider: openai diff --git a/examples/kubernetes/hosted-nvidia.yaml b/examples/kubernetes/hosted-nvidia.yaml index 79ac5976d5d..1fb609cbb51 100644 --- a/examples/kubernetes/hosted-nvidia.yaml +++ b/examples/kubernetes/hosted-nvidia.yaml @@ -15,14 +15,14 @@ spec: # Supply the existing Kubernetes cluster's OpenShell gateway. gateway: management: external - runtime: - provider: kubernetes endpoint: https://openshell.example.com credential: {env: GATEWAY_TOKEN} tls: ca: {env: GATEWAY_CA} certificate: {env: GATEWAY_CERT} key: {env: GATEWAY_KEY} + target: + kubernetes: {} inferenceProviders: - name: hosted-nvidia-prod provider: openai diff --git a/examples/kubernetes/managed-development.yaml b/examples/kubernetes/managed-development.yaml index 705ffd8896e..b2738db5956 100644 --- a/examples/kubernetes/managed-development.yaml +++ b/examples/kubernetes/managed-development.yaml @@ -15,16 +15,15 @@ metadata: spec: gateway: management: managed - runtime: - provider: kubernetes - # The SDK opens this loopback tunnel only for the duration of each command. - endpoint: https://127.0.0.1:17671 - kubernetes: - kubeconfig: {env: NEMOCLAW_CLUSTER_KUBECONFIG} - context: replace-with-explicit-context - namespace: nemoclaw-development - authentication: - profile: development + target: + kubernetes: + # The SDK opens this loopback tunnel only for the duration of each command. + endpoint: https://127.0.0.1:17671 + kubeconfig: {env: NEMOCLAW_CLUSTER_KUBECONFIG} + context: replace-with-explicit-context + namespace: nemoclaw-development + authentication: + profile: development inferenceProviders: - name: hosted-nvidia provider: openai diff --git a/examples/local.yaml b/examples/local.yaml index 4686c428545..ed40565a80c 100644 --- a/examples/local.yaml +++ b/examples/local.yaml @@ -10,9 +10,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17671 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/examples/managed-hermes.yaml b/examples/managed-hermes.yaml index f672d278f15..5418df7f971 100644 --- a/examples/managed-hermes.yaml +++ b/examples/managed-hermes.yaml @@ -10,13 +10,11 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - endpoint: http://127.0.0.1:17671 - engine: unix:///var/run/docker.sock - image: - ghcr.io/nvidia/openshell/gateway@sha256:ea14aa4db0980fab4769fb6b5509ac42ae3dc8495e645b1ba1fe1ada49892fa6 - networkCIDR: 172.20.0.0/24 + target: + docker: + endpoint: http://127.0.0.1:17671 + engine: unix:///var/run/docker.sock + networkCidr: 172.20.0.0/24 services: ollama-server: kind: ollama diff --git a/examples/managed-ollama-gpu.yaml b/examples/managed-ollama-gpu.yaml index 0a27bffb6e1..d07f2b3ba0c 100644 --- a/examples/managed-ollama-gpu.yaml +++ b/examples/managed-ollama-gpu.yaml @@ -10,13 +10,11 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - endpoint: http://127.0.0.1:17681 - engine: unix:///var/run/docker.sock - image: - ghcr.io/nvidia/openshell/gateway@sha256:ea14aa4db0980fab4769fb6b5509ac42ae3dc8495e645b1ba1fe1ada49892fa6 - networkCIDR: 172.30.110.0/24 + target: + docker: + endpoint: http://127.0.0.1:17681 + engine: unix:///var/run/docker.sock + networkCidr: 172.30.110.0/24 services: qwen: kind: ollama diff --git a/examples/managed-ollama.yaml b/examples/managed-ollama.yaml index 84f0ccb80ef..fa06ea603dd 100644 --- a/examples/managed-ollama.yaml +++ b/examples/managed-ollama.yaml @@ -10,13 +10,11 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - endpoint: http://127.0.0.1:17671 - engine: unix:///var/run/docker.sock - image: - ghcr.io/nvidia/openshell/gateway@sha256:ea14aa4db0980fab4769fb6b5509ac42ae3dc8495e645b1ba1fe1ada49892fa6 - networkCIDR: 172.20.0.0/24 + target: + docker: + endpoint: http://127.0.0.1:17671 + engine: unix:///var/run/docker.sock + networkCidr: 172.20.0.0/24 services: ollama-server: kind: ollama diff --git a/examples/managed-podman.yaml b/examples/managed-podman.yaml index c73d7f1cdee..2b5272258e5 100644 --- a/examples/managed-podman.yaml +++ b/examples/managed-podman.yaml @@ -12,10 +12,10 @@ metadata: spec: gateway: management: managed - runtime: - provider: podman - engine: unix:///run/user/1000/podman/podman.sock - endpoint: http://127.0.0.1:17681 + target: + podman: + engine: unix:///run/user/1000/podman/podman.sock + endpoint: http://127.0.0.1:17681 inferenceProviders: - name: local provider: openai diff --git a/examples/multiple-sandboxes.yaml b/examples/multiple-sandboxes.yaml index c156e148f23..c1c95fb35db 100644 --- a/examples/multiple-sandboxes.yaml +++ b/examples/multiple-sandboxes.yaml @@ -10,9 +10,9 @@ metadata: spec: gateway: management: external - runtime: - provider: docker endpoint: http://127.0.0.1:17681 + target: + docker: {} inferenceProviders: - name: local provider: openai diff --git a/examples/nemotron-amd64.yaml b/examples/nemotron-amd64.yaml index 0012ed0831b..8a46d57ff4a 100644 --- a/examples/nemotron-amd64.yaml +++ b/examples/nemotron-amd64.yaml @@ -9,9 +9,9 @@ metadata: spec: gateway: management: external - runtime: - provider: podman endpoint: http://127.0.0.1:17697 + target: + podman: {} services: nemotron: kind: vllm diff --git a/examples/onboarding/openclaw.yaml b/examples/onboarding/openclaw.yaml index 19bca1be871..d23451072d9 100644 --- a/examples/onboarding/openclaw.yaml +++ b/examples/onboarding/openclaw.yaml @@ -10,8 +10,8 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker + target: + docker: {} inferenceProviders: - name: nvidia-prod provider: openai diff --git a/examples/openclaw-dashboard.yaml b/examples/openclaw-dashboard.yaml index 8095eb6a73c..a3fa4bc7413 100644 --- a/examples/openclaw-dashboard.yaml +++ b/examples/openclaw-dashboard.yaml @@ -10,11 +10,11 @@ metadata: spec: gateway: management: external - # Replace with the Docker or Podman engine holding the sandbox image. - engine: unix:///var/run/docker.sock - runtime: - provider: docker endpoint: http://127.0.0.1:17671 + target: + docker: + # Replace with the engine holding the sandbox image; for a Podman gateway, use the podman key. + engine: unix:///var/run/docker.sock inferenceProviders: - name: local provider: openai diff --git a/examples/openshift/external-gateway.yaml b/examples/openshift/external-gateway.yaml index 1f14e364d05..88d9803db6f 100644 --- a/examples/openshift/external-gateway.yaml +++ b/examples/openshift/external-gateway.yaml @@ -14,14 +14,15 @@ spec: # Supply the existing OpenShift cluster's OpenShell gateway. gateway: management: external - runtime: - provider: openshift endpoint: https://openshell.example.com credential: {env: GATEWAY_TOKEN} tls: ca: {env: GATEWAY_CA} certificate: {env: GATEWAY_CERT} key: {env: GATEWAY_KEY} + target: + # OpenShift gateways report the upstream Kubernetes driver. + kubernetes: {} inferenceProviders: - name: inference provider: openai diff --git a/examples/openshift/managed-development.yaml b/examples/openshift/managed-development.yaml index 75a63b66e95..1b0e2fef12f 100644 --- a/examples/openshift/managed-development.yaml +++ b/examples/openshift/managed-development.yaml @@ -15,16 +15,16 @@ metadata: spec: gateway: management: managed - runtime: - provider: openshift - # The SDK opens this loopback tunnel only for the duration of each command. - endpoint: https://127.0.0.1:17671 - kubernetes: - kubeconfig: {env: NEMOCLAW_CLUSTER_KUBECONFIG} - context: replace-with-explicit-openshift-context - namespace: nemoclaw-openshift-development - authentication: - profile: development + target: + kubernetes: + distribution: openshift + # The SDK opens this loopback tunnel only for the duration of each command. + endpoint: https://127.0.0.1:17671 + kubeconfig: {env: NEMOCLAW_CLUSTER_KUBECONFIG} + context: replace-with-explicit-openshift-context + namespace: nemoclaw-openshift-development + authentication: + profile: development inferenceProviders: - name: hosted-nvidia provider: openai diff --git a/examples/spark/deepagents-team.yaml b/examples/spark/deepagents-team.yaml index 27e8e886812..4cda9ff4697 100644 --- a/examples/spark/deepagents-team.yaml +++ b/examples/spark/deepagents-team.yaml @@ -11,10 +11,10 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - endpoint: http://127.0.0.1:17802 - networkCIDR: 172.30.162.0/24 + target: + docker: + endpoint: http://127.0.0.1:17802 + networkCidr: 172.30.162.0/24 services: local: kind: vllm diff --git a/examples/spark/local-and-hosted.yaml b/examples/spark/local-and-hosted.yaml index 0b8b5bb6363..3f7ff5daa54 100644 --- a/examples/spark/local-and-hosted.yaml +++ b/examples/spark/local-and-hosted.yaml @@ -11,10 +11,10 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - endpoint: http://127.0.0.1:17805 - networkCIDR: 172.30.165.0/24 + target: + docker: + endpoint: http://127.0.0.1:17805 + networkCidr: 172.30.165.0/24 services: local: kind: vllm diff --git a/examples/spark/pi-small.yaml b/examples/spark/pi-small.yaml index 0855827d292..c508992fca7 100644 --- a/examples/spark/pi-small.yaml +++ b/examples/spark/pi-small.yaml @@ -11,10 +11,10 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - endpoint: http://127.0.0.1:17801 - networkCIDR: 172.30.161.0/24 + target: + docker: + endpoint: http://127.0.0.1:17801 + networkCidr: 172.30.161.0/24 services: local: kind: vllm diff --git a/examples/spark/remote-vllm.yaml b/examples/spark/remote-vllm.yaml index e75c31a4fb2..9096d554927 100644 --- a/examples/spark/remote-vllm.yaml +++ b/examples/spark/remote-vllm.yaml @@ -9,9 +9,9 @@ metadata: spec: gateway: management: external - runtime: - provider: podman endpoint: http://127.0.0.1:17697 + target: + podman: {} services: qwen: kind: vllm diff --git a/examples/spark/shared-model.yaml b/examples/spark/shared-model.yaml index ccf033d4ec9..08d70debe28 100644 --- a/examples/spark/shared-model.yaml +++ b/examples/spark/shared-model.yaml @@ -11,10 +11,10 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - endpoint: http://127.0.0.1:17803 - networkCIDR: 172.30.163.0/24 + target: + docker: + endpoint: http://127.0.0.1:17803 + networkCidr: 172.30.163.0/24 services: shared: kind: vllm diff --git a/examples/spark/spark-inline.yaml b/examples/spark/spark-inline.yaml index 9ec475af7a9..2e34278718d 100644 --- a/examples/spark/spark-inline.yaml +++ b/examples/spark/spark-inline.yaml @@ -11,13 +11,11 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - endpoint: http://127.0.0.1:17705 - engine: unix:///var/run/docker.sock - image: - ghcr.io/nvidia/openshell/gateway@sha256:ea14aa4db0980fab4769fb6b5509ac42ae3dc8495e645b1ba1fe1ada49892fa6 - networkCIDR: 172.30.125.0/24 + target: + docker: + endpoint: http://127.0.0.1:17705 + engine: unix:///var/run/docker.sock + networkCidr: 172.30.125.0/24 services: qwen: kind: vllm diff --git a/examples/spark/two-models.yaml b/examples/spark/two-models.yaml index 18902a86e1c..c9e56deeba3 100644 --- a/examples/spark/two-models.yaml +++ b/examples/spark/two-models.yaml @@ -11,10 +11,10 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - endpoint: http://127.0.0.1:17804 - networkCIDR: 172.30.164.0/24 + target: + docker: + endpoint: http://127.0.0.1:17804 + networkCidr: 172.30.164.0/24 services: fast: kind: vllm diff --git a/examples/spark/vllm.yaml b/examples/spark/vllm.yaml index 41d57610fa9..f76f9312c16 100644 --- a/examples/spark/vllm.yaml +++ b/examples/spark/vllm.yaml @@ -9,13 +9,11 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - endpoint: http://127.0.0.1:17695 - engine: unix:///var/run/docker.sock - image: - ghcr.io/nvidia/openshell/gateway@sha256:ea14aa4db0980fab4769fb6b5509ac42ae3dc8495e645b1ba1fe1ada49892fa6 - networkCIDR: 172.30.121.0/24 + target: + docker: + endpoint: http://127.0.0.1:17695 + engine: unix:///var/run/docker.sock + networkCidr: 172.30.121.0/24 services: qwen: kind: vllm diff --git a/examples/station/shared-model.yaml b/examples/station/shared-model.yaml index facc274df0a..e98ba95707c 100644 --- a/examples/station/shared-model.yaml +++ b/examples/station/shared-model.yaml @@ -11,13 +11,11 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - endpoint: http://127.0.0.1:17697 - engine: unix:///var/run/docker.sock - image: - ghcr.io/nvidia/openshell/gateway@sha256:ea14aa4db0980fab4769fb6b5509ac42ae3dc8495e645b1ba1fe1ada49892fa6 - networkCIDR: 172.30.132.0/24 + target: + docker: + endpoint: http://127.0.0.1:17697 + engine: unix:///var/run/docker.sock + networkCidr: 172.30.132.0/24 services: shared: kind: vllm diff --git a/examples/station/vllm.yaml b/examples/station/vllm.yaml index af5287944b9..ecfd06f4c98 100644 --- a/examples/station/vllm.yaml +++ b/examples/station/vllm.yaml @@ -9,13 +9,11 @@ metadata: spec: gateway: management: managed - runtime: - provider: docker - endpoint: http://127.0.0.1:17696 - engine: unix:///var/run/docker.sock - image: - ghcr.io/nvidia/openshell/gateway@sha256:ea14aa4db0980fab4769fb6b5509ac42ae3dc8495e645b1ba1fe1ada49892fa6 - networkCIDR: 172.30.131.0/24 + target: + docker: + endpoint: http://127.0.0.1:17696 + engine: unix:///var/run/docker.sock + networkCidr: 172.30.131.0/24 services: qwen: kind: vllm diff --git a/schemas/nemoclaw-v1alpha1.schema.json b/schemas/nemoclaw-v1alpha1.schema.json index 6fd70ed6f98..fe4b68f0f28 100644 --- a/schemas/nemoclaw-v1alpha1.schema.json +++ b/schemas/nemoclaw-v1alpha1.schema.json @@ -322,6 +322,26 @@ ], "type": "object" }, + "ExternalEngine": { + "additionalProperties": false, + "description": "Engine holding sandbox images for an existing Docker or Podman gateway.", + "properties": { + "engine": { + "description": "Engine containing the sandbox images, used only for image metadata inspection. Required for deployment planning; omission permits retained-state teardown.", + "type": "string" + } + }, + "type": "object" + }, + "ExternalKubernetes": { + "additionalProperties": false, + "description": "An existing Kubernetes or OpenShift gateway takes no target settings; sandbox image metadata replaces engine inspection.", + "properties": {}, + "type": "object", + "x-nemoclaw-removed-fields": { + "distribution": "distribution applies only to a managed gateway's spec.gateway.target.kubernetes; an existing gateway reports only the kubernetes driver" + } + }, "ExternalOllama": { "additionalProperties": false, "description": "External Ollama daemon observed by the managed proxy installer.", @@ -362,6 +382,53 @@ ], "type": "object" }, + "ExternalTarget": { + "description": "Exactly one target key: docker, podman, or kubernetes.", + "oneOf": [ + { + "additionalProperties": false, + "description": "The existing gateway runs sandboxes on Docker.", + "properties": { + "docker": { + "$ref": "#/$defs/ExternalEngine", + "description": "The existing gateway runs sandboxes on Docker." + } + }, + "required": [ + "docker" + ], + "type": "object" + }, + { + "additionalProperties": false, + "description": "The existing gateway runs sandboxes on Podman.", + "properties": { + "podman": { + "$ref": "#/$defs/ExternalEngine", + "description": "The existing gateway runs sandboxes on Podman." + } + }, + "required": [ + "podman" + ], + "type": "object" + }, + { + "additionalProperties": false, + "description": "The existing gateway runs sandboxes on Kubernetes, including OpenShift. Sandboxes need explicit images with metadata, and managed inference services are excluded.", + "properties": { + "kubernetes": { + "$ref": "#/$defs/ExternalKubernetes", + "description": "The existing gateway runs sandboxes on Kubernetes, including OpenShift. Sandboxes need explicit images with metadata, and managed inference services are excluded." + } + }, + "required": [ + "kubernetes" + ], + "type": "object" + } + ] + }, "File": { "additionalProperties": false, "description": "One immutable file in a model snapshot.", @@ -421,175 +488,35 @@ "oneOf": [ { "additionalProperties": false, - "allOf": [ - { - "if": { - "properties": { - "runtime": { - "properties": { - "provider": { - "const": "podman" - } - }, - "required": [ - "provider" - ] - } - }, - "required": [ - "runtime" - ] - }, - "then": { - "properties": { - "engine": { - "minLength": 1 - } - }, - "required": [ - "engine" - ], - "x-nemoclaw-error": "Podman requires spec.gateway.engine to name its local API service socket." - } - } - ], - "description": "A gateway installed and managed by this deployment.\nManaged Podman targets local rootless Linux; rootful, remote, and other platforms are unqualified.", - "else": { - "properties": { - "endpoint": { - "anyOf": [ - { - "const": "" - }, - { - "pattern": "^http://127\\.0\\.0\\.1:[0-9]+/?$" - } - ], - "default": "http://127.0.0.1:17681" - }, - "engine": { - "anyOf": [ - { - "const": "" - }, - { - "pattern": "^unix:///" - } - ], - "default": "unix:///var/run/docker.sock" - }, - "image": { - "default": "ghcr.io/nvidia/openshell/gateway@sha256:ea14aa4db0980fab4769fb6b5509ac42ae3dc8495e645b1ba1fe1ada49892fa6", - "enum": [ - "", - "ghcr.io/nvidia/openshell/gateway@sha256:ea14aa4db0980fab4769fb6b5509ac42ae3dc8495e645b1ba1fe1ada49892fa6" - ] - }, - "networkCIDR": { - "anyOf": [ - { - "const": "" - }, - { - "pattern": "/24$" - } - ], - "x-nemoclaw-default-rule": "Omitted or empty selects 172.30.N.0/24, where N is the first byte of SHA-256(metadata.uid)." - } - }, - "required": [] - }, - "if": { - "required": [ - "kubernetes" - ] - }, + "description": "A gateway installed and managed by this deployment.", "properties": { - "endpoint": { - "default": "http://127.0.0.1:17681", - "description": "Local engine gateways use an HTTP origin with an unprivileged loopback port. Kubernetes requires `https://127.0.0.1:PORT` with an explicit nonzero port and no trailing slash; commands forward that local port to the owned gateway.", - "type": "string", - "x-nemoclaw-default-rule": "Without kubernetes, omitted or empty selects the local HTTP endpoint. Kubernetes requires an explicit HTTPS loopback endpoint and port." - }, - "engine": { - "default": "unix:///var/run/docker.sock", - "description": "Managed local gateway Unix engine socket; Podman requires its API service socket. Excluded by kubernetes.", - "type": "string", - "x-nemoclaw-default-rule": "With runtime.provider docker, omitted or empty selects Docker's default socket. Podman requires its API service socket. Excluded by kubernetes." - }, - "image": { - "default": "ghcr.io/nvidia/openshell/gateway@sha256:ea14aa4db0980fab4769fb6b5509ac42ae3dc8495e645b1ba1fe1ada49892fa6", - "description": "Managed local gateway image pinned by the SDK. Excluded by kubernetes, whose component images are also SDK-pinned.", - "type": "string", - "x-nemoclaw-default-rule": "Without kubernetes, omitted or empty selects the SDK default. Excluded by kubernetes." - }, - "imagePullPolicy": { - "$ref": "#/$defs/ImagePullPolicy", - "description": "Image acquisition before local container creation. Docker accepts IfNotPresent (the default) or Never; Podman also accepts Always before creation or restart. Excluded by kubernetes." - }, - "kubernetes": { - "$ref": "#/$defs/ManagedKubernetes", - "description": "Explicit Kubernetes provisioning target. Excludes local engine, image, imagePullPolicy, and networkCIDR settings and requires Kubernetes sandboxes without managed inference services." - }, "management": { "const": "managed", "description": "Whether this deployment manages the gateway.", "type": "string" }, - "networkCIDR": { - "description": "Canonical private IPv4 /24 for a managed local gateway. Excluded by kubernetes.", - "type": "string", - "x-nemoclaw-default-rule": "Without kubernetes, omitted or empty selects 172.30.N.0/24, where N is the first byte of SHA-256(metadata.uid). Excluded by kubernetes." - }, - "runtime": { - "$ref": "#/$defs/Runtime", - "description": "Compute driver the gateway runs every sandbox with; omission selects Docker." + "target": { + "$ref": "#/$defs/ManagedTarget", + "default": { + "docker": {} + }, + "description": "Where the gateway runs. The key selects the compute driver for every sandbox; omission selects a local Docker engine." } }, "required": [ "management" ], - "then": { - "allOf": [ - { - "not": { - "anyOf": [ - { - "required": [ - "engine" - ] - }, - { - "required": [ - "image" - ] - }, - { - "required": [ - "imagePullPolicy" - ] - }, - { - "required": [ - "networkCIDR" - ] - } - ] - } - } - ], - "properties": { - "endpoint": { - "pattern": "^https://127\\.0\\.0\\.1:(?:[1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$(?![\\s\\S])" - } - }, - "required": [ - "endpoint" - ], - "x-nemoclaw-error": "managed Kubernetes requires an explicit HTTPS 127.0.0.1 endpoint with a nonzero port and excludes local engine settings" - }, "title": "Managed gateway", - "type": "object" + "type": "object", + "x-nemoclaw-removed-fields": { + "endpoint": "spec.gateway.endpoint of a managed gateway moved to the endpoint of its spec.gateway.target key", + "engine": "spec.gateway.engine moved to spec.gateway.target.docker.engine or spec.gateway.target.podman.engine", + "image": "spec.gateway.image is removed because the SDK pins the gateway image", + "imagePullPolicy": "spec.gateway.imagePullPolicy moved to spec.gateway.target.docker or spec.gateway.target.podman", + "kubernetes": "spec.gateway.kubernetes moved to spec.gateway.target.kubernetes", + "networkCIDR": "spec.gateway.networkCIDR moved to networkCidr under spec.gateway.target.docker or spec.gateway.target.podman", + "runtime": "spec.gateway.runtime is replaced by the key under spec.gateway.target: docker, podman, or kubernetes" + } }, { "additionalProperties": false, @@ -614,18 +541,17 @@ "pattern": "^https?://", "type": "string" }, - "engine": { - "description": "Engine containing Docker or Podman sandbox images, used only for image metadata inspection. Required for their deployment planning; omission permits retained-state teardown. Kubernetes and OpenShift use image.metadata instead.", - "type": "string" - }, "management": { "const": "external", "description": "Whether this deployment manages the gateway.", "type": "string" }, - "runtime": { - "$ref": "#/$defs/Runtime", - "description": "Compute driver the existing gateway runs; omission selects Docker. Planning checks it against the driver the gateway reports." + "target": { + "$ref": "#/$defs/ExternalTarget", + "default": { + "docker": {} + }, + "description": "The key selects the compute driver that runs every sandbox; omission selects Docker. Planning checks it against the driver the gateway reports." }, "tls": { "$ref": "#/$defs/TLS", @@ -653,7 +579,11 @@ } }, "title": "External gateway", - "type": "object" + "type": "object", + "x-nemoclaw-removed-fields": { + "engine": "spec.gateway.engine moved to spec.gateway.target.docker.engine or spec.gateway.target.podman.engine", + "runtime": "spec.gateway.runtime is replaced by the key under spec.gateway.target: docker, podman, or kubernetes" + } } ] }, @@ -719,7 +649,8 @@ "properties": { "metadata": { "$ref": "#/$defs/FileRef", - "description": "Environment reference to the absolute path of a local OCI metadata bundle for `ref`; required for Kubernetes and OpenShift, where no local engine can be inspected. Destroy does not read it. Its index, manifest, configuration, and Fabric catalog are verified against `ref` before use. The bundle holds no image layers or credentials. Docker and Podman inspect their engine instead." + "description": "Environment reference to the absolute path of a local OCI metadata bundle for `ref`. A Kubernetes target requires it because no local engine can be inspected; Docker and Podman targets inspect their engine instead and reject it. Destroy does not read it. Its index, manifest, configuration, and Fabric catalog are verified against `ref` before use. The bundle holds no image layers or credentials.", + "x-nemoclaw-required": "With a Kubernetes target" }, "ref": { "anyOf": [ @@ -730,10 +661,10 @@ "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._:/-]*@sha256:[a-f0-9]{64}$" } ], - "description": "Immutable image reference. Kubernetes and OpenShift require an explicit nonempty reference. For other drivers, omitted or empty selects the generic SDK agent image pin; verify that it contains the selected Fabric adapter.", + "description": "Immutable image reference pinned by digest.", "type": "string", - "x-nemoclaw-default-rule": "Kubernetes and OpenShift require an explicit immutable image reference. For other drivers, omitted or empty selects the generic SDK agent image pin; verify that it contains the selected Fabric adapter.", - "x-nemoclaw-required": "For Kubernetes sandboxes" + "x-nemoclaw-default-rule": "A Kubernetes target requires an explicit immutable image reference. For Docker and Podman targets, omitted or empty selects the generic SDK agent image pin; verify that it contains the selected Fabric adapter.", + "x-nemoclaw-required": "With a Kubernetes target" } }, "type": "object" @@ -1062,9 +993,79 @@ ], "type": "object" }, + "ManagedDocker": { + "additionalProperties": false, + "description": "Local Docker engine settings for a managed gateway.", + "properties": { + "endpoint": { + "anyOf": [ + { + "const": "" + }, + { + "pattern": "^http://127\\.0\\.0\\.1:[0-9]+/?$" + } + ], + "default": "http://127.0.0.1:17681", + "description": "Gateway HTTP origin with the 127.0.0.1 loopback address and an unprivileged port.", + "type": "string", + "x-nemoclaw-default-rule": "Omitted or empty selects the default.", + "x-nemoclaw-error": "a Docker or Podman gateway endpoint is http://127.0.0.1:PORT with an unprivileged port" + }, + "engine": { + "anyOf": [ + { + "const": "" + }, + { + "pattern": "^unix:///" + } + ], + "default": "unix:///var/run/docker.sock", + "description": "Docker engine Unix socket.", + "type": "string", + "x-nemoclaw-default-rule": "Omitted or empty selects the default." + }, + "imagePullPolicy": { + "default": "IfNotPresent", + "description": "Gateway image acquisition before container creation: IfNotPresent (the default) or Never.", + "oneOf": [ + { + "const": "IfNotPresent", + "description": "Pull only when the pinned image is absent from the selected engine.", + "type": "string" + }, + { + "const": "Never", + "description": "Use only a local image. Fail if it is absent from the selected engine.", + "type": "string" + } + ] + }, + "networkCidr": { + "anyOf": [ + { + "const": "" + }, + { + "pattern": "/24$" + } + ], + "description": "Canonical private IPv4 /24 for the gateway network.", + "type": "string", + "x-nemoclaw-default-rule": "Omitted or empty selects 172.30.N.0/24, where N is the first byte of SHA-256(metadata.uid).", + "x-nemoclaw-error": "networkCidr must be a canonical private IPv4 /24" + } + }, + "type": "object", + "x-nemoclaw-removed-fields": { + "image": "spec.gateway.target.docker takes no image because the SDK pins the gateway image", + "networkCIDR": "spec.gateway.target.docker spells networkCIDR as networkCidr" + } + }, "ManagedKubernetes": { "additionalProperties": false, - "description": "Explicit existing-cluster target for a managed development gateway. The SDK does not create a cluster or select an ambient context, and installs nothing cluster-wide: Agent Sandbox and a default StorageClass must already exist. `runtime.provider: openshift` selects the OpenShift profile.", + "description": "Explicit existing-cluster target for a managed development gateway. The SDK does not create a cluster or select an ambient context, and installs nothing cluster-wide: Agent Sandbox and a default StorageClass must already exist.", "properties": { "authentication": { "$ref": "#/$defs/KubernetesAuthentication", @@ -1077,6 +1078,28 @@ "pattern": "^[^\\x00-\\x20\\x7f]+$(?![\\s\\S])", "type": "string" }, + "distribution": { + "default": "kubernetes", + "description": "Cluster distribution. `openshift` makes the SDK wait up to 30 seconds for OpenShift to assign the namespace its SCC UID range, read the first UID and the first supplemental group (the UID when no supplemental groups are assigned), record that namespace identity, pass it to the gateway chart as security-context values, and bind the `openshift` compute driver. Sandboxes use the upstream Kubernetes driver either way.", + "oneOf": [ + { + "const": "kubernetes", + "description": "Upstream Kubernetes.", + "type": "string" + }, + { + "const": "openshift", + "description": "OpenShift, which assigns namespace user and group IDs.", + "type": "string" + } + ] + }, + "endpoint": { + "description": "Local HTTPS origin `https://127.0.0.1:PORT` with an explicit nonzero port and no trailing slash. Commands forward that local port to the owned gateway.", + "pattern": "^https://127\\.0\\.0\\.1:(?:[1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$(?![\\s\\S])", + "type": "string", + "x-nemoclaw-error": "managed Kubernetes requires an explicit HTTPS 127.0.0.1 endpoint with a nonzero port and no path" + }, "environment": { "description": "Caller environment variables that the kubeconfig's exec credential plugin needs, such as `AWS_PROFILE` for an EKS cluster. Cluster operations receive only platform variables and these; they are resolved like credential references and never written to configuration or state.", "items": { @@ -1192,6 +1215,7 @@ } }, "required": [ + "endpoint", "kubeconfig", "context", "namespace", @@ -1199,6 +1223,108 @@ ], "type": "object" }, + "ManagedPodman": { + "additionalProperties": false, + "description": "Local rootless Linux Podman engine settings for a managed gateway.", + "properties": { + "endpoint": { + "anyOf": [ + { + "const": "" + }, + { + "pattern": "^http://127\\.0\\.0\\.1:[0-9]+/?$" + } + ], + "default": "http://127.0.0.1:17681", + "description": "Gateway HTTP origin with the 127.0.0.1 loopback address and an unprivileged port.", + "type": "string", + "x-nemoclaw-default-rule": "Omitted or empty selects the default.", + "x-nemoclaw-error": "a Docker or Podman gateway endpoint is http://127.0.0.1:PORT with an unprivileged port" + }, + "engine": { + "description": "Podman API service Unix socket. It depends on the host user, so it has no default.", + "minLength": 1, + "pattern": "^unix:///", + "type": "string", + "x-nemoclaw-error": "Podman requires spec.gateway.target.podman.engine to name its local API service socket" + }, + "imagePullPolicy": { + "$ref": "#/$defs/ImagePullPolicy", + "default": "IfNotPresent", + "description": "Gateway image acquisition: Always before creation or restart, IfNotPresent (the default), or Never." + }, + "networkCidr": { + "anyOf": [ + { + "const": "" + }, + { + "pattern": "/24$" + } + ], + "description": "Canonical private IPv4 /24 for the gateway network.", + "type": "string", + "x-nemoclaw-default-rule": "Omitted or empty selects 172.30.N.0/24, where N is the first byte of SHA-256(metadata.uid).", + "x-nemoclaw-error": "networkCidr must be a canonical private IPv4 /24" + } + }, + "required": [ + "engine" + ], + "type": "object", + "x-nemoclaw-removed-fields": { + "image": "spec.gateway.target.podman takes no image because the SDK pins the gateway image", + "networkCIDR": "spec.gateway.target.podman spells networkCIDR as networkCidr" + } + }, + "ManagedTarget": { + "description": "Exactly one target key: docker, podman, or kubernetes.", + "oneOf": [ + { + "additionalProperties": false, + "description": "Install the gateway on a local Docker engine.", + "properties": { + "docker": { + "$ref": "#/$defs/ManagedDocker", + "description": "Install the gateway on a local Docker engine." + } + }, + "required": [ + "docker" + ], + "type": "object" + }, + { + "additionalProperties": false, + "description": "Install the gateway on a local rootless Linux Podman engine. Rootful, remote, and other platforms are unqualified.", + "properties": { + "podman": { + "$ref": "#/$defs/ManagedPodman", + "description": "Install the gateway on a local rootless Linux Podman engine. Rootful, remote, and other platforms are unqualified." + } + }, + "required": [ + "podman" + ], + "type": "object" + }, + { + "additionalProperties": false, + "description": "Install the gateway in an explicit existing Kubernetes cluster. Sandboxes need explicit images with metadata, and managed inference services are excluded.", + "properties": { + "kubernetes": { + "$ref": "#/$defs/ManagedKubernetes", + "description": "Install the gateway in an explicit existing Kubernetes cluster. Sandboxes need explicit images with metadata, and managed inference services are excluded." + } + }, + "required": [ + "kubernetes" + ], + "type": "object" + } + ] + }, "Manifest": { "additionalProperties": false, "description": "Pinned model snapshot inventory. The parser rejects duplicate files and file/directory conflicts.", @@ -2178,24 +2304,6 @@ ], "type": "object" }, - "Runtime": { - "additionalProperties": false, - "description": "The compute driver an OpenShell gateway runs sandboxes with. One gateway runs one driver.", - "properties": { - "provider": { - "default": "docker", - "description": "Docker, Podman, Kubernetes, or OpenShift profile. Kubernetes and OpenShift require an external gateway or an explicit managed cluster target, and external inference endpoints. OpenShift uses the upstream Kubernetes driver with namespace-assigned identities. A managed service with Podman requires explicit service placement.", - "enum": [ - "docker", - "podman", - "kubernetes", - "openshift" - ], - "type": "string" - } - }, - "type": "object" - }, "Sandbox": { "additionalProperties": false, "allOf": [ @@ -2251,8 +2359,8 @@ }, "image": { "$ref": "#/$defs/Image", - "description": "Kubernetes requires an explicit immutable agent image compatible with the gateway's runtime user and group IDs. For other drivers, omission selects the generic SDK agent image pin; verify that it contains the selected Fabric adapter.", - "x-nemoclaw-required": "For Kubernetes sandboxes" + "description": "Agent image compatible with the gateway's runtime user and group IDs. A Kubernetes target requires an explicit `ref` and `metadata`; Docker and Podman targets may omit it and use the generic SDK agent image pin.", + "x-nemoclaw-required": "With a Kubernetes target" }, "inferenceProviders": { "description": "Named inference definitions visible to this sandbox's routes. Names must not shadow deployment definitions.", @@ -3341,162 +3449,6 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, "allOf": [ - { - "if": { - "not": { - "properties": { - "spec": { - "properties": { - "gateway": { - "properties": { - "runtime": { - "properties": { - "provider": { - "const": "podman" - } - }, - "required": [ - "provider" - ] - } - }, - "required": [ - "runtime" - ] - } - }, - "required": [ - "gateway" - ] - } - }, - "required": [ - "spec" - ] - } - }, - "then": { - "properties": { - "spec": { - "properties": { - "gateway": { - "properties": { - "imagePullPolicy": { - "enum": [ - "IfNotPresent", - "Never" - ] - } - } - } - } - } - } - } - }, - { - "if": { - "properties": { - "spec": { - "properties": { - "gateway": { - "properties": { - "management": { - "const": "managed" - } - }, - "required": [ - "management" - ] - } - }, - "required": [ - "gateway" - ] - } - }, - "required": [ - "spec" - ] - }, - "then": { - "else": { - "properties": { - "spec": { - "properties": { - "gateway": { - "properties": { - "runtime": { - "properties": { - "provider": { - "enum": [ - "docker", - "podman" - ] - } - } - } - } - } - } - } - } - }, - "if": { - "properties": { - "spec": { - "properties": { - "gateway": { - "required": [ - "kubernetes" - ] - } - }, - "required": [ - "gateway" - ] - } - }, - "required": [ - "spec" - ] - }, - "then": { - "properties": { - "spec": { - "properties": { - "gateway": { - "properties": { - "runtime": { - "properties": { - "provider": { - "enum": [ - "kubernetes", - "openshift" - ] - } - }, - "required": [ - "provider" - ] - } - }, - "required": [ - "runtime" - ] - } - }, - "required": [ - "gateway" - ] - } - }, - "required": [ - "spec" - ] - } - } - }, { "else": { "properties": { @@ -3521,7 +3473,8 @@ } } } - } + }, + "x-nemoclaw-error": "image.metadata is available only for a spec.gateway.target.kubernetes gateway; Docker and Podman use engine image inspection" }, "if": { "properties": { @@ -3529,22 +3482,14 @@ "properties": { "gateway": { "properties": { - "runtime": { - "properties": { - "provider": { - "enum": [ - "kubernetes", - "openshift" - ] - } - }, + "target": { "required": [ - "provider" + "kubernetes" ] } }, "required": [ - "runtime" + "target" ] } }, @@ -3589,7 +3534,8 @@ }, "required": [ "spec" - ] + ], + "x-nemoclaw-error": "a Kubernetes target requires each sandbox image.ref pinned by digest and image.metadata" } }, { @@ -3599,22 +3545,14 @@ "properties": { "gateway": { "properties": { - "runtime": { - "properties": { - "provider": { - "enum": [ - "kubernetes", - "openshift" - ] - } - }, + "target": { "required": [ - "provider" + "kubernetes" ] } }, "required": [ - "runtime" + "target" ] } }, @@ -3629,59 +3567,6 @@ }, "then": { "allOf": [ - { - "anyOf": [ - { - "properties": { - "spec": { - "properties": { - "gateway": { - "properties": { - "management": { - "const": "external" - } - }, - "required": [ - "management" - ] - } - }, - "required": [ - "gateway" - ] - } - }, - "required": [ - "spec" - ] - }, - { - "properties": { - "spec": { - "properties": { - "gateway": { - "properties": { - "management": { - "const": "managed" - } - }, - "required": [ - "management", - "kubernetes" - ] - } - }, - "required": [ - "gateway" - ] - } - }, - "required": [ - "spec" - ] - } - ] - }, { "properties": { "spec": { @@ -3694,7 +3579,7 @@ } } ], - "x-nemoclaw-error": "Kubernetes requires an external gateway or an explicit managed Kubernetes target, and external inference endpoints; managed services are not supported" + "x-nemoclaw-error": "a Kubernetes target requires external inference endpoints; managed services are not supported" } } ], @@ -3730,7 +3615,7 @@ "x-nemoclaw-parser-checks": [ "Document::parse rejects YAML aliases, anchors, merge keys, all explicit tags (including core tags such as !!binary), duplicate keys, multiple documents, and input larger than 1 MiB. It applies the compiled input schema before defaulting; Document::validate applies the normalized schema and semantic checks, including for directly constructed Rust values.", "The parser checks endpoint transport and address policy, managed gateway port bounds, canonical private IPv4 /24 networks, local engine socket syntax, and publication address/port/network agreement.", - "Managed Kubernetes requires explicit kubeconfig environment, context, namespace, and development authentication profile; Agent Sandbox and one default StorageClass must already be installed. Its HTTPS endpoint is exactly 127.0.0.1 with an explicit port from 1 through 65535 and no path. Local engine fields and managed inference services are excluded; gateway.runtime.provider is kubernetes or openshift. OpenShift uses the upstream Kubernetes driver and requires platform-owned OpenShift security prerequisites. Cluster identity, ownership, prerequisite compatibility, and credential files are checked during operations.", + "A managed Kubernetes target requires explicit kubeconfig environment, context, namespace, and development authentication profile; Agent Sandbox and one default StorageClass must already be installed. Its HTTPS endpoint is exactly 127.0.0.1 with an explicit port from 1 through 65535 and no path. A Kubernetes target, managed or external, excludes managed inference services. The openshift distribution uses the upstream Kubernetes driver and requires platform-owned OpenShift security prerequisites. Cluster identity, ownership, prerequisite compatibility, and credential files are checked during operations.", "Explicit sandbox policies are also checked by the pinned OpenShell policy parser and validator, including protocol-specific rule semantics, process identities, filesystem paths, and destination address restrictions.", "Explicit filesystem grants must permit reads of the packaged Fabric runtime and NemoClaw bridge directories; parent and read-write grants count. This parser check does not inspect images, resolve symlinks, or establish runtime permissions.", "The schema requires an explicit default for multiple model choices. Rust checks unique route names, that the default names a route, and that native model and tool fields have valid structural shapes. Fabric validates adapter-specific combinations.", From a9d11e3f797f10e20091d2a872965884a28cc34e Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Tue, 13 Oct 2026 22:04:36 +0000 Subject: [PATCH 5/9] refactor(config)!: key sandboxes and inference providers by name `spec.sandboxes` and both `inferenceProviders` collections were arrays, unlike `harnesses`, `inferences`, `integrations`, and `services`. Rust had to enforce name uniqueness, onboarding addressed the sandbox as `/spec/sandboxes/0`, overlays would patch by index, and authored order leaked into export and status output while identity ignored it. - `spec.sandboxes`, `spec.inferenceProviders`, and `spec.sandboxes..inferenceProviders` are maps. The key replaces `name` and keeps its pattern; a deployment holds 1 to 32 sandboxes. - Inline route providers keep a required `name`, because they have no key and their name feeds the provider registration. - Keys order nothing: export, apply health, and diagnostics list sandboxes and providers by name. Schema diagnostics show a key only when it is a valid name and point at the rejected key's own line. - Onboarding addresses the sole sandbox and its providers by key, asks no sandbox-name question, rejects a template whose sandbox key is not a name, and never prints such a key. OpenTofu addresses, provider registration keys, Fabric data-source numbering, and every other compiled identity match the list form for the same names across all examples. Document digests change. The OpenShell contract fixtures for multiple-sandboxes and tavily-web-search are regenerated: the fixture check numbered sandboxes in authored order while compile numbers them by name, so two checked-in fixtures carried swapped adapter bindings. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Hai Nguyen --- .../examples/print_journey_tree.rs | 12 +- crates/nemoclaw-authoring/src/deployment.rs | 142 +++++-- .../src/discovery_queries.rs | 4 +- .../src/journey_definition.rs | 85 +++-- .../nemoclaw-authoring/src/journey_state.rs | 41 +- .../src/journey_state/answer.rs | 11 +- .../src/journey_state/authored_values.rs | 65 +++- .../src/journey_state/mutation.rs | 11 +- .../src/journey_state/observations.rs | 4 +- .../src/journey_state/paths.rs | 22 +- .../resolver/adapter_questions.rs | 18 +- .../resolver/deployment_questions.rs | 2 +- .../resolver/inference_questions.rs | 6 +- .../resolver/native_questions.rs | 3 +- .../resolver/schema_questions.rs | 16 +- .../journey_state/resolver/sdk_questions.rs | 9 +- .../src/journey_state/selection.rs | 27 +- crates/nemoclaw-authoring/src/lib.rs | 2 + .../src/partial_document.rs | 11 +- crates/nemoclaw-authoring/src/pointer.rs | 82 ++++ crates/nemoclaw-authoring/src/sdk_schema.rs | 32 +- crates/nemoclaw-authoring/src/settings.rs | 4 +- .../src/target_assessment.rs | 6 +- .../tests/deployment_journey.rs | 91 ++++- .../tests/fixtures/minimum-inline.yaml | 5 +- .../tests/journey_authoring_boundaries.rs | 69 +++- .../tests/journey_decision_status.rs | 2 +- .../nemoclaw-authoring/tests/journey_edits.rs | 44 ++- .../tests/journey_guidance.rs | 196 +++++++++- .../tests/journey_resolution.rs | 356 ++++++++++-------- .../tests/journey_tree_preview.rs | 70 ++-- .../tests/onboarding_journey_presets.rs | 37 +- .../tests/partial_documents.rs | 14 +- crates/nemoclaw-authoring/tests/support.rs | 4 +- .../tests/target_assessment.rs | 11 +- .../tests/target_prerequisites.rs | 2 +- crates/nemoclaw-build/src/ci/live.rs | 4 +- crates/nemoclaw-build/src/schema/reference.rs | 23 ++ crates/nemoclaw-build/tests/ci.rs | 8 +- crates/nemoclaw-cli/tests/commands.rs | 4 +- .../fixtures/hermes-nvidia-hosted/v1.yaml | 4 +- .../fixtures/openclaw-nvidia-hosted/v1.yaml | 4 +- crates/nemoclaw-e2e/src/image_runtime.rs | 14 +- crates/nemoclaw-e2e/tests/brev.rs | 4 +- crates/nemoclaw-e2e/tests/deployment.rs | 162 ++++---- .../tests/docker_provider_proxy.rs | 2 +- crates/nemoclaw-e2e/tests/dummy_agent.rs | 6 +- .../nemoclaw-e2e/tests/export_observations.rs | 40 +- .../nemoclaw-e2e/tests/fabric_deployment.rs | 98 +++-- crates/nemoclaw-e2e/tests/fabric_live.rs | 7 +- crates/nemoclaw-e2e/tests/helm_recovery.rs | 3 +- crates/nemoclaw-e2e/tests/hosted_parity.rs | 62 ++- .../nemoclaw-e2e/tests/inference_discovery.rs | 7 +- crates/nemoclaw-e2e/tests/kubernetes_live.rs | 7 +- crates/nemoclaw-e2e/tests/managed_gateway.rs | 8 +- crates/nemoclaw-e2e/tests/model_live.rs | 7 +- .../nemoclaw-e2e/tests/multiple_providers.rs | 8 +- .../tests/openshell_contract_fixtures.rs | 4 +- crates/nemoclaw-e2e/tests/remote_service.rs | 25 +- .../tests/service_images/support.rs | 13 +- crates/nemoclaw-e2e/tests/shared_service.rs | 2 +- crates/nemoclaw-e2e/tests/spark.rs | 14 +- crates/nemoclaw-e2e/tests/web_search.rs | 23 +- crates/nemoclaw-onboarding/src/lib.rs | 71 +++- crates/nemoclaw-onboarding/src/tui/app.rs | 4 +- crates/nemoclaw-onboarding/src/tui/labels.rs | 83 +++- crates/nemoclaw-onboarding/src/tui/tests.rs | 64 +++- crates/nemoclaw-onboarding/src/tui/text.json | 3 - crates/nemoclaw-onboarding/src/tui/view.rs | 8 +- .../tests/contract/discovery.rs | 2 +- crates/nemoclaw-runtime/src/schema.rs | 27 ++ crates/nemoclaw-sdk/src/compile.rs | 44 +-- crates/nemoclaw-sdk/src/config/inference.rs | 2 +- .../nemoclaw-sdk/src/config/integrations.rs | 22 +- crates/nemoclaw-sdk/src/config/mod.rs | 31 +- crates/nemoclaw-sdk/src/config/providers.rs | 157 ++++---- crates/nemoclaw-sdk/src/config/references.rs | 119 +++--- .../nemoclaw-sdk/src/config/schema/runtime.rs | 146 ++++++- .../src/config/schema/validation.rs | 69 ++-- crates/nemoclaw-sdk/src/config/types.rs | 38 +- crates/nemoclaw-sdk/src/config/validation.rs | 13 +- crates/nemoclaw-sdk/src/config/yaml_source.rs | 19 +- crates/nemoclaw-sdk/src/deployment/apply.rs | 6 +- crates/nemoclaw-sdk/src/deployment/export.rs | 26 +- .../nemoclaw-sdk/src/deployment/reporting.rs | 15 +- .../src/deployment/runtime/teardown.rs | 27 +- crates/nemoclaw-sdk/src/deployment/tests.rs | 53 ++- crates/nemoclaw-sdk/src/discovery.rs | 7 +- crates/nemoclaw-sdk/src/discovery_graph.rs | 11 +- .../nemoclaw-sdk/src/fabric_capabilities.rs | 6 +- crates/nemoclaw-sdk/src/fabric_config.rs | 14 +- crates/nemoclaw-sdk/src/image_runtime.rs | 6 +- .../nemoclaw-sdk/src/inference_discovery.rs | 2 +- .../src/services/authentication.rs | 2 +- crates/nemoclaw-sdk/src/services/registry.rs | 2 +- crates/nemoclaw-sdk/src/state/tests.rs | 52 ++- crates/nemoclaw-sdk/tests/agent_tools.rs | 52 ++- crates/nemoclaw-sdk/tests/compile.rs | 36 +- crates/nemoclaw-sdk/tests/config.rs | 198 +++++++--- crates/nemoclaw-sdk/tests/config_choices.rs | 1 - .../nemoclaw-sdk/tests/config_diagnostics.rs | 83 +++- crates/nemoclaw-sdk/tests/config_input.rs | 61 ++- crates/nemoclaw-sdk/tests/config_kinds.rs | 11 +- .../nemoclaw-sdk/tests/config_kubernetes.rs | 55 +-- crates/nemoclaw-sdk/tests/config_openshift.rs | 9 +- crates/nemoclaw-sdk/tests/config_scenarios.rs | 206 +++++++--- crates/nemoclaw-sdk/tests/config_schema.rs | 292 ++++++++++++-- .../nemoclaw-sdk/tests/config_validation.rs | 21 +- crates/nemoclaw-sdk/tests/discovery_graph.rs | 5 +- .../nemoclaw-sdk/tests/execution_settings.rs | 9 +- crates/nemoclaw-sdk/tests/fabric_planner.rs | 32 +- .../tests/fixtures/config/fabric-claude.yaml | 36 +- .../tests/fixtures/config/fabric-pi.yaml | 52 +-- .../tests/fixtures/config/fabric.yaml | 36 +- .../tests/fixtures/config/local.yaml | 36 +- .../tests/fixtures/config/managed-ollama.yaml | 36 +- .../tests/fixtures/config/spark.yaml | 36 +- .../nemoclaw-sdk/tests/harness_references.rs | 48 ++- .../tests/inference_connection.rs | 21 +- .../nemoclaw-sdk/tests/inference_discovery.rs | 12 +- .../tests/inference_references.rs | 34 +- .../nemoclaw-sdk/tests/inference_settings.rs | 44 ++- crates/nemoclaw-sdk/tests/interfaces.rs | 7 +- .../nemoclaw-sdk/tests/kubernetes_compile.rs | 3 +- .../tests/kubernetes_managed_compile.rs | 3 +- crates/nemoclaw-sdk/tests/managed_hermes.rs | 2 +- crates/nemoclaw-sdk/tests/managed_podman.rs | 8 +- crates/nemoclaw-sdk/tests/model_selection.rs | 5 +- crates/nemoclaw-sdk/tests/multiple_models.rs | 29 +- .../nemoclaw-sdk/tests/multiple_providers.rs | 53 +-- .../nemoclaw-sdk/tests/multiple_sandboxes.rs | 124 ++---- crates/nemoclaw-sdk/tests/native_inference.rs | 25 +- crates/nemoclaw-sdk/tests/nemotron_serving.rs | 2 +- crates/nemoclaw-sdk/tests/network_config.rs | 59 +-- crates/nemoclaw-sdk/tests/observability.rs | 5 +- crates/nemoclaw-sdk/tests/ollama_proxy.rs | 32 +- .../nemoclaw-sdk/tests/provider_references.rs | 65 ++-- .../tests/reference_combinations.rs | 29 +- .../tests/reference_diagnostics.rs | 30 +- .../nemoclaw-sdk/tests/resource_management.rs | 6 +- .../nemoclaw-sdk/tests/service_references.rs | 11 +- crates/nemoclaw-sdk/tests/spark_examples.rs | 4 +- crates/nemoclaw-sdk/tests/support/config.rs | 20 + .../tests/support/scripted_tofu.rs | 3 +- crates/nemoclaw-sdk/tests/web_search.rs | 121 +++--- .../fixtures/multiple-sandboxes.tf.json | 4 +- .../fixtures/tavily-web-search.tf.json | 4 +- docs/build.md | 4 +- docs/configuration-references.md | 34 +- docs/contributing/configuration-schema.md | 2 +- docs/design/onboarding-journeys.md | 7 +- docs/get-started.md | 8 +- docs/inference.md | 10 +- docs/models.md | 2 +- docs/reference/configuration.md | 142 +++---- docs/sandbox-network.md | 2 +- docs/troubleshooting.md | 2 +- docs/usage.md | 17 +- examples/explicit-policy.yaml | 4 +- examples/fabric-claude.yaml | 4 +- examples/fabric-codex.yaml | 4 +- examples/fabric-hermes.yaml | 4 +- examples/fabric-mini-swe-agent.yaml | 4 +- examples/fabric-nooa-bench.yaml | 4 +- examples/fabric-nooa.yaml | 4 +- examples/fabric-openclaw.yaml | 4 +- examples/fabric-pi.yaml | 4 +- examples/fabric-remote-agent.yaml | 4 +- examples/fabric.yaml | 4 +- examples/full-featured-openclaw.yaml | 8 +- examples/hermes-auth.yaml | 4 +- examples/hermes-interfaces.yaml | 4 +- examples/inference-tuning.yaml | 4 +- examples/inline-inference.yaml | 2 +- examples/kubernetes/external-gateway.yaml | 8 +- examples/kubernetes/hosted-nvidia.yaml | 8 +- examples/kubernetes/managed-development.yaml | 8 +- examples/local.yaml | 4 +- examples/managed-hermes.yaml | 4 +- examples/managed-ollama-gpu.yaml | 4 +- examples/managed-ollama.yaml | 4 +- examples/managed-podman.yaml | 4 +- examples/multiple-models.yaml | 6 +- examples/multiple-providers.yaml | 8 +- examples/multiple-sandboxes.yaml | 12 +- examples/nemotron-amd64.yaml | 4 +- examples/onboarding/openclaw.yaml | 4 +- examples/openclaw-dashboard.yaml | 4 +- examples/openclaw-web-search.yaml | 6 +- examples/openshift/external-gateway.yaml | 8 +- examples/openshift/managed-development.yaml | 8 +- examples/spark/deepagents-team.yaml | 6 +- examples/spark/local-and-hosted.yaml | 6 +- examples/spark/pi-small.yaml | 4 +- examples/spark/remote-vllm.yaml | 4 +- examples/spark/shared-model.yaml | 8 +- examples/spark/spark-inline.yaml | 4 +- examples/spark/two-models.yaml | 6 +- examples/spark/vllm.yaml | 4 +- examples/station/shared-model.yaml | 6 +- examples/station/vllm.yaml | 4 +- examples/tavily-web-search.yaml | 6 +- schemas/nemoclaw-v1alpha1.schema.json | 196 ++++++++-- 203 files changed, 3947 insertions(+), 2053 deletions(-) create mode 100644 crates/nemoclaw-authoring/src/pointer.rs diff --git a/crates/nemoclaw-authoring/examples/print_journey_tree.rs b/crates/nemoclaw-authoring/examples/print_journey_tree.rs index 069a912cdab..04bdf7b4771 100644 --- a/crates/nemoclaw-authoring/examples/print_journey_tree.rs +++ b/crates/nemoclaw-authoring/examples/print_journey_tree.rs @@ -17,7 +17,7 @@ fn main() -> Result<(), Box> { let capabilities = Capabilities::from_catalog(&catalog); let minimum = PartialDocument::from_yaml( - b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nspec:\n sandboxes:\n - {}\n", + b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nspec:\n sandboxes:\n assistant: {}\n", )?; let minimum = JourneyDefinition::new("minimum viable values", minimum) .ask(["/metadata/name"]) @@ -41,7 +41,7 @@ fn main() -> Result<(), Box> { let mut guided_values: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml"))?; guided_values - .pointer_mut("/spec/sandboxes/0/agent/inference/routes/0/overrides") + .pointer_mut("/spec/sandboxes/assistant/agent/inference/routes/0/overrides") .and_then(serde_json::Value::as_object_mut) .expect("bundled example has one model route") .remove("model"); @@ -49,11 +49,11 @@ fn main() -> Result<(), Box> { let guided = JourneyDefinition::new("guided preview", guided) .ask([ "/metadata/name", - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", "/spec/gateway/target", - "/spec/inferenceProviders/0/provider", - "/spec/inferenceProviders/0/api", - "/spec/sandboxes/0/agent/inference/routes/0/overrides/model", + "/spec/inferenceProviders/nvidia-prod/provider", + "/spec/inferenceProviders/nvidia-prod/api", + "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model", ]) .omit([JourneyScope::ActiveAdapterSettings]); println!(); diff --git a/crates/nemoclaw-authoring/src/deployment.rs b/crates/nemoclaw-authoring/src/deployment.rs index 1947aca9152..d192e7dca10 100644 --- a/crates/nemoclaw-authoring/src/deployment.rs +++ b/crates/nemoclaw-authoring/src/deployment.rs @@ -6,9 +6,12 @@ use crate::{ Diagnostics, diagnostics::diagnostic, + journey_definition::sandbox_path, + pointer::{escape, replace_entry_keys}, sdk_schema::{finite_choices, sdk_field_schema_for}, settings::SettingQuestion, }; +use nemoclaw_sdk::config::valid_name; use serde_json::Value; pub(crate) fn deployment_questions_for_values( @@ -17,45 +20,61 @@ pub(crate) fn deployment_questions_for_values( active_routes: Option<&str>, ) -> Result, Diagnostics> { let mut questions = Vec::new(); - collect(values, values, "", &mut questions, 0)?; + let sandbox = sandbox_path(values); + collect(values, values, "", sandbox.as_deref(), &mut questions, 0)?; questions.retain(|question| { - (!question.path.contains("/execution/") + let fields = fields(&question.path); + (!fields.contains("/execution/") || active_harness .is_some_and(|base| question.path.starts_with(&format!("{base}/execution/")))) - && (!question.path.contains("/routes/") + && (!fields.contains("/routes/") || active_routes.is_some_and(|base| question.path.starts_with(&format!("{base}/")))) }); Ok(questions) } -fn escaped(part: &str) -> String { - part.replace('~', "~0").replace('/', "~1") +/// `path` with the names of sandboxes, services, harnesses, and other named +/// definitions replaced by `*`, so a check for a field never matches a name. +fn fields(path: &str) -> String { + replace_entry_keys(path, |_| "*".into()) +} + +/// `path` relative to `sandbox`, the pointer to the journey's only sandbox, or +/// `None` when `path` is outside that sandbox. +fn in_sandbox<'a>(path: &'a str, sandbox: Option<&str>) -> Option<&'a str> { + path.strip_prefix(sandbox?) + .filter(|rest| rest.is_empty() || rest.starts_with('/')) } // These are deployment-owned editing regions, not a second description of their fields // or constraints. Native settings and model/provider choices have separate owner views. -fn region(path: &str) -> bool { +fn region(path: &str, sandbox: Option<&str>) -> bool { + let fields = fields(path); path.starts_with("/spec/gateway/") || path.starts_with("/spec/services/") - || path.starts_with("/spec/sandboxes/0/image/") - || path.starts_with("/spec/sandboxes/0/network/") - || path.starts_with("/spec/sandboxes/0/agent/auth/") - || path.starts_with("/spec/sandboxes/0/harness/execution/") - || (path.contains("/routes/") && path.ends_with("/overrides/maxTokens")) - || (path.contains("/harnesses/") && path.contains("/execution/")) + || in_sandbox(path, sandbox).is_some_and(|rest| { + rest.starts_with("/image/") + || rest.starts_with("/network/") + || rest.starts_with("/agent/auth/") + || rest.starts_with("/harness/execution/") + }) + || (fields.contains("/routes/") && fields.ends_with("/overrides/maxTokens")) + || (fields.contains("/harnesses/") && fields.contains("/execution/")) } fn excluded(path: &str) -> bool { - path.ends_with("/management") - || (path.starts_with("/spec/services/") && path.ends_with("/kind")) + let fields = fields(path); + fields.ends_with("/management") + || (path.starts_with("/spec/services/") && fields.ends_with("/kind")) } -fn complex(path: &str) -> bool { - (path.starts_with("/spec/services/") && path.ends_with("/recipe")) - || path == "/spec/sandboxes/0/network/policy" +fn complex(path: &str, sandbox: Option<&str>) -> bool { + (path.starts_with("/spec/services/") && fields(path).ends_with("/recipe")) + || in_sandbox(path, sandbox) == Some("/network/policy") } fn collect( root: &Value, value: &Value, path: &str, + sandbox: Option<&str>, out: &mut Vec, depth: usize, ) -> Result<(), Diagnostics> { @@ -65,12 +84,12 @@ fn collect( "Deployment question depth exceeded.", )); } - if value.is_null() || !interested(path) { + if value.is_null() || !interested(path, sandbox) { return Ok(()); } - if region(path) + if region(path, sandbox) && !excluded(path) - && (!value.is_object() && !value.is_array() || complex(path) || value.is_array()) + && (!value.is_object() && !value.is_array() || complex(path, sandbox) || value.is_array()) { let Some((schema, required)) = sdk_field_schema_for(root, path) else { // A `false` schema accepts no value, so the only answer is to omit @@ -109,14 +128,22 @@ fn collect( collect( root, child, - &format!("{path}/{}", escaped(key)), + &format!("{path}/{}", escape(key)), + sandbox, out, depth + 1, )?; } } else if let Some(array) = value.as_array() { for (index, child) in array.iter().enumerate() { - collect(root, child, &format!("{path}/{index}"), out, depth + 1)?; + collect( + root, + child, + &format!("{path}/{index}"), + sandbox, + out, + depth + 1, + )?; } } Ok(()) @@ -135,6 +162,10 @@ fn title(path: &str) -> String { } result } + // A key the SDK rejects as a name is not shown. + let path = replace_entry_keys(path, |key| { + if valid_name(key) { key } else { "[entry]" }.to_owned() + }); let parts: Vec<_> = path.split('/').filter(|part| !part.is_empty()).collect(); let (prefix, rest) = if parts.get(1) == Some(&"gateway") { ("Gateway".to_owned(), &parts[2..]) @@ -158,25 +189,60 @@ fn title(path: &str) -> String { ) } -fn interested(path: &str) -> bool { - [ +fn interested(path: &str, sandbox: Option<&str>) -> bool { + let fields = fields(path); + // A path is inside a root or an ancestor that leads to one. + let near = |root: &str| { + path == root + || path.starts_with(&format!("{root}/")) + || root.starts_with(&format!("{path}/")) + }; + ([ "/spec/gateway", "/spec/services", - "/spec/sandboxes/0/image", - "/spec/sandboxes/0/network", - "/spec/sandboxes/0/agent/auth", - "/spec/sandboxes/0/harness/execution", - "/spec/sandboxes/0/agent/inference", "/spec/inferences", - "/spec/sandboxes/0/inferences", "/spec/harnesses", - "/spec/sandboxes/0/harnesses", ] - .iter() - .any(|root| { - path == *root - || path.starts_with(&format!("{root}/")) - || root.starts_with(&format!("{path}/")) - }) && !path.contains("/settings") - && !path.contains("/config") + .into_iter() + .any(near) + || sandbox.is_some_and(|sandbox| { + [ + "/image", + "/network", + "/agent/auth", + "/harness/execution", + "/agent/inference", + "/inferences", + "/harnesses", + ] + .into_iter() + .any(|region| near(&format!("{sandbox}{region}"))) + })) + && !fields.contains("/settings") + && !fields.contains("/config") +} + +#[cfg(test)] +mod tests { + use super::title; + + #[test] + fn a_title_shows_a_definition_key_only_when_it_is_a_name() { + for (path, expected) in [ + ( + "/spec/services/qwen/serving/port", + "Service qwen: serving / port", + ), + ( + "/spec/services/PRIVATE INVALID NAME/image", + "Service [entry]: image", + ), + ( + "/spec/harnesses/PRIVATE INVALID NAME/execution/timeoutSeconds", + "Deployment: harnesses / [entry] / execution / timeout Seconds", + ), + ] { + assert_eq!(title(path), expected); + } + } } diff --git a/crates/nemoclaw-authoring/src/discovery_queries.rs b/crates/nemoclaw-authoring/src/discovery_queries.rs index 4375cefb817..2746afaae11 100644 --- a/crates/nemoclaw-authoring/src/discovery_queries.rs +++ b/crates/nemoclaw-authoring/src/discovery_queries.rs @@ -15,7 +15,7 @@ pub fn inference_request_for_document( document: &Document, route_name: Option<&str>, ) -> Result, Diagnostics> { - let [sandbox] = document.spec.sandboxes.as_slice() else { + let Some(sandbox) = crate::journey_definition::sole_sandbox(document) else { return Err(crate::diagnostics::diagnostic( "sandbox", "Inference discovery requires one sandbox.", @@ -33,7 +33,7 @@ pub fn inference_request_for_document( let provider = document .sandbox_route_provider(sandbox, route) .map_err(|error| crate::diagnostics::diagnostic("provider", &error.to_string()))?; - EndpointRequest::for_external_provider(provider) + EndpointRequest::for_external_provider(provider.definition) .map_err(|error| crate::diagnostics::diagnostic("provider", &error.to_string())) } diff --git a/crates/nemoclaw-authoring/src/journey_definition.rs b/crates/nemoclaw-authoring/src/journey_definition.rs index 0ce7c6f250b..3ab9a082ce7 100644 --- a/crates/nemoclaw-authoring/src/journey_definition.rs +++ b/crates/nemoclaw-authoring/src/journey_definition.rs @@ -3,6 +3,7 @@ //! Sparse values and deliberate question guidance for one onboarding journey. +use nemoclaw_sdk::config::{Document, valid_name}; use serde_json::Value; use std::collections::BTreeSet; @@ -13,10 +14,35 @@ use crate::{ }; pub(crate) const NAME: &str = "/metadata/name"; -pub(crate) const HARNESS: &str = "/spec/sandboxes/0/harness/kind"; -pub(crate) const SETTINGS: &str = "/spec/sandboxes/0/harness/settings"; pub(crate) const INFERENCE_PRESET: &str = "inference:preset"; +/// The pointer to the journey's only sandbox, `/spec/sandboxes/`, when +/// `/spec/sandboxes` holds exactly one object and its key is a valid name. +/// Questions address the sandbox by this key, so a key the SDK rejects never +/// becomes part of a question ID. +pub(crate) fn sandbox_path(values: &Value) -> Option { + let sandboxes = values.pointer("/spec/sandboxes")?.as_object()?; + let [(name, sandbox)] = sandboxes.iter().collect::>()[..] else { + return None; + }; + (sandbox.is_object() && valid_name(name)).then(|| format!("/spec/sandboxes/{name}")) +} + +/// The pointer to the inline harness kind of the journey's only sandbox, +/// which is also the ID of the harness question. +pub(crate) fn harness_field(values: &Value) -> Option { + sandbox_path(values).map(|sandbox| format!("{sandbox}/harness/kind")) +} + +/// The name of a one-sandbox document's sandbox; `None` for any other count. +pub(crate) fn sole_sandbox(document: &Document) -> Option<&str> { + let mut names = document.spec.sandboxes.keys(); + match (names.next(), names.next()) { + (Some(name), None) => Some(name), + _ => None, + } +} + /// A schema-discovered family of applicable questions. The schema determines /// which fields exist and whether they are required; this only asks to review /// supplied values in that family. @@ -134,19 +160,13 @@ impl JourneyDefinition { /// Start mutable resolution over the sparse v1 single-sandbox envelope. pub fn start(&self, capabilities: &Capabilities) -> Result { - self.validate_guidance(capabilities)?; - if !self - .base - .supplied() - .pointer("/spec/sandboxes") - .and_then(Value::as_array) - .is_some_and(|sandboxes| sandboxes.len() == 1 && sandboxes[0].is_object()) - { + if sandbox_path(self.base.supplied()).is_none() { return Err(diagnostic( "journey", - "The v1 journey requires exactly one sandbox object.", + "The v1 journey requires exactly one sandbox keyed by a lowercase name.", )); } + self.validate_guidance(capabilities)?; crate::JourneyState::new(self.clone()) } @@ -173,10 +193,37 @@ impl JourneyDefinition { &format!("scope {scope:?} cannot be omitted in this preview"), )); } + let supplied = self.base.supplied(); + let sandbox = sandbox_path(supplied); + let harness = harness_field(supplied); for field in &self.ask { - if field == NAME || field == HARNESS || field == INFERENCE_PRESET { + if field == NAME || Some(field) == harness.as_ref() || field == INFERENCE_PRESET { continue; } + // A field of another sandbox or of an absent provider would add + // that entry when answered. + let entry = |collection: &str| { + let rest = field.strip_prefix(collection)?.strip_prefix('/')?; + Some(rest.split_once('/').map_or(rest, |(key, _)| key)) + }; + if let Some(key) = entry("/spec/sandboxes") + && sandbox.as_ref() != Some(&format!("/spec/sandboxes/{key}")) + { + return Err(diagnostic( + "journey", + "asked fields must belong to the journey's sandbox", + )); + } + if let Some(key) = entry("/spec/inferenceProviders") + && supplied + .pointer(&format!("/spec/inferenceProviders/{key}")) + .is_none() + { + return Err(diagnostic( + "journey", + "asked provider fields must belong to a supplied provider", + )); + } if sdk_field_schema_for(self.base.supplied(), field).is_some() || sdk_field_possible(field) { @@ -231,16 +278,10 @@ impl JourneyDefinition { "required adapter settings alternatives cannot be omitted", )); } - if self - .base - .supplied() - .pointer(HARNESS) - .and_then(Value::as_str) - == Some(adapter) - && self - .base - .supplied() - .pointer(&format!("{SETTINGS}{pointer}")) + if let (Some(sandbox), Some(harness)) = (&sandbox, &harness) + && supplied.pointer(harness).and_then(Value::as_str) == Some(adapter) + && supplied + .pointer(&format!("{sandbox}/harness/settings{pointer}")) .is_some() { return Err(diagnostic( diff --git a/crates/nemoclaw-authoring/src/journey_state.rs b/crates/nemoclaw-authoring/src/journey_state.rs index 936b7f4da25..ebabc616d27 100644 --- a/crates/nemoclaw-authoring/src/journey_state.rs +++ b/crates/nemoclaw-authoring/src/journey_state.rs @@ -20,9 +20,10 @@ use crate::{ diagnostics::diagnostic, identity::new_deployment_uid, journey_definition::{ - HARNESS, INFERENCE_PRESET, JourneyDefinition, JourneyScope, NAME, adapter_field, - adapter_schema, native_field, + INFERENCE_PRESET, JourneyDefinition, JourneyScope, NAME, adapter_field, adapter_schema, + harness_field, native_field, sandbox_path, }, + pointer::escape, sdk_schema::{ finite_choices, sdk_discriminator, sdk_exclusive_required_fields, sdk_field_possible, sdk_field_schema, sdk_field_schema_for, sdk_selected_branch, sdk_variant_key, @@ -32,7 +33,6 @@ use crate::{ }; const ROUTE_SELECTION: &str = "route:selection"; -const ROUTES: &str = "/spec/sandboxes/0/agent/inference/routes"; const GATEWAY_TARGET: &str = "/spec/gateway/target"; /// Why an applicable decision is still open. @@ -85,19 +85,17 @@ enum NativeSettingOwner { } impl QuestionTarget { - fn sdk(path: impl Into) -> Self { + /// The target of an SDK field question in a journey whose current values + /// are `values`. + fn sdk(values: &Value, path: impl Into) -> Self { let path = path.into(); if path == NAME { return Self::DeploymentName; } - if path == HARNESS { + if harness_field(values).as_ref() == Some(&path) { return Self::Harness; } - let segments = path.split('/').collect::>(); - let provider_field = segments.len() == 5 - && segments[1] == "spec" - && segments[2] == "inferenceProviders" - && segments[3].parse::().is_ok(); + let provider_field = provider_field(&path).map(|(_, field)| field); let target_field = path .strip_prefix(GATEWAY_TARGET) .and_then(|rest| rest.strip_prefix('/')) @@ -107,9 +105,9 @@ impl QuestionTarget { SdkFieldRole::GatewayManagement } else if target_field == Some("engine") { SdkFieldRole::GatewayEngine - } else if provider_field && segments[4] == "api" { + } else if provider_field == Some("api") { SdkFieldRole::ProviderApi - } else if provider_field && segments[4] == "endpoint" { + } else if provider_field == Some("endpoint") { SdkFieldRole::ProviderEndpoint } else { SdkFieldRole::Plain @@ -118,6 +116,21 @@ impl QuestionTarget { } } +/// The pointer to the deployment provider keyed `name`. +fn provider_path(name: &str) -> String { + format!("/spec/inferenceProviders/{}", escape(name)) +} + +/// The key of a deployment provider and the field that `path` names inside +/// it, for `/spec/inferenceProviders//`. +fn provider_field(path: &str) -> Option<(String, &str)> { + let (key, field) = path + .strip_prefix("/spec/inferenceProviders/")? + .split_once('/')?; + (!key.is_empty() && !field.contains('/')) + .then(|| (key.replace("~1", "/").replace("~0", "~"), field)) +} + /// One currently applicable decision in the bounded journey surface. #[derive(Clone, Debug, PartialEq)] pub struct JourneyQuestion { @@ -351,6 +364,6 @@ use authored_values::AuthoredValues; use decision_record::DecisionRecord; use journey_position::JourneyPosition; use paths::{ - escape_pointer, harness_kind, harness_path, managed_target_engine, native_value, routes_path, - scalar_question, settings_path, + harness_kind, harness_path, managed_target_engine, native_value, routes_path, scalar_question, + settings_path, }; diff --git a/crates/nemoclaw-authoring/src/journey_state/answer.rs b/crates/nemoclaw-authoring/src/journey_state/answer.rs index 2a5b097b4b2..dc50e6439a6 100644 --- a/crates/nemoclaw-authoring/src/journey_state/answer.rs +++ b/crates/nemoclaw-authoring/src/journey_state/answer.rs @@ -95,7 +95,7 @@ impl JourneyState { .filter_map(Value::as_str) .filter(|other| *other != selected) { - let field = format!("{path}/{}", escape_pointer(other)); + let field = format!("{path}/{}", escape(other)); candidate.authored.put_sdk_field(&field, None)?; candidate.decisions.accepted.remove(&field); } @@ -161,12 +161,7 @@ impl JourneyState { role, SdkFieldRole::ProviderApi | SdkFieldRole::ProviderEndpoint ) { - path.rsplit_once('/') - .and_then(|(base, _)| { - candidate.authored.values.pointer(&format!("{base}/name")) - }) - .and_then(Value::as_str) - .map(str::to_owned) + provider_field(path).map(|(provider, _)| provider) } else { None }; @@ -297,7 +292,7 @@ impl JourneyState { })?; previous .authored - .put_sdk_field(&format!("{path}/{}", escape_pointer(&selected)), None)?; + .put_sdk_field(&format!("{path}/{}", escape(&selected)), None)?; Some(Value::String(selected)) } QuestionTarget::VariantKey { path } => { diff --git a/crates/nemoclaw-authoring/src/journey_state/authored_values.rs b/crates/nemoclaw-authoring/src/journey_state/authored_values.rs index 74323e30685..c1d81792d31 100644 --- a/crates/nemoclaw-authoring/src/journey_state/authored_values.rs +++ b/crates/nemoclaw-authoring/src/journey_state/authored_values.rs @@ -75,18 +75,21 @@ impl AuthoredValues { { self.inactive_settings.insert(old.clone(), settings.clone()); } + let sandbox = sandbox_path(&self.values) + .ok_or_else(|| diagnostic("journey", "The v1 journey requires one sandbox object."))?; + let inline = format!("{sandbox}/harness"); let owner_path = harness_path(&self.values) .or_else(|| { position .selected_forms - .get("/spec/sandboxes/0") + .get(&sandbox) .filter(|form| *form == "harness") - .map(|_| "/spec/sandboxes/0/harness".into()) + .map(|_| inline.clone()) }) .ok_or_else(|| diagnostic("journey", "Harness is unavailable."))?; - let harness = if owner_path == "/spec/sandboxes/0/harness" { + let harness = if owner_path == inline { self.values - .pointer_mut("/spec/sandboxes/0") + .pointer_mut(&sandbox) .and_then(Value::as_object_mut) .ok_or_else(|| { diagnostic("journey", "The v1 journey requires one sandbox object.") @@ -183,6 +186,22 @@ impl AuthoredValues { if value.is_none() && self.values.pointer(parent).is_none() { return Ok(()); } + // The journey edits its one sandbox; a write never adds another. + let sandbox = pointer + .strip_prefix("/spec/sandboxes/") + .map(|rest| rest.split_once('/').map_or(rest, |(key, _)| key)); + if value.is_some() + && let Some(key) = sandbox + && self + .values + .pointer(&format!("/spec/sandboxes/{key}")) + .is_none() + { + return Err(diagnostic( + "journey", + "The v1 journey cannot add a sandbox.", + )); + } let mut current = &mut self.values; for segment in parent.split('/').skip(1) { let key = segment.replace("~1", "/").replace("~0", "~"); @@ -241,7 +260,7 @@ impl AuthoredValues { let mut inactive = Vec::new(); let mut active_objects = Vec::new(); for (key, value) in fields { - let field = format!("{parent}/{}", escape_pointer(key)); + let field = format!("{parent}/{}", escape(key)); if field == written || sdk_field_schema_for(before, &field).is_none() { continue; } @@ -297,15 +316,12 @@ impl AuthoredValues { .cloned() .unwrap_or_default(); self.put_sdk_field(pointer, Some(serde_json::json!({ key: {} })))?; - let selected = format!("{pointer}/{}", escape_pointer(key)); + let selected = format!("{pointer}/{}", escape(key)); let carried = settings .into_iter() .filter(|(name, value)| { - sdk_field_schema_for( - &self.values, - &format!("{selected}/{}", escape_pointer(name)), - ) - .is_some_and(|(schema, _)| schema_accepts(&schema, value) == Some(true)) + sdk_field_schema_for(&self.values, &format!("{selected}/{}", escape(name))) + .is_some_and(|(schema, _)| schema_accepts(&schema, value) == Some(true)) }) .collect::>(); self.put_sdk_field(&selected, Some(Value::Object(carried))) @@ -335,3 +351,30 @@ impl AuthoredValues { self.put_sdk_field(&path, engine) } } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn an_sdk_field_write_never_adds_a_sandbox() { + let original = json!({"spec": {"sandboxes": {"assistant": {"agent": {}}}}}); + let mut authored = AuthoredValues::new(original.clone()); + for pointer in ["/spec/sandboxes/other/agent/name", "/spec/sandboxes/other"] { + let error = authored + .put_sdk_field(pointer, Some(json!("main"))) + .unwrap_err() + .to_string(); + assert_eq!(error, "journey: The v1 journey cannot add a sandbox."); + assert_eq!(authored.values, original); + } + authored + .put_sdk_field("/spec/sandboxes/assistant/agent/name", Some(json!("main"))) + .unwrap(); + assert_eq!( + authored.values, + json!({"spec": {"sandboxes": {"assistant": {"agent": {"name": "main"}}}}}) + ); + } +} diff --git a/crates/nemoclaw-authoring/src/journey_state/mutation.rs b/crates/nemoclaw-authoring/src/journey_state/mutation.rs index 5c9b3774f1f..69411c6b99c 100644 --- a/crates/nemoclaw-authoring/src/journey_state/mutation.rs +++ b/crates/nemoclaw-authoring/src/journey_state/mutation.rs @@ -34,13 +34,13 @@ impl JourneyState { &mut self, preset: ProviderPreset, ) -> Result<(), Diagnostics> { - let (route_index, provider_index) = self.route_provider().ok_or_else(|| { + let (route_index, previous_name) = self.route_provider().ok_or_else(|| { diagnostic( "journey", "Inference presets require a selected route using an external provider.", ) })?; - let provider_path = format!("/spec/inferenceProviders/{provider_index}"); + let provider_path = provider_path(&previous_name); let route_path = format!( "{}/{route_index}", routes_path(&self.authored.values) @@ -48,13 +48,6 @@ impl JourneyState { ); let api_path = format!("{provider_path}/api"); let endpoint_path = format!("{provider_path}/endpoint"); - let previous_name = self - .authored - .values - .pointer(&format!("{provider_path}/name")) - .and_then(Value::as_str) - .ok_or_else(|| diagnostic("journey", "The shared provider needs a name."))? - .to_owned(); let previous = self.current_preset(); if previous == Some(preset) { self.decisions.selected_presets.insert(route_index, preset); diff --git a/crates/nemoclaw-authoring/src/journey_state/observations.rs b/crates/nemoclaw-authoring/src/journey_state/observations.rs index 76791c1eca7..8a8c204c68c 100644 --- a/crates/nemoclaw-authoring/src/journey_state/observations.rs +++ b/crates/nemoclaw-authoring/src/journey_state/observations.rs @@ -192,7 +192,9 @@ impl JourneyState { capabilities: &Capabilities, observations: &DiscoveryObservations, ) -> Result<(), Diagnostics> { - if !self.decisions.accepted.contains(HARNESS) { + if !harness_field(&self.authored.values) + .is_some_and(|field| self.decisions.accepted.contains(&field)) + { return Err(diagnostic( "delegation", "Choose a harness before delegating settings.", diff --git a/crates/nemoclaw-authoring/src/journey_state/paths.rs b/crates/nemoclaw-authoring/src/journey_state/paths.rs index aa83bc0ec99..4611ce237cd 100644 --- a/crates/nemoclaw-authoring/src/journey_state/paths.rs +++ b/crates/nemoclaw-authoring/src/journey_state/paths.rs @@ -22,27 +22,27 @@ pub(super) fn native_value<'a>( } pub(super) fn routes_path(values: &Value) -> Option { - let agent = values.pointer("/spec/sandboxes/0/agent")?; + let sandbox = sandbox_path(values)?; + let agent = values.pointer(&format!("{sandbox}/agent"))?; if agent.get("inference").is_some() { - return Some(ROUTES.into()); + return Some(format!("{sandbox}/agent/inference/routes")); } let reference = agent.get("inferenceRef")?.as_str()?; - let escaped = reference.replace('~', "~0").replace('/', "~1"); - let path = format!("/spec/inferences/{escaped}/routes"); + let path = format!("/spec/inferences/{}/routes", escape(reference)); values.pointer(&path).is_some().then_some(path) } pub(super) fn harness_path(values: &Value) -> Option { - let sandbox = values.pointer("/spec/sandboxes/0")?; + let path = sandbox_path(values)?; + let sandbox = values.pointer(&path)?; if let Some(reference) = sandbox.get("harnessRef").and_then(Value::as_str) { - let escaped = reference.replace('~', "~0").replace('/', "~1"); - let path = format!("/spec/harnesses/{escaped}"); + let path = format!("/spec/harnesses/{}", escape(reference)); return values.pointer(&path).is_some().then_some(path); } sandbox .get("harness") .is_some() - .then(|| "/spec/sandboxes/0/harness".into()) + .then(|| format!("{path}/harness")) } pub(super) fn harness_kind(values: &Value) -> Option<&str> { @@ -73,14 +73,10 @@ pub(super) fn managed_target_engine(values: &Value) -> Option<(String, String)> else { return None; }; - let engine = format!("{GATEWAY_TARGET}/{}/engine", escape_pointer(key)); + let engine = format!("{GATEWAY_TARGET}/{}/engine", escape(key)); sdk_field_schema_for(values, &engine).map(|_| (key.clone(), engine)) } -pub(super) fn escape_pointer(segment: &str) -> String { - segment.replace('~', "~0").replace('/', "~1") -} - pub(super) fn scalar_question(schema: &Value, choices: &[Value]) -> bool { matches!( schema["type"].as_str(), diff --git a/crates/nemoclaw-authoring/src/journey_state/resolver/adapter_questions.rs b/crates/nemoclaw-authoring/src/journey_state/resolver/adapter_questions.rs index 776e3babe79..91971a9e76e 100644 --- a/crates/nemoclaw-authoring/src/journey_state/resolver/adapter_questions.rs +++ b/crates/nemoclaw-authoring/src/journey_state/resolver/adapter_questions.rs @@ -13,13 +13,16 @@ impl QuestionResolver<'_> { let omitted = &mut work.omitted; let warnings = &mut work.warnings; let unverified = &mut work.unverified; + let sandbox = sandbox_path(&self.authored.values); + let harness_id = harness_field(&self.authored.values); let active_harness = harness_path(&self.authored.values).or_else(|| { + let sandbox = sandbox.as_ref()?; (self .position .selected_forms - .get("/spec/sandboxes/0") + .get(sandbox) .is_some_and(|form| form == "harness")) - .then(|| "/spec/sandboxes/0/harness".into()) + .then(|| format!("{sandbox}/harness")) }); let chosen = active_harness .as_ref() @@ -27,8 +30,9 @@ impl QuestionResolver<'_> { .and_then(Value::as_str); let harness_open = active_harness.is_some() && (chosen.is_none() - || (self.definition.ask.contains(HARNESS) - && !self.decisions.accepted.contains(HARNESS))); + || harness_id.as_ref().is_some_and(|field| { + self.definition.ask.contains(field) && !self.decisions.accepted.contains(field) + })); let reachable: Vec<&str> = if harness_open { capabilities .harnesses() @@ -52,10 +56,10 @@ impl QuestionResolver<'_> { warnings.push(format!("{field} is not reachable from {reason}")); } } - if harness_open { + if harness_open && let Some(harness_id) = harness_id { // Fabric supplies the active harness choices; replace the generic // SDK leaf question if sparse traversal found the same field. - questions.retain(|question| question.id != HARNESS); + questions.retain(|question| question.id != harness_id); if let Some(harness) = chosen && adapter_schema(capabilities, harness)?.is_none() { @@ -69,7 +73,7 @@ impl QuestionResolver<'_> { target: QuestionTarget::Harness, kind: JourneyQuestionKind::Field, reopened_because: None, - id: HARNESS.into(), + id: harness_id, reason: if chosen.is_none() { JourneyQuestionReason::Missing } else { diff --git a/crates/nemoclaw-authoring/src/journey_state/resolver/deployment_questions.rs b/crates/nemoclaw-authoring/src/journey_state/resolver/deployment_questions.rs index 6f750ed779c..6f861af4646 100644 --- a/crates/nemoclaw-authoring/src/journey_state/resolver/deployment_questions.rs +++ b/crates/nemoclaw-authoring/src/journey_state/resolver/deployment_questions.rs @@ -28,7 +28,7 @@ impl QuestionResolver<'_> { continue; } questions.push(JourneyQuestion { - target: QuestionTarget::sdk(field.path.clone()), + target: QuestionTarget::sdk(&self.authored.values, field.path.clone()), kind: JourneyQuestionKind::Field, reopened_because: None, id: field.path, diff --git a/crates/nemoclaw-authoring/src/journey_state/resolver/inference_questions.rs b/crates/nemoclaw-authoring/src/journey_state/resolver/inference_questions.rs index 5a86dd43aff..245ee2baae0 100644 --- a/crates/nemoclaw-authoring/src/journey_state/resolver/inference_questions.rs +++ b/crates/nemoclaw-authoring/src/journey_state/resolver/inference_questions.rs @@ -23,7 +23,7 @@ impl QuestionResolver<'_> { { let value = self.authored.values.pointer(&path); questions.push(JourneyQuestion { - target: QuestionTarget::sdk(path.clone()), + target: QuestionTarget::sdk(&self.authored.values, path.clone()), kind: JourneyQuestionKind::InferenceModel, reopened_because: None, id: path, @@ -136,7 +136,7 @@ impl QuestionResolver<'_> { let schema = policy.sdk_schema(&path, schema); let value = self.authored.values.pointer(&path); questions.push(JourneyQuestion { - target: QuestionTarget::sdk(path.clone()), + target: QuestionTarget::sdk(&self.authored.values, path.clone()), kind: JourneyQuestionKind::Field, reopened_because: None, id: path, @@ -162,7 +162,7 @@ impl QuestionResolver<'_> { .expect("external provider endpoint is in the SDK schema") .0; questions.push(JourneyQuestion { - target: QuestionTarget::sdk(endpoint.clone()), + target: QuestionTarget::sdk(&self.authored.values, endpoint.clone()), kind: JourneyQuestionKind::Field, reopened_because: None, id: endpoint.clone(), diff --git a/crates/nemoclaw-authoring/src/journey_state/resolver/native_questions.rs b/crates/nemoclaw-authoring/src/journey_state/resolver/native_questions.rs index 6e2d23a7173..82f21061505 100644 --- a/crates/nemoclaw-authoring/src/journey_state/resolver/native_questions.rs +++ b/crates/nemoclaw-authoring/src/journey_state/resolver/native_questions.rs @@ -198,7 +198,8 @@ pub(super) fn native_questions_for_values( } } if let (Some(schema), Some(document)) = (capabilities.model_schemas.get(harness_id), document) { - let sandbox = &document.spec.sandboxes[0]; + let sandbox = crate::journey_definition::sole_sandbox(document) + .ok_or_else(|| diagnostic("journey", "The v1 journey requires one sandbox object."))?; let inference = document .sandbox_inference(sandbox) .map_err(|error| diagnostic("journey", &error.to_string()))?; diff --git a/crates/nemoclaw-authoring/src/journey_state/resolver/schema_questions.rs b/crates/nemoclaw-authoring/src/journey_state/resolver/schema_questions.rs index 8f76c9c24c9..7a805dda59f 100644 --- a/crates/nemoclaw-authoring/src/journey_state/resolver/schema_questions.rs +++ b/crates/nemoclaw-authoring/src/journey_state/resolver/schema_questions.rs @@ -17,14 +17,13 @@ pub(super) fn collect_required_leaf_questions( return; } if let Some((discriminator, _)) = sdk_discriminator(schema) { - let escaped = discriminator.replace('~', "~0").replace('/', "~1"); - let choice_path = format!("{path}/{escaped}"); + let choice_path = format!("{path}/{}", escape(&discriminator)); if let Some((choice_schema, _)) = sdk_field_schema_for(values, &choice_path) { let supplied = values.pointer(&choice_path); if !supplied.is_some_and(|value| schema_accepts(&choice_schema, value) == Some(true)) { if !questions.iter().any(|question| question.id == choice_path) { questions.push(JourneyQuestion { - target: QuestionTarget::sdk(choice_path.clone()), + target: QuestionTarget::sdk(values, choice_path.clone()), kind: JourneyQuestionKind::Field, reopened_because: None, id: choice_path, @@ -64,7 +63,7 @@ pub(super) fn collect_required_leaf_questions( .iter() .filter(|name| { values - .pointer(&format!("{path}/{}", escape_pointer(name))) + .pointer(&format!("{path}/{}", escape(name))) .is_some() }) .collect::>(); @@ -76,7 +75,7 @@ pub(super) fn collect_required_leaf_questions( .map(|name| name.as_str()) .or_else(|| selected_forms.get(path).map(String::as_str)); if let Some(selected) = selected { - let child_path = format!("{path}/{}", escape_pointer(selected)); + let child_path = format!("{path}/{}", escape(selected)); if let Some((child_schema, _)) = sdk_field_schema_for(values, &child_path) { let supplied = values.pointer(&child_path); if !supplied.is_some_and(|value| schema_accepts(&child_schema, value) == Some(true)) @@ -85,7 +84,7 @@ pub(super) fn collect_required_leaf_questions( let choices = finite_choices(&child_schema); if scalar_question(&child_schema, &choices) { questions.push(JourneyQuestion { - target: QuestionTarget::sdk(child_path.clone()), + target: QuestionTarget::sdk(values, child_path.clone()), kind: JourneyQuestionKind::Field, reopened_because: None, id: child_path, @@ -139,8 +138,7 @@ pub(super) fn collect_required_leaf_questions( return; }; for name in required.iter().filter_map(Value::as_str) { - let escaped = name.replace('~', "~0").replace('/', "~1"); - let child_path = format!("{path}/{escaped}"); + let child_path = format!("{path}/{}", escape(name)); if questions.iter().any(|question| question.id == child_path) { continue; } @@ -154,7 +152,7 @@ pub(super) fn collect_required_leaf_questions( let choices = finite_choices(&child_schema); if scalar_question(&child_schema, &choices) { questions.push(JourneyQuestion { - target: QuestionTarget::sdk(child_path.clone()), + target: QuestionTarget::sdk(values, child_path.clone()), kind: JourneyQuestionKind::Field, reopened_because: None, id: child_path, diff --git a/crates/nemoclaw-authoring/src/journey_state/resolver/sdk_questions.rs b/crates/nemoclaw-authoring/src/journey_state/resolver/sdk_questions.rs index 25d4d2c7437..d0a67a38a4b 100644 --- a/crates/nemoclaw-authoring/src/journey_state/resolver/sdk_questions.rs +++ b/crates/nemoclaw-authoring/src/journey_state/resolver/sdk_questions.rs @@ -53,9 +53,10 @@ impl QuestionResolver<'_> { }); } + let harness = harness_field(&self.authored.values); for field in &self.definition.ask { if field == NAME - || field == HARNESS + || Some(field) == harness.as_ref() || field == INFERENCE_PRESET || adapter_field(field).is_some() { @@ -79,7 +80,7 @@ impl QuestionResolver<'_> { key, ), None => ( - QuestionTarget::sdk(field.clone()), + QuestionTarget::sdk(&self.authored.values, field.clone()), policy.sdk_schema(field, schema), supplied.cloned(), ), @@ -116,7 +117,7 @@ impl QuestionResolver<'_> { // arrays and conditional alternatives remain an explicit frontier. for issue in assessment.issues() { if issue.path() == NAME - || issue.path() == HARNESS + || harness.as_deref() == Some(issue.path()) || questions.iter().any(|question| question.id == issue.path()) { continue; @@ -182,7 +183,7 @@ impl QuestionResolver<'_> { continue; } questions.push(JourneyQuestion { - target: QuestionTarget::sdk(issue.path()), + target: QuestionTarget::sdk(&self.authored.values, issue.path()), kind: JourneyQuestionKind::Field, reopened_because: None, id: issue.path().into(), diff --git a/crates/nemoclaw-authoring/src/journey_state/selection.rs b/crates/nemoclaw-authoring/src/journey_state/selection.rs index 9fa5eb2e655..d2bcba4fd87 100644 --- a/crates/nemoclaw-authoring/src/journey_state/selection.rs +++ b/crates/nemoclaw-authoring/src/journey_state/selection.rs @@ -19,7 +19,10 @@ impl SelectionView<'_> { )) } - fn route_provider(&self) -> Option<(usize, usize)> { + /// The selected route and the key of the deployment provider it uses, + /// when that provider has an external endpoint. Questions address the + /// provider by this key, so it must be a valid name. + fn route_provider(&self) -> Option<(usize, String)> { let route = self.position.selected_route?; let reference = self .values @@ -27,30 +30,26 @@ impl SelectionView<'_> { "{}/{route}/providerRef", routes_path(self.values)? ))? - .as_str()?; - let providers = self + .as_str() + .filter(|reference| nemoclaw_sdk::config::valid_name(reference))?; + let provider = self .values .pointer("/spec/inferenceProviders")? - .as_array()?; - let provider = providers - .iter() - .position(|item| item.get("name").and_then(Value::as_str) == Some(reference))?; - (providers[provider].get("serviceRef").is_none()).then_some((route, provider)) + .get(reference)?; + (provider.get("serviceRef").is_none()).then(|| (route, reference.to_owned())) } fn provider_path(&self) -> Option { self.route_provider() - .map(|(_, provider)| format!("/spec/inferenceProviders/{provider}")) + .map(|(_, provider)| provider_path(&provider)) } fn current_preset(&self) -> Option { - let (route, provider_index) = self.route_provider()?; + let (route, provider) = self.route_provider()?; if let Some(preset) = self.decisions.selected_presets.get(&route).copied() { return Some(preset); } - let provider = self - .values - .pointer(&format!("/spec/inferenceProviders/{provider_index}"))?; + let provider = self.values.pointer(&provider_path(&provider))?; let kind: InferenceProviderKind = serde_json::from_value(provider.get("provider")?.clone()).ok()?; let endpoint = provider.get("endpoint")?.as_str()?; @@ -76,7 +75,7 @@ impl JourneyState { pub(super) fn route_model_path(&self) -> Option { self.selection().route_model_path() } - pub(super) fn route_provider(&self) -> Option<(usize, usize)> { + pub(super) fn route_provider(&self) -> Option<(usize, String)> { self.selection().route_provider() } pub(super) fn current_preset(&self) -> Option { diff --git a/crates/nemoclaw-authoring/src/lib.rs b/crates/nemoclaw-authoring/src/lib.rs index 88ef1dace6a..2b70b50612e 100644 --- a/crates/nemoclaw-authoring/src/lib.rs +++ b/crates/nemoclaw-authoring/src/lib.rs @@ -19,6 +19,7 @@ mod journey_definition; mod journey_state; mod journey_tree; mod partial_document; +mod pointer; mod provider_presets; mod target_assessment; @@ -34,6 +35,7 @@ pub use journey_state::{ JourneyState, }; pub use partial_document::{PartialAssessment, PartialDocument, PartialIssue, PartialIssueKind}; +pub use pointer::replace_entry_keys; pub use provider_presets::ProviderPreset; pub use target_assessment::{CompatibilityStatus, DiscoveryAssessment, assess_target}; diff --git a/crates/nemoclaw-authoring/src/partial_document.rs b/crates/nemoclaw-authoring/src/partial_document.rs index 6ee277b5b0d..ca5e1bca634 100644 --- a/crates/nemoclaw-authoring/src/partial_document.rs +++ b/crates/nemoclaw-authoring/src/partial_document.rs @@ -11,7 +11,7 @@ use nemoclaw_sdk::config::{ }; use serde_json::Value; -use crate::{Diagnostics, diagnostics::diagnostic}; +use crate::{Diagnostics, diagnostics::diagnostic, pointer::escape}; use jsonschema::error::ValidationErrorKind as Kind; static INPUT_SCHEMA: LazyLock = LazyLock::new(input_schema); @@ -87,6 +87,13 @@ impl PartialDocument { &self.supplied } + /// The ID of a single-sandbox journey's harness question, the pointer to + /// `/spec/sandboxes//harness/kind`, or `None` unless exactly one + /// sandbox is supplied and its key is a valid name. + pub fn harness_field(&self) -> Option { + crate::journey_definition::harness_field(&self.supplied) + } + /// Inspect the current sparse input. Compound rules remain deferred until /// a partial evaluator can prove whether a branch is impossible or incomplete. pub fn assess(&self) -> PartialAssessment { @@ -121,7 +128,7 @@ fn issue(error: &jsonschema::ValidationError<'_>) -> PartialIssue { && let Some(property) = property.as_str() { path.push('/'); - path.push_str(&property.replace('~', "~0").replace('/', "~1")); + path.push_str(&escape(property)); } PartialIssue { path, diff --git a/crates/nemoclaw-authoring/src/pointer.rs b/crates/nemoclaw-authoring/src/pointer.rs new file mode 100644 index 00000000000..8dbd784a8d9 --- /dev/null +++ b/crates/nemoclaw-authoring/src/pointer.rs @@ -0,0 +1,82 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! JSON pointer segments, and the keys among them that name SDK definitions. + +/// Escape `segment` for use as one JSON pointer segment. +pub(crate) fn escape(segment: &str) -> String { + segment.replace('~', "~0").replace('/', "~1") +} + +/// `pointer` with each segment that keys a named SDK definition replaced by +/// `replace(segment)`. These keys name sandboxes and the providers, services, +/// harnesses, inferences, and integrations of the deployment or of a sandbox; +/// they are names only by position, so a name can equal a field name. A +/// prefix before the pointer's first `/`, such as `form:`, is kept. +pub fn replace_entry_keys(pointer: &str, replace: impl Fn(&str) -> String) -> String { + let mut parts = pointer.split('/').map(str::to_owned).collect::>(); + for index in 1..parts.len() { + let before = parts[1..index] + .iter() + .map(String::as_str) + .collect::>(); + if matches!( + before.as_slice(), + [ + "spec", + "sandboxes" + | "inferenceProviders" + | "services" + | "harnesses" + | "inferences" + | "integrations" + ] | [ + "spec", + "sandboxes", + _, + "inferenceProviders" | "harnesses" | "inferences" | "integrations" + ] | ["spec", "sandboxes", _, "agent", "integrations"] + ) { + parts[index] = replace(&parts[index]); + } + } + parts.join("/") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_keys_in_named_definition_positions_are_replaced() { + let star = |_: &str| "*".to_owned(); + for (pointer, expected) in [ + ( + "/spec/sandboxes/routes/agent/inference/routes/0/name", + "/spec/sandboxes/*/agent/inference/routes/0/name", + ), + ( + "form:/spec/sandboxes/settings/agent", + "form:/spec/sandboxes/*/agent", + ), + ( + "/spec/sandboxes/a/inferenceProviders/services/endpoint", + "/spec/sandboxes/*/inferenceProviders/*/endpoint", + ), + ( + "/spec/sandboxes/a/agent/integrations/search/kind", + "/spec/sandboxes/*/agent/integrations/*/kind", + ), + ("/spec/services/config/recipe", "/spec/services/*/recipe"), + ( + "/spec/harnesses/execution/execution/timeoutSeconds", + "/spec/harnesses/*/execution/timeoutSeconds", + ), + ("/spec/sandboxes", "/spec/sandboxes"), + ("/spec/gateway/target/docker", "/spec/gateway/target/docker"), + ("adapter:x:/services/port", "adapter:x:/services/port"), + ] { + assert_eq!(replace_entry_keys(pointer, star), expected, "{pointer}"); + } + } +} diff --git a/crates/nemoclaw-authoring/src/sdk_schema.rs b/crates/nemoclaw-authoring/src/sdk_schema.rs index 46da898b139..b7de6aecf18 100644 --- a/crates/nemoclaw-authoring/src/sdk_schema.rs +++ b/crates/nemoclaw-authoring/src/sdk_schema.rs @@ -133,8 +133,11 @@ fn field_schema_in(root: &Value, values: &Value, path: &str) -> Option<(Value, b { node = branch; } - if part.parse::().is_ok() { - node = node.get("items")?; + // A numeric segment indexes an array; under an object it is a map key. + if part.parse::().is_ok() + && let Some(items) = node.get("items") + { + node = items; required = true; } else if let Some(property) = node .get("properties") @@ -435,6 +438,31 @@ mod tests { assert!(field_schema_in(&root, &values, "/target/podman/engine").is_none()); } + #[test] + fn a_numeric_map_key_names_an_entry_and_an_array_index_names_an_item() { + // SDK collections reject numeric names, so this map accepts any key. + let root = json!({ + "type": "object", + "properties": {"entries": { + "type": "object", + "additionalProperties": { + "type": "object", + "properties": { + "name": {"type": "string"}, + "routes": {"type": "array", "items": {"type": "integer"}} + }, + "required": ["name"] + } + }} + }); + let values = json!({"entries": {"7": {"routes": [1]}}}); + let (schema, required) = field_schema_in(&root, &values, "/entries/7/name").unwrap(); + assert_eq!(schema["type"], "string"); + assert!(required); + let (schema, _) = field_schema_in(&root, &values, "/entries/7/routes/0").unwrap(); + assert_eq!(schema["type"], "integer"); + } + #[test] fn only_a_union_of_single_key_objects_offers_its_keys() { let keyed_union = json!({"oneOf": [ diff --git a/crates/nemoclaw-authoring/src/settings.rs b/crates/nemoclaw-authoring/src/settings.rs index 2daa59c990a..52060d790d1 100644 --- a/crates/nemoclaw-authoring/src/settings.rs +++ b/crates/nemoclaw-authoring/src/settings.rs @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use crate::{Diagnostics, diagnostics::diagnostic}; +use crate::{Diagnostics, diagnostics::diagnostic, pointer::escape}; use nemoclaw_sdk::json_schema::schema_accepts; use serde_json::{Map, Value}; @@ -242,7 +242,7 @@ pub(crate) fn collect( .filter(|_| path.is_empty() || required || !values.is_null()) { for (name, child) in properties { - let child_path = format!("{path}/{}", name.replace('~', "~0").replace('/', "~1")); + let child_path = format!("{path}/{}", escape(name)); let child_required = effective["required"] .as_array() .is_some_and(|names| names.iter().any(|value| value.as_str() == Some(name))); diff --git a/crates/nemoclaw-authoring/src/target_assessment.rs b/crates/nemoclaw-authoring/src/target_assessment.rs index 9672eeee2b4..7183b820008 100644 --- a/crates/nemoclaw-authoring/src/target_assessment.rs +++ b/crates/nemoclaw-authoring/src/target_assessment.rs @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use crate::{Diagnostics, diagnostics::diagnostic}; +use crate::{Diagnostics, diagnostics::diagnostic, journey_definition::sole_sandbox}; use nemoclaw_sdk::{ config::Document, discovery::{DiscoveryObservations, DiscoveryQuery, ObservationStatus, plan_queries}, @@ -35,12 +35,12 @@ pub struct DiscoveryAssessment { /// Read the target from SDK-valid desired state. pub(crate) fn target_of(document: &Document) -> Result { - let [_] = document.spec.sandboxes.as_slice() else { + if sole_sandbox(document).is_none() { return Err(diagnostic( "sandbox", "guided discovery requires one sandbox", )); - }; + } Ok(Target { engine: document.spec.gateway.image_engine().to_owned(), managed_gateway: document.spec.gateway.as_managed().is_some(), diff --git a/crates/nemoclaw-authoring/tests/deployment_journey.rs b/crates/nemoclaw-authoring/tests/deployment_journey.rs index f6b05d03cfc..17a257f3e9e 100644 --- a/crates/nemoclaw-authoring/tests/deployment_journey.rs +++ b/crates/nemoclaw-authoring/tests/deployment_journey.rs @@ -5,7 +5,8 @@ use nemoclaw_authoring::{ Capabilities, JourneyDefinition, JourneyQuestionReason, JourneyScope, PartialDocument, }; use nemoclaw_sdk::config::Document; -use serde_json::json; +use serde_json::{Value, json}; +use std::collections::BTreeSet; fn example(name: &str) -> PartialDocument { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) @@ -302,7 +303,7 @@ fn single_sandbox_examples_offer_existing_sdk_values_without_changing_them() { fn reference_scoped_execution_questions_follow_the_selected_harness_only() { let capabilities = Capabilities::available(); let mut value = example("fabric-openclaw.yaml").supplied().clone(); - let mut harness = value["spec"]["sandboxes"][0]["harness"].clone(); + let mut harness = value["spec"]["sandboxes"]["assistant"]["harness"].clone(); harness["execution"] = json!({"timeoutSeconds":120}); value["spec"]["harnesses"] = json!({"unused":harness}); let path = "/spec/harnesses/unused/execution/timeoutSeconds"; @@ -323,11 +324,11 @@ fn reference_scoped_execution_questions_follow_the_selected_harness_only() { let mut state = state; assert!(state.answer(&capabilities, path, Some(json!(240))).is_err()); - value["spec"]["sandboxes"][0] + value["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove("harness"); - value["spec"]["sandboxes"][0]["harnessRef"] = json!("unused"); + value["spec"]["sandboxes"]["assistant"]["harnessRef"] = json!("unused"); let mut state = JourneyDefinition::new( "reference", PartialDocument::from_yaml(value.to_string().as_bytes()).unwrap(), @@ -345,3 +346,85 @@ fn reference_scoped_execution_questions_follow_the_selected_harness_only() { state.answer(&capabilities, path, Some(json!(240))).unwrap(); assert_eq!(state.values().pointer(path), Some(&json!(240))); } + +#[test] +fn deployment_questions_do_not_depend_on_sandbox_service_or_harness_names() { + let capabilities = Capabilities::available(); + // Move each map entry to `to` and point the references at it. + fn renamed(base: &Value, sandbox: &str, service: &str, harness: &str) -> Value { + let mut value = base.clone(); + for (collection, from, to) in [ + ("sandboxes", "assistant", sandbox), + ("services", "ollama-server", service), + ("harnesses", "agent", harness), + ] { + let map = value["spec"][collection].as_object_mut().unwrap(); + let entry = map.remove(from).unwrap(); + map.insert(to.into(), entry); + } + value["spec"]["inferenceProviders"]["local"]["serviceRef"] = json!(service); + value["spec"]["sandboxes"][sandbox]["harnessRef"] = json!(harness); + value + } + // Question IDs with each key replaced by its collection's placeholder. + let ids = |value: &Value, keys: [&str; 3]| { + let state = JourneyDefinition::new( + "names", + PartialDocument::from_yaml(value.to_string().as_bytes()).unwrap(), + ) + .ask([JourneyScope::DeploymentFields]) + .start(&capabilities) + .unwrap(); + state + .resolve(&capabilities) + .unwrap() + .questions() + .iter() + .map(|question| { + let mut id = question.id().to_owned(); + for (collection, key) in ["sandboxes", "services", "harnesses"].iter().zip(keys) { + let prefix = format!("/spec/{collection}/{key}/"); + if let Some(rest) = id.strip_prefix(&prefix) { + id = format!("/spec/{collection}//{rest}"); + } + } + id + }) + .collect::>() + }; + let mut base = example("managed-ollama.yaml").supplied().clone(); + let sandbox = base["spec"]["sandboxes"]["assistant"] + .as_object_mut() + .unwrap(); + sandbox.insert( + "image".into(), + json!({"ref": nemoclaw_sdk::config::DEFAULT_AGENT_IMAGE}), + ); + let mut harness = sandbox.remove("harness").unwrap(); + harness["execution"] = json!({"timeoutSeconds": 120}); + base["spec"]["harnesses"] = json!({"agent": harness}); + let base = renamed(&base, "assistant", "ollama-server", "agent"); + let expected = ids(&base, ["assistant", "ollama-server", "agent"]); + for id in [ + "/spec/sandboxes//image/ref", + "/spec/sandboxes//network/tier", + "/spec/services//image", + "/spec/harnesses//execution/timeoutSeconds", + ] { + assert!(expected.contains(id), "{id}: {expected:#?}"); + } + // Each key is also a field name or contains one that the question filters + // look for. + for keys in [ + ["routes", "config-server", "settings"], + ["configurator", "routes", "config"], + ["execution", "settings", "routes"], + ] { + let [sandbox, service, harness] = keys; + assert_eq!( + ids(&renamed(&base, sandbox, service, harness), keys), + expected, + "{keys:?}" + ); + } +} diff --git a/crates/nemoclaw-authoring/tests/fixtures/minimum-inline.yaml b/crates/nemoclaw-authoring/tests/fixtures/minimum-inline.yaml index 36f4991d052..f7639261f24 100644 --- a/crates/nemoclaw-authoring/tests/fixtures/minimum-inline.yaml +++ b/crates/nemoclaw-authoring/tests/fixtures/minimum-inline.yaml @@ -8,13 +8,14 @@ metadata: {} spec: gateway: {} inferenceProviders: - - name: nvidia-prod + nvidia-prod: api: openai-completions endpoint: https://integrate.api.nvidia.com/v1 credential: env: NVIDIA_API_KEY sandboxes: - - harness: {} + assistant: + harness: {} agent: inference: routes: diff --git a/crates/nemoclaw-authoring/tests/journey_authoring_boundaries.rs b/crates/nemoclaw-authoring/tests/journey_authoring_boundaries.rs index 6a029da92c7..d792a4d0f23 100644 --- a/crates/nemoclaw-authoring/tests/journey_authoring_boundaries.rs +++ b/crates/nemoclaw-authoring/tests/journey_authoring_boundaries.rs @@ -9,6 +9,13 @@ fn supplied() -> Value { serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")).unwrap() } +/// Rename a map entry, keeping its value. +fn rename(map: &mut Value, from: &str, to: &str) { + let map = map.as_object_mut().unwrap(); + let value = map.remove(from).unwrap(); + map.insert(to.into(), value); +} + fn start(values: Value, capabilities: &Capabilities) -> nemoclaw_authoring::JourneyState { let base = PartialDocument::from_yaml(values.to_string().as_bytes()).unwrap(); JourneyDefinition::new("boundaries", base) @@ -28,7 +35,7 @@ fn supplied_hosted_defaults_remain_an_sdk_valid_isolated_document() { .document() .unwrap() .clone(); - let sandbox = &document.spec.sandboxes[0]; + let sandbox = &document.spec.sandboxes["assistant"]; let provider = document.inference_provider().unwrap(); assert_eq!(provider.provider, InferenceProviderKind::Openai); assert_eq!(provider.api, Some(InferenceApi::OpenaiCompletions)); @@ -41,14 +48,19 @@ fn supplied_hosted_defaults_remain_an_sdk_valid_isolated_document() { fn explicit_custom_provider_identity_survives_an_unrelated_model_answer() { let capabilities = Capabilities::available(); let mut values = supplied(); - values["spec"]["inferenceProviders"][0]["name"] = json!("my-private-service"); - values["spec"]["inferenceProviders"][0]["endpoint"] = + rename( + &mut values["spec"]["inferenceProviders"], + "nvidia-prod", + "my-private-service", + ); + values["spec"]["inferenceProviders"]["my-private-service"]["endpoint"] = json!("https://models.private.example/v1"); - values["spec"]["inferenceProviders"][0]["credential"]["env"] = json!("PRIVATE_MODEL_TOKEN"); - values["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["providerRef"] = + values["spec"]["inferenceProviders"]["my-private-service"]["credential"]["env"] = + json!("PRIVATE_MODEL_TOKEN"); + values["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["providerRef"] = json!("my-private-service"); let mut state = start(values, &capabilities); - let model = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; + let model = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; state .answer(&capabilities, model, Some(json!("custom/new-model"))) .unwrap(); @@ -64,7 +76,7 @@ fn explicit_custom_provider_identity_survives_an_unrelated_model_answer() { assert_eq!(provider.endpoint, "https://models.private.example/v1"); assert_eq!(document.credential_names(), ["PRIVATE_MODEL_TOKEN"]); assert_eq!( - document.spec.sandboxes[0] + document.spec.sandboxes["assistant"] .agent .inference .as_ref() @@ -81,12 +93,21 @@ fn supplied_automation_values_survive_a_journey_without_reprojection() { let capabilities = Capabilities::available(); let mut values = supplied(); values["metadata"]["name"] = json!("automated-deployment"); - values["spec"]["sandboxes"][0]["name"] = json!("automated-sandbox"); - values["spec"]["sandboxes"][0]["agent"]["name"] = json!("automated-agent"); - values["spec"]["inferenceProviders"][0]["name"] = json!("automated-provider"); - values["spec"]["inferenceProviders"][0]["api"] = json!("openai-responses"); - values["spec"]["inferenceProviders"][0]["credential"]["env"] = json!("AUTOMATED_API_KEY"); - values["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["providerRef"] = + rename( + &mut values["spec"]["sandboxes"], + "assistant", + "automated-sandbox", + ); + values["spec"]["sandboxes"]["automated-sandbox"]["agent"]["name"] = json!("automated-agent"); + rename( + &mut values["spec"]["inferenceProviders"], + "nvidia-prod", + "automated-provider", + ); + values["spec"]["inferenceProviders"]["automated-provider"]["api"] = json!("openai-responses"); + values["spec"]["inferenceProviders"]["automated-provider"]["credential"]["env"] = + json!("AUTOMATED_API_KEY"); + values["spec"]["sandboxes"]["automated-sandbox"]["agent"]["inference"]["routes"][0]["providerRef"] = json!("automated-provider"); let state = start(values, &capabilities); let document = state @@ -97,8 +118,14 @@ fn supplied_automation_values_survive_a_journey_without_reprojection() { .unwrap() .clone(); assert_eq!(document.metadata.name, "automated-deployment"); - assert_eq!(document.spec.sandboxes[0].name, "automated-sandbox"); - assert_eq!(document.spec.sandboxes[0].agent.name, "automated-agent"); + assert_eq!( + document.spec.sandboxes.keys().collect::>(), + ["automated-sandbox"] + ); + assert_eq!( + document.spec.sandboxes["automated-sandbox"].agent.name, + "automated-agent" + ); assert_eq!( document.inference_provider().unwrap().name, "automated-provider" @@ -128,7 +155,7 @@ fn every_advertised_harness_preserves_the_isolated_network_boundary() { let capabilities = Capabilities::available(); for harness in capabilities.harnesses() { let mut values = supplied(); - values["spec"]["sandboxes"][0]["harness"]["kind"] = json!(harness.as_str()); + values["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!(harness.as_str()); let state = start(values, &capabilities); let document = state .resolve(&capabilities) @@ -140,7 +167,7 @@ fn every_advertised_harness_preserves_the_isolated_network_boundary() { let reopened = Document::parse(document.yaml().unwrap().as_bytes()).unwrap(); assert_eq!(reopened, document); assert!(matches!( - document.spec.sandboxes[0].network.policy, + document.spec.sandboxes["assistant"].network.policy, NetworkPolicy::Isolated )); } @@ -150,11 +177,13 @@ fn every_advertised_harness_preserves_the_isolated_network_boundary() { fn a_missing_fabric_catalog_does_not_rewrite_supplied_harness_intent() { let capabilities = Capabilities::from_harnesses([]); let mut values = supplied(); - values["spec"]["sandboxes"][0]["harness"]["kind"] = json!("nvidia.fabric.claude"); + values["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!("nvidia.fabric.claude"); let state = start(values, &capabilities); let resolution = state.resolve(&capabilities).unwrap(); assert_eq!( - state.values().pointer("/spec/sandboxes/0/harness/kind"), + state + .values() + .pointer("/spec/sandboxes/assistant/harness/kind"), Some(&json!("nvidia.fabric.claude")) ); assert!(!resolution.unverified().is_empty()); @@ -176,7 +205,7 @@ fn unsupported_protocol_answer_is_rejected_without_mutating_the_document() { state .answer( &capabilities, - "/spec/inferenceProviders/0/api", + "/spec/inferenceProviders/nvidia-prod/api", Some(json!("anthropic-messages")) ) .is_err() diff --git a/crates/nemoclaw-authoring/tests/journey_decision_status.rs b/crates/nemoclaw-authoring/tests/journey_decision_status.rs index dc10cb1dbee..c6d925273d5 100644 --- a/crates/nemoclaw-authoring/tests/journey_decision_status.rs +++ b/crates/nemoclaw-authoring/tests/journey_decision_status.rs @@ -49,7 +49,7 @@ fn supplied_values_and_user_decisions_are_distinct() { assert!( session .values() - .pointer("/spec/sandboxes/0/harness/settings/cli") + .pointer("/spec/sandboxes/assistant/harness/settings/cli") .is_none() ); } diff --git a/crates/nemoclaw-authoring/tests/journey_edits.rs b/crates/nemoclaw-authoring/tests/journey_edits.rs index d957e3341f8..2ba6d99eea4 100644 --- a/crates/nemoclaw-authoring/tests/journey_edits.rs +++ b/crates/nemoclaw-authoring/tests/journey_edits.rs @@ -15,21 +15,30 @@ fn partial(values: &Value) -> PartialDocument { PartialDocument::from_yaml(values.to_string().as_bytes()).unwrap() } +fn provider_names(values: &Value) -> Vec { + values["spec"]["inferenceProviders"] + .as_object() + .unwrap() + .keys() + .cloned() + .collect() +} + #[test] fn preset_keeps_shared_provider_identity_and_reopens_every_dependent_route() { let capabilities = Capabilities::available(); let mut values = base_values(); - let routes = values["spec"]["sandboxes"][0]["agent"]["inference"]["routes"] + let routes = values["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"] .as_array_mut() .unwrap(); let mut second = routes[0].clone(); second["name"] = json!("second"); routes.push(second); - values["spec"]["sandboxes"][0]["agent"]["inference"]["default"] = - values["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["name"].clone(); - let provider_name = values["spec"]["inferenceProviders"][0]["name"].clone(); + values["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["default"] = + values["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["name"].clone(); + let providers = provider_names(&values); let first_name = - values["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["name"].clone(); + values["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["name"].clone(); let mut state = JourneyDefinition::new("shared-provider", partial(&values)) .ask([JourneyScope::RouteModels]) .ask(["inference:preset"]) @@ -45,7 +54,7 @@ fn preset_keeps_shared_provider_identity_and_reopens_every_dependent_route() { Some(json!("nvidia-endpoints")), ) .unwrap(); - let first_model = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; + let first_model = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; state .answer(&capabilities, first_model, Some(json!("first-model"))) .unwrap(); @@ -59,7 +68,7 @@ fn preset_keeps_shared_provider_identity_and_reopens_every_dependent_route() { Some(json!("nvidia-endpoints")), ) .unwrap(); - let second_model = "/spec/sandboxes/0/agent/inference/routes/1/overrides/model"; + let second_model = "/spec/sandboxes/assistant/agent/inference/routes/1/overrides/model"; state .answer(&capabilities, second_model, Some(json!("second-model"))) .unwrap(); @@ -67,10 +76,7 @@ fn preset_keeps_shared_provider_identity_and_reopens_every_dependent_route() { .answer(&capabilities, "inference:preset", Some(json!("openai"))) .unwrap(); - assert_eq!( - state.values()["spec"]["inferenceProviders"][0]["name"], - provider_name - ); + assert_eq!(provider_names(state.values()), providers); assert!( state .resolve(&capabilities) @@ -118,7 +124,7 @@ fn accepted_and_omitted_native_settings_can_be_revisited() { },"provenance":[]})]; let capabilities = Capabilities::from_catalog(&catalog); let mut values = base_values(); - values["spec"]["sandboxes"][0]["harness"]["kind"] = json!("fixture.native-edit"); + values["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!("fixture.native-edit"); let mut state = JourneyDefinition::new("native-edits", partial(&values)) .ask([JourneyScope::NativeSettings]) .start(&capabilities) @@ -154,13 +160,13 @@ fn accepted_and_omitted_native_settings_can_be_revisited() { assert_eq!( state .values() - .pointer("/spec/sandboxes/0/harness/config/workflow/settings/region"), + .pointer("/spec/sandboxes/assistant/harness/config/workflow/settings/region"), Some(&json!("east")) ); assert_eq!( - state - .values() - .pointer("/spec/sandboxes/0/agent/inference/routes/0/overrides/settings/variant"), + state.values().pointer( + "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/settings/variant" + ), Some(&json!("thorough")) ); let before = state.values().clone(); @@ -179,7 +185,7 @@ fn exact_and_scope_api_guidance_use_the_same_selected_provider_policy() { "../../../examples/spark/local-and-hosted.yaml" )) .unwrap(); - let api = "/spec/inferenceProviders/1/api"; + let api = "/spec/inferenceProviders/hosted/api"; for scopes in [ vec![JourneyScope::RouteModels], vec![JourneyScope::RouteModels, JourneyScope::InferenceApi], @@ -211,7 +217,9 @@ fn exact_and_scope_api_guidance_use_the_same_selected_provider_policy() { ); let model_index = questions .iter() - .position(|q| q.id() == "/spec/sandboxes/0/agent/inference/routes/1/overrides/model") + .position(|q| { + q.id() == "/spec/sandboxes/assistant/agent/inference/routes/1/overrides/model" + }) .unwrap(); assert!(api_index < model_index); assert!( diff --git a/crates/nemoclaw-authoring/tests/journey_guidance.rs b/crates/nemoclaw-authoring/tests/journey_guidance.rs index 2d1facd78b5..7da2a62291a 100644 --- a/crates/nemoclaw-authoring/tests/journey_guidance.rs +++ b/crates/nemoclaw-authoring/tests/journey_guidance.rs @@ -20,7 +20,7 @@ fn journey(values: Value, capabilities: &Capabilities) -> nemoclaw_authoring::Jo ) .ask([ "/metadata/name", - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", "inference:preset", ]) .ask([JourneyScope::InferenceApi, JourneyScope::RouteModels]) @@ -37,11 +37,172 @@ fn supplied_values_are_suggestions_for_finite_and_free_text_questions() { assert_eq!(name.reason(), JourneyQuestionReason::ExplicitAsk); assert_eq!(name.suggestion(), Some(&json!("openclaw-nvidia-hosted"))); assert!(name.choices().is_empty()); - let harness = resolved.question("/spec/sandboxes/0/harness/kind").unwrap(); + let harness = resolved + .question("/spec/sandboxes/assistant/harness/kind") + .unwrap(); assert_eq!(harness.suggestion(), Some(&json!("nvidia.fabric.openclaw"))); assert_eq!(harness.choices().len(), capabilities.harnesses().len()); } +#[test] +fn questions_address_the_only_sandbox_and_its_provider_by_their_keys() { + let capabilities = Capabilities::available(); + let mut values = supplied(); + let sandboxes = values["spec"]["sandboxes"].as_object_mut().unwrap(); + let sandbox = sandboxes.remove("assistant").unwrap(); + sandboxes.insert("coder".into(), sandbox); + let providers = values["spec"]["inferenceProviders"] + .as_object_mut() + .unwrap(); + let provider = providers.remove("nvidia-prod").unwrap(); + providers.insert("hosted".into(), provider); + values["spec"]["sandboxes"]["coder"]["agent"]["inference"]["routes"][0]["providerRef"] = + json!("hosted"); + let harness = "/spec/sandboxes/coder/harness/kind"; + let mut state = JourneyDefinition::new( + "keyed", + PartialDocument::from_yaml(values.to_string().as_bytes()).unwrap(), + ) + .ask([harness, "inference:preset"]) + .ask([JourneyScope::InferenceApi, JourneyScope::RouteModels]) + .start(&capabilities) + .unwrap(); + assert!( + state + .resolve(&capabilities) + .unwrap() + .question(harness) + .is_some() + ); + state + .answer(&capabilities, harness, Some(json!("nvidia.fabric.hermes"))) + .unwrap(); + state + .answer( + &capabilities, + "inference:preset", + Some(json!("nvidia-endpoints")), + ) + .unwrap(); + let api = "/spec/inferenceProviders/hosted/api"; + state + .answer(&capabilities, api, Some(json!("openai-responses"))) + .unwrap(); + let model = "/spec/sandboxes/coder/agent/inference/routes/0/overrides/model"; + state + .answer(&capabilities, model, Some(json!("custom/model"))) + .unwrap(); + let resolution = state.resolve(&capabilities).unwrap(); + let document = resolution.assessment().document().unwrap(); + let sandbox = &document.spec.sandboxes["coder"]; + assert_eq!( + sandbox.harness.as_ref().unwrap().kind.as_str(), + "nvidia.fabric.hermes" + ); + assert_eq!( + sandbox.agent.inference.as_ref().unwrap().routes[0] + .overrides + .model, + "custom/model" + ); + assert_eq!( + document.spec.inference_providers["hosted"].api, + Some(InferenceApi::OpenaiResponses) + ); +} + +#[test] +fn a_journey_requires_its_sandbox_key_to_be_a_name_and_never_echoes_it() { + let capabilities = Capabilities::available(); + let mut values = supplied(); + let sandboxes = values["spec"]["sandboxes"].as_object_mut().unwrap(); + let sandbox = sandboxes.remove("assistant").unwrap(); + sandboxes.insert("PRIVATE INVALID NAME".into(), sandbox); + let error = JourneyDefinition::new( + "invalid", + PartialDocument::from_yaml(values.to_string().as_bytes()).unwrap(), + ) + .ask([JourneyScope::DeploymentFields]) + .start(&capabilities) + .unwrap_err() + .to_string(); + assert_eq!( + error, + "journey: The v1 journey requires exactly one sandbox keyed by a lowercase name." + ); +} + +#[test] +fn a_provider_key_that_is_not_a_name_is_never_a_question_id() { + let capabilities = Capabilities::available(); + let mut values = supplied(); + let providers = values["spec"]["inferenceProviders"] + .as_object_mut() + .unwrap(); + let provider = providers.remove("nvidia-prod").unwrap(); + providers.insert("PRIVATE INVALID NAME".into(), provider); + values["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["providerRef"] = + json!("PRIVATE INVALID NAME"); + let mut state = journey(values, &capabilities); + let mut ids = Vec::new(); + for _ in 0..2 { + let resolution = state.resolve(&capabilities).unwrap(); + ids.extend( + resolution + .questions() + .iter() + .map(|question| question.id().to_owned()), + ); + if resolution.question("inference:preset").is_none() { + break; + } + state + .answer( + &capabilities, + "inference:preset", + Some(json!("nvidia-endpoints")), + ) + .unwrap(); + } + assert!(!ids.is_empty()); + assert!(ids.iter().all(|id| !id.contains("PRIVATE")), "{ids:?}"); +} + +#[test] +fn asked_fields_must_name_the_journey_sandbox_or_a_supplied_provider() { + let capabilities = Capabilities::available(); + let start = |field: &str| { + JourneyDefinition::new( + "asked", + PartialDocument::from_yaml(supplied().to_string().as_bytes()).unwrap(), + ) + .ask([field]) + .start(&capabilities) + }; + for (field, message) in [ + ( + "/spec/sandboxes/other/agent/name", + "journey: asked fields must belong to the journey's sandbox", + ), + ( + "/spec/sandboxes/other", + "journey: asked fields must belong to the journey's sandbox", + ), + ( + "/spec/inferenceProviders/other/api", + "journey: asked provider fields must belong to a supplied provider", + ), + ] { + assert_eq!(start(field).unwrap_err().to_string(), message, "{field}"); + } + for field in [ + "/spec/sandboxes/assistant/agent/name", + "/spec/inferenceProviders/nvidia-prod/api", + ] { + assert!(start(field).is_ok(), "{field}"); + } +} + #[test] fn generated_yaml_reopens_as_the_same_supplied_intent() { let capabilities = Capabilities::available(); @@ -56,7 +217,7 @@ fn generated_yaml_reopens_as_the_same_supplied_intent() { state .answer( &capabilities, - "/spec/inferenceProviders/0/api", + "/spec/inferenceProviders/nvidia-prod/api", Some(json!("openai-responses")), ) .unwrap(); @@ -79,16 +240,18 @@ fn generated_yaml_reopens_as_the_same_supplied_intent() { state.values().pointer("/metadata/uid") ); assert_eq!( - again.values().pointer("/spec/inferenceProviders/0/api"), + again + .values() + .pointer("/spec/inferenceProviders/nvidia-prod/api"), Some(&json!("openai-responses")) ); assert_eq!( again .values() - .pointer("/spec/sandboxes/0/agent/inference/routes/0/overrides/model"), + .pointer("/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"), state .values() - .pointer("/spec/sandboxes/0/agent/inference/routes/0/overrides/model") + .pointer("/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model") ); } @@ -101,7 +264,7 @@ fn every_advertised_harness_keeps_provider_protocol_choices() { state .answer( &capabilities, - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", Some(json!(harness.as_str())), ) .unwrap(); @@ -111,7 +274,7 @@ fn every_advertised_harness_keeps_provider_protocol_choices() { let api = state .resolve(&capabilities) .unwrap() - .question("/spec/inferenceProviders/0/api") + .question("/spec/inferenceProviders/nvidia-prod/api") .cloned() .unwrap(); assert_eq!( @@ -144,7 +307,7 @@ fn changing_a_model_preserves_an_explicit_target_engine() { Some(json!("nvidia-endpoints")), ) .unwrap(); - let model = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; + let model = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; state .answer(&capabilities, model, Some(json!("updated-model"))) .unwrap(); @@ -158,12 +321,13 @@ fn changing_a_model_preserves_an_explicit_target_engine() { fn an_anonymous_local_provider_is_lossless_without_a_credential_reference() { let capabilities = Capabilities::available(); let mut values = supplied(); - values["spec"]["inferenceProviders"][0]["endpoint"] = json!("http://127.0.0.1:11434/v1"); - values["spec"]["inferenceProviders"][0] + values["spec"]["inferenceProviders"]["nvidia-prod"]["endpoint"] = + json!("http://127.0.0.1:11434/v1"); + values["spec"]["inferenceProviders"]["nvidia-prod"] .as_object_mut() .unwrap() .remove("credential"); - values["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"]["model"] = + values["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["overrides"]["model"] = json!("local-model"); let mut state = journey(values, &capabilities); state @@ -176,11 +340,11 @@ fn an_anonymous_local_provider_is_lossless_without_a_credential_reference() { state .answer( &capabilities, - "/spec/inferenceProviders/0/endpoint", + "/spec/inferenceProviders/nvidia-prod/endpoint", Some(json!("http://127.0.0.1:11434/v1")), ) .unwrap(); - let model = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; + let model = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; state .answer(&capabilities, model, Some(json!("local-model"))) .unwrap(); @@ -218,7 +382,7 @@ fn newly_advertised_fabric_harness_is_a_choice_without_code_registration() { catalog.adapters.push(adapter); let capabilities = Capabilities::from_catalog(&catalog); let mut state = journey(supplied(), &capabilities); - let harness = "/spec/sandboxes/0/harness/kind"; + let harness = "/spec/sandboxes/assistant/harness/kind"; assert!( state .resolve(&capabilities) @@ -247,7 +411,7 @@ fn newly_advertised_fabric_harness_is_a_choice_without_code_registration() { .unwrap() .clone(); assert_eq!( - document.spec.sandboxes[0] + document.spec.sandboxes["assistant"] .harness .as_ref() .unwrap() diff --git a/crates/nemoclaw-authoring/tests/journey_resolution.rs b/crates/nemoclaw-authoring/tests/journey_resolution.rs index ab28790576f..38bf2245ac8 100644 --- a/crates/nemoclaw-authoring/tests/journey_resolution.rs +++ b/crates/nemoclaw-authoring/tests/journey_resolution.rs @@ -13,7 +13,7 @@ const TARGET: &str = "/spec/gateway/target"; fn minimum() -> PartialDocument { PartialDocument::from_yaml( - b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nspec:\n sandboxes:\n - {}\n", + b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nspec:\n sandboxes:\n assistant: {}\n", ) .unwrap() } @@ -24,24 +24,28 @@ fn empty_sandbox_asks_for_harness_form_before_inline_harness_kind() { let mut inline = JourneyDefinition::new("inline-form", minimum()) .start(&capabilities) .unwrap(); - let form = "form:/spec/sandboxes/0"; + let form = "form:/spec/sandboxes/assistant"; let initial = inline.resolve(&capabilities).unwrap(); let question = initial.question(form).expect("sandbox form question"); assert_eq!(question.choices(), &[json!("harness"), json!("harnessRef")]); - assert!(initial.question("/spec/sandboxes/0/harness/kind").is_none()); + assert!( + initial + .question("/spec/sandboxes/assistant/harness/kind") + .is_none() + ); inline .answer(&capabilities, form, Some(json!("harness"))) .unwrap(); let inline_questions = inline.resolve(&capabilities).unwrap(); let harness = inline_questions - .question("/spec/sandboxes/0/harness/kind") + .question("/spec/sandboxes/assistant/harness/kind") .expect("inline harness kind"); assert!(!harness.choices().is_empty()); assert_eq!( inline_questions .questions() .iter() - .filter(|question| question.id() == "/spec/sandboxes/0/harness/kind") + .filter(|question| question.id() == "/spec/sandboxes/assistant/harness/kind") .count(), 1 ); @@ -53,10 +57,14 @@ fn empty_sandbox_asks_for_harness_form_before_inline_harness_kind() { .answer(&capabilities, form, Some(json!("harnessRef"))) .unwrap(); let reference = referenced.resolve(&capabilities).unwrap(); - assert!(reference.question("/spec/sandboxes/0/harnessRef").is_some()); assert!( reference - .question("/spec/sandboxes/0/harness/kind") + .question("/spec/sandboxes/assistant/harnessRef") + .is_some() + ); + assert!( + reference + .question("/spec/sandboxes/assistant/harness/kind") .is_none() ); } @@ -67,12 +75,12 @@ fn omitted_optional_sdk_field_stays_absent_even_when_its_scope_is_asked() { let mut supplied: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - supplied["spec"]["inferenceProviders"][0] + supplied["spec"]["inferenceProviders"]["nvidia-prod"] .as_object_mut() .unwrap() .remove("api"); let base = PartialDocument::from_yaml(supplied.to_string().as_bytes()).unwrap(); - let path = "/spec/inferenceProviders/0/api"; + let path = "/spec/inferenceProviders/nvidia-prod/api"; let state = JourneyDefinition::new("omit-sdk-api", base) .ask([JourneyScope::InferenceApi]) .omit([ @@ -105,7 +113,7 @@ fn exact_and_scope_guidance_share_one_inference_api_question() { let base = PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - let path = "/spec/inferenceProviders/0/api"; + let path = "/spec/inferenceProviders/nvidia-prod/api"; let mut state = JourneyDefinition::new("same-api-decision", base) .ask([path]) .ask([JourneyScope::InferenceApi]) @@ -140,7 +148,7 @@ fn exact_and_scope_guidance_keep_route_model_question_kind() { let base = PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - let path = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; + let path = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; let state = JourneyDefinition::new("same-model-decision", base) .ask([path]) .ask([JourneyScope::RouteModels]) @@ -168,8 +176,8 @@ fn asked_inference_api_precedes_route_model_in_question_order() { .ask([JourneyScope::InferenceApi, JourneyScope::RouteModels]) .start(&capabilities) .unwrap(); - let api_path = "/spec/inferenceProviders/0/api"; - let model_path = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; + let api_path = "/spec/inferenceProviders/nvidia-prod/api"; + let model_path = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; let first = state.resolve(&capabilities).unwrap(); let api = first.question(api_path).expect("asked API"); @@ -203,7 +211,7 @@ fn omit_guidance_rejects_required_or_supplied_sdk_fields() { ); assert!( JourneyDefinition::new("supplied", base) - .omit(["/spec/inferenceProviders/0/api"]) + .omit(["/spec/inferenceProviders/nvidia-prod/api"]) .start(&capabilities) .is_err() ); @@ -233,7 +241,7 @@ fn adapter_settings_scope_omit_leaves_absent_optional_settings_unset_for_any_har ); let mut hermes = base.supplied().clone(); - hermes["spec"]["sandboxes"][0]["harness"]["kind"] = json!("nvidia.fabric.hermes"); + hermes["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!("nvidia.fabric.hermes"); let hermes = PartialDocument::from_yaml(hermes.to_string().as_bytes()).unwrap(); let resolution = JourneyDefinition::new("express-hermes", hermes) .omit([JourneyScope::ActiveAdapterSettings]) @@ -288,19 +296,15 @@ fn missing_required_sdk_leaf_values_become_questions_without_guidance() { serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); values["metadata"].as_object_mut().unwrap().remove("name"); - values["spec"]["sandboxes"][0] - .as_object_mut() - .unwrap() - .remove("name"); - values["spec"]["sandboxes"][0]["agent"] + values["spec"]["sandboxes"]["assistant"]["agent"] .as_object_mut() .unwrap() .remove("name"); - values["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0] + values["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0] .as_object_mut() .unwrap() .remove("name"); - values["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"] + values["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["overrides"] .as_object_mut() .unwrap() .remove("model"); @@ -310,11 +314,13 @@ fn missing_required_sdk_leaf_values_become_questions_without_guidance() { .unwrap(); for (path, value) in [ ("/metadata/name", "deployment"), - ("/spec/sandboxes/0/name", "sandbox"), - ("/spec/sandboxes/0/agent/name", "agent"), - ("/spec/sandboxes/0/agent/inference/routes/0/name", "primary"), + ("/spec/sandboxes/assistant/agent/name", "agent"), + ( + "/spec/sandboxes/assistant/agent/inference/routes/0/name", + "primary", + ), ( - "/spec/sandboxes/0/agent/inference/routes/0/overrides/model", + "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model", "nvidia/selected-model", ), ] { @@ -343,7 +349,7 @@ fn exclusive_sdk_forms_become_choices_then_ask_for_the_selected_field() { let mut agent_values: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - agent_values["spec"]["sandboxes"][0]["agent"] + agent_values["spec"]["sandboxes"]["assistant"]["agent"] .as_object_mut() .unwrap() .remove("inference"); @@ -351,7 +357,7 @@ fn exclusive_sdk_forms_become_choices_then_ask_for_the_selected_field() { let mut agent = JourneyDefinition::new("agent-form", agent_base) .start(&capabilities) .unwrap(); - let agent_form = "form:/spec/sandboxes/0/agent"; + let agent_form = "form:/spec/sandboxes/assistant/agent"; let question = agent .resolve(&capabilities) .unwrap() @@ -371,19 +377,19 @@ fn exclusive_sdk_forms_become_choices_then_ask_for_the_selected_field() { assert!(selected.question(agent_form).is_none()); assert!( selected - .question("/spec/sandboxes/0/agent/inferenceRef") + .question("/spec/sandboxes/assistant/agent/inferenceRef") .is_some() ); assert!( agent .values() - .pointer("/spec/sandboxes/0/agent/inferenceRef") + .pointer("/spec/sandboxes/assistant/agent/inferenceRef") .is_none() ); agent .answer( &capabilities, - "/spec/sandboxes/0/agent/inferenceRef", + "/spec/sandboxes/assistant/agent/inferenceRef", Some(json!("shared")), ) .unwrap(); @@ -393,7 +399,7 @@ fn exclusive_sdk_forms_become_choices_then_ask_for_the_selected_field() { assert!( agent .values() - .pointer("/spec/sandboxes/0/agent/inferenceRef") + .pointer("/spec/sandboxes/assistant/agent/inferenceRef") .is_none(), "switching forms must remove the incompatible supplied branch" ); @@ -401,7 +407,7 @@ fn exclusive_sdk_forms_become_choices_then_ask_for_the_selected_field() { let mut route_values: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - route_values["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0] + route_values["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0] .as_object_mut() .unwrap() .remove("providerRef"); @@ -409,7 +415,7 @@ fn exclusive_sdk_forms_become_choices_then_ask_for_the_selected_field() { let mut route = JourneyDefinition::new("route-form", route_base) .start(&capabilities) .unwrap(); - let route_form = "form:/spec/sandboxes/0/agent/inference/routes/0"; + let route_form = "form:/spec/sandboxes/assistant/agent/inference/routes/0"; let question = route .resolve(&capabilities) .unwrap() @@ -427,7 +433,7 @@ fn exclusive_sdk_forms_become_choices_then_ask_for_the_selected_field() { route .resolve(&capabilities) .unwrap() - .question("/spec/sandboxes/0/agent/inference/routes/0/providerRef") + .question("/spec/sandboxes/assistant/agent/inference/routes/0/providerRef") .is_some() ); } @@ -438,7 +444,7 @@ fn missing_object_parent_exposes_its_unconditional_required_fields() { let mut values: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - values["spec"]["sandboxes"][0] + values["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove("agent"); @@ -446,7 +452,7 @@ fn missing_object_parent_exposes_its_unconditional_required_fields() { let mut state = JourneyDefinition::new("missing-agent", base) .start(&capabilities) .unwrap(); - let name = "/spec/sandboxes/0/agent/name"; + let name = "/spec/sandboxes/assistant/agent/name"; assert_eq!( state .resolve(&capabilities) @@ -476,12 +482,12 @@ fn invalid_supplied_sdk_leaf_is_an_editable_question_without_guidance() { let mut values: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - values["spec"]["sandboxes"][0]["name"] = json!("Bad Name"); + values["spec"]["sandboxes"]["assistant"]["agent"]["name"] = json!("Bad Name"); let base = PartialDocument::from_yaml(values.to_string().as_bytes()).unwrap(); let mut state = JourneyDefinition::new("repair", base) .start(&capabilities) .unwrap(); - let path = "/spec/sandboxes/0/name"; + let path = "/spec/sandboxes/assistant/agent/name"; assert_eq!( state .resolve(&capabilities) @@ -550,7 +556,7 @@ fn sparse_journey_follows_nested_fabric_conditionals() { let mut base: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - base["spec"]["sandboxes"][0]["harness"]["kind"] = json!("fixture-schema-agent"); + base["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!("fixture-schema-agent"); let mut state = JourneyDefinition::new( "conditional", PartialDocument::from_yaml(base.to_string().as_bytes()).unwrap(), @@ -624,7 +630,7 @@ fn nested_adapter_guidance_asks_omits_and_warns_from_the_active_schema() { let mut base: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - base["spec"]["sandboxes"][0]["harness"] = json!({ + base["spec"]["sandboxes"]["assistant"]["harness"] = json!({ "kind":"fixture.nested-guidance", "settings":{"native":{"region":"west"}} }); @@ -657,7 +663,7 @@ fn nested_adapter_guidance_asks_omits_and_warns_from_the_active_schema() { .any(|warning| warning.contains("adapter:fixture.nested-guidance:/native/typo")) ); - base["spec"]["sandboxes"][0]["harness"]["settings"]["native"] = json!({}); + base["spec"]["sandboxes"]["assistant"]["harness"]["settings"]["native"] = json!({}); let required_omit = JourneyDefinition::new( "required-nested-omit", PartialDocument::from_yaml(base.to_string().as_bytes()).unwrap(), @@ -690,8 +696,8 @@ fn root_fabric_alternatives_are_answered_through_the_journey() { let mut base: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - base["spec"]["sandboxes"][0]["harness"]["kind"] = json!("fixture-root-agent"); - base["spec"]["sandboxes"][0]["harness"] + base["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!("fixture-root-agent"); + base["spec"]["sandboxes"]["assistant"]["harness"] .as_object_mut() .unwrap() .remove("settings"); @@ -717,7 +723,9 @@ fn root_fabric_alternatives_are_answered_through_the_journey() { .answer(&capabilities, root, Some(json!({"port":443}))) .unwrap(); assert_eq!( - state.values().pointer("/spec/sandboxes/0/harness/settings"), + state + .values() + .pointer("/spec/sandboxes/assistant/harness/settings"), Some(&json!({"port":443})) ); assert!( @@ -755,7 +763,7 @@ fn changed_adapter_schema_reopens_an_invalid_answer_without_rewriting_it() { let mut value: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - value["spec"]["sandboxes"][0]["harness"]["kind"] = json!("fixture-schema-agent"); + value["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!("fixture-schema-agent"); let base = PartialDocument::from_yaml(value.to_string().as_bytes()).unwrap(); let mut state = JourneyDefinition::new("changed-descriptor", base) .start(&capabilities) @@ -785,7 +793,7 @@ fn changed_adapter_schema_reopens_an_invalid_answer_without_rewriting_it() { assert_eq!( state .values() - .pointer("/spec/sandboxes/0/harness/settings/mode"), + .pointer("/spec/sandboxes/assistant/harness/settings/mode"), Some(&json!("revised")) ); } @@ -805,7 +813,7 @@ fn conflicting_adapter_descriptors_do_not_select_a_schema_by_catalog_order() { let mut value: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - value["spec"]["sandboxes"][0]["harness"]["kind"] = json!("fixture-schema-agent"); + value["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!("fixture-schema-agent"); let base = PartialDocument::from_yaml(value.to_string().as_bytes()).unwrap(); let state = JourneyDefinition::new("conflicting-descriptors", base) .start(&capabilities) @@ -829,7 +837,7 @@ fn omitting_a_nested_optional_setting_does_not_create_its_parent_object() { let mut value: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - value["spec"]["sandboxes"][0]["harness"]["kind"] = json!("test.optional-settings"); + value["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!("test.optional-settings"); let base = PartialDocument::from_yaml(value.to_string().as_bytes()).unwrap(); let mut state = JourneyDefinition::new("nested-optional", base) .start(&capabilities) @@ -846,7 +854,7 @@ fn omitting_a_nested_optional_setting_does_not_create_its_parent_object() { assert!( state .values() - .pointer("/spec/sandboxes/0/harness/settings/native") + .pointer("/spec/sandboxes/assistant/harness/settings/native") .is_none() ); } @@ -870,7 +878,7 @@ fn conditional_native_model_settings_survive_a_model_change_and_sdk_roundtrip() let mut value: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - value["spec"]["sandboxes"][0]["harness"]["kind"] = json!("fixture.model-owner"); + value["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!("fixture.model-owner"); let base = PartialDocument::from_yaml(value.to_string().as_bytes()).unwrap(); let mut state = JourneyDefinition::new("conditional-native", base) .ask([JourneyScope::NativeSettings]) @@ -898,14 +906,14 @@ fn conditional_native_model_settings_survive_a_model_change_and_sdk_roundtrip() ); assert!(state.answer(&capabilities, budget, Some(json!(0))).is_err()); state.answer(&capabilities, budget, Some(json!(3))).unwrap(); - let model = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; + let model = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; state .answer(&capabilities, model, Some(json!("different-model"))) .unwrap(); assert_eq!( state .values() - .pointer("/spec/sandboxes/0/agent/inference/routes/0/overrides/settings"), + .pointer("/spec/sandboxes/assistant/agent/inference/routes/0/overrides/settings"), Some(&json!({"variant":"thorough","budget":3})) ); let document = state @@ -965,7 +973,7 @@ fn sparse_journey_uses_workflow_and_model_owner_schemas() { let capabilities = Capabilities::from_catalog(&catalog); let mut partial: serde_json::Value = serde_saphyr::from_slice(include_bytes!("fixtures/minimum-inline.yaml")).unwrap(); - partial["spec"]["sandboxes"][0]["harness"]["kind"] = json!("fixture.native-owner"); + partial["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!("fixture.native-owner"); let mut sparse = JourneyDefinition::new( "sparse-native", PartialDocument::from_yaml(partial.to_string().as_bytes()).unwrap(), @@ -1000,13 +1008,13 @@ fn sparse_journey_uses_workflow_and_model_owner_schemas() { assert_eq!( sparse .values() - .pointer("/spec/sandboxes/0/harness/config/workflow/settings/region"), + .pointer("/spec/sandboxes/assistant/harness/config/workflow/settings/region"), Some(&json!("west")) ); let mut base: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - base["spec"]["sandboxes"][0]["harness"]["kind"] = json!("fixture.native-owner"); + base["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!("fixture.native-owner"); let mut state = JourneyDefinition::new( "native", PartialDocument::from_yaml(base.to_string().as_bytes()).unwrap(), @@ -1083,7 +1091,7 @@ fn exact_native_guidance_uses_active_fabric_fields_without_asking_the_whole_scop let mut supplied: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - supplied["spec"]["sandboxes"][0]["harness"]["kind"] = json!("fixture.exact-native"); + supplied["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!("fixture.exact-native"); let base = PartialDocument::from_yaml(supplied.to_string().as_bytes()).unwrap(); let mut state = JourneyDefinition::new("exact-native", base.clone()) .ask(["workflow:/target_id", "model:/variant"]) @@ -1117,8 +1125,8 @@ fn exact_native_guidance_uses_active_fabric_fields_without_asking_the_whole_scop ); let mut with_supplied = supplied; - with_supplied["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"]["settings"] = - json!({"variant":"quick"}); + with_supplied["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["overrides"] + ["settings"] = json!({"variant":"quick"}); let supplied_model = PartialDocument::from_yaml(with_supplied.to_string().as_bytes()).unwrap(); let invalid_omission = JourneyDefinition::new("supplied-model", supplied_model) .omit(["model:/variant"]) @@ -1283,7 +1291,7 @@ fn discovered_models_extend_the_current_route_question_without_restricting_custo DiscoveryQuery::Inference(request.clone()), catalog(ObservationStatus::Available), ); - let model = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; + let model = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; let discovered = state .resolve_with_observations(&capabilities, &observations) .unwrap(); @@ -1832,7 +1840,7 @@ fn delegation_facts(capabilities: &Capabilities) -> DelegationFacts { .unwrap(); let mut state = JourneyDefinition::new("delegate", base) .ask([ - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", "/metadata/name", "inference:preset", ]) @@ -1846,7 +1854,7 @@ fn delegation_facts(capabilities: &Capabilities) -> DelegationFacts { state .answer( capabilities, - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", Some(json!("nvidia.fabric.openclaw")), ) .unwrap(); @@ -1857,7 +1865,7 @@ fn delegation_facts(capabilities: &Capabilities) -> DelegationFacts { .document() .unwrap() .clone(); - let model = document.spec.sandboxes[0] + let model = document.spec.sandboxes["assistant"] .agent .inference .as_ref() @@ -1900,13 +1908,13 @@ fn sparse_journey_delegation_requires_current_target_observations() { PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); let mut state = JourneyDefinition::new("delegate", base) - .ask(["/spec/sandboxes/0/harness/kind", "/metadata/name"]) + .ask(["/spec/sandboxes/assistant/harness/kind", "/metadata/name"]) .start(&capabilities) .unwrap(); state .answer( &capabilities, - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", Some(json!("nvidia.fabric.openclaw")), ) .unwrap(); @@ -2103,13 +2111,13 @@ fn delegation_is_refused_for_a_route_backed_by_a_managed_service() { let base = PartialDocument::from_yaml(include_bytes!("../../../examples/managed-ollama.yaml")) .unwrap(); let mut state = JourneyDefinition::new("delegate", base) - .ask(["/spec/sandboxes/0/harness/kind"]) + .ask(["/spec/sandboxes/assistant/harness/kind"]) .start(&capabilities) .unwrap(); state .answer( &capabilities, - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", Some(json!("nvidia.fabric.openclaw")), ) .unwrap(); @@ -2142,7 +2150,7 @@ fn delegation_is_refused_before_a_harness_is_accepted() { PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); let state = JourneyDefinition::new("delegate", base) - .ask(["/spec/sandboxes/0/harness/kind"]) + .ask(["/spec/sandboxes/assistant/harness/kind"]) .start(&capabilities) .unwrap(); let refusal = state @@ -2173,8 +2181,8 @@ fn sparse_journey_visits_each_route_and_keeps_its_model_answers_separate() { .start(&capabilities) .unwrap(); let route = "route:selection"; - let hosted_model = "/spec/sandboxes/0/agent/inference/routes/1/overrides/model"; - let local_model = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; + let hosted_model = "/spec/sandboxes/assistant/agent/inference/routes/1/overrides/model"; + let local_model = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; let first = state.resolve(&capabilities).unwrap(); assert_eq!( first.question(route).unwrap().choices(), @@ -2238,7 +2246,10 @@ fn referenced_inference_routes_are_selected_and_edited_through_the_same_journey( &include_bytes!("../../../examples/multiple-providers.yaml")[..], ) .unwrap(); - document.spec.sandboxes.truncate(1); + document + .spec + .sandboxes + .retain(|name, _| name == "researcher"); let base = PartialDocument::from_yaml(serde_json::to_vec(&document).unwrap().as_slice()).unwrap(); let mut state = JourneyDefinition::new("referenced-routes", base) @@ -2313,7 +2324,10 @@ fn referenced_harness_settings_are_owned_by_the_referenced_definition() { &include_bytes!("../../../examples/multiple-models.yaml")[..], ) .unwrap(); - document.spec.sandboxes.truncate(1); + document + .spec + .sandboxes + .retain(|name, _| name == "researcher"); let base = PartialDocument::from_yaml(serde_json::to_vec(&document).unwrap().as_slice()).unwrap(); let mut state = JourneyDefinition::new("referenced-harness", base) @@ -2340,7 +2354,7 @@ fn referenced_harness_settings_are_owned_by_the_referenced_definition() { assert!( state .values() - .pointer("/spec/sandboxes/0/harness") + .pointer("/spec/sandboxes/researcher/harness") .is_none() ); } @@ -2352,14 +2366,17 @@ fn revisiting_a_referenced_harness_choice_does_not_create_an_inline_harness() { &include_bytes!("../../../examples/multiple-models.yaml")[..], ) .unwrap(); - document.spec.sandboxes.truncate(1); + document + .spec + .sandboxes + .retain(|name, _| name == "researcher"); let base = PartialDocument::from_yaml(serde_json::to_vec(&document).unwrap().as_slice()).unwrap(); let mut state = JourneyDefinition::new("referenced-harness-choice", base) - .ask(["/spec/sandboxes/0/harness/kind"]) + .ask(["/spec/sandboxes/researcher/harness/kind"]) .start(&capabilities) .unwrap(); - let field = "/spec/sandboxes/0/harness/kind"; + let field = "/spec/sandboxes/researcher/harness/kind"; state .answer(&capabilities, field, Some(json!("nvidia.fabric.openclaw"))) .unwrap(); @@ -2373,7 +2390,7 @@ fn revisiting_a_referenced_harness_choice_does_not_create_an_inline_harness() { assert!( state .values() - .pointer("/spec/sandboxes/0/harness") + .pointer("/spec/sandboxes/researcher/harness") .is_none() ); } @@ -2385,7 +2402,10 @@ fn referenced_model_settings_are_written_to_the_selected_route() { &include_bytes!("../../../examples/multiple-models.yaml")[..], ) .unwrap(); - document.spec.sandboxes.truncate(1); + document + .spec + .sandboxes + .retain(|name, _| name == "researcher"); let base = PartialDocument::from_yaml(serde_json::to_vec(&document).unwrap().as_slice()).unwrap(); let mut state = JourneyDefinition::new("referenced-model", base) @@ -2416,7 +2436,7 @@ fn referenced_model_settings_are_written_to_the_selected_route() { assert!( state .values() - .pointer("/spec/sandboxes/0/agent/inference") + .pointer("/spec/sandboxes/researcher/agent/inference") .is_none() ); } @@ -2438,7 +2458,10 @@ fn referenced_workflow_answers_keep_the_named_harness_as_the_owner() { &include_bytes!("../../../examples/multiple-models.yaml")[..], ) .unwrap(); - document.spec.sandboxes.truncate(1); + document + .spec + .sandboxes + .retain(|name, _| name == "researcher"); let mut value = serde_json::to_value(&document).unwrap(); value["spec"]["harnesses"]["assistant"]["kind"] = json!("fixture.workflow-owner"); let base = PartialDocument::from_yaml(value.to_string().as_bytes()).unwrap(); @@ -2466,7 +2489,7 @@ fn referenced_workflow_answers_keep_the_named_harness_as_the_owner() { assert!( state .values() - .pointer("/spec/sandboxes/0/harness") + .pointer("/spec/sandboxes/researcher/harness") .is_none() ); } @@ -2481,7 +2504,7 @@ fn omitting_an_implicit_api_keeps_the_sdk_default_without_writing_an_override() .ask([JourneyScope::InferenceApi]) .start(&capabilities) .unwrap(); - let path = "/spec/inferenceProviders/0/api"; + let path = "/spec/inferenceProviders/local/api"; let question = state .resolve(&capabilities) .unwrap() @@ -2525,7 +2548,7 @@ fn absent_optional_adapter_settings_remain_unsupplied_until_answered() { assert!( state .values() - .pointer("/spec/sandboxes/0/harness/settings/cli") + .pointer("/spec/sandboxes/assistant/harness/settings/cli") .is_none() ); } @@ -2540,7 +2563,7 @@ fn editing_a_route_model_preserves_explicit_credential_references() { .ask([JourneyScope::RouteModels]) .start(&capabilities) .unwrap(); - let model = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; + let model = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; state .answer( &capabilities, @@ -2590,7 +2613,7 @@ fn route_preset_changes_only_the_selected_external_provider() { state .answer( &capabilities, - "/spec/sandboxes/0/agent/inference/routes/0/overrides/model", + "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model", Some(json!("nvidia/Qwen3.8-27B-NVFP4")), ) .unwrap(); @@ -2608,24 +2631,28 @@ fn route_preset_changes_only_the_selected_external_provider() { .answer(&capabilities, "inference:preset", Some(json!("openai"))) .unwrap(); assert_eq!( - state.values().pointer("/spec/inferenceProviders/0"), - before.pointer("/spec/inferenceProviders/0") + state.values().pointer("/spec/inferenceProviders/local"), + before.pointer("/spec/inferenceProviders/local") ); assert_eq!( - state.values().pointer("/spec/inferenceProviders/1/name"), - Some(&json!("hosted")) + state.values()["spec"]["inferenceProviders"] + .as_object() + .unwrap() + .keys() + .collect::>(), + ["hosted", "local"] ); assert_eq!( state .values() - .pointer("/spec/sandboxes/0/agent/inference/routes/1/providerRef"), + .pointer("/spec/sandboxes/assistant/agent/inference/routes/1/providerRef"), Some(&json!("hosted")) ); assert_eq!( state .values() - .pointer("/spec/sandboxes/0/agent/inference/routes/0/overrides/model"), - before.pointer("/spec/sandboxes/0/agent/inference/routes/0/overrides/model") + .pointer("/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"), + before.pointer("/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model") ); } @@ -2636,10 +2663,14 @@ fn partial_journey_recomputes_questions_after_answers_and_omissions() { let mut state = definition.start(&capabilities).unwrap(); let questions = state.resolve(&capabilities).unwrap(); assert!(questions.question("/metadata/name").is_some()); - assert!(questions.question("form:/spec/sandboxes/0").is_some()); assert!( questions - .question("/spec/sandboxes/0/harness/kind") + .question("form:/spec/sandboxes/assistant") + .is_some() + ); + assert!( + questions + .question("/spec/sandboxes/assistant/harness/kind") .is_none() ); assert!( @@ -2658,14 +2689,14 @@ fn partial_journey_recomputes_questions_after_answers_and_omissions() { state .answer( &capabilities, - "form:/spec/sandboxes/0", + "form:/spec/sandboxes/assistant", Some(json!("harness")), ) .unwrap(); state .answer( &capabilities, - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", Some(json!("nvidia.fabric.openclaw")), ) .unwrap(); @@ -2730,7 +2761,7 @@ fn existing_onboarding_fields_resolve_and_materialize_without_a_draft() { serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); sparse - .pointer_mut("/spec/sandboxes/0/agent/inference/routes/0/overrides") + .pointer_mut("/spec/sandboxes/assistant/agent/inference/routes/0/overrides") .unwrap() .as_object_mut() .unwrap() @@ -2738,11 +2769,11 @@ fn existing_onboarding_fields_resolve_and_materialize_without_a_draft() { let base = PartialDocument::from_yaml(sparse.to_string().as_bytes()).unwrap(); let fields = [ "/metadata/name", - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", TARGET, - "/spec/inferenceProviders/0/provider", - "/spec/inferenceProviders/0/api", - "/spec/sandboxes/0/agent/inference/routes/0/overrides/model", + "/spec/inferenceProviders/nvidia-prod/provider", + "/spec/inferenceProviders/nvidia-prod/api", + "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model", ]; let definition = JourneyDefinition::new("guided", base).ask(fields).omit([ "adapter:nvidia.fabric.openclaw:/agent_name", @@ -2789,7 +2820,7 @@ fn existing_onboarding_fields_resolve_and_materialize_without_a_draft() { seen.push(field.to_owned()); let value = match field { "/metadata/name" => json!("new-deployment"), - "/spec/sandboxes/0/agent/inference/routes/0/overrides/model" => { + "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model" => { let before = state.values().clone(); assert!( state @@ -2820,7 +2851,7 @@ fn existing_onboarding_fields_resolve_and_materialize_without_a_draft() { assert_eq!( state .values() - .pointer("/spec/sandboxes/0/agent/inference/routes/0/overrides/model"), + .pointer("/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"), Some(&json!("nvidia/another-model")) ); } @@ -2832,12 +2863,11 @@ fn inference_preset_updates_sparse_values_and_reopens_dependent_answers() { PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); let preset = "inference:preset"; - let api = "/spec/inferenceProviders/0/api"; - let provider_name = "/spec/inferenceProviders/0/name"; - let model = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; + let api = "/spec/inferenceProviders/nvidia-prod/api"; + let model = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; let name = "/metadata/name"; let mut state = JourneyDefinition::new("preset", base) - .ask([name, preset, api, model, provider_name]) + .ask([name, preset, api, model]) .omit([ "adapter:nvidia.fabric.openclaw:/agent_name", "adapter:nvidia.fabric.openclaw:/cli", @@ -2869,9 +2899,6 @@ fn inference_preset_updates_sparse_values_and_reopens_dependent_answers() { state .answer(&capabilities, model, Some(json!("nvidia/my-model"))) .unwrap(); - state - .answer(&capabilities, provider_name, Some(json!("nvidia-prod"))) - .unwrap(); assert!( state .resolve(&capabilities) @@ -2902,33 +2929,31 @@ fn inference_preset_updates_sparse_values_and_reopens_dependent_answers() { assert_eq!( state .values() - .pointer("/spec/inferenceProviders/0/provider"), + .pointer("/spec/inferenceProviders/nvidia-prod/provider"), Some(&json!("anthropic")) ); assert_eq!( - state.values().pointer("/spec/inferenceProviders/0/name"), - Some(&json!("nvidia-prod")) - ); - assert_eq!( - state.values().pointer("/spec/inferenceProviders/0/api"), + state + .values() + .pointer("/spec/inferenceProviders/nvidia-prod/api"), Some(&json!("anthropic-messages")) ); assert_eq!( state .values() - .pointer("/spec/inferenceProviders/0/endpoint"), + .pointer("/spec/inferenceProviders/nvidia-prod/endpoint"), Some(&json!("https://api.anthropic.com")) ); assert_eq!( state .values() - .pointer("/spec/inferenceProviders/0/credential/env"), + .pointer("/spec/inferenceProviders/nvidia-prod/credential/env"), Some(&json!("ANTHROPIC_API_KEY")) ); assert_eq!( state .values() - .pointer("/spec/sandboxes/0/agent/inference/routes/0/providerRef"), + .pointer("/spec/sandboxes/assistant/agent/inference/routes/0/providerRef"), Some(&json!("nvidia-prod")) ); assert_eq!( @@ -2938,7 +2963,6 @@ fn inference_preset_updates_sparse_values_and_reopens_dependent_answers() { let resolved = state.resolve(&capabilities).unwrap(); assert!(resolved.question(name).is_none()); assert!(resolved.question(api).is_some()); - assert!(resolved.question(provider_name).is_none()); assert!(resolved.question(model).is_some()); assert!(resolved.materialized_document().is_none()); assert!( @@ -2970,7 +2994,7 @@ fn compatible_inference_preset_requires_an_endpoint_answer() { let mut state = JourneyDefinition::new("custom", base) .ask([ "inference:preset", - "/spec/sandboxes/0/agent/inference/routes/0/overrides/model", + "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model", ]) .start(&capabilities) .unwrap(); @@ -2984,22 +3008,22 @@ fn compatible_inference_preset_requires_an_endpoint_answer() { let resolved = state.resolve(&capabilities).unwrap(); assert!( resolved - .question("/spec/inferenceProviders/0/endpoint") + .question("/spec/inferenceProviders/nvidia-prod/endpoint") .is_some() ); assert!( resolved - .question("/spec/sandboxes/0/agent/inference/routes/0/overrides/model") + .question("/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model") .is_none() ); assert!( state .values() - .pointer("/spec/sandboxes/0/agent/inference/routes/0/overrides/model") + .pointer("/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model") .is_none() ); assert!(resolved.materialized_document().is_none()); - let endpoint = "/spec/inferenceProviders/0/endpoint"; + let endpoint = "/spec/inferenceProviders/nvidia-prod/endpoint"; let before = state.values().clone(); assert!( state @@ -3018,13 +3042,13 @@ fn compatible_inference_preset_requires_an_endpoint_answer() { state .resolve(&capabilities) .unwrap() - .question("/spec/sandboxes/0/agent/inference/routes/0/overrides/model") + .question("/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model") .is_some() ); state .answer( &capabilities, - "/spec/sandboxes/0/agent/inference/routes/0/overrides/model", + "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model", Some(json!("org/model")), ) .unwrap(); @@ -3043,9 +3067,9 @@ fn inference_dependencies_wait_for_preset_and_custom_endpoint() { let base = PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - let api = "/spec/inferenceProviders/0/api"; - let model = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; - let endpoint = "/spec/inferenceProviders/0/endpoint"; + let api = "/spec/inferenceProviders/nvidia-prod/api"; + let model = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; + let endpoint = "/spec/inferenceProviders/nvidia-prod/endpoint"; let preset = "inference:preset"; let mut state = JourneyDefinition::new("order", base) .ask([api, model, preset]) @@ -3086,14 +3110,17 @@ fn changing_inference_api_reopens_the_accepted_model_but_keeps_identity() { PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); let mut state = JourneyDefinition::new("api-dependency", base) - .ask(["/metadata/name", "/spec/inferenceProviders/0/endpoint"]) + .ask([ + "/metadata/name", + "/spec/inferenceProviders/nvidia-prod/endpoint", + ]) .ask([JourneyScope::InferenceApi, JourneyScope::RouteModels]) .start(&capabilities) .unwrap(); let name = "/metadata/name"; - let api = "/spec/inferenceProviders/0/api"; - let model = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; - let endpoint = "/spec/inferenceProviders/0/endpoint"; + let api = "/spec/inferenceProviders/nvidia-prod/api"; + let model = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; + let endpoint = "/spec/inferenceProviders/nvidia-prod/endpoint"; state .answer(&capabilities, name, Some(json!("my-project"))) .unwrap(); @@ -3157,11 +3184,11 @@ fn changing_the_second_provider_api_reopens_its_route_model() { .unwrap(); let mut state = JourneyDefinition::new("second-provider-api", base) .ask([JourneyScope::RouteModels]) - .ask(["/spec/inferenceProviders/1/api"]) + .ask(["/spec/inferenceProviders/hosted/api"]) .start(&capabilities) .unwrap(); - let api = "/spec/inferenceProviders/1/api"; - let model = "/spec/sandboxes/0/agent/inference/routes/1/overrides/model"; + let api = "/spec/inferenceProviders/hosted/api"; + let model = "/spec/sandboxes/assistant/agent/inference/routes/1/overrides/model"; state .answer(&capabilities, "route:selection", Some(json!("hosted"))) .unwrap(); @@ -3189,7 +3216,7 @@ fn optional_sdk_question_can_be_deliberately_omitted() { PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); let mut state = JourneyDefinition::new("optional-api", base) - .ask(["/spec/inferenceProviders/0/api"]) + .ask(["/spec/inferenceProviders/nvidia-prod/api"]) .omit([ "adapter:nvidia.fabric.openclaw:/agent_name", "adapter:nvidia.fabric.openclaw:/cli", @@ -3238,12 +3265,13 @@ fn switching_harness_reopens_the_active_adapter_without_losing_its_values() { let base = PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - let definition = JourneyDefinition::new("switch", base).ask(["/spec/sandboxes/0/harness/kind"]); + let definition = + JourneyDefinition::new("switch", base).ask(["/spec/sandboxes/assistant/harness/kind"]); let mut state = definition.start(&capabilities).unwrap(); state .answer( &capabilities, - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", Some(json!("nvidia.fabric.openclaw")), ) .unwrap(); @@ -3257,7 +3285,7 @@ fn switching_harness_reopens_the_active_adapter_without_losing_its_values() { state .answer( &capabilities, - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", Some(json!("nvidia.fabric.hermes")), ) .unwrap(); @@ -3271,14 +3299,14 @@ fn switching_harness_reopens_the_active_adapter_without_losing_its_values() { state .answer( &capabilities, - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", Some(json!("nvidia.fabric.openclaw")), ) .unwrap(); assert_eq!( state .values() - .pointer("/spec/sandboxes/0/harness/settings/agent_name"), + .pointer("/spec/sandboxes/assistant/harness/settings/agent_name"), Some(&json!("kept-agent")) ); } @@ -3298,14 +3326,14 @@ fn accepted_answers_can_be_revisited_without_losing_other_values() { state .answer( &capabilities, - "form:/spec/sandboxes/0", + "form:/spec/sandboxes/assistant", Some(json!("harness")), ) .unwrap(); state .answer( &capabilities, - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", Some(json!("nvidia.fabric.openclaw")), ) .unwrap(); @@ -3331,7 +3359,7 @@ fn accepted_answers_can_be_revisited_without_losing_other_values() { assert_eq!( state .values() - .pointer("/spec/sandboxes/0/harness/settings/agent_name"), + .pointer("/spec/sandboxes/assistant/harness/settings/agent_name"), Some(&json!("beta")) ); } @@ -3342,7 +3370,7 @@ fn fabric_invalid_value_reopens_a_question_even_when_sdk_document_is_valid() { let mut base: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - base["spec"]["sandboxes"][0]["harness"]["settings"] = json!({"cli": 42}); + base["spec"]["sandboxes"]["assistant"]["harness"]["settings"] = json!({"cli": 42}); let base = PartialDocument::from_yaml(base.to_string().as_bytes()).unwrap(); let mut state = JourneyDefinition::new("fabric-invalid", base) .start(&capabilities) @@ -3427,7 +3455,7 @@ fn supplied_template_can_finish_a_guided_journey_through_one_resolver() { PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); let definition = JourneyDefinition::new("guided-complete", base) - .ask(["/metadata/name", "/spec/sandboxes/0/harness/kind"]) + .ask(["/metadata/name", "/spec/sandboxes/assistant/harness/kind"]) .omit([ "adapter:nvidia.fabric.openclaw:/agent_name", "adapter:nvidia.fabric.openclaw:/cli", @@ -3463,7 +3491,7 @@ fn supplied_template_can_finish_a_guided_journey_through_one_resolver() { state .answer( &capabilities, - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", Some(json!("nvidia.fabric.openclaw")), ) .unwrap(); @@ -3485,18 +3513,22 @@ fn absent_harness_catalog_cannot_silently_accept_an_unadvertised_choice() { .start(&capabilities) .unwrap(); let resolved = state.resolve(&capabilities).unwrap(); - assert!(resolved.question("form:/spec/sandboxes/0").is_some()); + assert!( + resolved + .question("form:/spec/sandboxes/assistant") + .is_some() + ); state .answer( &capabilities, - "form:/spec/sandboxes/0", + "form:/spec/sandboxes/assistant", Some(json!("harness")), ) .unwrap(); let resolved = state.resolve(&capabilities).unwrap(); assert!( resolved - .question("/spec/sandboxes/0/harness/kind") + .question("/spec/sandboxes/assistant/harness/kind") .is_some() ); assert!(!resolved.unverified().is_empty()); @@ -3504,7 +3536,7 @@ fn absent_harness_catalog_cannot_silently_accept_an_unadvertised_choice() { state .answer( &capabilities, - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", Some(json!("nvidia.fabric.openclaw")) ) .is_err() @@ -3514,7 +3546,7 @@ fn absent_harness_catalog_cannot_silently_accept_an_unadvertised_choice() { #[test] fn missing_gateway_asks_for_the_schema_discriminator() { let base = PartialDocument::from_yaml( - b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nspec:\n sandboxes:\n - {}\n", + b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nspec:\n sandboxes:\n assistant: {}\n", ) .unwrap(); let capabilities = Capabilities::available(); @@ -3840,7 +3872,7 @@ fn adapter_setting_questions_carry_fabric_descriptions() { let mut values: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - values["spec"]["sandboxes"][0]["harness"] = json!({"kind": "nvidia.fabric.hermes"}); + values["spec"]["sandboxes"]["assistant"]["harness"] = json!({"kind": "nvidia.fabric.hermes"}); let base = PartialDocument::from_yaml(values.to_string().as_bytes()).unwrap(); let capabilities = Capabilities::available(); let resolution = JourneyDefinition::new("described-settings", base) @@ -3920,19 +3952,21 @@ fn minimally_supplied_inline_envelope_materializes_through_one_resolver() { let answers = [ ("/metadata/name", json!("minimum-inline")), ("/spec/gateway/management", json!("managed")), - ("/spec/inferenceProviders/0/provider", json!("openai")), - ("/spec/sandboxes/0/name", json!("assistant")), ( - "/spec/sandboxes/0/harness/kind", + "/spec/inferenceProviders/nvidia-prod/provider", + json!("openai"), + ), + ( + "/spec/sandboxes/assistant/harness/kind", json!("nvidia.fabric.openclaw"), ), - ("/spec/sandboxes/0/agent/name", json!("primary")), + ("/spec/sandboxes/assistant/agent/name", json!("primary")), ( - "/spec/sandboxes/0/agent/inference/routes/0/name", + "/spec/sandboxes/assistant/agent/inference/routes/0/name", json!("primary"), ), ( - "/spec/sandboxes/0/agent/inference/routes/0/overrides/model", + "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model", json!("nvidia/nemotron-3-super-120b-a12b"), ), ]; diff --git a/crates/nemoclaw-authoring/tests/journey_tree_preview.rs b/crates/nemoclaw-authoring/tests/journey_tree_preview.rs index e5d9362da26..a8267217553 100644 --- a/crates/nemoclaw-authoring/tests/journey_tree_preview.rs +++ b/crates/nemoclaw-authoring/tests/journey_tree_preview.rs @@ -64,7 +64,7 @@ fn configured_native_questions_appear_in_the_same_definition_tree() { #[test] fn minimum_values_preview_shows_harness_branches_and_optional_omission() { let base = PartialDocument::from_yaml( - b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nspec:\n sandboxes:\n - {}\n", + b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nspec:\n sandboxes:\n assistant: {}\n", ) .unwrap(); let journey = JourneyDefinition::new("minimum-values", base) @@ -73,15 +73,16 @@ fn minimum_values_preview_shows_harness_branches_and_optional_omission() { let tree = journey.print_tree(&Capabilities::available()).unwrap(); assert!(tree.contains("/metadata/name")); - assert!(tree.contains("/spec/sandboxes/0/name")); - assert!(tree.contains("/spec/sandboxes/0/agent/name")); + // The sandbox's key is its name, so no question asks for one. + assert!(!tree.contains("/spec/sandboxes/assistant/name"), "{tree}"); + assert!(tree.contains("/spec/sandboxes/assistant/agent/name")); assert!( - tree.contains("Choices for form:/spec/sandboxes/0:"), + tree.contains("Choices for form:/spec/sandboxes/assistant:"), "{tree}" ); assert!(tree.contains("ā”œā”€ harnessRef"), "{tree}"); assert!( - tree.contains("Choices for /spec/sandboxes/0/harness/kind:"), + tree.contains("Choices for /spec/sandboxes/assistant/harness/kind:"), "{tree}" ); assert!(tree.contains("nvidia.fabric.openclaw")); @@ -122,13 +123,16 @@ fn guided_sdk_questions_are_visible_in_the_tree_without_printing_suggestions() { PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); let journey = JourneyDefinition::new("guided-sdk", base).ask([ - "/spec/inferenceProviders/0/api", - "/spec/sandboxes/0/agent/inference/routes/0/overrides/model", + "/spec/inferenceProviders/nvidia-prod/api", + "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model", ]); let tree = journey.print_tree(&Capabilities::available()).unwrap(); - assert!(tree.contains("/spec/inferenceProviders/0/api"), "{tree}"); assert!( - tree.contains("/spec/sandboxes/0/agent/inference/routes/0/overrides/model"), + tree.contains("/spec/inferenceProviders/nvidia-prod/api"), + "{tree}" + ); + assert!( + tree.contains("/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"), "{tree}" ); assert!( @@ -145,18 +149,18 @@ fn inference_preset_preview_shows_custom_endpoint_branch() { .unwrap(); let journey = JourneyDefinition::new("preset", base).ask([ "inference:preset", - "/spec/inferenceProviders/0/api", - "/spec/sandboxes/0/agent/inference/routes/0/overrides/model", + "/spec/inferenceProviders/nvidia-prod/api", + "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model", ]); let tree = journey.print_tree(&Capabilities::available()).unwrap(); assert!(tree.contains("inference:preset"), "{tree}"); assert!(tree.contains("openai-compatible"), "{tree}"); assert!( - tree.contains("/spec/inferenceProviders/0/endpoint"), + tree.contains("/spec/inferenceProviders/nvidia-prod/endpoint"), "{tree}" ); assert!( - tree.contains("/spec/sandboxes/0/agent/inference/routes/0/overrides/model"), + tree.contains("/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"), "{tree}" ); assert!(!tree.contains("https://inference.example.com/v1"), "{tree}"); @@ -167,7 +171,7 @@ fn preview_does_not_print_supplied_native_setting_values() { let mut base: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - base.pointer_mut("/spec/sandboxes/0/harness") + base.pointer_mut("/spec/sandboxes/assistant/harness") .unwrap() .as_object_mut() .unwrap() @@ -189,7 +193,9 @@ fn omission_is_scoped_to_its_adapter() { let mut base: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - let harness = base.pointer_mut("/spec/sandboxes/0/harness").unwrap(); + let harness = base + .pointer_mut("/spec/sandboxes/assistant/harness") + .unwrap(); harness["kind"] = serde_json::json!("nvidia.fabric.hermes"); harness["settings"] = serde_json::json!({"cli": "from-other-adapter"}); let base = PartialDocument::from_yaml(base.to_string().as_bytes()).unwrap(); @@ -243,12 +249,16 @@ fn invalid_supplied_sdk_leaf_is_visible_without_printing_its_value() { let mut values: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - values["spec"]["sandboxes"][0]["name"] = serde_json::json!("PRIVATE INVALID NAME"); + values["spec"]["sandboxes"]["assistant"]["agent"]["name"] = + serde_json::json!("PRIVATE INVALID NAME"); let base = PartialDocument::from_yaml(values.to_string().as_bytes()).unwrap(); - let tree = JourneyDefinition::new("invalid-sandbox", base) + let tree = JourneyDefinition::new("invalid-agent", base) .print_tree(&Capabilities::available()) .unwrap(); - assert!(tree.contains("/spec/sandboxes/0/name: "), "{tree}"); + assert!( + tree.contains("/spec/sandboxes/assistant/agent/name: "), + "{tree}" + ); assert!(tree.contains("invalid supplied value"), "{tree}"); assert!(!tree.contains("PRIVATE INVALID NAME"), "{tree}"); } @@ -258,7 +268,7 @@ fn harness_without_a_fabric_schema_does_not_claim_zero_questions() { let mut base: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - base["spec"]["sandboxes"][0]["harness"]["kind"] = + base["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = serde_json::json!("nvidia.fabric.unsupported"); let base = PartialDocument::from_yaml(base.to_string().as_bytes()).unwrap(); let journey = JourneyDefinition::new("invalid-harness", base); @@ -273,7 +283,7 @@ fn invalid_fabric_setting_is_labeled_without_printing_its_value() { let mut base: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - base["spec"]["sandboxes"][0]["harness"]["settings"] = serde_json::json!({"cli": 42}); + base["spec"]["sandboxes"]["assistant"]["harness"]["settings"] = serde_json::json!({"cli": 42}); let base = PartialDocument::from_yaml(base.to_string().as_bytes()).unwrap(); let tree = JourneyDefinition::new("invalid-setting", base) @@ -295,8 +305,8 @@ fn tree_branches_on_finite_sdk_choices_from_the_resolver() { let base = PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - let definition = - JourneyDefinition::new("api-choices", base).ask(["/spec/inferenceProviders/0/api"]); + let definition = JourneyDefinition::new("api-choices", base) + .ask(["/spec/inferenceProviders/nvidia-prod/api"]); let capabilities = Capabilities::available(); let resolution = definition .start(&capabilities) @@ -304,7 +314,7 @@ fn tree_branches_on_finite_sdk_choices_from_the_resolver() { .resolve(&capabilities) .unwrap(); let question = resolution - .question("/spec/inferenceProviders/0/api") + .question("/spec/inferenceProviders/nvidia-prod/api") .unwrap(); assert!(question.choices().len() > 1); let tree = definition.print_tree(&capabilities).unwrap(); @@ -322,7 +332,7 @@ fn tree_does_not_print_supplied_route_names_as_choice_labels() { serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); let routes = values - .pointer_mut("/spec/sandboxes/0/agent/inference/routes") + .pointer_mut("/spec/sandboxes/assistant/agent/inference/routes") .unwrap() .as_array_mut() .unwrap(); @@ -363,7 +373,7 @@ fn tree_branches_on_sdk_exclusive_forms() { let mut values: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - values["spec"]["sandboxes"][0]["agent"] + values["spec"]["sandboxes"]["assistant"]["agent"] .as_object_mut() .unwrap() .remove("inference"); @@ -372,11 +382,11 @@ fn tree_branches_on_sdk_exclusive_forms() { .print_tree(&capabilities) .unwrap(); assert!( - tree.contains("Choices for form:/spec/sandboxes/0/agent"), + tree.contains("Choices for form:/spec/sandboxes/assistant/agent"), "{tree}" ); assert!( - tree.contains("/spec/sandboxes/0/agent/inferenceRef: "), + tree.contains("/spec/sandboxes/assistant/agent/inferenceRef: "), "{tree}" ); } @@ -390,9 +400,9 @@ fn minimum_inline_fixture_prints_the_questions_it_can_materialize() { for field in [ "/metadata/name", "/spec/gateway/management", - "/spec/sandboxes/0/harness/kind", - "/spec/sandboxes/0/agent/inference/routes/0/name", - "/spec/sandboxes/0/agent/inference/routes/0/overrides/model", + "/spec/sandboxes/assistant/harness/kind", + "/spec/sandboxes/assistant/agent/inference/routes/0/name", + "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model", ] { assert!(tree.contains(field), "missing {field}: {tree}"); } diff --git a/crates/nemoclaw-authoring/tests/onboarding_journey_presets.rs b/crates/nemoclaw-authoring/tests/onboarding_journey_presets.rs index 02074fa2902..f96671f91be 100644 --- a/crates/nemoclaw-authoring/tests/onboarding_journey_presets.rs +++ b/crates/nemoclaw-authoring/tests/onboarding_journey_presets.rs @@ -13,7 +13,7 @@ fn guided() -> nemoclaw_authoring::JourneyState { PartialDocument::from_yaml(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); JourneyDefinition::new("guided-presets", base) - .ask(["/spec/sandboxes/0/harness/kind", "inference:preset"]) + .ask(["/spec/sandboxes/assistant/harness/kind", "inference:preset"]) .ask([JourneyScope::InferenceApi]) .ask([JourneyScope::RouteModels]) .start(&capabilities) @@ -35,7 +35,7 @@ fn the_journey_advertises_every_fabric_harness_and_curated_provider() { let state = guided(); let resolution = state.resolve(&capabilities).unwrap(); let harnesses = resolution - .question("/spec/sandboxes/0/harness/kind") + .question("/spec/sandboxes/assistant/harness/kind") .unwrap(); assert_eq!( harnesses.choices(), @@ -64,7 +64,7 @@ fn every_curated_preset_and_protocol_roundtrips_through_the_sdk() { state .answer(&capabilities, "inference:preset", Some(json!(preset.id()))) .unwrap(); - let endpoint = "/spec/inferenceProviders/0/endpoint"; + let endpoint = "/spec/inferenceProviders/nvidia-prod/endpoint"; if state .resolve(&capabilities) .unwrap() @@ -79,7 +79,7 @@ fn every_curated_preset_and_protocol_roundtrips_through_the_sdk() { ) .unwrap(); } - let api_path = "/spec/inferenceProviders/0/api"; + let api_path = "/spec/inferenceProviders/nvidia-prod/api"; state .answer( &capabilities, @@ -87,7 +87,7 @@ fn every_curated_preset_and_protocol_roundtrips_through_the_sdk() { Some(serde_json::to_value(api).unwrap()), ) .unwrap(); - let model_path = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; + let model_path = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; if state .resolve(&capabilities) .unwrap() @@ -129,17 +129,12 @@ fn custom_endpoint_questions_stay_user_facing_without_internal_provider_names() Some(json!("openai-compatible")), ) .unwrap(); - let endpoint = "/spec/inferenceProviders/0/endpoint"; + let endpoint = "/spec/inferenceProviders/nvidia-prod/endpoint"; let resolution = state.resolve(&capabilities).unwrap(); assert!(resolution.question(endpoint).is_some()); assert!( resolution - .question("/spec/inferenceProviders/0/name") - .is_none() - ); - assert!( - resolution - .question("/spec/inferenceProviders/0/credential/env") + .question("/spec/inferenceProviders/nvidia-prod/credential/env") .is_none() ); state @@ -149,7 +144,7 @@ fn custom_endpoint_questions_stay_user_facing_without_internal_provider_names() Some(json!("https://inference.example.com/v1")), ) .unwrap(); - let model = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; + let model = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; state .answer(&capabilities, model, Some(json!("example/reasoning-model"))) .unwrap(); @@ -177,7 +172,7 @@ fn switching_the_target_preserves_the_selected_model() { .ask(["/spec/gateway/target"]) .start(&capabilities) .unwrap(); - let model = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; + let model = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; let before: Value = state.values().pointer(model).unwrap().clone(); let podman = "unix:///run/user/501/podman/podman.sock"; crate::support::found_local_engines( @@ -197,7 +192,7 @@ fn switching_the_target_preserves_the_selected_model() { #[test] fn provider_presets_offer_the_expected_connection_and_model_suggestions() { let capabilities = Capabilities::available(); - let model = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; + let model = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; let cases = [ ( ProviderPreset::OpenAi, @@ -261,7 +256,7 @@ fn a_hermes_author_can_select_nous_without_losing_the_selected_harness() { state .answer( &capabilities, - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", Some(json!("nvidia.fabric.hermes")), ) .unwrap(); @@ -278,13 +273,15 @@ fn a_hermes_author_can_select_nous_without_losing_the_selected_harness() { .answer(&capabilities, "inference:preset", Some(json!("nous"))) .unwrap(); assert_eq!( - state.values().pointer("/spec/sandboxes/0/harness/kind"), + state + .values() + .pointer("/spec/sandboxes/assistant/harness/kind"), Some(&json!("nvidia.fabric.hermes")) ); assert_eq!( state .values() - .pointer("/spec/inferenceProviders/0/endpoint"), + .pointer("/spec/inferenceProviders/nvidia-prod/endpoint"), Some(&json!("https://inference-api.nousresearch.com/v1")) ); } @@ -296,7 +293,7 @@ fn a_pi_author_can_explicitly_choose_responses_api() { state .answer( &capabilities, - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", Some(json!("nvidia.fabric.pi")), ) .unwrap(); @@ -307,7 +304,7 @@ fn a_pi_author_can_explicitly_choose_responses_api() { Some(json!("nvidia-endpoints")), ) .unwrap(); - let api = "/spec/inferenceProviders/0/api"; + let api = "/spec/inferenceProviders/nvidia-prod/api"; state .answer(&capabilities, api, Some(json!("openai-responses"))) .unwrap(); diff --git a/crates/nemoclaw-authoring/tests/partial_documents.rs b/crates/nemoclaw-authoring/tests/partial_documents.rs index 51e1cd5c613..0b8035898e6 100644 --- a/crates/nemoclaw-authoring/tests/partial_documents.rs +++ b/crates/nemoclaw-authoring/tests/partial_documents.rs @@ -7,7 +7,7 @@ use nemoclaw_sdk::config::Document; #[test] fn sparse_input_reports_missing_values_without_constructing_a_document() { let partial = PartialDocument::from_yaml( - b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nspec:\n sandboxes:\n - harness:\n kind: nvidia.fabric.openclaw\n", + b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nspec:\n sandboxes:\n assistant:\n harness:\n kind: nvidia.fabric.openclaw\n", ) .unwrap(); let assessment = partial.assess(); @@ -29,7 +29,7 @@ fn sparse_input_reports_missing_values_without_constructing_a_document() { #[test] fn supplied_invalid_name_is_distinct_from_missing_values() { let partial = PartialDocument::from_yaml( - b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nmetadata:\n name: Bad Name\nspec:\n sandboxes:\n - harness:\n kind: nvidia.fabric.openclaw\n", + b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nmetadata:\n name: Bad Name\nspec:\n sandboxes:\n assistant:\n harness:\n kind: nvidia.fabric.openclaw\n", ) .unwrap(); let assessment = partial.assess(); @@ -64,7 +64,7 @@ fn inference_form_is_pending_when_absent_and_invalid_when_both_forms_are_supplie let original = Document::parse(yaml.as_slice()).unwrap(); let mut value = serde_json::to_value(original).unwrap(); let agent = value - .pointer_mut("/spec/sandboxes/0/agent") + .pointer_mut("/spec/sandboxes/assistant/agent") .unwrap() .as_object_mut() .unwrap(); @@ -72,11 +72,12 @@ fn inference_form_is_pending_when_absent_and_invalid_when_both_forms_are_supplie let partial = PartialDocument::from_yaml(value.to_string().as_bytes()).unwrap(); let assessment = partial.assess(); assert!(assessment.issues().iter().any(|issue| { - issue.path() == "/spec/sandboxes/0/agent" && issue.kind() == PartialIssueKind::Deferred + issue.path() == "/spec/sandboxes/assistant/agent" + && issue.kind() == PartialIssueKind::Deferred })); let agent = value - .pointer_mut("/spec/sandboxes/0/agent") + .pointer_mut("/spec/sandboxes/assistant/agent") .unwrap() .as_object_mut() .unwrap(); @@ -85,6 +86,7 @@ fn inference_form_is_pending_when_absent_and_invalid_when_both_forms_are_supplie let partial = PartialDocument::from_yaml(value.to_string().as_bytes()).unwrap(); let assessment = partial.assess(); assert!(assessment.issues().iter().any(|issue| { - issue.path() == "/spec/sandboxes/0/agent" && issue.kind() == PartialIssueKind::Invalid + issue.path() == "/spec/sandboxes/assistant/agent" + && issue.kind() == PartialIssueKind::Invalid })); } diff --git a/crates/nemoclaw-authoring/tests/support.rs b/crates/nemoclaw-authoring/tests/support.rs index 98327809292..3bd0109d5b4 100644 --- a/crates/nemoclaw-authoring/tests/support.rs +++ b/crates/nemoclaw-authoring/tests/support.rs @@ -21,7 +21,9 @@ pub struct Target { /// Read a one-sandbox document's target directly, independently of the code under test. pub fn target(document: &Document) -> Target { - let sandbox = &document.spec.sandboxes[0]; + let [sandbox] = document.spec.sandboxes.values().collect::>()[..] else { + panic!("the document has one sandbox"); + }; Target { engine: document.spec.gateway.image_engine().to_owned(), compute_driver: document.spec.gateway.compute_driver(), diff --git a/crates/nemoclaw-authoring/tests/target_assessment.rs b/crates/nemoclaw-authoring/tests/target_assessment.rs index bcde4a22002..4b0d52cc9bb 100644 --- a/crates/nemoclaw-authoring/tests/target_assessment.rs +++ b/crates/nemoclaw-authoring/tests/target_assessment.rs @@ -260,8 +260,13 @@ fn editing_the_target_leaves_only_the_edited_observation_unfound() { before: document(), engine_observed: true, change: |document| { - document.spec.sandboxes[0].image.ref_ = - format!("another-image@sha256:{}", "0".repeat(64)); + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .image + .ref_ = format!("another-image@sha256:{}", "0".repeat(64)); }, engine_unobserved: false, image_unobserved: true, @@ -447,7 +452,7 @@ fn cluster_document(management: &str) -> Document { "target": {"kubernetes": {}} }) }; - value["spec"]["sandboxes"][0]["image"]["metadata"] = + value["spec"]["sandboxes"]["assistant"]["image"]["metadata"] = serde_json::json!({"env": "IMAGE_METADATA"}); Document::parse(value.to_string().as_bytes()).unwrap() } diff --git a/crates/nemoclaw-authoring/tests/target_prerequisites.rs b/crates/nemoclaw-authoring/tests/target_prerequisites.rs index dad6444e627..449bdc94f86 100644 --- a/crates/nemoclaw-authoring/tests/target_prerequisites.rs +++ b/crates/nemoclaw-authoring/tests/target_prerequisites.rs @@ -121,7 +121,7 @@ fn one_resolution_combines_model_suggestions_and_target_compatibility() { let resolved = state .resolve_with_observations(&capabilities, &observations) .unwrap(); - let model = "/spec/sandboxes/0/agent/inference/routes/0/overrides/model"; + let model = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"; assert!( resolved .question(model) diff --git a/crates/nemoclaw-build/src/ci/live.rs b/crates/nemoclaw-build/src/ci/live.rs index cb6ae980707..44eb0580200 100644 --- a/crates/nemoclaw-build/src/ci/live.rs +++ b/crates/nemoclaw-build/src/ci/live.rs @@ -84,11 +84,11 @@ spec: endpoint: http://127.0.0.1:{port} networkCidr: {subnet} inferenceProviders: - - name: hosted + hosted: provider: openai endpoint: https://inference.example.test/v1 sandboxes: - - name: assistant + assistant: image: ref: {image} network: diff --git a/crates/nemoclaw-build/src/schema/reference.rs b/crates/nemoclaw-build/src/schema/reference.rs index 4395d22e114..e5fb4a36dfb 100644 --- a/crates/nemoclaw-build/src/schema/reference.rs +++ b/crates/nemoclaw-build/src/schema/reference.rs @@ -236,6 +236,7 @@ fn guide(name: &str) -> &'static str { "[Managed models](../models.md)" } "InferenceProvider" + | "InlineInferenceProvider" | "Inference" | "Route" | "Overrides" @@ -321,6 +322,8 @@ fn constraints(schema: &Value) -> String { ("maxLength", "maximum characters"), ("minItems", "minimum items"), ("maxItems", "maximum items"), + ("minProperties", "minimum entries"), + ("maxProperties", "maximum entries"), ] { if let Some(value) = schema.get(key) { parts.push(format!("{label} {value}")); @@ -444,6 +447,26 @@ mod tests { } } + #[test] + fn map_entry_bounds_render_beside_the_key_pattern() { + let input = schema( + json!({"entries":{"description":"Entries by name.", "type":"object", + "minProperties":1, "maxProperties":32, "propertyNames":{"pattern":"^[a-z]+$"}, + "additionalProperties":{"type":"string"}}}), + json!({}), + ); + let markdown = render_reference(&input).unwrap(); + assert!( + markdown.contains("minimum entries 1; maximum entries 32; keys: pattern `^[a-z]+$`"), + "{markdown}" + ); + } + + #[test] + fn inline_inference_providers_share_the_inference_guide() { + assert_eq!(guide("InlineInferenceProvider"), guide("InferenceProvider")); + } + #[test] fn equivalent_alternative_types_do_not_repeat_or_invent_constraints() { assert_eq!( diff --git a/crates/nemoclaw-build/tests/ci.rs b/crates/nemoclaw-build/tests/ci.rs index 570ab7ce388..ffcf559422c 100644 --- a/crates/nemoclaw-build/tests/ci.rs +++ b/crates/nemoclaw-build/tests/ci.rs @@ -108,7 +108,7 @@ fn gateway_documents_are_fresh_and_avoid_ports_and_subnets_in_use() { }); let value: serde_json::Value = serde_saphyr::from_str(&document).unwrap(); assert!( - value["spec"]["sandboxes"][0]["harness"] + value["spec"]["sandboxes"]["assistant"]["harness"] .get("settings") .is_none() ); @@ -123,7 +123,7 @@ fn gateway_documents_are_fresh_and_avoid_ports_and_subnets_in_use() { }); let with_settings: serde_json::Value = serde_saphyr::from_str(&with_settings).unwrap(); assert_eq!( - with_settings["spec"]["sandboxes"][0]["harness"]["settings"], + with_settings["spec"]["sandboxes"]["assistant"]["harness"]["settings"], serde_json::json!({"reply": "dummy-reply"}) ); assert_eq!(value["metadata"]["uid"], first.as_str()); @@ -132,11 +132,11 @@ fn gateway_documents_are_fresh_and_avoid_ports_and_subnets_in_use() { assert_eq!(docker["endpoint"], "http://127.0.0.1:17950"); assert_eq!(docker["networkCidr"], chosen.as_str()); assert_eq!( - value["spec"]["sandboxes"][0]["image"]["ref"], + value["spec"]["sandboxes"]["assistant"]["image"]["ref"], "nc-live@sha256:abc" ); assert_eq!( - value["spec"]["sandboxes"][0]["harness"]["kind"], + value["spec"]["sandboxes"]["assistant"]["harness"]["kind"], "nvidia.fabric.pi" ); assert!(value["spec"].get("services").is_none()); diff --git a/crates/nemoclaw-cli/tests/commands.rs b/crates/nemoclaw-cli/tests/commands.rs index 96161ca2b36..06ff9d434b1 100644 --- a/crates/nemoclaw-cli/tests/commands.rs +++ b/crates/nemoclaw-cli/tests/commands.rs @@ -195,7 +195,7 @@ fn unsupported_ownership_annotations_leave_an_applied_deployment_unchanged() { ) .unwrap(); let mut invalid = serde_json::to_value(&document).unwrap(); - invalid["spec"]["inferenceProviders"][0]["management"] = serde_json::json!("external"); + invalid["spec"]["inferenceProviders"]["local"]["management"] = serde_json::json!("external"); let config = directory.path().join("unsupported.yaml"); fs::write(&config, invalid.to_string()).unwrap(); let output = Command::new(env!("CARGO_BIN_EXE_nemoclaw")) @@ -214,7 +214,7 @@ fn unsupported_ownership_annotations_leave_an_applied_deployment_unchanged() { "{diagnostic}" ); assert!( - diagnostic.contains("spec.inferenceProviders[0]") + diagnostic.contains("spec.inferenceProviders.local") && diagnostic.contains("unknown fields are not allowed"), "{diagnostic}" ); diff --git a/crates/nemoclaw-e2e/fixtures/hermes-nvidia-hosted/v1.yaml b/crates/nemoclaw-e2e/fixtures/hermes-nvidia-hosted/v1.yaml index b8cee6a0500..c5d6c6ce891 100644 --- a/crates/nemoclaw-e2e/fixtures/hermes-nvidia-hosted/v1.yaml +++ b/crates/nemoclaw-e2e/fixtures/hermes-nvidia-hosted/v1.yaml @@ -17,14 +17,14 @@ spec: engine: unix:///var/run/docker.sock networkCidr: 172.30.187.0/24 inferenceProviders: - - name: hosted-nvidia-prod + hosted-nvidia-prod: provider: openai api: openai-completions endpoint: https://integrate.api.nvidia.com/v1 credential: env: NVIDIA_INFERENCE_API_KEY sandboxes: - - name: assistant + assistant: harness: kind: nvidia.fabric.hermes settings: diff --git a/crates/nemoclaw-e2e/fixtures/openclaw-nvidia-hosted/v1.yaml b/crates/nemoclaw-e2e/fixtures/openclaw-nvidia-hosted/v1.yaml index c9c6f061a9d..6bd65f25378 100644 --- a/crates/nemoclaw-e2e/fixtures/openclaw-nvidia-hosted/v1.yaml +++ b/crates/nemoclaw-e2e/fixtures/openclaw-nvidia-hosted/v1.yaml @@ -18,14 +18,14 @@ spec: engine: unix:///var/run/docker.sock networkCidr: 172.30.60.0/24 inferenceProviders: - - name: hosted-nvidia-prod + hosted-nvidia-prod: provider: openai api: openai-completions endpoint: https://integrate.api.nvidia.com/v1 credential: env: NVIDIA_INFERENCE_API_KEY sandboxes: - - name: assistant + assistant: harness: kind: nvidia.fabric.openclaw image: diff --git a/crates/nemoclaw-e2e/src/image_runtime.rs b/crates/nemoclaw-e2e/src/image_runtime.rs index a1dc48748dd..a0c2ca80291 100644 --- a/crates/nemoclaw-e2e/src/image_runtime.rs +++ b/crates/nemoclaw-e2e/src/image_runtime.rs @@ -34,14 +34,10 @@ pub fn targets( serde_json::json!(["/usr/local/bin/python3.99"]).to_string(), ); } else if target.kind == "sandbox" { - let sandbox = document - .spec - .sandboxes - .iter() - .find(|sandbox| sandbox.name == target.values["name"]) - .unwrap(); - let requirements = - nemoclaw_sdk::fabric_capabilities::requirements_for_sandbox(document, sandbox)?; + let requirements = nemoclaw_sdk::fabric_capabilities::requirements_for_sandbox( + document, + &target.values["name"], + )?; let adapter = requirements.configuration["harness"]["adapter_id"] .as_str() .unwrap(); @@ -96,7 +92,7 @@ pub async fn engine(document: &mut Document) -> transport::Fixture { let references: Vec<_> = document .spec .sandboxes - .iter() + .values() .map(|sandbox| sandbox.image.ref_.clone()) .collect(); let fixture = transport::Fixture::engine(move |request| { diff --git a/crates/nemoclaw-e2e/tests/brev.rs b/crates/nemoclaw-e2e/tests/brev.rs index b37b3ebfebd..58b17eb744e 100644 --- a/crates/nemoclaw-e2e/tests/brev.rs +++ b/crates/nemoclaw-e2e/tests/brev.rs @@ -346,7 +346,7 @@ async fn bare_brev_hosted_openclaw_lifecycle() { ); assert_eq!( document - .sandbox_harness(&document.spec.sandboxes[0]) + .sandbox_harness(document.spec.sandboxes.keys().next().unwrap()) .unwrap() .kind, "nvidia.fabric.openclaw".parse().unwrap() @@ -436,7 +436,7 @@ async fn bare_brev_hosted_openclaw_lifecycle() { let response = openclaw_reply( &client, &binding, - &document.spec.sandboxes[0].agent.name, + &document.spec.sandboxes.values().next().unwrap().agent.name, &format!("{}-brev", document.metadata.uid), ) .await; diff --git a/crates/nemoclaw-e2e/tests/deployment.rs b/crates/nemoclaw-e2e/tests/deployment.rs index 2fe0edfb267..6980b2b9a21 100644 --- a/crates/nemoclaw-e2e/tests/deployment.rs +++ b/crates/nemoclaw-e2e/tests/deployment.rs @@ -168,9 +168,8 @@ async fn independent_sandboxes_reconcile_concurrently_and_retain_shared_dependen .unwrap(); *document.spec.gateway.endpoint_mut() = fixture.endpoint.clone(); let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; - let mut second = document.spec.sandboxes[0].clone(); - second.name = "independent".into(); - document.spec.sandboxes.push(second); + let second = document.spec.sandboxes["assistant"].clone(); + document.spec.sandboxes.insert("independent".into(), second); fixture.state.lock().unwrap().sandbox_create_delay = std::time::Duration::from_secs(2); let deployment = Deployment::new(directory.path(), &bundle); let cancel = CancellationToken::new(); @@ -314,7 +313,11 @@ async fn interrupted_create_preserves_pending_targets_allows_unrelated_intent_an assert_eq!(fixture.state.lock().unwrap().effects, effects); assert_apply_unfinished(&deployment, &cancel).await; let mut changed = document.clone(); - changed.spec.sandboxes[0] + changed + .spec + .sandboxes + .get_mut("assistant") + .unwrap() .agent .inference .as_mut() @@ -389,15 +392,14 @@ async fn sdk_apply_cli_export_sdk_reapply_and_cli_destroy_share_state() { async fn separate_agent_sandboxes_cli_export_reapply_and_policy_drift() { let mut document = Document::parse(include_str!("../../../examples/fabric-openclaw.yaml").as_bytes()).unwrap(); - let primary = document.spec.sandboxes[0].clone(); + let primary = document.spec.sandboxes["assistant"].clone(); for name in ["reader", "reviewer", "auditor"] { let mut sandbox = primary.clone(); - sandbox.name = name.into(); sandbox.agent.name = name.into(); sandbox.agent.tools = Some(nemoclaw_sdk::config::AgentTools { allow: vec!["read".into()], }); - document.spec.sandboxes.push(sandbox); + document.spec.sandboxes.insert(name.into(), sandbox); } let lifecycle = Lifecycle::start(&document.yaml().unwrap()).await; let effects = lifecycle.apply().await; @@ -414,7 +416,11 @@ async fn tool_disclosure_cli_export_reapply_and_native_settings_drift() { // both modes, so one deployment covers their drift detection. let mut document = Document::parse(include_str!("../../../examples/fabric-openclaw.yaml").as_bytes()).unwrap(); - document.spec.sandboxes[0] + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() .harness .as_mut() .unwrap() @@ -424,8 +430,12 @@ async fn tool_disclosure_cli_export_reapply_and_native_settings_drift() { .unwrap(), ); // Export and reapply also cover an authored inference API. - document.spec.inference_providers[0].api = - Some(nemoclaw_sdk::config::InferenceApi::OpenaiCompletions); + document + .spec + .inference_providers + .get_mut("local") + .unwrap() + .api = Some(nemoclaw_sdk::config::InferenceApi::OpenaiCompletions); let lifecycle = Lifecycle::start(&document.yaml().unwrap()).await; let effects = lifecycle.apply().await; assert_eq!(effects, lifecycle.document.spec.sandboxes.len() + 3); @@ -445,7 +455,13 @@ async fn web_search_cli_export_reapply_and_registration_drift() { "search":{"kind":"webSearch","provider":"tavily","credential":{"env":"SEARCH_KEY"}} })) .unwrap(); - document.spec.sandboxes[0].agent.integration_refs = vec!["search".into()]; + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .agent + .integration_refs = vec!["search".into()]; let lifecycle = Lifecycle::start(&document.yaml().unwrap()).await; let effects = lifecycle.apply().await; assert_eq!(effects, lifecycle.document.spec.sandboxes.len() + 5); @@ -607,8 +623,9 @@ impl Lifecycle { /// A search profile without endpoints, or a sandbox without its provider /// attachments, stops plan and export until the gateway is restored. async fn assert_search_registration_drift(&self) { - let search_provider = self.document.spec.sandboxes[0] - .integration_bindings(&self.document.spec.integrations) + let (name, sandbox) = self.document.spec.sandboxes.first_key_value().unwrap(); + let search_provider = sandbox + .integration_bindings(name, &self.document.spec.integrations) .unwrap() .first() .map(|binding| match binding.definition { @@ -656,11 +673,7 @@ impl Lifecycle { .unwrap() .profiles .insert(key, profile); - let sandbox_key = format!( - "{}/{}", - self.document.workspace(), - self.document.spec.sandboxes[0].name - ); + let sandbox_key = format!("{}/{name}", self.document.workspace()); let attached = self.fixture.state.lock().unwrap().sandboxes[&sandbox_key] .spec .as_ref() @@ -708,7 +721,13 @@ impl Lifecycle { async fn assert_tool_policy_drift(&self, effects: usize) { let state = fs::read(self.directory.path().join("terraform.tfstate")).unwrap(); let mut broadened = self.document.clone(); - broadened.spec.sandboxes[1].agent.tools = None; + broadened + .spec + .sandboxes + .get_mut("reader") + .unwrap() + .agent + .tools = None; let plan = self .deployment .plan(&broadened, &self.cancel) @@ -744,11 +763,8 @@ impl Lifecycle { /// The first sandbox's Fabric configuration arrives on stdin without the /// credential, and its drift is planned without effects. async fn assert_native_settings_drift(&self, effects: usize) { - let key = format!( - "{}/{}", - self.document.workspace(), - self.document.spec.sandboxes[0].name - ); + let (name, _) = self.document.spec.sandboxes.first_key_value().unwrap(); + let key = format!("{}/{name}", self.document.workspace()); let sandbox_id = self.fixture.state.lock().unwrap().sandboxes[&key] .metadata .as_ref() @@ -759,11 +775,7 @@ impl Lifecycle { self.fixture.state.lock().unwrap().fabric_configurations[&sandbox_id].clone(); assert_eq!( original, - nemoclaw_sdk::fabric_config::for_sandbox( - &self.document, - &self.document.spec.sandboxes[0] - ) - .unwrap() + nemoclaw_sdk::fabric_config::for_sandbox(&self.document, name).unwrap() ); assert!(!original.to_string().contains("fixture-only-inference-key")); { @@ -956,8 +968,9 @@ async fn destroy_does_not_require_the_inference_credential_or_rewrite_its_refere .unwrap(); *document.spec.gateway.endpoint_mut() = fixture.endpoint.clone(); let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; - document.spec.inference_providers[0].endpoint = "https://inference.example.test/v1".into(); - document.spec.inference_providers[0].credential = Some(nemoclaw_sdk::config::SecretRef { + let local = document.spec.inference_providers.get_mut("local").unwrap(); + local.endpoint = "https://inference.example.test/v1".into(); + local.credential = Some(nemoclaw_sdk::config::SecretRef { env: "NEMOCLAW_TEST_REMOVED_INFERENCE_KEY".into(), }); let cancel = CancellationToken::new(); @@ -1029,8 +1042,9 @@ async fn apply_preserves_bindings_without_generating_inference() { .unwrap(); *document.spec.gateway.endpoint_mut() = fixture.endpoint.clone(); let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; - document.spec.inference_providers[0].endpoint = "https://unreachable.invalid/v1".into(); - document.spec.inference_providers[0].credential = Some(nemoclaw_sdk::config::SecretRef { + let local = document.spec.inference_providers.get_mut("local").unwrap(); + local.endpoint = "https://unreachable.invalid/v1".into(); + local.credential = Some(nemoclaw_sdk::config::SecretRef { env: "MODEL_TOKEN".into(), }); let deployment = @@ -1116,7 +1130,12 @@ async fn apply_health_failure_retains_resources_and_unchanged_apply_checks_again let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; // Keep passive discovery identical across applies. An unroutable endpoint can // fail as either a transport error or a timeout. - document.spec.inference_providers[0].endpoint = "http://127.0.0.1:9/v1".into(); + document + .spec + .inference_providers + .get_mut("local") + .unwrap() + .endpoint = "http://127.0.0.1:9/v1".into(); let deployment = Deployment::new(directory.path(), &bundle); let cancel = CancellationToken::new(); fixture.state.lock().unwrap().health_report = Some(serde_json::json!({ @@ -1239,7 +1258,7 @@ async fn apply_health_failure_retains_resources_and_unchanged_apply_checks_again #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[ignore = "requires a verified NEMOCLAW_TEST_BUNDLE"] -async fn mixed_sandboxes_reorder_add_recover_export_and_destroy_independently() { +async fn mixed_sandboxes_add_recover_export_and_destroy_independently() { let bundle = PathBuf::from(std::env::var_os("NEMOCLAW_TEST_BUNDLE").unwrap()); let directory = tempfile::tempdir().unwrap(); let fixture = Fixture::start().await; @@ -1249,10 +1268,12 @@ async fn mixed_sandboxes_reorder_add_recover_export_and_destroy_independently() .unwrap(); *document.spec.gateway.endpoint_mut() = fixture.endpoint.clone(); let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; - let mut other = document.spec.sandboxes[0].clone(); - other.name = "research".into(); + let mut other = document.spec.sandboxes["assistant"].clone(); other.harness.as_mut().unwrap().kind = "nvidia.fabric.langchain.deepagents".parse().unwrap(); - document.spec.sandboxes.push(other.clone()); + document + .spec + .sandboxes + .insert("research".into(), other.clone()); let deployment = Deployment::new(directory.path(), &bundle); let cancel = CancellationToken::new(); let preview = deployment.plan(&document, &cancel).await.unwrap(); @@ -1264,25 +1285,7 @@ async fn mixed_sandboxes_reorder_add_recover_export_and_destroy_independently() let before: serde_json::Value = serde_json::from_slice(&fs::read(directory.path().join("terraform.tfstate")).unwrap()) .unwrap(); - document.spec.sandboxes.reverse(); - assert!( - deployment - .plan(&document, &cancel) - .await - .unwrap() - .changes - .is_empty() - ); - assert!( - deployment - .apply(&document, &cancel) - .await - .unwrap() - .changes - .is_empty() - ); - other.name = "third".into(); - document.spec.sandboxes.push(other); + document.spec.sandboxes.insert("third".into(), other); let added = deployment.plan(&document, &cancel).await.unwrap(); assert_eq!(added.changes.len(), 2); assert!( @@ -1499,7 +1502,11 @@ async fn failed_first_configuration_accepts_corrected_intent_without_recreating_ assert!(deployment.apply(&document, &cancel).await.is_err()); let sandboxes = fixture.state.lock().unwrap().sandboxes.clone(); let effects = fixture.state.lock().unwrap().effects; - document.spec.sandboxes[0] + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() .agent .inference .as_mut() @@ -1539,8 +1546,9 @@ async fn cli_redaction_preserves_failures_and_recovery_with_short_and_colliding_ .unwrap(); *document.spec.gateway.endpoint_mut() = fixture.endpoint.clone(); let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; - document.spec.inference_providers[0].endpoint = "https://127.0.0.1:9/v1".into(); - document.spec.inference_providers[0].credential = Some(nemoclaw_sdk::config::SecretRef { + let local = document.spec.inference_providers.get_mut("local").unwrap(); + local.endpoint = "https://127.0.0.1:9/v1".into(); + local.credential = Some(nemoclaw_sdk::config::SecretRef { env: "NEMOCLAW_TEST_REDACTION_KEY".into(), }); let input = directory.path().join("deployment.yaml"); @@ -1580,7 +1588,11 @@ async fn cli_redaction_preserves_failures_and_recovery_with_short_and_colliding_ ); let original = fixture.state.lock().unwrap().sandboxes.clone(); let effects = fixture.state.lock().unwrap().effects; - document.spec.sandboxes[0] + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() .agent .inference .as_mut() @@ -1678,7 +1690,7 @@ async fn rejected_policy_fails_promptly_with_context_and_allows_recovery_or_dest .unwrap(); *document.spec.gateway.endpoint_mut() = fixture.endpoint.clone(); let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; - let name = document.spec.sandboxes[0].name.clone(); + let name = document.spec.sandboxes.keys().next().unwrap().clone(); { let mut state = fixture.state.lock().unwrap(); state.sandbox_phase = Some(SandboxPhase::Starting); @@ -1777,6 +1789,13 @@ async fn rejected_policy_fails_promptly_with_context_and_allows_recovery_or_dest } } +/// Move the input's `from` sandbox to the key `to`. +fn rename_sandbox(input: &mut serde_json::Value, from: &str, to: &str) { + let sandboxes = input["spec"]["sandboxes"].as_object_mut().unwrap(); + let sandbox = sandboxes.remove(from).unwrap(); + sandboxes.insert(to.into(), sandbox); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[ignore = "requires a verified NEMOCLAW_TEST_BUNDLE; isolated gateway fixture"] async fn pi_start_failure_names_the_sandbox_in_cli_text_and_json_and_allows_destroy() { @@ -1789,8 +1808,8 @@ async fn pi_start_failure_names_the_sandbox_in_cli_text_and_json_and_allows_dest )) .unwrap(); input["spec"]["gateway"]["endpoint"] = fixture.endpoint.clone().into(); - input["spec"]["sandboxes"][0]["name"] = "coder".into(); - input["spec"]["sandboxes"][0]["harness"]["kind"] = "nvidia.fabric.pi".into(); + rename_sandbox(&mut input, "assistant", "coder"); + input["spec"]["sandboxes"]["coder"]["harness"]["kind"] = "nvidia.fabric.pi".into(); let mut document = Document::parse(input.to_string().as_bytes()).unwrap(); let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; let input = directory.path().join("input.yaml"); @@ -1882,7 +1901,7 @@ async fn sandbox_startup_failure_names_reason_and_guidance_and_allows_destroy() )) .unwrap(); input["spec"]["gateway"]["endpoint"] = fixture.endpoint.clone().into(); - input["spec"]["sandboxes"][0]["name"] = "coder".into(); + rename_sandbox(&mut input, "assistant", "coder"); let mut document = Document::parse(input.to_string().as_bytes()).unwrap(); let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; let input = directory.path().join("input.yaml"); @@ -1970,15 +1989,14 @@ async fn scoped_provider_labels_and_stopped_runtime_plans_preserve_authored_iden )) .unwrap(); input["spec"]["gateway"]["endpoint"] = fixture.endpoint.clone().into(); - let mut provider = input["spec"]["inferenceProviders"][0].take(); - provider["name"] = "responses".into(); - input["spec"] + let mut providers = input["spec"] .as_object_mut() .unwrap() - .remove("inferenceProviders"); - input["spec"]["sandboxes"][0]["inferenceProviders"] = serde_json::json!([provider]); - input["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["providerRef"] = - "responses".into(); + .remove("inferenceProviders") + .unwrap(); + let sandbox = &mut input["spec"]["sandboxes"]["assistant"]; + sandbox["inferenceProviders"] = serde_json::json!({"responses": providers["local"].take()}); + sandbox["agent"]["inference"]["routes"][0]["providerRef"] = "responses".into(); let mut document = Document::parse(input.to_string().as_bytes()).unwrap(); let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; let state = directory.path().join("state"); diff --git a/crates/nemoclaw-e2e/tests/docker_provider_proxy.rs b/crates/nemoclaw-e2e/tests/docker_provider_proxy.rs index 93700a19f9a..a96d7e3f495 100644 --- a/crates/nemoclaw-e2e/tests/docker_provider_proxy.rs +++ b/crates/nemoclaw-e2e/tests/docker_provider_proxy.rs @@ -422,7 +422,7 @@ fn proxy_configuration( .unwrap(); value["metadata"]["uid"] = json!(uid); value["spec"]["gateway"] = json!({"management":"external", "endpoint":gateway_endpoint}); - let provider = &mut value["spec"]["inferenceProviders"][0]; + let provider = &mut value["spec"]["inferenceProviders"]["local"]; provider["serviceRef"] = json!("ollama-auth"); value["spec"]["services"] = json!({"ollama-auth": { "kind":"ollamaProxy", diff --git a/crates/nemoclaw-e2e/tests/dummy_agent.rs b/crates/nemoclaw-e2e/tests/dummy_agent.rs index 35b43c53244..12def40186e 100644 --- a/crates/nemoclaw-e2e/tests/dummy_agent.rs +++ b/crates/nemoclaw-e2e/tests/dummy_agent.rs @@ -118,8 +118,8 @@ async fn the_dummy_agent_completes_a_managed_docker_lifecycle() { document.spec.gateway.compute_driver(), ComputeDriver::Docker ); - let sandbox = &document.spec.sandboxes[0]; - let harness = document.sandbox_harness(sandbox).unwrap(); + let (name, sandbox) = document.spec.sandboxes.first_key_value().unwrap(); + let harness = document.sandbox_harness(name).unwrap(); assert_eq!(harness.kind, "org.nemoclaw.dummy".parse().unwrap()); // The dummy replies with this setting, so the reply shows that apply // delivered the authored native settings to the running agent. @@ -130,7 +130,7 @@ async fn the_dummy_agent_completes_a_managed_docker_lifecycle() { .and_then(|reply| reply.as_str()) .expect("the document sets harness.settings.reply") .to_owned(); - let resource = format!("openshell_sandbox.{}", sandbox.name); + let resource = format!("openshell_sandbox.{name}"); let engine = document .spec .gateway diff --git a/crates/nemoclaw-e2e/tests/export_observations.rs b/crates/nemoclaw-e2e/tests/export_observations.rs index a7d4d565184..05ab581319e 100644 --- a/crates/nemoclaw-e2e/tests/export_observations.rs +++ b/crates/nemoclaw-e2e/tests/export_observations.rs @@ -90,8 +90,9 @@ async fn export_uses_provider_observations_without_resolving_inference_credentia .unwrap(); *document.spec.gateway.endpoint_mut() = fixture.endpoint.clone(); let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; - document.spec.inference_providers[0].endpoint = "https://models.example/v1".into(); - document.spec.inference_providers[0].credential = Some(nemoclaw_sdk::config::SecretRef { + let local = document.spec.inference_providers.get_mut("local").unwrap(); + local.endpoint = "https://models.example/v1".into(); + local.credential = Some(nemoclaw_sdk::config::SecretRef { env: "EXPORT_INFERENCE_REFERENCE".into(), }); let cancel = CancellationToken::new(); @@ -112,7 +113,11 @@ async fn export_uses_provider_observations_without_resolving_inference_credentia "CHANGED_EXPORT_REFERENCE".into(), ); } - document.spec.inference_providers[0] + document + .spec + .inference_providers + .get_mut("local") + .unwrap() .credential .as_mut() .unwrap() @@ -137,7 +142,15 @@ async fn export_rejects_observed_pi_model_drift_without_reconfiguring_it() { .unwrap(); *document.spec.gateway.endpoint_mut() = fixture.endpoint.clone(); let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; - document.spec.sandboxes[0].harness.as_mut().unwrap().kind = "nvidia.fabric.pi".parse().unwrap(); + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .harness + .as_mut() + .unwrap() + .kind = "nvidia.fabric.pi".parse().unwrap(); let deployment = Deployment::new(directory.path(), &bundle); let cancel = CancellationToken::new(); deployment.apply(&document, &cancel).await.unwrap(); @@ -198,25 +211,32 @@ async fn mixed_search_export_preserves_scopes_shared_registrations_and_state_on_ .unwrap(); *document.spec.gateway.endpoint_mut() = fixture.endpoint.clone(); let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; - document.spec.inference_providers[0].endpoint = "https://127.0.0.1:9/v1".into(); + document + .spec + .inference_providers + .get_mut("local") + .unwrap() + .endpoint = "https://127.0.0.1:9/v1".into(); document.spec.integrations = serde_json::from_value(serde_json::json!({ "shared-search":{"kind":"webSearch", "provider":"tavily", "credential":{"env":"EXPORT_TAVILY_KEY"}}, "unused-search":{"kind":"webSearch", "provider":"brave", "credential":{"env":"UNUSED_EXPORT_KEY"}} })).unwrap(); - document.spec.sandboxes[0].agent.integration_refs = vec!["shared-search".into()]; - let mut hermes = document.spec.sandboxes[0].clone(); - hermes.name = "hermes".into(); + let assistant = document.spec.sandboxes.get_mut("assistant").unwrap(); + assistant.agent.integration_refs = vec!["shared-search".into()]; + let mut hermes = assistant.clone(); hermes.harness.as_mut().unwrap().kind = "nvidia.fabric.hermes".parse().unwrap(); hermes.integrations = serde_json::from_value(serde_json::json!({ "sandbox-search":{"kind":"webSearch", "provider":"brave", "credential":{"env":"EXPORT_BRAVE_KEY"}} })).unwrap(); hermes.agent.integration_refs = vec!["sandbox-search".into()]; let mut pi = hermes.clone(); - pi.name = "pi".into(); pi.harness.as_mut().unwrap().kind = "nvidia.fabric.pi".parse().unwrap(); pi.agent.integration_refs.clear(); pi.agent.integrations = std::mem::take(&mut pi.integrations); - document.spec.sandboxes.extend([hermes, pi]); + document + .spec + .sandboxes + .extend([("hermes".into(), hermes), ("pi".into(), pi)]); let deployment = Deployment::new(directory.path(), &bundle).with_secrets(Arc::new(Values)); let cancel = CancellationToken::new(); deployment.apply(&document, &cancel).await.unwrap(); diff --git a/crates/nemoclaw-e2e/tests/fabric_deployment.rs b/crates/nemoclaw-e2e/tests/fabric_deployment.rs index 9b8fd487fc0..c4434791e99 100644 --- a/crates/nemoclaw-e2e/tests/fabric_deployment.rs +++ b/crates/nemoclaw-e2e/tests/fabric_deployment.rs @@ -50,20 +50,37 @@ async fn harness_reconciles_configuration_and_protects_sandbox_identity(harness: } }) .await; - document.spec.inference_providers[0].endpoint = format!("{}/v1", catalog.endpoint); - document.spec.sandboxes[0].harness.as_mut().unwrap().kind = harness.parse().unwrap(); + document + .spec + .inference_providers + .get_mut("local") + .unwrap() + .endpoint = format!("{}/v1", catalog.endpoint); + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .harness + .as_mut() + .unwrap() + .kind = harness.parse().unwrap(); if harness == "nvidia.fabric.pi" { let pi = Document::parse( include_str!("../../nemoclaw-sdk/tests/fixtures/config/fabric-pi.yaml").as_bytes(), ) .unwrap(); - document.spec.sandboxes[0] + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() .agent .inference .as_mut() .unwrap() .routes[0] - .overrides = pi.spec.sandboxes[0] + .overrides = pi.spec.sandboxes["assistant"] .agent .inference .as_ref() @@ -144,7 +161,11 @@ async fn harness_reconciles_configuration_and_protects_sandbox_identity(harness: ); if harness != "nvidia.fabric.pi" { let mut changed_model = document.clone(); - changed_model.spec.sandboxes[0] + changed_model + .spec + .sandboxes + .get_mut("assistant") + .unwrap() .agent .inference .as_mut() @@ -184,7 +205,11 @@ async fn harness_reconciles_configuration_and_protects_sandbox_identity(harness: let initial_writes = writes(); if harness == "nvidia.fabric.pi" { let mut changed_model = document.clone(); - changed_model.spec.sandboxes[0] + changed_model + .spec + .sandboxes + .get_mut("assistant") + .unwrap() .agent .inference .as_mut() @@ -192,7 +217,11 @@ async fn harness_reconciles_configuration_and_protects_sandbox_identity(harness: .routes[0] .overrides .model = "another-custom-model".into(); - changed_model.spec.sandboxes[0] + changed_model + .spec + .sandboxes + .get_mut("assistant") + .unwrap() .agent .inference .as_mut() @@ -210,11 +239,12 @@ async fn harness_reconciles_configuration_and_protects_sandbox_identity(harness: serde_json::json!("${runtime.value} %{native}"), ); let planned = deployment.plan(&changed_model, &cancel).await.unwrap(); - assert!(planned.changes.iter().any(|change| change.resource - == format!( - "fabric_agent_configuration.{}", - document.spec.sandboxes[0].name - ))); + assert!( + planned + .changes + .iter() + .any(|change| change.resource == "fabric_agent_configuration.assistant") + ); assert_eq!(writes(), initial_writes, "plan must not configure Pi"); let before = fs::read(directory.path().join("terraform.tfstate")).unwrap(); let state = fixture.state.clone(); @@ -291,22 +321,22 @@ async fn harness_reconciles_configuration_and_protects_sandbox_identity(harness: let sandboxes = fixture.state.lock().unwrap().sandboxes.clone(); let before_writes = writes(); let mut changed = document.clone(); - changed.spec.sandboxes[0].harness.as_mut().unwrap().kind = - if harness == "nvidia.fabric.langchain.deepagents" { - "nvidia.fabric.hermes".parse().unwrap() - } else { - "nvidia.fabric.langchain.deepagents".parse().unwrap() - }; - changed.spec.sandboxes[0].harness.as_mut().unwrap().config = None; - changed.spec.inference_providers[0].api = None; - changed.spec.sandboxes[0] - .agent - .inference - .as_mut() - .unwrap() - .routes[0] + let sandbox = changed.spec.sandboxes.get_mut("assistant").unwrap(); + sandbox.harness.as_mut().unwrap().kind = if harness == "nvidia.fabric.langchain.deepagents" { + "nvidia.fabric.hermes".parse().unwrap() + } else { + "nvidia.fabric.langchain.deepagents".parse().unwrap() + }; + sandbox.harness.as_mut().unwrap().config = None; + sandbox.agent.inference.as_mut().unwrap().routes[0] .overrides .settings = None; + changed + .spec + .inference_providers + .get_mut("local") + .unwrap() + .api = None; // An adapter change selects different image-scoped executable grants and // provider attachments. It cannot replace the retained sandbox implicitly. let state = fs::read(directory.path().join("terraform.tfstate")).unwrap(); @@ -315,7 +345,7 @@ async fn harness_reconciles_configuration_and_protects_sandbox_identity(harness: deployment.apply(&changed, &cancel).await.unwrap_err(), ] { assert!( - matches!(&error, nemoclaw_sdk::Error::SandboxChangeRefused { sandbox, action: "replace" } if sandbox == &document.spec.sandboxes[0].name), + matches!(&error, nemoclaw_sdk::Error::SandboxChangeRefused { sandbox, action: "replace" } if sandbox == "assistant"), "{error}" ); } @@ -331,7 +361,13 @@ async fn harness_reconciles_configuration_and_protects_sandbox_identity(harness: let state = fs::read(directory.path().join("terraform.tfstate")).unwrap(); let before_writes = writes(); let mut replacement = document.clone(); - replacement.spec.sandboxes[0].image.ref_ = format!("replacement@sha256:{}", "a".repeat(64)); + replacement + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .image + .ref_ = format!("replacement@sha256:{}", "a".repeat(64)); assert!( deployment.plan(&replacement, &cancel).await.is_err(), "{harness} sandbox replacement must be refused during plan" @@ -474,7 +510,11 @@ async fn failed_configuration_reports_safe_runtime_state_and_recovers_without_re .id .clone(); let effects = fixture.state.lock().unwrap().effects; - document.spec.sandboxes[0] + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() .agent .inference .as_mut() diff --git a/crates/nemoclaw-e2e/tests/fabric_live.rs b/crates/nemoclaw-e2e/tests/fabric_live.rs index ddec9891a73..d539940f179 100644 --- a/crates/nemoclaw-e2e/tests/fabric_live.rs +++ b/crates/nemoclaw-e2e/tests/fabric_live.rs @@ -145,7 +145,8 @@ async fn fabric_native_access_and_reconciliation_preserve_the_hosted_runtime() { let input = invocation_input("NEMOCLAW_LIVE_FABRIC_INPUT"); assert!(uses_independent_inference(&document)); let provider = document.inference_provider().unwrap(); - let agent = &document.spec.sandboxes[0].agent; + let sandbox = document.spec.sandboxes.values().next().unwrap(); + let agent = &sandbox.agent; assert!(matches!(document.spec.gateway, Gateway::External(_))); // Managed-service installation is qualified separately; this live target // exercises only an external inference provider. @@ -162,7 +163,7 @@ async fn fabric_native_access_and_reconciliation_preserve_the_hosted_runtime() { Arc::new(EnvironmentSecrets), ) .unwrap(); - if document.spec.sandboxes[0].network.policy == nemoclaw_sdk::config::NetworkPolicy::Isolated { + if sandbox.network.policy == nemoclaw_sdk::config::NetworkPolicy::Isolated { let denial = exec( &client, &binding, @@ -283,7 +284,7 @@ async fn dependency_upgrade_survives_apply_process_exit() { let reply = invoke( &client, &binding, - &document.spec.sandboxes[0].agent.name, + &document.spec.sandboxes.values().next().unwrap().agent.name, &input, ) .await; diff --git a/crates/nemoclaw-e2e/tests/helm_recovery.rs b/crates/nemoclaw-e2e/tests/helm_recovery.rs index fd9702ff110..e36fc3a36da 100644 --- a/crates/nemoclaw-e2e/tests/helm_recovery.rs +++ b/crates/nemoclaw-e2e/tests/helm_recovery.rs @@ -214,7 +214,8 @@ fn document() -> Document { "authentication":{"profile":"development"} }} }); - value["spec"]["sandboxes"][0]["image"]["metadata"] = json!({"env":"TEST_IMAGE_METADATA"}); + value["spec"]["sandboxes"]["assistant"]["image"]["metadata"] = + json!({"env":"TEST_IMAGE_METADATA"}); Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap() } diff --git a/crates/nemoclaw-e2e/tests/hosted_parity.rs b/crates/nemoclaw-e2e/tests/hosted_parity.rs index df4f6dcfc86..20741e83afb 100644 --- a/crates/nemoclaw-e2e/tests/hosted_parity.rs +++ b/crates/nemoclaw-e2e/tests/hosted_parity.rs @@ -28,9 +28,20 @@ fn authored_document(raw: &[u8], current: &[u8]) -> Document { assert_eq!(gateway.len(), 1, "unexpected historical gateway field"); let target = runtime["provider"].as_str().unwrap(); gateway.insert("target".into(), json!({target: {"endpoint": endpoint}})); - let sandboxes = projected["spec"]["sandboxes"].as_array_mut().unwrap(); + // v0 listed sandboxes and providers with a name field; current intent keys + // each by that name. + for collection in ["inferenceProviders", "sandboxes"] { + let entries = projected["spec"][collection].take(); + projected["spec"][collection] = keyed(entries); + } + let sandboxes = projected["spec"]["sandboxes"].as_object_mut().unwrap(); assert_eq!(sandboxes.len(), 1, "hosted parity requires one sandbox"); - let sandbox = sandboxes[0].as_object_mut().unwrap(); + let sandbox = sandboxes + .values_mut() + .next() + .unwrap() + .as_object_mut() + .unwrap(); let agents = sandbox .remove("agents") .expect("raw v0 export requires its historical agents list"); @@ -82,6 +93,24 @@ fn authored_document(raw: &[u8], current: &[u8]) -> Document { document } +fn keyed(entries: serde_json::Value) -> serde_json::Value { + let mut keyed = serde_json::Map::new(); + for mut entry in serde_json::from_value::>(entries) + .expect("raw v0 export lists its entries") + { + let name = entry + .as_object_mut() + .unwrap() + .remove("name") + .expect("raw v0 export names each entry"); + assert!( + keyed.insert(name.as_str().unwrap().into(), entry).is_none(), + "raw v0 export repeats a name" + ); + } + keyed.into() +} + #[test] fn live_inputs_preserve_raw_export_and_require_matching_authored_intent() { for (raw, current) in [ @@ -97,7 +126,13 @@ fn live_inputs_preserve_raw_export_and_require_matching_authored_intent() { let document = authored_document(raw, current); assert_eq!(document, Document::parse(current).unwrap()); let mut changed = document.clone(); - changed.spec.sandboxes[0].agent.name = "different-agent".into(); + changed + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .agent + .name = "different-agent".into(); assert!( std::panic::catch_unwind(|| authored_document(raw, changed.yaml().unwrap().as_bytes())) .is_err() @@ -118,8 +153,11 @@ fn assert_hosted_document(document: &Document, harness: HarnessKind, runtime_roo assert!(runtime.to_string().contains(DEFAULT_GATEWAY_IMAGE)); assert!(!document.yaml().unwrap().contains(DEFAULT_GATEWAY_IMAGE)); - let provider = &document.spec.inference_providers[0]; - assert_eq!(provider.name, "hosted-nvidia-prod"); + assert_eq!( + document.spec.inference_providers.keys().collect::>(), + ["hosted-nvidia-prod"] + ); + let provider = &document.spec.inference_providers["hosted-nvidia-prod"]; assert_eq!(provider.provider, InferenceProviderKind::Openai); assert_eq!(provider.endpoint, "https://integrate.api.nvidia.com/v1"); assert_eq!( @@ -128,7 +166,11 @@ fn assert_hosted_document(document: &Document, harness: HarnessKind, runtime_roo ); assert!(provider.service_ref.is_none()); - let sandbox = &document.spec.sandboxes[0]; + assert_eq!( + document.spec.sandboxes.keys().collect::>(), + ["assistant"] + ); + let sandbox = &document.spec.sandboxes["assistant"]; assert!(sandbox.image.ref_.contains("@sha256:")); assert_eq!(sandbox.image.ref_.rsplit(':').next().unwrap().len(), 64); assert_eq!( @@ -154,11 +196,11 @@ fn assert_hosted_document(document: &Document, harness: HarnessKind, runtime_roo "raw export policy must grant the v1 runtime root {root}" ); } - assert_eq!(document.sandbox_harness(sandbox).unwrap().kind, harness); - let inference = document.sandbox_inference(sandbox).unwrap(); + assert_eq!(document.sandbox_harness("assistant").unwrap().kind, harness); + let inference = document.sandbox_inference("assistant").unwrap(); assert_eq!( inference.routes[0].provider_ref.as_deref(), - Some(provider.name.as_str()) + Some("hosted-nvidia-prod") ); assert_eq!( inference.routes[0].overrides.model, @@ -184,7 +226,7 @@ fn hosted_hermes_scenario_preserves_authored_intent() { include_bytes!("../fixtures/hermes-nvidia-hosted/v1.yaml"), ); assert_hosted_document(&v1, "nvidia.fabric.hermes".parse().unwrap(), "/opt/hermes"); - let harness = v1.sandbox_harness(&v1.spec.sandboxes[0]).unwrap(); + let harness = v1.sandbox_harness("assistant").unwrap(); assert_eq!( harness.settings.as_ref().unwrap()["interfaces"], json!({"api":{"port":8643}}) diff --git a/crates/nemoclaw-e2e/tests/inference_discovery.rs b/crates/nemoclaw-e2e/tests/inference_discovery.rs index aa99e790e18..dd44796f4ed 100644 --- a/crates/nemoclaw-e2e/tests/inference_discovery.rs +++ b/crates/nemoclaw-e2e/tests/inference_discovery.rs @@ -68,9 +68,10 @@ async fn optional_catalog_failures_preserve_complete_unchanged_plans_and_typed_u .unwrap(); *document.spec.gateway.endpoint_mut() = fixture.endpoint.clone(); let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut document).await; - document.spec.inference_providers[0].provider = provider; - document.spec.inference_providers[0].api = Some(api); - document.spec.inference_providers[0].endpoint = endpoint.clone(); + let local = document.spec.inference_providers.get_mut("local").unwrap(); + local.provider = provider; + local.api = Some(api); + local.endpoint = endpoint.clone(); let input = directory.path().join("deployment.yaml"); fs::write(&input, document.yaml().unwrap()).unwrap(); let deployment = Deployment::new(directory.path(), &bundle); diff --git a/crates/nemoclaw-e2e/tests/kubernetes_live.rs b/crates/nemoclaw-e2e/tests/kubernetes_live.rs index 221c43aae2d..b8e05d01396 100644 --- a/crates/nemoclaw-e2e/tests/kubernetes_live.rs +++ b/crates/nemoclaw-e2e/tests/kubernetes_live.rs @@ -361,7 +361,8 @@ async fn the_gateway_installs_authenticates_and_is_removed_keeping_storage() { "authentication": {"profile": "development"} }} }); - value["spec"]["sandboxes"][0]["image"]["metadata"] = json!({"env": "TEST_IMAGE_METADATA"}); + value["spec"]["sandboxes"]["assistant"]["image"]["metadata"] = + json!({"env": "TEST_IMAGE_METADATA"}); let document = Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap(); let generations: Generations = [ "workspace", @@ -531,11 +532,11 @@ spec: namespace: {namespace} authentication: {{profile: development}} inferenceProviders: - - name: hosted + hosted: provider: openai endpoint: https://inference.example.test/v1 sandboxes: - - name: assistant + assistant: image: ref: {image} metadata: {{env: NEMOCLAW_TEST_AGENT_METADATA}} diff --git a/crates/nemoclaw-e2e/tests/managed_gateway.rs b/crates/nemoclaw-e2e/tests/managed_gateway.rs index 4357c8aded4..e7d7e1167b5 100644 --- a/crates/nemoclaw-e2e/tests/managed_gateway.rs +++ b/crates/nemoclaw-e2e/tests/managed_gateway.rs @@ -54,7 +54,13 @@ async fn managed_gateway_plan_apply_noop_destroy_and_recovery_use_real_opentofu( let mut document = Document::parse(fs::File::open(path("NEMOCLAW_TEST_GATEWAY_DOCUMENT")).unwrap()).unwrap(); assert!(matches!(document.spec.gateway, Gateway::Managed(_))); - assert!(document.spec.inference_providers[0].service_ref.is_none()); + assert!( + document + .spec + .inference_providers + .values() + .all(|provider| provider.service_ref.is_none()) + ); assert!(document.spec.services.is_empty()); let directory = path("NEMOCLAW_TEST_GATEWAY_STATE"); let deployment = Deployment::new(&directory, &path("NEMOCLAW_TEST_BUNDLE")); diff --git a/crates/nemoclaw-e2e/tests/model_live.rs b/crates/nemoclaw-e2e/tests/model_live.rs index 5032bc052df..eae78ccb0f0 100644 --- a/crates/nemoclaw-e2e/tests/model_live.rs +++ b/crates/nemoclaw-e2e/tests/model_live.rs @@ -81,7 +81,12 @@ async fn exercise(fresh: bool) { let directory = explicit("NEMOCLAW_LIVE_MODEL_STATE"); let deployment = Deployment::new(&directory, &explicit("NEMOCLAW_TEST_BUNDLE")); let cancel = CancellationToken::new(); - let service_name = document.spec.inference_providers[0] + let service_name = document + .spec + .inference_providers + .values() + .next() + .unwrap() .service_ref .as_ref() .unwrap(); diff --git a/crates/nemoclaw-e2e/tests/multiple_providers.rs b/crates/nemoclaw-e2e/tests/multiple_providers.rs index d7be4c534f4..54185093217 100644 --- a/crates/nemoclaw-e2e/tests/multiple_providers.rs +++ b/crates/nemoclaw-e2e/tests/multiple_providers.rs @@ -35,7 +35,7 @@ async fn provider_union_export_reapply_drift_and_destroy_remain_scoped_to_each_s *first.spec.gateway.endpoint_mut() = fixture.endpoint.clone(); // A closed loopback port fails the same way on every runner, so repeated // observations stay identical instead of timing out on the example hosts. - for provider in &mut first.spec.inference_providers { + for provider in first.spec.inference_providers.values_mut() { provider.endpoint = match provider.endpoint.split_once("://") { Some(("https", _)) => "https://127.0.0.1:9/v1", _ => "http://127.0.0.1:9/v1", @@ -45,7 +45,7 @@ async fn provider_union_export_reapply_drift_and_destroy_remain_scoped_to_each_s let _image_engine = nemoclaw_e2e::image_runtime::engine(&mut first).await; let mut second = first.clone(); second.metadata.uid = "7db61f79-1965-45ac-824a-1c3f3b26aa5d".into(); - second.spec.sandboxes.remove(0); + second.spec.sandboxes.remove("researcher"); assert_eq!(second.credential_names(), Vec::<&str>::new()); let first_state = tempfile::tempdir().unwrap(); let second_state = tempfile::tempdir().unwrap(); @@ -86,8 +86,8 @@ async fn provider_union_export_reapply_drift_and_destroy_remain_scoped_to_each_s &fs::read(first_state.path().join("terraform.tfstate")).unwrap(), &state, ); - let first_key = format!("{}/{}", first.workspace(), first.spec.sandboxes[0].name); - let second_key = format!("{}/{}", second.workspace(), second.spec.sandboxes[0].name); + let first_key = format!("{}/researcher", first.workspace()); + let second_key = format!("{}/writer", second.workspace()); let hosted = { let mut live = fixture.state.lock().unwrap(); let second_spec = live.sandboxes[&second_key].spec.as_ref().unwrap(); diff --git a/crates/nemoclaw-e2e/tests/openshell_contract_fixtures.rs b/crates/nemoclaw-e2e/tests/openshell_contract_fixtures.rs index 228c0fc0c1e..e44321869bb 100644 --- a/crates/nemoclaw-e2e/tests/openshell_contract_fixtures.rs +++ b/crates/nemoclaw-e2e/tests/openshell_contract_fixtures.rs @@ -33,7 +33,9 @@ fn fixture(mut document: Document) -> Option { if encoded.contains("managedService") { return None; } - for (index, sandbox) in document.spec.sandboxes.iter().enumerate() { + // Compile numbers each sandbox's data source by its position in name + // order, which is the map's iteration order. + for (index, sandbox) in document.spec.sandboxes.values().enumerate() { let kind = sandbox.harness.as_ref().map_or_else( || "nvidia.fabric.openclaw".to_owned(), |harness| harness.kind.to_string(), diff --git a/crates/nemoclaw-e2e/tests/remote_service.rs b/crates/nemoclaw-e2e/tests/remote_service.rs index 018a483fb63..d71b7191266 100644 --- a/crates/nemoclaw-e2e/tests/remote_service.rs +++ b/crates/nemoclaw-e2e/tests/remote_service.rs @@ -107,14 +107,15 @@ impl Scenario { )) .unwrap(); value["spec"]["services"]["qwen"] = source["spec"]["services"]["ollama-server"].clone(); - value["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"]["model"] = - json!("qwen3:0.6b"); + let route = + &mut value["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]; + route["overrides"]["model"] = json!("qwen3:0.6b"); } let check_pulls = harness == "nvidia.fabric.openclaw" && !authenticated; if check_pulls { value["spec"]["services"]["qwen"]["imagePullPolicy"] = json!("IfNotPresent"); } - value["spec"]["sandboxes"][0]["harness"]["kind"] = harness.into(); + value["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = harness.into(); value["spec"]["gateway"] = json!({"management":"external","endpoint":gateway.endpoint,"target":{"podman":{}}}); value["spec"]["services"]["qwen"]["placement"] = @@ -123,7 +124,7 @@ impl Scenario { json!({"endpoint":"http://10.0.0.8:18888/v1","bindAddress":"10.0.0.8"}); if authenticated { value["spec"]["services"]["qwen"]["authentication"] = "bearer".into(); - value["spec"]["sandboxes"][0]["agent"]["auth"] = json!({"method":"api-key"}); + value["spec"]["sandboxes"]["assistant"]["agent"]["auth"] = json!({"method":"api-key"}); } let mut image_document = Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap(); @@ -837,12 +838,7 @@ async fn refused_sandbox_changes_preserve_retained_intent( gateway: &Fixture, ) { let mut original = read(root, "config.yaml"); - let mut reviewer = original["spec"]["sandboxes"][0].clone(); - reviewer["name"] = json!("reviewer"); - original["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(reviewer); + original["spec"]["sandboxes"]["reviewer"] = original["spec"]["sandboxes"]["assistant"].clone(); save(root, "config.yaml", &original); run(root, bundle, "apply", "config.yaml", true).await; let before = [ @@ -857,14 +853,17 @@ async fn refused_sandbox_changes_preserve_retained_intent( let mut rejected = original.clone(); match change { "remove" => { - rejected["spec"]["sandboxes"].as_array_mut().unwrap().pop(); + rejected["spec"]["sandboxes"] + .as_object_mut() + .unwrap() + .remove("reviewer"); } "policy" => { - rejected["spec"]["sandboxes"][1]["network"] = + rejected["spec"]["sandboxes"]["reviewer"]["network"] = json!({"policy":{"explicit":{"version":1,"network_policies":{}}}}); } _ => { - rejected["spec"]["sandboxes"][1]["image"]["ref"] = + rejected["spec"]["sandboxes"]["reviewer"]["image"]["ref"] = json!(format!("sandbox@sha256:{}", "c".repeat(64))); if change == "image-with-runtime-change" { rejected["spec"]["services"]["qwen"]["image"] = diff --git a/crates/nemoclaw-e2e/tests/service_images/support.rs b/crates/nemoclaw-e2e/tests/service_images/support.rs index 957a2c881b4..543705f726c 100644 --- a/crates/nemoclaw-e2e/tests/service_images/support.rs +++ b/crates/nemoclaw-e2e/tests/service_images/support.rs @@ -235,20 +235,17 @@ impl Scenario { .unwrap(); value["metadata"]["uid"] = json!(self.uid); value["spec"]["gateway"] = json!({"management":"external","endpoint":self.gateway.endpoint,"target":{"docker":{"engine":self._metadata.endpoint}}}); - value["spec"]["inferenceProviders"] = json!([{"name":"local","provider":"openai","api":"openai-completions","serviceRef":"shared"}]); + value["spec"]["inferenceProviders"] = + json!({"local":{"provider":"openai","api":"openai-completions","serviceRef":"shared"}}); value["spec"]["services"] = json!({"shared":{"kind":"ollamaProxy","engine":"unix:///var/run/docker.sock","image":self.proxy_image,"imagePullPolicy":"Never","endpoint":self.endpoint,"upstream":{"endpoint":self.upstream,"model":{"name":"llama3:fixture","digest":"a".repeat(64)}}}}); - let mut sandbox = value["spec"]["sandboxes"][0].clone(); + let mut sandbox = value["spec"]["sandboxes"]["assistant"].clone(); sandbox["image"]["ref"] = json!(self.agents.image); sandbox["harness"] = self.agents.profile["harness"].clone(); sandbox["agent"]["inference"]["routes"][0]["overrides"]["model"] = json!("llama3:fixture"); value["spec"]["sandboxes"] = json!( (0..count) - .map(|index| { - let mut item = sandbox.clone(); - item["name"] = json!(format!("assistant-{index}")); - item - }) - .collect::>() + .map(|index| (format!("assistant-{index}"), sandbox.clone())) + .collect::>() ); Document::parse(value.to_string().as_bytes()).unwrap() } diff --git a/crates/nemoclaw-e2e/tests/shared_service.rs b/crates/nemoclaw-e2e/tests/shared_service.rs index 5c740c68532..6ff75a0f290 100644 --- a/crates/nemoclaw-e2e/tests/shared_service.rs +++ b/crates/nemoclaw-e2e/tests/shared_service.rs @@ -33,7 +33,7 @@ async fn shared_service_preserves_consumers_and_export_reapply() { assert_eq!(scenario.agent_identity("assistant-1"), survivor); let original = document.clone(); - document.spec.sandboxes.remove(0); + document.spec.sandboxes.remove("assistant-0"); let error = deployment.apply(&document, &cancel).await.unwrap_err(); assert!( matches!(error, nemoclaw_sdk::Error::SandboxChangeRefused { sandbox, action: "remove" } if sandbox == "assistant-0") diff --git a/crates/nemoclaw-e2e/tests/spark.rs b/crates/nemoclaw-e2e/tests/spark.rs index 50d92e1bd3a..92dd3371eb8 100644 --- a/crates/nemoclaw-e2e/tests/spark.rs +++ b/crates/nemoclaw-e2e/tests/spark.rs @@ -16,7 +16,12 @@ fn explicit_path(name: &str) -> PathBuf { } fn vllm(document: &Document) -> &Service { - let name = document.spec.inference_providers[0] + let name = document + .spec + .inference_providers + .values() + .next() + .unwrap() .service_ref .as_ref() .unwrap(); @@ -27,7 +32,12 @@ fn vllm(document: &Document) -> &Service { } fn vllm_mut(document: &mut Document) -> &mut Service { - let name = document.spec.inference_providers[0] + let name = document + .spec + .inference_providers + .values() + .next() + .unwrap() .service_ref .clone() .unwrap(); diff --git a/crates/nemoclaw-e2e/tests/web_search.rs b/crates/nemoclaw-e2e/tests/web_search.rs index fb599e3329c..b1343d09db1 100644 --- a/crates/nemoclaw-e2e/tests/web_search.rs +++ b/crates/nemoclaw-e2e/tests/web_search.rs @@ -47,7 +47,12 @@ async fn search_credential_lifecycle( "search":{"kind":"webSearch","provider":provider_type,"credential":{"env":"SEARCH_KEY"}} })) .unwrap(); - doc.spec.sandboxes[0].agent.integration_refs = vec!["search".into()]; + doc.spec + .sandboxes + .get_mut("assistant") + .unwrap() + .agent + .integration_refs = vec!["search".into()]; let client = OpenShell::connect( &doc.spec.gateway.connection(), Arc::new(Key("owned-search-key")), @@ -178,10 +183,14 @@ async fn separate_search_credentials_reach_only_their_selected_sandbox_attachmen let mut doc = Document::parse(include_str!("../../../examples/fabric-openclaw.yaml").as_bytes()).unwrap(); *doc.spec.gateway.endpoint_mut() = fixture.endpoint.clone(); - let mut other = doc.spec.sandboxes[0].clone(); - other.name = "other".into(); - doc.spec.sandboxes.push(other); - for (sandbox, reference) in doc.spec.sandboxes.iter_mut().zip(["SEARCH_A", "SEARCH_B"]) { + let other = doc.spec.sandboxes["assistant"].clone(); + doc.spec.sandboxes.insert("other".into(), other); + for (sandbox, reference) in doc + .spec + .sandboxes + .values_mut() + .zip(["SEARCH_A", "SEARCH_B"]) + { sandbox.integrations = serde_json::from_value(serde_json::json!({"search":{"kind":"webSearch","provider":"brave","credential":{"env":reference}}})).unwrap(); sandbox.agent.integration_refs = vec!["search".into()]; } @@ -197,7 +206,7 @@ async fn separate_search_credentials_reach_only_their_selected_sandbox_attachmen } } let state = fixture.state.lock().unwrap(); - for (sandbox, reference) in doc.spec.sandboxes.iter().zip(["SEARCH_A", "SEARCH_B"]) { + for (sandbox, reference) in doc.spec.sandboxes.keys().zip(["SEARCH_A", "SEARCH_B"]) { let provider = targets .iter() .find(|t| { @@ -212,7 +221,7 @@ async fn separate_search_credentials_reach_only_their_selected_sandbox_attachmen stored.credentials["BRAVE_API_KEY"], format!("fixture-{reference}") ); - let attached = &state.sandboxes[&format!("{}/{}", doc.workspace(), sandbox.name)] + let attached = &state.sandboxes[&format!("{}/{sandbox}", doc.workspace())] .spec .as_ref() .unwrap() diff --git a/crates/nemoclaw-onboarding/src/lib.rs b/crates/nemoclaw-onboarding/src/lib.rs index 81b5fce9439..fcb7a156c70 100644 --- a/crates/nemoclaw-onboarding/src/lib.rs +++ b/crates/nemoclaw-onboarding/src/lib.rs @@ -68,13 +68,13 @@ fn load_journey( .ok_or("template metadata must be an object")? .insert("uid".into(), serde_json::json!(new_deployment_uid()?)); let partial = PartialDocument::from_yaml(&serde_json::to_vec(&supplied)?)?; + // The harness question names the template's only sandbox by its key; + // `start` rejects a template without exactly one sandbox keyed by a name. + let harness = partial.harness_field(); JourneyDefinition::new("onboarding", partial) - .ask([ - "/metadata/name", - "/spec/sandboxes/0/harness/kind", - "/spec/gateway/target", - "inference:preset", - ]) + .ask(["/metadata/name"]) + .ask(harness) + .ask(["/spec/gateway/target", "inference:preset"]) .ask([JourneyScope::InferenceApi]) .ask([JourneyScope::RouteModels]) .ask([JourneyScope::ActiveAdapterSettings]) @@ -169,17 +169,60 @@ mod tests { let mut values: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - let second = values["spec"]["sandboxes"][0].clone(); - values["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(second); + values["spec"]["sandboxes"]["second"] = values["spec"]["sandboxes"]["assistant"].clone(); let yaml = serde_json::to_vec(&values).unwrap(); std::fs::write(&path, &yaml).unwrap(); assert!(load_journey(Source::Template(&path), &Capabilities::available()).is_err()); assert_eq!(std::fs::read(path).unwrap(), yaml); } + #[test] + fn a_template_sandbox_key_that_is_not_a_name_is_rejected_without_echoing_it() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("template.yaml"); + let mut values: serde_json::Value = + serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) + .unwrap(); + let sandboxes = values["spec"]["sandboxes"].as_object_mut().unwrap(); + let sandbox = sandboxes.remove("assistant").unwrap(); + sandboxes.insert("PRIVATE INVALID NAME".into(), sandbox); + std::fs::write(&path, serde_json::to_vec(&values).unwrap()).unwrap(); + let error = load_journey(Source::Template(&path), &Capabilities::available()) + .err() + .unwrap() + .to_string(); + assert_eq!( + error, + "journey: The v1 journey requires exactly one sandbox keyed by a lowercase name." + ); + } + + #[test] + fn the_harness_question_names_the_template_sandbox_by_its_key() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("template.yaml"); + let mut values: serde_json::Value = + serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) + .unwrap(); + let sandboxes = values["spec"]["sandboxes"].as_object_mut().unwrap(); + let sandbox = sandboxes.remove("assistant").unwrap(); + sandboxes.insert("coder".into(), sandbox); + std::fs::write(&path, serde_json::to_vec(&values).unwrap()).unwrap(); + let capabilities = Capabilities::available(); + let journey = load_journey(Source::Template(&path), &capabilities).unwrap(); + let resolution = journey.resolve(&capabilities).unwrap(); + assert!( + resolution + .question("/spec/sandboxes/coder/harness/kind") + .is_some() + ); + assert!( + resolution + .question("/spec/sandboxes/assistant/harness/kind") + .is_none() + ); + } + #[test] fn unknown_adapter_template_keeps_authored_settings_and_reports_unverified_schema() { let directory = tempfile::tempdir().unwrap(); @@ -187,7 +230,7 @@ mod tests { let mut values: serde_json::Value = serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) .unwrap(); - values["spec"]["sandboxes"][0]["harness"] = serde_json::json!({ + values["spec"]["sandboxes"]["assistant"]["harness"] = serde_json::json!({ "kind": "fixture-reopen-adapter", "settings": {"custom_option": "retained"} }); @@ -197,7 +240,7 @@ mod tests { assert_eq!( journey .values() - .pointer("/spec/sandboxes/0/harness/settings/custom_option"), + .pointer("/spec/sandboxes/assistant/harness/settings/custom_option"), Some(&serde_json::json!("retained")) ); let resolution = journey.resolve(&capabilities).unwrap(); @@ -232,7 +275,7 @@ mod tests { assert_eq!( state .values() - .pointer("/spec/sandboxes/0/agent/inference/routes/0/overrides/model"), + .pointer("/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model"), Some(&serde_json::json!("nvidia/nemotron-3-super-120b-a12b")) ); } diff --git a/crates/nemoclaw-onboarding/src/tui/app.rs b/crates/nemoclaw-onboarding/src/tui/app.rs index a532efd88dd..29ab4b15ddd 100644 --- a/crates/nemoclaw-onboarding/src/tui/app.rs +++ b/crates/nemoclaw-onboarding/src/tui/app.rs @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use super::labels::display_value; +use super::labels::{display_value, pointer_text}; use nemoclaw_authoring::{ Capabilities, Diagnostics, JourneyQuestion, JourneyResolution, JourneyState, }; @@ -290,7 +290,7 @@ impl JourneyWizard { .assessment() .issues() .iter() - .map(|issue| format!("{}: {}", issue.path(), issue.rule())) + .map(|issue| format!("{}: {}", pointer_text(issue.path()), issue.rule())) .collect::>(); self.error = Some(format!( "Cannot save yet: {} {} {}", diff --git a/crates/nemoclaw-onboarding/src/tui/labels.rs b/crates/nemoclaw-onboarding/src/tui/labels.rs index e5360358100..92d3a385617 100644 --- a/crates/nemoclaw-onboarding/src/tui/labels.rs +++ b/crates/nemoclaw-onboarding/src/tui/labels.rs @@ -1,7 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use nemoclaw_authoring::{JourneyQuestion, JourneyQuestionKind, ProviderPreset}; +use nemoclaw_authoring::{ + JourneyQuestion, JourneyQuestionKind, ProviderPreset, replace_entry_keys, +}; +use nemoclaw_sdk::config::valid_name; use serde::Deserialize; use serde_json::Value; use std::{collections::BTreeMap, sync::OnceLock}; @@ -21,8 +24,8 @@ struct QuestionText { } /// Friendly text for questions and choices from `text.json`, keyed by -/// question ID with `*` standing for array indices, service names, gateway -/// target keys, and adapter IDs. Entries +/// question ID with `*` standing for array indices, sandbox, provider, and +/// service names, gateway target keys, and adapter IDs. Entries /// override the titles and descriptions advertised by the SDK and Fabric /// schemas. Describe Fabric adapter and model settings in the Fabric adapter /// descriptors instead, so every client receives the same text. @@ -34,20 +37,18 @@ fn text() -> &'static Text { } /// Map keys for a question ID, most specific first: the ID itself, then with -/// array indices, service names, and gateway target keys replaced by `*`, then -/// also the adapter ID. +/// array indices, the names of sandboxes, providers, services, and other named +/// definitions, and the gateway target key replaced by `*`, then also the +/// adapter ID. A key is a name only by its position in the ID. fn keys(id: &str) -> [String; 3] { - let parts = id.split('/').collect::>(); + let named = replace_entry_keys(id, |_| "*".into()); + let parts = named.split('/').collect::>(); let indices = parts .iter() .enumerate() .map(|(index, part)| { - let service = index > 0 && parts[index - 1] == "services"; - let target = index > 1 && parts[index - 2..index] == ["gateway", "target"]; - if service - || target - || (!part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit())) - { + let target = index == 4 && parts[1..4] == ["spec", "gateway", "target"]; + if target || (!part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit())) { "*" } else { part @@ -142,14 +143,26 @@ pub(super) fn label(question: &JourneyQuestion) -> String { readable(id) } +/// A question ID or document pointer for display: a sandbox, provider, +/// service, or other definition key that is not a valid name reads as +/// `[entry]`, as in SDK diagnostics, so rejected input is never shown. +pub(super) fn pointer_text(pointer: &str) -> String { + replace_entry_keys(pointer, |key| { + if valid_name(key) { key } else { "[entry]" }.to_owned() + }) +} + /// `adapter:x:/interfaces/dashboard/port` reads as "Dashboard: port". fn readable(id: &str) -> String { - let pointer = id.rsplit_once(':').map_or(id, |(_, pointer)| pointer); + let id = pointer_text(id); + let pointer = id + .rsplit_once(':') + .map_or(id.as_str(), |(_, pointer)| pointer); let mut parts = pointer .split('/') .filter(|part| !part.is_empty() && !part.bytes().all(|byte| byte.is_ascii_digit())) .map(words); - let last = parts.next_back().unwrap_or_else(|| words(id)); + let last = parts.next_back().unwrap_or_else(|| words(&id)); match parts.next_back() { Some(parent) if !matches!(parent.as_str(), "Spec" | "Settings") => { acronyms(&format!("{parent}: {}", last.to_lowercase())) @@ -213,11 +226,12 @@ fn words(part: &str) -> String { /// The managed service a question belongs to, shown under its title. pub(super) fn service(question: &JourneyQuestion) -> Option<&str> { - question + let name = question .id() .strip_prefix("/spec/services/")? .split('/') - .next() + .next()?; + Some(if valid_name(name) { name } else { "[entry]" }) } // External labels stay unchanged in authored values; escape them only for the terminal. @@ -241,11 +255,23 @@ mod tests { use super::{keys, readable}; #[test] - fn map_keys_generalize_indices_service_names_and_adapters() { + fn map_keys_generalize_indices_collection_keys_and_adapters() { assert_eq!( - keys("/spec/sandboxes/0/agent/inference/routes/1/name")[1], + keys("/spec/sandboxes/assistant/agent/inference/routes/1/name")[1], "/spec/sandboxes/*/agent/inference/routes/*/name" ); + assert_eq!( + keys("form:/spec/sandboxes/assistant/agent")[1], + "form:/spec/sandboxes/*/agent" + ); + assert_eq!( + keys("/spec/inferenceProviders/nvidia-prod/api")[1], + "/spec/inferenceProviders/*/api" + ); + assert_eq!( + keys("/spec/sandboxes/assistant/inferenceProviders/own/endpoint")[1], + "/spec/sandboxes/*/inferenceProviders/*/endpoint" + ); assert_eq!( keys("/spec/services/qwen/serving/port")[1], "/spec/services/*/serving/port" @@ -256,6 +282,23 @@ mod tests { ); // The target key question itself names no key. assert_eq!(keys("/spec/gateway/target")[1], "/spec/gateway/target"); + // Only a key's position makes it a name; a name can equal a field. + assert_eq!( + keys("/spec/sandboxes/services/image/ref")[1], + "/spec/sandboxes/*/image/ref" + ); + assert_eq!( + keys("/spec/sandboxes/target/inferenceProviders/sandboxes/endpoint")[1], + "/spec/sandboxes/*/inferenceProviders/*/endpoint" + ); + assert_eq!( + keys("adapter:x:/services/port")[1], + "adapter:x:/services/port" + ); + assert_eq!( + keys("/spec/gateway/kubernetes/target/endpoint")[1], + "/spec/gateway/kubernetes/target/endpoint" + ); assert_eq!( keys("adapter:nvidia.fabric.openclaw:/native_config/cron")[2], "adapter:*:/native_config/cron" @@ -275,5 +318,9 @@ mod tests { readable("/spec/gateway/target/docker/networkCidr"), "Docker: network CIDR" ); + assert_eq!( + readable("/spec/inferenceProviders/PRIVATE INVALID NAME/endpoint"), + "[entry]: endpoint" + ); } } diff --git a/crates/nemoclaw-onboarding/src/tui/tests.rs b/crates/nemoclaw-onboarding/src/tui/tests.rs index 38a209332f5..ae425211d0b 100644 --- a/crates/nemoclaw-onboarding/src/tui/tests.rs +++ b/crates/nemoclaw-onboarding/src/tui/tests.rs @@ -122,8 +122,9 @@ fn root_adapter_alternatives_accept_json_object_input() { "../../../../examples/onboarding/openclaw.yaml" )) .unwrap(); - values["spec"]["sandboxes"][0]["harness"]["kind"] = serde_json::json!("fixture-root-agent"); - values["spec"]["sandboxes"][0]["harness"] + values["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = + serde_json::json!("fixture-root-agent"); + values["spec"]["sandboxes"]["assistant"]["harness"] .as_object_mut() .unwrap() .remove("settings"); @@ -160,7 +161,8 @@ fn resolver_failure_is_not_reported_as_a_finished_questionnaire() { "../../../../examples/onboarding/openclaw.yaml" )) .unwrap(); - values["spec"]["sandboxes"][0]["harness"]["kind"] = serde_json::json!("fixture-schema-agent"); + values["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = + serde_json::json!("fixture-schema-agent"); let base = PartialDocument::from_yaml(values.to_string().as_bytes()).unwrap(); let state = JourneyDefinition::new("conflicting-descriptors", base) .start(&capabilities) @@ -188,6 +190,42 @@ fn resolver_failure_is_not_reported_as_a_finished_questionnaire() { ); } +#[test] +fn output_shows_a_collection_key_that_is_not_a_name_as_an_entry() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("template.yaml"); + let mut values: Value = serde_saphyr::from_slice(include_bytes!( + "../../../../examples/onboarding/openclaw.yaml" + )) + .unwrap(); + values["spec"]["inferenceProviders"]["PRIVATE INVALID NAME"] = + serde_json::json!({"provider": "openai", "endpoint": 7}); + std::fs::write(&path, serde_json::to_vec(&values).unwrap()).unwrap(); + let capabilities = Capabilities::available(); + let state = load_journey(Source::Template(&path), &capabilities).unwrap(); + let mut wizard = JourneyWizard::new(capabilities, state); + let mut terminal = Terminal::new(TestBackend::new(200, 60)).unwrap(); + let mut output = String::new(); + for _ in 0..100 { + terminal.draw(|frame| wizard.render(frame)).unwrap(); + output.push_str(&terminal.backend().to_string()); + wizard.advance(); + if let Some(error) = &wizard.error { + output.push_str(error); + } + if wizard.accepted || wizard.error.is_some() { + break; + } + } + terminal.draw(|frame| wizard.render(frame)).unwrap(); + output.push_str(&terminal.backend().to_string()); + assert!( + output.contains("/spec/inferenceProviders/[entry]/endpoint"), + "{output}" + ); + assert!(!output.contains("PRIVATE"), "{output}"); +} + #[test] fn configured_target_prerequisite_blocks_save_until_observed() { let capabilities = Capabilities::available(); @@ -227,7 +265,7 @@ fn wizard_uses_the_shared_resolver_for_an_sdk_form_choice() { "../../../../examples/onboarding/openclaw.yaml" )) .unwrap(); - values["spec"]["sandboxes"][0]["agent"] + values["spec"]["sandboxes"]["assistant"]["agent"] .as_object_mut() .unwrap() .remove("inference"); @@ -237,14 +275,14 @@ fn wizard_uses_the_shared_resolver_for_an_sdk_form_choice() { .unwrap(); let mut wizard = JourneyWizard::new(capabilities, state); let question = wizard.question().unwrap().unwrap(); - assert_eq!(question.id(), "form:/spec/sandboxes/0/agent"); + assert_eq!(question.id(), "form:/spec/sandboxes/assistant/agent"); assert_eq!(label(&question), "Choose agent form"); wizard .submit(Some(serde_json::json!("inferenceRef"))) .unwrap(); assert_eq!( wizard.question().unwrap().unwrap().id(), - "/spec/sandboxes/0/agent/inferenceRef" + "/spec/sandboxes/assistant/agent/inferenceRef" ); } @@ -257,14 +295,14 @@ fn enter_uses_the_supplied_choice_suggestion() { wizard.advance(); assert_eq!( wizard.question().unwrap().unwrap().id(), - "/spec/sandboxes/0/harness/kind" + "/spec/sandboxes/assistant/harness/kind" ); wizard.advance(); assert_eq!( wizard .state() .values() - .pointer("/spec/sandboxes/0/harness/kind"), + .pointer("/spec/sandboxes/assistant/harness/kind"), Some(&serde_json::json!("nvidia.fabric.openclaw")) ); } @@ -280,7 +318,7 @@ fn back_restores_the_previous_answer_without_rewriting_the_template() { .unwrap(); assert_eq!( wizard.question().unwrap().unwrap().id(), - "/spec/sandboxes/0/harness/kind" + "/spec/sandboxes/assistant/harness/kind" ); wizard.back(); assert_eq!(wizard.question().unwrap().unwrap().id(), "/metadata/name"); @@ -382,7 +420,7 @@ fn mixed_local_and_hosted_template_reaches_review_without_losing_routes() { ); let document = wizard.document().unwrap(); assert_eq!( - document.spec.sandboxes[0] + document.spec.sandboxes["assistant"] .agent .inference .as_ref() @@ -868,13 +906,13 @@ fn missing_catalog_key_does_not_occupy_the_error_slot_or_hide_engine_failures() )) .unwrap(); let mut state = JourneyDefinition::new("catalog-note", base) - .ask(["/spec/sandboxes/0/harness/kind", "/metadata/name"]) + .ask(["/spec/sandboxes/assistant/harness/kind", "/metadata/name"]) .start(&capabilities) .unwrap(); state .answer( &capabilities, - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", Some(serde_json::json!("nvidia.fabric.openclaw")), ) .unwrap(); @@ -937,7 +975,7 @@ fn missing_catalog_key_does_not_occupy_the_error_slot_or_hide_engine_failures() image: ImageMetadata { architecture: Some("arm64".into()), operating_system: Some("linux".into()), - repo_digests: vec![document.spec.sandboxes[0].image.ref_.clone()], + repo_digests: vec![document.spec.sandboxes["assistant"].image.ref_.clone()], ..Default::default() }, compatibility: Some(CompatibilityReport { diff --git a/crates/nemoclaw-onboarding/src/tui/text.json b/crates/nemoclaw-onboarding/src/tui/text.json index fe6db00b224..a289e068c1e 100644 --- a/crates/nemoclaw-onboarding/src/tui/text.json +++ b/crates/nemoclaw-onboarding/src/tui/text.json @@ -56,9 +56,6 @@ "/spec/sandboxes/*/image/ref": { "title": "Sandbox image" }, - "/spec/sandboxes/*/name": { - "title": "Name this sandbox" - }, "/spec/sandboxes/*/network/policy": { "title": "Network policy" }, diff --git a/crates/nemoclaw-onboarding/src/tui/view.rs b/crates/nemoclaw-onboarding/src/tui/view.rs index dfd0115b3f7..b2577dab761 100644 --- a/crates/nemoclaw-onboarding/src/tui/view.rs +++ b/crates/nemoclaw-onboarding/src/tui/view.rs @@ -158,7 +158,7 @@ impl JourneyWizard { } else { "Optional" }, - terminal_text(question.id()) + terminal_text(&labels::pointer_text(question.id())) ), Style::new().fg(DIM), ))); @@ -244,7 +244,11 @@ impl JourneyWizard { .take(5) .map(|issue| { Line::from(Span::styled( - terminal_text(&format!("{}: {}", issue.path(), issue.rule())), + terminal_text(&format!( + "{}: {}", + labels::pointer_text(issue.path()), + issue.rule() + )), Style::new().fg(WARNING), )) }), diff --git a/crates/nemoclaw-provider/tests/contract/discovery.rs b/crates/nemoclaw-provider/tests/contract/discovery.rs index a008654d521..686000d40bb 100644 --- a/crates/nemoclaw-provider/tests/contract/discovery.rs +++ b/crates/nemoclaw-provider/tests/contract/discovery.rs @@ -185,7 +185,7 @@ async fn compiled_discovery_requires_runtime_metadata_but_allows_unknown_capabil let document = Document::parse(include_bytes!("../../../../examples/onboarding/openclaw.yaml").as_slice()) .unwrap(); - let image = document.spec.sandboxes[0].image.ref_.clone(); + let image = document.spec.sandboxes["assistant"].image.ref_.clone(); let mode = Arc::new(AtomicUsize::new(0)); let current = mode.clone(); let requests = Arc::new(AtomicUsize::new(0)); diff --git a/crates/nemoclaw-runtime/src/schema.rs b/crates/nemoclaw-runtime/src/schema.rs index 7b902feafd8..ec07c37abbc 100644 --- a/crates/nemoclaw-runtime/src/schema.rs +++ b/crates/nemoclaw-runtime/src/schema.rs @@ -34,10 +34,13 @@ pub fn forbid(names: &[&str]) -> Value { } // Required ancestors make a condition false when a field is omitted. // Consequences constrain only fields that are present, allowing SDK defaults. +// A `[]` segment reaches every array item and a `*` segment every map value. pub fn at(path: &str, rule: Value, required: bool) -> Value { path.split('/').rev().fold(rule, |child, segment| { if segment == "[]" { json!({"items": child}) + } else if segment == "*" { + json!({"additionalProperties": child}) } else if required { json!({"required": [segment], "properties": {segment: child}}) } else { @@ -248,6 +251,30 @@ mod tests { ] } + #[test] + fn a_path_reaches_array_items_and_every_map_value() { + let rule = json!({"required": ["ref"]}); + assert_eq!( + at("spec/sandboxes/*/image", rule.clone(), true), + json!({"required": ["spec"], "properties": {"spec": { + "required": ["sandboxes"], "properties": {"sandboxes": { + "additionalProperties": {"required": ["image"], "properties": {"image": rule}} + }} + }}}) + ); + assert_eq!( + at("routes/[]/provider", json!({}), false), + json!({"properties": {"routes": {"items": {"properties": {"provider": {}}}}}}) + ); + let schema = at("sandboxes/*/image", forbid(&["metadata"]), false); + let validator = jsonschema::validator_for(&schema).unwrap(); + assert!(validator.is_valid(&json!({"sandboxes": {"one": {"image": {}}}}))); + assert!(!validator.is_valid(&json!({"sandboxes": { + "one": {"image": {}}, + "two": {"image": {"metadata": {}}} + }}))); + } + #[test] fn a_kind_or_management_constant_selects_its_variant() { let variants = [ diff --git a/crates/nemoclaw-sdk/src/compile.rs b/crates/nemoclaw-sdk/src/compile.rs index 495f25a6ea2..b9357b4d125 100644 --- a/crates/nemoclaw-sdk/src/compile.rs +++ b/crates/nemoclaw-sdk/src/compile.rs @@ -93,15 +93,13 @@ fn targets_with_plans( generations, )?); } - let mut sandboxes: Vec<_> = document.spec.sandboxes.iter().collect(); - sandboxes.sort_by_key(|sandbox| &sandbox.name); - for sandbox in sandboxes { - let harness = document.sandbox_harness(sandbox)?; - let web_search = document.web_search(sandbox)?; - let image_scope = document.image_scope(sandbox)?; + for (name, sandbox) in &document.spec.sandboxes { + let harness = document.sandbox_harness(name)?; + let web_search = document.web_search(name)?; + let image_scope = document.image_scope(name)?; let agent_name = &sandbox.agent.name; let mut provider_names = document - .sandbox_inference_providers(sandbox)? + .sandbox_inference_providers(name)? .iter() .map(|provider| provider.key.clone()) .collect::>(); @@ -114,7 +112,7 @@ fn targets_with_plans( } let mut values: Row = [ - ("name".into(), sandbox.name.clone()), + ("name".into(), name.clone()), ("workspace".into(), workspace.clone()), ("owner".into(), document.metadata.uid.clone()), ( @@ -132,16 +130,16 @@ fn targets_with_plans( .into(); values.insert( "policy_json".into(), - serde_json::to_string(&crate::image_runtime::policy_input(document, sandbox)?) + serde_json::to_string(&crate::image_runtime::policy_input(document, name)?) .expect("policy input"), ); { result.push(Target { kind: "agent_configuration".into(), - address: format!("fabric_agent_configuration.{}", sandbox.name), + address: format!("fabric_agent_configuration.{name}"), values: [ ("workspace".into(), workspace.clone()), - ("name".into(), sandbox.name.clone()), + ("name".into(), name.clone()), ("owner".into(), document.metadata.uid.clone()), ( "generation".into(), @@ -149,11 +147,11 @@ fn targets_with_plans( ), ( "sandbox_id".into(), - format!("${{openshell_sandbox.{}.id}}", sandbox.name), + format!("${{openshell_sandbox.{name}.id}}"), ), ( "config_json".into(), - crate::fabric_config::for_sandbox(document, sandbox)?.to_string(), + crate::fabric_config::for_sandbox(document, name)?.to_string(), ), ] .into(), @@ -161,7 +159,7 @@ fn targets_with_plans( } result.push(Target { kind: "sandbox".into(), - address: format!("openshell_sandbox.{}", sandbox.name), + address: format!("openshell_sandbox.{name}"), values, }); if let Some(search) = web_search { @@ -405,11 +403,10 @@ fn compile_with_plans( .collect(); let mut runtime_sources = BTreeMap::new(); let mut profile_sources = BTreeMap::new(); - let mut ordered: Vec<_> = document.spec.sandboxes.iter().collect(); - ordered.sort_by_key(|sandbox| &sandbox.name); - for (index, sandbox) in ordered.iter().enumerate() { + // Fabric reads are numbered in name order, as discovery issues them. + for (index, sandbox) in document.spec.sandboxes.keys().enumerate() { let source = format!("data.fabric_capabilities.sandbox_{index}"); - runtime_sources.insert(sandbox.name.clone(), source.clone()); + runtime_sources.insert(sandbox.clone(), source.clone()); for provider in document.sandbox_inference_providers(sandbox)? { profile_sources .entry(format!("nemoclaw-inference-{}", provider.key)) @@ -467,7 +464,7 @@ fn compile_with_plans( "${{{}.runtime_json}}", runtime_sources[&target.values["name"]] )); - let sandbox = document.sandbox(&target.values["name"])?; + let sandbox = target.values["name"].as_str(); let mut dependencies: Vec<_> = document .sandbox_inference_providers(sandbox)? .into_iter() @@ -561,7 +558,7 @@ fn compile_with_plans( let sandbox_readiness: BTreeMap<_, _> = document .spec .sandboxes - .iter() + .keys() .map(|sandbox| { // Readiness names the sandbox and configuration attributes it reads. let mut readiness: serde_json::Map = [ @@ -578,15 +575,14 @@ fn compile_with_plans( .map(|name| { ( name.to_owned(), - json!(format!("${{openshell_sandbox.{}.{name}}}", sandbox.name)), + json!(format!("${{openshell_sandbox.{sandbox}.{name}}}")), ) }) .collect(); readiness.insert( "config_json".into(), json!(format!( - "${{fabric_agent_configuration.{}.config_json}}", - sandbox.name + "${{fabric_agent_configuration.{sandbox}.config_json}}" )), ); // uuid() is unknown in a saved plan and records a unique observation @@ -599,7 +595,7 @@ fn compile_with_plans( "error_message":"${self.error_message != null ? self.error_message : \"Fabric readiness could not be established; resources retained\"}" }]}), ); - (sandbox.name.clone(), Value::Object(readiness)) + (sandbox.clone(), Value::Object(readiness)) }) .collect(); graph["resource"] = resources; diff --git a/crates/nemoclaw-sdk/src/config/inference.rs b/crates/nemoclaw-sdk/src/config/inference.rs index 462fa2cff98..a5a0d2cbddf 100644 --- a/crates/nemoclaw-sdk/src/config/inference.rs +++ b/crates/nemoclaw-sdk/src/config/inference.rs @@ -22,7 +22,7 @@ impl Document { /// cannot be resolved. This operation does not contact external services. pub fn inference_connection(&self) -> Result { self.validate()?; - self.provider_connection(self.inference_provider()?) + self.provider_connection(self.inference_provider()?.definition) } /// Resolve one selected provider using the same publication rules as deployment. diff --git a/crates/nemoclaw-sdk/src/config/integrations.rs b/crates/nemoclaw-sdk/src/config/integrations.rs index fbf5d009530..29d0e8b92ab 100644 --- a/crates/nemoclaw-sdk/src/config/integrations.rs +++ b/crates/nemoclaw-sdk/src/config/integrations.rs @@ -34,8 +34,10 @@ pub struct IntegrationBinding<'a> { impl Sandbox { /// Resolve deployment and sandbox definitions without implicitly granting access. + /// `name` is this sandbox's key, which diagnostics use to identify it. pub fn integration_bindings<'a>( &'a self, + name: &str, shared: &'a BTreeMap, ) -> Result>, ConfigError> { validate_definitions(shared)?; @@ -66,26 +68,26 @@ impl Sandbox { .integration_refs .iter() .enumerate() - .map(|(index, name)| { + .map(|(index, reference)| { let definition = self .integrations - .get(name) - .or_else(|| shared.get(name)) + .get(reference) + .or_else(|| shared.get(reference)) .ok_or_else(|| { super::references::missing_reference( &format!( - "spec.sandboxes[{}].agent.integrationRefs[{index}]", - super::references::diagnostic_name(&self.name) + "{}.agent.integrationRefs[{index}]", + super::references::sandbox_path(name) ), "integration", - name, + reference, shared .keys() .chain(self.integrations.keys()) .map(String::as_str), ) })?; - Ok((None, name.as_str(), definition)) + Ok((None, reference.as_str(), definition)) }); let inline = agent .integrations @@ -115,12 +117,14 @@ impl Sandbox { } impl Document { + /// The web search attached to the named sandbox, if any. pub(crate) fn web_search( &self, - sandbox: &super::Sandbox, + sandbox: &str, ) -> Result, ConfigError> { + let (name, sandbox) = self.named_sandbox(sandbox)?; let mut selected = None; - for binding in sandbox.integration_bindings(&self.spec.integrations)? { + for binding in sandbox.integration_bindings(name, &self.spec.integrations)? { match binding.definition { Integration::WebSearch(search) => { if selected.is_some() { diff --git a/crates/nemoclaw-sdk/src/config/mod.rs b/crates/nemoclaw-sdk/src/config/mod.rs index 34b03368ef0..97a06a999dd 100644 --- a/crates/nemoclaw-sdk/src/config/mod.rs +++ b/crates/nemoclaw-sdk/src/config/mod.rs @@ -14,6 +14,7 @@ pub use integrations::*; pub use nemoclaw_openshell::search::search_policy; mod inference; mod providers; +pub use providers::NamedProvider; pub(crate) mod references; mod source; mod yaml_source; @@ -83,8 +84,14 @@ fn read_yaml(input: impl Read) -> Result<(String, serde_json::Value), ConfigErro impl Document { /// Read, default, and validate a configuration document. /// + /// The input is read as YAML, which also accepts JSON, and a duplicate key + /// is an error, so two sandboxes or providers in one collection cannot share + /// a name. Deserializing a `Document` directly, for example with + /// `serde_json`, keeps the last duplicate instead. + /// /// # Errors - /// Returns an error for unreadable, oversized, malformed, or invalid input. + /// Returns an error for unreadable, oversized, malformed, or invalid input, + /// including duplicate keys. pub fn parse(input: impl Read) -> Result { let (text, tree) = read_yaml(input)?; schema::validate_input(&tree, Some(&text))?; @@ -105,20 +112,14 @@ impl Document { .map_err(|_| ConfigError::new("cannot serialize configuration")) } pub fn digest(&self) -> String { - // Named declaration order is not deployment intent; retain authored order on export. + // Route order is not deployment intent; retain authored order on export. + // Sandboxes and providers are maps ordered by name, so their authored + // order is not intent and export emits name order. let mut canonical = self.clone(); - canonical.spec.sandboxes.sort_by(|a, b| a.name.cmp(&b.name)); - canonical - .spec - .inference_providers - .sort_by(|a, b| a.name.cmp(&b.name)); for inference in canonical.spec.inferences.values_mut() { inference.routes.sort_by(|a, b| a.name.cmp(&b.name)); } - for sandbox in &mut canonical.spec.sandboxes { - sandbox - .inference_providers - .sort_by(|a, b| a.name.cmp(&b.name)); + for sandbox in canonical.spec.sandboxes.values_mut() { for inference in sandbox .inferences .values_mut() @@ -168,17 +169,17 @@ impl Document { } if let Ok(providers) = self.selected_inference_providers() { for provider in providers { - if let Some(credential) = &provider.credential { + if let Some(credential) = &provider.definition.credential { names.push(credential.env.as_str()); } } } - for sandbox in &self.spec.sandboxes { + for (name, sandbox) in &self.spec.sandboxes { if let Some(metadata) = &sandbox.image.metadata { names.push(metadata.env.as_str()); } for binding in sandbox - .integration_bindings(&self.spec.integrations) + .integration_bindings(name, &self.spec.integrations) .expect("validated integration references") { match binding.definition { @@ -218,7 +219,7 @@ impl Document { } // Cluster sandboxes have no engine-supplied default image. if !self.spec.gateway.compute_driver().is_kubernetes() { - for sandbox in &mut self.spec.sandboxes { + for sandbox in self.spec.sandboxes.values_mut() { default_string(&mut sandbox.image.ref_, DEFAULT_AGENT_IMAGE); } } diff --git a/crates/nemoclaw-sdk/src/config/providers.rs b/crates/nemoclaw-sdk/src/config/providers.rs index 3ed12ed8e59..e0fca8a8d06 100644 --- a/crates/nemoclaw-sdk/src/config/providers.rs +++ b/crates/nemoclaw-sdk/src/config/providers.rs @@ -1,28 +1,37 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use super::references::{ScopedInference, diagnostic_name, missing_reference}; +use super::references::{ScopedInference, diagnostic_name, missing_reference, sandbox_path}; use super::source::DefinitionSource; -use super::{ConfigError, Document, Inference, InferenceProvider, Route, Sandbox}; +use super::{ConfigError, Document, Inference, InferenceProvider, Route}; use std::collections::{BTreeMap, BTreeSet}; // The resource key identifies the registration; the authored path distinguishes // separate definitions with identical values and lets export edit the right one. pub(crate) struct SelectedProvider<'a> { + /// The definition's map key, or an inline definition's own name. + pub name: &'a str, pub definition: &'a InferenceProvider, pub key: String, pub(crate) path: String, } impl<'a> SelectedProvider<'a> { - fn new(definition: &'a InferenceProvider, sandbox: Option<&Sandbox>, path: String) -> Self { + /// `sandbox` names the sandbox that declares the definition, if any. + fn new( + name: &'a str, + definition: &'a InferenceProvider, + sandbox: Option<&str>, + path: String, + ) -> Self { use sha2::{Digest, Sha256}; let key = sandbox.map_or_else( - || definition.name.clone(), + || name.to_owned(), |sandbox| { - let digest = Sha256::digest(format!("{}/{}", sandbox.name, definition.name)); + let digest = Sha256::digest(format!("{sandbox}/{name}")); format!("local-{}", &super::hex(&digest)[..24]) }, ); Self { + name, definition, key, path, @@ -32,33 +41,46 @@ impl<'a> SelectedProvider<'a> { use sha2::{Digest, Sha256}; self.key = format!( "{}-{}", - &self.definition.name[..self.definition.name.len().min(12)], + &self.name[..self.name.len().min(12)], &super::hex(&Sha256::digest(format!("{}\0{scope}", self.key)))[..24] ); self } } +/// A selected inference definition with the name that identifies it: its map +/// key, or an inline definition's own name. Its fields read through to the +/// definition. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct NamedProvider<'a> { + pub name: &'a str, + pub definition: &'a InferenceProvider, +} +impl std::ops::Deref for NamedProvider<'_> { + type Target = InferenceProvider; + fn deref(&self) -> &InferenceProvider { + self.definition + } +} + fn provider_path(base: &str, name: &str) -> String { format!("{base}.inferenceProviders[{}]", diagnostic_name(name)) } -fn sandbox_path(sandbox: &Sandbox) -> String { - format!("spec.sandboxes[{}]", diagnostic_name(&sandbox.name)) -} impl Document { - pub(crate) fn image_scope(&self, sandbox: &Sandbox) -> Result { + /// The image identity of the named sandbox, which scopes its registrations. + pub(crate) fn image_scope(&self, sandbox: &str) -> Result { use sha2::{Digest, Sha256}; Ok(super::hex(&Sha256::digest(format!( "{}\0{}", - sandbox.image.ref_, + self.sandbox(sandbox)?.image.ref_, self.sandbox_harness(sandbox)?.kind.as_str() )))[..24] .into()) } pub(crate) fn sandbox_route_registration<'a>( &'a self, - sandbox: &'a Sandbox, + sandbox: &str, route: &'a Route, ) -> Result, ConfigError> { let inference = self.scoped_inference(sandbox)?; @@ -72,11 +94,11 @@ impl Document { inference: &ScopedInference<'a>, ) -> Result, ConfigError> { let enclosing = || { - self.spec.inference_providers.iter().chain( + self.spec.inference_providers.keys().chain( inference .sandbox .into_iter() - .flat_map(|s| &s.inference_providers), + .flat_map(|(_, sandbox)| sandbox.inference_providers.keys()), ) }; match DefinitionSource::from_parts( @@ -85,35 +107,33 @@ impl Document { "route requires exactly one of provider or providerRef", )? { DefinitionSource::Inline(provider) => { - if enclosing().any(|definition| definition.name == provider.name) { + if enclosing().any(|name| *name == provider.name) { return Err(ConfigError::new( "inline provider names must not shadow enclosing definitions", )); } Ok(SelectedProvider::new( - provider, - inference.sandbox, + &provider.name, + &provider.definition, + inference.sandbox.map(|(sandbox, _)| sandbox), format!("{}.provider", inference.route_path(route)), )) } DefinitionSource::Reference(name) => { - if let Some(provider) = self - .spec - .inference_providers - .iter() - .find(|p| p.name == name) - { + if let Some((name, provider)) = self.spec.inference_providers.get_key_value(name) { return Ok(SelectedProvider::new( + name, provider, None, provider_path("spec", name), )); } - if let Some(sandbox) = inference.sandbox - && let Some(provider) = - sandbox.inference_providers.iter().find(|p| p.name == name) + if let Some((sandbox, definition)) = inference.sandbox + && let Some((name, provider)) = + definition.inference_providers.get_key_value(name) { return Ok(SelectedProvider::new( + name, provider, Some(sandbox), provider_path(&sandbox_path(sandbox), name), @@ -123,18 +143,18 @@ impl Document { &format!("{}.providerRef", inference.route_path(route)), "provider", name, - enclosing().map(|p| p.name.as_str()), + enclosing().map(String::as_str), )) } } } - /// Resolve a route using the declaration scope of the sandbox's selected inference. + /// Resolve a route using the declaration scope of the named sandbox's selected inference. pub fn sandbox_route_provider<'a>( &'a self, - sandbox: &'a Sandbox, - route: &'a Route, - ) -> Result<&'a InferenceProvider, ConfigError> { + sandbox: &str, + route: &Route, + ) -> Result, ConfigError> { let inference = self.scoped_inference(sandbox)?; let selected = inference .inference @@ -142,7 +162,11 @@ impl Document { .iter() .find(|candidate| candidate.name == route.name) .ok_or(ConfigError::new("route is not selected by this sandbox"))?; - Ok(self.route_provider(selected, &inference)?.definition) + let provider = self.route_provider(selected, &inference)?; + Ok(NamedProvider { + name: provider.name, + definition: provider.definition, + }) } /// Mutate the authored provider definition selected by a sandbox route. @@ -151,8 +175,7 @@ impl Document { sandbox_name: &str, route_name: &str, ) -> Result<&mut InferenceProvider, ConfigError> { - let sandbox = self.sandbox(sandbox_name)?; - let inference = self.scoped_inference(sandbox)?; + let inference = self.scoped_inference(sandbox_name)?; let route = inference .inference .routes @@ -164,10 +187,10 @@ impl Document { } /// Resolve an unambiguous deployment provider. Multi-provider callers must select by identity. - pub fn inference_provider(&self) -> Result<&InferenceProvider, ConfigError> { + pub fn inference_provider(&self) -> Result, ConfigError> { let providers = self.selected_inference_providers()?; match providers.as_slice() { - [provider] => Ok(provider), + [provider] => Ok(*provider), _ => Err(ConfigError::new( "select an explicit provider in a multi-provider deployment", )), @@ -175,11 +198,17 @@ impl Document { } /// Providers selected across all sandboxes, deduplicated by scoped definition identity. - pub fn selected_inference_providers(&self) -> Result, ConfigError> { + pub fn selected_inference_providers(&self) -> Result>, ConfigError> { Ok(self .selected_providers()? .into_iter() - .map(|p| (p.path, p.definition)) + .map(|p| { + let provider = NamedProvider { + name: p.name, + definition: p.definition, + }; + (p.path, provider) + }) .collect::>() .into_values() .collect()) @@ -187,25 +216,19 @@ impl Document { pub(crate) fn selected_providers(&self) -> Result>, ConfigError> { let mut selected = BTreeMap::new(); - for sandbox in &self.spec.sandboxes { - let mut names = BTreeSet::new(); - for definition in self - .spec + for (name, sandbox) in &self.spec.sandboxes { + if sandbox .inference_providers - .iter() - .chain(&sandbox.inference_providers) + .keys() + .any(|name| self.spec.inference_providers.contains_key(name)) { - if !super::validation::valid_name(&definition.name) - || !names.insert(&definition.name) - { - return Err(ConfigError::new( - "provider names must be unique lowercase names without shadowing", - )); - } + return Err(ConfigError::new( + "sandbox provider names must not shadow deployment definitions", + )); } - let inference = self.scoped_inference(sandbox)?; + let inference = self.scoped_inference(name)?; for route in &inference.inference.routes { - let provider = self.sandbox_route_registration(sandbox, route)?; + let provider = self.sandbox_route_registration(name, route)?; let path = provider.path.clone(); if let Some(previous) = selected.insert(provider.key.clone(), provider) && previous.path != path @@ -231,10 +254,10 @@ impl Document { Ok(selected.into_values().collect()) } - pub(crate) fn sandbox_inference_providers<'a>( - &'a self, - sandbox: &'a Sandbox, - ) -> Result>, ConfigError> { + pub(crate) fn sandbox_inference_providers( + &self, + sandbox: &str, + ) -> Result>, ConfigError> { let mut selected = BTreeMap::new(); let inference = self.scoped_inference(sandbox)?; for route in &inference.inference.routes { @@ -295,7 +318,7 @@ impl Document { self.spec .inference_providers .iter_mut() - .map(|provider| (provider_path("spec", &provider.name), provider)) + .map(|(name, provider)| (provider_path("spec", name), provider)) .chain( self.spec .inferences @@ -307,14 +330,14 @@ impl Document { ) }), ) - .chain(self.spec.sandboxes.iter_mut().flat_map(|sandbox| { - let base = sandbox_path(sandbox); + .chain(self.spec.sandboxes.iter_mut().flat_map(|(name, sandbox)| { + let base = sandbox_path(name); let definitions = base.clone(); let inferences = base.clone(); sandbox .inference_providers .iter_mut() - .map(move |provider| (provider_path(&definitions, &provider.name), provider)) + .map(move |(name, provider)| (provider_path(&definitions, name), provider)) .chain( sandbox .inferences @@ -341,12 +364,12 @@ impl Document { pub(super) fn provider_definitions(&self) -> impl Iterator { self.spec .inference_providers - .iter() + .values() .chain( self.spec .sandboxes - .iter() - .flat_map(|sandbox| &sandbox.inference_providers), + .values() + .flat_map(|sandbox| sandbox.inference_providers.values()), ) .chain(self.inference_definitions().flat_map(|selection| { selection @@ -354,6 +377,7 @@ impl Document { .routes .iter() .filter_map(|route| route.provider.as_ref()) + .map(|provider| &provider.definition) })) } } @@ -364,6 +388,9 @@ fn inline_providers_mut( ) -> impl Iterator { inference.routes.iter_mut().filter_map(move |route| { let path = format!("{base}.routes[{}].provider", diagnostic_name(&route.name)); - route.provider.as_mut().map(|provider| (path, provider)) + route + .provider + .as_mut() + .map(|provider| (path, &mut provider.definition)) }) } diff --git a/crates/nemoclaw-sdk/src/config/references.rs b/crates/nemoclaw-sdk/src/config/references.rs index 8f1699bad0a..30c94d136cf 100644 --- a/crates/nemoclaw-sdk/src/config/references.rs +++ b/crates/nemoclaw-sdk/src/config/references.rs @@ -7,15 +7,17 @@ use super::{ConfigError, Document, Harness, Inference, Route, Sandbox}; // A shared deployment definition cannot see a consuming sandbox's local providers. pub(crate) struct ScopedInference<'a> { pub inference: &'a Inference, - pub sandbox: Option<&'a Sandbox>, + /// The declaring sandbox's name and definition; none for a deployment definition. + pub sandbox: Option<(&'a str, &'a Sandbox)>, pub path: String, } impl<'a> ScopedInference<'a> { - fn new(inference: &'a Inference, sandbox: Option<&'a Sandbox>, name: Option<&str>) -> Self { - let base = sandbox.map_or_else( - || "spec".into(), - |s| format!("spec.sandboxes[{}]", diagnostic_name(&s.name)), - ); + fn new( + inference: &'a Inference, + sandbox: Option<(&'a str, &'a Sandbox)>, + name: Option<&str>, + ) -> Self { + let base = sandbox.map_or_else(|| "spec".into(), |(sandbox, _)| sandbox_path(sandbox)); let path = name.map_or_else( || format!("{base}.agent.inference"), |name| format!("{base}.inferences[{}]", diagnostic_name(name)), @@ -31,28 +33,33 @@ impl<'a> ScopedInference<'a> { } } +/// The diagnostic path of a sandbox, which its name identifies. +pub(super) fn sandbox_path(name: &str) -> String { + format!("spec.sandboxes[{}]", diagnostic_name(name)) +} + impl Document { pub fn sandbox(&self, name: &str) -> Result<&Sandbox, ConfigError> { + Ok(self.named_sandbox(name)?.1) + } + + /// The sandbox declared under `name`, with the name borrowed from its key. + pub(crate) fn named_sandbox(&self, name: &str) -> Result<(&str, &Sandbox), ConfigError> { self.spec .sandboxes - .iter() - .find(|sandbox| sandbox.name == name) + .get_key_value(name) + .map(|(name, sandbox)| (name.as_str(), sandbox)) .ok_or(ConfigError::new("sandbox name has no definition")) } - /// Resolve inference using the supplied sandbox's definitions and this deployment's definitions. + /// Resolve inference using the named sandbox's definitions and this deployment's definitions. /// Authored references are preserved; resolution does not depend on object addresses. - pub fn sandbox_inference<'a>( - &'a self, - sandbox: &'a Sandbox, - ) -> Result<&'a Inference, ConfigError> { + pub fn sandbox_inference(&self, sandbox: &str) -> Result<&Inference, ConfigError> { Ok(self.scoped_inference(sandbox)?.inference) } - pub(crate) fn scoped_inference<'a>( - &'a self, - sandbox: &'a Sandbox, - ) -> Result, ConfigError> { + pub(crate) fn scoped_inference(&self, name: &str) -> Result, ConfigError> { + let (name, sandbox) = self.named_sandbox(name)?; let agent = &sandbox.agent; match DefinitionSource::from_parts( agent.inference.as_ref(), @@ -60,24 +67,23 @@ impl Document { "agent requires exactly one of inference or inferenceRef", )? { DefinitionSource::Inline(inference) => { - Ok(ScopedInference::new(inference, Some(sandbox), None)) + Ok(ScopedInference::new(inference, Some((name, sandbox)), None)) } - DefinitionSource::Reference(name) => { - if let Some(inference) = self.spec.inferences.get(name) { - return Ok(ScopedInference::new(inference, None, Some(name))); + DefinitionSource::Reference(reference) => { + if let Some(inference) = self.spec.inferences.get(reference) { + return Ok(ScopedInference::new(inference, None, Some(reference))); } sandbox .inferences - .get(name) - .map(|inference| ScopedInference::new(inference, Some(sandbox), Some(name))) + .get(reference) + .map(|inference| { + ScopedInference::new(inference, Some((name, sandbox)), Some(reference)) + }) .ok_or_else(|| { missing_reference( - &format!( - "spec.sandboxes[{}].agent.inferenceRef", - diagnostic_name(&sandbox.name) - ), + &format!("{}.agent.inferenceRef", sandbox_path(name)), "inference", - name, + reference, self.spec .inferences .keys() @@ -94,23 +100,29 @@ impl Document { .inferences .iter() .map(|(name, inference)| ScopedInference::new(inference, None, Some(name))) - .chain(self.spec.sandboxes.iter().flat_map(|sandbox| { - sandbox - .inferences + .chain( + self.spec + .sandboxes .iter() - .map(move |(name, inference)| { - ScopedInference::new(inference, Some(sandbox), Some(name)) - }) - .chain( - sandbox.agent.inference.iter().map(move |inference| { - ScopedInference::new(inference, Some(sandbox), None) - }), - ) - })) + .flat_map(|(sandbox, definition)| { + let scope = Some((sandbox.as_str(), definition)); + definition + .inferences + .iter() + .map(move |(name, inference)| { + ScopedInference::new(inference, scope, Some(name)) + }) + .chain( + definition.agent.inference.iter().map(move |inference| { + ScopedInference::new(inference, scope, None) + }), + ) + }), + ) } pub(super) fn validate_inference_references(&self) -> Result<(), ConfigError> { - for sandbox in &self.spec.sandboxes { + for (name, sandbox) in &self.spec.sandboxes { if sandbox .inferences .keys() @@ -120,7 +132,7 @@ impl Document { "inference names must not shadow enclosing definitions", )); } - self.sandbox_inference(sandbox)?; + self.sandbox_inference(name)?; } for selection in self.inference_definitions() { selection.inference.validate_choices()?; @@ -133,13 +145,14 @@ impl Document { } impl Document { - /// Resolve the sandbox's harness without replacing its authored selection. - pub fn sandbox_harness<'a>(&'a self, sandbox: &'a Sandbox) -> Result<&'a Harness, ConfigError> { - sandbox.resolve_harness(&self.spec.harnesses) + /// Resolve the named sandbox's harness without replacing its authored selection. + pub fn sandbox_harness(&self, sandbox: &str) -> Result<&Harness, ConfigError> { + let (name, sandbox) = self.named_sandbox(sandbox)?; + sandbox.resolve_harness(name, &self.spec.harnesses) } pub(super) fn validate_harness_references(&self) -> Result<(), ConfigError> { - for sandbox in &self.spec.sandboxes { + for (name, sandbox) in &self.spec.sandboxes { if sandbox .harnesses .keys() @@ -158,7 +171,7 @@ impl Document { { harness.validate()?; } - self.sandbox_harness(sandbox)?; + sandbox.resolve_harness(name, &self.spec.harnesses)?; } Ok(()) } @@ -233,8 +246,10 @@ pub(crate) fn missing_reference<'a>( } impl Sandbox { + /// `name` is this sandbox's key, which diagnostics use to identify it. pub(super) fn resolve_harness<'a>( &'a self, + name: &str, harnesses: &'a std::collections::BTreeMap, ) -> Result<&'a Harness, ConfigError> { match DefinitionSource::from_parts( @@ -243,14 +258,14 @@ impl Sandbox { "sandbox requires exactly one of harness or harnessRef", )? { DefinitionSource::Inline(harness) => Ok(harness), - DefinitionSource::Reference(name) => harnesses - .get(name) - .or_else(|| self.harnesses.get(name)) + DefinitionSource::Reference(reference) => harnesses + .get(reference) + .or_else(|| self.harnesses.get(reference)) .ok_or_else(|| { missing_reference( - &format!("spec.sandboxes[{}].harnessRef", diagnostic_name(&self.name)), + &format!("{}.harnessRef", sandbox_path(name)), "harness", - name, + reference, harnesses .keys() .chain(self.harnesses.keys()) diff --git a/crates/nemoclaw-sdk/src/config/schema/runtime.rs b/crates/nemoclaw-sdk/src/config/schema/runtime.rs index ff57e64f3c2..e891abd1d23 100644 --- a/crates/nemoclaw-sdk/src/config/schema/runtime.rs +++ b/crates/nemoclaw-sdk/src/config/schema/runtime.rs @@ -1,7 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 //! Offline validators compiled once from the SDK contract, never from a deployment file. -use crate::config::{ConfigError, Document, RouteTuning}; +use crate::config::{ + ConfigError, Document, RouteTuning, + yaml_source::{self, escape}, +}; use nemoclaw_runtime::schema::{select_variant, variant_keys}; use serde::Serialize; use serde_json::{Value, json}; @@ -111,8 +114,25 @@ fn diagnostic( Kind::Constant { expected_value } => format!("must be {expected_value}"), Kind::Minimum { limit } => format!("must be at least {limit}"), Kind::Maximum { limit } => format!("must be at most {limit}"), + Kind::MinItems { limit } => { + format!("must have at least {}", count(*limit, "item", "items")) + } + Kind::MaxItems { limit } => { + format!("must have at most {}", count(*limit, "item", "items")) + } + Kind::MinProperties { limit } => { + format!("must have at least {}", count(*limit, "entry", "entries")) + } + Kind::MaxProperties { limit } => { + format!("must have at most {}", count(*limit, "entry", "entries")) + } Kind::Required { property } => format!("required field: {property}"), Kind::Pattern { pattern } => format!("required pattern: {pattern}"), + // The rejected key is input, so only the rule it broke is shown. + Kind::PropertyNames { error } => match error.kind() { + Kind::Pattern { pattern } => format!("each name requires pattern: {pattern}"), + _ => "names must be valid".into(), + }, Kind::Type { kind: TypeKind::Single(kind), } => format!("must be {kind}"), @@ -141,8 +161,17 @@ fn diagnostic( }; let pointer = error.instance_path().to_string(); let path = instance_path(&pointer, root); + // A rejected name is located at its own key, though the path names only + // its collection. + let rejected_key = match error.kind() { + Kind::PropertyNames { error } => error.instance().as_str().map(escape), + _ => None, + }; let position = source - .and_then(|text| super::super::yaml_source::position(text, &pointer)) + .and_then(|text| match &rejected_key { + Some(key) => yaml_source::position(text, &format!("{pointer}/{key}"), true), + None => yaml_source::position(text, &pointer, false), + }) .map(|(line, column)| format!(" (line {line}, column {column})")) .unwrap_or_default(); ConfigError(format!( @@ -166,10 +195,7 @@ fn annotation<'s>( let path = error.schema_path().as_str(); if let Kind::Required { property } = error.kind() && let (Some(object), Some(name)) = (path.strip_suffix("/required"), property.as_str()) - && let Some(found) = message(&format!( - "{object}/properties/{}", - name.replace('~', "~0").replace('/', "~1") - )) + && let Some(found) = message(&format!("{object}/properties/{}", escape(name))) { return Some(found); } @@ -223,6 +249,14 @@ fn removed_fields(schema: &Value, error: &jsonschema::ValidationError<'_>) -> Op }) } +fn count(limit: u64, one: &str, many: &str) -> String { + if limit == 1 { + format!("1 {one}") + } else { + format!("{limit} {many}") + } +} + fn scalar_constraint(schema: &Value) -> Option { if let Some(value) = schema.get("const") { return Some(value.to_string()); @@ -263,16 +297,17 @@ fn instance_path(pointer: &str, root: &Value) -> String { { [ "spec", - "services" | "harnesses" | "inferences" | "integrations", + "services" | "harnesses" | "inferences" | "integrations" | "inferenceProviders" + | "sandboxes", ] => true, [ "spec", "sandboxes", - index, - "harnesses" | "inferences" | "integrations", + sandbox, + "harnesses" | "inferences" | "integrations" | "inferenceProviders", ] - | ["spec", "sandboxes", index, "agent", "integrations"] => { - index.parse::().is_ok() + | ["spec", "sandboxes", sandbox, "agent", "integrations"] => { + NAME.is_valid(&Value::String((*sandbox).to_owned())) } _ => false, }; @@ -538,6 +573,95 @@ mod tests { ); } + #[test] + fn a_path_shows_collection_keys_only_when_they_are_names() { + let entry = json!({ + "agent": {"inference": {"routes": [{"provider": {}}]}, "integrations": {"search": {}}}, + "harnesses": {"shared": {}}, + "inferenceProviders": {"own": {}, "Private-Sentinel": {}} + }); + let root = json!({"spec": { + "inferenceProviders": {"local": {}, "Private-Sentinel": {}}, + "sandboxes": {"assistant": entry.clone(), "Private-Sentinel": entry} + }}); + for (pointer, expected) in [ + ("/spec/sandboxes", "spec.sandboxes"), + ( + "/spec/sandboxes/assistant/agent", + "spec.sandboxes.assistant.agent", + ), + ( + "/spec/sandboxes/assistant/agent/inference/routes/0/provider", + "spec.sandboxes.assistant.agent.inference.routes[0].provider", + ), + ( + "/spec/inferenceProviders/local", + "spec.inferenceProviders.local", + ), + ( + "/spec/sandboxes/assistant/inferenceProviders/own", + "spec.sandboxes.assistant.inferenceProviders.own", + ), + ( + "/spec/sandboxes/assistant/harnesses/shared", + "spec.sandboxes.assistant.harnesses.shared", + ), + ( + "/spec/sandboxes/assistant/agent/integrations/search", + "spec.sandboxes.assistant.agent.integrations.search", + ), + ( + "/spec/inferenceProviders/Private-Sentinel", + "spec.inferenceProviders.[entry]", + ), + ( + "/spec/sandboxes/assistant/inferenceProviders/Private-Sentinel", + "spec.sandboxes.assistant.inferenceProviders.[entry]", + ), + ( + "/spec/sandboxes/Private-Sentinel/agent", + "spec.sandboxes.[entry].agent", + ), + ( + "/spec/sandboxes/Private-Sentinel/harnesses/shared", + "spec.sandboxes.[entry].harnesses.[entry]", + ), + ] { + assert_eq!(instance_path(pointer, &root), expected, "{pointer}"); + } + } + + #[test] + fn a_collection_size_error_states_its_bound() { + let schema = json!({ + "type": "object", + "properties": { + "routes": {"type": "array", "minItems": 1, "maxItems": 2}, + "services": {"type": "object", "minProperties": 2, "maxProperties": 1} + } + }); + for (instance, expected) in [ + (json!({"routes": []}), "routes: must have at least 1 item"), + ( + json!({"routes": [1, 2, 3]}), + "routes: must have at most 2 items", + ), + ( + json!({"services": {}}), + "services: must have at least 2 entries", + ), + ( + json!({"services": {"a": 1, "b": 2}}), + "services: must have at most 1 entry", + ), + ] { + assert_eq!( + message(&schema, instance), + format!("configuration violates schema at {expected}") + ); + } + } + #[test] fn a_missing_field_reports_its_own_annotation() { let schema = json!({ diff --git a/crates/nemoclaw-sdk/src/config/schema/validation.rs b/crates/nemoclaw-sdk/src/config/schema/validation.rs index 2dea727ad3e..c80c556be30 100644 --- a/crates/nemoclaw-sdk/src/config/schema/validation.rs +++ b/crates/nemoclaw-sdk/src/config/schema/validation.rs @@ -63,15 +63,17 @@ pub(super) fn constrain(root: &mut Value, normalized: bool) { ); } for name in ["Spec", "Sandbox"] { + for field in ["inferences", "harnesses", "inferenceProviders"] { + property( + &mut defs[name], + field, + json!({"propertyNames": {"pattern": c::SLUG}}), + ); + } property( &mut defs[name], - "inferences", - json!({"propertyNames": {"pattern": c::SLUG}}), - ); - property( - &mut defs[name], - "harnesses", - json!({"propertyNames": {"pattern": c::SLUG}}), + "inferenceProviders", + json!({"x-nemoclaw-error": format!("inferenceProviders must map lowercase names ({}) to provider definitions", c::SLUG)}), ); } property( @@ -93,7 +95,7 @@ pub(super) fn constrain(root: &mut Value, normalized: bool) { "integrationRefs", json!({"uniqueItems": true, "items": {"type": "string", "pattern": c::SLUG}}), ); - for name in ["Metadata", "InferenceProvider", "Sandbox", "Agent"] { + for name in ["Metadata", "InlineInferenceProvider", "Agent"] { property( defs.get_mut(name).unwrap(), "name", @@ -156,8 +158,17 @@ pub(super) fn constrain(root: &mut Value, normalized: bool) { property( &mut defs["Spec"], "sandboxes", - json!({"minItems":1,"maxItems":32}), + json!({ + "propertyNames": {"pattern": c::SLUG}, "minProperties": 1, "maxProperties": 32, + "x-nemoclaw-error": format!("spec.sandboxes must map 1 to 32 lowercase names ({}) to sandbox definitions", c::SLUG) + }), ); + // Earlier documents listed named entries; the key now carries the name. + defs["Sandbox"]["x-nemoclaw-removed-fields"] = + json!({"name": "a sandbox's name is its key under spec.sandboxes"}); + defs["InferenceProvider"]["x-nemoclaw-removed-fields"] = json!({ + "name": "a provider's name is its key under inferenceProviders; only an inline route provider states name" + }); defs["Sandbox"]["allOf"] = json!([]); optional_string( &mut defs["Image"], @@ -240,20 +251,28 @@ pub(super) fn constrain(root: &mut Value, normalized: bool) { constrain_gateway(defs, normalized); - let provider = &mut defs["InferenceProvider"]; - property(provider, "serviceRef", json!({"pattern": c::SLUG})); - provider["if"] = json!({"required": ["serviceRef"]}); - provider["then"] = json!({"properties": {"provider":{"const":"openai"},"endpoint": {"const": ""}}, "allOf": [forbid(&["credential"])]}); - provider["else"] = - json!({"required": ["endpoint"], "properties": {"endpoint": {"pattern": "^https?://"}}}); - provider["allOf"] = json!([ - {"if": at("endpoint", json!({"pattern": "^http:"}), true), "then": forbid(&["credential"])}, - {"if": {"required":["api"]}, "then": { - "if": at("api", json!({"const":"anthropic-messages"}), true), - "then": at("provider", json!({"const":"anthropic"}), false), - "else": at("provider", json!({"const":"openai"}), false) - }} - ]); + // An inline definition carries the keyed definition's fields beside its + // name, so it takes the same rules. + for name in ["InferenceProvider", "InlineInferenceProvider"] { + let provider = &mut defs[name]; + property(provider, "serviceRef", json!({"pattern": c::SLUG})); + provider["if"] = json!({"required": ["serviceRef"]}); + provider["then"] = json!({ + "properties": {"provider":{"const":"openai"},"endpoint": {"const": ""}}, "allOf": [forbid(&["credential"])], + "x-nemoclaw-error": "serviceRef excludes endpoint and credential and selects provider openai" + }); + provider["else"] = json!({"required": ["endpoint"], "properties": {"endpoint": {"pattern": "^https?://"}}}); + let mut plain = forbid(&["credential"]); + plain["x-nemoclaw-error"] = json!("an http:// endpoint takes no credential"); + provider["allOf"] = json!([ + {"if": at("endpoint", json!({"pattern": "^http:"}), true), "then": plain}, + {"if": {"required":["api"]}, "then": { + "if": at("api", json!({"const":"anthropic-messages"}), true), + "then": at("provider", json!({"const":"anthropic"}), false), + "else": at("provider", json!({"const":"openai"}), false) + }} + ]); + } defs["AgentExecution"]["minProperties"] = json!(1); crate::services::constrain_schema(defs, normalized); @@ -265,14 +284,14 @@ pub(super) fn constrain(root: &mut Value, normalized: bool) { true, ); let mut explicit = at( - "spec/sandboxes/[]/image", + "spec/sandboxes/*/image", json!({"required": ["ref", "metadata"], "properties": {"ref": {"pattern": c::IMAGE}}}), true, ); explicit["x-nemoclaw-error"] = json!( "a Kubernetes target requires each sandbox image.ref pinned by digest and image.metadata" ); - let mut inspected = at("spec/sandboxes/[]/image", forbid(&["metadata"]), false); + let mut inspected = at("spec/sandboxes/*/image", forbid(&["metadata"]), false); inspected["x-nemoclaw-error"] = json!( "image.metadata is available only for a spec.gateway.target.kubernetes gateway; Docker and Podman use engine image inspection" ); diff --git a/crates/nemoclaw-sdk/src/config/types.rs b/crates/nemoclaw-sdk/src/config/types.rs index 75b9b69c2af..b552219e681 100644 --- a/crates/nemoclaw-sdk/src/config/types.rs +++ b/crates/nemoclaw-sdk/src/config/types.rs @@ -63,14 +63,14 @@ pub struct Spec { #[serde( rename = "inferenceProviders", default, - skip_serializing_if = "Vec::is_empty" + skip_serializing_if = "std::collections::BTreeMap::is_empty" )] #[schemars(default)] - /// Named inference definitions available to sandbox routes. Unselected definitions create no resources or credential requirements. - pub inference_providers: Vec, + /// Inference definitions keyed by lowercase name and available to sandbox routes. Unselected definitions create no resources or credential requirements. + pub inference_providers: std::collections::BTreeMap, #[serde(rename = "sandboxes")] - /// One to 32 uniquely named sandboxes. Each runs one agent through its selected Fabric adapter. Declaration order does not select a default sandbox or agent. - pub sandboxes: Vec, + /// One to 32 sandboxes keyed by lowercase name. Each runs one agent through its selected Fabric adapter. Key order has no meaning and selects no default sandbox or agent. + pub sandboxes: std::collections::BTreeMap, } #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] @@ -256,9 +256,6 @@ pub struct ExternalKubernetes {} #[serde(deny_unknown_fields)] /// Choose an endpoint for external inference or serviceRef for a managed service. pub struct InferenceProvider { - #[serde(rename = "name")] - /// Provider name referenced by model choices. - pub name: String, #[serde(rename = "provider")] /// OpenShell provider implementation. Must match the selected API family. pub provider: super::InferenceProviderKind, @@ -285,6 +282,18 @@ pub struct InferenceProvider { pub service_ref: Option, } +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +/// Inference definition owned by one route: choose an endpoint for external inference or serviceRef for a managed service. It has no map key, so it states its own name. +pub struct InlineInferenceProvider { + #[serde(rename = "name")] + /// Lowercase provider name. It must not shadow an enclosing definition. + pub name: String, + #[serde(flatten)] + /// Endpoint or managed service, with the same rules as a keyed definition. + pub definition: InferenceProvider, +} + #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] #[schemars(!default)] #[serde(default, deny_unknown_fields)] @@ -313,18 +322,15 @@ pub struct Sandbox { #[serde( rename = "inferenceProviders", default, - skip_serializing_if = "Vec::is_empty" + skip_serializing_if = "std::collections::BTreeMap::is_empty" )] #[schemars(default)] - /// Named inference definitions visible to this sandbox's routes. Names must not shadow deployment definitions. - pub inference_providers: Vec, + /// Inference definitions keyed by lowercase name and visible to this sandbox's routes. Names must not shadow deployment definitions. + pub inference_providers: std::collections::BTreeMap, #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] #[schemars(default)] /// Named integration definitions selected by this sandbox's agent through integrationRefs. Names must not collide with deployment definitions. pub integrations: std::collections::BTreeMap, - #[serde(rename = "name")] - /// Lowercase sandbox name. - pub name: String, #[serde(rename = "image")] #[schemars(default)] #[schemars(extend("x-nemoclaw-required" = "With a Kubernetes target"))] @@ -429,9 +435,9 @@ pub struct Route { /// Name of an enclosing inference provider. Exactly one of providerRef or provider is required. pub provider_ref: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - #[schemars(default, with = "InferenceProvider")] + #[schemars(default, with = "InlineInferenceProvider")] /// Inline inference definition owned by this route. Excludes providerRef and must not shadow an enclosing definition. - pub provider: Option, + pub provider: Option, #[serde(rename = "overrides")] /// Model selection, shared limits, and optional native settings. pub overrides: Overrides, diff --git a/crates/nemoclaw-sdk/src/config/validation.rs b/crates/nemoclaw-sdk/src/config/validation.rs index 55566f65e77..042824f5617 100644 --- a/crates/nemoclaw-sdk/src/config/validation.rs +++ b/crates/nemoclaw-sdk/src/config/validation.rs @@ -50,8 +50,7 @@ impl Document { for definition in self.provider_definitions() { self.validate_provider(definition)?; } - let mut sandbox_names = std::collections::BTreeSet::new(); - for sandbox in &self.spec.sandboxes { + for (name, sandbox) in &self.spec.sandboxes { require( self.spec.gateway.compute_driver().is_kubernetes() || sandbox.image.metadata.is_none(), @@ -60,13 +59,9 @@ impl Document { if let Some(metadata) = &sandbox.image.metadata { schema::validate_definition("FileRef", metadata)?; } - require( - sandbox_names.insert(&sandbox.name), - "sandbox names must be unique", - )?; sandbox.network.validate()?; - let web_search = self.web_search(sandbox)?; - crate::image_runtime::policy_input(self, sandbox)?; + let web_search = self.web_search(name)?; + crate::image_runtime::policy_input(self, name)?; if let Some(search) = web_search { require( selected_providers.iter().all(|provider| { @@ -87,7 +82,7 @@ impl Document { if let Some(tools) = &agent.tools { tools.validate()?; } - let inference = self.scoped_inference(sandbox)?; + let inference = self.scoped_inference(name)?; for route in &inference.inference.routes { let selected = self.route_provider(route, &inference)?; let provider = selected.definition; diff --git a/crates/nemoclaw-sdk/src/config/yaml_source.rs b/crates/nemoclaw-sdk/src/config/yaml_source.rs index 6c71a73b0ee..cadbd17fe0c 100644 --- a/crates/nemoclaw-sdk/src/config/yaml_source.rs +++ b/crates/nemoclaw-sdk/src/config/yaml_source.rs @@ -95,7 +95,9 @@ enum Frame { /// Locate a validated JSON pointer using the same YAML parser's node positions. /// This runs only after bounded deserialization, and never renders source text. -pub(super) fn position(text: &str, pointer: &str) -> Option<(usize, usize)> { +/// With `at_key`, the pointer names a mapping entry and the position is its +/// key's, so a rejected name points at itself rather than at its value. +pub(super) fn position(text: &str, pointer: &str, at_key: bool) -> Option<(usize, usize)> { let mut frames = Vec::new(); for event in Parser::new_from_str(text) { let (event, span) = event.ok()?; @@ -106,15 +108,17 @@ pub(super) fn position(text: &str, pointer: &str) -> Option<(usize, usize)> { Event::Scalar(ref value, ..) if matches!(frames.last(), Some(Frame::Mapping { key: None, .. })) => { - if let Some(Frame::Mapping { key, .. }) = frames.last_mut() { + if let Some(Frame::Mapping { path, key }) = frames.last_mut() { + if at_key && format!("{path}/{}", escape(value)) == pointer { + return Some((span.start.line(), span.start.col() + 1)); + } *key = Some(value.to_string()); } } Event::Scalar(..) | Event::MappingStart(..) | Event::SequenceStart(..) => { let path = match frames.last_mut() { Some(Frame::Mapping { path, key }) => { - let key = key.take()?.replace('~', "~0").replace('/', "~1"); - format!("{path}/{key}") + format!("{path}/{}", escape(&key.take()?)) } Some(Frame::Sequence { path, next }) => { let path = format!("{path}/{next}"); @@ -123,7 +127,7 @@ pub(super) fn position(text: &str, pointer: &str) -> Option<(usize, usize)> { } None => String::new(), }; - if path == pointer { + if !at_key && path == pointer { return Some((span.start.line(), span.start.col() + 1)); } match event { @@ -137,3 +141,8 @@ pub(super) fn position(text: &str, pointer: &str) -> Option<(usize, usize)> { } None } + +/// Escape one JSON pointer segment. +pub(super) fn escape(segment: &str) -> String { + segment.replace('~', "~0").replace('/', "~1") +} diff --git a/crates/nemoclaw-sdk/src/deployment/apply.rs b/crates/nemoclaw-sdk/src/deployment/apply.rs index d5c701e1572..906c9a3b1fa 100644 --- a/crates/nemoclaw-sdk/src/deployment/apply.rs +++ b/crates/nemoclaw-sdk/src/deployment/apply.rs @@ -89,8 +89,8 @@ impl Readiness { .spec .sandboxes .iter() - .map(|sandbox| { - let address = format!("data.fabric_sandbox_readiness.{}", sandbox.name); + .map(|(name, sandbox)| { + let address = format!("data.fabric_sandbox_readiness.{name}"); let observed = observations .get(&address) .ok_or(Error::State("sandbox readiness observation is absent"))?; @@ -111,7 +111,7 @@ impl Readiness { )); } Ok(SandboxObservation { - sandbox: sandbox.name.clone(), + sandbox: name.clone(), agent: sandbox.agent.name.clone(), failed: !observed["ready"] .as_bool() diff --git a/crates/nemoclaw-sdk/src/deployment/export.rs b/crates/nemoclaw-sdk/src/deployment/export.rs index b59dc6ab5ff..5f1731cae24 100644 --- a/crates/nemoclaw-sdk/src/deployment/export.rs +++ b/crates/nemoclaw-sdk/src/deployment/export.rs @@ -544,10 +544,9 @@ mod tests { let mut document = Document::parse(include_bytes!("../../tests/fixtures/config/local.yaml").as_slice()) .unwrap(); - let mut second = document.spec.sandboxes[0].clone(); - second.name = "second".into(); + let mut second = document.spec.sandboxes["assistant"].clone(); second.image.ref_ = format!("fixture/second@sha256:{}", "b".repeat(64)); - document.spec.sandboxes.push(second); + document.spec.sandboxes.insert("second".into(), second); let generations = ["workspace", "provider", "sandbox"] .map(|kind| (kind.into(), "a".repeat(32))) .into(); @@ -697,7 +696,7 @@ mod tests { "credential":{"env":"SEARCH_KEY"}} })) .unwrap(); - let sandbox = &mut document.spec.sandboxes[0]; + let sandbox = document.spec.sandboxes.get_mut("assistant").unwrap(); sandbox.agent.integration_refs = vec!["search".into()]; match scope { "deployment" => document.spec.integrations = definitions, @@ -751,8 +750,9 @@ mod tests { let mut document = Document::parse(include_str!("../../tests/fixtures/config/local.yaml").as_bytes()) .unwrap(); - document.spec.inference_providers[0].endpoint = "https://models.example/v1".into(); - document.spec.inference_providers[0].credential = Some(SecretRef { + let provider = document.spec.inference_providers.get_mut("local").unwrap(); + provider.endpoint = "https://models.example/v1".into(); + provider.credential = Some(SecretRef { env: "OLD_KEY".into(), }); let expected = provider_row(&document); @@ -770,11 +770,11 @@ mod tests { observed.insert("credential_env".into(), "NEW_INFERENCE_KEY".into()); export_provider(&mut document, &expected, &observed).unwrap(); assert_eq!( - document.spec.inference_providers[0].endpoint, + document.spec.inference_providers["local"].endpoint, "https://models.example/v1" ); assert_eq!( - document.spec.inference_providers[0] + document.spec.inference_providers["local"] .credential .as_ref() .unwrap() @@ -815,12 +815,12 @@ mod tests { .unwrap(), ) .unwrap(); - value["spec"]["inferenceProviders"].as_array_mut().unwrap().push(serde_json::json!({"name":"hosted","provider":"openai","endpoint":"https://hosted.example/v1","credential":{"env":"OLD_KEY"}})); - let inference = &mut value["spec"]["sandboxes"][0]["agent"]["inference"]; + value["spec"]["inferenceProviders"]["hosted"] = serde_json::json!({"provider":"openai","endpoint":"https://hosted.example/v1","credential":{"env":"OLD_KEY"}}); + let inference = &mut value["spec"]["sandboxes"]["assistant"]["agent"]["inference"]; inference["default"] = serde_json::json!("primary"); inference["routes"].as_array_mut().unwrap().push(serde_json::json!({"name":"smart","providerRef":"hosted","overrides":{"model":"smart"}})); let mut document = Document::parse(value.to_string().as_bytes()).unwrap(); - let original = document.spec.inference_providers[0].clone(); + let original = document.spec.inference_providers["local"].clone(); let record = Record::new(document.clone()).unwrap(); let expected = compile::targets(&document, &record.generations) .unwrap() @@ -834,9 +834,9 @@ mod tests { let mut observed = expected.clone(); observed.insert("credential_env".into(), "NEW_KEY".into()); export_provider(&mut document, &expected, &observed).unwrap(); - assert_eq!(&document.spec.inference_providers[0], &original); + assert_eq!(&document.spec.inference_providers["local"], &original); assert_eq!( - document.spec.inference_providers[1] + document.spec.inference_providers["hosted"] .credential .as_ref() .unwrap() diff --git a/crates/nemoclaw-sdk/src/deployment/reporting.rs b/crates/nemoclaw-sdk/src/deployment/reporting.rs index 51c43bc44f1..ffbc680c428 100644 --- a/crates/nemoclaw-sdk/src/deployment/reporting.rs +++ b/crates/nemoclaw-sdk/src/deployment/reporting.rs @@ -38,7 +38,7 @@ pub struct ResourceSource { impl OperationResult { pub(super) fn describe_sources(&mut self, document: &Document) -> Result<(), Error> { for provider in document.selected_providers()? { - if provider.key != provider.definition.name { + if provider.key != provider.name { for kind in ["provider", "provider_profile"] { self.resource_sources.insert( format!( @@ -47,7 +47,7 @@ impl OperationResult { provider.key ), ResourceSource { - name: provider.definition.name.clone(), + name: provider.name.to_owned(), path: provider.path.clone(), }, ); @@ -404,14 +404,13 @@ mod tests { fn inline_and_scoped_provider_sources_preserve_authored_names_without_values() { let mut input: Value = serde_saphyr::from_str(include_str!("../../tests/fixtures/config/local.yaml")).unwrap(); - let mut provider = input["spec"]["inferenceProviders"][0].take(); - provider["name"] = "responses".into(); + let provider = input["spec"]["inferenceProviders"]["local"].take(); input["spec"] .as_object_mut() .unwrap() .remove("inferenceProviders"); - let sandbox = &mut input["spec"]["sandboxes"][0]; - sandbox["inferenceProviders"] = json!([provider]); + let sandbox = &mut input["spec"]["sandboxes"]["assistant"]; + sandbox["inferenceProviders"] = json!({"responses": provider}); let route = &mut sandbox["agent"]["inference"]["routes"][0]; route["providerRef"] = "responses".into(); let document = Document::parse(input.to_string().as_bytes()).unwrap(); @@ -425,8 +424,8 @@ mod tests { .all(|source| source.name == "responses" && source.path == "spec.sandboxes[assistant].inferenceProviders[responses]") ); - let sandbox = &mut input["spec"]["sandboxes"][0]; - let mut provider = sandbox["inferenceProviders"][0].take(); + let sandbox = &mut input["spec"]["sandboxes"]["assistant"]; + let mut provider = sandbox["inferenceProviders"]["responses"].take(); sandbox .as_object_mut() .unwrap() diff --git a/crates/nemoclaw-sdk/src/deployment/runtime/teardown.rs b/crates/nemoclaw-sdk/src/deployment/runtime/teardown.rs index e84289fb637..296e9426b90 100644 --- a/crates/nemoclaw-sdk/src/deployment/runtime/teardown.rs +++ b/crates/nemoclaw-sdk/src/deployment/runtime/teardown.rs @@ -10,7 +10,7 @@ pub(super) fn destroy_environment(document: &Document) -> Document { for provider in environment.provider_definitions_mut() { provider.credential = None; } - for sandbox in &mut environment.spec.sandboxes { + for sandbox in environment.spec.sandboxes.values_mut() { // Destroy never reads the image, so it needs no metadata path. sandbox.image.metadata = None; sandbox.integrations.clear(); @@ -371,7 +371,12 @@ mod tests { assert!(document.credential_names().contains(&"TEST_IMAGE_METADATA")); let environment = destroy_environment(&document); assert_eq!(environment.credential_names(), ["TEST_KUBECONFIG"]); - assert!(document.spec.sandboxes[0].image.metadata.is_some()); + assert!( + document.spec.sandboxes["assistant"] + .image + .metadata + .is_some() + ); } #[tokio::test] @@ -654,8 +659,7 @@ mod tests { #[test] fn multiple_services_retain_each_volume_and_require_its_own_binding() { let (mut record, _) = runtime_state(); - let mut provider = record.document.spec.inference_providers[0].clone(); - provider.name = "other".into(); + let mut provider = record.document.spec.inference_providers["qwen"].clone(); provider.service_ref = Some("other".into()); let mut definition = record.document.spec.services["qwen"].clone(); update_service(&mut definition, "/serving/port", |port| { @@ -666,11 +670,18 @@ mod tests { .spec .services .insert("other".into(), definition); - record.document.spec.inference_providers.push(provider); - let mut sandbox = record.document.spec.sandboxes[0].clone(); - sandbox.name = "other".into(); + record + .document + .spec + .inference_providers + .insert("other".into(), provider); + let mut sandbox = record.document.spec.sandboxes["assistant"].clone(); sandbox.agent.inference.as_mut().unwrap().routes[0].provider_ref = Some("other".into()); - record.document.spec.sandboxes.push(sandbox); + record + .document + .spec + .sandboxes + .insert("other".into(), sandbox); let bindings: BTreeMap<_, _> = compile::runtime_targets(&record.document, &record.generations) .unwrap() diff --git a/crates/nemoclaw-sdk/src/deployment/tests.rs b/crates/nemoclaw-sdk/src/deployment/tests.rs index 3928925564b..d8aed0ae49c 100644 --- a/crates/nemoclaw-sdk/src/deployment/tests.rs +++ b/crates/nemoclaw-sdk/src/deployment/tests.rs @@ -18,7 +18,8 @@ pub(super) fn kubernetes_context() -> (Document, crate::compile::Generations) { "authentication":{"profile":"development"} }} }); - value["spec"]["sandboxes"][0]["image"]["metadata"] = json!({"env":"TEST_IMAGE_METADATA"}); + value["spec"]["sandboxes"]["assistant"]["image"]["metadata"] = + json!({"env":"TEST_IMAGE_METADATA"}); let document = Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap(); let generations = Record::new(document.clone()).unwrap().generations; (document, generations) @@ -128,7 +129,12 @@ fn kubernetes_environment_is_operation_scoped_and_stable_across_export_directori } } let (mut document, _) = kubernetes_context(); - document.spec.inference_providers[0].credential = Some(SecretRef { + document + .spec + .inference_providers + .get_mut("local") + .unwrap() + .credential = Some(SecretRef { env: "UNREAD_INFERENCE_KEY".into(), }); let temporary = tempfile::tempdir().unwrap(); @@ -444,8 +450,18 @@ fn credential_references_cannot_override_opentofu_control_variables() { } let mut document = Document::parse(include_str!("../../tests/fixtures/config/local.yaml").as_bytes()).unwrap(); - document.spec.inference_providers[0].endpoint = "https://example.com/v1".into(); - document.spec.inference_providers[0].credential = Some(SecretRef { + document + .spec + .inference_providers + .get_mut("local") + .unwrap() + .endpoint = "https://example.com/v1".into(); + document + .spec + .inference_providers + .get_mut("local") + .unwrap() + .credential = Some(SecretRef { env: "TF_CLI_CONFIG_FILE".into(), }); assert!(command_environment(&document, &Values, Path::new("state")).is_err()); @@ -515,7 +531,12 @@ async fn schema_commands_do_not_require_inference_credentials() { Deployment::new(&state_path, bundle_directory.path()).with_secrets(secrets.clone()); let mut document = Document::parse(include_str!("../../tests/fixtures/config/local.yaml").as_bytes()).unwrap(); - document.spec.inference_providers[0].credential = Some(SecretRef { + document + .spec + .inference_providers + .get_mut("local") + .unwrap() + .credential = Some(SecretRef { env: "TEST_INFERENCE_CREDENTIAL".into(), }); let cancel = CancellationToken::new(); @@ -635,14 +656,30 @@ fn gateway_observation_resolves_only_gateway_credentials() { } })) .unwrap(); - document.spec.inference_providers[0].credential = Some(SecretRef { + document + .spec + .inference_providers + .get_mut("local") + .unwrap() + .credential = Some(SecretRef { env: "INFERENCE_TOKEN".into(), }); - document.spec.sandboxes[0].integrations = serde_json::from_value(json!({ + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .integrations = serde_json::from_value(json!({ "search": {"kind": "webSearch", "provider": "brave", "credential": {"env": "SEARCH_KEY"}} })) .unwrap(); - document.spec.sandboxes[0].agent.integration_refs = vec!["search".into()]; + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .agent + .integration_refs = vec!["search".into()]; let environment = gateway_environment(&document, &GatewayValues, Path::new("state")).unwrap(); for name in ["GATEWAY_TOKEN", "GATEWAY_CA", "GATEWAY_CERT", "GATEWAY_KEY"] { assert_eq!(environment[name], format!("test-{name}")); diff --git a/crates/nemoclaw-sdk/src/discovery.rs b/crates/nemoclaw-sdk/src/discovery.rs index 83fe5dee93d..38c915970d0 100644 --- a/crates/nemoclaw-sdk/src/discovery.rs +++ b/crates/nemoclaw-sdk/src/discovery.rs @@ -93,13 +93,12 @@ pub fn plan_queries(document: &Document) -> Result, ConfigEr compute_driver: gateway.compute_driver, }); queries.extend(platform.clone().map(DiscoveryQuery::Engine)); - let mut sandboxes: Vec<_> = document.spec.sandboxes.iter().collect(); - sandboxes.sort_by(|left, right| left.name.cmp(&right.name)); - for sandbox in sandboxes { + // One Fabric read per sandbox, in name order. + for (name, sandbox) in &document.spec.sandboxes { queries.push(DiscoveryQuery::Fabric(FabricRequest { engine: engine.into(), image: sandbox.image.ref_.clone(), - requirements: crate::fabric_capabilities::requirements_for_sandbox(document, sandbox)?, + requirements: crate::fabric_capabilities::requirements_for_sandbox(document, name)?, platform: platform.clone(), metadata_env: sandbox .image diff --git a/crates/nemoclaw-sdk/src/discovery_graph.rs b/crates/nemoclaw-sdk/src/discovery_graph.rs index e5359b92634..276da5fadab 100644 --- a/crates/nemoclaw-sdk/src/discovery_graph.rs +++ b/crates/nemoclaw-sdk/src/discovery_graph.rs @@ -98,9 +98,8 @@ fn read( pub(crate) fn populate(graph: &mut Value, document: &Document) -> Result<(), ConfigError> { let mut observations = Map::new(); - let mut sandboxes: Vec<_> = document.spec.sandboxes.iter().collect(); - sandboxes.sort_by(|left, right| left.name.cmp(&right.name)); - let mut sandboxes = sandboxes.into_iter(); + // Discovery reads Fabric once per sandbox, in name order. + let mut sandboxes = document.spec.sandboxes.keys(); let (mut endpoints, mut targets, mut images) = (0, 0, 0); for query in plan_queries(document)? { match &query { @@ -149,7 +148,7 @@ pub(crate) fn populate(graph: &mut Value, document: &Document) -> Result<(), Con .expect("resolved adapter"); let context = literal(&format!( "sandbox/{}: adapter/{} compatibility rejected", - sandbox.name, + sandbox, crate::fabric_capabilities::diagnostic_field(adapter) )); let rejection = format!( @@ -163,9 +162,9 @@ pub(crate) fn populate(graph: &mut Value, document: &Document) -> Result<(), Con }, { "condition": "${self.runtime_json != \"\"}", "error_message": if metadata_env.is_some() || document.spec.gateway.compute_driver().is_kubernetes() { - format!("sandbox/{}: image runtime metadata is unavailable. Set image.metadata.env to an absolute metadata bundle path and verify that it matches the immutable image digest. Resources retained.", sandbox.name) + format!("sandbox/{sandbox}: image runtime metadata is unavailable. Set image.metadata.env to an absolute metadata bundle path and verify that it matches the immutable image digest. Resources retained.") } else { - format!("sandbox/{}: image runtime metadata is unavailable. Set the engine of spec.gateway.target.docker or spec.gateway.target.podman to the sandbox image engine, load an image built with its runtime manifest, and use its immutable digest. Resources retained.", sandbox.name) + format!("sandbox/{sandbox}: image runtime metadata is unavailable. Set the engine of spec.gateway.target.docker or spec.gateway.target.podman to the sandbox image engine, load an image built with its runtime manifest, and use its immutable digest. Resources retained.") } }] }); })?; diff --git a/crates/nemoclaw-sdk/src/fabric_capabilities.rs b/crates/nemoclaw-sdk/src/fabric_capabilities.rs index c95d5883680..af2626c64d7 100644 --- a/crates/nemoclaw-sdk/src/fabric_capabilities.rs +++ b/crates/nemoclaw-sdk/src/fabric_capabilities.rs @@ -5,12 +5,12 @@ //! document places on its image. pub use nemoclaw_fabric::capabilities::*; -/// The Fabric configuration and filesystem reads a sandbox requires. +/// The Fabric configuration and filesystem reads the named sandbox requires. pub fn requirements_for_sandbox( document: &crate::config::Document, - sandbox: &crate::config::Sandbox, + sandbox: &str, ) -> Result { - let filesystem_read = match &sandbox.network.policy { + let filesystem_read = match &document.sandbox(sandbox)?.network.policy { crate::config::NetworkPolicy::Explicit(policy) => { policy.filesystem_policy.as_ref().map(|fs| { fs.read_only diff --git a/crates/nemoclaw-sdk/src/fabric_config.rs b/crates/nemoclaw-sdk/src/fabric_config.rs index f26c0090082..92a9f730128 100644 --- a/crates/nemoclaw-sdk/src/fabric_config.rs +++ b/crates/nemoclaw-sdk/src/fabric_config.rs @@ -1,17 +1,19 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 //! Deployment-owned projection into the public Fabric configuration contract. -use crate::config::{ConfigError, Document, Sandbox}; +use crate::config::{ConfigError, Document}; use serde_json::{Value, json}; -/// Resolve deployment references without interpreting native adapter settings. -/// This exact configuration is planned against the image descriptors and sent to Fabric. -pub fn for_sandbox(document: &Document, sandbox: &Sandbox) -> Result { +/// Resolve deployment references for the named sandbox without interpreting +/// native adapter settings. This exact configuration is planned against the +/// image descriptors and sent to Fabric. +pub fn for_sandbox(document: &Document, sandbox: &str) -> Result { let harness = document.sandbox_harness(sandbox)?; let selection = document.scoped_inference(sandbox)?; + let agent = &document.sandbox(sandbox)?.agent; let mut result = json!({ "schema_version":"fabric.agent/v1alpha1", - "metadata":{"name":sandbox.agent.name}, + "metadata":{"name":agent.name}, "harness":{"adapter_id":harness.kind.as_str(),"settings":harness.settings.clone().unwrap_or_default()}, "runtime":{"artifacts":"/sandbox/artifacts"}, "environment":{"provider":"local","workspace":"/sandbox/workspace"}, @@ -24,7 +26,7 @@ pub fn for_sandbox(document: &Document, sandbox: &Sandbox) -> Result Result { use crate::config::{ConfigError, NetworkPolicy}; - let explicit = match &sandbox.network.policy { + let explicit = match &document.sandbox(sandbox)?.network.policy { NetworkPolicy::Isolated => None, NetworkPolicy::Explicit(policy) => Some(policy.clone()), }; diff --git a/crates/nemoclaw-sdk/src/inference_discovery.rs b/crates/nemoclaw-sdk/src/inference_discovery.rs index dd8755284b2..e3bc8655d92 100644 --- a/crates/nemoclaw-sdk/src/inference_discovery.rs +++ b/crates/nemoclaw-sdk/src/inference_discovery.rs @@ -133,7 +133,7 @@ pub fn observe_credentials( pub fn endpoint_requests(document: &Document) -> Result, Error> { document.validate()?; let mut requests = Vec::new(); - for sandbox in &document.spec.sandboxes { + for sandbox in document.spec.sandboxes.keys() { for provider in document.sandbox_inference_providers(sandbox)? { let Some(request) = EndpointRequest::for_external_provider(provider.definition)? else { continue; diff --git a/crates/nemoclaw-sdk/src/services/authentication.rs b/crates/nemoclaw-sdk/src/services/authentication.rs index 9d9139d4433..fe3806612ed 100644 --- a/crates/nemoclaw-sdk/src/services/authentication.rs +++ b/crates/nemoclaw-sdk/src/services/authentication.rs @@ -25,7 +25,7 @@ mod durable_source_tests { }; let mut value: Value = serde_saphyr::from_str(text).unwrap(); if proxy { - value["spec"]["inferenceProviders"][0]["serviceRef"] = json!("ollama-auth"); + value["spec"]["inferenceProviders"]["local"]["serviceRef"] = json!("ollama-auth"); value["spec"]["services"] = json!({"ollama-auth":{"kind":"ollamaProxy","image":format!("proxy@sha256:{}","a".repeat(64)),"endpoint":"http://172.20.0.1:11435/v1","upstream":{"endpoint":"http://127.0.0.1:11434/v1","model":{"name":"qwen3:0.6b","digest":"a".repeat(64)}}}}); } else { value["spec"]["services"]["qwen"]["authentication"] = json!("bearer"); diff --git a/crates/nemoclaw-sdk/src/services/registry.rs b/crates/nemoclaw-sdk/src/services/registry.rs index aec550b34e4..63e31dbc792 100644 --- a/crates/nemoclaw-sdk/src/services/registry.rs +++ b/crates/nemoclaw-sdk/src/services/registry.rs @@ -400,7 +400,7 @@ fn definition<'a>( .map(|(name, definition)| Some((name.as_str(), definition))) .ok_or_else(|| { crate::config::references::missing_reference( - "inferenceProviders[].serviceRef", + "serviceRef", "service", name, document.spec.services.keys().map(String::as_str), diff --git a/crates/nemoclaw-sdk/src/state/tests.rs b/crates/nemoclaw-sdk/src/state/tests.rs index e1461a35f18..69d0d9a4e22 100644 --- a/crates/nemoclaw-sdk/src/state/tests.rs +++ b/crates/nemoclaw-sdk/src/state/tests.rs @@ -83,7 +83,8 @@ fn removed_ownership_annotations_preserve_intent_and_resource_bindings_for_recov .unwrap(); let record = Record::new(document).unwrap(); let mut old = serde_json::to_value(&record).unwrap(); - old["document"]["spec"]["inferenceProviders"][0]["management"] = serde_json::json!("external"); + old["document"]["spec"]["inferenceProviders"]["local"]["management"] = + serde_json::json!("external"); let bytes = serde_json::to_vec(&old).unwrap(); let intent = dir.path().join("intent.json"); let state = dir.path().join("terraform.tfstate"); @@ -248,18 +249,26 @@ fn pending_creation_guards_only_unresolved_targets_and_survives_runtime_recovery record.pending = true; record.pending_creations = [(pending.address.clone(), pending.values.clone())].into(); let mut revised = document.clone(); - let mut unrelated = revised.spec.inference_providers[0].clone(); - unrelated.name = "unrelated".into(); - revised.spec.inference_providers.push(unrelated); + let unrelated = revised.spec.inference_providers["local"].clone(); + revised + .spec + .inference_providers + .insert("unrelated".into(), unrelated); assert!(record.validate_pending_intent(&revised).is_ok()); - revised.spec.sandboxes[0].image.ref_ = - format!("example.invalid/changed@sha256:{}", "b".repeat(64)); + revised + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .image + .ref_ = format!("example.invalid/changed@sha256:{}", "b".repeat(64)); revised.validate().unwrap(); assert!(matches!( record.validate_pending_intent(&revised), Err(Error::Conflict(_)) )); - revised.spec.sandboxes[0].name = "replacement".into(); + let sandbox = revised.spec.sandboxes.remove("assistant").unwrap(); + revised.spec.sandboxes.insert("replacement".into(), sandbox); revised.validate().unwrap(); assert!(matches!( record.validate_pending_intent(&revised), @@ -398,7 +407,7 @@ fn a_kubernetes_records_generations_reload_and_stay_stable() { "namespace": "test-agents", "authentication": {"profile": "development"} }} }); - value["spec"]["sandboxes"][0]["image"]["metadata"] = + value["spec"]["sandboxes"]["assistant"]["image"]["metadata"] = serde_json::json!({"env": "TEST_IMAGE_METADATA"}); let document = Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap(); let mut record = Record::new(document.clone()).unwrap(); @@ -658,7 +667,11 @@ fn bound_sandbox_guard_allows_configuration_updates_additions_and_explicit_recre )]); let mut revised = document.clone(); revised.metadata.name = "new-display-name".into(); - revised.spec.sandboxes[0] + revised + .spec + .sandboxes + .get_mut("assistant") + .unwrap() .agent .inference .as_mut() @@ -666,28 +679,31 @@ fn bound_sandbox_guard_allows_configuration_updates_additions_and_explicit_recre .routes[0] .overrides .model = "corrected-model".into(); - let mut added = revised.spec.sandboxes[0].clone(); - added.name = "reviewer".into(); - revised.spec.sandboxes.push(added); - revised.spec.sandboxes.reverse(); + let added = revised.spec.sandboxes["assistant"].clone(); + revised.spec.sandboxes.insert("reviewer".into(), added); record.validate_bound_sandboxes(&revised, &bound).unwrap(); for change in ["remove", "image", "agent", "policy", "endpoint"] { let mut value = serde_json::to_value(&document).unwrap(); match change { - "remove" => value["spec"]["sandboxes"][0]["name"] = serde_json::json!("different"), + "remove" => { + let sandboxes = value["spec"]["sandboxes"].as_object_mut().unwrap(); + let sandbox = sandboxes.remove("assistant").unwrap(); + sandboxes.insert("different".into(), sandbox); + } "image" => { - value["spec"]["sandboxes"][0]["image"]["ref"] = + value["spec"]["sandboxes"]["assistant"]["image"]["ref"] = serde_json::json!(format!("sandbox@sha256:{}", "f".repeat(64))) } "agent" => { - value["spec"]["sandboxes"][0]["agent"]["name"] = serde_json::json!("different") + value["spec"]["sandboxes"]["assistant"]["agent"]["name"] = + serde_json::json!("different") } "policy" => { - value["spec"]["sandboxes"][0]["network"] = + value["spec"]["sandboxes"]["assistant"]["network"] = serde_json::json!({"policy":{"explicit":{"version":1,"network_policies":{}}}}) } "endpoint" => { - value["spec"]["inferenceProviders"][0]["endpoint"] = + value["spec"]["inferenceProviders"]["local"]["endpoint"] = serde_json::json!("http://127.0.0.1:19999/v1") } _ => unreachable!(), diff --git a/crates/nemoclaw-sdk/tests/agent_tools.rs b/crates/nemoclaw-sdk/tests/agent_tools.rs index feedb9b87af..7bae4beca5f 100644 --- a/crates/nemoclaw-sdk/tests/agent_tools.rs +++ b/crates/nemoclaw-sdk/tests/agent_tools.rs @@ -9,17 +9,16 @@ use serde_json::{Value, json}; fn input(count: usize) -> Value { let mut value: Value = serde_saphyr::from_str(include_str!("../../../examples/fabric-openclaw.yaml")).unwrap(); - let primary = value["spec"]["sandboxes"][0].clone(); - value["spec"]["sandboxes"] = Value::Array( + let primary = value["spec"]["sandboxes"]["assistant"].clone(); + value["spec"]["sandboxes"] = Value::Object( (0..count) .map(|n| { let mut sandbox = primary.clone(); - sandbox["name"] = json!(format!("sandbox-{n}")); sandbox["agent"]["name"] = json!(format!("agent-{n}")); if n != 0 { sandbox["agent"]["tools"] = json!({"allow":["read"]}); } - sandbox + (format!("sandbox-{n}"), sandbox) }) .collect(), ); @@ -54,7 +53,7 @@ fn separate_sandboxes_preserve_each_agents_restrictions_in_launch_and_yaml() { } } let mut v = input(1); - v["spec"]["sandboxes"][0]["agent"]["tools"] = json!({"allow":["read"]}); + v["spec"]["sandboxes"]["sandbox-0"]["agent"]["tools"] = json!({"allow":["read"]}); assert!(parse(&v).is_ok()); assert!(schema.is_valid(&v)); } @@ -71,15 +70,12 @@ fn invalid_sandboxes_and_permissions_fail_before_planning() { json!(null), ] { let mut v = input(3); - v["spec"]["sandboxes"][1]["agent"]["tools"] = tools; + v["spec"]["sandboxes"]["sandbox-1"]["agent"]["tools"] = tools; assert!(parse(&v).is_err()); assert!(!schema.is_valid(&v)); } let mut v = input(3); - v["spec"]["sandboxes"][1]["name"] = json!("sandbox-0"); - assert!(parse(&v).is_err()); - let mut v = input(3); - v["spec"]["sandboxes"][1]["agent"]["harness"]["kind"] = json!("hermes"); + v["spec"]["sandboxes"]["sandbox-1"]["agent"]["harness"]["kind"] = json!("hermes"); assert!(parse(&v).is_err()); assert!(!schema.is_valid(&v)); } @@ -87,16 +83,16 @@ fn invalid_sandboxes_and_permissions_fail_before_planning() { #[test] fn disclosure_belongs_to_opaque_native_settings() { let mut value = input(2); - for (i, mode) in ["progressive", "direct"].iter().enumerate() { - value["spec"]["sandboxes"][i]["harness"]["settings"] = json!({"disclosure":mode}); + let modes = [("sandbox-0", "progressive"), ("sandbox-1", "direct")]; + for (sandbox, mode) in modes { + value["spec"]["sandboxes"][sandbox]["harness"]["settings"] = json!({"disclosure":mode}); } let doc = parse(&value).unwrap(); - for (i, mode) in ["progressive", "direct"].iter().enumerate() { - let config = - nemoclaw_sdk::fabric_config::for_sandbox(&doc, &doc.spec.sandboxes[i]).unwrap(); - assert_eq!(config["harness"]["settings"]["disclosure"], *mode); + for (sandbox, mode) in modes { + let config = nemoclaw_sdk::fabric_config::for_sandbox(&doc, sandbox).unwrap(); + assert_eq!(config["harness"]["settings"]["disclosure"], mode); } - value["spec"]["sandboxes"][0]["agent"]["tools"] = json!({"disclosure":"direct"}); + value["spec"]["sandboxes"]["sandbox-0"]["agent"]["tools"] = json!({"disclosure":"direct"}); assert!(parse(&value).is_err()); } @@ -105,8 +101,8 @@ fn tool_choices_are_preserved_independently_of_harness_identity() { let schema = jsonschema::validator_for(&input_schema()).unwrap(); for harness in ["deepagents", "pi"] { let mut value = input(1); - value["spec"]["sandboxes"][0]["harness"]["kind"] = json!(harness); - value["spec"]["sandboxes"][0]["agent"]["tools"] = json!({"allow":["read"]}); + value["spec"]["sandboxes"]["sandbox-0"]["harness"]["kind"] = json!(harness); + value["spec"]["sandboxes"]["sandbox-0"]["agent"]["tools"] = json!({"allow":["read"]}); let document = parse(&value).expect("native read tool policy"); assert!(schema.is_valid(&value)); let generations = ["workspace", "provider", "sandbox"] @@ -123,7 +119,8 @@ fn tool_choices_are_preserved_independently_of_harness_identity() { .unwrap(); assert_eq!(settings["tools"], json!({"enabled":["read"]})); for disclosure in ["direct", "progressive"] { - value["spec"]["sandboxes"][0]["agent"]["tools"] = json!({"disclosure":disclosure}); + value["spec"]["sandboxes"]["sandbox-0"]["agent"]["tools"] = + json!({"disclosure":disclosure}); assert!(parse(&value).is_err()); // Native disclosure belongs to harness.settings. assert!(!schema.is_valid(&value)); @@ -132,12 +129,16 @@ fn tool_choices_are_preserved_independently_of_harness_identity() { } #[test] -fn deep_agents_use_separate_sandboxes_with_stable_names_and_independent_models() { +fn deep_agents_use_separate_sandboxes_with_their_own_agent_names_and_models() { let mut value = input(2); - for sandbox in value["spec"]["sandboxes"].as_array_mut().unwrap() { + for sandbox in value["spec"]["sandboxes"] + .as_object_mut() + .unwrap() + .values_mut() + { sandbox["harness"]["kind"] = json!("deepagents"); } - value["spec"]["sandboxes"][1]["agent"]["inference"]["routes"][0]["overrides"]["model"] = + value["spec"]["sandboxes"]["sandbox-1"]["agent"]["inference"]["routes"][0]["overrides"]["model"] = json!("other-model"); let doc = parse(&value).expect("one native Deep Agents instance per sandbox"); assert!( @@ -157,9 +158,4 @@ fn deep_agents_use_separate_sandboxes_with_stable_names_and_independent_models() assert_eq!(configuration["metadata"]["name"], "agent-1"); let settings: Value = serde_json::from_str(&sandbox.values["config_json"]).unwrap(); assert_eq!(settings["models"]["default"]["model"], "other-model"); - value["spec"]["sandboxes"].as_array_mut().unwrap().reverse(); - assert_eq!( - targets(&parse(&value).unwrap(), &generations).unwrap(), - rows - ); } diff --git a/crates/nemoclaw-sdk/tests/compile.rs b/crates/nemoclaw-sdk/tests/compile.rs index 82d3df74e2b..d8dfb58c6d2 100644 --- a/crates/nemoclaw-sdk/tests/compile.rs +++ b/crates/nemoclaw-sdk/tests/compile.rs @@ -157,15 +157,18 @@ fn compiled_resources_preserve_ownership_connections_and_dependency_order() { env: "GATEWAY_KEY".into(), }, }); - let provider = &mut document.spec.inference_providers[0]; - provider.name = "remote".into(); + let mut provider = document.spec.inference_providers.remove("local").unwrap(); provider.endpoint = "https://models.example.test/v1".into(); provider.credential = Some(SecretRef { env: "MODEL_TOKEN".into(), }); - let sandbox = &mut document.spec.sandboxes[0]; - sandbox.name = "worker".into(); + document + .spec + .inference_providers + .insert("remote".into(), provider); + let mut sandbox = document.spec.sandboxes.remove("assistant").unwrap(); sandbox.agent.inference.as_mut().unwrap().routes[0].provider_ref = Some("remote".into()); + document.spec.sandboxes.insert("worker".into(), sandbox); let generations = ownership_generations(); let graph = compile(&document, &generations, "0.1.0").unwrap(); // Only the gateway providers take the connection. @@ -267,7 +270,10 @@ fn managed_plans_query_selected_engine_and_image_without_probe_resources() { "read existing capabilities during plan" ); let image = &graph["data"]["fabric_capabilities"]["sandbox_0"]; - assert_eq!(image["image"], document.spec.sandboxes[0].image.ref_); + assert_eq!( + image["image"], + document.spec.sandboxes["assistant"].image.ref_ + ); assert!( image.get("depends_on").is_none(), "metadata inspection must not depend on image acquisition" @@ -282,11 +288,7 @@ fn managed_plans_query_selected_engine_and_image_without_probe_resources() { serde_json::from_str(image["config_json"].as_str().unwrap()).unwrap(); assert_eq!( configuration["harness"]["adapter_id"], - document - .sandbox_harness(&document.spec.sandboxes[0]) - .unwrap() - .kind - .as_str() + document.sandbox_harness("assistant").unwrap().kind.as_str() ); assert_eq!( configuration["models"]["default"]["api"], @@ -300,10 +302,11 @@ fn managed_plans_query_selected_engine_and_image_without_probe_resources() { fn arbitrary_fabric_harness_identifier_survives_runtime_compilation() { let mut value: serde_json::Value = serde_saphyr::from_str(include_str!("fixtures/config/local.yaml")).unwrap(); - value["spec"]["sandboxes"][0]["harness"]["kind"] = "org.fixture.custom-adapter".into(); - value["spec"]["sandboxes"][0]["harness"]["settings"] = + value["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = + "org.fixture.custom-adapter".into(); + value["spec"]["sandboxes"]["assistant"]["harness"]["settings"] = serde_json::json!({"custom_option":"fixture-value"}); - value["spec"]["inferenceProviders"][0]["api"] = "openai-responses".into(); + value["spec"]["inferenceProviders"]["local"]["api"] = "openai-responses".into(); let document = Document::parse(value.to_string().as_bytes()).unwrap(); let targets = nemoclaw_sdk::compile::targets(&document, &ownership_generations()).unwrap(); let sandbox = targets @@ -345,10 +348,9 @@ fn adding_an_image_keeps_existing_registration_and_separates_executable_scopes() .find(|target| target.kind == "provider") .unwrap(); let mut changed = document.clone(); - let mut second = changed.spec.sandboxes[0].clone(); - second.name = "second".into(); + let mut second = changed.spec.sandboxes["assistant"].clone(); second.image.ref_ = format!("fixture/other@sha256:{}", "b".repeat(64)); - changed.spec.sandboxes.push(second); + changed.spec.sandboxes.insert("second".into(), second); let after = targets(&changed, &generations).unwrap(); assert!(after.contains(original)); assert_eq!( @@ -363,7 +365,7 @@ fn adding_an_image_keeps_existing_registration_and_separates_executable_scopes() 1, "authored provider selection is independent of registration count" ); - assert_eq!(changed.inference_provider_mut().unwrap().name, "local"); + assert_eq!(changed.inference_provider().unwrap().name, "local"); let graph = compile(&changed, &generations, "0.1.0").unwrap(); for name in ["assistant", "second"] { assert!( diff --git a/crates/nemoclaw-sdk/tests/config.rs b/crates/nemoclaw-sdk/tests/config.rs index 99f411bcfd0..f191e9c9733 100644 --- a/crates/nemoclaw-sdk/tests/config.rs +++ b/crates/nemoclaw-sdk/tests/config.rs @@ -90,7 +90,13 @@ fn endpoint_policy_rejects_credentials_metadata_and_remote_plaintext() { fn managed_defaults_and_safety_bounds_match_the_qualified_recipe() { let mut original = Document::parse(include_str!("fixtures/config/spark.yaml").as_bytes()).unwrap(); - original.spec.sandboxes[0].image.ref_ = nemoclaw_sdk::config::DEFAULT_AGENT_IMAGE.into(); + original + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .image + .ref_ = nemoclaw_sdk::config::DEFAULT_AGENT_IMAGE.into(); let mut defaulted = original.clone(); let network_cidr = original .spec @@ -109,8 +115,21 @@ fn managed_defaults_and_safety_bounds_match_the_qualified_recipe() { }; service.serving = Default::default(); service.memory = Default::default(); - defaulted.spec.sandboxes[0].image.ref_.clear(); - defaulted.spec.sandboxes[0].network.policy = Default::default(); + defaulted + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .image + .ref_ + .clear(); + defaulted + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .network + .policy = Default::default(); defaulted.defaults(); assert_eq!(defaulted, original); for timeout in [0, 59, 3601] { @@ -123,7 +142,12 @@ fn managed_defaults_and_safety_bounds_match_the_qualified_recipe() { assert!(changed.validate().is_err()); } let mut changed = original.clone(); - changed.spec.inference_providers[0].endpoint = "http://127.0.0.1:18888/v1".into(); + changed + .spec + .inference_providers + .get_mut("qwen") + .unwrap() + .endpoint = "http://127.0.0.1:18888/v1".into(); assert!(changed.validate().is_err()); let mut changed = original; let ServiceDefinition::Vllm(service) = changed.spec.services.get_mut("qwen").unwrap() else { @@ -149,24 +173,41 @@ fn fabric_protocol_and_managed_ollama_constraints_survive_the_port() { "pi", ] { let mut document = original.clone(); - document.spec.sandboxes[0].harness.as_mut().unwrap().kind = harness.parse().unwrap(); - document.spec.inference_providers[0].provider = if harness == "claude" { + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .harness + .as_mut() + .unwrap() + .kind = harness.parse().unwrap(); + document + .spec + .inference_providers + .get_mut("local") + .unwrap() + .provider = if harness == "claude" { nemoclaw_sdk::config::InferenceProviderKind::Anthropic } else { nemoclaw_sdk::config::InferenceProviderKind::Openai }; assert!(document.validate().is_ok()); assert_eq!( - document - .sandbox_harness(&document.spec.sandboxes[0]) - .unwrap() - .runtime(), + document.sandbox_harness("assistant").unwrap().runtime(), "fabric" ); } let mut wrong = original; - wrong.spec.sandboxes[0].harness.as_mut().unwrap().kind = - "nvidia.fabric.claude".parse().unwrap(); + wrong + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .harness + .as_mut() + .unwrap() + .kind = "nvidia.fabric.claude".parse().unwrap(); assert!(wrong.validate().is_ok()); let base = include_str!("fixtures/config/managed-ollama.yaml"); for (from, to) in [ @@ -193,24 +234,35 @@ fn openclaw_uses_only_fabric_with_external_or_managed_dependencies() { include_str!("fixtures/config/managed-ollama.yaml"), ] { let mut document = Document::parse(input.as_bytes()).unwrap(); - document.spec.sandboxes[0].harness.as_mut().unwrap().kind = - "nvidia.fabric.openclaw".parse().unwrap(); - document.spec.sandboxes[0].image.ref_.clear(); + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .harness + .as_mut() + .unwrap() + .kind = "nvidia.fabric.openclaw".parse().unwrap(); + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .image + .ref_ + .clear(); document.defaults(); document.validate().unwrap(); assert_eq!( - document.spec.sandboxes[0].image.ref_, + document.spec.sandboxes["assistant"].image.ref_, nemoclaw_sdk::config::DEFAULT_AGENT_IMAGE ); assert_eq!( - document - .sandbox_harness(&document.spec.sandboxes[0]) - .unwrap() - .runtime(), + document.sandbox_harness("assistant").unwrap().runtime(), "fabric" ); let mut input = serde_json::to_value(&document).unwrap(); - input["spec"]["sandboxes"][0]["harness"]["kind"] = serde_json::json!(""); + input["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = serde_json::json!(""); assert!( Document::parse(input.to_string().as_bytes()).is_err(), "a harness must be declared" @@ -223,10 +275,7 @@ fn sandbox_harness_is_the_only_implementation_selector() { let input = include_str!("fixtures/config/local.yaml"); let document = Document::parse(input.as_bytes()).unwrap(); assert_eq!( - document - .sandbox_harness(&document.spec.sandboxes[0]) - .unwrap() - .runtime(), + document.sandbox_harness("assistant").unwrap().runtime(), "fabric" ); assert!(!document.yaml().unwrap().contains("type:")); @@ -245,7 +294,11 @@ fn pi_preserves_yaml_model_ids_and_explicit_custom_metadata() { let custom = Document::parse(input.as_bytes()).unwrap(); for name in ["qwen3:4b", "my-custom-model", "gpt-4o-mini"] { let mut document = custom.clone(); - document.spec.sandboxes[0] + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() .agent .inference .as_mut() @@ -258,7 +311,11 @@ fn pi_preserves_yaml_model_ids_and_explicit_custom_metadata() { assert_eq!(Document::parse(yaml.as_bytes()).unwrap(), document); } let mut catalog = custom; - let route = &mut catalog.spec.sandboxes[0] + let route = &mut catalog + .spec + .sandboxes + .get_mut("assistant") + .unwrap() .agent .inference .as_mut() @@ -277,12 +334,12 @@ fn pi_model_is_an_optional_opaque_object() { ) .unwrap(); let opaque = serde_json::json!({"contextWindow": "Pi validates this", "futureOption": {"nested": [null, 7, true]}, "thinkingLevelMap": {"off": null}}); - tree["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"]["settings"]["model_metadata"] = - opaque.clone(); + tree["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["overrides"]["settings"] + ["model_metadata"] = opaque.clone(); let parsed = Document::parse(tree.to_string().as_bytes()).unwrap(); assert_eq!( - serde_json::to_value(&parsed).unwrap()["spec"]["sandboxes"][0]["agent"]["inference"]["routes"] - [0]["overrides"]["settings"]["model_metadata"], + serde_json::to_value(&parsed).unwrap()["spec"]["sandboxes"]["assistant"]["agent"]["inference"] + ["routes"][0]["overrides"]["settings"]["model_metadata"], opaque ); assert_eq!( @@ -295,7 +352,7 @@ fn pi_model_is_an_optional_opaque_object() { serde_json::json!(7), Value::Null, ] { - tree["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"]["settings"] = + tree["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["overrides"]["settings"] = invalid; assert!(Document::parse(tree.to_string().as_bytes()).is_err()); } @@ -310,7 +367,11 @@ fn pi_model_updates_leave_the_sandbox_connection_unchanged() { .map(|name| (name.into(), "a".repeat(32))) .into(); let before = targets(&document, &generations).unwrap(); - document.spec.sandboxes[0] + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() .agent .inference .as_mut() @@ -353,7 +414,15 @@ fn harness_selection_does_not_determine_service_ownership() { include_str!("fixtures/config/managed-ollama.yaml"), ] { let mut document = Document::parse(fixture.as_bytes()).unwrap(); - document.spec.sandboxes[0].harness.as_mut().unwrap().kind = harness.parse().unwrap(); + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .harness + .as_mut() + .unwrap() + .kind = harness.parse().unwrap(); assert!( document.validate().is_ok(), "{harness}: {:?}", @@ -363,13 +432,25 @@ fn harness_selection_does_not_determine_service_ownership() { } let mut claude = Document::parse(include_str!("../../../examples/spark/vllm.yaml").as_bytes()).unwrap(); - claude.spec.sandboxes[0].harness.as_mut().unwrap().kind = - "nvidia.fabric.claude".parse().unwrap(); + claude + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .harness + .as_mut() + .unwrap() + .kind = "nvidia.fabric.claude".parse().unwrap(); assert!( claude.validate().is_ok(), "harness identity does not change the provider's protocol default" ); - claude.spec.inference_providers[0].provider = InferenceProviderKind::Anthropic; + claude + .spec + .inference_providers + .get_mut("qwen") + .unwrap() + .provider = InferenceProviderKind::Anthropic; assert!( claude.validate().is_err(), "managed vLLM exposes the OpenAI API regardless of harness ownership" @@ -400,7 +481,11 @@ fn fabric_harness_identifiers_are_extensible_and_validated() { let baseline = include_str!("fixtures/config/local.yaml"); let source = baseline.replace("kind: nvidia.fabric.openclaw", "kind: fixture-new-agent"); let mut document = Document::parse(source.as_bytes()).unwrap(); - document.spec.sandboxes[0] + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() .harness .as_mut() .unwrap() @@ -426,17 +511,26 @@ fn fabric_harness_identifiers_are_extensible_and_validated() { nemoclaw_sdk::config::InferenceApi::OpenaiResponses, nemoclaw_sdk::config::InferenceApi::AnthropicMessages, ] { - document.spec.inference_providers[0].api = Some(api); - document.spec.inference_providers[0].provider = - if api == nemoclaw_sdk::config::InferenceApi::AnthropicMessages { - InferenceProviderKind::Anthropic - } else { - InferenceProviderKind::Openai - }; + document + .spec + .inference_providers + .get_mut("local") + .unwrap() + .api = Some(api); + document + .spec + .inference_providers + .get_mut("local") + .unwrap() + .provider = if api == nemoclaw_sdk::config::InferenceApi::AnthropicMessages { + InferenceProviderKind::Anthropic + } else { + InferenceProviderKind::Openai + }; document.validate().unwrap(); } assert_eq!( - document.spec.sandboxes[0] + document.spec.sandboxes["assistant"] .harness .as_ref() .unwrap() @@ -468,8 +562,8 @@ fn fabric_harness_identifiers_are_extensible_and_validated() { fn default_image_is_deployment_policy_independent_of_adapter_identity() { let mut value: Value = serde_saphyr::from_str(include_str!("fixtures/config/local.yaml")).unwrap(); - value["spec"]["sandboxes"][0]["harness"]["kind"] = "fixture-new-agent".into(); - value["spec"]["sandboxes"][0] + value["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = "fixture-new-agent".into(); + value["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove("image"); @@ -477,7 +571,7 @@ fn default_image_is_deployment_policy_independent_of_adapter_identity() { Document::parse(serde_json::to_vec(&value).unwrap().as_slice()) .unwrap() .spec - .sandboxes[0] + .sandboxes["assistant"] .image .ref_, nemoclaw_sdk::config::DEFAULT_AGENT_IMAGE @@ -504,7 +598,7 @@ fn arbitrary_adapter_features_are_preserved_for_fabric_validation() { fn native_identifiers_and_model_metadata_do_not_require_sdk_registration() { let mut tree: Value = serde_saphyr::from_str(include_str!("fixtures/config/local.yaml")).unwrap(); - let sandbox = &mut tree["spec"]["sandboxes"][0]; + let sandbox = &mut tree["spec"]["sandboxes"]["assistant"]; sandbox["harness"]["kind"] = "fixture-featureful-agent".into(); sandbox["agent"]["tools"] = serde_json::json!({"allow":["lookup","custom_search"]}); let inference = &mut sandbox["agent"]["inference"]; @@ -520,7 +614,7 @@ fn native_identifiers_and_model_metadata_do_not_require_sdk_registration() { Document::parse(parsed.yaml().unwrap().as_bytes()).unwrap(), parsed ); - tree["spec"]["sandboxes"][0]["harness"]["settings"] = + tree["spec"]["sandboxes"]["assistant"]["harness"]["settings"] = serde_json::json!({"disclosure":"adapter-defined-mode"}); Document::parse(serde_json::to_vec(&tree).unwrap().as_slice()).unwrap(); for invalid in [ @@ -528,7 +622,7 @@ fn native_identifiers_and_model_metadata_do_not_require_sdk_registration() { serde_json::json!({"allow":["read","read"]}), serde_json::json!({"disclosure":""}), ] { - tree["spec"]["sandboxes"][0]["agent"]["tools"] = invalid; + tree["spec"]["sandboxes"]["assistant"]["agent"]["tools"] = invalid; assert!(Document::parse(serde_json::to_vec(&tree).unwrap().as_slice()).is_err()); } } diff --git a/crates/nemoclaw-sdk/tests/config_choices.rs b/crates/nemoclaw-sdk/tests/config_choices.rs index dedab329ace..f95a4619970 100644 --- a/crates/nemoclaw-sdk/tests/config_choices.rs +++ b/crates/nemoclaw-sdk/tests/config_choices.rs @@ -11,7 +11,6 @@ use nemoclaw_sdk::{ fn provider() -> InferenceProvider { InferenceProvider { - name: "test".into(), provider: InferenceProviderKind::Openai, api: None, endpoint: String::new(), diff --git a/crates/nemoclaw-sdk/tests/config_diagnostics.rs b/crates/nemoclaw-sdk/tests/config_diagnostics.rs index dd5fe0a2965..759ee2c50e8 100644 --- a/crates/nemoclaw-sdk/tests/config_diagnostics.rs +++ b/crates/nemoclaw-sdk/tests/config_diagnostics.rs @@ -36,24 +36,78 @@ fn schema_failure_names_the_service_field_constraint_and_source_position() { } #[test] -fn schema_failure_identifies_array_indices_and_expected_type_without_values() { +fn schema_failure_names_sandboxes_and_providers_by_key_without_values() { let mut input = source("fabric-openclaw.yaml"); - let mut second = input["spec"]["sandboxes"][0].clone(); - second["name"] = json!("second"); + let mut second = input["spec"]["sandboxes"]["assistant"].clone(); second["agent"]["inference"]["routes"] = json!("PRIVATE_SENTINEL"); - input["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(second); + input["spec"]["sandboxes"]["second"] = second; let error = Document::parse(input.to_string().as_bytes()) .unwrap_err() .to_string(); assert!( - error.contains("spec.sandboxes[1].agent.inference.routes"), + error.contains("spec.sandboxes.second.agent.inference.routes"), "{error}" ); assert!(error.contains("must be array"), "{error}"); assert!(!error.contains("PRIVATE_SENTINEL")); + + for (pointer, path) in [ + ( + "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model", + "spec.sandboxes.assistant.agent.inference.routes[0].overrides.model", + ), + ( + "/spec/sandboxes/assistant/inferenceProviders/own/endpoint", + "spec.sandboxes.assistant.inferenceProviders.own.endpoint", + ), + ( + "/spec/inferenceProviders/local/endpoint", + "spec.inferenceProviders.local.endpoint", + ), + ] { + let mut value = source("fabric-openclaw.yaml"); + value["spec"]["sandboxes"]["assistant"]["inferenceProviders"] = + json!({"own": {"provider": "openai", "endpoint": "http://172.20.0.1:11447/v1"}}); + *value.pointer_mut(pointer).unwrap() = json!(["PRIVATE_SENTINEL"]); + let error = Document::parse(value.to_string().as_bytes()) + .unwrap_err() + .to_string(); + assert!( + error.contains(&format!("schema at {path} (line")) && error.contains("must be string"), + "{error}" + ); + assert!(!error.contains("PRIVATE_SENTINEL"), "{error}"); + } +} + +#[test] +fn an_invalid_name_key_reports_its_own_position_without_echoing_it() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples"); + for (file, key, collection) in [ + ("multiple-sandboxes.yaml", " review:", "spec.sandboxes"), + ( + "multiple-providers.yaml", + " hosted:", + "spec.inferenceProviders", + ), + ] { + let text = std::fs::read_to_string(root.join(file)).unwrap().replacen( + key, + " PRIVATE SENTINEL:", + 1, + ); + let line = text + .lines() + .position(|line| line == " PRIVATE SENTINEL:") + .unwrap() + + 1; + let error = Document::parse(text.as_bytes()).unwrap_err().to_string(); + assert!( + error.contains(&format!("at {collection} (line {line}, column 5): ")), + "{file}: {error}" + ); + assert!(!error.contains("SENTINEL"), "{error}"); + } } #[test] @@ -119,7 +173,7 @@ fn explicit_core_tags_are_rejected_without_rejecting_tag_text_inside_strings() { assert!(!error.contains("ZXhwbG9yZS10MTA=")); } let mut literal = input; - literal["spec"]["sandboxes"][0]["harness"]["settings"] = + literal["spec"]["sandboxes"]["assistant"]["harness"]["settings"] = json!({"opaque": "!!binary literal text"}); Document::parse(literal.to_string().as_bytes()).unwrap(); } @@ -127,8 +181,9 @@ fn explicit_core_tags_are_rejected_without_rejecting_tag_text_inside_strings() { #[test] fn flow_document_columns_count_characters_and_do_not_include_values() { let mut input = source("fabric-openclaw.yaml"); - input["spec"]["inferenceProviders"][0]["endpoint"] = json!("http://Ć©.example.com/v1"); - input["spec"]["sandboxes"][0]["agent"]["inference"]["routes"] = json!("PRIVATE_SENTINEL"); + input["spec"]["inferenceProviders"]["local"]["endpoint"] = json!("http://Ć©.example.com/v1"); + input["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"] = + json!("PRIVATE_SENTINEL"); let text = input.to_string(); let offset = text.find("\"routes\":\"PRIVATE_SENTINEL\"").unwrap() + "\"routes\":".len(); let column = text[..offset].chars().count() + 1; @@ -158,13 +213,13 @@ fn collection_tags_are_rejected_and_quoted_or_block_tag_text_is_preserved() { ); } let mut literal = input; - literal["spec"]["sandboxes"][0]["harness"]["settings"] = + literal["spec"]["sandboxes"]["assistant"]["harness"]["settings"] = json!({"opaque": "!!binary literal text\n!custom still text"}); let text = serde_saphyr::to_string(&literal).unwrap(); let document = Document::parse(text.as_bytes()).unwrap(); assert_eq!( - serde_json::to_value(document).unwrap()["spec"]["sandboxes"][0]["harness"]["settings"], - literal["spec"]["sandboxes"][0]["harness"]["settings"] + serde_json::to_value(document).unwrap()["spec"]["sandboxes"]["assistant"]["harness"]["settings"], + literal["spec"]["sandboxes"]["assistant"]["harness"]["settings"] ); } diff --git a/crates/nemoclaw-sdk/tests/config_input.rs b/crates/nemoclaw-sdk/tests/config_input.rs index 58cbbfc1531..726d0efa7b4 100644 --- a/crates/nemoclaw-sdk/tests/config_input.rs +++ b/crates/nemoclaw-sdk/tests/config_input.rs @@ -15,34 +15,40 @@ fn parse(value: &Value) -> Result { #[test] fn omitted_image_uses_the_pin_for_the_selected_harness() { let mut openclaw = input("fabric-openclaw.yaml"); - openclaw["spec"]["sandboxes"][0] + openclaw["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove("image"); assert_eq!( - parse(&openclaw).unwrap().spec.sandboxes[0].image.ref_, + parse(&openclaw).unwrap().spec.sandboxes["assistant"] + .image + .ref_, DEFAULT_AGENT_IMAGE ); let mut hermes = input("managed-hermes.yaml"); - hermes["spec"]["sandboxes"][0] + hermes["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove("image"); assert_eq!( - parse(&hermes).unwrap().spec.sandboxes[0].image.ref_, + parse(&hermes).unwrap().spec.sandboxes["assistant"] + .image + .ref_, DEFAULT_AGENT_IMAGE ); - let harness = hermes["spec"]["sandboxes"][0] + let harness = hermes["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove("harness") .unwrap(); hermes["spec"]["harnesses"]["assistant"] = harness; - hermes["spec"]["sandboxes"][0]["harnessRef"] = json!("assistant"); + hermes["spec"]["sandboxes"]["assistant"]["harnessRef"] = json!("assistant"); assert_eq!( - parse(&hermes).unwrap().spec.sandboxes[0].image.ref_, + parse(&hermes).unwrap().spec.sandboxes["assistant"] + .image + .ref_, DEFAULT_AGENT_IMAGE ); } @@ -70,7 +76,7 @@ fn omitted_empty_and_zero_values_produce_the_same_defaults() { .remove(key); } for key in ["image", "runtime", "network"] { - omitted["spec"]["sandboxes"][0] + omitted["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove(key); @@ -86,8 +92,8 @@ fn omitted_empty_and_zero_values_produce_the_same_defaults() { for key in ["endpoint", "engine", "networkCidr"] { explicit["spec"]["gateway"]["target"]["docker"][key] = json!(""); } - explicit["spec"]["sandboxes"][0]["image"] = json!({"ref": ""}); - explicit["spec"]["sandboxes"][0]["network"] = json!({"tier": ""}); + explicit["spec"]["sandboxes"]["assistant"]["image"] = json!({"ref": ""}); + explicit["spec"]["sandboxes"]["assistant"]["network"] = json!({"tier": ""}); explicit["spec"]["services"]["qwen"]["serving"] = json!({ "port": 0, "contextTokens": 0, "maxSequences": 0, "batchTokens": 0, "startupTimeoutSeconds": 0, "speculativeTokens": 0, @@ -102,7 +108,7 @@ fn omitted_empty_and_zero_values_produce_the_same_defaults() { assert_eq!(parse(&explicit).unwrap().digest(), expected.digest()); for path in [ "/spec/gateway/target/docker/endpoint", - "/spec/sandboxes/0/image", + "/spec/sandboxes/assistant/image", "/spec/services/qwen/serving/port", ] { let mut invalid = explicit.clone(); @@ -148,9 +154,8 @@ fn required_fields_and_mutually_exclusive_provider_forms_are_rejected() { "/metadata/uid", "/spec/gateway/management", "/spec/gateway/endpoint", - "/spec/inferenceProviders/0/name", - "/spec/inferenceProviders/0/provider", - "/spec/sandboxes/0/harness", + "/spec/inferenceProviders/local/provider", + "/spec/sandboxes/assistant/harness", ] { let mut invalid = baseline.clone(); let (parent, key) = path.rsplit_once('/').unwrap(); @@ -164,7 +169,7 @@ fn required_fields_and_mutually_exclusive_provider_forms_are_rejected() { } for field in ["endpoint", "credential", "ollama"] { let mut invalid = input("spark/spark-inline.yaml"); - invalid["spec"]["inferenceProviders"][0][field] = match field { + invalid["spec"]["inferenceProviders"]["qwen"][field] = match field { "endpoint" => json!("https://inference.example.com/v1"), "credential" => json!({"env": "MODEL_TOKEN"}), _ => json!({}), @@ -176,7 +181,7 @@ fn required_fields_and_mutually_exclusive_provider_forms_are_rejected() { #[test] fn only_pi_metadata_permits_nested_null_values() { let mut value = input("fabric-pi.yaml"); - let pointer = "/spec/sandboxes/0/agent/inference/routes/0/overrides/settings"; + let pointer = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/settings"; *value.pointer_mut(pointer).unwrap() = json!({"future": [null, {"nested": null}]}); parse(&value).unwrap(); *value.pointer_mut(pointer).unwrap() = Value::Null; @@ -199,3 +204,27 @@ fn service_image_error_identifies_the_required_digest_pin() { } parse(&original).unwrap(); } + +#[test] +fn export_lists_sandboxes_and_providers_in_name_order() { + // The example declares its sandboxes out of name order. + let text = include_str!("../../../examples/multiple-sandboxes.yaml"); + let document = Document::parse(text.as_bytes()).unwrap(); + let mut value = serde_json::to_value(&document).unwrap(); + value["spec"]["inferenceProviders"]["hosted"] = json!({ + "provider": "openai", + "endpoint": "https://hosted.example/v1" + }); + let document = parse(&value).unwrap(); + let exported = document.yaml().unwrap(); + let line = |key: &str| { + exported + .lines() + .position(|line| line.trim() == format!("{key}:")) + .unwrap_or_else(|| panic!("{key}: {exported}")) + }; + let sandboxes = ["alice", "bob", "coding", "research", "review"].map(line); + assert!(sandboxes.is_sorted(), "{exported}"); + assert!(line("hosted") < line("local"), "{exported}"); + assert_eq!(Document::parse(exported.as_bytes()).unwrap(), document); +} diff --git a/crates/nemoclaw-sdk/tests/config_kinds.rs b/crates/nemoclaw-sdk/tests/config_kinds.rs index 2b4129549bb..9d39c7ae660 100644 --- a/crates/nemoclaw-sdk/tests/config_kinds.rs +++ b/crates/nemoclaw-sdk/tests/config_kinds.rs @@ -114,7 +114,7 @@ fn the_target_is_chosen_once_on_the_gateway() { } // A sandbox does not select its own runtime. let mut input = base; - input["spec"]["sandboxes"][0]["runtime"] = json!({"provider": "docker"}); + input["spec"]["sandboxes"]["assistant"]["runtime"] = json!({"provider": "docker"}); assert!(!validator.is_valid(&input)); assert!(Document::parse(input.to_string().as_bytes()).is_err()); } @@ -200,7 +200,8 @@ fn opaque_fabric_identifiers_preserve_owner_valid_long_and_control_values() { assert_eq!(catalog.adapters[0].adapter_id(), id); let mut input: serde_json::Value = serde_saphyr::from_str(include_str!("fixtures/config/local.yaml")).unwrap(); - input["spec"]["sandboxes"][0]["harness"]["kind"] = json!(catalog.adapters[0].adapter_id()); + input["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = + json!(catalog.adapters[0].adapter_id()); assert!( validator.is_valid(&input), "schema rejected Fabric identifier" @@ -209,11 +210,7 @@ fn opaque_fabric_identifiers_preserve_owner_valid_long_and_control_values() { let encoded = document.yaml().unwrap(); let restored = Document::parse(encoded.as_bytes()).unwrap(); assert_eq!( - restored - .sandbox_harness(&restored.spec.sandboxes[0]) - .unwrap() - .kind - .as_str(), + restored.sandbox_harness("assistant").unwrap().kind.as_str(), id ); } diff --git a/crates/nemoclaw-sdk/tests/config_kubernetes.rs b/crates/nemoclaw-sdk/tests/config_kubernetes.rs index 67db19168d4..c659ac6ed85 100644 --- a/crates/nemoclaw-sdk/tests/config_kubernetes.rs +++ b/crates/nemoclaw-sdk/tests/config_kubernetes.rs @@ -8,7 +8,8 @@ fn external_document() -> Value { Document::parse(include_bytes!("fixtures/config/local.yaml").as_slice()).unwrap(); let mut input = serde_json::to_value(document).unwrap(); input["spec"]["gateway"]["target"] = json!({"kubernetes": {}}); - input["spec"]["sandboxes"][0]["image"]["metadata"] = json!({"env":"TEST_IMAGE_METADATA"}); + input["spec"]["sandboxes"]["assistant"]["image"]["metadata"] = + json!({"env":"TEST_IMAGE_METADATA"}); input } @@ -163,7 +164,7 @@ fn kubernetes_sandboxes_must_name_their_image_metadata() { // No local engine can be inspected, so each image's metadata bundle is // required up front. let mut input = external_document(); - input["spec"]["sandboxes"][0]["image"] + input["spec"]["sandboxes"]["assistant"]["image"] .as_object_mut() .unwrap() .remove("metadata"); @@ -332,12 +333,13 @@ fn authored_credentials_cannot_shadow_managed_kubernetes_runtime_controls() { ] { for path in [ "/spec/gateway/target/kubernetes/kubeconfig", - "/spec/inferenceProviders/0/credential", + "/spec/inferenceProviders/local/credential", ] { let mut input = managed_document(); - input["spec"]["inferenceProviders"][0]["endpoint"] = + input["spec"]["inferenceProviders"]["local"]["endpoint"] = json!("https://inference.example/v1"); - input["spec"]["inferenceProviders"][0]["credential"] = json!({"env":"HOSTED_API_KEY"}); + input["spec"]["inferenceProviders"]["local"]["credential"] = + json!({"env":"HOSTED_API_KEY"}); *input.pointer_mut(path).unwrap() = json!({"env":name}); assert!(!validator.is_valid(&input)); assert!(Document::parse(input.to_string().as_bytes()).is_err()); @@ -435,12 +437,13 @@ fn managed_kubeconfig_controls_do_not_restrict_other_credential_references() { ] { let mut input = external_document(); input["spec"]["gateway"]["target"] = json!({"docker": {}}); - input["spec"]["sandboxes"][0]["image"] + input["spec"]["sandboxes"]["assistant"]["image"] .as_object_mut() .unwrap() .remove("metadata"); - input["spec"]["inferenceProviders"][0]["endpoint"] = json!("https://inference.example/v1"); - input["spec"]["inferenceProviders"][0]["credential"] = json!({"env": name}); + input["spec"]["inferenceProviders"]["local"]["endpoint"] = + json!("https://inference.example/v1"); + input["spec"]["inferenceProviders"]["local"]["credential"] = json!({"env": name}); Document::parse(input.to_string().as_bytes()).unwrap(); } } @@ -496,7 +499,9 @@ fn kubernetes_requires_an_explicit_nonempty_image_before_defaults() { let validator = jsonschema::validator_for(&schema::input_schema()).unwrap(); for image in [None, Some(json!({})), Some(json!({"ref": ""}))] { let mut input = external_document(); - let sandbox = input["spec"]["sandboxes"][0].as_object_mut().unwrap(); + let sandbox = input["spec"]["sandboxes"]["assistant"] + .as_object_mut() + .unwrap(); match image { Some(image) => { sandbox.insert("image".into(), image); @@ -513,10 +518,10 @@ fn kubernetes_requires_an_explicit_nonempty_image_before_defaults() { #[test] fn directly_constructed_kubernetes_sandboxes_never_default_their_image() { let mut document = Document::parse(external_document().to_string().as_bytes()).unwrap(); - document.spec.sandboxes[0].image = Default::default(); + document.spec.sandboxes.get_mut("assistant").unwrap().image = Default::default(); assert!(document.validate().is_err()); document.defaults(); - assert!(document.spec.sandboxes[0].image.ref_.is_empty()); + assert!(document.spec.sandboxes["assistant"].image.ref_.is_empty()); assert!(document.validate().is_err()); } @@ -527,7 +532,7 @@ fn a_managed_gateway_without_a_cluster_target_rejects_image_metadata() { assert!(!jsonschema::is_valid(&schema::input_schema(), &input)); let error = schema_error(&input); assert!( - error.contains("schema at spec.sandboxes[0].image (line") + error.contains("schema at spec.sandboxes.assistant.image (line") && error.ends_with( "): image.metadata is available only for a spec.gateway.target.kubernetes gateway; Docker and Podman use engine image inspection" ), @@ -621,14 +626,14 @@ fn an_external_kubernetes_target_requires_image_metadata_and_rejects_services() Document::parse(input.to_string().as_bytes()).unwrap(); for field in ["ref", "metadata"] { let mut input = external_document(); - input["spec"]["sandboxes"][0]["image"] + input["spec"]["sandboxes"]["assistant"]["image"] .as_object_mut() .unwrap() .remove(field); assert!(!validator.is_valid(&input), "{field}"); let error = schema_error(&input); assert!( - error.contains("schema at spec.sandboxes[0].image (line") + error.contains("schema at spec.sandboxes.assistant.image (line") && error.ends_with( "): a Kubernetes target requires each sandbox image.ref pinned by digest and image.metadata" ), @@ -682,12 +687,14 @@ fn a_reserved_reference_name_states_whether_the_reference_holds_a_secret_or_a_fi "certificate": {"env": "GATEWAY_CERT"}, "key": {"env": "GATEWAY_KEY"} }); - external["spec"]["inferenceProviders"][0]["endpoint"] = json!("https://inference.example/v1"); - external["spec"]["inferenceProviders"][0]["credential"] = json!({"env": "HOSTED_API_KEY"}); - external["spec"]["sandboxes"][0]["integrations"] = json!({ + external["spec"]["inferenceProviders"]["local"]["endpoint"] = + json!("https://inference.example/v1"); + external["spec"]["inferenceProviders"]["local"]["credential"] = + json!({"env": "HOSTED_API_KEY"}); + external["spec"]["sandboxes"]["assistant"]["integrations"] = json!({ "search": {"kind": "webSearch", "provider": "brave", "credential": {"env": "SEARCH_KEY"}} }); - external["spec"]["sandboxes"][0]["agent"]["integrationRefs"] = json!(["search"]); + external["spec"]["sandboxes"]["assistant"]["agent"]["integrationRefs"] = json!(["search"]); Document::parse(external.to_string().as_bytes()).unwrap(); for (mut input, pointer, path, rule) in [ ( @@ -698,14 +705,14 @@ fn a_reserved_reference_name_states_whether_the_reference_holds_a_secret_or_a_fi ), ( external.clone(), - "/spec/inferenceProviders/0/credential", - "spec.inferenceProviders[0].credential.env", + "/spec/inferenceProviders/local/credential", + "spec.inferenceProviders.local.credential.env", secret, ), ( external.clone(), - "/spec/sandboxes/0/integrations/search/credential", - "spec.sandboxes[0].integrations.search.credential.env", + "/spec/sandboxes/assistant/integrations/search/credential", + "spec.sandboxes.assistant.integrations.search.credential.env", secret, ), ( @@ -728,8 +735,8 @@ fn a_reserved_reference_name_states_whether_the_reference_holds_a_secret_or_a_fi ), ( external, - "/spec/sandboxes/0/image/metadata", - "spec.sandboxes[0].image.metadata.env", + "/spec/sandboxes/assistant/image/metadata", + "spec.sandboxes.assistant.image.metadata.env", file, ), ( diff --git a/crates/nemoclaw-sdk/tests/config_openshift.rs b/crates/nemoclaw-sdk/tests/config_openshift.rs index 2267a9b3b42..c8fca364eb5 100644 --- a/crates/nemoclaw-sdk/tests/config_openshift.rs +++ b/crates/nemoclaw-sdk/tests/config_openshift.rs @@ -22,7 +22,8 @@ fn cluster(distribution: Option<&str>) -> Value { target["distribution"] = json!(distribution); } input["spec"]["gateway"] = json!({"management": "managed", "target": {"kubernetes": target}}); - input["spec"]["sandboxes"][0]["image"]["metadata"] = json!({"env":"TEST_IMAGE_METADATA"}); + input["spec"]["sandboxes"]["assistant"]["image"]["metadata"] = + json!({"env":"TEST_IMAGE_METADATA"}); input } @@ -72,15 +73,15 @@ fn openshift_preserves_authored_profile_and_uses_the_upstream_kubernetes_driver( fn openshift_never_defaults_an_image_or_uses_a_local_managed_gateway() { for managed in [false, true] { let mut value = input(managed); - value["spec"]["sandboxes"][0] + value["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove("image"); assert!(Document::parse(value.to_string().as_bytes()).is_err()); let mut document = Document::parse(input(managed).to_string().as_bytes()).unwrap(); - document.spec.sandboxes[0].image = Default::default(); + document.spec.sandboxes.get_mut("assistant").unwrap().image = Default::default(); document.defaults(); - assert!(document.spec.sandboxes[0].image.ref_.is_empty()); + assert!(document.spec.sandboxes["assistant"].image.ref_.is_empty()); assert!(document.validate().is_err()); } let mut value = input(false); diff --git a/crates/nemoclaw-sdk/tests/config_scenarios.rs b/crates/nemoclaw-sdk/tests/config_scenarios.rs index 314783ba508..b8a81774c27 100644 --- a/crates/nemoclaw-sdk/tests/config_scenarios.rs +++ b/crates/nemoclaw-sdk/tests/config_scenarios.rs @@ -12,15 +12,15 @@ fn anthropic_with_claude_should_work() { let document = Document::parse(desired.yaml().as_bytes()).unwrap(); let desired = normalized(&document); assert_eq!( - desired["spec"]["inferenceProviders"][0]["provider"], + desired["spec"]["inferenceProviders"]["local"]["provider"], "anthropic" ); assert_eq!( - desired["spec"]["inferenceProviders"][0]["endpoint"], + desired["spec"]["inferenceProviders"]["local"]["endpoint"], "https://api.anthropic.com/v1" ); assert_eq!( - desired["spec"]["sandboxes"][0]["harness"]["kind"], + desired["spec"]["sandboxes"]["assistant"]["harness"]["kind"], "nvidia.fabric.claude" ); assert_eq!(document.credential_names(), ["ANTHROPIC_API_KEY"]); @@ -34,11 +34,11 @@ fn anthropic_compatible_endpoint_should_work() { let document = Document::parse(desired.yaml().as_bytes()).unwrap(); let desired = normalized(&document); assert_eq!( - desired["spec"]["inferenceProviders"][0]["provider"], + desired["spec"]["inferenceProviders"]["local"]["provider"], "anthropic" ); assert_eq!( - desired["spec"]["inferenceProviders"][0]["endpoint"], + desired["spec"]["inferenceProviders"]["local"]["endpoint"], "https://anthropic.example.com/v1" ); assert_eq!( @@ -55,13 +55,13 @@ fn openai_compatible_endpoint_with_tuning_should_work() { let document = Document::parse(desired.yaml().as_bytes()).unwrap(); let desired = normalized(&document); let overrides = - &desired["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"]; + &desired["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["overrides"]; assert_eq!( - desired["spec"]["inferenceProviders"][0]["api"], + desired["spec"]["inferenceProviders"]["local"]["api"], "openai-responses" ); assert_eq!( - desired["spec"]["inferenceProviders"][0]["endpoint"], + desired["spec"]["inferenceProviders"]["local"]["endpoint"], "https://inference.example.com/v1" ); assert_eq!(document.credential_names(), ["COMPATIBLE_API_KEY"]); @@ -83,7 +83,7 @@ fn openai_endpoint_should_work() { let document = Document::parse(desired.yaml().as_bytes()).unwrap(); let desired = normalized(&document); assert_eq!( - desired["spec"]["inferenceProviders"][0]["endpoint"], + desired["spec"]["inferenceProviders"]["local"]["endpoint"], "https://api.openai.com/v1" ); assert_eq!(document.credential_names(), ["OPENAI_API_KEY"]); @@ -98,7 +98,7 @@ fn openrouter_endpoint_should_work() { let document = Document::parse(desired.yaml().as_bytes()).unwrap(); let desired = normalized(&document); assert_eq!( - desired["spec"]["inferenceProviders"][0]["endpoint"], + desired["spec"]["inferenceProviders"]["local"]["endpoint"], "https://openrouter.ai/api/v1" ); assert_eq!(document.credential_names(), ["OPENROUTER_API_KEY"]); @@ -110,7 +110,7 @@ fn deep_agents_should_work() { let document = Document::parse(yaml.as_slice()).unwrap(); let desired = normalized(&document); assert_eq!( - desired["spec"]["sandboxes"][0]["harness"]["kind"], + desired["spec"]["sandboxes"]["assistant"]["harness"]["kind"], "nvidia.fabric.langchain.deepagents" ); } @@ -120,12 +120,15 @@ fn multiple_openclaw_sandboxes_with_policy_tools_and_observability_should_work() let yaml = include_bytes!("../../../examples/full-featured-openclaw.yaml"); let document = Document::parse(yaml.as_slice()).unwrap(); let desired = normalized(&document); - let sandboxes = desired["spec"]["sandboxes"].as_array().unwrap(); + let sandboxes = desired["spec"]["sandboxes"].as_object().unwrap(); assert_eq!(sandboxes.len(), 3); - assert_eq!(sandboxes[0]["agent"]["name"], "researcher"); - assert_eq!(sandboxes[1]["agent"]["name"], "writer"); - assert_eq!(sandboxes[2]["agent"]["name"], "reader"); - assert_eq!(sandboxes[2]["agent"]["tools"]["allow"], json!(["read"])); + for name in ["researcher", "writer", "reader"] { + assert_eq!(sandboxes[name]["agent"]["name"], name); + } + assert_eq!( + sandboxes["reader"]["agent"]["tools"]["allow"], + json!(["read"]) + ); assert_eq!( desired["spec"]["harnesses"]["assistant"]["settings"]["native_config"]["tools"]["toolSearch"] ["mode"], @@ -148,11 +151,11 @@ fn pi_with_native_model_metadata_should_work() { let document = Document::parse(yaml.as_slice()).unwrap(); let desired = normalized(&document); assert_eq!( - desired["spec"]["sandboxes"][0]["harness"]["kind"], + desired["spec"]["sandboxes"]["assistant"]["harness"]["kind"], "nvidia.fabric.pi" ); assert_eq!( - desired["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"]["settings"] + desired["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["overrides"]["settings"] ["model_metadata"]["api"], "openai-completions" ); @@ -163,7 +166,7 @@ fn managed_ollama_should_work() { let yaml = include_bytes!("../../../examples/managed-ollama.yaml"); let document = Document::parse(yaml.as_slice()).unwrap(); let desired = normalized(&document); - let service = desired["spec"]["inferenceProviders"][0]["serviceRef"] + let service = desired["spec"]["inferenceProviders"]["local"]["serviceRef"] .as_str() .unwrap(); assert_eq!(desired["spec"]["services"][service]["kind"], "ollama"); @@ -174,7 +177,7 @@ fn managed_vllm_should_work() { let yaml = include_bytes!("../../../examples/nemotron-amd64.yaml"); let document = Document::parse(yaml.as_slice()).unwrap(); let desired = normalized(&document); - let service = desired["spec"]["inferenceProviders"][0]["serviceRef"] + let service = desired["spec"]["inferenceProviders"]["nemotron"]["serviceRef"] .as_str() .unwrap(); assert_eq!(desired["spec"]["services"][service]["kind"], "vllm"); @@ -190,7 +193,7 @@ fn external_ollama_proxy_should_work() { .external_ollama_proxy(); let document = Document::parse(desired.yaml().as_bytes()).unwrap(); let desired = normalized(&document); - let service = desired["spec"]["inferenceProviders"][0]["serviceRef"] + let service = desired["spec"]["inferenceProviders"]["local"]["serviceRef"] .as_str() .unwrap(); assert_eq!( @@ -230,7 +233,8 @@ fn openclaw_dashboard_should_work() { let document = Document::parse(yaml.as_slice()).unwrap(); let desired = normalized(&document); assert_eq!( - desired["spec"]["sandboxes"][0]["harness"]["settings"]["native_config"]["gateway"]["port"], + desired["spec"]["sandboxes"]["assistant"]["harness"]["settings"]["native_config"]["gateway"] + ["port"], 18800 ); } @@ -240,9 +244,10 @@ fn hermes_api_dashboard_and_tui_should_work() { let yaml = include_bytes!("../../../examples/hermes-interfaces.yaml"); let document = Document::parse(yaml.as_slice()).unwrap(); let desired = normalized(&document); - let interfaces = &desired["spec"]["sandboxes"][0]["harness"]["settings"]["interfaces"]; + let interfaces = + &desired["spec"]["sandboxes"]["assistant"]["harness"]["settings"]["interfaces"]; assert_eq!( - desired["spec"]["sandboxes"][0]["harness"]["kind"], + desired["spec"]["sandboxes"]["assistant"]["harness"]["kind"], "nvidia.fabric.hermes" ); assert_eq!(interfaces["api"]["port"], 8643); @@ -411,6 +416,13 @@ fn normalized(document: &Document) -> Value { serde_json::to_value(document).unwrap() } +/// The single entry of a sandbox or provider map. +fn only(map: &mut Value) -> &mut Value { + let map = map.as_object_mut().unwrap(); + assert_eq!(map.len(), 1); + map.values_mut().next().unwrap() +} + struct DesiredState { value: Value, } @@ -426,39 +438,47 @@ impl DesiredState { } } + /// The example's only sandbox. + fn sandbox(&mut self) -> &mut Value { + only(&mut self.value["spec"]["sandboxes"]) + } + + /// The example's only deployment provider. + fn provider(&mut self) -> &mut Value { + only(&mut self.value["spec"]["inferenceProviders"]) + } + fn provider_endpoint(mut self, endpoint: &str) -> Self { - self.value["spec"]["inferenceProviders"][0]["endpoint"] = json!(endpoint); + self.provider()["endpoint"] = json!(endpoint); self } fn provider_credential(mut self, environment_variable: &str) -> Self { - self.value["spec"]["inferenceProviders"][0]["credential"] = - json!({"env": environment_variable}); + self.provider()["credential"] = json!({"env": environment_variable}); self } fn provider_kind(mut self, provider: &str, api: &str) -> Self { - self.value["spec"]["inferenceProviders"][0]["provider"] = json!(provider); - self.value["spec"]["inferenceProviders"][0]["api"] = json!(api); + self.provider()["provider"] = json!(provider); + self.provider()["api"] = json!(api); self } fn inference_inputs(mut self, inputs: &[&str]) -> Self { - self.value["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"]["input"] = - json!(inputs); + self.sandbox()["agent"]["inference"]["routes"][0]["overrides"]["input"] = json!(inputs); self } fn sandbox_name(mut self, name: &str) -> Self { - self.value["spec"]["sandboxes"][0]["name"] = json!(name); + let sandboxes = self.value["spec"]["sandboxes"].as_object_mut().unwrap(); + let sandbox = sandboxes.values().next().unwrap().clone(); + sandboxes.clear(); + sandboxes.insert(name.into(), sandbox); self } fn service_backend(mut self, backend: &str) -> Self { - let service = self.value["spec"]["inferenceProviders"][0]["serviceRef"] - .as_str() - .unwrap() - .to_owned(); + let service = self.provider()["serviceRef"].as_str().unwrap().to_owned(); self.value["spec"]["services"][service]["kind"] = json!(backend); self } @@ -470,7 +490,7 @@ impl DesiredState { } fn sandbox_resources(mut self) -> Self { - self.value["spec"]["sandboxes"][0]["resources"] = json!({"cpu": "4", "memory": "16Gi"}); + self.sandbox()["resources"] = json!({"cpu": "4", "memory": "16Gi"}); self } @@ -496,16 +516,14 @@ impl DesiredState { } fn hermes_provider_tools(mut self) -> Self { - self.value["spec"]["sandboxes"][0]["harness"]["providerAuthentication"] = - json!({"method": "oauth"}); - self.value["spec"]["sandboxes"][0]["harness"]["toolGateways"] = json!(["nous-web"]); - self.value["spec"]["sandboxes"][0]["credentialPlaceholderExtensions"] = - json!(["TELEGRAM_BOT_TOKEN_AGENT_A"]); + self.sandbox()["harness"]["providerAuthentication"] = json!({"method": "oauth"}); + self.sandbox()["harness"]["toolGateways"] = json!(["nous-web"]); + self.sandbox()["credentialPlaceholderExtensions"] = json!(["TELEGRAM_BOT_TOKEN_AGENT_A"]); self } fn trusted_private_hosts(mut self) -> Self { - self.value["spec"]["sandboxes"][0]["network"]["trustedPrivateHosts"] = + self.sandbox()["network"]["trustedPrivateHosts"] = json!(["10.10.0.12", "inference.corp.example"]); self } @@ -517,7 +535,7 @@ impl DesiredState { } fn messaging_channel(mut self) -> Self { - self.value["spec"]["sandboxes"][0]["channels"] = + self.sandbox()["channels"] = json!([{"kind": "slack", "credential": {"env": "SLACK_BOT_TOKEN"}}]); self } @@ -549,3 +567,103 @@ impl DesiredState { serde_saphyr::to_string(&self.value).unwrap() } } + +/// Five sandboxes, declared out of name order, select deployment, sandbox, +/// inline sandbox, and inline deployment providers. Two sandboxes declare a +/// provider with the same name. +fn keyed_scopes() -> Value { + let mut value: Value = + serde_saphyr::from_str(include_str!("../../../examples/multiple-sandboxes.yaml")).unwrap(); + value["spec"]["inferences"]["inline-chat"] = json!({"routes": [{ + "name": "primary", + "provider": {"name": "shared-inline", "provider": "openai", "endpoint": "http://172.20.0.1:11449/v1"}, + "overrides": {"model": "qwen3:4b"} + }]}); + let sandboxes = &mut value["spec"]["sandboxes"]; + sandboxes["alice"]["agent"] = json!({"name": "alice", "inference": {"routes": [{ + "name": "primary", + "provider": {"name": "alice-local", "provider": "openai", "endpoint": "http://172.20.0.1:11448/v1"}, + "overrides": {"model": "qwen3:4b"} + }]}}); + for (sandbox, agent) in [("bob", "bob"), ("coding", "coder")] { + sandboxes[sandbox]["inferenceProviders"] = json!({"own": { + "provider": "openai", + "endpoint": "http://172.20.0.1:11447/v1" + }}); + sandboxes[sandbox]["agent"] = json!({"name": agent, "inference": {"routes": [{ + "name": "primary", "providerRef": "own", "overrides": {"model": "qwen3:4b"} + }]}}); + } + sandboxes["review"]["agent"]["inferenceRef"] = json!("inline-chat"); + value +} + +#[test] +fn keyed_sandboxes_and_providers_keep_the_resource_identities_of_named_entries() { + use nemoclaw_sdk::compile::{Generations, compile, targets}; + let document = Document::parse(keyed_scopes().to_string().as_bytes()).unwrap(); + let generations: Generations = [ + "workspace", + "provider", + "sandbox", + "managed_gateway", + "inference_service", + "ollama", + "ollama_proxy", + ] + .map(|key| (key.into(), "a".repeat(32))) + .into(); + let rows = targets(&document, &generations).unwrap(); + let graph = compile(&document, &generations, "0.1.0").unwrap(); + // Recorded from the same deployment authored as lists of named entries. + let registrations = [ + "alice-local-f11c16aa4f659d8e6299464a", + "local-3d36801b67957c3bcfa1093b", + "own-85a913ad5423a77eb0892729", + "own-8b0d99bb9c608112cc047ea2", + "shared-inlin-f02e6745609dc72d5e7de733", + ]; + let sandboxes = [ + ("alice", "alice-local-f11c16aa4f659d8e6299464a"), + ("bob", "own-85a913ad5423a77eb0892729"), + ("coding", "own-8b0d99bb9c608112cc047ea2"), + ("research", "local-3d36801b67957c3bcfa1093b"), + ("review", "shared-inlin-f02e6745609dc72d5e7de733"), + ]; + let mut expected: Vec = registrations + .iter() + .flat_map(|key| { + [ + format!("openshell_provider_profile.inference_{key}"), + format!("openshell_provider_registration.inference_{key}"), + ] + }) + .chain(sandboxes.iter().flat_map(|(name, _)| { + [ + format!("fabric_agent_configuration.{name}"), + format!("openshell_sandbox.{name}"), + ] + })) + .chain(["openshell_workspace.deployment".into()]) + .collect(); + expected.sort(); + let mut addresses: Vec<_> = rows.iter().map(|row| row.address.clone()).collect(); + addresses.sort(); + assert_eq!(addresses, expected); + for (index, (name, registration)) in sandboxes.into_iter().enumerate() { + let row = rows + .iter() + .find(|row| row.address == format!("openshell_sandbox.{name}")) + .unwrap(); + assert_eq!(row.values["name"], name); + assert_eq!( + row.values["provider_names_json"], + format!(r#"["{registration}"]"#) + ); + // Fabric reads are numbered in name order. + assert_eq!( + graph["resource"]["openshell_sandbox"][name]["runtime_json"], + format!("${{data.fabric_capabilities.sandbox_{index}.runtime_json}}") + ); + } +} diff --git a/crates/nemoclaw-sdk/tests/config_schema.rs b/crates/nemoclaw-sdk/tests/config_schema.rs index 2dc032c7487..e225353c9cf 100644 --- a/crates/nemoclaw-sdk/tests/config_schema.rs +++ b/crates/nemoclaw-sdk/tests/config_schema.rs @@ -83,7 +83,7 @@ fn image_pull_policy_accepts_only_supported_values_on_managed_containers() { external["spec"]["gateway"]["imagePullPolicy"] = json!("Never"); agrees(&validator, &external, false); let mut sandbox = input("local.yaml"); - sandbox["spec"]["sandboxes"][0]["imagePullPolicy"] = json!("Never"); + sandbox["spec"]["sandboxes"]["assistant"]["imagePullPolicy"] = json!("Never"); agrees(&validator, &sandbox, false); } @@ -101,13 +101,12 @@ fn input_schema_rejects_missing_required_fields_and_structural_nulls() { "/spec", "/spec/gateway", "/spec/gateway/management", - "/spec/inferenceProviders/0/name", + "/spec/inferenceProviders/local/provider", "/spec/sandboxes", - "/spec/sandboxes/0/name", - "/spec/sandboxes/0/agent", - "/spec/sandboxes/0/harness", - "/spec/sandboxes/0/agent/inference", - "/spec/sandboxes/0/agent/inference/routes/0/overrides/model", + "/spec/sandboxes/assistant/agent", + "/spec/sandboxes/assistant/harness", + "/spec/sandboxes/assistant/agent/inference", + "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model", ] { let mut value = original.clone(); let (parent, key) = path.rsplit_once('/').unwrap(); @@ -124,7 +123,7 @@ fn input_schema_rejects_missing_required_fields_and_structural_nulls() { ("/spec/gateway", "tls"), ("/spec/gateway", "target"), ("/spec/gateway/target", "docker"), - ("/spec/inferenceProviders/0", "serviceRef"), + ("/spec/inferenceProviders/local", "serviceRef"), ("/spec", "services"), ] { let mut value = original.clone(); @@ -144,7 +143,7 @@ fn input_schema_preserves_defaults_strict_objects_and_opaque_pi_metadata() { .remove(key); } for key in ["image", "network", "runtime"] { - value["spec"]["sandboxes"][0] + value["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove(key); @@ -159,7 +158,7 @@ fn input_schema_preserves_defaults_strict_objects_and_opaque_pi_metadata() { value["spec"]["gateway"]["surprise"] = json!(true); agrees(&validator, &value, false); let mut value = input("fabric-pi.yaml"); - let path = "/spec/sandboxes/0/agent/inference/routes/0/overrides/settings"; + let path = "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/settings"; *value.pointer_mut(path).unwrap() = json!({"future": [null, {"value": null}]}); agrees(&validator, &value, true); *value.pointer_mut(path).unwrap() = Value::Null; @@ -234,13 +233,13 @@ fn schema_and_parser_enforce_choices_bounds_and_conditional_forms() { ), ( "spark/vllm.yaml", - "/spec/inferenceProviders/0/endpoint", + "/spec/inferenceProviders/qwen/endpoint", json!("https://api.example.com/v1"), false, ), ( "spark/vllm.yaml", - "/spec/inferenceProviders/0/credential", + "/spec/inferenceProviders/qwen/credential", json!({"env": "TOKEN"}), false, ), @@ -300,7 +299,7 @@ fn schema_and_parser_enforce_choices_bounds_and_conditional_forms() { ), ( "spark/vllm.yaml", - "/spec/sandboxes/0/harness/kind", + "/spec/sandboxes/assistant/harness/kind", json!("deepagents"), true, ), @@ -377,10 +376,10 @@ fn documented_parser_checks_remain_required_after_schema_validation() { assert!(schema["x-nemoclaw-parser-checks"].as_array().unwrap().len() >= 4); let validator = jsonschema::validator_for(&schema).unwrap(); for (file, path, replacement) in [ - ("local.yaml", "/spec/inferenceProviders", json!([])), + ("local.yaml", "/spec/inferenceProviders", json!({})), ( "local.yaml", - "/spec/sandboxes/0/agent/inference/routes/0/providerRef", + "/spec/sandboxes/assistant/agent/inference/routes/0/providerRef", json!("foreign"), ), ( @@ -400,7 +399,7 @@ fn documented_parser_checks_remain_required_after_schema_validation() { ), ( "managed-ollama.yaml", - "/spec/sandboxes/0/agent/inference/routes/0/overrides/model", + "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model", json!("untagged"), ), ( @@ -446,7 +445,7 @@ fn every_sandbox_requires_one_agent() { let value = input("local.yaml"); agrees(&validator, &value, true); let mut missing = value.clone(); - missing["spec"]["sandboxes"][0] + missing["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove("agent"); @@ -482,7 +481,7 @@ fn gateway_variants_reject_fields_owned_by_the_other_mode() { fn a_sandbox_cannot_choose_a_runtime_apart_from_its_gateway() { let validator = jsonschema::validator_for(&input_schema()).unwrap(); let mut value = input("managed-podman.yaml"); - value["spec"]["sandboxes"][0]["runtime"] = json!({"provider": "docker"}); + value["spec"]["sandboxes"]["assistant"]["runtime"] = json!({"provider": "docker"}); agrees(&validator, &value, false); } @@ -524,7 +523,7 @@ fn cluster_target() -> Value { /// and its metadata bundle. fn cluster_document() -> Value { let mut value = managed(json!({"kubernetes": cluster_target()})); - value["spec"]["sandboxes"][0]["image"] = json!({ + value["spec"]["sandboxes"]["assistant"]["image"] = json!({ "ref": format!("registry.example/agent@sha256:{}", "a".repeat(64)), "metadata": {"env": "TEST_IMAGE_METADATA"} }); @@ -890,10 +889,10 @@ fn schema_patterns_reject_trailing_newlines_in_identifiers_and_pins() { for (file, path) in [ ("local.yaml", "/metadata/name"), ("local.yaml", "/metadata/uid"), - ("local.yaml", "/spec/sandboxes/0/agent/name"), + ("local.yaml", "/spec/sandboxes/assistant/agent/name"), ( "local.yaml", - "/spec/sandboxes/0/agent/inference/routes/0/overrides/model", + "/spec/sandboxes/assistant/agent/inference/routes/0/overrides/model", ), ("spark/vllm.yaml", "/spec/services/qwen/image"), ( @@ -907,3 +906,254 @@ fn schema_patterns_reject_trailing_newlines_in_identifiers_and_pins() { agrees_at(&validator, &value, false, file, path); } } + +/// The keys of the object at `pointer`, sorted, since `serde_json::Map` +/// keeps no insertion order. +fn keys(value: &Value, pointer: &str) -> Vec { + value + .pointer(pointer) + .and_then(Value::as_object) + .unwrap_or_else(|| panic!("{pointer} is not an object")) + .keys() + .cloned() + .collect() +} + +#[test] +fn sandboxes_and_inference_providers_are_keyed_by_name() { + let validator = jsonschema::validator_for(&input_schema()).unwrap(); + let mut value = input("multiple-providers.yaml"); + let writer = &mut value["spec"]["sandboxes"]["writer"]; + writer["inferenceProviders"] = json!({"own": { + "provider": "openai", + "endpoint": "http://172.20.0.1:11447/v1" + }}); + writer["agent"]["inference"]["routes"][0]["providerRef"] = json!("own"); + agrees(&validator, &value, true); + let document = + serde_json::to_value(Document::parse(value.to_string().as_bytes()).unwrap()).unwrap(); + assert_eq!(keys(&document, "/spec/sandboxes"), ["researcher", "writer"]); + assert_eq!( + keys(&document, "/spec/inferenceProviders"), + ["hosted", "local"] + ); + assert_eq!( + keys(&document, "/spec/sandboxes/writer/inferenceProviders"), + ["own"] + ); + // The key is the name, so a keyed definition takes no name field. + let sandbox = "a sandbox's name is its key under spec.sandboxes"; + let provider = "a provider's name is its key under inferenceProviders; only an inline route provider states name"; + for (pointer, message) in [ + ("/spec/sandboxes/writer", sandbox), + ("/spec/inferenceProviders/local", provider), + ("/spec/sandboxes/writer/inferenceProviders/own", provider), + ] { + let mut named = value.clone(); + let key = pointer.rsplit('/').next().unwrap(); + named.pointer_mut(pointer).unwrap()["name"] = json!(key); + agrees_at( + &validator, + &named, + false, + "multiple-providers.yaml", + pointer, + ); + assert_eq!( + schema_diagnostic(&named), + format!("{}: {message}", pointer[1..].replace('/', ".")) + ); + } + // The earlier list of named entries is rejected. + let mut listed = input("local.yaml"); + let mut sandbox = listed["spec"]["sandboxes"]["assistant"].clone(); + sandbox["name"] = json!("assistant"); + listed["spec"]["sandboxes"] = json!([sandbox]); + agrees(&validator, &listed, false); + assert_eq!( + schema_diagnostic(&listed), + format!("spec.sandboxes: {SANDBOXES}") + ); + let mut listed = input("local.yaml"); + let mut provider = listed["spec"]["inferenceProviders"]["local"].clone(); + provider["name"] = json!("local"); + listed["spec"]["inferenceProviders"] = json!([provider]); + agrees(&validator, &listed, false); + assert_eq!( + schema_diagnostic(&listed), + format!("spec.inferenceProviders: {PROVIDERS}") + ); +} + +const SANDBOXES: &str = "spec.sandboxes must map 1 to 32 lowercase names (^[a-z][a-z0-9-]{0,39}$) to sandbox definitions"; +const PROVIDERS: &str = + "inferenceProviders must map lowercase names (^[a-z][a-z0-9-]{0,39}$) to provider definitions"; + +#[test] +fn a_name_key_outside_the_name_pattern_is_rejected_without_echoing_it() { + let validator = jsonschema::validator_for(&input_schema()).unwrap(); + let mut scoped = input("local.yaml"); + scoped["spec"]["sandboxes"]["assistant"]["inferenceProviders"] = json!({"own": { + "provider": "openai", + "endpoint": "http://172.20.0.1:11447/v1" + }}); + agrees(&validator, &scoped, true); + for (collection, key, rule) in [ + ("/spec/sandboxes", "assistant", SANDBOXES), + ("/spec/inferenceProviders", "local", PROVIDERS), + ( + "/spec/sandboxes/assistant/inferenceProviders", + "own", + PROVIDERS, + ), + ] { + for invalid in ["Private-Sentinel", "9private-sentinel", "private_sentinel"] { + let mut value = scoped.clone(); + let map = value + .pointer_mut(collection) + .unwrap() + .as_object_mut() + .unwrap(); + let entry = map.remove(key).unwrap(); + map.insert(invalid.into(), entry); + agrees_at(&validator, &value, false, invalid, collection); + let error = schema_diagnostic(&value); + let path = collection[1..].replace('/', "."); + assert_eq!(error, format!("{path}: {rule}")); + assert!(!error.contains(invalid), "{error}"); + } + } +} + +#[test] +fn a_deployment_declares_one_to_32_sandboxes() { + let validator = jsonschema::validator_for(&input_schema()).unwrap(); + let value = input("local.yaml"); + let sandbox = value["spec"]["sandboxes"]["assistant"].clone(); + for (count, accepted) in [(0, false), (1, true), (32, true), (33, false)] { + let mut sized = value.clone(); + sized["spec"]["sandboxes"] = Value::Object( + (0..count) + .map(|index| (format!("sandbox-{index}"), sandbox.clone())) + .collect(), + ); + agrees_at( + &validator, + &sized, + accepted, + "local.yaml", + &count.to_string(), + ); + if !accepted { + assert_eq!( + schema_diagnostic(&sized), + format!("spec.sandboxes: {SANDBOXES}") + ); + } + } +} + +#[test] +fn an_inline_route_provider_names_itself_and_keeps_the_provider_rules() { + let validator = jsonschema::validator_for(&input_schema()).unwrap(); + let original = input("inline-inference.yaml"); + agrees(&validator, &original, true); + let pointer = "/spec/sandboxes/assistant/agent/inference/routes/0/provider"; + let mut unnamed = original.clone(); + unnamed + .pointer_mut(pointer) + .unwrap() + .as_object_mut() + .unwrap() + .remove("name"); + agrees(&validator, &unnamed, false); + assert_eq!( + schema_diagnostic(&unnamed), + r#"spec.sandboxes.assistant.agent.inference.routes[0].provider: required field: "name""# + ); + for (field, replacement) in [ + ("name", json!("Upper")), + ("credential", json!({"env": "MODEL_TOKEN"})), + ("api", json!("anthropic-messages")), + ("serviceRef", json!("qwen")), + ("endpoint", json!("")), + ] { + let mut value = original.clone(); + value.pointer_mut(pointer).unwrap()[field] = replacement; + agrees_at(&validator, &value, false, "inline-inference.yaml", field); + } +} + +#[test] +fn a_provider_exclusion_rule_states_what_it_excludes() { + let service = "serviceRef excludes endpoint and credential and selects provider openai"; + let plain = "an http:// endpoint takes no credential"; + let credential = json!({"env": "MODEL_TOKEN"}); + for (file, pointer, path) in [ + ( + "local.yaml", + "/spec/inferenceProviders/local", + "spec.inferenceProviders.local", + ), + ( + "inline-inference.yaml", + "/spec/sandboxes/assistant/agent/inference/routes/0/provider", + "spec.sandboxes.assistant.agent.inference.routes[0].provider", + ), + ] { + for (fields, at, message) in [ + (json!({"serviceRef": "qwen"}), ".endpoint", service), + ( + json!({"serviceRef": "qwen", "endpoint": null, "credential": credential}), + "", + service, + ), + ( + json!({"serviceRef": "qwen", "endpoint": null, "provider": "anthropic"}), + ".provider", + service, + ), + (json!({"credential": credential}), "", plain), + ] { + let mut value = input(file); + let provider = value.pointer_mut(pointer).unwrap().as_object_mut().unwrap(); + for (field, replacement) in fields.as_object().unwrap() { + match replacement { + Value::Null => provider.remove(field), + _ => provider.insert(field.clone(), replacement.clone()), + }; + } + assert_eq!( + schema_diagnostic(&value), + format!("{path}{at}: {message}"), + "{file}: {fields}" + ); + } + } +} + +#[test] +fn duplicate_sandbox_or_provider_names_are_rejected_as_duplicate_yaml_keys() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples"); + for (file, key, duplicate) in [ + ("multiple-sandboxes.yaml", "\n bob:\n", "\n alice:\n"), + ( + "multiple-providers.yaml", + "\n hosted:\n", + "\n local:\n", + ), + ] { + let text = std::fs::read_to_string(root.join(file)).unwrap(); + assert!(text.contains(key), "{file}"); + let error = Document::parse(text.replacen(key, duplicate, 1).as_bytes()) + .unwrap_err() + .to_string(); + assert!(error.contains("duplicate mapping key"), "{file}: {error}"); + } + // JSON input is read as YAML, so it gets the same check. + let text = input("multiple-sandboxes.yaml").to_string(); + let error = Document::parse(text.replacen(r#""bob":"#, r#""alice":"#, 1).as_bytes()) + .unwrap_err() + .to_string(); + assert!(error.contains("duplicate mapping key"), "{error}"); +} diff --git a/crates/nemoclaw-sdk/tests/config_validation.rs b/crates/nemoclaw-sdk/tests/config_validation.rs index becd8f9d757..55d5e886723 100644 --- a/crates/nemoclaw-sdk/tests/config_validation.rs +++ b/crates/nemoclaw-sdk/tests/config_validation.rs @@ -77,7 +77,7 @@ fn normalization_markers_are_accepted_only_before_defaults() { let baseline = document("spark/vllm.yaml"); for path in [ "/spec/gateway/target/docker/networkCidr", - "/spec/sandboxes/0/image/ref", + "/spec/sandboxes/assistant/image/ref", ] { let mut value = serde_json::to_value(&baseline).unwrap(); *value.pointer_mut(path).unwrap() = json!(""); @@ -102,7 +102,10 @@ fn normalization_markers_are_accepted_only_before_defaults() { #[test] fn standalone_harness_validation_uses_the_same_contract_as_documents() { let baseline = document("fabric-openclaw.yaml"); - let harness = baseline.spec.sandboxes[0].harness.as_ref().unwrap(); + let harness = baseline.spec.sandboxes["assistant"] + .harness + .as_ref() + .unwrap(); for invalid in [ json!({"execution":{"timeoutSeconds":0}}), json!({"execution":{"timeoutSeconds":1000000001_u64}}), @@ -115,7 +118,7 @@ fn standalone_harness_validation_uses_the_same_contract_as_documents() { let candidate: nemoclaw_sdk::config::Harness = serde_json::from_value(value).unwrap(); assert!(candidate.validate().is_err()); let mut direct = baseline.clone(); - direct.spec.sandboxes[0].harness = Some(candidate); + direct.spec.sandboxes.get_mut("assistant").unwrap().harness = Some(candidate); assert!(direct.validate().is_err()); } } @@ -134,7 +137,7 @@ fn schema_diagnostics_never_echo_values_unknown_properties_or_definition_names() json!({"SECRET-MAP-KEY": {"kind":"SECRET-VALUE"}}), ), ( - "/spec/sandboxes/0/harness", + "/spec/sandboxes/assistant/harness", json!({"kind":"openclaw", "SECRET-PROPERTY":"SECRET-VALUE"}), ), ] { @@ -188,8 +191,7 @@ fn policy_schema_owns_nonempty_destinations_and_rules() { let baseline = serde_json::to_value(document("explicit-policy.yaml")).unwrap(); let validator = jsonschema::validator_for(&nemoclaw_sdk::config::schema::input_schema()).unwrap(); - let path = - "/spec/sandboxes/0/network/policy/explicit/network_policies/documentation/endpoints/0"; + let path = "/spec/sandboxes/assistant/network/policy/explicit/network_policies/documentation/endpoints/0"; for replacement in [ json!({"port":443,"host":""}), json!({"port":443,"allowed_ips":[]}), @@ -203,6 +205,11 @@ fn policy_schema_owns_nonempty_destinations_and_rules() { assert!(Document::parse(value.to_string().as_bytes()).is_err()); let direct: Document = serde_json::from_value(value).unwrap(); assert!(direct.validate().is_err()); - assert!(direct.spec.sandboxes[0].network.policy_proto().is_err()); + assert!( + direct.spec.sandboxes["assistant"] + .network + .policy_proto() + .is_err() + ); } } diff --git a/crates/nemoclaw-sdk/tests/discovery_graph.rs b/crates/nemoclaw-sdk/tests/discovery_graph.rs index 0ace68327e0..0241c84a570 100644 --- a/crates/nemoclaw-sdk/tests/discovery_graph.rs +++ b/crates/nemoclaw-sdk/tests/discovery_graph.rs @@ -153,14 +153,15 @@ fn plan_queries_list_the_reads_of_a_managed_gateway_with_a_hosted_route() { compute_driver: ComputeDriver::Docker, }; assert_eq!(queries[3], DiscoveryQuery::Engine(platform.clone())); - let sandbox = &document.spec.sandboxes[0]; + let sandbox = &document.spec.sandboxes["assistant"]; assert_eq!( queries[4], DiscoveryQuery::Fabric(FabricRequest { engine: engine.into(), image: sandbox.image.ref_.clone(), requirements: nemoclaw_sdk::fabric_capabilities::requirements_for_sandbox( - &document, sandbox + &document, + "assistant" ) .unwrap(), platform: Some(platform), diff --git a/crates/nemoclaw-sdk/tests/execution_settings.rs b/crates/nemoclaw-sdk/tests/execution_settings.rs index d65377ed968..f93b251f9b2 100644 --- a/crates/nemoclaw-sdk/tests/execution_settings.rs +++ b/crates/nemoclaw-sdk/tests/execution_settings.rs @@ -9,11 +9,12 @@ fn input() -> Value { fn invocation_timeout_projects_to_public_runtime_for_any_adapter() { for id in ["nvidia.fabric.pi", "org.fixture.future"] { let mut value = input(); - value["spec"]["sandboxes"][0]["harness"]["kind"] = id.into(); - value["spec"]["sandboxes"][0]["harness"]["execution"] = json!({"timeoutSeconds":900}); + value["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = id.into(); + value["spec"]["sandboxes"]["assistant"]["harness"]["execution"] = + json!({"timeoutSeconds":900}); let doc = Document::parse(value.to_string().as_bytes()).unwrap(); assert_eq!( - fabric_config::for_sandbox(&doc, &doc.spec.sandboxes[0]).unwrap()["runtime"]["timeout_seconds"], + fabric_config::for_sandbox(&doc, "assistant").unwrap()["runtime"]["timeout_seconds"], 900 ); assert_eq!( @@ -33,7 +34,7 @@ fn invalid_timeout_and_native_heartbeat_requirements_are_not_silently_accepted() json!({"heartbeatEvery":"30m"}), ] { let mut value = input(); - value["spec"]["sandboxes"][0]["harness"]["execution"] = execution; + value["spec"]["sandboxes"]["assistant"]["harness"]["execution"] = execution; assert!(Document::parse(value.to_string().as_bytes()).is_err()); } } diff --git a/crates/nemoclaw-sdk/tests/fabric_planner.rs b/crates/nemoclaw-sdk/tests/fabric_planner.rs index 4d619541af1..e143a57e163 100644 --- a/crates/nemoclaw-sdk/tests/fabric_planner.rs +++ b/crates/nemoclaw-sdk/tests/fabric_planner.rs @@ -80,18 +80,18 @@ fn public_fabric_configuration_passes_through_without_overriding_deployment_bind use nemoclaw_sdk::config::Document; let mut input: serde_json::Value = serde_saphyr::from_str(include_str!("fixtures/config/local.yaml")).unwrap(); - input["spec"]["sandboxes"][0]["harness"]["config"] = json!({"mcp":{"servers":{"custom":{"transport":"stdio","url":"owned-fixture","exposure":"harness_native"}}},"runtime":{"max_turns":3}}); + input["spec"]["sandboxes"]["assistant"]["harness"]["config"] = json!({"mcp":{"servers":{"custom":{"transport":"stdio","url":"owned-fixture","exposure":"harness_native"}}},"runtime":{"max_turns":3}}); let doc = Document::parse(input.to_string().as_bytes()).unwrap(); - let actual = nemoclaw_sdk::fabric_config::for_sandbox(&doc, &doc.spec.sandboxes[0]).unwrap(); + let actual = nemoclaw_sdk::fabric_config::for_sandbox(&doc, "assistant").unwrap(); assert_eq!(actual["runtime"]["max_turns"], 3); assert_eq!( actual["mcp"], - input["spec"]["sandboxes"][0]["harness"]["config"]["mcp"] + input["spec"]["sandboxes"]["assistant"]["harness"]["config"]["mcp"] ); - input["spec"]["sandboxes"][0]["harness"]["config"]["models"] = + input["spec"]["sandboxes"]["assistant"]["harness"]["config"]["models"] = json!({"default":{"base_url":"https://substituted.invalid"}}); let doc = Document::parse(input.to_string().as_bytes()).unwrap(); - assert!(nemoclaw_sdk::fabric_config::for_sandbox(&doc, &doc.spec.sandboxes[0]).is_err()); + assert!(nemoclaw_sdk::fabric_config::for_sandbox(&doc, "assistant").is_err()); } #[test] @@ -197,16 +197,15 @@ fn rejected_model_limit_identifies_the_field_and_authored_route_without_values() }; let mut input: serde_json::Value = serde_saphyr::from_str(include_str!("fixtures/config/local.yaml")).unwrap(); - input["spec"]["sandboxes"][0]["harness"]["kind"] = "nvidia.fabric.pi".into(); - input["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["name"] = "fast".into(); - input["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"]["maxTokens"] = + input["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = "nvidia.fabric.pi".into(); + input["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["name"] = + "fast".into(); + input["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["overrides"]["maxTokens"] = 256.into(); let document = Document::parse(input.to_string().as_bytes()).unwrap(); - let mut request = nemoclaw_sdk::fabric_capabilities::requirements_for_sandbox( - &document, - &document.spec.sandboxes[0], - ) - .unwrap(); + let mut request = + nemoclaw_sdk::fabric_capabilities::requirements_for_sandbox(&document, "assistant") + .unwrap(); let report = assess_fabric(&FabricCatalog::bundled(), &request); assert_eq!(report.status, Support::Unsupported); let text = serde_json::to_string(&report).unwrap(); @@ -369,11 +368,11 @@ spec: endpoint: http://127.0.0.1:18080 networkCidr: 10.231.200.0/24 inferenceProviders: - - name: hosted + hosted: provider: openai endpoint: https://inference.example.test/v1 sandboxes: - - name: assistant + assistant: image: ref: nc-dummy@sha256:0000000000000000000000000000000000000000000000000000000000000000 network: @@ -402,8 +401,7 @@ spec: )) .unwrap(), }]; - let configuration = - nemoclaw_sdk::fabric_config::for_sandbox(&document, &document.spec.sandboxes[0]).unwrap(); + let configuration = nemoclaw_sdk::fabric_config::for_sandbox(&document, "assistant").unwrap(); let plan = plan_configuration(&catalog, configuration.clone()).unwrap(); assert_eq!(plan.config.harness.unwrap().settings["reply"], "dummy-ok"); let mut unknown = configuration; diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/fabric-claude.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/fabric-claude.yaml index 892a863ea0d..3d1438e7a4d 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/fabric-claude.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/fabric-claude.yaml @@ -13,22 +13,22 @@ spec: target: docker: {} inferenceProviders: - - name: local - provider: anthropic - endpoint: http://172.20.0.1:11446/v1 + local: + provider: anthropic + endpoint: http://172.20.0.1:11446/v1 sandboxes: - - name: assistant - image: - ref: nc-prototype-fabric@sha256:ad0f0a9bdef6b1d1efd77b850cff8137d257fee03aa29e3b6980d81cd52fb3fb - network: - tier: isolated - harness: - kind: nvidia.fabric.claude - agent: - name: main - inference: - routes: - - name: primary - providerRef: local - overrides: - model: fixture-model + assistant: + image: + ref: nc-prototype-fabric@sha256:ad0f0a9bdef6b1d1efd77b850cff8137d257fee03aa29e3b6980d81cd52fb3fb + network: + tier: isolated + harness: + kind: nvidia.fabric.claude + agent: + name: main + inference: + routes: + - name: primary + providerRef: local + overrides: + model: fixture-model diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/fabric-pi.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/fabric-pi.yaml index d2f6db7e90e..fe3ea7a4c25 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/fabric-pi.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/fabric-pi.yaml @@ -13,30 +13,30 @@ spec: target: docker: {} inferenceProviders: - - name: local - provider: openai - endpoint: http://172.20.0.1:11446/v1 + local: + provider: openai + endpoint: http://172.20.0.1:11446/v1 sandboxes: - - name: assistant - image: - ref: nc-multi-models@sha256:2ee5e33522a37d3d77bb6381a92e963cb1d5884f2dd28b353b4b7fa0d95f212e - network: - tier: isolated - harness: - kind: nvidia.fabric.pi - agent: - name: main - inference: - routes: - - name: primary - providerRef: local - overrides: - model: qwen3:4b - settings: - model_metadata: - api: openai-completions - contextWindow: 8192 - maxTokens: 2048 - reasoning: false - input: - - text + assistant: + image: + ref: nc-multi-models@sha256:2ee5e33522a37d3d77bb6381a92e963cb1d5884f2dd28b353b4b7fa0d95f212e + network: + tier: isolated + harness: + kind: nvidia.fabric.pi + agent: + name: main + inference: + routes: + - name: primary + providerRef: local + overrides: + model: qwen3:4b + settings: + model_metadata: + api: openai-completions + contextWindow: 8192 + maxTokens: 2048 + reasoning: false + input: + - text diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/fabric.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/fabric.yaml index 485f64ff7d7..6a85a4de6ea 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/fabric.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/fabric.yaml @@ -13,22 +13,22 @@ spec: target: docker: {} inferenceProviders: - - name: local - provider: openai - endpoint: http://172.20.0.1:11446/v1 + local: + provider: openai + endpoint: http://172.20.0.1:11446/v1 sandboxes: - - name: assistant - image: - ref: nc-prototype-fabric@sha256:a6a0e5cf53501e765ae43457212989ff4716c6224352dc109ebd49c3780450cd - network: - tier: isolated - harness: - kind: nvidia.fabric.langchain.deepagents - agent: - name: main - inference: - routes: - - name: primary - providerRef: local - overrides: - model: qwen3:1.7b + assistant: + image: + ref: nc-prototype-fabric@sha256:a6a0e5cf53501e765ae43457212989ff4716c6224352dc109ebd49c3780450cd + network: + tier: isolated + harness: + kind: nvidia.fabric.langchain.deepagents + agent: + name: main + inference: + routes: + - name: primary + providerRef: local + overrides: + model: qwen3:1.7b diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/local.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/local.yaml index e8565ea5bca..1cbe7057a6d 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/local.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/local.yaml @@ -13,22 +13,22 @@ spec: target: docker: {} inferenceProviders: - - name: local - provider: openai - endpoint: http://172.20.0.1:11436/v1 + local: + provider: openai + endpoint: http://172.20.0.1:11436/v1 sandboxes: - - name: assistant - image: - ref: nc-multi-models@sha256:3ab70ded67440e838a37d6c9f0e3b08b95e2acf416c6076f8817bac190525cf0 - network: - tier: isolated - harness: - kind: nvidia.fabric.openclaw - agent: - name: main - inference: - routes: - - name: primary - providerRef: local - overrides: - model: qwen3.5:0.8b + assistant: + image: + ref: nc-multi-models@sha256:3ab70ded67440e838a37d6c9f0e3b08b95e2acf416c6076f8817bac190525cf0 + network: + tier: isolated + harness: + kind: nvidia.fabric.openclaw + agent: + name: main + inference: + routes: + - name: primary + providerRef: local + overrides: + model: qwen3.5:0.8b diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/managed-ollama.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/managed-ollama.yaml index 7c032f43432..0fa70d32929 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/managed-ollama.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/managed-ollama.yaml @@ -28,22 +28,22 @@ spec: memory: gpuMemoryGiB: 16 inferenceProviders: - - name: local - provider: openai - serviceRef: ollama-server + local: + provider: openai + serviceRef: ollama-server sandboxes: - - name: assistant - image: - ref: nc-multi-models@sha256:3ab70ded67440e838a37d6c9f0e3b08b95e2acf416c6076f8817bac190525cf0 - network: - tier: isolated - harness: - kind: nvidia.fabric.openclaw - agent: - name: main - inference: - routes: - - name: primary - providerRef: local - overrides: - model: qwen3:0.6b + assistant: + image: + ref: nc-multi-models@sha256:3ab70ded67440e838a37d6c9f0e3b08b95e2acf416c6076f8817bac190525cf0 + network: + tier: isolated + harness: + kind: nvidia.fabric.openclaw + agent: + name: main + inference: + routes: + - name: primary + providerRef: local + overrides: + model: qwen3:0.6b diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/spark.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/spark.yaml index 99440e8b545..af93d399b7f 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/spark.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/spark.yaml @@ -75,22 +75,22 @@ spec: size: 1 sha256: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa inferenceProviders: - - name: qwen - provider: openai - serviceRef: qwen + qwen: + provider: openai + serviceRef: qwen sandboxes: - - name: assistant - image: - ref: nc-multi-models@sha256:3ab70ded67440e838a37d6c9f0e3b08b95e2acf416c6076f8817bac190525cf0 - network: - tier: isolated - harness: - kind: nvidia.fabric.openclaw - agent: - name: assistant - inference: - routes: - - name: primary - providerRef: qwen - overrides: - model: fixture-model + assistant: + image: + ref: nc-multi-models@sha256:3ab70ded67440e838a37d6c9f0e3b08b95e2acf416c6076f8817bac190525cf0 + network: + tier: isolated + harness: + kind: nvidia.fabric.openclaw + agent: + name: assistant + inference: + routes: + - name: primary + providerRef: qwen + overrides: + model: fixture-model diff --git a/crates/nemoclaw-sdk/tests/harness_references.rs b/crates/nemoclaw-sdk/tests/harness_references.rs index 30e8ed6ec6a..ac3787f9337 100644 --- a/crates/nemoclaw-sdk/tests/harness_references.rs +++ b/crates/nemoclaw-sdk/tests/harness_references.rs @@ -9,19 +9,19 @@ use serde_json::{Value, json}; fn input() -> Value { let mut value: Value = serde_saphyr::from_str(include_str!("../../../examples/fabric-openclaw.yaml")).unwrap(); - value["spec"]["sandboxes"][0]["harness"] = + value["spec"]["sandboxes"]["assistant"]["harness"] = json!({"kind":"openclaw", "execution":{"timeoutSeconds":900}}); value } fn shared(mut value: Value, sandbox: bool) -> Value { - let harness = value["spec"]["sandboxes"][0] + let harness = value["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove("harness") .unwrap(); - value["spec"]["sandboxes"][0]["harnessRef"] = json!("assistant"); + value["spec"]["sandboxes"]["assistant"]["harnessRef"] = json!("assistant"); let scope = if sandbox { - &mut value["spec"]["sandboxes"][0] + &mut value["spec"]["sandboxes"]["assistant"] } else { &mut value["spec"] }; @@ -49,12 +49,7 @@ fn shared_harness_configuration_compiles_identically_and_survives_export() { Document::parse(doc.yaml().unwrap().as_bytes()).unwrap(), doc ); - let mut other = value["spec"]["sandboxes"][0].clone(); - other["name"] = json!("writer"); - value["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(other); + value["spec"]["sandboxes"]["writer"] = value["spec"]["sandboxes"]["assistant"].clone(); let doc = Document::parse(value.to_string().as_bytes()).unwrap(); let rows = targets(&doc, &generations).unwrap(); let runtime: Value = serde_json::from_str( @@ -72,23 +67,23 @@ fn shared_harness_configuration_compiles_identically_and_survives_export() { #[test] fn sandbox_harness_selection_rejects_ambiguity_agent_selection_and_unsupported_counts() { let mut missing = shared(input(), false); - missing["spec"]["sandboxes"][0]["harnessRef"] = json!("missing"); + missing["spec"]["sandboxes"]["assistant"]["harnessRef"] = json!("missing"); let mut both = shared(input(), false); - both["spec"]["sandboxes"][0]["harness"] = json!({"kind":"openclaw"}); + both["spec"]["sandboxes"]["assistant"]["harness"] = json!({"kind":"openclaw"}); let mut shadow = shared(input(), false); - shadow["spec"]["sandboxes"][0]["harnesses"] = shadow["spec"]["harnesses"].clone(); + shadow["spec"]["sandboxes"]["assistant"]["harnesses"] = shadow["spec"]["harnesses"].clone(); let mut absent = input(); - absent["spec"]["sandboxes"][0] + absent["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove("harness"); let mut limited = input(); limited["spec"]["gateway"] = json!({"management":"external","endpoint":"http://127.0.0.1:8080"}); - limited["spec"]["sandboxes"][0]["harness"] = json!({"kind":"nvidia.fabric.hermes"}); - let mut other = limited["spec"]["sandboxes"][0]["agent"].clone(); + limited["spec"]["sandboxes"]["assistant"]["harness"] = json!({"kind":"nvidia.fabric.hermes"}); + let mut other = limited["spec"]["sandboxes"]["assistant"]["agent"].clone(); other["name"] = json!("other"); - limited["spec"]["sandboxes"][0]["agents"] = json!([other]); + limited["spec"]["sandboxes"]["assistant"]["agents"] = json!([other]); let schema = jsonschema::validator_for(&input_schema()).unwrap(); for value in [absent, both, limited] { assert!(Document::parse(value.to_string().as_bytes()).is_err()); @@ -123,13 +118,13 @@ fn default_image_follows_the_selected_harness_and_tolerates_incomplete_selection use nemoclaw_sdk::config::DEFAULT_AGENT_IMAGE; let mut inline = input(); - inline["spec"]["sandboxes"][0]["harness"] = json!({"kind":"nvidia.fabric.hermes"}); + inline["spec"]["sandboxes"]["assistant"]["harness"] = json!({"kind":"nvidia.fabric.hermes"}); let mut missing = shared(inline.clone(), false); - missing["spec"]["sandboxes"][0]["harnessRef"] = json!("missing"); + missing["spec"]["sandboxes"]["assistant"]["harnessRef"] = json!("missing"); let mut both = shared(inline.clone(), false); - both["spec"]["sandboxes"][0]["harness"] = json!({"kind":"nvidia.fabric.hermes"}); + both["spec"]["sandboxes"]["assistant"]["harness"] = json!({"kind":"nvidia.fabric.hermes"}); let mut absent = input(); - absent["spec"]["sandboxes"][0] + absent["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove("harness"); @@ -142,11 +137,14 @@ fn default_image_follows_the_selected_harness_and_tolerates_incomplete_selection (absent, false), ] { let mut document: Document = serde_json::from_value(value).unwrap(); - document.spec.sandboxes[0].image.ref_.clear(); + let sandbox = document.spec.sandboxes.get_mut("assistant").unwrap(); + sandbox.image.ref_.clear(); document.defaults(); - let sandbox = &document.spec.sandboxes[0]; - assert_eq!(sandbox.image.ref_, DEFAULT_AGENT_IMAGE); - let selected = document.sandbox_harness(sandbox); + assert_eq!( + document.spec.sandboxes["assistant"].image.ref_, + DEFAULT_AGENT_IMAGE + ); + let selected = document.sandbox_harness("assistant"); if valid { assert_eq!( selected.unwrap().kind, diff --git a/crates/nemoclaw-sdk/tests/inference_connection.rs b/crates/nemoclaw-sdk/tests/inference_connection.rs index 9231043f0af..e8c09efc9e3 100644 --- a/crates/nemoclaw-sdk/tests/inference_connection.rs +++ b/crates/nemoclaw-sdk/tests/inference_connection.rs @@ -36,8 +36,18 @@ fn inference_connection_is_resolved_independently_of_the_sandbox_engine() { assert!(published.credential.is_none()); let mut remote = Document::parse(include_str!("fixtures/config/local.yaml").as_bytes()).unwrap(); - remote.spec.inference_providers[0].endpoint = "https://inference.example.test:9443/v1".into(); - remote.spec.inference_providers[0].credential = Some(SecretRef { + remote + .spec + .inference_providers + .get_mut("local") + .unwrap() + .endpoint = "https://inference.example.test:9443/v1".into(); + remote + .spec + .inference_providers + .get_mut("local") + .unwrap() + .credential = Some(SecretRef { env: "MODEL_TOKEN".into(), }); let first = remote.inference_connection().unwrap(); @@ -50,7 +60,12 @@ fn inference_connection_is_resolved_independently_of_the_sandbox_engine() { assert_eq!(first.endpoint, "https://inference.example.test:9443/v1"); assert_eq!(first.credential.unwrap().env, "MODEL_TOKEN"); // Resolution is pure: this address need not be reachable by the CLI host. - remote.spec.inference_providers[0].endpoint = "https://unreachable.invalid/v1".into(); + remote + .spec + .inference_providers + .get_mut("local") + .unwrap() + .endpoint = "https://unreachable.invalid/v1".into(); remote.validate().unwrap(); assert_eq!( remote.inference_connection().unwrap().endpoint, diff --git a/crates/nemoclaw-sdk/tests/inference_discovery.rs b/crates/nemoclaw-sdk/tests/inference_discovery.rs index 3376caea06c..f39532ce234 100644 --- a/crates/nemoclaw-sdk/tests/inference_discovery.rs +++ b/crates/nemoclaw-sdk/tests/inference_discovery.rs @@ -38,20 +38,16 @@ fn endpoint_requests_deduplicate_shared_routes_and_preserve_harness_api_defaults Document::parse(include_bytes!("../../../examples/onboarding/openclaw.yaml").as_slice()) .unwrap(); let mut value = serde_json::to_value(document).unwrap(); - value["spec"]["inferenceProviders"][0] + value["spec"]["inferenceProviders"]["nvidia-prod"] .as_object_mut() .unwrap() .remove("api"); - let mut second = value["spec"]["sandboxes"][0].clone(); - second["name"] = serde_json::json!("second"); - value["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(second.clone()); + let mut second = value["spec"]["sandboxes"]["assistant"].clone(); + value["spec"]["sandboxes"]["second"] = second.clone(); let document = Document::parse(value.to_string().as_bytes()).unwrap(); assert_eq!(endpoint_requests(&document).unwrap().len(), 1); second["harness"]["kind"] = serde_json::json!("codex"); - value["spec"]["sandboxes"][1] = second; + value["spec"]["sandboxes"]["second"] = second; let document = Document::parse(value.to_string().as_bytes()).unwrap(); let requests = endpoint_requests(&document).unwrap(); assert_eq!(requests.len(), 1); diff --git a/crates/nemoclaw-sdk/tests/inference_references.rs b/crates/nemoclaw-sdk/tests/inference_references.rs index fe9c60182e2..9fadc1b8343 100644 --- a/crates/nemoclaw-sdk/tests/inference_references.rs +++ b/crates/nemoclaw-sdk/tests/inference_references.rs @@ -10,14 +10,14 @@ fn input() -> Value { crate::support::example("fabric-openclaw.yaml") } fn shared(mut value: Value, sandbox: bool) -> Value { - let inference = value["spec"]["sandboxes"][0]["agent"] + let inference = value["spec"]["sandboxes"]["assistant"]["agent"] .as_object_mut() .unwrap() .remove("inference") .unwrap(); - value["spec"]["sandboxes"][0]["agent"]["inferenceRef"] = json!("chat"); + value["spec"]["sandboxes"]["assistant"]["agent"]["inferenceRef"] = json!("chat"); let scope = if sandbox { - &mut value["spec"]["sandboxes"][0] + &mut value["spec"]["sandboxes"]["assistant"] } else { &mut value["spec"] }; @@ -47,7 +47,7 @@ fn inference_reference_preserves_authored_scope_and_runtime_behavior() { ); let authored = serde_json::to_value(&doc).unwrap(); assert!( - authored["spec"]["sandboxes"][0]["agent"] + authored["spec"]["sandboxes"]["assistant"]["agent"] .get("inference") .is_none() ); @@ -56,13 +56,13 @@ fn inference_reference_preserves_authored_scope_and_runtime_behavior() { #[test] fn inference_references_reject_ambiguity_shadowing_and_invisible_providers() { let mut missing = shared(input(), false); - missing["spec"]["sandboxes"][0]["agent"]["inferenceRef"] = json!("missing"); + missing["spec"]["sandboxes"]["assistant"]["agent"]["inferenceRef"] = json!("missing"); let mut both = shared(input(), false); - both["spec"]["sandboxes"][0]["agent"]["inference"] = json!({}); + both["spec"]["sandboxes"]["assistant"]["agent"]["inference"] = json!({}); let mut shadow = shared(input(), false); - shadow["spec"]["sandboxes"][0]["inferences"] = shadow["spec"]["inferences"].clone(); + shadow["spec"]["sandboxes"]["assistant"]["inferences"] = shadow["spec"]["inferences"].clone(); let mut invisible = shared(input(), false); - invisible["spec"]["sandboxes"][0]["inferenceProviders"] = invisible["spec"] + invisible["spec"]["sandboxes"]["assistant"]["inferenceProviders"] = invisible["spec"] .as_object_mut() .unwrap() .remove("inferenceProviders") @@ -99,22 +99,18 @@ fn unused_inference_is_validated_but_adds_no_credentials_or_resources() { #[test] fn shared_inline_provider_is_one_instance_and_edits_stay_in_its_definition() { let mut value = input(); - let provider = value["spec"] + let mut provider = value["spec"] .as_object_mut() .unwrap() .remove("inferenceProviders") - .unwrap()[0] + .unwrap()["local"] .clone(); - let route = &mut value["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]; + provider["name"] = json!("local"); + let route = &mut value["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]; route.as_object_mut().unwrap().remove("providerRef"); route["provider"] = provider; let mut value = shared(value, false); - let mut other = value["spec"]["sandboxes"][0].clone(); - other["name"] = json!("other"); - value["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(other); + value["spec"]["sandboxes"]["other"] = value["spec"]["sandboxes"]["assistant"].clone(); let mut doc = Document::parse(value.to_string().as_bytes()).unwrap(); doc.inference_provider_mut().unwrap().endpoint = "http://127.0.0.1:19999/v1".into(); let authored = serde_json::to_value(&doc).unwrap(); @@ -132,8 +128,8 @@ fn shared_inline_provider_is_one_instance_and_edits_stay_in_its_definition() { fn shared_pi_metadata_accepts_opaque_nulls_only_inside_the_model() { let mut value: Value = serde_saphyr::from_str(include_str!("../../../examples/fabric-pi.yaml")).unwrap(); - value["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"]["settings"]["model_metadata"] - ["custom"] = Value::Null; + value["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["overrides"]["settings"] + ["model_metadata"]["custom"] = Value::Null; let mut value = shared(value, false); assert!(Document::parse(value.to_string().as_bytes()).is_ok()); value["spec"]["inferences"]["chat"]["routes"][0]["overrides"]["model"] = Value::Null; diff --git a/crates/nemoclaw-sdk/tests/inference_settings.rs b/crates/nemoclaw-sdk/tests/inference_settings.rs index 47517850629..42902738fc2 100644 --- a/crates/nemoclaw-sdk/tests/inference_settings.rs +++ b/crates/nemoclaw-sdk/tests/inference_settings.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; fn input(harness: &str) -> Value { let mut v: Value = serde_saphyr::from_str(include_str!("../../../examples/local.yaml")).unwrap(); - v["spec"]["sandboxes"][0]["harness"]["kind"] = json!(harness); + v["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!(harness); v } fn parse(v: &Value) -> Result { @@ -17,8 +17,9 @@ fn parse(v: &Value) -> Result { #[test] fn api_and_tuning_survive_compilation_and_yaml() { let mut v = input("openclaw"); - v["spec"]["inferenceProviders"][0]["api"] = json!("openai-responses"); - let route = &mut v["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"]; + v["spec"]["inferenceProviders"]["local"]["api"] = json!("openai-responses"); + let route = + &mut v["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["overrides"]; route["settings"]["contextWindow"] = json!(65536); route["maxTokens"] = json!(8192); route["settings"]["reasoning"] = json!(true); @@ -55,12 +56,12 @@ fn api_and_tuning_survive_compilation_and_yaml() { #[test] fn hermes_auth_requires_the_routed_credential_provider() { let mut v = input("hermes"); - v["spec"]["inferenceProviders"][0]["endpoint"] = + v["spec"]["inferenceProviders"]["local"]["endpoint"] = json!("https://inference-api.nousresearch.com/v1"); - v["spec"]["inferenceProviders"][0]["credential"] = json!({"env":"NOUS_API_KEY"}); - v["spec"]["sandboxes"][0]["agent"]["auth"] = json!({"method":"api-key"}); + v["spec"]["inferenceProviders"]["local"]["credential"] = json!({"env":"NOUS_API_KEY"}); + v["spec"]["sandboxes"]["assistant"]["agent"]["auth"] = json!({"method":"api-key"}); assert!(parse(&v).is_ok()); - v["spec"]["sandboxes"][0]["agent"]["auth"]["providerRef"] = json!("foreign"); + v["spec"]["sandboxes"]["assistant"]["agent"]["auth"]["providerRef"] = json!("foreign"); assert!(parse(&v).is_err()); } #[test] @@ -72,7 +73,8 @@ fn unsupported_or_out_of_range_options_fail_before_deployment() { ("reasoningEffort", json!("")), ] { let mut v = input("openclaw"); - v["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"][field] = value; + v["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["overrides"] + [field] = value; assert!(parse(&v).is_err()); assert!( !jsonschema::validator_for(&input_schema()) @@ -81,7 +83,7 @@ fn unsupported_or_out_of_range_options_fail_before_deployment() { ); } let mut v = input("deepagents"); - v["spec"]["inferenceProviders"][0]["api"] = json!("unrecognized-protocol"); + v["spec"]["inferenceProviders"]["local"]["api"] = json!("unrecognized-protocol"); assert!(parse(&v).is_err()); } @@ -95,8 +97,8 @@ fn explicit_apis_validate_transport_families_and_native_wire_requirements() { "anthropic-messages", ] { let mut v = input(harness); - v["spec"]["inferenceProviders"][0]["api"] = json!(api); - v["spec"]["inferenceProviders"][0]["provider"] = + v["spec"]["inferenceProviders"]["local"]["api"] = json!(api); + v["spec"]["inferenceProviders"]["local"]["provider"] = json!(if api == "anthropic-messages" { "anthropic" } else { @@ -105,7 +107,7 @@ fn explicit_apis_validate_transport_families_and_native_wire_requirements() { let accepted = true; assert_eq!(parse(&v).is_ok(), accepted, "{harness}/{api}"); assert!(validator.is_valid(&v), "structural schema {harness}/{api}"); - v["spec"]["inferenceProviders"][0]["provider"] = + v["spec"]["inferenceProviders"]["local"]["provider"] = json!(if api == "anthropic-messages" { "openai" } else { @@ -120,19 +122,20 @@ fn explicit_apis_validate_transport_families_and_native_wire_requirements() { #[test] fn explicit_false_and_default_survive_and_auth_cannot_bypass_credentials() { let mut v = input("openclaw"); - let overrides = &mut v["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"]; + let overrides = + &mut v["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["overrides"]; overrides["settings"]["reasoning"] = json!(false); overrides["settings"]["reasoning_effort"] = json!("default"); let d = parse(&v).unwrap(); let exported: Value = serde_saphyr::from_str(&d.yaml().unwrap()).unwrap(); assert_eq!( - exported["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"]["settings"] - ["reasoning"], + exported["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["overrides"] + ["settings"]["reasoning"], false ); for harness in ["hermes", "openclaw"] { let mut v = input(harness); - v["spec"]["sandboxes"][0]["agent"]["auth"] = json!({"method":"api-key"}); + v["spec"]["sandboxes"]["assistant"]["agent"]["auth"] = json!({"method":"api-key"}); assert!(parse(&v).is_err()); assert!( jsonschema::validator_for(&input_schema()) @@ -146,7 +149,8 @@ fn explicit_false_and_default_survive_and_auth_cannot_bypass_credentials() { ("unexpected", json!(true)), ] { let mut v = input("openclaw"); - v["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"][field] = value; + v["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["overrides"] + [field] = value; assert!(parse(&v).is_err()); assert!( !jsonschema::validator_for(&input_schema()) @@ -161,13 +165,13 @@ fn native_tuning_is_preserved_for_adapter_validation() { let schema = jsonschema::validator_for(&input_schema()).unwrap(); for harness in ["deepagents", "mini-swe-agent", "remote-agent"] { let mut v = input(harness); - v["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"]["maxTokens"] = + v["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["overrides"]["maxTokens"] = json!(128); let doc = parse(&v).unwrap(); assert!(schema.is_valid(&v), "{harness}"); assert_eq!(parse(&serde_json::to_value(&doc).unwrap()).unwrap(), doc); - v["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"]["settings"]["reasoning_effort"] = - json!("high"); + v["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["overrides"]["settings"] + ["reasoning_effort"] = json!("high"); assert!(parse(&v).is_ok()); assert!(schema.is_valid(&v)); } diff --git a/crates/nemoclaw-sdk/tests/interfaces.rs b/crates/nemoclaw-sdk/tests/interfaces.rs index 99da21bd493..9e3b802a192 100644 --- a/crates/nemoclaw-sdk/tests/interfaces.rs +++ b/crates/nemoclaw-sdk/tests/interfaces.rs @@ -12,7 +12,8 @@ fn adapter_defined_interfaces_survive_without_sdk_registration() { json!({"dashboard":{"port":8642,"bind":"127.0.0.1"}}), json!({"api":{"port":9000},"dashboard":{"enabled":false}}), ] { - value["spec"]["sandboxes"][0]["harness"]["settings"]["interfaces"] = interfaces.clone(); + value["spec"]["sandboxes"]["assistant"]["harness"]["settings"]["interfaces"] = + interfaces.clone(); let document = Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap(); assert_eq!( Document::parse(document.yaml().unwrap().as_bytes()).unwrap(), @@ -20,7 +21,7 @@ fn adapter_defined_interfaces_survive_without_sdk_registration() { ); assert_eq!( serde_json::to_value( - &document.spec.sandboxes[0] + &document.spec.sandboxes["assistant"] .harness .as_ref() .unwrap() @@ -40,7 +41,7 @@ fn interface_configuration_requires_an_object() { serde_saphyr::from_str(include_str!("../../../examples/local.yaml")).unwrap(); let validator = jsonschema::validator_for(&input_schema()).unwrap(); for invalid in [json!(null), json!([]), json!(true), json!("dashboard")] { - value["spec"]["sandboxes"][0]["harness"]["settings"] = invalid; + value["spec"]["sandboxes"]["assistant"]["harness"]["settings"] = invalid; assert!(!validator.is_valid(&value)); assert!(Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).is_err()); } diff --git a/crates/nemoclaw-sdk/tests/kubernetes_compile.rs b/crates/nemoclaw-sdk/tests/kubernetes_compile.rs index 284fac0ad5a..e5e0f0d7125 100644 --- a/crates/nemoclaw-sdk/tests/kubernetes_compile.rs +++ b/crates/nemoclaw-sdk/tests/kubernetes_compile.rs @@ -13,7 +13,8 @@ fn kubernetes_compiles_only_openshell_resources_and_checks_the_driver_before_mut Document::parse(include_bytes!("fixtures/config/local.yaml").as_slice()).unwrap(); let mut input = serde_json::to_value(original).unwrap(); input["spec"]["gateway"]["target"] = json!({"kubernetes": {}}); - input["spec"]["sandboxes"][0]["image"]["metadata"] = json!({"env":"TEST_IMAGE_METADATA"}); + input["spec"]["sandboxes"]["assistant"]["image"]["metadata"] = + json!({"env":"TEST_IMAGE_METADATA"}); let document = Document::parse(input.to_string().as_bytes()).unwrap(); let generations = ["workspace", "provider", "sandbox"] .map(|kind| (kind.into(), "a".repeat(32))) diff --git a/crates/nemoclaw-sdk/tests/kubernetes_managed_compile.rs b/crates/nemoclaw-sdk/tests/kubernetes_managed_compile.rs index d06f45ee17c..0845b9ac1c4 100644 --- a/crates/nemoclaw-sdk/tests/kubernetes_managed_compile.rs +++ b/crates/nemoclaw-sdk/tests/kubernetes_managed_compile.rs @@ -19,7 +19,8 @@ fn document() -> Document { "authentication":{"profile":"development"} }} }); - value["spec"]["sandboxes"][0]["image"]["metadata"] = json!({"env":"TEST_IMAGE_METADATA"}); + value["spec"]["sandboxes"]["assistant"]["image"]["metadata"] = + json!({"env":"TEST_IMAGE_METADATA"}); Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap() } diff --git a/crates/nemoclaw-sdk/tests/managed_hermes.rs b/crates/nemoclaw-sdk/tests/managed_hermes.rs index 30e2f603d21..600a39cdfb2 100644 --- a/crates/nemoclaw-sdk/tests/managed_hermes.rs +++ b/crates/nemoclaw-sdk/tests/managed_hermes.rs @@ -10,7 +10,7 @@ fn hermes_accepts_managed_gateway_and_inference() { include_str!("../../../examples/managed-ollama.yaml"), ] { let mut value: Value = serde_saphyr::from_str(source).unwrap(); - value["spec"]["sandboxes"][0]["harness"]["kind"] = "hermes".into(); + value["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = "hermes".into(); let document = Document::parse(serde_json::to_vec(&value).unwrap().as_slice()) .expect("Hermes native server supports managed services"); assert_eq!( diff --git a/crates/nemoclaw-sdk/tests/managed_podman.rs b/crates/nemoclaw-sdk/tests/managed_podman.rs index 9fa3325c478..3bcd77e0f45 100644 --- a/crates/nemoclaw-sdk/tests/managed_podman.rs +++ b/crates/nemoclaw-sdk/tests/managed_podman.rs @@ -45,12 +45,8 @@ fn managed_podman_selects_one_driver_and_mounts_the_declared_socket() { socket_mount.source.as_deref(), Some("/run/user/1000/podman/podman.sock") ); - let mut other = value["spec"]["sandboxes"][0].clone(); - other["name"] = json!("other"); + let mut other = value["spec"]["sandboxes"]["assistant"].clone(); other["runtime"]["provider"] = json!("docker"); - value["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(other); + value["spec"]["sandboxes"]["other"] = other; assert!(Document::parse(value.to_string().as_bytes()).is_err()); } diff --git a/crates/nemoclaw-sdk/tests/model_selection.rs b/crates/nemoclaw-sdk/tests/model_selection.rs index 0d55b3fbfe0..a06a4c9d7d3 100644 --- a/crates/nemoclaw-sdk/tests/model_selection.rs +++ b/crates/nemoclaw-sdk/tests/model_selection.rs @@ -36,7 +36,10 @@ fn a_different_model_uses_generic_serving_without_recipe_settings() { ] { assert!(!args.iter().any(|a| a == flag)); } - doc.spec.sandboxes[0] + doc.spec + .sandboxes + .get_mut("assistant") + .unwrap() .agent .inference .as_mut() diff --git a/crates/nemoclaw-sdk/tests/multiple_models.rs b/crates/nemoclaw-sdk/tests/multiple_models.rs index 5ec7cedc23c..eba6ab28548 100644 --- a/crates/nemoclaw-sdk/tests/multiple_models.rs +++ b/crates/nemoclaw-sdk/tests/multiple_models.rs @@ -10,7 +10,7 @@ fn input() -> Value { } fn choices() -> Value { let mut value = input(); - let inference = &mut value["spec"]["sandboxes"][0]["agent"]["inference"]; + let inference = &mut value["spec"]["sandboxes"]["assistant"]["agent"]["inference"]; let mut fast = inference["routes"][0].clone(); fast["name"] = json!("fast"); fast["overrides"]["model"] = json!("fast-model"); @@ -21,13 +21,9 @@ fn choices() -> Value { #[test] fn multiple_models_preserve_named_choices_and_each_agents_default() { let mut value = choices(); - let mut other = value["spec"]["sandboxes"][0].clone(); - other["name"] = json!("other"); + let mut other = value["spec"]["sandboxes"]["assistant"].clone(); other["agent"]["inference"]["default"] = json!("primary"); - value["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(other); + value["spec"]["sandboxes"]["other"] = other; let doc = Document::parse(value.to_string().as_bytes()).expect("multiple named models"); assert!( jsonschema::validator_for(&input_schema()) @@ -70,16 +66,17 @@ fn multiple_models_preserve_named_choices_and_each_agents_default() { #[test] fn ambiguous_defaults_and_duplicate_choices_are_rejected() { let mut missing = choices(); - missing["spec"]["sandboxes"][0]["agent"]["inference"] + missing["spec"]["sandboxes"]["assistant"]["agent"]["inference"] .as_object_mut() .unwrap() .remove("default"); let mut unknown = choices(); - unknown["spec"]["sandboxes"][0]["agent"]["inference"]["default"] = json!("missing"); + unknown["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["default"] = json!("missing"); let mut duplicate = choices(); - duplicate["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][1]["name"] = json!("primary"); + duplicate["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][1]["name"] = + json!("primary"); let mut hermes = choices(); - hermes["spec"]["sandboxes"][0]["harness"]["kind"] = json!("hermes"); + hermes["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!("hermes"); assert!(Document::parse(hermes.to_string().as_bytes()).is_ok()); for value in [missing, unknown, duplicate] { assert!(Document::parse(value.to_string().as_bytes()).is_err()); @@ -90,15 +87,11 @@ fn ambiguous_defaults_and_duplicate_choices_are_rejected() { fn pi_choices_preserve_native_metadata_and_provider_credentials() { let mut value: Value = serde_saphyr::from_str(include_str!("../../../examples/fabric-pi.yaml")).unwrap(); - let mut provider = value["spec"]["inferenceProviders"][0].clone(); - provider["name"] = json!("hosted"); + let mut provider = value["spec"]["inferenceProviders"]["local"].clone(); provider["endpoint"] = json!("https://hosted.example/v1"); provider["credential"] = json!({"env":"HOSTED_KEY"}); - value["spec"]["inferenceProviders"] - .as_array_mut() - .unwrap() - .push(provider); - let inference = &mut value["spec"]["sandboxes"][0]["agent"]["inference"]; + value["spec"]["inferenceProviders"]["hosted"] = provider; + let inference = &mut value["spec"]["sandboxes"]["assistant"]["agent"]["inference"]; let mut hosted = inference["routes"][0].clone(); hosted["name"] = json!("smart"); hosted["providerRef"] = json!("hosted"); diff --git a/crates/nemoclaw-sdk/tests/multiple_providers.rs b/crates/nemoclaw-sdk/tests/multiple_providers.rs index 4b53d31aabb..190311f0e0f 100644 --- a/crates/nemoclaw-sdk/tests/multiple_providers.rs +++ b/crates/nemoclaw-sdk/tests/multiple_providers.rs @@ -19,9 +19,15 @@ fn generations() -> Generations { .map(|key| (key.into(), "a".repeat(32))) .into() } +/// The name of the example's only deployment provider. +fn only_provider(value: &Value) -> String { + let providers = value["spec"]["inferenceProviders"].as_object().unwrap(); + assert_eq!(providers.len(), 1); + providers.keys().next().unwrap().clone() +} fn hosted(mut value: Value) -> Value { - value["spec"]["inferenceProviders"].as_array_mut().unwrap().push(json!({"name":"hosted","provider":"anthropic","api":"anthropic-messages","endpoint":"https://hosted.example/v1","credential":{"env":"HOSTED_KEY"}})); - let inference = &mut value["spec"]["sandboxes"][0]["agent"]["inference"]; + value["spec"]["inferenceProviders"]["hosted"] = json!({"provider":"anthropic","api":"anthropic-messages","endpoint":"https://hosted.example/v1","credential":{"env":"HOSTED_KEY"}}); + let inference = &mut value["spec"]["sandboxes"]["assistant"]["agent"]["inference"]; inference["default"] = json!("smart"); inference["routes"] .as_array_mut() @@ -34,8 +40,7 @@ fn a_sandbox_attaches_the_union_of_selected_providers_with_bound_credentials() { let input: Value = serde_saphyr::from_str(include_str!("../../../examples/fabric-openclaw.yaml")).unwrap(); let mut value = hosted(input); - let mut other = value["spec"]["sandboxes"][0].clone(); - other["name"] = json!("other"); + let mut other = value["spec"]["sandboxes"]["assistant"].clone(); other["agent"]["inference"]["routes"] .as_array_mut() .unwrap() @@ -44,10 +49,7 @@ fn a_sandbox_attaches_the_union_of_selected_providers_with_bound_credentials() { .as_object_mut() .unwrap() .remove("default"); - value["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(other); + value["spec"]["sandboxes"]["other"] = other; let doc = Document::parse(value.to_string().as_bytes()).expect("local and hosted providers"); assert!( jsonschema::validator_for(&input_schema()) @@ -139,10 +141,7 @@ fn a_sandbox_attaches_the_union_of_selected_providers_with_bound_credentials() { fn managed_inference_remains_owned_when_the_default_uses_a_hosted_provider() { let mut value: Value = serde_saphyr::from_str(include_str!("../../../examples/spark/vllm.yaml")).unwrap(); - let local_name = value["spec"]["inferenceProviders"][0]["name"] - .as_str() - .unwrap() - .to_owned(); + let local_name = only_provider(&value); value["spec"]["services"]["qwen"]["authentication"] = json!("bearer"); let doc = Document::parse(hosted(value).to_string().as_bytes()) .expect("managed local model plus external default"); @@ -172,10 +171,7 @@ fn managed_inference_remains_owned_when_the_default_uses_a_hosted_provider() { fn managed_ollama_installs_while_an_external_provider_is_the_default() { let value: Value = serde_saphyr::from_str(include_str!("../../../examples/managed-ollama.yaml")).unwrap(); - let local_name = value["spec"]["inferenceProviders"][0]["name"] - .as_str() - .unwrap() - .to_owned(); + let local_name = only_provider(&value); let doc = Document::parse(hosted(value).to_string().as_bytes()).unwrap(); let runtime = runtime_targets(&doc, &generations()).unwrap(); assert!( @@ -207,17 +203,13 @@ fn managed_ollama_installs_while_an_external_provider_is_the_default() { fn multiple_selected_ollama_installers_have_independent_resources_and_dependencies() { let mut value: Value = serde_saphyr::from_str(include_str!("../../../examples/managed-ollama.yaml")).unwrap(); - let mut other = value["spec"]["inferenceProviders"][0].clone(); - other["name"] = json!("other"); + let mut other = value["spec"]["inferenceProviders"]["local"].clone(); other["serviceRef"] = json!("other"); let mut other_service = value["spec"]["services"]["ollama-server"].clone(); other_service["serving"]["port"] = json!(18999); value["spec"]["services"]["other"] = other_service; - value["spec"]["inferenceProviders"] - .as_array_mut() - .unwrap() - .push(other); - let inference = &mut value["spec"]["sandboxes"][0]["agent"]["inference"]; + value["spec"]["inferenceProviders"]["other"] = other; + let inference = &mut value["spec"]["sandboxes"]["assistant"]["agent"]["inference"]; inference["default"] = json!("primary"); let mut route = inference["routes"][0].clone(); route["name"] = json!("other"); @@ -245,22 +237,15 @@ fn multiple_selected_ollama_installers_have_independent_resources_and_dependenci fn managed_services_have_independent_storage_credentials_and_dependencies() { let mut value: Value = serde_saphyr::from_str(include_str!("../../../examples/spark/vllm.yaml")).unwrap(); - let first = value["spec"]["inferenceProviders"][0]["name"] - .as_str() - .unwrap() - .to_owned(); + let first = only_provider(&value); value["spec"]["services"]["qwen"]["authentication"] = json!("bearer"); - let mut other = value["spec"]["inferenceProviders"][0].clone(); - other["name"] = json!("other"); + let mut other = value["spec"]["inferenceProviders"][&first].clone(); other["serviceRef"] = json!("other"); let mut other_service = value["spec"]["services"]["qwen"].clone(); other_service["serving"]["port"] = json!(18999); value["spec"]["services"]["other"] = other_service; - value["spec"]["inferenceProviders"] - .as_array_mut() - .unwrap() - .push(other); - let inference = &mut value["spec"]["sandboxes"][0]["agent"]["inference"]; + value["spec"]["inferenceProviders"]["other"] = other; + let inference = &mut value["spec"]["sandboxes"]["assistant"]["agent"]["inference"]; inference["default"] = json!("primary"); let mut route = inference["routes"][0].clone(); route["name"] = json!("other"); diff --git a/crates/nemoclaw-sdk/tests/multiple_sandboxes.rs b/crates/nemoclaw-sdk/tests/multiple_sandboxes.rs index 20d0544d5f8..24d07a39f4a 100644 --- a/crates/nemoclaw-sdk/tests/multiple_sandboxes.rs +++ b/crates/nemoclaw-sdk/tests/multiple_sandboxes.rs @@ -22,23 +22,22 @@ fn example() -> Value { serde_saphyr::from_str(include_str!("../../../examples/fabric-openclaw.yaml")).unwrap() } fn graph(value: &Value) -> Value { + compiled(&value.to_string()) +} +fn compiled(text: &str) -> Value { compile( - &Document::parse(value.to_string().as_bytes()).unwrap(), + &Document::parse(text.as_bytes()).unwrap(), &generations(), "0.1.0", ) .unwrap() } #[test] -fn different_adapters_separate_provider_grants_and_ignore_declaration_order() { +fn different_adapters_separate_provider_grants() { let mut value = example(); - let mut other = value["spec"]["sandboxes"][0].clone(); - other["name"] = json!("research"); + let mut other = value["spec"]["sandboxes"]["assistant"].clone(); other["harness"] = json!({"kind":"deepagents"}); - value["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(other); + value["spec"]["sandboxes"]["research"] = other; assert!( jsonschema::validator_for(&nemoclaw_sdk::config::schema::input_schema()) .unwrap() @@ -59,50 +58,20 @@ fn different_adapters_separate_provider_grants_and_ignore_declaration_order() { .len(), 2 ); - value["spec"]["sandboxes"].as_array_mut().unwrap().reverse(); - assert_eq!(before, graph(&value)); -} -#[test] -fn sandbox_and_provider_order_do_not_change_compiled_identity_or_settings() { - let mut value = example(); - let mut other = value["spec"]["sandboxes"][0].clone(); - other["name"] = json!("bob"); - let mut provider = value["spec"]["inferenceProviders"][0].clone(); - provider["name"] = json!("other-models"); - provider["endpoint"] = json!("http://172.20.0.1:11447/v1"); - value["spec"]["inferenceProviders"] - .as_array_mut() - .unwrap() - .push(provider); - other["agent"]["inference"]["routes"][0]["providerRef"] = json!("other-models"); - value["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(other); - let before = graph(&value); - value["spec"]["sandboxes"].as_array_mut().unwrap().reverse(); - value["spec"]["inferenceProviders"] - .as_array_mut() - .unwrap() - .reverse(); - assert_eq!(before, graph(&value)); } #[test] fn sandbox_local_provider_and_inference_names_do_not_escape_their_scope() { let mut value = example(); - let provider = value["spec"]["inferenceProviders"] - .as_array_mut() - .unwrap() - .remove(0); - value["spec"]["sandboxes"][0]["inferenceProviders"] = json!([provider]); - let mut other = value["spec"]["sandboxes"][0].clone(); - other["name"] = json!("other"); - other["inferenceProviders"][0]["endpoint"] = json!("http://172.20.0.1:11447/v1"); - value["spec"]["sandboxes"] - .as_array_mut() + let providers = value["spec"] + .as_object_mut() .unwrap() - .push(other); + .remove("inferenceProviders") + .unwrap(); + value["spec"]["sandboxes"]["assistant"]["inferenceProviders"] = providers; + let mut other = value["spec"]["sandboxes"]["assistant"].clone(); + other["inferenceProviders"]["local"]["endpoint"] = json!("http://172.20.0.1:11447/v1"); + value["spec"]["sandboxes"]["other"] = other; let before = graph(&value); let providers = before["resource"]["openshell_provider_registration"] .as_object() @@ -112,20 +81,13 @@ fn sandbox_local_provider_and_inference_names_do_not_escape_their_scope() { providers.values().next().unwrap()["name"], providers.values().next_back().unwrap()["name"] ); - value["spec"]["sandboxes"].as_array_mut().unwrap().reverse(); - assert_eq!(before, graph(&value)); } #[test] fn adding_a_sandbox_preserves_existing_resource_addresses_and_values() { let mut value = example(); let before = graph(&value); - let mut other = value["spec"]["sandboxes"][0].clone(); - other["name"] = json!("additional"); - value["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(other); + value["spec"]["sandboxes"]["additional"] = value["spec"]["sandboxes"]["assistant"].clone(); let after = graph(&value); for (kind, instances) in before["resource"].as_object().unwrap() { for (name, instance) in instances.as_object().unwrap() { @@ -142,24 +104,20 @@ fn adding_a_sandbox_preserves_existing_resource_addresses_and_values() { } #[test] -fn reordering_named_declarations_preserves_pending_intent_digest() { +fn reversed_sandbox_and_provider_keys_parse_to_the_same_document_and_digest() { let mut value = example(); - let mut other = value["spec"]["sandboxes"][0].clone(); - other["name"] = json!("another"); - value["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(other); - let before = Document::parse(value.to_string().as_bytes()) - .unwrap() - .digest(); - value["spec"]["sandboxes"].as_array_mut().unwrap().reverse(); - assert_eq!( - before, - Document::parse(value.to_string().as_bytes()) - .unwrap() - .digest() - ); + let mut other = value["spec"]["sandboxes"]["assistant"].clone(); + let mut provider = value["spec"]["inferenceProviders"]["local"].clone(); + provider["endpoint"] = json!("http://172.20.0.1:11447/v1"); + value["spec"]["inferenceProviders"]["other-models"] = provider; + other["agent"]["inference"]["routes"][0]["providerRef"] = json!("other-models"); + value["spec"]["sandboxes"]["bob"] = other; + let document = Document::parse(value.to_string().as_bytes()).unwrap(); + let reversed = + crate::support::reversed(&value, &["/spec/sandboxes", "/spec/inferenceProviders"]); + let reversed = Document::parse(reversed.as_bytes()).unwrap(); + assert_eq!(document, reversed); + assert_eq!(document.digest(), reversed.digest()); } #[test] @@ -181,19 +139,17 @@ fn five_agent_example_compiles_to_five_independent_sandboxes_sharing_inference() assert_eq!(sandboxes.len(), 5); assert_eq!(rows.iter().filter(|row| row.kind == "provider").count(), 3); let mut counts = std::collections::BTreeMap::new(); - let mut names = std::collections::BTreeSet::new(); - for sandbox in &document.spec.sandboxes { - let harness = document.sandbox_harness(sandbox).unwrap(); + for (name, sandbox) in &document.spec.sandboxes { + let harness = document.sandbox_harness(name).unwrap(); *counts.entry(harness.kind.as_str()).or_insert(0) += 1; - assert!(names.insert(sandbox.name.as_str())); let row = sandboxes .iter() - .find(|row| row.values["name"] == sandbox.name) + .find(|row| &row.values["name"] == name) .unwrap(); let configuration = rows .iter() .find(|candidate| { - candidate.kind == "agent_configuration" && candidate.values["name"] == sandbox.name + candidate.kind == "agent_configuration" && &candidate.values["name"] == name }) .unwrap(); let settings: Value = serde_json::from_str(&configuration.values["config_json"]).unwrap(); @@ -212,17 +168,11 @@ fn five_agent_example_compiles_to_five_independent_sandboxes_sharing_inference() } #[test] -fn managed_discovery_preserves_request_identity_when_sandboxes_are_reordered() { +fn managed_discovery_compiles_a_second_sandbox_with_another_adapter() { let mut value: Value = serde_saphyr::from_str(include_str!("../../../examples/onboarding/openclaw.yaml")).unwrap(); - let mut other = value["spec"]["sandboxes"][0].clone(); - other["name"] = json!("research"); + let mut other = value["spec"]["sandboxes"]["assistant"].clone(); other["harness"] = json!({"kind":"deepagents"}); - value["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(other); - let before = graph(&value); - value["spec"]["sandboxes"].as_array_mut().unwrap().reverse(); - assert_eq!(before, graph(&value)); + value["spec"]["sandboxes"]["research"] = other; + graph(&value); } diff --git a/crates/nemoclaw-sdk/tests/native_inference.rs b/crates/nemoclaw-sdk/tests/native_inference.rs index 9a04956856a..dda8ba61be6 100644 --- a/crates/nemoclaw-sdk/tests/native_inference.rs +++ b/crates/nemoclaw-sdk/tests/native_inference.rs @@ -40,10 +40,27 @@ fn explicit_protocol_is_preserved_for_selected_image_validation() { use nemoclaw_sdk::config::{InferenceApi, InferenceProviderKind}; let mut document = Document::parse(include_str!("fixtures/config/local.yaml").as_bytes()).unwrap(); - document.spec.sandboxes[0].harness.as_mut().unwrap().kind = - "nvidia.fabric.codex".parse().unwrap(); - document.spec.inference_providers[0].api = Some(InferenceApi::AnthropicMessages); - document.spec.inference_providers[0].provider = InferenceProviderKind::Anthropic; + document + .spec + .sandboxes + .get_mut("assistant") + .unwrap() + .harness + .as_mut() + .unwrap() + .kind = "nvidia.fabric.codex".parse().unwrap(); + document + .spec + .inference_providers + .get_mut("local") + .unwrap() + .api = Some(InferenceApi::AnthropicMessages); + document + .spec + .inference_providers + .get_mut("local") + .unwrap() + .provider = InferenceProviderKind::Anthropic; document.validate().unwrap(); let generations: Generations = ["workspace", "provider", "sandbox"] .map(|key| (key.into(), "a".repeat(32))) diff --git a/crates/nemoclaw-sdk/tests/nemotron_serving.rs b/crates/nemoclaw-sdk/tests/nemotron_serving.rs index c18f9955366..ea4e605c2e8 100644 --- a/crates/nemoclaw-sdk/tests/nemotron_serving.rs +++ b/crates/nemoclaw-sdk/tests/nemotron_serving.rs @@ -20,7 +20,7 @@ fn input() -> Value { "serving":{"modelName":"nvidia-nemotron-3.5-lightning-30b-a3b-nvfp4","contextTokens":65536,"maxSequences":1,"batchTokens":4096,"mambaBackend":"flashinfer","toolParser":"qwen3_coder","reasoningParser":"nemotron_v3","enforceEager":false,"startupTimeoutSeconds":1800}, "memory":{"gpuMemoryUtilization":0.75} }); - value["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["overrides"]["model"] = + value["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["overrides"]["model"] = json!("nvidia-nemotron-3.5-lightning-30b-a3b-nvfp4"); value } diff --git a/crates/nemoclaw-sdk/tests/network_config.rs b/crates/nemoclaw-sdk/tests/network_config.rs index 7037f857f75..e8740cc4135 100644 --- a/crates/nemoclaw-sdk/tests/network_config.rs +++ b/crates/nemoclaw-sdk/tests/network_config.rs @@ -9,7 +9,7 @@ use serde_json::{Value, json}; fn input() -> Value { let mut value: Value = serde_saphyr::from_str(include_str!("../../../examples/local.yaml")).unwrap(); - value["spec"]["sandboxes"][0]["network"] = json!({ + value["spec"]["sandboxes"]["assistant"]["network"] = json!({ "policy": {"explicit": { "version": 1, "filesystem_policy": {"include_workdir": false, "read_only": ["/usr", "/opt", "/app"], "read_write": ["/sandbox", "/tmp"]}, @@ -26,7 +26,8 @@ fn parse(value: &Value) -> Result { #[test] fn sandbox_proxy_override_is_rejected_before_deployment() { let mut value = input(); - value["spec"]["sandboxes"][0]["network"]["proxy"] = json!({"host": "10.200.0.1", "port": 3129}); + value["spec"]["sandboxes"]["assistant"]["network"]["proxy"] = + json!({"host": "10.200.0.1", "port": 3129}); assert!( parse(&value).is_err(), "sandbox proxy overrides must not replace OpenShell's policy proxy" @@ -68,13 +69,13 @@ fn explicit_policy_survives_yaml_and_compilation() { #[test] fn conflicting_unknown_and_invalid_network_settings_are_rejected() { for (path, replacement) in [ - ("/spec/sandboxes/0/network/tier", json!("isolated")), + ("/spec/sandboxes/assistant/network/tier", json!("isolated")), ( - "/spec/sandboxes/0/network/policy/explicit/version", + "/spec/sandboxes/assistant/network/policy/explicit/version", json!(0), ), ( - "/spec/sandboxes/0/network/policy/explicit/network_policies/docs/endpoints/0/port", + "/spec/sandboxes/assistant/network/policy/explicit/network_policies/docs/endpoints/0/port", json!(0), ), ] { @@ -84,8 +85,8 @@ fn conflicting_unknown_and_invalid_network_settings_are_rejected() { assert!(parse(&value).is_err(), "{path}"); } let mut value = input(); - value["spec"]["sandboxes"][0]["network"]["policy"]["explicit"]["network_policies"]["docs"]["endpoints"] - [0]["credentials"] = json!("secret"); + value["spec"]["sandboxes"]["assistant"]["network"]["policy"]["explicit"]["network_policies"] + ["docs"]["endpoints"][0]["credentials"] = json!("secret"); let error = parse(&value).unwrap_err(); assert!(!error.to_string().contains("secret")); } @@ -100,8 +101,8 @@ fn policy_rejects_silently_ignored_or_ambiguous_endpoint_options() { ("mcp", json!({"max_body_bytes": 0})), ] { let mut document = input(); - document["spec"]["sandboxes"][0]["network"]["policy"]["explicit"]["network_policies"]["docs"] - ["endpoints"][0][field] = value; + document["spec"]["sandboxes"]["assistant"]["network"]["policy"]["explicit"]["network_policies"] + ["docs"]["endpoints"][0][field] = value; assert!(parse(&document).is_err(), "must reject {field}"); } } @@ -119,22 +120,29 @@ fn explicit_policy_supports_tcp_rest_websocket_rpc_mcp_and_deny_all() { let validator = jsonschema::validator_for(&input_schema()).unwrap(); for endpoint in endpoints { let mut value = input(); - value["spec"]["sandboxes"][0]["network"]["policy"]["explicit"]["network_policies"]["docs"] - ["endpoints"][0] = endpoint.clone(); + value["spec"]["sandboxes"]["assistant"]["network"]["policy"]["explicit"]["network_policies"] + ["docs"]["endpoints"][0] = endpoint.clone(); assert!(validator.is_valid(&value), "schema: {endpoint}"); let document = parse(&value).unwrap_or_else(|e| panic!("{endpoint}: {e}")); - let proto = document.spec.sandboxes[0].network.policy_proto().unwrap(); + let proto = document.spec.sandboxes["assistant"] + .network + .policy_proto() + .unwrap(); assert!( nemoclaw_sdk::config::policy_json(&proto).is_ok(), "observation must retain {endpoint}" ); } let mut value = input(); - value["spec"]["sandboxes"][0]["network"]["policy"]["explicit"]["network_policies"] = json!({}); + value["spec"]["sandboxes"]["assistant"]["network"]["policy"]["explicit"]["network_policies"] = + json!({}); let document = parse(&value).unwrap(); assert!( nemoclaw_sdk::config::policy_json( - &document.spec.sandboxes[0].network.policy_proto().unwrap() + &document.spec.sandboxes["assistant"] + .network + .policy_proto() + .unwrap() ) .is_ok() ); @@ -143,8 +151,8 @@ fn explicit_policy_supports_tcp_rest_websocket_rpc_mcp_and_deny_all() { #[test] fn policy_template_markers_remain_literal_in_opentofu_configuration() { let mut value = input(); - value["spec"]["sandboxes"][0]["network"]["policy"]["explicit"]["network_policies"]["docs"]["endpoints"] - [0]["rules"][0]["allow"]["path"] = json!("/docs/${file}/%{literal}"); + value["spec"]["sandboxes"]["assistant"]["network"]["policy"]["explicit"]["network_policies"] + ["docs"]["endpoints"][0]["rules"][0]["allow"]["path"] = json!("/docs/${file}/%{literal}"); let document = parse(&value).unwrap(); let generations: Generations = ["workspace", "provider", "sandbox"] .map(|k| (k.into(), format!("{k}-generation"))) @@ -174,12 +182,12 @@ fn document_validation_preserves_filesystem_intent_until_image_discovery() { json!(["/opt", "/app"]), ] { let mut value = input(); - value["spec"]["sandboxes"][0]["network"]["policy"]["explicit"]["filesystem_policy"]["read_only"] = - grants; + value["spec"]["sandboxes"]["assistant"]["network"]["policy"]["explicit"]["filesystem_policy"] + ["read_only"] = grants; let document = parse(&value).unwrap(); assert_eq!( - serde_json::to_value(&document.spec.sandboxes[0].network).unwrap()["policy"], - value["spec"]["sandboxes"][0]["network"]["policy"] + serde_json::to_value(&document.spec.sandboxes["assistant"].network).unwrap()["policy"], + value["spec"]["sandboxes"]["assistant"]["network"]["policy"] ); } } @@ -189,7 +197,7 @@ fn landlock_uses_runtime_spellings_without_main_branch_aliases() { let validator = jsonschema::validator_for(&input_schema()).unwrap(); for spelling in ["best_effort", "hard_requirement", "strict"] { let mut value = input(); - value["spec"]["sandboxes"][0]["network"]["policy"]["explicit"]["landlock"]["compatibility"] = + value["spec"]["sandboxes"]["assistant"]["network"]["policy"]["explicit"]["landlock"]["compatibility"] = json!(spelling); if spelling == "strict" { assert!( @@ -201,7 +209,7 @@ fn landlock_uses_runtime_spellings_without_main_branch_aliases() { assert!(validator.is_valid(&value)); let document = parse(&value).unwrap(); assert_eq!( - document.spec.sandboxes[0] + document.spec.sandboxes["assistant"] .network .policy_proto() .unwrap() @@ -216,7 +224,7 @@ fn landlock_uses_runtime_spellings_without_main_branch_aliases() { #[test] fn network_deserialization_rejects_conflicting_policy_choices() { - let explicit = input()["spec"]["sandboxes"][0]["network"]["policy"].clone(); + let explicit = input()["spec"]["sandboxes"]["assistant"]["network"]["policy"].clone(); for value in [ json!({"tier": "isolated", "policy": explicit}), json!({"tier": "unrestricted"}), @@ -244,7 +252,7 @@ fn default_network_is_a_valid_isolated_policy() { #[test] fn policy_choice_preserves_the_export_shape() { - let explicit_input = input()["spec"]["sandboxes"][0]["network"]["policy"].clone(); + let explicit_input = input()["spec"]["sandboxes"]["assistant"]["network"]["policy"].clone(); let explicit = serde_json::from_value(explicit_input["explicit"].clone()).unwrap(); for (policy, expected) in [ (NetworkPolicy::Isolated, json!({"tier": "isolated"})), @@ -266,7 +274,8 @@ fn policy_choice_preserves_the_export_shape() { #[test] fn removed_tls_modes_are_rejected_and_automatic_tls_round_trips() { let mut value = input(); - let endpoint = "/spec/sandboxes/0/network/policy/explicit/network_policies/docs/endpoints/0"; + let endpoint = + "/spec/sandboxes/assistant/network/policy/explicit/network_policies/docs/endpoints/0"; value .pointer_mut(endpoint) .unwrap() diff --git a/crates/nemoclaw-sdk/tests/observability.rs b/crates/nemoclaw-sdk/tests/observability.rs index 0ff0a2117d9..e885cc8740e 100644 --- a/crates/nemoclaw-sdk/tests/observability.rs +++ b/crates/nemoclaw-sdk/tests/observability.rs @@ -11,7 +11,7 @@ fn native_telemetry_settings_are_opaque_and_do_not_implicitly_grant_network_acce let mut input: Value = serde_saphyr::from_str(include_str!("fixtures/config/local.yaml")).unwrap(); let settings = json!({"telemetry":{"future":null,"service":"agent ${fixture} %{literal}"}}); - input["spec"]["sandboxes"][0]["harness"]["settings"] = settings.clone(); + input["spec"]["sandboxes"]["assistant"]["harness"]["settings"] = settings.clone(); let document = Document::parse(input.to_string().as_bytes()).unwrap(); let generations: Generations = ["workspace", "provider", "sandbox"] .map(|key| (key.into(), "a".repeat(32))) @@ -41,8 +41,7 @@ fn native_telemetry_settings_are_opaque_and_do_not_implicitly_grant_network_acce .contains_key("nemoclaw-otlp") ); let graph = compile(&document, &generations, "0.1.0").unwrap(); - let encoded = graph["resource"]["fabric_agent_configuration"][&document.spec.sandboxes[0].name] - ["config_json"] + let encoded = graph["resource"]["fabric_agent_configuration"]["assistant"]["config_json"] .as_str() .unwrap(); assert!(encoded.contains("agent $${fixture} %%{literal}")); diff --git a/crates/nemoclaw-sdk/tests/ollama_proxy.rs b/crates/nemoclaw-sdk/tests/ollama_proxy.rs index dd11c0233c8..ba41c985957 100644 --- a/crates/nemoclaw-sdk/tests/ollama_proxy.rs +++ b/crates/nemoclaw-sdk/tests/ollama_proxy.rs @@ -9,7 +9,7 @@ use serde_json::{Value, json}; fn input() -> Value { let mut value: Value = serde_saphyr::from_str(include_str!("fixtures/config/managed-ollama.yaml")).unwrap(); - let provider = &mut value["spec"]["inferenceProviders"][0]; + let provider = &mut value["spec"]["inferenceProviders"]["local"]; provider["serviceRef"] = json!("ollama-auth"); value["spec"]["services"] = json!({"ollama-auth": { "kind":"ollamaProxy", @@ -74,19 +74,11 @@ fn explicit_proxy_engine_works_with_an_external_gateway() { #[test] fn proxy_readiness_is_fresh_and_orders_only_its_selected_consumer() { let mut value = input(); - value["spec"]["inferenceProviders"] - .as_array_mut() - .unwrap() - .push(json!({ - "name":"other", "provider":"openai", "endpoint":"http://127.0.0.1:11436/v1" - })); - let mut second = value["spec"]["sandboxes"][0].clone(); - second["name"] = json!("other"); + value["spec"]["inferenceProviders"]["other"] = + json!({"provider":"openai", "endpoint":"http://127.0.0.1:11436/v1"}); + let mut second = value["spec"]["sandboxes"]["assistant"].clone(); second["agent"]["inference"]["routes"][0]["providerRef"] = json!("other"); - value["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(second); + value["spec"]["sandboxes"]["other"] = second; let document = Document::parse(value.to_string().as_bytes()).unwrap(); let generations: Generations = ["workspace", "provider", "sandbox", "ollama_proxy"] .map(|key| (key.into(), "a".repeat(32))) @@ -289,7 +281,7 @@ fn proxy_rejects_unpinned_models_nonlocal_daemons_and_ambiguous_ownership() { ("credential", json!({"env":"API_KEY"})), ] { let mut value = input(); - value["spec"]["inferenceProviders"][0][field] = bad; + value["spec"]["inferenceProviders"]["local"][field] = bad; assert!(Document::parse(value.to_string().as_bytes()).is_err()); } let schema = jsonschema::validator_for(&input_schema()).unwrap(); @@ -311,7 +303,7 @@ fn proxy_rejects_unpinned_models_nonlocal_daemons_and_ambiguous_ownership() { fn deep_agents_and_pi_use_authenticated_ollama_proxy_connections() { for harness in ["deepagents", "pi"] { let mut value = input(); - value["spec"]["sandboxes"][0]["harness"]["kind"] = json!(harness); + value["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!(harness); let doc = Document::parse(value.to_string().as_bytes()).unwrap(); assert!( jsonschema::validator_for(&input_schema()) @@ -341,13 +333,9 @@ fn named_proxies_have_distinct_containers_storage_and_credentials() { let mut second = value["spec"]["services"]["ollama-auth"].clone(); second["endpoint"] = json!("http://172.20.0.1:11436/v1"); value["spec"]["services"]["second"] = second; - let mut provider = value["spec"]["inferenceProviders"][0].clone(); - provider["name"] = json!("second"); + let mut provider = value["spec"]["inferenceProviders"]["local"].clone(); provider["serviceRef"] = json!("second"); - value["spec"]["inferenceProviders"] - .as_array_mut() - .unwrap() - .push(provider); + value["spec"]["inferenceProviders"]["second"] = provider; let doc = Document::parse(value.to_string().as_bytes()).unwrap(); let gens: Generations = ["workspace", "provider", "sandbox", "ollama_proxy"] .map(|key| (key.into(), "a".repeat(32))) @@ -368,7 +356,7 @@ fn named_proxies_have_distinct_containers_storage_and_credentials() { } let first = serde_json::to_value(&doc).unwrap(); let mut changed = first; - changed["spec"]["inferenceProviders"][0]["serviceRef"] = json!("second"); + changed["spec"]["inferenceProviders"]["local"]["serviceRef"] = json!("second"); let doc = Document::parse(changed.to_string().as_bytes()).unwrap(); let other = compile(&doc, &gens, "0.1.0").unwrap(); assert_ne!( diff --git a/crates/nemoclaw-sdk/tests/provider_references.rs b/crates/nemoclaw-sdk/tests/provider_references.rs index c9cbb74db54..4361c89471a 100644 --- a/crates/nemoclaw-sdk/tests/provider_references.rs +++ b/crates/nemoclaw-sdk/tests/provider_references.rs @@ -11,13 +11,20 @@ use serde_json::{Value, json}; fn input() -> Value { crate::support::example("fabric-openclaw.yaml") } +/// Moves the example's only provider into its first route; an inline +/// provider carries its name instead of a key. fn inline(mut value: Value) -> Value { - let provider = value["spec"]["inferenceProviders"][0].clone(); - value["spec"] + let providers = value["spec"] .as_object_mut() .unwrap() - .remove("inferenceProviders"); - let route = &mut value["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]; + .remove("inferenceProviders") + .unwrap(); + let providers = providers.as_object().unwrap(); + assert_eq!(providers.len(), 1); + let (name, provider) = providers.iter().next().unwrap(); + let mut provider = provider.clone(); + provider["name"] = json!(name); + let route = &mut value["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]; route.as_object_mut().unwrap().remove("providerRef"); route["provider"] = provider; value @@ -26,7 +33,7 @@ fn inline(mut value: Value) -> Value { fn provider_declaration_scope_preserves_intent_and_compiles_identically() { let shared = input(); let mut sandbox = shared.clone(); - sandbox["spec"]["sandboxes"][0]["inferenceProviders"] = sandbox["spec"] + sandbox["spec"]["sandboxes"]["assistant"]["inferenceProviders"] = sandbox["spec"] .as_object_mut() .unwrap() .remove("inferenceProviders") @@ -59,12 +66,14 @@ fn provider_declaration_scope_preserves_intent_and_compiles_identically() { } #[test] fn route_requires_exactly_one_provider_form() { + let mut provider = input()["spec"]["inferenceProviders"]["local"].clone(); + provider["name"] = json!("local"); for patch in [ json!({}), - json!({"providerRef":"local", "provider":input()["spec"]["inferenceProviders"][0]}), + json!({"providerRef":"local", "provider":provider}), ] { let mut value = input(); - let route = &mut value["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]; + let route = &mut value["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]; route.as_object_mut().unwrap().remove("providerRef"); route .as_object_mut() @@ -82,7 +91,7 @@ fn route_requires_exactly_one_provider_form() { fn unused_provider_definitions_require_no_secrets_or_resources() { let mut value = input(); let original = Document::parse(value.to_string().as_bytes()).unwrap(); - value["spec"]["inferenceProviders"].as_array_mut().unwrap().insert(0, json!({"name":"unused", "provider":"openai", "endpoint":"https://example.com/v1", "credential":{"env":"UNUSED_KEY"}})); + value["spec"]["inferenceProviders"]["unused"] = json!({"provider":"openai", "endpoint":"https://example.com/v1", "credential":{"env":"UNUSED_KEY"}}); let doc = Document::parse(value.to_string().as_bytes()).unwrap(); let generations: Generations = ["workspace", "provider", "sandbox"] .map(|k| (k.into(), "a".repeat(32))) @@ -97,8 +106,8 @@ fn unused_provider_definitions_require_no_secrets_or_resources() { #[test] fn hermes_auth_uses_the_selected_inline_provider_without_a_second_reference() { let mut value = inline(input()); - value["spec"]["sandboxes"][0]["harness"]["kind"] = json!("hermes"); - let agent = &mut value["spec"]["sandboxes"][0]["agent"]; + value["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!("hermes"); + let agent = &mut value["spec"]["sandboxes"]["assistant"]["agent"]; agent["auth"] = json!({"method":"api-key"}); agent["inference"]["routes"][0]["provider"]["endpoint"] = json!("https://inference.example.test/v1"); @@ -129,22 +138,18 @@ fn hermes_auth_uses_the_selected_inline_provider_without_a_second_reference() { #[test] fn references_reject_missing_names_shadowing_and_distinct_inline_instances() { let original = input(); - let provider = original["spec"]["inferenceProviders"][0].clone(); + let providers = original["spec"]["inferenceProviders"].clone(); let mut missing = original.clone(); - missing["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["providerRef"] = + missing["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["providerRef"] = json!("missing"); - let mut duplicate = original.clone(); - duplicate["spec"]["inferenceProviders"] - .as_array_mut() - .unwrap() - .push(provider.clone()); let mut shadow = original.clone(); - shadow["spec"]["sandboxes"][0]["inferenceProviders"] = json!([provider.clone()]); + shadow["spec"]["sandboxes"]["assistant"]["inferenceProviders"] = providers.clone(); let mut inline_shadow = inline(original.clone()); - inline_shadow["spec"]["inferenceProviders"] = json!([provider]); + inline_shadow["spec"]["inferenceProviders"] = providers; let mut empty_ref = inline(original); - empty_ref["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["providerRef"] = json!(""); - for value in [missing, duplicate, shadow, inline_shadow, empty_ref] { + empty_ref["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["providerRef"] = + json!(""); + for value in [missing, shadow, inline_shadow, empty_ref] { assert!(Document::parse(value.to_string().as_bytes()).is_err()); } } @@ -172,11 +177,11 @@ fn inline_managed_providers_reuse_named_service_runtime_and_defaults() { assert_eq!( provider_scope::normalized_as( targets(&local, &generations).unwrap(), - &shared.inference_provider().unwrap().name + shared.inference_provider().unwrap().name ), provider_scope::normalized_as( targets(&shared, &generations).unwrap(), - &shared.inference_provider().unwrap().name + shared.inference_provider().unwrap().name ) ); let local_runtime = nemoclaw_sdk::compile::runtime_targets(&local, &generations).unwrap(); @@ -199,8 +204,7 @@ fn selected_route_provider_updates_its_declared_scope_without_flattening() { include_bytes!("../../../examples/multiple-providers.yaml").as_slice(), ) .unwrap(); - let sandbox = &document.spec.sandboxes[0]; - let inference = document.sandbox_inference(sandbox).unwrap(); + let inference = document.sandbox_inference("researcher").unwrap(); let route = inference .routes .iter() @@ -208,7 +212,7 @@ fn selected_route_provider_updates_its_declared_scope_without_flattening() { .unwrap(); assert_eq!( document - .sandbox_route_provider(sandbox, route) + .sandbox_route_provider("researcher", route) .unwrap() .name, "local" @@ -218,15 +222,18 @@ fn selected_route_provider_updates_its_declared_scope_without_flattening() { .unwrap() .endpoint = "http://127.0.0.1:9000/v1".into(); assert_eq!( - document.spec.inference_providers[0].endpoint, + document.spec.inference_providers["local"].endpoint, "http://127.0.0.1:9000/v1" ); assert_eq!( - document.spec.inference_providers[1].endpoint, + document.spec.inference_providers["hosted"].endpoint, "https://hosted.example/v1" ); assert_eq!( - document.spec.sandboxes[0].agent.inference_ref.as_deref(), + document.spec.sandboxes["researcher"] + .agent + .inference_ref + .as_deref(), Some("smart-and-fast") ); document.validate().unwrap(); diff --git a/crates/nemoclaw-sdk/tests/reference_combinations.rs b/crates/nemoclaw-sdk/tests/reference_combinations.rs index 488a25dcbfa..e9198fce74e 100644 --- a/crates/nemoclaw-sdk/tests/reference_combinations.rs +++ b/crates/nemoclaw-sdk/tests/reference_combinations.rs @@ -33,44 +33,45 @@ fn declaration_scope_combinations_preserve_runtime_and_authored_intent() { for inference_scope in 0..3 { for harness_scope in 0..3 { let mut value = input.clone(); - let provider = value["spec"] + let providers = value["spec"] .as_object_mut() .unwrap() .remove("inferenceProviders") - .unwrap()[0] - .clone(); + .unwrap(); if provider_scope == 2 { - let route = - &mut value["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]; + let route = &mut value["spec"]["sandboxes"]["assistant"]["agent"]["inference"] + ["routes"][0]; route.as_object_mut().unwrap().remove("providerRef"); + let mut provider = providers["local"].clone(); + provider["name"] = json!("local"); route["provider"] = provider; } else { let scope = if provider_scope == 0 { &mut value["spec"] } else { - &mut value["spec"]["sandboxes"][0] + &mut value["spec"]["sandboxes"]["assistant"] }; - scope["inferenceProviders"] = json!([provider]); + scope["inferenceProviders"] = providers; } if inference_scope != 0 { - let agent = &mut value["spec"]["sandboxes"][0]["agent"]; + let agent = &mut value["spec"]["sandboxes"]["assistant"]["agent"]; let inference = agent.as_object_mut().unwrap().remove("inference").unwrap(); agent["inferenceRef"] = json!("chat"); let scope = if inference_scope == 1 { &mut value["spec"] } else { - &mut value["spec"]["sandboxes"][0] + &mut value["spec"]["sandboxes"]["assistant"] }; scope["inferences"] = json!({"chat": inference}); } if harness_scope != 0 { - let sandbox = &mut value["spec"]["sandboxes"][0]; + let sandbox = &mut value["spec"]["sandboxes"]["assistant"]; let harness = sandbox.as_object_mut().unwrap().remove("harness").unwrap(); sandbox["harnessRef"] = json!("shared"); let scope = if harness_scope == 1 { &mut value["spec"] } else { - &mut value["spec"]["sandboxes"][0] + &mut value["spec"]["sandboxes"]["assistant"] }; scope["harnesses"] = json!({"shared": harness}); } @@ -118,9 +119,9 @@ fn example_configurations_pass_the_canonical_fabric_planner() { for path in examples::yaml_files(&root.join("examples")) { let document = Document::parse(std::fs::File::open(&path).unwrap()).unwrap(); let _rows = targets(&document, &generations).unwrap(); - for definition in &document.spec.sandboxes { + for sandbox in document.spec.sandboxes.keys() { let configuration = - nemoclaw_sdk::fabric_config::for_sandbox(&document, definition).unwrap(); + nemoclaw_sdk::fabric_config::for_sandbox(&document, sandbox).unwrap(); let descriptors = catalog .adapters .iter() @@ -139,7 +140,7 @@ fn example_configurations_pass_the_canonical_fabric_planner() { &descriptors, &targets, ) { - failures.push(format!("{} / {}: {error}", path.display(), definition.name)); + failures.push(format!("{} / {}: {error}", path.display(), sandbox)); } checked += 1; } diff --git a/crates/nemoclaw-sdk/tests/reference_diagnostics.rs b/crates/nemoclaw-sdk/tests/reference_diagnostics.rs index 9f1741f72c6..0f1dee59d05 100644 --- a/crates/nemoclaw-sdk/tests/reference_diagnostics.rs +++ b/crates/nemoclaw-sdk/tests/reference_diagnostics.rs @@ -19,9 +19,9 @@ fn missing_references_identify_the_consumer_and_visible_names() { ] { let mut v = input(); let path = if field == "harness" { - "/spec/sandboxes/0" + "/spec/sandboxes/assistant" } else { - "/spec/sandboxes/0/agent" + "/spec/sandboxes/assistant/agent" }; let definition = v .pointer_mut(path) @@ -43,7 +43,8 @@ fn missing_references_identify_the_consumer_and_visible_names() { ); } let mut v = input(); - v["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["providerRef"] = json!("missing"); + v["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["providerRef"] = + json!("missing"); assert_eq!( error(v), "spec.sandboxes[assistant].agent.inference.routes[primary].providerRef: unknown provider \"missing\"; visible definitions: local" @@ -51,7 +52,7 @@ fn missing_references_identify_the_consumer_and_visible_names() { let mut v = input(); v["spec"]["integrations"] = json!({"search":{"kind":"webSearch","provider":"brave","credential":{"env":"SEARCH_KEY"}}}); - v["spec"]["sandboxes"][0]["agent"]["integrationRefs"] = json!(["serach"]); + v["spec"]["sandboxes"]["assistant"]["agent"]["integrationRefs"] = json!(["serach"]); assert_eq!( error(v), "spec.sandboxes[assistant].agent.integrationRefs[0]: unknown integration \"serach\"; visible definitions: search" @@ -60,19 +61,19 @@ fn missing_references_identify_the_consumer_and_visible_names() { #[test] fn shared_inference_does_not_suggest_sandbox_local_providers() { let mut v = input(); - let inference = v["spec"]["sandboxes"][0]["agent"] + let inference = v["spec"]["sandboxes"]["assistant"]["agent"] .as_object_mut() .unwrap() .remove("inference") .unwrap(); v["spec"]["inferences"] = json!({"smart": inference}); - v["spec"]["sandboxes"][0]["agent"]["inferenceRef"] = json!("smart"); + v["spec"]["sandboxes"]["assistant"]["agent"]["inferenceRef"] = json!("smart"); let providers = v["spec"] .as_object_mut() .unwrap() .remove("inferenceProviders") .unwrap(); - v["spec"]["sandboxes"][0]["inferenceProviders"] = providers; + v["spec"]["sandboxes"]["assistant"]["inferenceProviders"] = providers; assert_eq!( error(v), "spec.inferences[smart].routes[primary].providerRef: unknown provider \"local\"; visible definitions: (none)" @@ -82,18 +83,17 @@ fn shared_inference_does_not_suggest_sandbox_local_providers() { #[test] fn visible_names_are_sorted_and_exclude_other_sandboxes() { let mut v = input(); - let definition = v["spec"]["sandboxes"][0]["harness"].clone(); + let definition = v["spec"]["sandboxes"]["assistant"]["harness"].clone(); v["spec"]["harnesses"] = json!({"zulu": definition}); - v["spec"]["sandboxes"][0]["harnesses"] = json!({"alpha": definition}); - let mut other = v["spec"]["sandboxes"][0].clone(); - other["name"] = json!("other"); + v["spec"]["sandboxes"]["assistant"]["harnesses"] = json!({"alpha": definition}); + let mut other = v["spec"]["sandboxes"]["assistant"].clone(); other["harnesses"] = json!({"private": definition}); - v["spec"]["sandboxes"].as_array_mut().unwrap().push(other); - v["spec"]["sandboxes"][0] + v["spec"]["sandboxes"]["other"] = other; + v["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove("harness"); - v["spec"]["sandboxes"][0]["harnessRef"] = json!("missing"); + v["spec"]["sandboxes"]["assistant"]["harnessRef"] = json!("missing"); assert_eq!( error(v), "spec.sandboxes[assistant].harnessRef: unknown harness \"missing\"; visible definitions: alpha, zulu" @@ -103,7 +103,7 @@ fn visible_names_are_sorted_and_exclude_other_sandboxes() { #[test] fn malformed_reference_values_are_not_echoed() { let mut v = input(); - v["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["providerRef"] = + v["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["providerRef"] = json!("https://user:secret@example.com\nforged diagnostic"); let message = error(v); assert!(message.contains("schema")); diff --git a/crates/nemoclaw-sdk/tests/resource_management.rs b/crates/nemoclaw-sdk/tests/resource_management.rs index 17923ca4bc9..e508422d4f4 100644 --- a/crates/nemoclaw-sdk/tests/resource_management.rs +++ b/crates/nemoclaw-sdk/tests/resource_management.rs @@ -16,13 +16,13 @@ fn ownership_follows_configuration_instead_of_optional_annotations() { for (source, parent, field, declaration) in [ ( include_str!("../../../examples/fabric-openclaw.yaml"), - "/spec/inferenceProviders/0", + "/spec/inferenceProviders/local", "management", json!("external"), ), ( include_str!("../../../examples/managed-ollama-gpu.yaml"), - "/spec/inferenceProviders/0", + "/spec/inferenceProviders/qwen", "management", json!("managed"), ), @@ -107,7 +107,7 @@ fn provider_selects_exactly_one_connection_form() { json!({"serviceRef":"qwen", "credential":{"env":"UNUSED"}}), ] { let mut value = original.clone(); - let provider = value["spec"]["inferenceProviders"][0] + let provider = value["spec"]["inferenceProviders"]["qwen"] .as_object_mut() .unwrap(); provider.remove("serviceRef"); diff --git a/crates/nemoclaw-sdk/tests/service_references.rs b/crates/nemoclaw-sdk/tests/service_references.rs index 9e541a1d77b..2dfb75e94d8 100644 --- a/crates/nemoclaw-sdk/tests/service_references.rs +++ b/crates/nemoclaw-sdk/tests/service_references.rs @@ -55,8 +55,13 @@ fn declared_services_install_once_and_service_ref_selects_the_inference_connecti #[test] fn service_references_reject_missing_names() { let mut missing = managed_ollama_service(); - missing["spec"]["inferenceProviders"][0]["serviceRef"] = json!("missing"); - assert!(Document::parse(missing.to_string().as_bytes()).is_err()); + missing["spec"]["inferenceProviders"]["local"]["serviceRef"] = json!("missing"); + assert_eq!( + Document::parse(missing.to_string().as_bytes()) + .unwrap_err() + .to_string(), + r#"serviceRef: unknown service "missing"; visible definitions: ollama-server, unused"# + ); } #[test] @@ -66,7 +71,7 @@ fn unconsumed_local_services_cannot_inherit_a_podman_engine() { include_str!("../../../examples/managed-ollama-gpu.yaml"), ] { let mut value: serde_json::Value = serde_saphyr::from_str(source).unwrap(); - let provider = value["spec"]["inferenceProviders"][0] + let provider = value["spec"]["inferenceProviders"]["qwen"] .as_object_mut() .unwrap(); provider.remove("serviceRef"); diff --git a/crates/nemoclaw-sdk/tests/spark_examples.rs b/crates/nemoclaw-sdk/tests/spark_examples.rs index 74026bf5466..648a9872c58 100644 --- a/crates/nemoclaw-sdk/tests/spark_examples.rs +++ b/crates/nemoclaw-sdk/tests/spark_examples.rs @@ -58,7 +58,7 @@ fn arm64_hardware_scenarios_compile_their_declared_resources() { Document::parse(doc.yaml().unwrap().as_bytes()).unwrap(), doc ); - for provider in &doc.spec.inference_providers { + for provider in doc.spec.inference_providers.values() { if let Some(name) = &provider.service_ref { let ServiceDefinition::Vllm(service) = &doc.spec.services[name] else { panic!("{name}: expected vLLM service"); @@ -88,7 +88,7 @@ fn arm64_hardware_scenarios_compile_their_declared_resources() { }) ); assert!(service.image.starts_with("nc-prototype-vllm@sha256:")); - for sandbox in &doc.spec.sandboxes { + for sandbox in doc.spec.sandboxes.values() { assert!(sandbox.image.ref_.starts_with("nc-fabric@sha256:")); } if name == "shared-model.yaml" { diff --git a/crates/nemoclaw-sdk/tests/support/config.rs b/crates/nemoclaw-sdk/tests/support/config.rs index 96567bef570..dbcb295e347 100644 --- a/crates/nemoclaw-sdk/tests/support/config.rs +++ b/crates/nemoclaw-sdk/tests/support/config.rs @@ -23,6 +23,26 @@ pub fn fixture(name: &str) -> Value { ) } +/// Document text that authors each map at `pointers` in reverse key order, so +/// a test can show that the order of named entries carries no intent. +pub fn reversed(value: &Value, pointers: &[&str]) -> String { + let mut text = value.to_string(); + for pointer in pointers { + let map = value.pointer(pointer).unwrap(); + let entries = map.as_object().unwrap(); + assert!(entries.len() > 1, "{pointer} has nothing to reorder"); + let authored = map.to_string(); + assert_eq!(text.matches(&authored).count(), 1, "{pointer} is ambiguous"); + let reversed: Vec<_> = entries + .iter() + .rev() + .map(|(key, entry)| format!("{}:{entry}", Value::from(key.as_str()))) + .collect(); + text = text.replace(&authored, &format!("{{{}}}", reversed.join(","))); + } + text +} + fn load(path: &Path) -> Value { let text = std::fs::read_to_string(path).unwrap_or_else(|error| panic!("{}: {error}", path.display())); diff --git a/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs b/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs index 99c1637f753..2922a09afa0 100644 --- a/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs +++ b/crates/nemoclaw-sdk/tests/support/scripted_tofu.rs @@ -277,7 +277,8 @@ pub fn kubernetes_document(name: &str, namespace: &str) -> Document { "namespace": namespace, "authentication": {"profile": "development"} }} }); - value["spec"]["sandboxes"][0]["image"]["metadata"] = json!({"env": "TEST_IMAGE_METADATA"}); + value["spec"]["sandboxes"]["assistant"]["image"]["metadata"] = + json!({"env": "TEST_IMAGE_METADATA"}); Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap() } diff --git a/crates/nemoclaw-sdk/tests/web_search.rs b/crates/nemoclaw-sdk/tests/web_search.rs index 9003b2b0c89..17f5fa20bf1 100644 --- a/crates/nemoclaw-sdk/tests/web_search.rs +++ b/crates/nemoclaw-sdk/tests/web_search.rs @@ -10,9 +10,9 @@ use serde_json::{Value, json}; fn input() -> Value { let mut value: Value = serde_saphyr::from_str(include_str!("../../../examples/fabric-openclaw.yaml")).unwrap(); - value["spec"]["sandboxes"][0]["integrations"] = + value["spec"]["sandboxes"]["assistant"]["integrations"] = json!({"search":{"kind":"webSearch","provider":"brave","credential":{"env":"SEARCH_KEY"}}}); - value["spec"]["sandboxes"][0]["agent"]["integrationRefs"] = json!(["search"]); + value["spec"]["sandboxes"]["assistant"]["agent"]["integrationRefs"] = json!(["search"]); value } #[test] @@ -78,40 +78,38 @@ fn search_uses_owned_profile_and_provider_without_exporting_secrets() { fn search_rejects_unknown_and_duplicate_references() { for refs in [json!(["missing"]), json!(["search", "search"])] { let mut value = input(); - value["spec"]["sandboxes"][0]["agent"]["integrationRefs"] = refs; + value["spec"]["sandboxes"]["assistant"]["agent"]["integrationRefs"] = refs; assert!(Document::parse(value.to_string().as_bytes()).is_err()); } let mut value = input(); - value["spec"]["sandboxes"][0]["agent"]["tools"] = json!({"allow":["read"]}); + value["spec"]["sandboxes"]["assistant"]["agent"]["tools"] = json!({"allow":["read"]}); assert!(Document::parse(value.to_string().as_bytes()).is_ok()); } #[test] fn shared_integration_references_grant_only_the_selected_agents() { let mut value = input(); - value["spec"]["sandboxes"][0] + value["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove("integrations"); value["spec"]["integrations"] = json!({"search": { "kind": "webSearch", "provider": "brave", "credential": {"env": "SEARCH_KEY"} }}); - let mut writer = value["spec"]["sandboxes"][0].clone(); - writer["name"] = json!("writer"); + let mut writer = value["spec"]["sandboxes"]["assistant"].clone(); writer["agent"]["name"] = json!("writer"); let mut reader = writer.clone(); - reader["name"] = json!("reader"); reader["agent"]["name"] = json!("reader"); reader["agent"] .as_object_mut() .unwrap() .remove("integrationRefs"); value["spec"]["sandboxes"] - .as_array_mut() + .as_object_mut() .unwrap() - .extend([writer, reader]); - for index in [0, 1] { - value["spec"]["sandboxes"][index]["agent"]["integrationRefs"] = json!(["search"]); + .extend([("writer".into(), writer), ("reader".into(), reader)]); + for name in ["assistant", "writer"] { + value["spec"]["sandboxes"][name]["agent"]["integrationRefs"] = json!(["search"]); } let doc = Document::parse(value.to_string().as_bytes()).expect("shared definitions must parse"); assert!( @@ -201,7 +199,7 @@ fn agent_inline_and_enclosing_definitions_compile_to_the_same_search_grants() { .unwrap(); for scope in ["deployment", "agent"] { let mut value = value.clone(); - let definitions = value["spec"]["sandboxes"][0] + let definitions = value["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove("integrations") @@ -209,11 +207,11 @@ fn agent_inline_and_enclosing_definitions_compile_to_the_same_search_grants() { if scope == "deployment" { value["spec"]["integrations"] = definitions; } else { - value["spec"]["sandboxes"][0]["agent"] + value["spec"]["sandboxes"]["assistant"]["agent"] .as_object_mut() .unwrap() .remove("integrationRefs"); - value["spec"]["sandboxes"][0]["agent"]["integrations"] = definitions; + value["spec"]["sandboxes"]["assistant"]["agent"]["integrations"] = definitions; } let doc = Document::parse(value.to_string().as_bytes()) .expect("inline and shared definitions must parse"); @@ -233,7 +231,7 @@ fn agent_inline_and_enclosing_definitions_compile_to_the_same_search_grants() { #[test] fn unused_definitions_create_no_search_resources_policy_or_secret_requirements() { let mut value = input(); - value["spec"]["sandboxes"][0]["agent"]["integrationRefs"] = json!([]); + value["spec"]["sandboxes"]["assistant"]["agent"]["integrationRefs"] = json!([]); let doc = Document::parse(value.to_string().as_bytes()).unwrap(); let generations = ["workspace", "provider", "sandbox"] .map(|key| (key.into(), "a".repeat(32))) @@ -248,34 +246,32 @@ fn unused_definitions_create_no_search_resources_policy_or_secret_requirements() #[test] fn integration_scopes_reject_shadowing_and_sibling_sandbox_references() { let original = input(); - let definitions = original["spec"]["sandboxes"][0]["integrations"].clone(); + let definitions = original["spec"]["sandboxes"]["assistant"]["integrations"].clone(); let mut shared_collision = original.clone(); shared_collision["spec"]["integrations"] = definitions.clone(); let mut local_collision = original.clone(); - local_collision["spec"]["sandboxes"][0]["agent"]["integrations"] = definitions.clone(); + local_collision["spec"]["sandboxes"]["assistant"]["agent"]["integrations"] = + definitions.clone(); let mut global_collision = original.clone(); - global_collision["spec"]["sandboxes"][0] + global_collision["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove("integrations"); global_collision["spec"]["integrations"] = definitions.clone(); - global_collision["spec"]["sandboxes"][0]["agent"]["integrations"] = definitions.clone(); + global_collision["spec"]["sandboxes"]["assistant"]["agent"]["integrations"] = + definitions.clone(); let mut sibling = original; - sibling["spec"]["sandboxes"][0] + sibling["spec"]["sandboxes"]["assistant"] .as_object_mut() .unwrap() .remove("integrations"); - let mut other = sibling["spec"]["sandboxes"][0].clone(); - other["name"] = json!("other"); + let mut other = sibling["spec"]["sandboxes"]["assistant"].clone(); other["agent"] .as_object_mut() .unwrap() .remove("integrationRefs"); other["agent"]["integrations"] = definitions; - sibling["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(other); + sibling["spec"]["sandboxes"]["other"] = other; for value in [shared_collision, local_collision, global_collision, sibling] { assert!(Document::parse(value.to_string().as_bytes()).is_err()); } @@ -284,9 +280,10 @@ fn integration_scopes_reject_shadowing_and_sibling_sandbox_references() { #[test] fn distinct_search_definitions_are_not_silently_merged_by_value() { let mut value = input(); - let second = value["spec"]["sandboxes"][0]["integrations"]["search"].clone(); - value["spec"]["sandboxes"][0]["integrations"]["other"] = second; - value["spec"]["sandboxes"][0]["agent"]["integrationRefs"] = json!(["search", "other"]); + let second = value["spec"]["sandboxes"]["assistant"]["integrations"]["search"].clone(); + value["spec"]["sandboxes"]["assistant"]["integrations"]["other"] = second; + value["spec"]["sandboxes"]["assistant"]["agent"]["integrationRefs"] = + json!(["search", "other"]); let error = Document::parse(value.to_string().as_bytes()).unwrap_err(); assert_eq!( error.0, @@ -297,7 +294,7 @@ fn distinct_search_definitions_are_not_silently_merged_by_value() { #[test] fn schema_and_parser_reject_unsupported_integration_shapes() { let validator = jsonschema::validator_for(&input_schema()).unwrap(); - let definition = input()["spec"]["sandboxes"][0]["integrations"]["search"].clone(); + let definition = input()["spec"]["sandboxes"]["assistant"]["integrations"]["search"].clone(); let mut cases = Vec::new(); for patch in [ json!({"kind":"voiceclaw"}), @@ -316,7 +313,7 @@ fn schema_and_parser_reject_unsupported_integration_shapes() { cases.push(json!({"webSearch":{"provider":"brave","agentRefs":["main"],"credential":{"env":"SEARCH_KEY"}}})); for definitions in cases { let mut value = input(); - value["spec"]["sandboxes"][0]["integrations"] = definitions; + value["spec"]["sandboxes"]["assistant"]["integrations"] = definitions; assert!(Document::parse(value.to_string().as_bytes()).is_err()); assert!(!validator.is_valid(&value)); } @@ -325,12 +322,7 @@ fn schema_and_parser_reject_unsupported_integration_shapes() { #[test] fn sandboxes_share_search_registration_only_for_the_same_credential() { let mut value = input(); - let mut other = value["spec"]["sandboxes"][0].clone(); - other["name"] = json!("other"); - value["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(other); + value["spec"]["sandboxes"]["other"] = value["spec"]["sandboxes"]["assistant"].clone(); let doc = Document::parse(value.to_string().as_bytes()).unwrap(); let generations: Generations = ["workspace", "provider", "sandbox"] .map(|key| (key.into(), "a".repeat(32))) @@ -348,7 +340,7 @@ fn sandboxes_share_search_registration_only_for_the_same_credential() { 1 ); assert_eq!(doc.credential_names(), vec!["SEARCH_KEY"]); - value["spec"]["sandboxes"][1]["integrations"]["search"]["credential"]["env"] = + value["spec"]["sandboxes"]["other"]["integrations"]["search"]["credential"]["env"] = json!("OTHER_KEY"); let doc = Document::parse(value.to_string().as_bytes()).unwrap(); let resources = targets(&doc, &generations).unwrap(); @@ -390,7 +382,8 @@ fn sandboxes_share_search_registration_only_for_the_same_credential() { #[test] fn native_search_preserves_explicit_grants_and_tool_configuration() { let mut value = input(); - value["spec"]["sandboxes"][0]["harness"]["kind"] = json!("nvidia.fabric.langchain.deepagents"); + value["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = + json!("nvidia.fabric.langchain.deepagents"); let document = Document::parse(value.to_string().as_bytes()).expect("Deep Agents search"); let generations = ["workspace", "provider", "sandbox"] .map(|key| (key.into(), "a".repeat(32))) @@ -404,7 +397,7 @@ fn native_search_preserves_explicit_grants_and_tool_configuration() { .iter() .any(|name| name.starts_with("brave-search-")) ); - value["spec"]["sandboxes"][0]["agent"]["tools"] = json!({"allow":["read"]}); + value["spec"]["sandboxes"]["assistant"]["agent"]["tools"] = json!({"allow":["read"]}); assert!(Document::parse(value.to_string().as_bytes()).is_ok()); } @@ -412,8 +405,9 @@ fn native_search_preserves_explicit_grants_and_tool_configuration() { fn tavily_preserves_openclaw_and_hermes_intent_and_credential_references() { for harness in ["nvidia.fabric.openclaw", "nvidia.fabric.hermes"] { let mut value = input(); - value["spec"]["sandboxes"][0]["harness"]["kind"] = json!(harness); - value["spec"]["sandboxes"][0]["integrations"]["search"]["provider"] = json!("tavily"); + value["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!(harness); + value["spec"]["sandboxes"]["assistant"]["integrations"]["search"]["provider"] = + json!("tavily"); let doc = Document::parse(value.to_string().as_bytes()).expect("Tavily must parse"); assert!( jsonschema::validator_for(&input_schema()) @@ -525,7 +519,7 @@ fn tavily_example_separates_openclaw_and_hermes_executable_scopes() { .map(|key| (key.into(), "a".repeat(32))) .into(); let rows = targets(&document, &generations).unwrap(); - for sandbox in &document.spec.sandboxes { + for sandbox in document.spec.sandboxes.keys() { let authored = document .sandbox_harness(sandbox) .unwrap() @@ -569,13 +563,9 @@ fn different_search_providers_keep_distinct_bindings_for_the_same_credential_ref &generations, ) .unwrap(); - let mut tavily = value["spec"]["sandboxes"][0].clone(); - tavily["name"] = json!("tavily-assistant"); + let mut tavily = value["spec"]["sandboxes"]["assistant"].clone(); tavily["integrations"]["search"]["provider"] = json!("tavily"); - value["spec"]["sandboxes"] - .as_array_mut() - .unwrap() - .push(tavily); + value["spec"]["sandboxes"]["tavily-assistant"] = tavily; let doc = Document::parse(value.to_string().as_bytes()).unwrap(); let rows = targets(&doc, &generations).unwrap(); for row in existing { @@ -605,13 +595,14 @@ fn different_search_providers_keep_distinct_bindings_for_the_same_credential_ref fn native_search_constraints_are_forwarded_for_fabric_validation() { for harness in ["deepagents", "pi"] { let mut value = input(); - value["spec"]["sandboxes"][0]["harness"]["kind"] = json!(harness); - value["spec"]["sandboxes"][0]["integrations"]["search"]["provider"] = json!("tavily"); + value["spec"]["sandboxes"]["assistant"]["harness"]["kind"] = json!(harness); + value["spec"]["sandboxes"]["assistant"]["integrations"]["search"]["provider"] = + json!("tavily"); assert!(Document::parse(value.to_string().as_bytes()).is_ok()); } let mut value = input(); - value["spec"]["sandboxes"][0]["integrations"]["search"]["provider"] = json!("tavily"); - value["spec"]["sandboxes"][0]["agent"]["tools"] = json!({"allow":["read"]}); + value["spec"]["sandboxes"]["assistant"]["integrations"]["search"]["provider"] = json!("tavily"); + value["spec"]["sandboxes"]["assistant"]["agent"]["tools"] = json!({"allow":["read"]}); assert!(Document::parse(value.to_string().as_bytes()).is_ok()); } @@ -619,15 +610,18 @@ fn native_search_constraints_are_forwarded_for_fabric_validation() { fn tavily_rejects_collisions_with_managed_profile_and_provider_names() { for name in ["tavily-search", "tavily-search-custom"] { let mut value = input(); - value["spec"]["sandboxes"][0]["integrations"]["search"]["provider"] = json!("tavily"); - value["spec"]["inferenceProviders"][0]["name"] = json!(name); - value["spec"]["sandboxes"][0]["agent"]["inference"]["routes"][0]["providerRef"] = + value["spec"]["sandboxes"]["assistant"]["integrations"]["search"]["provider"] = + json!("tavily"); + let providers = value["spec"]["inferenceProviders"].as_object_mut().unwrap(); + let provider = providers.remove("local").unwrap(); + providers.insert(name.into(), provider); + value["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["providerRef"] = json!(name); let error = Document::parse(value.to_string().as_bytes()).unwrap_err(); assert!(error.0.contains("reserved for web search"), "{error}"); } let mut value = input(); - value["spec"]["sandboxes"][0]["integrations"]["search"]["provider"] = json!("tavily"); + value["spec"]["sandboxes"]["assistant"]["integrations"]["search"]["provider"] = json!("tavily"); let manifest: serde_json::Value = serde_json::from_str(include_str!("../../../image/fabric/runtime.json")).unwrap(); let mut policy = manifest["policy"].clone(); @@ -636,9 +630,9 @@ fn tavily_rejects_collisions_with_managed_profile_and_provider_names() { "endpoints":[{"host":"search.example.com","port":443}], "binaries":[{"path":"/usr/local/bin/node"}] }}); - value["spec"]["sandboxes"][0]["network"] = json!({"policy": {"explicit": policy}}); + value["spec"]["sandboxes"]["assistant"]["network"] = json!({"policy": {"explicit": policy}}); Document::parse(value.to_string().as_bytes()).expect("non-colliding policy must be valid"); - let rules = value["spec"]["sandboxes"][0]["network"]["policy"]["explicit"]["network_policies"] + let rules = value["spec"]["sandboxes"]["assistant"]["network"]["policy"]["explicit"]["network_policies"] .as_object_mut() .unwrap(); let mut rule = rules.remove("custom-search").unwrap(); @@ -651,10 +645,11 @@ fn tavily_rejects_collisions_with_managed_profile_and_provider_names() { #[test] fn attaching_brave_and_tavily_to_one_agent_does_not_discard_either_intent() { let mut value = input(); - let mut other = value["spec"]["sandboxes"][0]["integrations"]["search"].clone(); + let mut other = value["spec"]["sandboxes"]["assistant"]["integrations"]["search"].clone(); other["provider"] = json!("tavily"); - value["spec"]["sandboxes"][0]["integrations"]["other"] = other; - value["spec"]["sandboxes"][0]["agent"]["integrationRefs"] = json!(["search", "other"]); + value["spec"]["sandboxes"]["assistant"]["integrations"]["other"] = other; + value["spec"]["sandboxes"]["assistant"]["agent"]["integrationRefs"] = + json!(["search", "other"]); assert_eq!( Document::parse(value.to_string().as_bytes()).unwrap_err().0, "a sandbox supports only one attached web search definition" diff --git a/crates/openshell-provider/tests/contract/fixtures/multiple-sandboxes.tf.json b/crates/openshell-provider/tests/contract/fixtures/multiple-sandboxes.tf.json index 8bfb388b352..39f16cfa308 100644 --- a/crates/openshell-provider/tests/contract/fixtures/multiple-sandboxes.tf.json +++ b/crates/openshell-provider/tests/contract/fixtures/multiple-sandboxes.tf.json @@ -301,7 +301,7 @@ "provider_names": [ "local-b95da89e857d01251c2f1583" ], - "runtime_json": "{\"runtime\":{\"schema_version\":1,\"command\":[\"/usr/local/bin/fabric-agent\"],\"environment\":{\"ADAPTER_PYTHON\":\"/opt/fabric/bin/python\",\"HOME\":\"/sandbox\",\"NEMOCLAW_ANONYMOUS_API_KEY\":\"unused\",\"NODE_EXTRA_CA_CERTS\":\"/etc/ssl/certs/ca-certificates.crt\",\"PATH\":\"/opt/fabric/bin:/usr/local/bin:/usr/bin:/bin\",\"PYTHONDONTWRITEBYTECODE\":\"1\",\"SSL_CERT_FILE\":\"/etc/ssl/certs/ca-certificates.crt\",\"TMPDIR\":\"/sandbox/tmp\",\"XDG_CACHE_HOME\":\"/sandbox/.cache\"},\"required_paths\":[\"/opt/fabric\",\"/opt/nemoclaw\"],\"policy\":{\"version\":1,\"filesystem_policy\":{\"include_workdir\":false,\"read_only\":[\"/usr\",\"/bin\",\"/sbin\",\"/lib\",\"/lib64\",\"/etc\",\"/app\",\"/opt\",\"/proc\"],\"read_write\":[\"/sandbox\",\"/tmp\",\"/dev/null\",\"/dev/urandom\",\"/home/node\"]},\"landlock\":{\"compatibility\":\"best_effort\"},\"process\":{\"run_as_user\":\"10001\",\"run_as_group\":\"10001\"},\"network_policies\":{}},\"binaries\":{\"nvidia.fabric.langchain.deepagents\":[\"/usr/local/bin/python3.99\"]}},\"adapter_id\":\"nvidia.fabric.langchain.deepagents\"}", + "runtime_json": "{\"runtime\":{\"schema_version\":1,\"command\":[\"/usr/local/bin/fabric-agent\"],\"environment\":{\"ADAPTER_PYTHON\":\"/opt/fabric/bin/python\",\"HOME\":\"/sandbox\",\"NEMOCLAW_ANONYMOUS_API_KEY\":\"unused\",\"NODE_EXTRA_CA_CERTS\":\"/etc/ssl/certs/ca-certificates.crt\",\"PATH\":\"/opt/fabric/bin:/usr/local/bin:/usr/bin:/bin\",\"PYTHONDONTWRITEBYTECODE\":\"1\",\"SSL_CERT_FILE\":\"/etc/ssl/certs/ca-certificates.crt\",\"TMPDIR\":\"/sandbox/tmp\",\"XDG_CACHE_HOME\":\"/sandbox/.cache\"},\"required_paths\":[\"/opt/fabric\",\"/opt/nemoclaw\"],\"policy\":{\"version\":1,\"filesystem_policy\":{\"include_workdir\":false,\"read_only\":[\"/usr\",\"/bin\",\"/sbin\",\"/lib\",\"/lib64\",\"/etc\",\"/app\",\"/opt\",\"/proc\"],\"read_write\":[\"/sandbox\",\"/tmp\",\"/dev/null\",\"/dev/urandom\",\"/home/node\"]},\"landlock\":{\"compatibility\":\"best_effort\"},\"process\":{\"run_as_user\":\"10001\",\"run_as_group\":\"10001\"},\"network_policies\":{}},\"binaries\":{\"nvidia.fabric.pi\":[\"/usr/local/bin/python3.99\"]}},\"adapter_id\":\"nvidia.fabric.pi\"}", "workspace": "${openshell_workspace.deployment.name}" }, "research": { @@ -393,7 +393,7 @@ "provider_names": [ "local-3d36801b67957c3bcfa1093b" ], - "runtime_json": "{\"runtime\":{\"schema_version\":1,\"command\":[\"/usr/local/bin/fabric-agent\"],\"environment\":{\"ADAPTER_PYTHON\":\"/opt/fabric/bin/python\",\"HOME\":\"/sandbox\",\"NEMOCLAW_ANONYMOUS_API_KEY\":\"unused\",\"NODE_EXTRA_CA_CERTS\":\"/etc/ssl/certs/ca-certificates.crt\",\"PATH\":\"/opt/fabric/bin:/usr/local/bin:/usr/bin:/bin\",\"PYTHONDONTWRITEBYTECODE\":\"1\",\"SSL_CERT_FILE\":\"/etc/ssl/certs/ca-certificates.crt\",\"TMPDIR\":\"/sandbox/tmp\",\"XDG_CACHE_HOME\":\"/sandbox/.cache\"},\"required_paths\":[\"/opt/fabric\",\"/opt/nemoclaw\"],\"policy\":{\"version\":1,\"filesystem_policy\":{\"include_workdir\":false,\"read_only\":[\"/usr\",\"/bin\",\"/sbin\",\"/lib\",\"/lib64\",\"/etc\",\"/app\",\"/opt\",\"/proc\"],\"read_write\":[\"/sandbox\",\"/tmp\",\"/dev/null\",\"/dev/urandom\",\"/home/node\"]},\"landlock\":{\"compatibility\":\"best_effort\"},\"process\":{\"run_as_user\":\"10001\",\"run_as_group\":\"10001\"},\"network_policies\":{}},\"binaries\":{\"nvidia.fabric.pi\":[\"/usr/local/bin/python3.99\"]}},\"adapter_id\":\"nvidia.fabric.pi\"}", + "runtime_json": "{\"runtime\":{\"schema_version\":1,\"command\":[\"/usr/local/bin/fabric-agent\"],\"environment\":{\"ADAPTER_PYTHON\":\"/opt/fabric/bin/python\",\"HOME\":\"/sandbox\",\"NEMOCLAW_ANONYMOUS_API_KEY\":\"unused\",\"NODE_EXTRA_CA_CERTS\":\"/etc/ssl/certs/ca-certificates.crt\",\"PATH\":\"/opt/fabric/bin:/usr/local/bin:/usr/bin:/bin\",\"PYTHONDONTWRITEBYTECODE\":\"1\",\"SSL_CERT_FILE\":\"/etc/ssl/certs/ca-certificates.crt\",\"TMPDIR\":\"/sandbox/tmp\",\"XDG_CACHE_HOME\":\"/sandbox/.cache\"},\"required_paths\":[\"/opt/fabric\",\"/opt/nemoclaw\"],\"policy\":{\"version\":1,\"filesystem_policy\":{\"include_workdir\":false,\"read_only\":[\"/usr\",\"/bin\",\"/sbin\",\"/lib\",\"/lib64\",\"/etc\",\"/app\",\"/opt\",\"/proc\"],\"read_write\":[\"/sandbox\",\"/tmp\",\"/dev/null\",\"/dev/urandom\",\"/home/node\"]},\"landlock\":{\"compatibility\":\"best_effort\"},\"process\":{\"run_as_user\":\"10001\",\"run_as_group\":\"10001\"},\"network_policies\":{}},\"binaries\":{\"nvidia.fabric.langchain.deepagents\":[\"/usr/local/bin/python3.99\"]}},\"adapter_id\":\"nvidia.fabric.langchain.deepagents\"}", "workspace": "${openshell_workspace.deployment.name}" } }, diff --git a/crates/openshell-provider/tests/contract/fixtures/tavily-web-search.tf.json b/crates/openshell-provider/tests/contract/fixtures/tavily-web-search.tf.json index 401cfc27567..4bb97f10ff2 100644 --- a/crates/openshell-provider/tests/contract/fixtures/tavily-web-search.tf.json +++ b/crates/openshell-provider/tests/contract/fixtures/tavily-web-search.tf.json @@ -277,7 +277,7 @@ "local-4dcf1b725a48b148ce57287f", "tavily-search-64af2c4d05f99c5a04c99cd4" ], - "runtime_json": "{\"runtime\":{\"schema_version\":1,\"command\":[\"/usr/local/bin/fabric-agent\"],\"environment\":{\"ADAPTER_PYTHON\":\"/opt/fabric/bin/python\",\"HOME\":\"/sandbox\",\"NEMOCLAW_ANONYMOUS_API_KEY\":\"unused\",\"NODE_EXTRA_CA_CERTS\":\"/etc/ssl/certs/ca-certificates.crt\",\"PATH\":\"/opt/fabric/bin:/usr/local/bin:/usr/bin:/bin\",\"PYTHONDONTWRITEBYTECODE\":\"1\",\"SSL_CERT_FILE\":\"/etc/ssl/certs/ca-certificates.crt\",\"TMPDIR\":\"/sandbox/tmp\",\"XDG_CACHE_HOME\":\"/sandbox/.cache\"},\"required_paths\":[\"/opt/fabric\",\"/opt/nemoclaw\"],\"policy\":{\"version\":1,\"filesystem_policy\":{\"include_workdir\":false,\"read_only\":[\"/usr\",\"/bin\",\"/sbin\",\"/lib\",\"/lib64\",\"/etc\",\"/app\",\"/opt\",\"/proc\"],\"read_write\":[\"/sandbox\",\"/tmp\",\"/dev/null\",\"/dev/urandom\",\"/home/node\"]},\"landlock\":{\"compatibility\":\"best_effort\"},\"process\":{\"run_as_user\":\"10001\",\"run_as_group\":\"10001\"},\"network_policies\":{}},\"binaries\":{\"nvidia.fabric.openclaw\":[\"/usr/local/bin/python3.99\"]}},\"adapter_id\":\"nvidia.fabric.openclaw\"}", + "runtime_json": "{\"runtime\":{\"schema_version\":1,\"command\":[\"/usr/local/bin/fabric-agent\"],\"environment\":{\"ADAPTER_PYTHON\":\"/opt/fabric/bin/python\",\"HOME\":\"/sandbox\",\"NEMOCLAW_ANONYMOUS_API_KEY\":\"unused\",\"NODE_EXTRA_CA_CERTS\":\"/etc/ssl/certs/ca-certificates.crt\",\"PATH\":\"/opt/fabric/bin:/usr/local/bin:/usr/bin:/bin\",\"PYTHONDONTWRITEBYTECODE\":\"1\",\"SSL_CERT_FILE\":\"/etc/ssl/certs/ca-certificates.crt\",\"TMPDIR\":\"/sandbox/tmp\",\"XDG_CACHE_HOME\":\"/sandbox/.cache\"},\"required_paths\":[\"/opt/fabric\",\"/opt/nemoclaw\"],\"policy\":{\"version\":1,\"filesystem_policy\":{\"include_workdir\":false,\"read_only\":[\"/usr\",\"/bin\",\"/sbin\",\"/lib\",\"/lib64\",\"/etc\",\"/app\",\"/opt\",\"/proc\"],\"read_write\":[\"/sandbox\",\"/tmp\",\"/dev/null\",\"/dev/urandom\",\"/home/node\"]},\"landlock\":{\"compatibility\":\"best_effort\"},\"process\":{\"run_as_user\":\"10001\",\"run_as_group\":\"10001\"},\"network_policies\":{}},\"binaries\":{\"nvidia.fabric.hermes\":[\"/usr/local/bin/python3.99\"]}},\"adapter_id\":\"nvidia.fabric.hermes\"}", "workspace": "${openshell_workspace.deployment.name}" }, "researcher": { @@ -351,7 +351,7 @@ "local-d6ca74ad95e4f1d5f302f50e", "tavily-search-b834e6dcc9c43c0d32bd2c2f" ], - "runtime_json": "{\"runtime\":{\"schema_version\":1,\"command\":[\"/usr/local/bin/fabric-agent\"],\"environment\":{\"ADAPTER_PYTHON\":\"/opt/fabric/bin/python\",\"HOME\":\"/sandbox\",\"NEMOCLAW_ANONYMOUS_API_KEY\":\"unused\",\"NODE_EXTRA_CA_CERTS\":\"/etc/ssl/certs/ca-certificates.crt\",\"PATH\":\"/opt/fabric/bin:/usr/local/bin:/usr/bin:/bin\",\"PYTHONDONTWRITEBYTECODE\":\"1\",\"SSL_CERT_FILE\":\"/etc/ssl/certs/ca-certificates.crt\",\"TMPDIR\":\"/sandbox/tmp\",\"XDG_CACHE_HOME\":\"/sandbox/.cache\"},\"required_paths\":[\"/opt/fabric\",\"/opt/nemoclaw\"],\"policy\":{\"version\":1,\"filesystem_policy\":{\"include_workdir\":false,\"read_only\":[\"/usr\",\"/bin\",\"/sbin\",\"/lib\",\"/lib64\",\"/etc\",\"/app\",\"/opt\",\"/proc\"],\"read_write\":[\"/sandbox\",\"/tmp\",\"/dev/null\",\"/dev/urandom\",\"/home/node\"]},\"landlock\":{\"compatibility\":\"best_effort\"},\"process\":{\"run_as_user\":\"10001\",\"run_as_group\":\"10001\"},\"network_policies\":{}},\"binaries\":{\"nvidia.fabric.hermes\":[\"/usr/local/bin/python3.99\"]}},\"adapter_id\":\"nvidia.fabric.hermes\"}", + "runtime_json": "{\"runtime\":{\"schema_version\":1,\"command\":[\"/usr/local/bin/fabric-agent\"],\"environment\":{\"ADAPTER_PYTHON\":\"/opt/fabric/bin/python\",\"HOME\":\"/sandbox\",\"NEMOCLAW_ANONYMOUS_API_KEY\":\"unused\",\"NODE_EXTRA_CA_CERTS\":\"/etc/ssl/certs/ca-certificates.crt\",\"PATH\":\"/opt/fabric/bin:/usr/local/bin:/usr/bin:/bin\",\"PYTHONDONTWRITEBYTECODE\":\"1\",\"SSL_CERT_FILE\":\"/etc/ssl/certs/ca-certificates.crt\",\"TMPDIR\":\"/sandbox/tmp\",\"XDG_CACHE_HOME\":\"/sandbox/.cache\"},\"required_paths\":[\"/opt/fabric\",\"/opt/nemoclaw\"],\"policy\":{\"version\":1,\"filesystem_policy\":{\"include_workdir\":false,\"read_only\":[\"/usr\",\"/bin\",\"/sbin\",\"/lib\",\"/lib64\",\"/etc\",\"/app\",\"/opt\",\"/proc\"],\"read_write\":[\"/sandbox\",\"/tmp\",\"/dev/null\",\"/dev/urandom\",\"/home/node\"]},\"landlock\":{\"compatibility\":\"best_effort\"},\"process\":{\"run_as_user\":\"10001\",\"run_as_group\":\"10001\"},\"network_policies\":{}},\"binaries\":{\"nvidia.fabric.openclaw\":[\"/usr/local/bin/python3.99\"]}},\"adapter_id\":\"nvidia.fabric.openclaw\"}", "workspace": "${openshell_workspace.deployment.name}" } }, diff --git a/docs/build.md b/docs/build.md index 678ee3bfc08..884f7db2336 100644 --- a/docs/build.md +++ b/docs/build.md @@ -88,7 +88,7 @@ cargo images build --platform linux/arm64 openclaw docker image inspect nc-fabric:openclaw --format '{{index .RepoDigests 0}}' ``` -Use the printed immutable reference in `sandboxes[].image.ref`. +Use the printed immutable reference in `spec.sandboxes..image.ref`. Examples that omit `image` use the generic default agent image pin from `versions.json`. Select an explicit image containing the chosen Fabric adapter; a harness identifier does not select a different image. The selected image must still exist on the compute daemon. @@ -114,7 +114,7 @@ cargo images build --platform linux/amd64 deepagents docker image inspect nc-fabric:deepagents --format '{{index .RepoDigests 0}}' ``` -Use the printed immutable reference in `sandboxes[].image.ref`. +Use the printed immutable reference in `spec.sandboxes..image.ref`. Replace `deepagents` with `openclaw` to build the other qualified AMD64 harness. Run `cargo images build --platform linux/amd64 agents` to build both. The AMD64 builds and image tests do not establish successful gateway provisioning or an end-to-end agent response. diff --git a/docs/configuration-references.md b/docs/configuration-references.md index bf8a14ffc83..aca2c5b7e35 100644 --- a/docs/configuration-references.md +++ b/docs/configuration-references.md @@ -34,19 +34,19 @@ Moving a definition does not authorize replacing an existing resource; normal id ## Supported Families -Paths below are relative to `spec`; `agent` is inside `sandboxes[]` and `routes[]` is inside an inline or shared inference configuration. +Paths below are relative to `spec`; `agent` is inside `sandboxes.` and `routes[]` is inside an inline or shared inference configuration. | Family | Enclosing definitions | Consumer selection | Current runtime limit | |---|---|---|---| -| Inference provider | `inferenceProviders[]` or `sandboxes[].inferenceProviders[]`, each with a `name` | Route `provider` or `providerRef` | Up to 32 selected providers; each uses an external endpoint or references a named service | -| Inference | `inferences.` or `sandboxes[].inferences.` | Agent `inference` or `inferenceRef` | An explicit default selects a Fabric model role; Fabric validates the adapter's supported roles | -| Harness | `harnesses.` or `sandboxes[].harnesses.` | Sandbox `harness` or `harnessRef` | Exactly one configuration and one agent per sandbox | -| Integration | `integrations.` or `sandboxes[].integrations.` | Agent `integrations.` and/or `integrationRefs` | Brave or Tavily `webSearch` credentials and grants; one attached search definition per sandbox | - -Inference providers are list entries with a `name`; inferences, harnesses, and integrations are maps keyed by name. -Inline providers also require `name`. -Deployment-level provider names identify their OpenShell registrations; sandbox-local providers receive stable identities derived from the sandbox and provider names. -Different sandboxes can reuse a local definition name without sharing its registration. +| Inference provider | `inferenceProviders.` or `sandboxes..inferenceProviders.` | Route `provider` or `providerRef` | Up to 32 selected providers; each uses an external endpoint or references a named service | +| Inference | `inferences.` or `sandboxes..inferences.` | Agent `inference` or `inferenceRef` | An explicit default selects a Fabric model role; Fabric validates the adapter's supported roles | +| Harness | `harnesses.` or `sandboxes..harnesses.` | Sandbox `harness` or `harnessRef` | Exactly one configuration and one agent per sandbox | +| Integration | `integrations.` or `sandboxes..integrations.` | Agent `integrations.` and/or `integrationRefs` | Brave or Tavily `webSearch` credentials and grants; one attached search definition per sandbox | + +Sandboxes and the definitions in each family are maps keyed by name; a deployment-level or sandbox-level provider takes its name from its key. +An inline route `provider` has no key, so it requires `name`. +Each OpenShell registration name derives from the provider name, the sandbox that declares a sandbox-local definition, and the selecting sandbox's image reference and harness kind. +Sandboxes with the same image reference and harness kind share the registration of a deployment-level definition; different sandboxes can reuse a local definition name without sharing its registration. A document supports one to 32 named sandboxes; OpenClaw agents can select models from different providers. See [multiple model choices](inference.md#give-an-agent-multiple-model-choices) for defaults and current service limits. Multiple OpenClaw agents can reference the same provider and integration; distinct inline instances are not shared implicitly. @@ -74,12 +74,12 @@ spec: enabled: true allowedOrigins: [http://127.0.0.1:18800] sandboxes: - - name: researcher + researcher: harnessRef: assistant agent: name: researcher inferenceRef: chat - - name: writer + writer: harnessRef: assistant agent: name: writer @@ -101,7 +101,7 @@ Use `inferenceRef` to reuse the complete inference configuration, including its ```yaml spec: inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11446/v1 inferences: @@ -112,12 +112,12 @@ spec: overrides: model: qwen3:4b sandboxes: - - name: researcher + researcher: harness: {kind: nvidia.fabric.openclaw} agent: name: researcher inferenceRef: chat - - name: writer + writer: harness: {kind: nvidia.fabric.openclaw} agent: name: writer @@ -137,11 +137,11 @@ This fragment omits the deployment's other required fields: ```yaml spec: inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11446/v1 sandboxes: - - name: assistant + assistant: harness: {kind: nvidia.fabric.openclaw} agent: name: researcher diff --git a/docs/contributing/configuration-schema.md b/docs/contributing/configuration-schema.md index f0dd3a807dc..e1a2c56cba8 100644 --- a/docs/contributing/configuration-schema.md +++ b/docs/contributing/configuration-schema.md @@ -86,7 +86,7 @@ For a semantic check outside the schema, document the distinction in the generat `Document::parse` owns YAML syntax restrictions and invokes both validation stages. Schema diagnostics identify document fields, array indices, and constraints without echoing rejected values or unknown properties. -Valid names in the declared service, harness, inference, and integration collections identify the failing definition; other map keys appear as `[entry]`. +Valid names identify the failing definition in `spec.sandboxes`, `spec.inferenceProviders`, `spec.services`, `spec.harnesses`, `spec.inferences`, and `spec.integrations`, and in a validly named sandbox's `inferenceProviders`, `harnesses`, `inferences`, `integrations`, and `agent.integrations`; keys that are not valid names, and keys of other maps, appear as `[entry]`. Parsing a document also reports the source line and column for schema failures and YAML syntax errors. When a field moves or is removed, map its old name to a message naming the replacement in the rejecting object's `x-nemoclaw-removed-fields` annotation; the diagnostic then reports the messages of all such fields in the input instead of an unknown field. The `spec.gateway` variants list the fields that moved into `spec.gateway.target`; the reference generator does not render this annotation. diff --git a/docs/design/onboarding-journeys.md b/docs/design/onboarding-journeys.md index 9868fa97490..05536c54020 100644 --- a/docs/design/onboarding-journeys.md +++ b/docs/design/onboarding-journeys.md @@ -89,12 +89,13 @@ Run `cargo run -p nemoclaw-authoring --example print_journey_tree` from the repo | Preview | Input | Result | | --- | --- | --- | -| Minimum viable values | One empty sandbox, with explicit `ask` guidance for the name. | Stops at an unresolved SDK frontier; it does not enumerate every question. | -| Minimum inline scaffold | `crates/nemoclaw-authoring/tests/fixtures/minimum-inline.yaml`: inline harness and inference forms, one route, and an external endpoint. | Asks the deployment, sandbox, agent, and route names, gateway management, harness, provider kind, and model. `minimally_supplied_inline_envelope_materializes_through_one_resolver` materializes it after those answers and explicit optional omissions. | +| Minimum viable values | One empty sandbox keyed `assistant`, with explicit `ask` guidance for the deployment name. | Stops at an unresolved SDK frontier; it does not enumerate every question. | +| Minimum inline scaffold | `crates/nemoclaw-authoring/tests/fixtures/minimum-inline.yaml`: one sandbox keyed `assistant`, inline harness and inference forms, one route, and an external endpoint. | Asks the deployment, agent, and route names, gateway management, harness, provider kind, and model. `minimally_supplied_inline_envelope_materializes_through_one_resolver` materializes it after those answers and explicit optional omissions. | | Express | `examples/onboarding/openclaw.yaml`. | Zero questions, with absent optional adapter settings omitted through the `ActiveAdapterSettings` scope. Target compatibility remains a separate assessment. | -| Guided preview | The express template without a route model, with explicit `ask` guidance for the name, harness, gateway target, provider, API, and model fields. | Asks each of those fields. | +| Guided preview | The express template without a route model, with explicit `ask` guidance for the deployment name, harness, gateway target, provider, API, and model fields. | Asks each of those fields. | Starting a journey generates a missing deployment uid, so the uid is never a question. +A journey starts only when the partial document supplies exactly one sandbox; its key is the sandbox name, so that name is never a question. These previews do not establish complete coverage of arbitrary partial documents. ## Prototype Decisions and Limits diff --git a/docs/get-started.md b/docs/get-started.md index 463f3eaa0dc..6d788d32b5d 100644 --- a/docs/get-started.md +++ b/docs/get-started.md @@ -69,10 +69,10 @@ Edit the copied YAML before executing it: | `spec.gateway.target` key | `docker` or `podman`, matching your gateway's compute driver; see [gateway targets](usage.md#choose-the-gateway-target) | | `engine` under that key | The Docker or Podman engine containing the immutable sandbox image; replace the example's illustrative socket with that engine's address | | `spec.gateway.credential` and `spec.gateway.tls` | References required by that gateway; omit optional fields when unused | -| `spec.inferenceProviders[0].endpoint` | Your upstream inference base URL | -| `spec.inferenceProviders[0].provider` and `.api` | The [matching protocol and API](inference.md); the example selects OpenAI Responses | -| `spec.inferenceProviders[0].credential` | An environment reference when the endpoint needs a key | -| `spec.sandboxes[0].image.ref` | The immutable reference from your image build | +| `spec.inferenceProviders.local.endpoint` | Your upstream inference base URL | +| `spec.inferenceProviders.local.provider` and `.api` | The [matching protocol and API](inference.md); the example selects OpenAI Responses | +| `spec.inferenceProviders.local.credential` | An environment reference when the endpoint needs a key | +| `spec.sandboxes.assistant.image.ref` | The immutable reference from your image build | | The primary route's `overrides.model` | The exact model ID served by your endpoint | | Other route `overrides` | Limits and reasoning settings supported by that model; remove optional tuning you have not verified | diff --git a/docs/inference.md b/docs/inference.md index 531f70239a1..1d1f5ef7a9f 100644 --- a/docs/inference.md +++ b/docs/inference.md @@ -136,7 +136,7 @@ Guides for named hosted providers are tracked in [#12038](https://github.com/NVI ## Use an Image Built from This Revision -Explicit API selection, tuning, and authentication require an agent image built from this revision; [build it](build.md#build-agent-images) and use its immutable digest in `sandboxes[].image.ref`. +Explicit API selection, tuning, and authentication require an agent image built from this revision; [build it](build.md#build-agent-images) and use its immutable digest in `spec.sandboxes..image.ref`. The [tuning example](../examples/inference-tuning.yaml) and [Hermes authentication example](../examples/hermes-auth.yaml) contain zero-digest placeholders that must be replaced before deployment. Set their gateway and inference endpoints and model IDs for your services, and assign a fresh deployment UID. Model and native settings changes restart the runtime inside the existing sandbox; changing its image requires a separate deployment, as described in [the change path](usage.md#choose-the-change-path). @@ -187,7 +187,7 @@ services: memory: gpuMemoryGiB: 16 inferenceProviders: - - name: qwen + qwen: provider: openai api: openai-completions serviceRef: qwen @@ -237,7 +237,7 @@ Live image builds, GPU inference, tools and agent replies with this adapter have Set `authentication: bearer` under `spec.services.` to generate a private key for a managed vLLM service. Omission preserves the existing unauthenticated serving behavior. Build the [runtime image](build.md#build-a-runtime-image) from this revision and use its immutable digest; a container created from an incompatible image will not satisfy application readiness. -Do not supply `inferenceProviders[].credential` for a managed service. +Do not set `credential` on a provider that references a managed service. The supervisor creates a mode-0600 key in `/credentials/inference-key` on a separate credential volume under its own writer lock and reuses it after restart. It passes the key only to the vLLM child process through `VLLM_API_KEY`, then verifies `/v1/models` using bearer authentication before reporting readiness. @@ -289,7 +289,7 @@ services: name: qwen3:4b digest: REPLACE_WITH_MODEL_DIGEST inferenceProviders: - - name: local + local: provider: openai serviceRef: local ``` @@ -347,7 +347,7 @@ Declare an external HTTPS provider with a credential reference, then select it f ```yaml # Under spec.inferenceProviders: -- name: nous +nous: provider: openai api: openai-completions endpoint: https://inference-api.nousresearch.com/v1 diff --git a/docs/models.md b/docs/models.md index 0be1d459654..1b915bb508a 100644 --- a/docs/models.md +++ b/docs/models.md @@ -241,7 +241,7 @@ The example requires an existing OpenShell gateway and a Linux AMD64 Docker host That host must expose exactly one NVIDIA GPU with compute capability at least 9.0, at least 96,000,000,000 bytes of dedicated GPU memory, and driver major 580 or newer. Follow the [SSH placement prerequisites](remote-service.md), build the [AMD64 runtime image](build.md#build-a-runtime-image) on a matching host, and load it into the selected Docker daemon. Replace the zero image digest, SSH alias, gateway endpoint, private publication address, and deployment UID before applying. -Build a compatible OpenClaw sandbox image using the [agent image procedure](build.md#build-agent-images), replace `sandboxes[].image.ref` with its immutable digest, and load that image into the gateway's Podman daemon. +Build a compatible OpenClaw sandbox image using the [agent image procedure](build.md#build-agent-images), replace `spec.sandboxes..image.ref` with its immutable digest, and load that image into the gateway's Podman daemon. `hardware` declares the dedicated-GPU requirements. `memory.gpuMemoryUtilization: 0.75` allocates a fraction of the observed GPU memory and leaves KV-cache sizing to vLLM. diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 4b5a1392d02..bb94e9ec118 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -56,7 +56,7 @@ Guide: [Agent runtimes](../agents.md). Paths: -- `spec.sandboxes[].agent` +- `spec.sandboxes.{key}.agent` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -76,7 +76,7 @@ Guide: [Inference configuration](../inference.md). Paths: -- `spec.sandboxes[].agent.auth` +- `spec.sandboxes.{key}.agent.auth` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -91,8 +91,8 @@ Guide: [Agent runtimes](../agents.md). Paths: - `spec.harnesses.{key}.execution` -- `spec.sandboxes[].harness.execution` -- `spec.sandboxes[].harnesses.{key}.execution` +- `spec.sandboxes.{key}.harness.execution` +- `spec.sandboxes.{key}.harnesses.{key}.execution` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -106,7 +106,7 @@ Guide: [Agent runtimes](../agents.md). Paths: -- `spec.sandboxes[].agent.tools` +- `spec.sandboxes.{key}.agent.tools` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -120,7 +120,7 @@ Guide: [Inference configuration](../inference.md). Paths: -- `spec.sandboxes[].agent.auth.method` +- `spec.sandboxes.{key}.agent.auth.method` Accepted input: string. @@ -185,7 +185,7 @@ Guide: [Sandbox policy](../sandbox-network.md). Paths: -- `spec.sandboxes[].network.policy.explicit` +- `spec.sandboxes.{key}.network.policy.explicit` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -203,7 +203,7 @@ Guide: [Sandbox policy](../sandbox-network.md). Paths: -- `spec.sandboxes[].network.policy` +- `spec.sandboxes.{key}.network.policy` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -333,7 +333,7 @@ Paths: - `spec.gateway.tls.ca` - `spec.gateway.tls.certificate` - `spec.gateway.tls.key` -- `spec.sandboxes[].image.metadata` +- `spec.sandboxes.{key}.image.metadata` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -397,8 +397,8 @@ Guide: [Configuration and credentials](../usage.md#configuration-and-credentials Paths: - `spec.harnesses.{key}` -- `spec.sandboxes[].harness` -- `spec.sandboxes[].harnesses.{key}` +- `spec.sandboxes.{key}.harness` +- `spec.sandboxes.{key}.harnesses.{key}` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -415,7 +415,7 @@ Guide: [Configuration and credentials](../usage.md#configuration-and-credentials Paths: -- `spec.sandboxes[].image` +- `spec.sandboxes.{key}.image` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -446,8 +446,8 @@ Guide: [Inference configuration](../inference.md). Paths: - `spec.inferences.{key}` -- `spec.sandboxes[].agent.inference` -- `spec.sandboxes[].inferences.{key}` +- `spec.sandboxes.{key}.agent.inference` +- `spec.sandboxes.{key}.inferences.{key}` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -462,11 +462,11 @@ Guide: [Inference configuration](../inference.md). Paths: -- `spec.inferenceProviders[].api` +- `spec.inferenceProviders.{key}.api` - `spec.inferences.{key}.routes[].provider.api` -- `spec.sandboxes[].agent.inference.routes[].provider.api` -- `spec.sandboxes[].inferenceProviders[].api` -- `spec.sandboxes[].inferences.{key}.routes[].provider.api` +- `spec.sandboxes.{key}.agent.inference.routes[].provider.api` +- `spec.sandboxes.{key}.inferenceProviders.{key}.api` +- `spec.sandboxes.{key}.inferences.{key}.routes[].provider.api` Accepted input: string. @@ -480,18 +480,35 @@ Guide: [Inference configuration](../inference.md). Paths: -- `spec.inferenceProviders[]` +- `spec.inferenceProviders.{key}` +- `spec.sandboxes.{key}.inferenceProviders.{key}` + +| Field | Input type | Required | Default | Description and constraints | +|---|---|---|---|---| +| `api` | [InferenceApi](#inferenceapi) | No | — | Request API. Omission selects anthropic-messages for Anthropic providers and openai-completions for OpenAI providers; explicit values are preserved for Fabric validation. | +| `credential` | [SecretRef](#secretref) | No | — | Optional API credential reference for an external HTTPS endpoint. Excluded by serviceRef. | +| `endpoint` | string | Without serviceRef | — | Inference HTTP(S) URL owned outside the deployment. Required without serviceRef and excluded with serviceRef. | +| `provider` | string | Yes | — | OpenShell provider implementation. Must match the selected API family. Constraints: `"openai"` or `"anthropic"`. | +| `serviceRef` | string | No | — | Name of a managed service in spec.services. Excludes endpoint and credential. Constraints: pattern `^[a-z][a-z0-9-]{0,39}$`. | + +## InlineInferenceProvider + +Inference definition owned by one route: choose an endpoint for external inference or serviceRef for a managed service. It has no map key, so it states its own name. + +Guide: [Inference configuration](../inference.md). + +Paths: + - `spec.inferences.{key}.routes[].provider` -- `spec.sandboxes[].agent.inference.routes[].provider` -- `spec.sandboxes[].inferenceProviders[]` -- `spec.sandboxes[].inferences.{key}.routes[].provider` +- `spec.sandboxes.{key}.agent.inference.routes[].provider` +- `spec.sandboxes.{key}.inferences.{key}.routes[].provider` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| | `api` | [InferenceApi](#inferenceapi) | No | — | Request API. Omission selects anthropic-messages for Anthropic providers and openai-completions for OpenAI providers; explicit values are preserved for Fabric validation. | | `credential` | [SecretRef](#secretref) | No | — | Optional API credential reference for an external HTTPS endpoint. Excluded by serviceRef. | | `endpoint` | string | Without serviceRef | — | Inference HTTP(S) URL owned outside the deployment. Required without serviceRef and excluded with serviceRef. | -| `name` | string | Yes | — | Provider name referenced by model choices. Constraints: pattern `^[a-z][a-z0-9-]{0,39}$`. | +| `name` | string | Yes | — | Lowercase provider name. It must not shadow an enclosing definition. Constraints: pattern `^[a-z][a-z0-9-]{0,39}$`. | | `provider` | string | Yes | — | OpenShell provider implementation. Must match the selected API family. Constraints: `"openai"` or `"anthropic"`. | | `serviceRef` | string | No | — | Name of a managed service in spec.services. Excludes endpoint and credential. Constraints: pattern `^[a-z][a-z0-9-]{0,39}$`. | @@ -527,8 +544,8 @@ Guide: [Agent runtimes](../agents.md). Paths: - `spec.integrations.{key}` -- `spec.sandboxes[].agent.integrations.{key}` -- `spec.sandboxes[].integrations.{key}` +- `spec.sandboxes.{key}.agent.integrations.{key}` +- `spec.sandboxes.{key}.integrations.{key}` Accepted input: object. @@ -727,7 +744,7 @@ Guide: [Sandbox policy](../sandbox-network.md). Paths: -- `spec.sandboxes[].network` +- `spec.sandboxes.{key}.network` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -795,8 +812,8 @@ Guide: [Inference configuration](../inference.md). Paths: - `spec.inferences.{key}.routes[].overrides` -- `spec.sandboxes[].agent.inference.routes[].overrides` -- `spec.sandboxes[].inferences.{key}.routes[].overrides` +- `spec.sandboxes.{key}.agent.inference.routes[].overrides` +- `spec.sandboxes.{key}.inferences.{key}.routes[].overrides` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -812,7 +829,7 @@ Guide: [Sandbox policy](../sandbox-network.md). Paths: -- `spec.sandboxes[].network.policy.explicit.network_policies.{key}.endpoints[].rules[]` +- `spec.sandboxes.{key}.network.policy.explicit.network_policies.{key}.endpoints[].rules[]` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -826,10 +843,10 @@ Guide: [Sandbox policy](../sandbox-network.md). Paths: -- `spec.sandboxes[].network.policy.explicit.network_policies.{key}.endpoints[].deny_rules[].params.{key}` -- `spec.sandboxes[].network.policy.explicit.network_policies.{key}.endpoints[].deny_rules[].tool` -- `spec.sandboxes[].network.policy.explicit.network_policies.{key}.endpoints[].rules[].allow.params.{key}` -- `spec.sandboxes[].network.policy.explicit.network_policies.{key}.endpoints[].rules[].allow.tool` +- `spec.sandboxes.{key}.network.policy.explicit.network_policies.{key}.endpoints[].deny_rules[].params.{key}` +- `spec.sandboxes.{key}.network.policy.explicit.network_policies.{key}.endpoints[].deny_rules[].tool` +- `spec.sandboxes.{key}.network.policy.explicit.network_policies.{key}.endpoints[].rules[].allow.params.{key}` +- `spec.sandboxes.{key}.network.policy.explicit.network_policies.{key}.endpoints[].rules[].allow.tool` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -843,7 +860,7 @@ Guide: [Sandbox policy](../sandbox-network.md). Paths: -- `spec.sandboxes[].network.policy.explicit.network_policies.{key}.binaries[]` +- `spec.sandboxes.{key}.network.policy.explicit.network_policies.{key}.binaries[]` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -857,7 +874,7 @@ Guide: [Sandbox policy](../sandbox-network.md). Paths: -- `spec.sandboxes[].network.policy.explicit.network_policies.{key}.endpoints[]` +- `spec.sandboxes.{key}.network.policy.explicit.network_policies.{key}.endpoints[]` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -886,7 +903,7 @@ Guide: [Sandbox policy](../sandbox-network.md). Paths: -- `spec.sandboxes[].network.policy.explicit.filesystem_policy` +- `spec.sandboxes.{key}.network.policy.explicit.filesystem_policy` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -902,7 +919,7 @@ Guide: [Sandbox policy](../sandbox-network.md). Paths: -- `spec.sandboxes[].network.policy.explicit.network_policies.{key}.endpoints[].json_rpc` +- `spec.sandboxes.{key}.network.policy.explicit.network_policies.{key}.endpoints[].json_rpc` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -916,7 +933,7 @@ Guide: [Sandbox policy](../sandbox-network.md). Paths: -- `spec.sandboxes[].network.policy.explicit.landlock` +- `spec.sandboxes.{key}.network.policy.explicit.landlock` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -930,8 +947,8 @@ Guide: [Sandbox policy](../sandbox-network.md). Paths: -- `spec.sandboxes[].network.policy.explicit.network_policies.{key}.endpoints[].deny_rules[]` -- `spec.sandboxes[].network.policy.explicit.network_policies.{key}.endpoints[].rules[].allow` +- `spec.sandboxes.{key}.network.policy.explicit.network_policies.{key}.endpoints[].deny_rules[]` +- `spec.sandboxes.{key}.network.policy.explicit.network_policies.{key}.endpoints[].rules[].allow` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -948,7 +965,7 @@ Guide: [Sandbox policy](../sandbox-network.md). Paths: -- `spec.sandboxes[].network.policy.explicit.network_policies.{key}.endpoints[].mcp` +- `spec.sandboxes.{key}.network.policy.explicit.network_policies.{key}.endpoints[].mcp` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -965,7 +982,7 @@ Guide: [Sandbox policy](../sandbox-network.md). Paths: -- `spec.sandboxes[].network.policy.explicit.process` +- `spec.sandboxes.{key}.network.policy.explicit.process` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -980,7 +997,7 @@ Guide: [Sandbox policy](../sandbox-network.md). Paths: -- `spec.sandboxes[].network.policy.explicit.network_policies.{key}` +- `spec.sandboxes.{key}.network.policy.explicit.network_policies.{key}` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -996,10 +1013,10 @@ Guide: [Sandbox policy](../sandbox-network.md). Paths: -- `spec.sandboxes[].network.policy.explicit.network_policies.{key}.endpoints[].deny_rules[].params.{key}` -- `spec.sandboxes[].network.policy.explicit.network_policies.{key}.endpoints[].deny_rules[].tool` -- `spec.sandboxes[].network.policy.explicit.network_policies.{key}.endpoints[].rules[].allow.params.{key}` -- `spec.sandboxes[].network.policy.explicit.network_policies.{key}.endpoints[].rules[].allow.tool` +- `spec.sandboxes.{key}.network.policy.explicit.network_policies.{key}.endpoints[].deny_rules[].params.{key}` +- `spec.sandboxes.{key}.network.policy.explicit.network_policies.{key}.endpoints[].deny_rules[].tool` +- `spec.sandboxes.{key}.network.policy.explicit.network_policies.{key}.endpoints[].rules[].allow.params.{key}` +- `spec.sandboxes.{key}.network.policy.explicit.network_policies.{key}.endpoints[].rules[].allow.tool` Accepted input: string or [PolicyAnyMatcher](#policyanymatcher). @@ -1044,14 +1061,14 @@ Guide: [Inference configuration](../inference.md). Paths: - `spec.inferences.{key}.routes[]` -- `spec.sandboxes[].agent.inference.routes[]` -- `spec.sandboxes[].inferences.{key}.routes[]` +- `spec.sandboxes.{key}.agent.inference.routes[]` +- `spec.sandboxes.{key}.inferences.{key}.routes[]` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| | `name` | string | Yes | — | Unique lowercase name for this model choice. Constraints: pattern `^[a-z][a-z0-9-]{0,39}$`. | | `overrides` | [Overrides](#overrides) | Yes | — | Model selection, shared limits, and optional native settings. | -| `provider` | [InferenceProvider](#inferenceprovider) | No | — | Inline inference definition owned by this route. Excludes providerRef and must not shadow an enclosing definition. | +| `provider` | [InlineInferenceProvider](#inlineinferenceprovider) | No | — | Inline inference definition owned by this route. Excludes providerRef and must not shadow an enclosing definition. | | `providerRef` | string | No | — | Name of an enclosing inference provider. Exactly one of providerRef or provider is required. Constraints: pattern `^[a-z][a-z0-9-]{0,39}$`. | ## Sandbox @@ -1062,7 +1079,7 @@ Guide: [Configuration and credentials](../usage.md#configuration-and-credentials Paths: -- `spec.sandboxes[]` +- `spec.sandboxes.{key}` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -1071,10 +1088,9 @@ Paths: | `harnessRef` | string | No | — | Name of a visible harness configuration. Excludes inline harness. Constraints: pattern `^[a-z][a-z0-9-]{0,39}$`. | | `harnesses` | map of [Harness](#harness) | No | — | Named harness configurations available through harnessRef. Selecting a definition reuses configuration; runtime processes belong to each sandbox. Constraints: keys: pattern `^[a-z][a-z0-9-]{0,39}$`. | | `image` | [Image](#image) | With a Kubernetes target | — | Agent image compatible with the gateway's runtime user and group IDs. A Kubernetes target requires an explicit `ref` and `metadata`; Docker and Podman targets may omit it and use the generic SDK agent image pin. | -| `inferenceProviders` | array of [InferenceProvider](#inferenceprovider) | No | — | Named inference definitions visible to this sandbox's routes. Names must not shadow deployment definitions. | +| `inferenceProviders` | map of [InferenceProvider](#inferenceprovider) | No | — | Inference definitions keyed by lowercase name and visible to this sandbox's routes. Names must not shadow deployment definitions. Constraints: keys: pattern `^[a-z][a-z0-9-]{0,39}$`. | | `inferences` | map of [Inference](#inference) | No | — | Named inference configurations available through inferenceRef. Definitions resolve providers in their own scope and create no resources until selected. Constraints: keys: pattern `^[a-z][a-z0-9-]{0,39}$`. | | `integrations` | map of [Integration](#integration) | No | — | Named integration definitions selected by this sandbox's agent through integrationRefs. Names must not collide with deployment definitions. Constraints: keys: pattern `^[a-z][a-z0-9-]{0,39}$`. | -| `name` | string | Yes | — | Lowercase sandbox name. Constraints: pattern `^[a-z][a-z0-9-]{0,39}$`. | | `network` | [Network](#network) | No | — | Sandbox network policy; omission selects isolated egress with grants for declared inference. | ## SearchProvider @@ -1086,8 +1102,8 @@ Guide: [Agent runtimes](../agents.md). Paths: - `spec.integrations.{key}.provider` -- `spec.sandboxes[].agent.integrations.{key}.provider` -- `spec.sandboxes[].integrations.{key}.provider` +- `spec.sandboxes.{key}.agent.integrations.{key}.provider` +- `spec.sandboxes.{key}.integrations.{key}.provider` Accepted input: string. @@ -1102,14 +1118,14 @@ Guide: [Configuration and credentials](../usage.md#configuration-and-credentials Paths: - `spec.gateway.credential` -- `spec.inferenceProviders[].credential` +- `spec.inferenceProviders.{key}.credential` - `spec.inferences.{key}.routes[].provider.credential` - `spec.integrations.{key}.credential` -- `spec.sandboxes[].agent.inference.routes[].provider.credential` -- `spec.sandboxes[].agent.integrations.{key}.credential` -- `spec.sandboxes[].inferenceProviders[].credential` -- `spec.sandboxes[].inferences.{key}.routes[].provider.credential` -- `spec.sandboxes[].integrations.{key}.credential` +- `spec.sandboxes.{key}.agent.inference.routes[].provider.credential` +- `spec.sandboxes.{key}.agent.integrations.{key}.credential` +- `spec.sandboxes.{key}.inferenceProviders.{key}.credential` +- `spec.sandboxes.{key}.inferences.{key}.routes[].provider.credential` +- `spec.sandboxes.{key}.integrations.{key}.credential` | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| @@ -1336,10 +1352,10 @@ Paths: |---|---|---|---|---| | `gateway` | [Gateway](#gateway) | Yes | — | OpenShell gateway connection or managed gateway settings. | | `harnesses` | map of [Harness](#harness) | No | — | Named harness configurations available through harnessRef. Selecting a definition reuses configuration; runtime processes belong to each sandbox. Constraints: keys: pattern `^[a-z][a-z0-9-]{0,39}$`. | -| `inferenceProviders` | array of [InferenceProvider](#inferenceprovider) | No | — | Named inference definitions available to sandbox routes. Unselected definitions create no resources or credential requirements. | +| `inferenceProviders` | map of [InferenceProvider](#inferenceprovider) | No | — | Inference definitions keyed by lowercase name and available to sandbox routes. Unselected definitions create no resources or credential requirements. Constraints: keys: pattern `^[a-z][a-z0-9-]{0,39}$`. | | `inferences` | map of [Inference](#inference) | No | — | Named inference configurations available through inferenceRef. Definitions resolve providers in their own scope and create no resources until selected. Constraints: keys: pattern `^[a-z][a-z0-9-]{0,39}$`. | | `integrations` | map of [Integration](#integration) | No | — | Named integration definitions shared by agents through integrationRefs. Definitions alone grant no access. Constraints: keys: pattern `^[a-z][a-z0-9-]{0,39}$`. | -| `sandboxes` | array of [Sandbox](#sandbox) | Yes | — | One to 32 uniquely named sandboxes. Each runs one agent through its selected Fabric adapter. Declaration order does not select a default sandbox or agent. Constraints: minimum items 1; maximum items 32. | +| `sandboxes` | map of [Sandbox](#sandbox) | Yes | — | One to 32 sandboxes keyed by lowercase name. Each runs one agent through its selected Fabric adapter. Key order has no meaning and selects no default sandbox or agent. Constraints: minimum entries 1; maximum entries 32; keys: pattern `^[a-z][a-z0-9-]{0,39}$`. | | `services` | map of [ServiceDefinition](#servicedefinition) | No | — | Named managed container services to install, verify once, and remove during destroy. Inference providers may consume their connection through serviceRef. Constraints: keys: pattern `^[a-z][a-z0-9-]{0,39}$`. | ## TLS diff --git a/docs/sandbox-network.md b/docs/sandbox-network.md index 53164a540db..33f0784015d 100644 --- a/docs/sandbox-network.md +++ b/docs/sandbox-network.md @@ -3,7 +3,7 @@ # Configure Sandbox Policy -Use `sandboxes[].network.policy.explicit` to declare filesystem, process, and egress policy. +Use `spec.sandboxes..network.policy.explicit` to declare filesystem, process, and egress policy. Start from [the explicit-policy example](../examples/explicit-policy.yaml) and follow [deployment usage](usage.md) to plan, apply, and export it. Before applying, select a fresh deployment UUID, an available gateway and inference endpoint, and an immutable agent image available to the runtime. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 1dc4effefbf..f9004cf3ee7 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -61,7 +61,7 @@ Retain the original binding while investigating the selected gateway and engine. ## Correct a Document Validation Error Schema errors identify the document field, the violated constraint, and the source line and column. -For example, `spec.services.qwen.memory.kvCacheGiB` identifies the `qwen` service; `spec.sandboxes[1]` identifies the second sandbox. +For example, `spec.services.qwen.memory.kvCacheGiB` identifies the `qwen` service, and `spec.sandboxes.assistant.agent.inference.routes[1]` identifies the second route of the `assistant` sandbox. Array indices start at zero; source lines and columns start at one, and columns count characters. Valid declaration names appear in paths, while arbitrary map keys appear as `[entry]` and rejected values remain omitted. YAML syntax and duplicate-key errors also include source positions without copying source snippets. diff --git a/docs/usage.md b/docs/usage.md index dc5a050c3a0..e2d9800cc79 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -44,11 +44,12 @@ See [CLI options and output](reference/cli.md) for bundle selection, formats, an ## Configure Sandboxes and Inference -A document contains one to 32 named sandboxes, each with one harness and one agent. +`spec.sandboxes` holds one to 32 sandboxes keyed by name, each with one harness and one agent. +Key order has no meaning: export writes sandboxes and inference providers in name order, and apply reports sandbox health in name order. Use the [multiple-sandbox example](../examples/multiple-sandboxes.yaml) to share inference across different harnesses. [OpenClaw and Pi](agents.md) can select multiple models; each Deep Agents instance selects one. -Declare managed services under `spec.services` and select their connections with `inferenceProviders[].serviceRef`. +Declare managed services under `spec.services` and select their connections with an inference provider's `serviceRef`. Every declared service is installed and checked, even without an inference consumer. Services run on the gateway's Docker engine by default, or on another host through [SSH placement](remote-service.md). See [service constraints](inference.md#combine-local-and-hosted-providers) for multiple Ollama/vLLM services and [models](models.md) for hardware contracts and optional [recipes](recipes.md). @@ -238,14 +239,14 @@ Apply recomputes its plan; a successful earlier plan does not reserve resources ### Multiple Sandboxes -Sandbox names must be unique within a deployment; each sandbox declares one named agent. +Each sandbox declares one named agent. Agent names may repeat across sandboxes. -Adding a named sandbox preserves existing sandbox and provider identities. -Reordering declarations is not an update. -Each sandbox receives only its selected inference provider policies, while shared definitions reuse one provider registration. +Adding a sandbox preserves existing sandbox and provider identities. +Each sandbox receives only its selected inference provider policies; sandboxes with the same image reference and harness kind share the registration of a shared definition. Sandbox-local definitions are visible only to their enclosing sandbox. Sandboxes can select distinct Brave credential references; shared references reuse one registration. -Apply still refuses sandbox removal or replacement because its files and history are not separately retained; destroy operates on the whole deployment. +Apply still refuses to remove, rename, or replace an applied sandbox because its files and history are not separately retained; renaming its key removes the sandbox under the old name. +Destroy operates on the whole deployment. Use separate deployments when you need independent teardown. ### Choose the Change Path @@ -259,7 +260,7 @@ Use separate deployments when you need independent teardown. | Managed inference or proxy image or serving specification | Docker-provider reconciliation may replace the container while retaining its independently bound storage; review the plan and [model constraints](models.md) | | Deployment UID, [bound gateway settings](#choose-the-gateway-target), or bound credentials | Cannot retarget the existing state; create a separate deployment | | Remove an unused inference provider definition | Changes the desired document only; the SDK creates registrations for selected definitions, so unused definitions have no resources to delete | -| Remove a sandbox, retained storage, or a protected gateway binding | Apply refuses removal; assess a separate deployment and explicit retirement of the original | +| Remove or rename a sandbox, or remove retained storage or a protected gateway binding | Apply refuses removal; assess a separate deployment and explicit retirement of the original | | Change a credential value behind the same environment reference | Unchanged apply does not detect rotation; see [credential lifecycle](security.md#credentials-and-authentication) | Configuration edits do not recover a runtime whose bridge snapshot reports `runtime_state: unknown`. diff --git a/examples/explicit-policy.yaml b/examples/explicit-policy.yaml index bddf3c41c85..5b573c5ffd6 100644 --- a/examples/explicit-policy.yaml +++ b/examples/explicit-policy.yaml @@ -14,11 +14,11 @@ spec: target: docker: {} inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11436/v1 sandboxes: - - name: assistant + assistant: network: policy: explicit: diff --git a/examples/fabric-claude.yaml b/examples/fabric-claude.yaml index db1e09cc302..066fc79d284 100644 --- a/examples/fabric-claude.yaml +++ b/examples/fabric-claude.yaml @@ -16,11 +16,11 @@ spec: target: docker: {} inferenceProviders: - - name: local + local: provider: anthropic endpoint: http://172.20.0.1:11446/v1 sandboxes: - - name: assistant + assistant: image: ref: nc-prototype-fabric@sha256:ad0f0a9bdef6b1d1efd77b850cff8137d257fee03aa29e3b6980d81cd52fb3fb network: diff --git a/examples/fabric-codex.yaml b/examples/fabric-codex.yaml index 465185d16a4..f6a2510b716 100644 --- a/examples/fabric-codex.yaml +++ b/examples/fabric-codex.yaml @@ -16,12 +16,12 @@ spec: target: docker: {} inferenceProviders: - - name: local + local: provider: openai api: openai-responses endpoint: http://172.20.0.1:11446/v1 sandboxes: - - name: assistant + assistant: image: ref: nc-prototype-fabric@sha256:5d7ab97e878116ae728df2a29386345b4214975fa7360c8d091b6eb45cfb1479 network: diff --git a/examples/fabric-hermes.yaml b/examples/fabric-hermes.yaml index 3c1e0a82439..2325c1d75e6 100644 --- a/examples/fabric-hermes.yaml +++ b/examples/fabric-hermes.yaml @@ -14,11 +14,11 @@ spec: target: docker: {} inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11446/v1 sandboxes: - - name: assistant + assistant: image: ref: nc-prototype-fabric@sha256:22e0c2ddf37b8ee46c89341af7fd26f913072309630924038b62ad220dff0d40 network: diff --git a/examples/fabric-mini-swe-agent.yaml b/examples/fabric-mini-swe-agent.yaml index cbd75b293f5..670024ab511 100644 --- a/examples/fabric-mini-swe-agent.yaml +++ b/examples/fabric-mini-swe-agent.yaml @@ -16,11 +16,11 @@ spec: target: docker: {} inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11446/v1 sandboxes: - - name: assistant + assistant: image: ref: nc-prototype-fabric@sha256:b362c65247df2db9fd50f4699df5f2e067f68aabf3e7d2a6800b3ec03a9674f9 network: diff --git a/examples/fabric-nooa-bench.yaml b/examples/fabric-nooa-bench.yaml index f2fb5679ea1..303b3d9bb46 100644 --- a/examples/fabric-nooa-bench.yaml +++ b/examples/fabric-nooa-bench.yaml @@ -16,11 +16,11 @@ spec: target: docker: {} inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11446/v1 sandboxes: - - name: assistant + assistant: image: ref: nc-prototype-fabric@sha256:deaa2580e46f5d27105c7051771d36da36c5879ac2fea98e6b22cd651c910260 network: diff --git a/examples/fabric-nooa.yaml b/examples/fabric-nooa.yaml index 38fa4e3097f..e9355c22006 100644 --- a/examples/fabric-nooa.yaml +++ b/examples/fabric-nooa.yaml @@ -16,11 +16,11 @@ spec: target: docker: {} inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11446/v1 sandboxes: - - name: assistant + assistant: image: ref: nc-prototype-fabric@sha256:c1cf75ce3036c2c438375b8e9921eeca06f302a3f7f42d1e412cd571ffd8323b network: diff --git a/examples/fabric-openclaw.yaml b/examples/fabric-openclaw.yaml index b1271d00d6e..3a8586ee4cd 100644 --- a/examples/fabric-openclaw.yaml +++ b/examples/fabric-openclaw.yaml @@ -14,11 +14,11 @@ spec: target: docker: {} inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11446/v1 sandboxes: - - name: assistant + assistant: network: tier: isolated harness: diff --git a/examples/fabric-pi.yaml b/examples/fabric-pi.yaml index ee4758931b6..5a1cad6542d 100644 --- a/examples/fabric-pi.yaml +++ b/examples/fabric-pi.yaml @@ -16,11 +16,11 @@ spec: target: docker: {} inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11446/v1 sandboxes: - - name: assistant + assistant: image: ref: nc-multi-models@sha256:2ee5e33522a37d3d77bb6381a92e963cb1d5884f2dd28b353b4b7fa0d95f212e network: diff --git a/examples/fabric-remote-agent.yaml b/examples/fabric-remote-agent.yaml index 35bf78c6e15..146a39571d9 100644 --- a/examples/fabric-remote-agent.yaml +++ b/examples/fabric-remote-agent.yaml @@ -16,11 +16,11 @@ spec: target: docker: {} inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11446/v1 sandboxes: - - name: assistant + assistant: image: ref: nc-prototype-fabric@sha256:a60d580895c1667bddd2063078837134eb5cc7fea73aea7b0b6a55a4fa89204a network: diff --git a/examples/fabric.yaml b/examples/fabric.yaml index b2f261afb95..8e2a1b6cfcf 100644 --- a/examples/fabric.yaml +++ b/examples/fabric.yaml @@ -14,11 +14,11 @@ spec: target: docker: {} inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11446/v1 sandboxes: - - name: assistant + assistant: image: ref: nc-prototype-fabric@sha256:a6a0e5cf53501e765ae43457212989ff4716c6224352dc109ebd49c3780450cd network: diff --git a/examples/full-featured-openclaw.yaml b/examples/full-featured-openclaw.yaml index c9fafffa525..f0a8c2393b6 100644 --- a/examples/full-featured-openclaw.yaml +++ b/examples/full-featured-openclaw.yaml @@ -111,7 +111,7 @@ spec: memory: gpuMemoryUtilization: 0.75 inferenceProviders: - - name: nemotron + nemotron: provider: openai api: openai-completions serviceRef: nemotron @@ -122,7 +122,7 @@ spec: credential: env: BRAVE_API_KEY sandboxes: - - name: researcher + researcher: image: # Build a current Fabric OpenClaw image; the default image lacks these features. ref: @@ -189,7 +189,7 @@ spec: contextWindow: 65536 reasoning: true reasoning_effort: high - - name: writer + writer: image: # Build a current Fabric OpenClaw image; the default image lacks these features. ref: @@ -256,7 +256,7 @@ spec: contextWindow: 65536 reasoning: true reasoning_effort: high - - name: reader + reader: image: # Build a current Fabric OpenClaw image; the default image lacks these features. ref: diff --git a/examples/hermes-auth.yaml b/examples/hermes-auth.yaml index 5c57c8cac7a..298bcef6f0e 100644 --- a/examples/hermes-auth.yaml +++ b/examples/hermes-auth.yaml @@ -14,14 +14,14 @@ spec: target: docker: {} inferenceProviders: - - name: local + local: provider: openai api: openai-completions credential: env: NOUS_API_KEY endpoint: https://inference-api.nousresearch.com/v1 sandboxes: - - name: assistant + assistant: image: # Replace with the digest from a fresh Hermes image build; see docs/inference.md. ref: local-fabric-hermes@sha256:0000000000000000000000000000000000000000000000000000000000000000 diff --git a/examples/hermes-interfaces.yaml b/examples/hermes-interfaces.yaml index 27776d7634a..65c70e3d904 100644 --- a/examples/hermes-interfaces.yaml +++ b/examples/hermes-interfaces.yaml @@ -14,12 +14,12 @@ spec: target: docker: {} inferenceProviders: - - name: local + local: provider: openai api: openai-completions endpoint: http://172.20.0.1:11446/v1 sandboxes: - - name: assistant + assistant: image: ref: nc-prototype-fabric@sha256:0000000000000000000000000000000000000000000000000000000000000000 network: diff --git a/examples/inference-tuning.yaml b/examples/inference-tuning.yaml index 12e85ec428f..35df1dda98b 100644 --- a/examples/inference-tuning.yaml +++ b/examples/inference-tuning.yaml @@ -14,12 +14,12 @@ spec: target: docker: {} inferenceProviders: - - name: local + local: provider: openai api: openai-responses endpoint: https://inference.example.com/v1 sandboxes: - - name: assistant + assistant: image: # Replace with the digest from a fresh OpenClaw image build; see docs/inference.md. ref: local-fabric-openclaw@sha256:0000000000000000000000000000000000000000000000000000000000000000 diff --git a/examples/inline-inference.yaml b/examples/inline-inference.yaml index 729c0b5c183..cae010a63f1 100644 --- a/examples/inline-inference.yaml +++ b/examples/inline-inference.yaml @@ -15,7 +15,7 @@ spec: management: external endpoint: http://127.0.0.1:17681 sandboxes: - - name: assistant + assistant: harness: kind: nvidia.fabric.openclaw agent: diff --git a/examples/kubernetes/external-gateway.yaml b/examples/kubernetes/external-gateway.yaml index 8a77d469674..c4905948c11 100644 --- a/examples/kubernetes/external-gateway.yaml +++ b/examples/kubernetes/external-gateway.yaml @@ -23,13 +23,13 @@ spec: target: kubernetes: {} inferenceProviders: - - name: inference + inference: provider: openai endpoint: https://inference.example.com/v1 credential: {env: INFERENCE_API_KEY} # Each sandbox runs one independent agent using the shared inference profile. sandboxes: - - name: assistant + assistant: # Replace this example digest with an image adapted for the gateway's UID/GID 10001. image: metadata: {env: NEMOCLAW_AGENT_IMAGE_METADATA} @@ -41,7 +41,7 @@ spec: agent: name: main inferenceRef: chat - - name: researcher + researcher: image: metadata: {env: NEMOCLAW_AGENT_IMAGE_METADATA} ref: registry.example.com/nemoclaw/openclaw@sha256:0000000000000000000000000000000000000000000000000000000000000000 @@ -52,7 +52,7 @@ spec: agent: name: researcher inferenceRef: chat - - name: reviewer + reviewer: image: metadata: {env: NEMOCLAW_AGENT_IMAGE_METADATA} ref: registry.example.com/nemoclaw/openclaw@sha256:0000000000000000000000000000000000000000000000000000000000000000 diff --git a/examples/kubernetes/hosted-nvidia.yaml b/examples/kubernetes/hosted-nvidia.yaml index 1fb609cbb51..ffe07ab9a6b 100644 --- a/examples/kubernetes/hosted-nvidia.yaml +++ b/examples/kubernetes/hosted-nvidia.yaml @@ -24,7 +24,7 @@ spec: target: kubernetes: {} inferenceProviders: - - name: hosted-nvidia-prod + hosted-nvidia-prod: provider: openai api: openai-completions endpoint: https://integrate.api.nvidia.com/v1 @@ -32,7 +32,7 @@ spec: env: NVIDIA_INFERENCE_API_KEY # Each sandbox runs one independent agent using the shared inference profile. sandboxes: - - name: assistant + assistant: harness: kind: nvidia.fabric.openclaw image: @@ -65,7 +65,7 @@ spec: agent: name: primary inferenceRef: chat - - name: researcher + researcher: harness: kind: nvidia.fabric.openclaw image: @@ -98,7 +98,7 @@ spec: agent: name: researcher inferenceRef: chat - - name: reviewer + reviewer: harness: kind: nvidia.fabric.openclaw image: diff --git a/examples/kubernetes/managed-development.yaml b/examples/kubernetes/managed-development.yaml index b2738db5956..8cd8887b1a6 100644 --- a/examples/kubernetes/managed-development.yaml +++ b/examples/kubernetes/managed-development.yaml @@ -25,7 +25,7 @@ spec: authentication: profile: development inferenceProviders: - - name: hosted-nvidia + hosted-nvidia: provider: openai api: openai-completions endpoint: https://integrate.api.nvidia.com/v1 @@ -33,7 +33,7 @@ spec: env: NVIDIA_INFERENCE_API_KEY # Each sandbox runs one independent agent using the shared inference profile. sandboxes: - - name: assistant + assistant: harness: kind: nvidia.fabric.openclaw image: @@ -66,7 +66,7 @@ spec: agent: name: primary inferenceRef: chat - - name: researcher + researcher: harness: kind: nvidia.fabric.openclaw image: @@ -99,7 +99,7 @@ spec: agent: name: researcher inferenceRef: chat - - name: reviewer + reviewer: harness: kind: nvidia.fabric.openclaw image: diff --git a/examples/local.yaml b/examples/local.yaml index ed40565a80c..e16ad40e8f8 100644 --- a/examples/local.yaml +++ b/examples/local.yaml @@ -14,11 +14,11 @@ spec: target: docker: {} inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11436/v1 sandboxes: - - name: assistant + assistant: network: tier: isolated harness: diff --git a/examples/managed-hermes.yaml b/examples/managed-hermes.yaml index 5418df7f971..61e40448e88 100644 --- a/examples/managed-hermes.yaml +++ b/examples/managed-hermes.yaml @@ -28,11 +28,11 @@ spec: memory: gpuMemoryGiB: 16 inferenceProviders: - - name: local + local: provider: openai serviceRef: ollama-server sandboxes: - - name: assistant + assistant: image: ref: nc-prototype-fabric@sha256:0000000000000000000000000000000000000000000000000000000000000000 network: diff --git a/examples/managed-ollama-gpu.yaml b/examples/managed-ollama-gpu.yaml index d07f2b3ba0c..02ea33693a0 100644 --- a/examples/managed-ollama-gpu.yaml +++ b/examples/managed-ollama-gpu.yaml @@ -30,12 +30,12 @@ spec: memory: gpuMemoryGiB: 16 inferenceProviders: - - name: qwen + qwen: provider: openai api: openai-completions serviceRef: qwen sandboxes: - - name: assistant + assistant: image: ref: nc-multi-models@sha256:3ab70ded67440e838a37d6c9f0e3b08b95e2acf416c6076f8817bac190525cf0 network: diff --git a/examples/managed-ollama.yaml b/examples/managed-ollama.yaml index fa06ea603dd..1f9d18fca27 100644 --- a/examples/managed-ollama.yaml +++ b/examples/managed-ollama.yaml @@ -28,11 +28,11 @@ spec: memory: gpuMemoryGiB: 16 inferenceProviders: - - name: local + local: provider: openai serviceRef: ollama-server sandboxes: - - name: assistant + assistant: network: tier: isolated harness: diff --git a/examples/managed-podman.yaml b/examples/managed-podman.yaml index 2b5272258e5..9ca44080896 100644 --- a/examples/managed-podman.yaml +++ b/examples/managed-podman.yaml @@ -17,11 +17,11 @@ spec: engine: unix:///run/user/1000/podman/podman.sock endpoint: http://127.0.0.1:17681 inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11446/v1 sandboxes: - - name: assistant + assistant: image: ref: nc-prototype-fabric@sha256:a6a0e5cf53501e765ae43457212989ff4716c6224352dc109ebd49c3780450cd network: diff --git a/examples/multiple-models.yaml b/examples/multiple-models.yaml index 8425e9effe9..ee3415e6eb3 100644 --- a/examples/multiple-models.yaml +++ b/examples/multiple-models.yaml @@ -13,7 +13,7 @@ spec: management: external endpoint: http://127.0.0.1:17671 inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11434/v1 harnesses: @@ -38,12 +38,12 @@ spec: model_metadata: contextWindow: 8192 sandboxes: - - name: researcher + researcher: harnessRef: assistant agent: name: researcher inferenceRef: smart-and-fast - - name: writer + writer: harnessRef: assistant agent: name: writer diff --git a/examples/multiple-providers.yaml b/examples/multiple-providers.yaml index e9688c6bbdc..ae3cd03954c 100644 --- a/examples/multiple-providers.yaml +++ b/examples/multiple-providers.yaml @@ -14,10 +14,10 @@ spec: management: external endpoint: http://127.0.0.1:17671 inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11434/v1 - - name: hosted + hosted: provider: anthropic api: anthropic-messages endpoint: https://hosted.example/v1 @@ -45,12 +45,12 @@ spec: model_metadata: contextWindow: 8192 sandboxes: - - name: researcher + researcher: harnessRef: assistant agent: name: researcher inferenceRef: smart-and-fast - - name: writer + writer: harnessRef: assistant agent: name: writer diff --git a/examples/multiple-sandboxes.yaml b/examples/multiple-sandboxes.yaml index c1c95fb35db..5b4578686fa 100644 --- a/examples/multiple-sandboxes.yaml +++ b/examples/multiple-sandboxes.yaml @@ -14,11 +14,11 @@ spec: target: docker: {} inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11446/v1 sandboxes: - - name: alice + alice: network: tier: isolated harness: @@ -26,7 +26,7 @@ spec: agent: name: alice inferenceRef: chat - - name: bob + bob: network: tier: isolated harness: @@ -34,7 +34,7 @@ spec: agent: name: bob inferenceRef: chat - - name: research + research: image: ref: nc-prototype-fabric@sha256:a6a0e5cf53501e765ae43457212989ff4716c6224352dc109ebd49c3780450cd network: @@ -44,7 +44,7 @@ spec: agent: name: researcher inferenceRef: chat - - name: review + review: image: ref: nc-prototype-fabric@sha256:a6a0e5cf53501e765ae43457212989ff4716c6224352dc109ebd49c3780450cd network: @@ -54,7 +54,7 @@ spec: agent: name: reviewer inferenceRef: chat - - name: coding + coding: image: ref: nc-multi-models@sha256:2ee5e33522a37d3d77bb6381a92e963cb1d5884f2dd28b353b4b7fa0d95f212e network: diff --git a/examples/nemotron-amd64.yaml b/examples/nemotron-amd64.yaml index 8a46d57ff4a..52d4216ec27 100644 --- a/examples/nemotron-amd64.yaml +++ b/examples/nemotron-amd64.yaml @@ -49,11 +49,11 @@ spec: memory: gpuMemoryUtilization: 0.75 inferenceProviders: - - name: nemotron + nemotron: provider: openai serviceRef: nemotron sandboxes: - - name: assistant + assistant: image: # Build the Fabric OpenClaw image and replace this placeholder. ref: nc-prototype-fabric@sha256:0000000000000000000000000000000000000000000000000000000000000000 diff --git a/examples/onboarding/openclaw.yaml b/examples/onboarding/openclaw.yaml index d23451072d9..acaea546775 100644 --- a/examples/onboarding/openclaw.yaml +++ b/examples/onboarding/openclaw.yaml @@ -13,14 +13,14 @@ spec: target: docker: {} inferenceProviders: - - name: nvidia-prod + nvidia-prod: provider: openai api: openai-completions endpoint: https://integrate.api.nvidia.com/v1 credential: env: NVIDIA_API_KEY sandboxes: - - name: assistant + assistant: harness: kind: nvidia.fabric.openclaw agent: diff --git a/examples/openclaw-dashboard.yaml b/examples/openclaw-dashboard.yaml index a3fa4bc7413..75a7804598c 100644 --- a/examples/openclaw-dashboard.yaml +++ b/examples/openclaw-dashboard.yaml @@ -16,12 +16,12 @@ spec: # Replace with the engine holding the sandbox image; for a Podman gateway, use the podman key. engine: unix:///var/run/docker.sock inferenceProviders: - - name: local + local: provider: openai api: openai-responses endpoint: https://inference.example.com/v1 sandboxes: - - name: assistant + assistant: image: # Replace with the digest from a fresh OpenClaw image build; see docs/inference.md. ref: local-fabric-openclaw@sha256:0000000000000000000000000000000000000000000000000000000000000000 diff --git a/examples/openclaw-web-search.yaml b/examples/openclaw-web-search.yaml index fad207e65b5..50168f9009c 100644 --- a/examples/openclaw-web-search.yaml +++ b/examples/openclaw-web-search.yaml @@ -15,7 +15,7 @@ spec: management: external endpoint: http://127.0.0.1:17681 inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11446/v1 integrations: @@ -25,7 +25,7 @@ spec: credential: env: BRAVE_API_KEY sandboxes: - - name: researcher + researcher: image: # Replace with the digest from a current OpenClaw image build. ref: nc-fabric@sha256:0000000000000000000000000000000000000000000000000000000000000000 @@ -55,7 +55,7 @@ spec: providerRef: local overrides: model: qwen3:4b - - name: writer + writer: image: # Replace with the digest from a current OpenClaw image build. ref: nc-fabric@sha256:0000000000000000000000000000000000000000000000000000000000000000 diff --git a/examples/openshift/external-gateway.yaml b/examples/openshift/external-gateway.yaml index 88d9803db6f..63ae47e6b87 100644 --- a/examples/openshift/external-gateway.yaml +++ b/examples/openshift/external-gateway.yaml @@ -24,13 +24,13 @@ spec: # OpenShift gateways report the upstream Kubernetes driver. kubernetes: {} inferenceProviders: - - name: inference + inference: provider: openai endpoint: https://inference.example.com/v1 credential: {env: INFERENCE_API_KEY} # Each sandbox runs one independent agent using the shared inference profile. sandboxes: - - name: assistant + assistant: # Use an immutable image with runtime files readable by namespace-assigned UIDs. image: metadata: {env: NEMOCLAW_AGENT_IMAGE_METADATA} @@ -42,7 +42,7 @@ spec: agent: name: main inferenceRef: chat - - name: researcher + researcher: image: metadata: {env: NEMOCLAW_AGENT_IMAGE_METADATA} ref: registry.example.com/nemoclaw/openclaw@sha256:0000000000000000000000000000000000000000000000000000000000000000 @@ -53,7 +53,7 @@ spec: agent: name: researcher inferenceRef: chat - - name: reviewer + reviewer: image: metadata: {env: NEMOCLAW_AGENT_IMAGE_METADATA} ref: registry.example.com/nemoclaw/openclaw@sha256:0000000000000000000000000000000000000000000000000000000000000000 diff --git a/examples/openshift/managed-development.yaml b/examples/openshift/managed-development.yaml index 1b0e2fef12f..66f5333c7ba 100644 --- a/examples/openshift/managed-development.yaml +++ b/examples/openshift/managed-development.yaml @@ -26,7 +26,7 @@ spec: authentication: profile: development inferenceProviders: - - name: hosted-nvidia + hosted-nvidia: provider: openai api: openai-completions endpoint: https://integrate.api.nvidia.com/v1 @@ -34,7 +34,7 @@ spec: env: NVIDIA_INFERENCE_API_KEY # Each sandbox runs one independent agent using the shared inference profile. sandboxes: - - name: assistant + assistant: harness: kind: nvidia.fabric.openclaw image: @@ -64,7 +64,7 @@ spec: agent: name: primary inferenceRef: chat - - name: researcher + researcher: harness: kind: nvidia.fabric.openclaw image: @@ -94,7 +94,7 @@ spec: agent: name: researcher inferenceRef: chat - - name: reviewer + reviewer: harness: kind: nvidia.fabric.openclaw image: diff --git a/examples/spark/deepagents-team.yaml b/examples/spark/deepagents-team.yaml index 4cda9ff4697..68ebd9e4d36 100644 --- a/examples/spark/deepagents-team.yaml +++ b/examples/spark/deepagents-team.yaml @@ -43,11 +43,11 @@ spec: freeGateGiB: 12 consecutiveSamples: 5 inferenceProviders: - - name: local + local: provider: openai serviceRef: local sandboxes: - - name: researcher + researcher: image: ref: nc-fabric@sha256:f4a2f7068525f55f1dc25e77dfcc07998a32bd19f44ad75a61e304e255440f56 network: @@ -68,7 +68,7 @@ spec: tools: allow: - read - - name: writer + writer: image: ref: nc-fabric@sha256:f4a2f7068525f55f1dc25e77dfcc07998a32bd19f44ad75a61e304e255440f56 network: diff --git a/examples/spark/local-and-hosted.yaml b/examples/spark/local-and-hosted.yaml index 3f7ff5daa54..6c5fcd6c914 100644 --- a/examples/spark/local-and-hosted.yaml +++ b/examples/spark/local-and-hosted.yaml @@ -42,16 +42,16 @@ spec: freeGateGiB: 12 consecutiveSamples: 5 inferenceProviders: - - name: local + local: provider: openai serviceRef: local - - name: hosted + hosted: provider: openai endpoint: https://hosted.example/v1 credential: env: HOSTED_API_KEY sandboxes: - - name: assistant + assistant: image: ref: nc-fabric@sha256:a4402fa5dc8b020551f1e3bde409c8079767e53fcba7bd98b32197f82a9355a8 network: diff --git a/examples/spark/pi-small.yaml b/examples/spark/pi-small.yaml index c508992fca7..dbed01862d7 100644 --- a/examples/spark/pi-small.yaml +++ b/examples/spark/pi-small.yaml @@ -42,11 +42,11 @@ spec: freeGateGiB: 12 consecutiveSamples: 5 inferenceProviders: - - name: local + local: provider: openai serviceRef: local sandboxes: - - name: assistant + assistant: image: ref: nc-fabric@sha256:ac526ed31206c90557c7ac313400586e5347bee2c142efa4708256b122a81284 network: diff --git a/examples/spark/remote-vllm.yaml b/examples/spark/remote-vllm.yaml index 9096d554927..638e3f0a1c4 100644 --- a/examples/spark/remote-vllm.yaml +++ b/examples/spark/remote-vllm.yaml @@ -45,11 +45,11 @@ spec: freeGateGiB: 12 consecutiveSamples: 5 inferenceProviders: - - name: qwen + qwen: provider: openai serviceRef: qwen sandboxes: - - name: assistant + assistant: network: tier: isolated harness: diff --git a/examples/spark/shared-model.yaml b/examples/spark/shared-model.yaml index 08d70debe28..3e806eab70c 100644 --- a/examples/spark/shared-model.yaml +++ b/examples/spark/shared-model.yaml @@ -42,11 +42,11 @@ spec: freeGateGiB: 12 consecutiveSamples: 5 inferenceProviders: - - name: shared + shared: provider: openai serviceRef: shared sandboxes: - - name: pi + pi: image: ref: nc-fabric@sha256:ac526ed31206c90557c7ac313400586e5347bee2c142efa4708256b122a81284 network: @@ -71,7 +71,7 @@ spec: reasoning: false input: - text - - name: openclaw + openclaw: image: ref: nc-fabric@sha256:a4402fa5dc8b020551f1e3bde409c8079767e53fcba7bd98b32197f82a9355a8 network: @@ -92,7 +92,7 @@ spec: settings: model_metadata: contextWindow: 32768 - - name: deepagents + deepagents: image: ref: nc-fabric@sha256:f4a2f7068525f55f1dc25e77dfcc07998a32bd19f44ad75a61e304e255440f56 network: diff --git a/examples/spark/spark-inline.yaml b/examples/spark/spark-inline.yaml index 2e34278718d..d06a290f259 100644 --- a/examples/spark/spark-inline.yaml +++ b/examples/spark/spark-inline.yaml @@ -248,11 +248,11 @@ spec: size: 6722759 sha256: ce99b4cb2983d118806ce0a8b777a35b093e2000a503ebde25853284c9dfa003 inferenceProviders: - - name: qwen + qwen: provider: openai serviceRef: qwen sandboxes: - - name: assistant + assistant: network: tier: isolated harness: diff --git a/examples/spark/two-models.yaml b/examples/spark/two-models.yaml index c9e56deeba3..38fe9509590 100644 --- a/examples/spark/two-models.yaml +++ b/examples/spark/two-models.yaml @@ -67,14 +67,14 @@ spec: freeGateGiB: 12 consecutiveSamples: 5 inferenceProviders: - - name: fast + fast: provider: openai serviceRef: fast - - name: smart + smart: provider: openai serviceRef: smart sandboxes: - - name: assistant + assistant: image: ref: nc-fabric@sha256:ac526ed31206c90557c7ac313400586e5347bee2c142efa4708256b122a81284 network: diff --git a/examples/spark/vllm.yaml b/examples/spark/vllm.yaml index f76f9312c16..b1e1c2218da 100644 --- a/examples/spark/vllm.yaml +++ b/examples/spark/vllm.yaml @@ -41,11 +41,11 @@ spec: freeGateGiB: 12 consecutiveSamples: 5 inferenceProviders: - - name: qwen + qwen: provider: openai serviceRef: qwen sandboxes: - - name: assistant + assistant: network: tier: isolated harness: diff --git a/examples/station/shared-model.yaml b/examples/station/shared-model.yaml index e98ba95707c..a0e07eb0bec 100644 --- a/examples/station/shared-model.yaml +++ b/examples/station/shared-model.yaml @@ -44,11 +44,11 @@ spec: freeGateGiB: 12 consecutiveSamples: 5 inferenceProviders: - - name: shared + shared: provider: openai serviceRef: shared sandboxes: - - name: openclaw + openclaw: image: ref: nc-fabric@sha256:0000000000000000000000000000000000000000000000000000000000000000 network: @@ -69,7 +69,7 @@ spec: settings: model_metadata: contextWindow: 32768 - - name: pi + pi: image: ref: nc-fabric@sha256:0000000000000000000000000000000000000000000000000000000000000000 network: diff --git a/examples/station/vllm.yaml b/examples/station/vllm.yaml index ecfd06f4c98..b6884d7cd7d 100644 --- a/examples/station/vllm.yaml +++ b/examples/station/vllm.yaml @@ -42,11 +42,11 @@ spec: freeGateGiB: 12 consecutiveSamples: 5 inferenceProviders: - - name: qwen + qwen: provider: openai serviceRef: qwen sandboxes: - - name: assistant + assistant: image: ref: nc-fabric@sha256:0000000000000000000000000000000000000000000000000000000000000000 network: diff --git a/examples/tavily-web-search.yaml b/examples/tavily-web-search.yaml index d93c0a4af65..97f346a6f83 100644 --- a/examples/tavily-web-search.yaml +++ b/examples/tavily-web-search.yaml @@ -14,7 +14,7 @@ spec: management: external endpoint: http://127.0.0.1:17681 inferenceProviders: - - name: local + local: provider: openai endpoint: http://172.20.0.1:11446/v1 integrations: @@ -24,7 +24,7 @@ spec: credential: env: TAVILY_API_KEY sandboxes: - - name: researcher + researcher: image: # Use the digest from an OpenClaw image built from this revision. ref: nc-fabric@sha256:0000000000000000000000000000000000000000000000000000000000000000 @@ -54,7 +54,7 @@ spec: providerRef: local overrides: model: qwen3:4b - - name: hermes + hermes: image: # Use the digest from a Hermes image built from this revision. ref: nc-fabric@sha256:0000000000000000000000000000000000000000000000000000000000000000 diff --git a/schemas/nemoclaw-v1alpha1.schema.json b/schemas/nemoclaw-v1alpha1.schema.json index fe4b68f0f28..4b94f812689 100644 --- a/schemas/nemoclaw-v1alpha1.schema.json +++ b/schemas/nemoclaw-v1alpha1.schema.json @@ -760,7 +760,8 @@ ] } ] - } + }, + "x-nemoclaw-error": "an http:// endpoint takes no credential" } }, { @@ -813,6 +814,143 @@ "serviceRef" ] }, + "properties": { + "api": { + "$ref": "#/$defs/InferenceApi", + "description": "Request API. Omission selects anthropic-messages for Anthropic providers and openai-completions for OpenAI providers; explicit values are preserved for Fabric validation." + }, + "credential": { + "$ref": "#/$defs/SecretRef", + "description": "Optional API credential reference for an external HTTPS endpoint. Excluded by serviceRef." + }, + "endpoint": { + "description": "Inference HTTP(S) URL owned outside the deployment. Required without serviceRef and excluded with serviceRef.", + "type": "string", + "x-nemoclaw-required": "Without serviceRef" + }, + "provider": { + "description": "OpenShell provider implementation. Must match the selected API family.", + "enum": [ + "openai", + "anthropic" + ], + "type": "string" + }, + "serviceRef": { + "description": "Name of a managed service in spec.services. Excludes endpoint and credential.", + "pattern": "^[a-z][a-z0-9-]{0,39}$", + "type": "string" + } + }, + "required": [ + "provider" + ], + "then": { + "allOf": [ + { + "not": { + "anyOf": [ + { + "required": [ + "credential" + ] + } + ] + } + } + ], + "properties": { + "endpoint": { + "const": "" + }, + "provider": { + "const": "openai" + } + }, + "x-nemoclaw-error": "serviceRef excludes endpoint and credential and selects provider openai" + }, + "type": "object", + "x-nemoclaw-removed-fields": { + "name": "a provider's name is its key under inferenceProviders; only an inline route provider states name" + } + }, + "InlineInferenceProvider": { + "additionalProperties": false, + "allOf": [ + { + "if": { + "properties": { + "endpoint": { + "pattern": "^http:" + } + }, + "required": [ + "endpoint" + ] + }, + "then": { + "not": { + "anyOf": [ + { + "required": [ + "credential" + ] + } + ] + }, + "x-nemoclaw-error": "an http:// endpoint takes no credential" + } + }, + { + "if": { + "required": [ + "api" + ] + }, + "then": { + "else": { + "properties": { + "provider": { + "const": "openai" + } + } + }, + "if": { + "properties": { + "api": { + "const": "anthropic-messages" + } + }, + "required": [ + "api" + ] + }, + "then": { + "properties": { + "provider": { + "const": "anthropic" + } + } + } + } + } + ], + "description": "Inference definition owned by one route: choose an endpoint for external inference or serviceRef for a managed service. It has no map key, so it states its own name.", + "else": { + "properties": { + "endpoint": { + "pattern": "^https?://" + } + }, + "required": [ + "endpoint" + ] + }, + "if": { + "required": [ + "serviceRef" + ] + }, "properties": { "api": { "$ref": "#/$defs/InferenceApi", @@ -828,7 +966,7 @@ "x-nemoclaw-required": "Without serviceRef" }, "name": { - "description": "Provider name referenced by model choices.", + "description": "Lowercase provider name. It must not shadow an enclosing definition.", "pattern": "^[a-z][a-z0-9-]{0,39}$", "type": "string" }, @@ -871,7 +1009,8 @@ "provider": { "const": "openai" } - } + }, + "x-nemoclaw-error": "serviceRef excludes endpoint and credential and selects provider openai" }, "type": "object" }, @@ -2289,7 +2428,7 @@ "description": "Model selection, shared limits, and optional native settings." }, "provider": { - "$ref": "#/$defs/InferenceProvider", + "$ref": "#/$defs/InlineInferenceProvider", "description": "Inline inference definition owned by this route. Excludes providerRef and must not shadow an enclosing definition." }, "providerRef": { @@ -2363,11 +2502,15 @@ "x-nemoclaw-required": "With a Kubernetes target" }, "inferenceProviders": { - "description": "Named inference definitions visible to this sandbox's routes. Names must not shadow deployment definitions.", - "items": { + "additionalProperties": { "$ref": "#/$defs/InferenceProvider" }, - "type": "array" + "description": "Inference definitions keyed by lowercase name and visible to this sandbox's routes. Names must not shadow deployment definitions.", + "propertyNames": { + "pattern": "^[a-z][a-z0-9-]{0,39}$" + }, + "type": "object", + "x-nemoclaw-error": "inferenceProviders must map lowercase names (^[a-z][a-z0-9-]{0,39}$) to provider definitions" }, "inferences": { "additionalProperties": { @@ -2389,21 +2532,18 @@ }, "type": "object" }, - "name": { - "description": "Lowercase sandbox name.", - "pattern": "^[a-z][a-z0-9-]{0,39}$", - "type": "string" - }, "network": { "$ref": "#/$defs/Network", "description": "Sandbox network policy; omission selects isolated egress with grants for declared inference." } }, "required": [ - "name", "agent" ], - "type": "object" + "type": "object", + "x-nemoclaw-removed-fields": { + "name": "a sandbox's name is its key under spec.sandboxes" + } }, "SearchProvider": { "description": "Search provider supported by the managed profile.", @@ -3346,11 +3486,15 @@ "type": "object" }, "inferenceProviders": { - "description": "Named inference definitions available to sandbox routes. Unselected definitions create no resources or credential requirements.", - "items": { + "additionalProperties": { "$ref": "#/$defs/InferenceProvider" }, - "type": "array" + "description": "Inference definitions keyed by lowercase name and available to sandbox routes. Unselected definitions create no resources or credential requirements.", + "propertyNames": { + "pattern": "^[a-z][a-z0-9-]{0,39}$" + }, + "type": "object", + "x-nemoclaw-error": "inferenceProviders must map lowercase names (^[a-z][a-z0-9-]{0,39}$) to provider definitions" }, "inferences": { "additionalProperties": { @@ -3373,13 +3517,17 @@ "type": "object" }, "sandboxes": { - "description": "One to 32 uniquely named sandboxes. Each runs one agent through its selected Fabric adapter. Declaration order does not select a default sandbox or agent.", - "items": { + "additionalProperties": { "$ref": "#/$defs/Sandbox" }, - "maxItems": 32, - "minItems": 1, - "type": "array" + "description": "One to 32 sandboxes keyed by lowercase name. Each runs one agent through its selected Fabric adapter. Key order has no meaning and selects no default sandbox or agent.", + "maxProperties": 32, + "minProperties": 1, + "propertyNames": { + "pattern": "^[a-z][a-z0-9-]{0,39}$" + }, + "type": "object", + "x-nemoclaw-error": "spec.sandboxes must map 1 to 32 lowercase names (^[a-z][a-z0-9-]{0,39}$) to sandbox definitions" }, "services": { "additionalProperties": { @@ -3455,7 +3603,7 @@ "spec": { "properties": { "sandboxes": { - "items": { + "additionalProperties": { "properties": { "image": { "not": { @@ -3507,7 +3655,7 @@ "spec": { "properties": { "sandboxes": { - "items": { + "additionalProperties": { "properties": { "image": { "properties": { From 8e00dbc5ce954d3964bf759a65dc7eb4a27d480d Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Tue, 13 Oct 2026 22:20:36 +0000 Subject: [PATCH 6/9] feat(config)!: version the reshaped schema as v1alpha2 The schema's apiVersion and $id stayed the same across revisions whose rules differed, so a document or retained state from an earlier v1 revision failed at its first moved field, or loaded as "corrupt", with no sign that the whole document had to be re-authored. - `nemoclaw.nvidia.com/v1alpha2` names the configuration API, the schema file `schemas/nemoclaw-v1alpha2.schema.json`, and its `$id`, all from one constant. `schema --check` fails while another versioned schema file remains. - `Document::parse` rejects a v1alpha1 document before schema validation and points to the migration guide. - Retained intent is format version 8. A record from an earlier version or holding a v1alpha1 document fails before typed parsing with a message to retain it and use the earlier NemoClaw to destroy it, or to deploy separately. Its bytes stay untouched. - The contributor guide states the rule: a revision that rejects or reinterprets a document the previous revision accepted changes the API version; adding optional fields does not. - The migration guide describes keeping or exporting the earlier document, a field map from v1alpha1, and deploying the re-authored document separately. There is no conversion or adoption. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Hai Nguyen --- .../examples/print_journey_tree.rs | 2 +- .../tests/fixtures/minimum-inline.yaml | 2 +- .../tests/journey_resolution.rs | 4 +- .../tests/journey_tree_preview.rs | 2 +- .../tests/partial_documents.rs | 4 +- crates/nemoclaw-build/src/ci/live.rs | 2 +- crates/nemoclaw-build/src/schema.rs | 33 ++++- crates/nemoclaw-build/src/schema/reference.rs | 9 +- crates/nemoclaw-build/tests/schema.rs | 28 +++- .../fixtures/hermes-nvidia-hosted/v1.yaml | 2 +- .../fixtures/openclaw-nvidia-hosted/v1.yaml | 2 +- crates/nemoclaw-e2e/tests/hosted_parity.rs | 3 + crates/nemoclaw-e2e/tests/kubernetes_live.rs | 2 +- crates/nemoclaw-sdk/src/config/mod.rs | 21 ++- crates/nemoclaw-sdk/src/config/schema.rs | 6 +- crates/nemoclaw-sdk/src/state/mod.rs | 34 ++++- crates/nemoclaw-sdk/src/state/tests.rs | 49 +++++-- crates/nemoclaw-sdk/tests/config_schema.rs | 46 +++++++ crates/nemoclaw-sdk/tests/fabric_planner.rs | 2 +- .../tests/fixtures/config/fabric-claude.yaml | 2 +- .../tests/fixtures/config/fabric-pi.yaml | 2 +- .../tests/fixtures/config/fabric.yaml | 2 +- .../tests/fixtures/config/local.yaml | 2 +- .../tests/fixtures/config/managed-ollama.yaml | 2 +- .../tests/fixtures/config/spark.yaml | 2 +- docs/build.md | 2 +- docs/contributing/configuration-schema.md | 23 +++- docs/contributing/documentation-build.md | 2 +- docs/get-started.md | 2 +- docs/migration.md | 128 ++++++++++++++++++ docs/reference/configuration.md | 4 +- docs/release-notes.md | 13 ++ docs/sdk.md | 2 +- docs/state.md | 5 +- docs/troubleshooting.md | 1 + docs/usage.md | 5 +- examples/explicit-policy.yaml | 4 +- examples/fabric-claude.yaml | 4 +- examples/fabric-codex.yaml | 4 +- examples/fabric-hermes.yaml | 4 +- examples/fabric-mini-swe-agent.yaml | 4 +- examples/fabric-nooa-bench.yaml | 4 +- examples/fabric-nooa.yaml | 4 +- examples/fabric-openclaw.yaml | 4 +- examples/fabric-pi.yaml | 4 +- examples/fabric-remote-agent.yaml | 4 +- examples/fabric.yaml | 4 +- examples/full-featured-openclaw.yaml | 4 +- examples/hermes-auth.yaml | 4 +- examples/hermes-interfaces.yaml | 4 +- examples/inference-tuning.yaml | 4 +- examples/inline-inference.yaml | 4 +- examples/kubernetes/external-gateway.yaml | 4 +- examples/kubernetes/hosted-nvidia.yaml | 4 +- examples/kubernetes/managed-development.yaml | 4 +- examples/local.yaml | 4 +- examples/managed-hermes.yaml | 4 +- examples/managed-ollama-gpu.yaml | 4 +- examples/managed-ollama.yaml | 4 +- examples/managed-podman.yaml | 4 +- examples/multiple-models.yaml | 4 +- examples/multiple-providers.yaml | 4 +- examples/multiple-sandboxes.yaml | 4 +- examples/nemotron-amd64.yaml | 4 +- examples/onboarding/openclaw.yaml | 4 +- examples/openclaw-dashboard.yaml | 4 +- examples/openclaw-web-search.yaml | 4 +- examples/openshift/external-gateway.yaml | 4 +- examples/openshift/managed-development.yaml | 4 +- examples/spark/deepagents-team.yaml | 4 +- examples/spark/local-and-hosted.yaml | 4 +- examples/spark/pi-small.yaml | 4 +- examples/spark/remote-vllm.yaml | 4 +- examples/spark/shared-model.yaml | 4 +- examples/spark/spark-inline.yaml | 4 +- examples/spark/two-models.yaml | 4 +- examples/spark/vllm.yaml | 4 +- examples/station/shared-model.yaml | 4 +- examples/station/vllm.yaml | 4 +- examples/tavily-web-search.yaml | 4 +- ...ema.json => nemoclaw-v1alpha2.schema.json} | 6 +- 81 files changed, 486 insertions(+), 148 deletions(-) rename schemas/{nemoclaw-v1alpha1.schema.json => nemoclaw-v1alpha2.schema.json} (99%) diff --git a/crates/nemoclaw-authoring/examples/print_journey_tree.rs b/crates/nemoclaw-authoring/examples/print_journey_tree.rs index 04bdf7b4771..9e39e38db4d 100644 --- a/crates/nemoclaw-authoring/examples/print_journey_tree.rs +++ b/crates/nemoclaw-authoring/examples/print_journey_tree.rs @@ -17,7 +17,7 @@ fn main() -> Result<(), Box> { let capabilities = Capabilities::from_catalog(&catalog); let minimum = PartialDocument::from_yaml( - b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nspec:\n sandboxes:\n assistant: {}\n", + b"apiVersion: nemoclaw.nvidia.com/v1alpha2\nkind: NemoClawConfig\nspec:\n sandboxes:\n assistant: {}\n", )?; let minimum = JourneyDefinition::new("minimum viable values", minimum) .ask(["/metadata/name"]) diff --git a/crates/nemoclaw-authoring/tests/fixtures/minimum-inline.yaml b/crates/nemoclaw-authoring/tests/fixtures/minimum-inline.yaml index f7639261f24..719a2d52c21 100644 --- a/crates/nemoclaw-authoring/tests/fixtures/minimum-inline.yaml +++ b/crates/nemoclaw-authoring/tests/fixtures/minimum-inline.yaml @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # A deliberately sparse v1 single-sandbox authoring input. The inline forms, # one route, and external endpoint are structural choices supplied by the journey. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: {} spec: diff --git a/crates/nemoclaw-authoring/tests/journey_resolution.rs b/crates/nemoclaw-authoring/tests/journey_resolution.rs index 38bf2245ac8..af9bd8b11eb 100644 --- a/crates/nemoclaw-authoring/tests/journey_resolution.rs +++ b/crates/nemoclaw-authoring/tests/journey_resolution.rs @@ -13,7 +13,7 @@ const TARGET: &str = "/spec/gateway/target"; fn minimum() -> PartialDocument { PartialDocument::from_yaml( - b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nspec:\n sandboxes:\n assistant: {}\n", + b"apiVersion: nemoclaw.nvidia.com/v1alpha2\nkind: NemoClawConfig\nspec:\n sandboxes:\n assistant: {}\n", ) .unwrap() } @@ -3546,7 +3546,7 @@ fn absent_harness_catalog_cannot_silently_accept_an_unadvertised_choice() { #[test] fn missing_gateway_asks_for_the_schema_discriminator() { let base = PartialDocument::from_yaml( - b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nspec:\n sandboxes:\n assistant: {}\n", + b"apiVersion: nemoclaw.nvidia.com/v1alpha2\nkind: NemoClawConfig\nspec:\n sandboxes:\n assistant: {}\n", ) .unwrap(); let capabilities = Capabilities::available(); diff --git a/crates/nemoclaw-authoring/tests/journey_tree_preview.rs b/crates/nemoclaw-authoring/tests/journey_tree_preview.rs index a8267217553..d805d5d3a8b 100644 --- a/crates/nemoclaw-authoring/tests/journey_tree_preview.rs +++ b/crates/nemoclaw-authoring/tests/journey_tree_preview.rs @@ -64,7 +64,7 @@ fn configured_native_questions_appear_in_the_same_definition_tree() { #[test] fn minimum_values_preview_shows_harness_branches_and_optional_omission() { let base = PartialDocument::from_yaml( - b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nspec:\n sandboxes:\n assistant: {}\n", + b"apiVersion: nemoclaw.nvidia.com/v1alpha2\nkind: NemoClawConfig\nspec:\n sandboxes:\n assistant: {}\n", ) .unwrap(); let journey = JourneyDefinition::new("minimum-values", base) diff --git a/crates/nemoclaw-authoring/tests/partial_documents.rs b/crates/nemoclaw-authoring/tests/partial_documents.rs index 0b8035898e6..4b7b3eeadfb 100644 --- a/crates/nemoclaw-authoring/tests/partial_documents.rs +++ b/crates/nemoclaw-authoring/tests/partial_documents.rs @@ -7,7 +7,7 @@ use nemoclaw_sdk::config::Document; #[test] fn sparse_input_reports_missing_values_without_constructing_a_document() { let partial = PartialDocument::from_yaml( - b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nspec:\n sandboxes:\n assistant:\n harness:\n kind: nvidia.fabric.openclaw\n", + b"apiVersion: nemoclaw.nvidia.com/v1alpha2\nkind: NemoClawConfig\nspec:\n sandboxes:\n assistant:\n harness:\n kind: nvidia.fabric.openclaw\n", ) .unwrap(); let assessment = partial.assess(); @@ -29,7 +29,7 @@ fn sparse_input_reports_missing_values_without_constructing_a_document() { #[test] fn supplied_invalid_name_is_distinct_from_missing_values() { let partial = PartialDocument::from_yaml( - b"apiVersion: nemoclaw.nvidia.com/v1alpha1\nkind: NemoClawConfig\nmetadata:\n name: Bad Name\nspec:\n sandboxes:\n assistant:\n harness:\n kind: nvidia.fabric.openclaw\n", + b"apiVersion: nemoclaw.nvidia.com/v1alpha2\nkind: NemoClawConfig\nmetadata:\n name: Bad Name\nspec:\n sandboxes:\n assistant:\n harness:\n kind: nvidia.fabric.openclaw\n", ) .unwrap(); let assessment = partial.assess(); diff --git a/crates/nemoclaw-build/src/ci/live.rs b/crates/nemoclaw-build/src/ci/live.rs index 44eb0580200..d609094ee10 100644 --- a/crates/nemoclaw-build/src/ci/live.rs +++ b/crates/nemoclaw-build/src/ci/live.rs @@ -70,7 +70,7 @@ pub fn gateway_document(inputs: &GatewayInputs<'_>) -> String { }) .unwrap_or_default(); format!( - "apiVersion: nemoclaw.nvidia.com/v1alpha1 + "apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: {name} diff --git a/crates/nemoclaw-build/src/schema.rs b/crates/nemoclaw-build/src/schema.rs index 1eef7cf5042..a8873456b25 100644 --- a/crates/nemoclaw-build/src/schema.rs +++ b/crates/nemoclaw-build/src/schema.rs @@ -15,7 +15,38 @@ pub fn schema_bytes() -> Vec { pub fn generate(root: &Path, check: bool) -> Result<(), String> { let reference = render_reference(&input_schema())?; generated_file(root, SCHEMA_PATH, &schema_bytes(), check)?; - generated_file(root, REFERENCE_PATH, reference.as_bytes(), check) + generated_file(root, REFERENCE_PATH, reference.as_bytes(), check)?; + if check { + no_other_schema_version(root)?; + } + Ok(()) +} + +// Each API version has its own schema file. One left from another version +// would let editors check documents against a contract this SDK rejects. +fn no_other_schema_version(root: &Path) -> Result<(), String> { + let (directory, current) = SCHEMA_PATH.rsplit_once('/').expect("schema directory"); + let entries = fs::read_dir(root.join(directory)) + .map_err(|error| format!("cannot read {directory}: {error}"))?; + let mut others = entries + .map(|entry| entry.map(|entry| entry.file_name().to_string_lossy().into_owned())) + .collect::, _>>() + .map_err(|error| format!("cannot read {directory}: {error}"))? + .into_iter() + .filter(|name| { + name != current && name.starts_with("nemoclaw-") && name.ends_with(".schema.json") + }) + .map(|name| format!("{directory}/{name}")) + .collect::>(); + others.sort_unstable(); + if others.is_empty() { + Ok(()) + } else { + Err(format!( + "{} must be removed; {SCHEMA_PATH} is the only configuration schema", + others.join(", ") + )) + } } pub fn add_to_bundle( diff --git a/crates/nemoclaw-build/src/schema/reference.rs b/crates/nemoclaw-build/src/schema/reference.rs index e5fb4a36dfb..6b3bb429aa8 100644 --- a/crates/nemoclaw-build/src/schema/reference.rs +++ b/crates/nemoclaw-build/src/schema/reference.rs @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +use nemoclaw_sdk::config::schema::SCHEMA_PATH; use serde_json::Value; use std::{ collections::{BTreeMap, BTreeSet}, @@ -16,7 +17,13 @@ pub fn render_reference(schema: &Value) -> Result { "\n\n", "# YAML Configuration Reference\n\n", "\n\n", - "This reference and the [JSON Schema](../../schemas/nemoclaw-v1alpha1.schema.json) describe authored YAML for this source revision.\n", + )); + writeln!( + output, + "This reference and the [JSON Schema](../../{SCHEMA_PATH}) describe authored YAML for this source revision." + ) + .unwrap(); + output.push_str(concat!( "See [schema maintenance](../contributing/configuration-schema.md) for generation and validation commands.\n\n", "Paths use `[]` for an array element and `{key}` for a map entry.\n", "Required fields must appear when their containing object is present; conditional requirements are stated in the table or description.\n", diff --git a/crates/nemoclaw-build/tests/schema.rs b/crates/nemoclaw-build/tests/schema.rs index acef6aafd95..94906b1b6e8 100644 --- a/crates/nemoclaw-build/tests/schema.rs +++ b/crates/nemoclaw-build/tests/schema.rs @@ -28,14 +28,14 @@ fn schema_generation_is_repeatable_and_check_rejects_missing_or_stale_output() { ); let path = directory .path() - .join("schemas/nemoclaw-v1alpha1.schema.json"); + .join("schemas/nemoclaw-v1alpha2.schema.json"); let first = fs::read(&path).unwrap(); let schema: serde_json::Value = serde_json::from_slice(&first).unwrap(); assert_eq!( schema["$schema"], "https://json-schema.org/draft/2020-12/schema" ); - assert_eq!(schema["$id"], "urn:nemoclaw:config:v1alpha1"); + assert_eq!(schema["$id"], "urn:nemoclaw:config:v1alpha2"); assert!(generate(directory.path(), false).status.success()); assert_eq!(fs::read(&path).unwrap(), first); assert!(generate(directory.path(), true).status.success()); @@ -51,11 +51,33 @@ fn schema_generation_is_repeatable_and_check_rejects_missing_or_stale_output() { let stale = generate(directory.path(), true); assert!(!stale.status.success()); assert!( - String::from_utf8_lossy(&stale.stderr).contains("schemas/nemoclaw-v1alpha1.schema.json") + String::from_utf8_lossy(&stale.stderr).contains("schemas/nemoclaw-v1alpha2.schema.json") ); assert_eq!(fs::read(&path).unwrap(), b"{}\n"); } +#[test] +fn check_rejects_a_schema_left_for_another_api_version() { + let directory = tempfile::tempdir().unwrap(); + assert!(generate(directory.path(), false).status.success()); + let earlier = directory + .path() + .join("schemas/nemoclaw-v1alpha1.schema.json"); + fs::write(&earlier, b"{}\n").unwrap(); + let stale = generate(directory.path(), true); + assert!(!stale.status.success()); + let message = String::from_utf8_lossy(&stale.stderr); + assert!( + message.contains("schemas/nemoclaw-v1alpha1.schema.json"), + "{message}" + ); + assert_eq!(fs::read(&earlier).unwrap(), b"{}\n"); + // Other files in the directory are not schema versions. + fs::remove_file(&earlier).unwrap(); + fs::write(directory.path().join("schemas/README.md"), b"notes\n").unwrap(); + assert!(generate(directory.path(), true).status.success()); +} + #[test] fn bundle_rejects_a_builder_compiled_from_different_source_inputs() { let root = tempfile::tempdir().unwrap(); diff --git a/crates/nemoclaw-e2e/fixtures/hermes-nvidia-hosted/v1.yaml b/crates/nemoclaw-e2e/fixtures/hermes-nvidia-hosted/v1.yaml index c5d6c6ce891..1b61d93e1e9 100644 --- a/crates/nemoclaw-e2e/fixtures/hermes-nvidia-hosted/v1.yaml +++ b/crates/nemoclaw-e2e/fixtures/hermes-nvidia-hosted/v1.yaml @@ -3,7 +3,7 @@ # Current v1 intent authored from the reviewed raw v0 export produced by # NVIDIA/NemoClaw b6934c6300c4e1e175757e9281ae3a641d9a5b1f. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: hermes-nvidia-hosted diff --git a/crates/nemoclaw-e2e/fixtures/openclaw-nvidia-hosted/v1.yaml b/crates/nemoclaw-e2e/fixtures/openclaw-nvidia-hosted/v1.yaml index 6bd65f25378..e32c9a533e8 100644 --- a/crates/nemoclaw-e2e/fixtures/openclaw-nvidia-hosted/v1.yaml +++ b/crates/nemoclaw-e2e/fixtures/openclaw-nvidia-hosted/v1.yaml @@ -4,7 +4,7 @@ # b6934c6300c4e1e175757e9281ae3a641d9a5b1f. # 2026-09-17: refreshed from the public v0 config export contract in #11977. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: openclaw-nvidia-hosted diff --git a/crates/nemoclaw-e2e/tests/hosted_parity.rs b/crates/nemoclaw-e2e/tests/hosted_parity.rs index 20741e83afb..420051896b3 100644 --- a/crates/nemoclaw-e2e/tests/hosted_parity.rs +++ b/crates/nemoclaw-e2e/tests/hosted_parity.rs @@ -15,6 +15,9 @@ fn authored_document(raw: &[u8], current: &[u8]) -> Document { Document::parse(current).expect("authored v1 input must use current agent syntax"); let mut projected: serde_json::Value = serde_saphyr::from_str(std::str::from_utf8(raw).unwrap()).unwrap(); + // The raw export names the API version this projection replaces. + assert_eq!(projected["apiVersion"], "nemoclaw.nvidia.com/v1alpha1"); + projected["apiVersion"] = json!(nemoclaw_sdk::config::API_VERSION); // v0 named the compute driver beside the managed endpoint; current intent // keys the endpoint by the target the gateway runs on. let gateway = projected["spec"]["gateway"].as_object_mut().unwrap(); diff --git a/crates/nemoclaw-e2e/tests/kubernetes_live.rs b/crates/nemoclaw-e2e/tests/kubernetes_live.rs index b8e05d01396..aa6c4d03fdb 100644 --- a/crates/nemoclaw-e2e/tests/kubernetes_live.rs +++ b/crates/nemoclaw-e2e/tests/kubernetes_live.rs @@ -515,7 +515,7 @@ async fn deploy_to_the_health_check(distribution: &str, while_applying: impl Asy .unwrap() .port(); let yaml = format!( - "apiVersion: nemoclaw.nvidia.com/v1alpha1 + "apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: live-kind-agent diff --git a/crates/nemoclaw-sdk/src/config/mod.rs b/crates/nemoclaw-sdk/src/config/mod.rs index 97a06a999dd..a850de121ef 100644 --- a/crates/nemoclaw-sdk/src/config/mod.rs +++ b/crates/nemoclaw-sdk/src/config/mod.rs @@ -1,6 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +// One version names the API, its schema file, and the schema's identity. +// A revision that rejects or reinterprets a document the previous revision +// accepted changes it; see docs/contributing/configuration-schema.md. +macro_rules! api_version { + () => { + "v1alpha2" + }; +} + mod agent_inference; pub(crate) mod constraints; #[doc(hidden)] @@ -41,7 +50,10 @@ use std::io::Read; pub use types::*; pub use validation::{is_fabric_harness, valid_name, validate_endpoint}; -pub const API_VERSION: &str = "nemoclaw.nvidia.com/v1alpha1"; +pub const API_VERSION: &str = concat!("nemoclaw.nvidia.com/", api_version!()); +/// The API version of documents and retained state from earlier NemoClaw +/// revisions, which must be re-authored rather than read. +pub(crate) const EARLIER_API_VERSION: &str = "nemoclaw.nvidia.com/v1alpha1"; pub const MAX_DOCUMENT_BYTES: u64 = 1 << 20; pub use crate::artifact_pins::DEFAULT_AGENT_IMAGE; pub use crate::artifact_pins::DEFAULT_GATEWAY_IMAGE; @@ -94,6 +106,13 @@ impl Document { /// including duplicate keys. pub fn parse(input: impl Read) -> Result { let (text, tree) = read_yaml(input)?; + // An earlier document fails at its first changed field, which hides + // that the whole document must be re-authored. + if tree.get("apiVersion").and_then(serde_json::Value::as_str) == Some(EARLIER_API_VERSION) { + return Err(ConfigError(format!( + "configuration uses {EARLIER_API_VERSION}; this NemoClaw reads {API_VERSION}; re-author it as described in docs/migration.md" + ))); + } schema::validate_input(&tree, Some(&text))?; let mut document: Self = serde_json::from_value(tree).map_err(|_| { ConfigError::new("configuration contains an unknown field or invalid field type") diff --git a/crates/nemoclaw-sdk/src/config/schema.rs b/crates/nemoclaw-sdk/src/config/schema.rs index c5ff4c76190..3d94b22d2f8 100644 --- a/crates/nemoclaw-sdk/src/config/schema.rs +++ b/crates/nemoclaw-sdk/src/config/schema.rs @@ -6,7 +6,7 @@ pub(crate) mod validation; // Editors select union variants the same way schema diagnostics do. pub use nemoclaw_runtime::schema::{select_variant, variant_keys}; -pub const SCHEMA_PATH: &str = "schemas/nemoclaw-v1alpha1.schema.json"; +pub const SCHEMA_PATH: &str = concat!("schemas/nemoclaw-", api_version!(), ".schema.json"); pub fn input_schema() -> serde_json::Value { build_schema(false) @@ -22,8 +22,8 @@ fn build_schema(normalized: bool) -> serde_json::Value { .unwrap(); remove_serde_defaults(&mut schema); validation::constrain(&mut schema, normalized); - schema["$id"] = serde_json::json!("urn:nemoclaw:config:v1alpha1"); - schema["title"] = serde_json::json!("NemoClaw configuration (v1alpha1)"); + schema["$id"] = serde_json::json!(concat!("urn:nemoclaw:config:", api_version!())); + schema["title"] = serde_json::json!(concat!("NemoClaw configuration (", api_version!(), ")")); schema["$comment"] = serde_json::json!( "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. SPDX-License-Identifier: Apache-2.0. Generated from the SDK; do not edit." ); diff --git a/crates/nemoclaw-sdk/src/state/mod.rs b/crates/nemoclaw-sdk/src/state/mod.rs index 2615239d819..e5b3d4d0339 100644 --- a/crates/nemoclaw-sdk/src/state/mod.rs +++ b/crates/nemoclaw-sdk/src/state/mod.rs @@ -15,6 +15,11 @@ use std::{ path::{Path, PathBuf}, }; +/// Format of `intent.json`. Version 8 holds a `nemoclaw.nvidia.com/v1alpha2` +/// document; earlier versions held v1alpha1 documents. +const RECORD_VERSION: u32 = 8; +const EARLIER_STATE: &str = "deployment state was written by an earlier NemoClaw for nemoclaw.nvidia.com/v1alpha1; retain it and use that NemoClaw to destroy it, or deploy this document as a separate deployment"; + #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", default, deny_unknown_fields)] pub(crate) struct Record { @@ -100,7 +105,7 @@ impl Record { let mut generations = Generations::new(); allocate_missing_generation_values(&mut generations, &document)?; Ok(Self { - version: 7, + version: RECORD_VERSION, digest: document.digest(), document, generations, @@ -283,9 +288,12 @@ impl Record { self.destroy_runtime } fn validate(&self) -> Result<(), Error> { - if self.version != 7 { + if self.version < RECORD_VERSION { + return Err(Error::State(EARLIER_STATE)); + } + if self.version != RECORD_VERSION { return Err(Error::State( - "deployment predates Docker-provider model cache ownership; retain state and use the original NemoClaw version for recovery or teardown", + "deployment intent record has an unsupported format version; retain it for recovery", )); } let generations_valid = required_generation_kinds(&self.document).is_ok_and(|kinds| { @@ -478,9 +486,23 @@ impl Store { Err(error) if error.kind() == ErrorKind::NotFound => return Ok(None), Err(_) => return Err(Error::State("cannot read deployment intent")), }; - let record: Record = serde_json::from_slice(&bytes).map_err(|_| { - Error::State("deployment intent record is corrupt; retain it for recovery") - })?; + let corrupt = + || Error::State("deployment intent record is corrupt; retain it for recovery"); + let raw: serde_json::Value = serde_json::from_slice(&bytes).map_err(|_| corrupt())?; + // An earlier record's document need not parse as the current type, so + // identify it before the typed parse would call it corrupt. + let earlier_version = raw + .get("version") + .and_then(serde_json::Value::as_u64) + .is_some_and(|version| version < u64::from(RECORD_VERSION)); + let earlier_document = raw + .pointer("/document/apiVersion") + .and_then(serde_json::Value::as_str) + == Some(crate::config::EARLIER_API_VERSION); + if earlier_version || earlier_document { + return Err(Error::State(EARLIER_STATE)); + } + let record: Record = serde_json::from_value(raw).map_err(|_| corrupt())?; record.validate()?; Ok(Some(record)) } diff --git a/crates/nemoclaw-sdk/src/state/tests.rs b/crates/nemoclaw-sdk/src/state/tests.rs index 69d0d9a4e22..7912b4554b4 100644 --- a/crates/nemoclaw-sdk/src/state/tests.rs +++ b/crates/nemoclaw-sdk/src/state/tests.rs @@ -50,27 +50,54 @@ fn corrupt_intent_is_not_an_empty_deployment() { let dir = tempfile::tempdir().unwrap(); let store = Store::open(dir.path()).unwrap(); std::fs::write(dir.path().join("intent.json"), "{broken").unwrap(); - assert!(store.load().is_err()); + assert_eq!( + store.load().unwrap_err().to_string(), + "deployment intent record is corrupt; retain it for recovery" + ); assert_eq!( std::fs::read_to_string(dir.path().join("intent.json")).unwrap(), "{broken" ); } #[test] -fn legacy_intent_is_rejected_without_rewriting_recovery_state() { - let dir = tempfile::tempdir().unwrap(); - let store = Store::open(dir.path()).unwrap(); +fn intent_from_another_nemoclaw_format_is_rejected_by_version_and_stays_untouched() { + let earlier = "deployment state was written by an earlier NemoClaw for nemoclaw.nvidia.com/v1alpha1; retain it and use that NemoClaw to destroy it, or deploy this document as a separate deployment"; let document = crate::config::Document::parse( include_str!("../../tests/fixtures/config/local.yaml").as_bytes(), ) .unwrap(); - let mut record = Record::new(document).unwrap(); - record.version = 6; - let bytes = serde_json::to_vec(&record).unwrap(); - let path = dir.path().join("intent.json"); - std::fs::write(&path, &bytes).unwrap(); - assert!(store.load().is_err()); - assert_eq!(std::fs::read(path).unwrap(), bytes); + let current = serde_json::to_value(Record::new(document).unwrap()).unwrap(); + assert_eq!(current["version"], 8); + // The last earlier format held a v1alpha1 document whose shape this + // NemoClaw cannot parse: sandboxes and providers were named list entries. + let mut written = current.clone(); + written["version"] = serde_json::json!(7); + written["document"]["apiVersion"] = serde_json::json!("nemoclaw.nvidia.com/v1alpha1"); + written["document"]["spec"]["sandboxes"] = serde_json::json!([ + {"name": "assistant", "harness": {"kind": "nvidia.fabric.openclaw"}} + ]); + let mut version = current.clone(); + version["version"] = serde_json::json!(6); + let mut api = current.clone(); + api["document"]["apiVersion"] = serde_json::json!("nemoclaw.nvidia.com/v1alpha1"); + let mut later = current.clone(); + later["version"] = serde_json::json!(9); + let unsupported = + "deployment intent record has an unsupported format version; retain it for recovery"; + for (record, message) in [ + (written, earlier), + (version, earlier), + (api, earlier), + (later, unsupported), + ] { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(dir.path()).unwrap(); + let bytes = serde_json::to_vec(&record).unwrap(); + let path = dir.path().join("intent.json"); + std::fs::write(&path, &bytes).unwrap(); + assert_eq!(store.load().unwrap_err().to_string(), message, "{record}"); + assert_eq!(std::fs::read(path).unwrap(), bytes); + } } #[test] diff --git a/crates/nemoclaw-sdk/tests/config_schema.rs b/crates/nemoclaw-sdk/tests/config_schema.rs index e225353c9cf..0e2d61d74f3 100644 --- a/crates/nemoclaw-sdk/tests/config_schema.rs +++ b/crates/nemoclaw-sdk/tests/config_schema.rs @@ -636,6 +636,52 @@ fn schema_diagnostic(value: &Value) -> String { format!("{path}: {constraint}") } +#[test] +fn a_document_for_the_earlier_api_version_fails_before_schema_validation() { + let earlier = "configuration uses nemoclaw.nvidia.com/v1alpha1; this NemoClaw reads nemoclaw.nvidia.com/v1alpha2; re-author it as described in docs/migration.md"; + // An earlier document reports its version rather than its first moved field. + let written = br#" +apiVersion: nemoclaw.nvidia.com/v1alpha1 +kind: NemoClawConfig +metadata: + name: local-agent + uid: 87d485ad-fba7-4197-9eaa-aa97cc97446b +spec: + gateway: + management: managed + runtime: + provider: docker + networkCIDR: 172.20.0.0/24 + inferenceProviders: + - name: local + provider: openai + endpoint: http://172.20.0.1:11434/v1 + sandboxes: + - name: assistant + harness: + kind: nvidia.fabric.openclaw +"#; + assert_eq!( + Document::parse(&written[..]).unwrap_err().to_string(), + earlier + ); + let mut current = input("local.yaml"); + current["apiVersion"] = json!("nemoclaw.nvidia.com/v1alpha1"); + assert_eq!( + Document::parse(current.to_string().as_bytes()) + .unwrap_err() + .to_string(), + earlier + ); + // Any other version keeps the schema's own constraint. + let mut later = input("local.yaml"); + later["apiVersion"] = json!("nemoclaw.nvidia.com/v1alpha3"); + assert_eq!( + schema_diagnostic(&later), + r#"apiVersion: must be "nemoclaw.nvidia.com/v1alpha2""# + ); +} + #[test] fn an_earlier_gateway_shape_names_the_field_that_moved() { let runtime = "spec.gateway.runtime is replaced by the key under spec.gateway.target: docker, podman, or kubernetes"; diff --git a/crates/nemoclaw-sdk/tests/fabric_planner.rs b/crates/nemoclaw-sdk/tests/fabric_planner.rs index e143a57e163..ddb67da4529 100644 --- a/crates/nemoclaw-sdk/tests/fabric_planner.rs +++ b/crates/nemoclaw-sdk/tests/fabric_planner.rs @@ -354,7 +354,7 @@ fn explicit_filesystem_grants_reject_nul_in_required_paths_and_grants() { fn the_reference_dummy_descriptor_plans_a_deployment_configuration() { use nemoclaw_sdk::config::Document; let document = Document::parse( - br#"apiVersion: nemoclaw.nvidia.com/v1alpha1 + br#"apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: dummy diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/fabric-claude.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/fabric-claude.yaml index 3d1438e7a4d..3022daf9c72 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/fabric-claude.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/fabric-claude.yaml @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: fabric-claude diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/fabric-pi.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/fabric-pi.yaml index fe3ea7a4c25..5665c064bb7 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/fabric-pi.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/fabric-pi.yaml @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: fabric-pi diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/fabric.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/fabric.yaml index 6a85a4de6ea..ad1d441f81f 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/fabric.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/fabric.yaml @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: fabric-agent diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/local.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/local.yaml index 1cbe7057a6d..db269a83f5b 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/local.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/local.yaml @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: local-agent diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/managed-ollama.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/managed-ollama.yaml index 0fa70d32929..a7bf3f7df1c 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/managed-ollama.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/managed-ollama.yaml @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: local-agent diff --git a/crates/nemoclaw-sdk/tests/fixtures/config/spark.yaml b/crates/nemoclaw-sdk/tests/fixtures/config/spark.yaml index af93d399b7f..7e2e1d1b260 100644 --- a/crates/nemoclaw-sdk/tests/fixtures/config/spark.yaml +++ b/crates/nemoclaw-sdk/tests/fixtures/config/spark.yaml @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: spark-recipe diff --git a/docs/build.md b/docs/build.md index 884f7db2336..2891979defd 100644 --- a/docs/build.md +++ b/docs/build.md @@ -29,7 +29,7 @@ The SDK verifies the bundle before use. A `Deployment` hashes the bundle on its first operation and again only when the manifest or a file it lists is written, replaced, or removed. Managed Kubernetes deployment uses the bundled Helm provider and requires no host Helm CLI. -Each bundle includes `schemas/nemoclaw-v1alpha1.schema.json`, generated from its SDK contract and covered by the manifest hash. +Each bundle includes `schemas/nemoclaw-v1alpha2.schema.json`, generated from its SDK contract and covered by the manifest hash. Use that file for [editor assistance](usage.md#editor-schema-assistance) with the bundled CLI. The API version alone does not identify a source revision. diff --git a/docs/contributing/configuration-schema.md b/docs/contributing/configuration-schema.md index e1a2c56cba8..d6346563d62 100644 --- a/docs/contributing/configuration-schema.md +++ b/docs/contributing/configuration-schema.md @@ -3,7 +3,7 @@ # Maintain the Configuration Schema -The [YAML field reference](../reference/configuration.md) and [JSON Schema](../../schemas/nemoclaw-v1alpha1.schema.json) come from the SDK's configuration types and validation constraints. +The [YAML field reference](../reference/configuration.md) and [JSON Schema](../../schemas/nemoclaw-v1alpha2.schema.json) come from the SDK's configuration types and validation constraints. Edit their Rust sources, then regenerate both artifacts. CI rejects stale output. @@ -36,7 +36,7 @@ From the repository root: cargo run --locked -p nemoclaw-build -- schema ``` -The command replaces `schemas/nemoclaw-v1alpha1.schema.json` and `docs/reference/configuration.md` from the compiled SDK. +The command replaces `schemas/nemoclaw-v1alpha2.schema.json` and `docs/reference/configuration.md` from the compiled SDK. It contacts no deployment services and creates no runtime resources. Review both generated diffs with the source change. Generation fails when a public field or object has no description. @@ -104,14 +104,29 @@ Use the same typed definition and resolved behavior for inline and reference for Test missing and conflicting selections, scope collisions, unused definitions, and export/reapply. Add the family to the authoring guide's coverage table only when its runtime behavior is implemented. +## Change the API Version + +The schema's API version identifies the document format. +A revision that rejects or reinterprets a document the previous revision accepted changes the API version; adding an optional field does not. +An SDK still rejects fields added after its revision, so the API version alone does not identify a compatible SDK. + +To change the API version: + +1. Change `api_version!` in the [configuration module](../../crates/nemoclaw-sdk/src/config/mod.rs). + It sets `apiVersion`, the schema file name, and the schema's `$id` and title. +2. Set `EARLIER_API_VERSION` in the same file to the replaced version, and raise `RECORD_VERSION` and update `EARLIER_STATE` in the [state store](../../crates/nemoclaw-sdk/src/state/mod.rs). + Earlier documents and state then fail with a pointer to [migration](../migration.md) instead of a schema or corruption error. +3. Move the schema file with `git mv`, regenerate, and update examples, fixtures, and pages that name the version. + The freshness check fails while a schema file for another version remains in `schemas/`. +4. Add the changed fields to the [re-authoring procedure](../migration.md#re-author-a-v1alpha1-document) and the [release notes](../release-notes.md). + ## Keep Generation Reproducible The generator selects JSON Schema Draft 2020-12 explicitly, sorts object keys, and writes LF-terminated files. Schemars and the runtime validator have fixed versions in [Cargo.toml](../../Cargo.toml), with resolved dependencies in [Cargo.lock](../../Cargo.lock). Review generated changes when updating those dependencies. -The schema's API version identifies the document format; accepted fields can change between source revisions without changing that version. Use a schema from the same source revision as the SDK or CLI you run. -Native bundles carry their matching schema at `schemas/nemoclaw-v1alpha1.schema.json`, covered by the bundle manifest's hash. +Native bundles carry their matching schema at `schemas/nemoclaw-v1alpha2.schema.json`, covered by the bundle manifest's hash. The builder generates it from the compiled SDK and checks its source fingerprint before assembling CLI and provider binaries. See [bundle construction](../build.md#build-a-native-bundle) for rebuild and verification behavior. diff --git a/docs/contributing/documentation-build.md b/docs/contributing/documentation-build.md index bd9b1804ffd..e7877268556 100644 --- a/docs/contributing/documentation-build.md +++ b/docs/contributing/documentation-build.md @@ -15,7 +15,7 @@ Publication does not qualify the procedures or product configurations they descr | [Page manifest](../../fern/pages.json) | Selects published guides, navigation labels, and stable route slugs | | Repository `docs/*.md` and selected subdirectories | Generated `fern/_generated/pages/*.mdx` and `navigation.yml` | | [Pinned main revision](../../fern/main-source.json) | Earlier guides, generated agent variants, changelog, components, and assets under ignored `fern/_main/` | -| SDK types and constraints | [JSON Schema](../../schemas/nemoclaw-v1alpha1.schema.json) and [configuration reference](../reference/configuration.md); stale checked-in output fails validation | +| SDK types and constraints | [JSON Schema](../../schemas/nemoclaw-v1alpha2.schema.json) and [configuration reference](../reference/configuration.md); stale checked-in output fails validation | | [Fern configuration](../../fern/docs.yml) | NVIDIA theme, both versions, existing instances, and retained legacy redirects | | [Fern CLI pin](../../fern/fern.config.json) | The exact CLI used locally and in CI | diff --git a/docs/get-started.md b/docs/get-started.md index 6d788d32b5d..59bf8d8d5ff 100644 --- a/docs/get-started.md +++ b/docs/get-started.md @@ -79,7 +79,7 @@ Edit the copied YAML before executing it: Keep `gateway.management: external`, sandbox name `assistant`, and loopback dashboard port `18800` to match the access commands. The `engine` is used only for image inspection; it does not grant NemoClaw ownership of the external gateway. External gateways have no default image engine; use the address of the daemon holding the image, which may be on another host. -Update the copied schema comment to `../../schemas/nemoclaw-v1alpha1.schema.json` so editor diagnostics use this checkout's schema. +Update the copied schema comment to `../../schemas/nemoclaw-v1alpha2.schema.json` so editor diagnostics use this checkout's schema. Use the [field reference](reference/configuration.md) for accepted fields. For an authenticated inference endpoint, add this under its provider: diff --git a/docs/migration.md b/docs/migration.md index fefe699540f..d4793ef2627 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -10,6 +10,8 @@ Keep the earlier deployment's tooling, configuration, and state while evaluating There is no rehearsed upgrade, native-data transfer or rollback procedure yet ([#12639](https://github.com/NVIDIA/NemoClaw/issues/12639)). The evaluation steps below create a separate deployment; they do not provide an in-place upgrade or data conversion. +To move a v1 document from `nemoclaw.nvidia.com/v1alpha1` to `nemoclaw.nvidia.com/v1alpha2`, [re-author it](#re-author-a-v1alpha1-document). + ## Map the User Task | Earlier task | Current destination | @@ -65,6 +67,132 @@ Read [state and retention](state.md) before retiring either deployment. Backup and restore of native agent data are tracked in [#12639](https://github.com/NVIDIA/NemoClaw/issues/12639). Retain the earlier deployment until the required continuity has been verified. +## Re-Author a v1alpha1 Document + +This NemoClaw reads `apiVersion: nemoclaw.nvidia.com/v1alpha2`. +Earlier v1 revisions wrote `nemoclaw.nvidia.com/v1alpha1`, which places the gateway settings and names sandboxes and inference providers differently. +This NemoClaw rejects that document, and state written by an earlier NemoClaw, without changing any resource: + +| Input | Error | +|---|---| +| A v1alpha1 document given to `plan` or `apply` | `configuration uses nemoclaw.nvidia.com/v1alpha1; this NemoClaw reads nemoclaw.nvidia.com/v1alpha2; re-author it as described in docs/migration.md` | +| A state directory written by an earlier NemoClaw, with any command that reads it | `deployment state was written by an earlier NemoClaw for nemoclaw.nvidia.com/v1alpha1; retain it and use that NemoClaw to destroy it, or deploy this document as a separate deployment` | + +There is no conversion command, and this NemoClaw cannot adopt the earlier deployment's resources. +Re-author the document by hand and apply it as a separate deployment. +Agent files and conversation history are not transferred ([#12639](https://github.com/NVIDIA/NemoClaw/issues/12639)). + +### Keep the Earlier Document + +Keep the earlier bundle and its state directory; this NemoClaw cannot export or destroy that deployment. +Keep the v1alpha1 YAML you applied; it is the source for re-authoring and keeps its comments. +If you no longer have it, export it with the earlier bundle's CLI: + +```sh +/path/to/earlier-bundle/bin/nemoclaw export --state-dir .local/deployment --output v1alpha1.yaml +``` + +Export observes the running deployment and fails when its resources are unavailable or differ from the retained intent. +Check its exit status before using the file. + +### Rewrite the Fields + +Copy the document and make these changes: + +1. Set `apiVersion: nemoclaw.nvidia.com/v1alpha2`. +2. Set `metadata.uid` to a fresh UUID, for example from `uuidgen`. + A reused UID selects the earlier deployment's resource names. +3. Change a `# yaml-language-server: $schema=` comment to `nemoclaw-v1alpha2.schema.json`. +4. Move each field that v1alpha2 changed: + +| v1alpha1 field | v1alpha2 field | +|---|---| +| Managed `spec.gateway.runtime.provider`: `docker`, `podman`, or `kubernetes`; omitted means `docker` | The one key under `spec.gateway.target`; omitted `target` means `docker` | +| Managed `spec.gateway.runtime.provider: openshift` | `spec.gateway.target.kubernetes.distribution: openshift` | +| Managed `spec.gateway.endpoint` | `spec.gateway.target..endpoint`; required under `kubernetes` | +| Managed `spec.gateway.engine` and `spec.gateway.imagePullPolicy` | The same names under `spec.gateway.target.docker` or `spec.gateway.target.podman` | +| Managed `spec.gateway.networkCIDR` | `networkCidr` under `spec.gateway.target.docker` or `spec.gateway.target.podman` | +| `spec.gateway.kubernetes`: `kubeconfig`, `context`, `namespace`, `authentication`, and `environment` | The same names under `spec.gateway.target.kubernetes` | +| `spec.gateway.image` | Removed; delete it, because the SDK pins the gateway image | +| External `spec.gateway.runtime.provider: docker` or `podman`, with `spec.gateway.engine` | `spec.gateway.target.docker.engine` or `spec.gateway.target.podman.engine`; `engine` stays optional | +| External `spec.gateway.runtime.provider: kubernetes` or `openshift` | `spec.gateway.target.kubernetes: {}` | +| External `spec.gateway.endpoint`, `credential`, and `tls` | Unchanged | +| `spec.sandboxes` list entries, each with `name` | A map from each sandbox name to its settings, without `name` | +| `spec.inferenceProviders` and a sandbox's `inferenceProviders` list entries, each with `name` | Maps from each provider name to its settings, without `name` | +| An inline route provider, `routes[].provider`, with `name` | Unchanged; `name` stays required | +| Credential references, `{env: NAME}` | Unchanged | + +Names keep their earlier rules, and a deployment holds 1 to 32 sandboxes. +Map order has no meaning. + +For example, this v1alpha1 excerpt: + +```yaml +spec: + gateway: + management: managed + runtime: + provider: docker + endpoint: http://127.0.0.1:17671 + networkCIDR: 172.20.0.0/24 + inferenceProviders: + - name: local + provider: openai + endpoint: http://172.20.0.1:11434/v1 + sandboxes: + - name: assistant + harness: + kind: nvidia.fabric.openclaw +``` + +becomes: + +```yaml +spec: + gateway: + management: managed + target: + docker: + endpoint: http://127.0.0.1:17671 + networkCidr: 172.20.0.0/24 + inferenceProviders: + local: + provider: openai + endpoint: http://172.20.0.1:11434/v1 + sandboxes: + assistant: + harness: + kind: nvidia.fabric.openclaw +``` + +Plan the result with the new deployment's state directory. +A field left at its v1alpha1 location fails with a message that names its replacement, for example: + +```text +configuration violates schema at spec.gateway (line 8, column 5): spec.gateway.runtime is replaced by the key under spec.gateway.target: docker, podman, or kubernetes; spec.gateway.endpoint of a managed gateway moved to the endpoint of its spec.gateway.target key; spec.gateway.networkCIDR moved to networkCidr under spec.gateway.target.docker or spec.gateway.target.podman +``` + +Each run reports one location; correct it and plan again until the document parses. +The [configuration reference](reference/configuration.md) lists every v1alpha2 field. +To start over instead, `nemoclaw onboard` writes a v1alpha2 document with a fresh UID. + +### Deploy the Re-Authored Document + +Choose what happens to the earlier deployment: + +- **Destroy it with the earlier NemoClaw.** + Run `/path/to/earlier-bundle/bin/nemoclaw plan --destroy --state-dir .local/deployment`, review the preview, then run the same CLI's `destroy` with that state directory. + **Destroy deletes sandbox files and conversation history.** + The storage it retains, and how to remove that storage, follow the earlier revision's documentation. +- **Keep it.** + Keep its bundle and state directory to operate it. + +Then apply the re-authored document as a separate deployment, as in [Keep Deployment Identities Separate](#keep-deployment-identities-separate): + +- Use its fresh `metadata.uid` and a new state directory. +- Give the gateway an endpoint, `networkCidr`, and Kubernetes namespace that the earlier deployment does not use; destroy retains the earlier gateway network and namespace. +- Plan and apply with this NemoClaw. + ## Find Earlier Documentation The [combined staging site](https://nvidia-preview-nemoclaw-v1.docs.buildwithfern.com/nemoclaw/v1/overview) has a version selector: diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index bb94e9ec118..ba06b6c2dab 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -5,7 +5,7 @@ -This reference and the [JSON Schema](../../schemas/nemoclaw-v1alpha1.schema.json) describe authored YAML for this source revision. +This reference and the [JSON Schema](../../schemas/nemoclaw-v1alpha2.schema.json) describe authored YAML for this source revision. See [schema maintenance](../contributing/configuration-schema.md) for generation and validation commands. Paths use `[]` for an array element and `{key}` for a map entry. @@ -43,7 +43,7 @@ Paths: | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| -| `apiVersion` | string | Yes | — | Configuration API version understood by this SDK. Constraints: `"nemoclaw.nvidia.com/v1alpha1"`. | +| `apiVersion` | string | Yes | — | Configuration API version understood by this SDK. Constraints: `"nemoclaw.nvidia.com/v1alpha2"`. | | `kind` | string | Yes | — | Configuration document kind. Constraints: `"NemoClawConfig"`. | | `metadata` | [Metadata](#metadata) | Yes | — | Deployment name and durable ownership identity. | | `spec` | [Spec](#spec) | Yes | — | Gateway, inference provider, and sandbox configuration. | diff --git a/docs/release-notes.md b/docs/release-notes.md index faf9a141b0a..04692e5cfb3 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -17,6 +17,19 @@ See [the overview](overview.md) for implemented boundaries and [the CLI referenc Earlier CLI commands, schemas, and state formats have no compatibility guarantees. See [migration](migration.md) for where each earlier task lives now, and [state](state.md) for data preservation. +The configuration API version is now `nemoclaw.nvidia.com/v1alpha2`, with its schema at `schemas/nemoclaw-v1alpha2.schema.json`. +It makes five changes: + +- `spec.gateway.target` selects the backend with one key, `docker`, `podman`, or `kubernetes`, which holds that backend's settings. + It replaces `runtime.provider` and `spec.gateway.kubernetes` and takes the managed `endpoint`, `engine`, and `imagePullPolicy`; `distribution: openshift` replaces the `openshift` provider. +- `spec.gateway.image` is removed; the SDK pins the gateway image. +- The managed gateway's `networkCIDR` is spelled `networkCidr`. +- `spec.sandboxes`, `spec.inferenceProviders`, and a sandbox's `inferenceProviders` are maps keyed by name instead of lists of entries with `name`. +- Credential references are typed `SecretRef` or `FileRef` in the schema and the Rust SDK; the YAML form `{env: NAME}` is unchanged. + +Deployment state uses `intent.json` format version 8. +This NemoClaw rejects v1alpha1 documents and state written by an earlier NemoClaw without converting or adopting them; [re-author each document](migration.md#re-author-a-v1alpha1-document) and apply it as a separate deployment. + ## Qualification and Known Issues See [current limits](limits.md) for what v1 does not do yet or has not tested, with the issue tracking each. diff --git a/docs/sdk.md b/docs/sdk.md index ec658850e90..2594c987208 100644 --- a/docs/sdk.md +++ b/docs/sdk.md @@ -22,7 +22,7 @@ serde_json = "1" The SDK build also needs the pinned Protocol Buffers compiler and native C toolchain described in the build guide. An application outside this workspace resolves its own dependencies and lockfile. -Keep its SDK checkout, built bundle, and input schema matched; the `v1alpha1` API string alone does not establish compatibility. +Keep its SDK checkout, built bundle, and input schema matched; the API version alone does not establish compatibility. ## Preview a Deployment diff --git a/docs/state.md b/docs/state.md index 018c074d945..66a1d12f958 100644 --- a/docs/state.md +++ b/docs/state.md @@ -25,7 +25,10 @@ They are implementation details for identifying retained state, not a manual edi The [state store](../crates/nemoclaw-sdk/src/state/mod.rs), [deployment lifecycle](../crates/nemoclaw-sdk/src/deployment/mod.rs), and [OpenTofu configuration](../crates/nemoclaw-sdk/src/deployment/opentofu.rs) define these files. Keep the whole directory after failure; deleting state does not establish that its runtime resources are absent. The local lock does not exclude other clients of the same gateway. -State records carry a format version; the SDK rejects a different version without rewriting the directory or adopting its resources. +`intent.json` records format version 8 and a `nemoclaw.nvidia.com/v1alpha2` document. +The SDK rejects any other format version without rewriting the directory or adopting its resources. +State from an earlier NemoClaw, with format version 7 or earlier or a `nemoclaw.nvidia.com/v1alpha1` document, fails with `deployment state was written by an earlier NemoClaw for nemoclaw.nvidia.com/v1alpha1`. +Keep that directory for the NemoClaw that wrote it, and follow [re-authoring](migration.md#re-author-a-v1alpha1-document) to deploy with this one. ## Agent Files diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index f9004cf3ee7..91fd7066f52 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -37,6 +37,7 @@ Do not attach environment dumps, TLS private keys, interface tokens, or the enti |---|---| | Unknown field, duplicate key, or rejected combination | Use the [document path and source position](#correct-a-document-validation-error), then compare the input with the matching [configuration reference](reference/configuration.md) | | Bundle or schema hash failure | Follow [bundle rebuilding](build.md#build-a-native-bundle) and keep the selected bundle unchanged during operations | +| `configuration uses nemoclaw.nvidia.com/v1alpha1` or `deployment state was written by an earlier NemoClaw` | Keep the earlier bundle and state directory, and [re-author the document](migration.md#re-author-a-v1alpha1-document) for a separate deployment | | `state is bound to a different deployment UID or gateway` | Restore the original UID and gateway endpoint; a new target needs separate state and resources | | `unfinished apply has different intent` | Reapply the exact YAML from the unfinished operation before trying another configuration | | Deployment lock error | Check for another operation using the same state directory; a lock failure does not authorize state deletion | diff --git a/docs/usage.md b/docs/usage.md index e2d9800cc79..205c9851802 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -219,11 +219,11 @@ There is no migration or lost-state adoption workflow for credentials or gateway Add a schema comment for editor completion, descriptions, and diagnostics: ```yaml -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json ``` Editors using [YAML Language Server](https://github.com/redhat-developer/yaml-language-server) resolve the path relative to the YAML file; update it when copying examples. -Select `schemas/nemoclaw-v1alpha1.schema.json` from the matching bundle or CLI source revision; the API version alone is insufficient. +Select `schemas/nemoclaw-v1alpha2.schema.json` from the matching bundle or CLI source revision; the API version alone is insufficient. Keep `$schema` in the comment; a YAML field named `$schema` is an unknown configuration field and is rejected. Exported YAML omits comments, so add the association again if you want editor assistance for an export. @@ -259,6 +259,7 @@ Use separate deployments when you need independent teardown. | Sandbox network policy | Changes the sandbox specification; follow [policy change constraints](sandbox-network.md) and use a separate deployment when replacement is required | | Managed inference or proxy image or serving specification | Docker-provider reconciliation may replace the container while retaining its independently bound storage; review the plan and [model constraints](models.md) | | Deployment UID, [bound gateway settings](#choose-the-gateway-target), or bound credentials | Cannot retarget the existing state; create a separate deployment | +| Move from a NemoClaw that wrote `nemoclaw.nvidia.com/v1alpha1` documents and state | This NemoClaw rejects both without changing resources; keep the earlier bundle and state, and [re-author the document](migration.md#re-author-a-v1alpha1-document) for a separate deployment | | Remove an unused inference provider definition | Changes the desired document only; the SDK creates registrations for selected definitions, so unused definitions have no resources to delete | | Remove or rename a sandbox, or remove retained storage or a protected gateway binding | Apply refuses removal; assess a separate deployment and explicit retirement of the original | | Change a credential value behind the same environment reference | Unchanged apply does not detect rotation; see [credential lifecycle](security.md#credentials-and-authentication) | diff --git a/examples/explicit-policy.yaml b/examples/explicit-policy.yaml index 5b573c5ffd6..ad41dcebfe8 100644 --- a/examples/explicit-policy.yaml +++ b/examples/explicit-policy.yaml @@ -1,8 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: explicit-policy-agent diff --git a/examples/fabric-claude.yaml b/examples/fabric-claude.yaml index 066fc79d284..6ee4ca59b1c 100644 --- a/examples/fabric-claude.yaml +++ b/examples/fabric-claude.yaml @@ -1,10 +1,10 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json # Replace the fixture endpoint/model with your own compatible service. # See docs/reference/fabric-harnesses.md for protocol requirements and test commands. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: fabric-claude diff --git a/examples/fabric-codex.yaml b/examples/fabric-codex.yaml index f6a2510b716..7f65446937f 100644 --- a/examples/fabric-codex.yaml +++ b/examples/fabric-codex.yaml @@ -1,10 +1,10 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json # Replace the fixture endpoint/model with your own compatible service. # See docs/reference/fabric-harnesses.md for protocol requirements and test commands. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: fabric-codex diff --git a/examples/fabric-hermes.yaml b/examples/fabric-hermes.yaml index 2325c1d75e6..ccad0856372 100644 --- a/examples/fabric-hermes.yaml +++ b/examples/fabric-hermes.yaml @@ -1,8 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: fabric-hermes diff --git a/examples/fabric-mini-swe-agent.yaml b/examples/fabric-mini-swe-agent.yaml index 670024ab511..8a7a96f93e1 100644 --- a/examples/fabric-mini-swe-agent.yaml +++ b/examples/fabric-mini-swe-agent.yaml @@ -1,10 +1,10 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json # Replace the fixture endpoint/model with your own compatible service. # See docs/reference/fabric-harnesses.md for protocol requirements and test commands. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: fabric-mini-swe-agent diff --git a/examples/fabric-nooa-bench.yaml b/examples/fabric-nooa-bench.yaml index 303b3d9bb46..1dc4a6f743d 100644 --- a/examples/fabric-nooa-bench.yaml +++ b/examples/fabric-nooa-bench.yaml @@ -1,10 +1,10 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json # Replace the fixture endpoint/model with your own compatible service. # See docs/reference/fabric-harnesses.md for protocol requirements and test commands. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: fabric-nooa-bench diff --git a/examples/fabric-nooa.yaml b/examples/fabric-nooa.yaml index e9355c22006..e119365bdf4 100644 --- a/examples/fabric-nooa.yaml +++ b/examples/fabric-nooa.yaml @@ -1,10 +1,10 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json # Replace the fixture endpoint/model with your own compatible service. # See docs/reference/fabric-harnesses.md for protocol requirements and test commands. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: fabric-nooa diff --git a/examples/fabric-openclaw.yaml b/examples/fabric-openclaw.yaml index 3a8586ee4cd..b2c896e3c58 100644 --- a/examples/fabric-openclaw.yaml +++ b/examples/fabric-openclaw.yaml @@ -1,8 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: fabric-openclaw diff --git a/examples/fabric-pi.yaml b/examples/fabric-pi.yaml index 5a1cad6542d..310fa6ebcd2 100644 --- a/examples/fabric-pi.yaml +++ b/examples/fabric-pi.yaml @@ -1,10 +1,10 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json # Set the endpoint and model for your service. Custom models need piModel metadata. # See docs/agents.md for catalog models and protocol requirements. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: fabric-pi diff --git a/examples/fabric-remote-agent.yaml b/examples/fabric-remote-agent.yaml index 146a39571d9..23a0679b345 100644 --- a/examples/fabric-remote-agent.yaml +++ b/examples/fabric-remote-agent.yaml @@ -1,10 +1,10 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json # Replace the fixture endpoint/model with your own compatible service. # See docs/reference/fabric-harnesses.md for protocol requirements and test commands. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: fabric-remote-agent diff --git a/examples/fabric.yaml b/examples/fabric.yaml index 8e2a1b6cfcf..8a258652408 100644 --- a/examples/fabric.yaml +++ b/examples/fabric.yaml @@ -1,8 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: fabric-agent diff --git a/examples/full-featured-openclaw.yaml b/examples/full-featured-openclaw.yaml index f0a8c2393b6..2469469cf9f 100644 --- a/examples/full-featured-openclaw.yaml +++ b/examples/full-featured-openclaw.yaml @@ -1,13 +1,13 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json # Broad compatible feature example, not an all-fields template or a live-qualified deployment. # Replace the UID, image placeholders, SSH alias, addresses, and model settings for your hosts. # Requires local Docker/OpenShell, a compatible remote NVIDIA GPU, an existing proxy and OTLP collector, # and BRAVE_API_KEY on the applying host. Apply provisions resources and checks readiness without inference. # See docs/configuration-references.md#combine-supported-features for alternatives and limits. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: full-featured-openclaw diff --git a/examples/hermes-auth.yaml b/examples/hermes-auth.yaml index 298bcef6f0e..641854f9c00 100644 --- a/examples/hermes-auth.yaml +++ b/examples/hermes-auth.yaml @@ -1,8 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: hermes-auth diff --git a/examples/hermes-interfaces.yaml b/examples/hermes-interfaces.yaml index 65c70e3d904..7ec39b173fc 100644 --- a/examples/hermes-interfaces.yaml +++ b/examples/hermes-interfaces.yaml @@ -1,8 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: hermes-interfaces diff --git a/examples/inference-tuning.yaml b/examples/inference-tuning.yaml index 35df1dda98b..0d1c9eb7d47 100644 --- a/examples/inference-tuning.yaml +++ b/examples/inference-tuning.yaml @@ -1,8 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: tuned-agent diff --git a/examples/inline-inference.yaml b/examples/inline-inference.yaml index cae010a63f1..b9d3c9846ca 100644 --- a/examples/inline-inference.yaml +++ b/examples/inline-inference.yaml @@ -1,11 +1,11 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json # Defines the provider on its sole consuming route; see docs/configuration-references.md. # Set your own deployment UID, endpoints, and model before applying. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: inline-inference diff --git a/examples/kubernetes/external-gateway.yaml b/examples/kubernetes/external-gateway.yaml index c4905948c11..ab6bde4201d 100644 --- a/examples/kubernetes/external-gateway.yaml +++ b/examples/kubernetes/external-gateway.yaml @@ -1,11 +1,11 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha2.schema.json # Supply a unique deployment UID, an accessible digest-selected image for every agent, # and an inference endpoint reachable from inside each Kubernetes sandbox. # Write each image's metadata bundle with `cargo images export-metadata` and set # NEMOCLAW_AGENT_IMAGE_METADATA to its path; see docs/build.md. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: kubernetes-agent diff --git a/examples/kubernetes/hosted-nvidia.yaml b/examples/kubernetes/hosted-nvidia.yaml index ffe07ab9a6b..fd7ef64c388 100644 --- a/examples/kubernetes/hosted-nvidia.yaml +++ b/examples/kubernetes/hosted-nvidia.yaml @@ -1,12 +1,12 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha2.schema.json # The shared inference profile matches the Docker hosted-NVIDIA fixture at # crates/nemoclaw-e2e/fixtures/openclaw-nvidia-hosted/v1.yaml. # Replace the deployment UID and every image digest before applying. # Write each image's metadata bundle with `cargo images export-metadata` and set # NEMOCLAW_AGENT_IMAGE_METADATA to its path; see docs/build.md. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: kubernetes-hosted-nvidia diff --git a/examples/kubernetes/managed-development.yaml b/examples/kubernetes/managed-development.yaml index 8cd8887b1a6..69f42d22d2f 100644 --- a/examples/kubernetes/managed-development.yaml +++ b/examples/kubernetes/managed-development.yaml @@ -1,13 +1,13 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha2.schema.json # One apply provisions a development gateway and three agents on an existing cluster. # Requires explicit access to an existing Kubernetes cluster with Agent Sandbox # and one default StorageClass installed. # Replace the deployment UID and every image digest before applying. # Write each image's metadata bundle with `cargo images export-metadata` and set # NEMOCLAW_AGENT_IMAGE_METADATA to its path; see docs/build.md. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: kubernetes-managed-development diff --git a/examples/local.yaml b/examples/local.yaml index e16ad40e8f8..687c23f7d86 100644 --- a/examples/local.yaml +++ b/examples/local.yaml @@ -1,8 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: local-agent diff --git a/examples/managed-hermes.yaml b/examples/managed-hermes.yaml index 61e40448e88..a0c40319831 100644 --- a/examples/managed-hermes.yaml +++ b/examples/managed-hermes.yaml @@ -1,8 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: local-agent diff --git a/examples/managed-ollama-gpu.yaml b/examples/managed-ollama-gpu.yaml index 02ea33693a0..0c78fd5e839 100644 --- a/examples/managed-ollama-gpu.yaml +++ b/examples/managed-ollama-gpu.yaml @@ -1,8 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: managed-ollama-gpu diff --git a/examples/managed-ollama.yaml b/examples/managed-ollama.yaml index 1f9d18fca27..988fbd62486 100644 --- a/examples/managed-ollama.yaml +++ b/examples/managed-ollama.yaml @@ -1,8 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: local-agent diff --git a/examples/managed-podman.yaml b/examples/managed-podman.yaml index 9ca44080896..46678d38ef8 100644 --- a/examples/managed-podman.yaml +++ b/examples/managed-podman.yaml @@ -1,10 +1,10 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json # Local rootless Linux; see docs/usage.md for API and networking prerequisites. # Set the API socket and use an image digest from that Podman image store. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: podman-agent diff --git a/examples/multiple-models.yaml b/examples/multiple-models.yaml index ee3415e6eb3..075e66063b9 100644 --- a/examples/multiple-models.yaml +++ b/examples/multiple-models.yaml @@ -1,9 +1,9 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json # Replace the UID, endpoint, model IDs, and agent image for your services. # The existing endpoint must serve both models; this example does not start it. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: multiple-models diff --git a/examples/multiple-providers.yaml b/examples/multiple-providers.yaml index ae3cd03954c..048396f36a3 100644 --- a/examples/multiple-providers.yaml +++ b/examples/multiple-providers.yaml @@ -1,10 +1,10 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json # Replace the UID, endpoint, model IDs, and agent image for your services. # Requires a local model endpoint and a hosted HTTPS endpoint; this example starts neither. # Set HOSTED_API_KEY on the applying host. Requests to a hosted model may incur charges. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: multiple-providers diff --git a/examples/multiple-sandboxes.yaml b/examples/multiple-sandboxes.yaml index 5b4578686fa..1d0c82cff5d 100644 --- a/examples/multiple-sandboxes.yaml +++ b/examples/multiple-sandboxes.yaml @@ -1,8 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json # Replace the deployment UID, image pins, endpoint, and model for your host. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: multiple-sandboxes diff --git a/examples/nemotron-amd64.yaml b/examples/nemotron-amd64.yaml index 52d4216ec27..8d902a76cf8 100644 --- a/examples/nemotron-amd64.yaml +++ b/examples/nemotron-amd64.yaml @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json -apiVersion: nemoclaw.nvidia.com/v1alpha1 +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: remote-nemotron-model diff --git a/examples/onboarding/openclaw.yaml b/examples/onboarding/openclaw.yaml index acaea546775..a0a465dac6a 100644 --- a/examples/onboarding/openclaw.yaml +++ b/examples/onboarding/openclaw.yaml @@ -1,8 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha2.schema.json # YAML defaults for `nemoclaw onboard`; the command assigns a new deployment UID. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: openclaw-nvidia-hosted diff --git a/examples/openclaw-dashboard.yaml b/examples/openclaw-dashboard.yaml index 75a7804598c..80456aa08dd 100644 --- a/examples/openclaw-dashboard.yaml +++ b/examples/openclaw-dashboard.yaml @@ -1,8 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: openclaw-dashboard diff --git a/examples/openclaw-web-search.yaml b/examples/openclaw-web-search.yaml index 50168f9009c..03c03ba4a86 100644 --- a/examples/openclaw-web-search.yaml +++ b/examples/openclaw-web-search.yaml @@ -1,11 +1,11 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json # Two agents share one inference provider and one Brave search definition. # Set your own deployment UID, endpoints, and model; see docs/agents.md#brave-web-search. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: openclaw-web-search diff --git a/examples/openshift/external-gateway.yaml b/examples/openshift/external-gateway.yaml index 63ae47e6b87..187ce43026e 100644 --- a/examples/openshift/external-gateway.yaml +++ b/examples/openshift/external-gateway.yaml @@ -1,11 +1,11 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha2.schema.json # Supply a unique deployment UID, an accessible digest-selected image for every agent, # and an inference endpoint reachable from inside each OpenShift sandbox. # Write each image's metadata bundle with `cargo images export-metadata` and set # NEMOCLAW_AGENT_IMAGE_METADATA to its path; see docs/build.md. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: openshift-agent diff --git a/examples/openshift/managed-development.yaml b/examples/openshift/managed-development.yaml index 66f5333c7ba..53deda70751 100644 --- a/examples/openshift/managed-development.yaml +++ b/examples/openshift/managed-development.yaml @@ -1,13 +1,13 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha2.schema.json # One apply provisions a development gateway and three agents on an existing cluster. # Requires explicit access to an existing OpenShift cluster with Agent Sandbox # and one default StorageClass installed. # Replace the deployment UID and every image digest before applying. # Write each image's metadata bundle with `cargo images export-metadata` and set # NEMOCLAW_AGENT_IMAGE_METADATA to its path; see docs/build.md. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: openshift-managed-development diff --git a/examples/spark/deepagents-team.yaml b/examples/spark/deepagents-team.yaml index 68ebd9e4d36..6f0a04ccd6f 100644 --- a/examples/spark/deepagents-team.yaml +++ b/examples/spark/deepagents-team.yaml @@ -1,9 +1,9 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha2.schema.json # Build current images and replace these local digests and the deployment UID. # Model sources, host requirements, and validation limits: README.md. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: spark-deepagents-team diff --git a/examples/spark/local-and-hosted.yaml b/examples/spark/local-and-hosted.yaml index 6c5fcd6c914..4fe5707ef6a 100644 --- a/examples/spark/local-and-hosted.yaml +++ b/examples/spark/local-and-hosted.yaml @@ -1,9 +1,9 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha2.schema.json # Build current images and replace these local digests and the deployment UID. # Model sources, host requirements, and validation limits: README.md. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: spark-local-and-hosted diff --git a/examples/spark/pi-small.yaml b/examples/spark/pi-small.yaml index dbed01862d7..7346eaa5e23 100644 --- a/examples/spark/pi-small.yaml +++ b/examples/spark/pi-small.yaml @@ -1,9 +1,9 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha2.schema.json # Build current images and replace these local digests and the deployment UID. # Model sources, host requirements, and validation limits: README.md. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: spark-pi-small diff --git a/examples/spark/remote-vllm.yaml b/examples/spark/remote-vllm.yaml index 638e3f0a1c4..8548b15d378 100644 --- a/examples/spark/remote-vllm.yaml +++ b/examples/spark/remote-vllm.yaml @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json -apiVersion: nemoclaw.nvidia.com/v1alpha1 +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha2.schema.json +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: remote-qwen3-model diff --git a/examples/spark/shared-model.yaml b/examples/spark/shared-model.yaml index 3e806eab70c..0a0c5d6aa33 100644 --- a/examples/spark/shared-model.yaml +++ b/examples/spark/shared-model.yaml @@ -1,9 +1,9 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha2.schema.json # Build current images and replace these local digests and the deployment UID. # Model sources, host requirements, and validation limits: README.md. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: spark-shared-model diff --git a/examples/spark/spark-inline.yaml b/examples/spark/spark-inline.yaml index d06a290f259..f15b7e4bc3f 100644 --- a/examples/spark/spark-inline.yaml +++ b/examples/spark/spark-inline.yaml @@ -2,8 +2,8 @@ # SPDX-License-Identifier: Apache-2.0 # Model tuning informed by MiaAI Lab's AGPL-3.0-or-later single-Spark recipe. # Upstream revision and attribution: ../../runtimes/qwen38/NOTICE.md. -# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json -apiVersion: nemoclaw.nvidia.com/v1alpha1 +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha2.schema.json +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: spark-inline-recipe diff --git a/examples/spark/two-models.yaml b/examples/spark/two-models.yaml index 38fe9509590..9ed2dc6d5d9 100644 --- a/examples/spark/two-models.yaml +++ b/examples/spark/two-models.yaml @@ -1,9 +1,9 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha2.schema.json # Build current images and replace these local digests and the deployment UID. # Model sources, host requirements, and validation limits: README.md. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: spark-two-models diff --git a/examples/spark/vllm.yaml b/examples/spark/vllm.yaml index b1e1c2218da..eddb76f3cc0 100644 --- a/examples/spark/vllm.yaml +++ b/examples/spark/vllm.yaml @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json -apiVersion: nemoclaw.nvidia.com/v1alpha1 +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha2.schema.json +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: qwen3-selected-model diff --git a/examples/station/shared-model.yaml b/examples/station/shared-model.yaml index a0e07eb0bec..61a084f1579 100644 --- a/examples/station/shared-model.yaml +++ b/examples/station/shared-model.yaml @@ -1,9 +1,9 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha2.schema.json # Build current images and replace these local digests and the deployment UID. # Hardware, model, and validation limits: README.md. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: dgx-station-qwen3-openclaw-pi diff --git a/examples/station/vllm.yaml b/examples/station/vllm.yaml index b6884d7cd7d..85a787a83cd 100644 --- a/examples/station/vllm.yaml +++ b/examples/station/vllm.yaml @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json -apiVersion: nemoclaw.nvidia.com/v1alpha1 +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha2.schema.json +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: dgx-station-qwen3-openclaw diff --git a/examples/tavily-web-search.yaml b/examples/tavily-web-search.yaml index 97f346a6f83..1fac2b0f291 100644 --- a/examples/tavily-web-search.yaml +++ b/examples/tavily-web-search.yaml @@ -1,10 +1,10 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha1.schema.json +# yaml-language-server: $schema=../schemas/nemoclaw-v1alpha2.schema.json # Set your own deployment UID, image digests, endpoints, and model before applying. # See docs/agents.md#tavily-web-search. -apiVersion: nemoclaw.nvidia.com/v1alpha1 +apiVersion: nemoclaw.nvidia.com/v1alpha2 kind: NemoClawConfig metadata: name: tavily-web-search diff --git a/schemas/nemoclaw-v1alpha1.schema.json b/schemas/nemoclaw-v1alpha2.schema.json similarity index 99% rename from schemas/nemoclaw-v1alpha1.schema.json rename to schemas/nemoclaw-v1alpha2.schema.json index 4b94f812689..55ae03b2def 100644 --- a/schemas/nemoclaw-v1alpha1.schema.json +++ b/schemas/nemoclaw-v1alpha2.schema.json @@ -3593,7 +3593,7 @@ "type": "object" } }, - "$id": "urn:nemoclaw:config:v1alpha1", + "$id": "urn:nemoclaw:config:v1alpha2", "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, "allOf": [ @@ -3734,7 +3734,7 @@ "description": "Desired configuration for one deployment. Fields describe authored input before SDK normalization.", "properties": { "apiVersion": { - "const": "nemoclaw.nvidia.com/v1alpha1", + "const": "nemoclaw.nvidia.com/v1alpha2", "description": "Configuration API version understood by this SDK.", "type": "string" }, @@ -3758,7 +3758,7 @@ "metadata", "spec" ], - "title": "NemoClaw configuration (v1alpha1)", + "title": "NemoClaw configuration (v1alpha2)", "type": "object", "x-nemoclaw-parser-checks": [ "Document::parse rejects YAML aliases, anchors, merge keys, all explicit tags (including core tags such as !!binary), duplicate keys, multiple documents, and input larger than 1 MiB. It applies the compiled input schema before defaulting; Document::validate applies the normalized schema and semantic checks, including for directly constructed Rust values.", From 436dfeb10489137c8b1d6bbad1ab20cfefb7b90d Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Tue, 13 Oct 2026 22:38:57 +0000 Subject: [PATCH 7/9] test(config): retarget each example to each gateway target #13080 asks for a test that retargets every example to every backend and compares the required edits with a documented list. The test rewrites the gateway of all 44 examples for managed and external Docker, Podman, and Kubernetes targets, applies the documented edit for each schema or parser violation until the document parses, and requires the applied edits to match a rule table derived from the example's features. The documented edits are: for Kubernetes, an explicit sandbox image reference and image metadata, and external endpoints instead of managed services; for Docker or Podman, no image metadata; and explicit placement for managed services unless the gateway is managed Docker. docs/usage.md lists them. The test checks authoring portability only: a live deployment cannot change its target. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Hai Nguyen --- crates/nemoclaw-sdk/tests/main.rs | 2 + crates/nemoclaw-sdk/tests/retargeting.rs | 316 +++++++++++++++++++++++ docs/usage.md | 9 +- 3 files changed, 326 insertions(+), 1 deletion(-) create mode 100644 crates/nemoclaw-sdk/tests/retargeting.rs diff --git a/crates/nemoclaw-sdk/tests/main.rs b/crates/nemoclaw-sdk/tests/main.rs index e9c584b040d..791c9700ec2 100644 --- a/crates/nemoclaw-sdk/tests/main.rs +++ b/crates/nemoclaw-sdk/tests/main.rs @@ -157,6 +157,8 @@ mod reference_diagnostics; mod refresh; #[path = "resource_management.rs"] mod resource_management; +#[path = "retargeting.rs"] +mod retargeting; #[path = "runtime_boundaries.rs"] mod runtime_boundaries; #[path = "runtime_compile.rs"] diff --git a/crates/nemoclaw-sdk/tests/retargeting.rs b/crates/nemoclaw-sdk/tests/retargeting.rs new file mode 100644 index 00000000000..42e712b4c53 --- /dev/null +++ b/crates/nemoclaw-sdk/tests/retargeting.rs @@ -0,0 +1,316 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +//! Re-authoring each example for each gateway target needs exactly the edits +//! that docs/usage.md lists. This covers authored documents only: state binds +//! a deployment's target, so a live deployment never moves. + +use crate::examples; +use nemoclaw_sdk::config::{Document, schema::input_schema}; +use serde_json::{Value, json}; +use std::collections::BTreeSet; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Target { + ManagedDocker, + ManagedPodman, + ManagedKubernetes, + ExternalDocker, + ExternalPodman, + ExternalKubernetes, +} + +impl Target { + const ALL: [Self; 6] = [ + Self::ManagedDocker, + Self::ManagedPodman, + Self::ManagedKubernetes, + Self::ExternalDocker, + Self::ExternalPodman, + Self::ExternalKubernetes, + ]; + + /// A gateway of this kind with only the target's required fields. + fn gateway(self) -> Value { + const DOCKER: &str = "unix:///var/run/docker.sock"; + const PODMAN: &str = "unix:///run/user/1000/podman/podman.sock"; + let managed = |target| json!({"management": "managed", "target": target}); + let external = |target| { + json!({ + "management": "external", + "endpoint": "https://openshell.example.com", + "target": target + }) + }; + match self { + Self::ManagedDocker => managed(json!({"docker": {}})), + Self::ManagedPodman => managed(json!({"podman": {"engine": PODMAN}})), + Self::ManagedKubernetes => managed(json!({"kubernetes": { + "endpoint": "https://127.0.0.1:17690", + "kubeconfig": {"env": "CLUSTER_KUBECONFIG"}, + "context": "cluster", + "namespace": "agents", + "authentication": {"profile": "development"} + }})), + Self::ExternalDocker => external(json!({"docker": {"engine": DOCKER}})), + Self::ExternalPodman => external(json!({"podman": {"engine": PODMAN}})), + Self::ExternalKubernetes => external(json!({"kubernetes": {}})), + } + } + + fn kubernetes(self) -> bool { + matches!(self, Self::ManagedKubernetes | Self::ExternalKubernetes) + } +} + +/// The edits docs/usage.md lists for moving a document to another target. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum Edit { + /// Kubernetes: no engine supplies a default image, so each sandbox names + /// its `image.ref`. + SetImageRef, + /// Kubernetes: `image.metadata` stands in for engine image inspection. + AddImageMetadata, + /// Kubernetes: no managed services, so each `serviceRef` provider uses an + /// external endpoint instead. + ReplaceServices, + /// Docker and Podman: the engine inspects the image instead. + RemoveImageMetadata, + /// Other than managed Docker: each Ollama and vLLM service needs explicit + /// `placement` and `publication`, since only a managed Docker gateway + /// lends its engine and network to services. An `ollamaProxy` service + /// needs an explicit `engine` instead; no example declares one. + PlaceServices, +} + +/// The edits that resolve each violation a retargeted example reports. A +/// schema violation is its field, with map keys as `*`, and keyword; the +/// others are semantic messages. +const RESOLUTIONS: &[(&str, &[Edit])] = &[ + ( + "/spec/sandboxes/*/image: required", + &[Edit::SetImageRef, Edit::AddImageMetadata], + ), + ( + "/spec/sandboxes/*/image/metadata: required", + &[Edit::AddImageMetadata], + ), + ("/spec/sandboxes/*/image: not", &[Edit::RemoveImageMetadata]), + ("/spec/services: maxProperties", &[Edit::ReplaceServices]), + ( + "Ollama requires the managed gateway Docker engine or explicit placement", + &[Edit::PlaceServices], + ), + ( + "vLLM requires the managed gateway Docker engine or explicit placement", + &[Edit::PlaceServices], + ), +]; + +/// The edits moving `example` to `target` needs, predicted from its features. +fn predicted(example: &Value, target: Target) -> BTreeSet { + let sandboxes = values(&example["spec"]["sandboxes"]); + let services = values(&example["spec"]["services"]); + let named = |sandbox: &&Value| has_image_ref(sandbox); + let described = |sandbox: &&Value| sandbox["image"].get("metadata").is_some(); + let placed = |service: &&Value| service.get("placement").is_some(); + let cluster = target.kubernetes(); + [ + (Edit::SetImageRef, cluster && !sandboxes.iter().all(named)), + ( + Edit::AddImageMetadata, + cluster && !sandboxes.iter().all(described), + ), + (Edit::ReplaceServices, cluster && !services.is_empty()), + ( + Edit::RemoveImageMetadata, + !cluster && sandboxes.iter().any(described), + ), + ( + Edit::PlaceServices, + !cluster && target != Target::ManagedDocker && !services.iter().all(placed), + ), + ] + .into_iter() + .filter_map(|(edit, needed)| needed.then_some(edit)) + .collect() +} + +#[test] +fn retargeting_each_example_needs_only_the_documented_edits() { + let validator = jsonschema::validator_for(&input_schema()).unwrap(); + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let paths = examples::yaml_files(&root.join("examples")); + assert!(!paths.is_empty()); + let mut failures = Vec::new(); + for path in paths { + let text = std::fs::read_to_string(&path).unwrap(); + let example: Value = serde_saphyr::from_str(&text).unwrap(); + let defaulted = serde_json::to_value(Document::parse(text.as_bytes()).unwrap()).unwrap(); + let name = path.strip_prefix(&root).unwrap().display(); + for target in Target::ALL { + let expected = predicted(&example, target); + match required_edits(&validator, &example, &defaulted, target) { + Ok(edits) if edits == expected => {} + Ok(edits) => failures.push(format!( + "{name} to {target:?} needs {edits:?}; the rule table predicts {expected:?}" + )), + Err(violation) => failures.push(format!("{name} to {target:?}: {violation}")), + } + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} + +/// Retarget `example`, then apply the documented edit for each violation +/// until it parses. Returns the edits applied, or a violation that no edit +/// resolves. +fn required_edits( + validator: &jsonschema::Validator, + example: &Value, + defaulted: &Value, + target: Target, +) -> Result, String> { + let mut document = example.clone(); + document["spec"]["gateway"] = target.gateway(); + let mut applied = BTreeSet::new(); + loop { + let violations = violations(validator, &document); + if violations.is_empty() { + return Ok(applied); + } + let mut round = BTreeSet::new(); + for (class, violation) in violations { + let (_, edits) = RESOLUTIONS + .iter() + .find(|(known, _)| *known == class) + .ok_or_else(|| format!("no documented edit resolves {violation}"))?; + if let Some(edit) = edits.iter().find(|edit| applied.contains(*edit)) { + return Err(format!("{edit:?} did not resolve {violation}")); + } + round.extend(edits.iter().copied()); + } + for edit in &round { + edit.apply(&mut document, defaulted); + } + applied.extend(round); + } +} + +/// Every schema violation, or else the first semantic one, each as its +/// class in `RESOLUTIONS` and as reported. +fn violations(validator: &jsonschema::Validator, document: &Value) -> Vec<(String, String)> { + let schema: Vec<_> = validator + .iter_errors(document) + .map(|error| { + let mut path = error.instance_path().as_str().to_owned(); + if let jsonschema::error::ValidationErrorKind::Required { property } = error.kind() { + path = format!("{path}/{}", property.as_str().unwrap()); + } + let keyword = error.kind().keyword(); + ( + format!("{}: {keyword}", any_key(&path)), + format!("{path}: {keyword}"), + ) + }) + .collect(); + if !schema.is_empty() { + return schema; + } + match Document::parse(document.to_string().as_bytes()) { + Ok(_) => Vec::new(), + Err(error) => vec![(error.to_string(), error.to_string())], + } +} + +/// `pointer` with each sandbox, service, and inference provider key as `*`. +fn any_key(pointer: &str) -> String { + let mut map = false; + pointer + .split('/') + .map(|segment| { + let key = std::mem::replace( + &mut map, + matches!(segment, "sandboxes" | "services" | "inferenceProviders"), + ); + if key { "*" } else { segment } + }) + .collect::>() + .join("/") +} + +impl Edit { + fn apply(self, document: &mut Value, defaulted: &Value) { + let spec = &mut document["spec"]; + match self { + Self::SetImageRef => { + for sandbox in values_mut(&mut spec["sandboxes"]) { + if !has_image_ref(sandbox) { + sandbox["image"]["ref"] = json!(format!( + "registry.example.com/nemoclaw/openclaw@sha256:{}", + "0".repeat(64) + )); + } + } + } + Self::AddImageMetadata => { + for sandbox in values_mut(&mut spec["sandboxes"]) { + sandbox["image"]["metadata"] = json!({"env": "NEMOCLAW_AGENT_IMAGE_METADATA"}); + } + } + Self::ReplaceServices => { + spec.as_object_mut().unwrap().remove("services"); + use_external_endpoints(spec); + } + Self::RemoveImageMetadata => { + for sandbox in values_mut(&mut spec["sandboxes"]) { + sandbox["image"].as_object_mut().unwrap().remove("metadata"); + } + } + Self::PlaceServices => { + for (name, service) in spec["services"].as_object_mut().unwrap() { + if service.get("placement").is_some() { + continue; + } + let port = &defaulted["spec"]["services"][name]["serving"]["port"]; + service["placement"] = + json!({"engine": "ssh://gpu-box", "networkCidr": "172.30.119.0/24"}); + service["publication"] = json!({ + "endpoint": format!("http://10.0.0.8:{port}/v1"), + "bindAddress": "10.0.0.8" + }); + } + } + } + } +} + +/// Points each provider that names a service at an external endpoint. +fn use_external_endpoints(value: &mut Value) { + match value { + Value::Object(object) => { + if object.remove("serviceRef").is_some() { + object.insert("endpoint".into(), json!("https://inference.example.com/v1")); + } + object.values_mut().for_each(use_external_endpoints); + } + Value::Array(items) => items.iter_mut().for_each(use_external_endpoints), + _ => {} + } +} + +/// The schema already requires an authored `image.ref` to be pinned by digest. +fn has_image_ref(sandbox: &Value) -> bool { + sandbox["image"]["ref"] + .as_str() + .is_some_and(|image| !image.is_empty()) +} + +fn values(map: &Value) -> Vec<&Value> { + map.as_object() + .map(|map| map.values().collect()) + .unwrap_or_default() +} + +fn values_mut(map: &mut Value) -> impl Iterator { + map.as_object_mut().unwrap().values_mut() +} diff --git a/docs/usage.md b/docs/usage.md index 08c58f48dc7..dbe9bca77ba 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -82,7 +82,14 @@ An existing deployment cannot move to another target. For a managed gateway, deployment state binds the target key and every setting under it except `imagePullPolicy`: the endpoint, engine, `networkCidr`, distribution, and cluster settings. For an external gateway, it binds `endpoint`. To change a bound setting, create a separate deployment with a fresh `metadata.uid` and state directory. -To re-author a document for another target, fill in the new key's required fields; for `kubernetes`, give each sandbox an explicit `image.ref` and `image.metadata` and replace `spec.services` with external inference endpoints; for `docker` or `podman`, remove `image.metadata`. + +To move a document to another target, rewrite `spec.gateway` for that target, make the edits below, and apply the result as a separate deployment: + +| New target | Edits | +| --- | --- | +| `kubernetes`, managed or external | Give each sandbox an explicit `image.ref` and an `image.metadata` bundle ([Prepare Agent Images](kubernetes.md#prepare-agent-images)). Remove `spec.services`, and replace each `serviceRef` with an inference `endpoint` reachable from the cluster. | +| `docker` or `podman`, managed or external | Remove each sandbox's `image.metadata`; the engine inspects the image instead. | +| Managed `podman`, external `docker`, or external `podman` | Also give each `ollama` and `vllm` service explicit `placement` and `publication` ([SSH placement](remote-service.md)) and each `ollamaProxy` service an explicit `engine`, since only a managed `docker` gateway runs services on its own engine. | The SDK pins the gateway image, and the document does not name it. A Docker or Podman gateway stays bound to the image pin of the bundle that created it, and a managed Kubernetes gateway to that bundle's gateway chart pin: keep operating it with that bundle, or create a separate deployment to use a bundle with a different pin. From fe83ba3bdbf8db2d2f0683e7183af238639bb4a0 Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Tue, 13 Oct 2026 23:20:49 +0000 Subject: [PATCH 8/9] fix(config): address final review of the v1alpha2 reshape - Reject provider keys and inline provider names outside the name pattern again, and truncate registration-key prefixes by character, so a Rust-built document with a non-ASCII provider name returns an error instead of panicking. - Report an intent record without an integer version as corrupt, and point the earlier-state message to the migration guide. - Test that a bound managed gateway refuses another target key, distribution, network, context, namespace, or endpoint, and accepts a pull-policy change. - Retarget examples to managed OpenShift as well, and require an explicit engine, not placement, for an Ollama proxy. - Share one rule for which map keys are names between schema diagnostics and onboarding, and one masking and JSON-pointer helper set in authoring. - Carry removed-field hints as ordered pairs, and correct the release notes, migration example, and troubleshooting paths. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Hai Nguyen --- crates/nemoclaw-authoring/src/deployment.rs | 8 +- .../src/journey_definition.rs | 17 ++- .../nemoclaw-authoring/src/journey_state.rs | 15 +-- .../src/journey_state/authored_values.rs | 16 +-- .../resolver/native_questions.rs | 2 +- crates/nemoclaw-authoring/src/lib.rs | 2 +- .../src/partial_document.rs | 12 +- crates/nemoclaw-authoring/src/pointer.rs | 93 ++++++++++----- crates/nemoclaw-authoring/src/sdk_schema.rs | 12 +- crates/nemoclaw-authoring/src/settings.rs | 12 +- crates/nemoclaw-authoring/tests/support.rs | 24 +++- crates/nemoclaw-e2e/tests/deployment.rs | 7 +- crates/nemoclaw-onboarding/src/lib.rs | 30 ++++- crates/nemoclaw-onboarding/src/tui/app.rs | 6 +- crates/nemoclaw-onboarding/src/tui/labels.rs | 25 +--- crates/nemoclaw-onboarding/src/tui/view.rs | 8 +- crates/nemoclaw-sdk/src/compile_runtime.rs | 7 +- .../nemoclaw-sdk/src/config/integrations.rs | 15 ++- crates/nemoclaw-sdk/src/config/mod.rs | 43 ++++--- crates/nemoclaw-sdk/src/config/providers.rs | 20 +++- crates/nemoclaw-sdk/src/config/schema.rs | 2 + .../nemoclaw-sdk/src/config/schema/runtime.rs | 93 +++++++-------- .../src/config/schema/validation.rs | 72 ++++++++---- crates/nemoclaw-sdk/src/config/validation.rs | 13 ++- .../src/deployment/runtime/tests.rs | 82 +++++++++++++ crates/nemoclaw-sdk/src/deployment/tests.rs | 11 +- crates/nemoclaw-sdk/src/managed/settings.rs | 9 +- crates/nemoclaw-sdk/src/state/mod.rs | 17 ++- crates/nemoclaw-sdk/src/state/tests.rs | 29 ++++- .../nemoclaw-sdk/tests/provider_references.rs | 40 +++++++ crates/nemoclaw-sdk/tests/retargeting.rs | 106 +++++++++++++---- docs/contributing/configuration-schema.md | 2 +- docs/migration.md | 10 +- docs/release-notes.md | 34 +++--- docs/troubleshooting.md | 1 + schemas/nemoclaw-v1alpha2.schema.json | 108 +++++++++++++----- 36 files changed, 696 insertions(+), 307 deletions(-) diff --git a/crates/nemoclaw-authoring/src/deployment.rs b/crates/nemoclaw-authoring/src/deployment.rs index d192e7dca10..640768b3a28 100644 --- a/crates/nemoclaw-authoring/src/deployment.rs +++ b/crates/nemoclaw-authoring/src/deployment.rs @@ -7,11 +7,10 @@ use crate::{ Diagnostics, diagnostics::diagnostic, journey_definition::sandbox_path, - pointer::{escape, replace_entry_keys}, + pointer::{escape, mask_entry_keys, replace_entry_keys}, sdk_schema::{finite_choices, sdk_field_schema_for}, settings::SettingQuestion, }; -use nemoclaw_sdk::config::valid_name; use serde_json::Value; pub(crate) fn deployment_questions_for_values( @@ -162,10 +161,7 @@ fn title(path: &str) -> String { } result } - // A key the SDK rejects as a name is not shown. - let path = replace_entry_keys(path, |key| { - if valid_name(key) { key } else { "[entry]" }.to_owned() - }); + let path = mask_entry_keys(path); let parts: Vec<_> = path.split('/').filter(|part| !part.is_empty()).collect(); let (prefix, rest) = if parts.get(1) == Some(&"gateway") { ("Gateway".to_owned(), &parts[2..]) diff --git a/crates/nemoclaw-authoring/src/journey_definition.rs b/crates/nemoclaw-authoring/src/journey_definition.rs index 3ab9a082ce7..63aeff4c8bd 100644 --- a/crates/nemoclaw-authoring/src/journey_definition.rs +++ b/crates/nemoclaw-authoring/src/journey_definition.rs @@ -10,11 +10,15 @@ use std::collections::BTreeSet; use crate::{ Capabilities, Diagnostics, PartialDocument, diagnostics::diagnostic, + pointer::entry_key, sdk_schema::{sdk_field_possible, sdk_field_schema_for}, }; pub(crate) const NAME: &str = "/metadata/name"; pub(crate) const INFERENCE_PRESET: &str = "inference:preset"; +/// The journey edits exactly one sandbox, which its key names. +pub(crate) const ONE_SANDBOX: &str = + "The v1 journey requires exactly one sandbox keyed by a lowercase name."; /// The pointer to the journey's only sandbox, `/spec/sandboxes/`, when /// `/spec/sandboxes` holds exactly one object and its key is a valid name. @@ -161,10 +165,7 @@ impl JourneyDefinition { /// Start mutable resolution over the sparse v1 single-sandbox envelope. pub fn start(&self, capabilities: &Capabilities) -> Result { if sandbox_path(self.base.supplied()).is_none() { - return Err(diagnostic( - "journey", - "The v1 journey requires exactly one sandbox keyed by a lowercase name.", - )); + return Err(diagnostic("journey", ONE_SANDBOX)); } self.validate_guidance(capabilities)?; crate::JourneyState::new(self.clone()) @@ -202,11 +203,7 @@ impl JourneyDefinition { } // A field of another sandbox or of an absent provider would add // that entry when answered. - let entry = |collection: &str| { - let rest = field.strip_prefix(collection)?.strip_prefix('/')?; - Some(rest.split_once('/').map_or(rest, |(key, _)| key)) - }; - if let Some(key) = entry("/spec/sandboxes") + if let Some(key) = entry_key(field, "/spec/sandboxes") && sandbox.as_ref() != Some(&format!("/spec/sandboxes/{key}")) { return Err(diagnostic( @@ -214,7 +211,7 @@ impl JourneyDefinition { "asked fields must belong to the journey's sandbox", )); } - if let Some(key) = entry("/spec/inferenceProviders") + if let Some(key) = entry_key(field, "/spec/inferenceProviders") && supplied .pointer(&format!("/spec/inferenceProviders/{key}")) .is_none() diff --git a/crates/nemoclaw-authoring/src/journey_state.rs b/crates/nemoclaw-authoring/src/journey_state.rs index ebabc616d27..ffa2157354c 100644 --- a/crates/nemoclaw-authoring/src/journey_state.rs +++ b/crates/nemoclaw-authoring/src/journey_state.rs @@ -20,10 +20,10 @@ use crate::{ diagnostics::diagnostic, identity::new_deployment_uid, journey_definition::{ - INFERENCE_PRESET, JourneyDefinition, JourneyScope, NAME, adapter_field, adapter_schema, - harness_field, native_field, sandbox_path, + INFERENCE_PRESET, JourneyDefinition, JourneyScope, NAME, ONE_SANDBOX, adapter_field, + adapter_schema, harness_field, native_field, sandbox_path, }, - pointer::escape, + pointer::{entry_key, escape, unescape}, sdk_schema::{ finite_choices, sdk_discriminator, sdk_exclusive_required_fields, sdk_field_possible, sdk_field_schema, sdk_field_schema_for, sdk_selected_branch, sdk_variant_key, @@ -124,11 +124,12 @@ fn provider_path(name: &str) -> String { /// The key of a deployment provider and the field that `path` names inside /// it, for `/spec/inferenceProviders//`. fn provider_field(path: &str) -> Option<(String, &str)> { - let (key, field) = path + let key = entry_key(path, "/spec/inferenceProviders")?; + let field = path .strip_prefix("/spec/inferenceProviders/")? - .split_once('/')?; - (!key.is_empty() && !field.contains('/')) - .then(|| (key.replace("~1", "/").replace("~0", "~"), field)) + .strip_prefix(key)? + .strip_prefix('/')?; + (!key.is_empty() && !field.contains('/')).then(|| (unescape(key), field)) } /// One currently applicable decision in the bounded journey surface. diff --git a/crates/nemoclaw-authoring/src/journey_state/authored_values.rs b/crates/nemoclaw-authoring/src/journey_state/authored_values.rs index c1d81792d31..51732c0e4b4 100644 --- a/crates/nemoclaw-authoring/src/journey_state/authored_values.rs +++ b/crates/nemoclaw-authoring/src/journey_state/authored_values.rs @@ -75,8 +75,8 @@ impl AuthoredValues { { self.inactive_settings.insert(old.clone(), settings.clone()); } - let sandbox = sandbox_path(&self.values) - .ok_or_else(|| diagnostic("journey", "The v1 journey requires one sandbox object."))?; + let sandbox = + sandbox_path(&self.values).ok_or_else(|| diagnostic("journey", ONE_SANDBOX))?; let inline = format!("{sandbox}/harness"); let owner_path = harness_path(&self.values) .or_else(|| { @@ -91,9 +91,7 @@ impl AuthoredValues { self.values .pointer_mut(&sandbox) .and_then(Value::as_object_mut) - .ok_or_else(|| { - diagnostic("journey", "The v1 journey requires one sandbox object.") - })? + .ok_or_else(|| diagnostic("journey", ONE_SANDBOX))? .entry("harness") .or_insert_with(|| Value::Object(Map::new())) } else { @@ -182,14 +180,12 @@ impl AuthoredValues { let (parent, property) = pointer .rsplit_once('/') .ok_or_else(|| diagnostic("journey", "Invalid SDK field path."))?; - let property = property.replace("~1", "/").replace("~0", "~"); + let property = unescape(property); if value.is_none() && self.values.pointer(parent).is_none() { return Ok(()); } // The journey edits its one sandbox; a write never adds another. - let sandbox = pointer - .strip_prefix("/spec/sandboxes/") - .map(|rest| rest.split_once('/').map_or(rest, |(key, _)| key)); + let sandbox = entry_key(pointer, "/spec/sandboxes"); if value.is_some() && let Some(key) = sandbox && self @@ -204,7 +200,7 @@ impl AuthoredValues { } let mut current = &mut self.values; for segment in parent.split('/').skip(1) { - let key = segment.replace("~1", "/").replace("~0", "~"); + let key = unescape(segment); current = match current { Value::Array(items) => { let index = key diff --git a/crates/nemoclaw-authoring/src/journey_state/resolver/native_questions.rs b/crates/nemoclaw-authoring/src/journey_state/resolver/native_questions.rs index 82f21061505..fb9f75ca3f2 100644 --- a/crates/nemoclaw-authoring/src/journey_state/resolver/native_questions.rs +++ b/crates/nemoclaw-authoring/src/journey_state/resolver/native_questions.rs @@ -199,7 +199,7 @@ pub(super) fn native_questions_for_values( } if let (Some(schema), Some(document)) = (capabilities.model_schemas.get(harness_id), document) { let sandbox = crate::journey_definition::sole_sandbox(document) - .ok_or_else(|| diagnostic("journey", "The v1 journey requires one sandbox object."))?; + .ok_or_else(|| diagnostic("journey", crate::journey_definition::ONE_SANDBOX))?; let inference = document .sandbox_inference(sandbox) .map_err(|error| diagnostic("journey", &error.to_string()))?; diff --git a/crates/nemoclaw-authoring/src/lib.rs b/crates/nemoclaw-authoring/src/lib.rs index 2b70b50612e..f53165b3e25 100644 --- a/crates/nemoclaw-authoring/src/lib.rs +++ b/crates/nemoclaw-authoring/src/lib.rs @@ -35,7 +35,7 @@ pub use journey_state::{ JourneyState, }; pub use partial_document::{PartialAssessment, PartialDocument, PartialIssue, PartialIssueKind}; -pub use pointer::replace_entry_keys; +pub use pointer::{mask_entry_keys, replace_entry_keys}; pub use provider_presets::ProviderPreset; pub use target_assessment::{CompatibilityStatus, DiscoveryAssessment, assess_target}; diff --git a/crates/nemoclaw-authoring/src/partial_document.rs b/crates/nemoclaw-authoring/src/partial_document.rs index ca5e1bca634..f5c63239350 100644 --- a/crates/nemoclaw-authoring/src/partial_document.rs +++ b/crates/nemoclaw-authoring/src/partial_document.rs @@ -5,18 +5,14 @@ use std::sync::LazyLock; -use nemoclaw_sdk::config::{ - Document, parse_yaml_value, - schema::{input_schema, select_variant}, -}; +use nemoclaw_sdk::config::{Document, parse_yaml_value, schema::select_variant}; use serde_json::Value; -use crate::{Diagnostics, diagnostics::diagnostic, pointer::escape}; +use crate::{Diagnostics, diagnostics::diagnostic, pointer::escape, sdk_schema::schema_root}; use jsonschema::error::ValidationErrorKind as Kind; -static INPUT_SCHEMA: LazyLock = LazyLock::new(input_schema); static INPUT_VALIDATOR: LazyLock = LazyLock::new(|| { - jsonschema::validator_for(&INPUT_SCHEMA).expect("SDK input schema must compile") + jsonschema::validator_for(schema_root()).expect("SDK input schema must compile") }); /// Authored values before SDK defaults or required-field validation. @@ -97,7 +93,7 @@ impl PartialDocument { /// Inspect the current sparse input. Compound rules remain deferred until /// a partial evaluator can prove whether a branch is impossible or incomplete. pub fn assess(&self) -> PartialAssessment { - let issues = schema_issues(&INPUT_SCHEMA, &INPUT_VALIDATOR, &self.supplied); + let issues = schema_issues(schema_root(), &INPUT_VALIDATOR, &self.supplied); if !issues.is_empty() { return PartialAssessment { issues, diff --git a/crates/nemoclaw-authoring/src/pointer.rs b/crates/nemoclaw-authoring/src/pointer.rs index 8dbd784a8d9..4827f2825d9 100644 --- a/crates/nemoclaw-authoring/src/pointer.rs +++ b/crates/nemoclaw-authoring/src/pointer.rs @@ -3,44 +3,59 @@ //! JSON pointer segments, and the keys among them that name SDK definitions. +use nemoclaw_sdk::config::schema::entry_key_shown; + /// Escape `segment` for use as one JSON pointer segment. pub(crate) fn escape(segment: &str) -> String { segment.replace('~', "~0").replace('/', "~1") } +/// The text of one escaped JSON pointer segment. +pub(crate) fn unescape(segment: &str) -> String { + segment.replace("~1", "/").replace("~0", "~") +} + +/// The escaped key of the entry of `collection`, a pointer such as +/// `/spec/sandboxes`, that `pointer` addresses or lies inside. +pub(crate) fn entry_key<'a>(pointer: &'a str, collection: &str) -> Option<&'a str> { + let rest = pointer.strip_prefix(collection)?.strip_prefix('/')?; + Some(rest.split_once('/').map_or(rest, |(key, _)| key)) +} + +/// [`replace_entry_keys`], also telling `replace` whether SDK diagnostics +/// show the key. +fn map_entry_keys(pointer: &str, replace: impl Fn(&str, bool) -> String) -> String { + let parts = pointer.split('/').collect::>(); + let names = parts.iter().map(|part| unescape(part)).collect::>(); + let names = names.iter().map(String::as_str).collect::>(); + let mut mapped = vec![parts[0].to_owned()]; + for index in 1..parts.len() { + mapped.push(match entry_key_shown(&names[1..index], names[index]) { + Some(shown) => replace(parts[index], shown), + None => parts[index].to_owned(), + }); + } + mapped.join("/") +} + /// `pointer` with each segment that keys a named SDK definition replaced by /// `replace(segment)`. These keys name sandboxes and the providers, services, /// harnesses, inferences, and integrations of the deployment or of a sandbox; /// they are names only by position, so a name can equal a field name. A /// prefix before the pointer's first `/`, such as `form:`, is kept. +#[doc(hidden)] pub fn replace_entry_keys(pointer: &str, replace: impl Fn(&str) -> String) -> String { - let mut parts = pointer.split('/').map(str::to_owned).collect::>(); - for index in 1..parts.len() { - let before = parts[1..index] - .iter() - .map(String::as_str) - .collect::>(); - if matches!( - before.as_slice(), - [ - "spec", - "sandboxes" - | "inferenceProviders" - | "services" - | "harnesses" - | "inferences" - | "integrations" - ] | [ - "spec", - "sandboxes", - _, - "inferenceProviders" | "harnesses" | "inferences" | "integrations" - ] | ["spec", "sandboxes", _, "agent", "integrations"] - ) { - parts[index] = replace(&parts[index]); - } - } - parts.join("/") + map_entry_keys(pointer, |key, _| replace(key)) +} + +/// `pointer` for display, with each definition key that SDK diagnostics hide +/// read as `[entry]`, so rejected input is never shown. A sandbox, provider, +/// service, or other definition key is shown only when it, and the key of any +/// sandbox enclosing it, is a valid name. +pub fn mask_entry_keys(pointer: &str) -> String { + map_entry_keys(pointer, |key, shown| { + if shown { key } else { "[entry]" }.to_owned() + }) } #[cfg(test)] @@ -79,4 +94,28 @@ mod tests { assert_eq!(replace_entry_keys(pointer, star), expected, "{pointer}"); } } + + #[test] + fn masking_hides_the_definition_keys_that_sdk_diagnostics_hide() { + for (pointer, expected) in [ + ( + "/spec/sandboxes/assistant/inferenceProviders/own/endpoint", + "/spec/sandboxes/assistant/inferenceProviders/own/endpoint", + ), + ( + "/spec/inferenceProviders/Private Sentinel/endpoint", + "/spec/inferenceProviders/[entry]/endpoint", + ), + ( + "/spec/sandboxes/Private Sentinel/harnesses/shared/kind", + "/spec/sandboxes/[entry]/harnesses/[entry]/kind", + ), + ( + "form:/spec/services/a~1b/image", + "form:/spec/services/[entry]/image", + ), + ] { + assert_eq!(mask_entry_keys(pointer), expected, "{pointer}"); + } + } } diff --git a/crates/nemoclaw-authoring/src/sdk_schema.rs b/crates/nemoclaw-authoring/src/sdk_schema.rs index b7de6aecf18..50e8ce821b1 100644 --- a/crates/nemoclaw-authoring/src/sdk_schema.rs +++ b/crates/nemoclaw-authoring/src/sdk_schema.rs @@ -5,7 +5,7 @@ use std::sync::OnceLock; -use crate::fingerprint::sha256; +use crate::{fingerprint::sha256, pointer::unescape}; use nemoclaw_sdk::config::schema::{input_schema, select_variant, variant_keys}; use nemoclaw_sdk::json_schema::schema_accepts; use serde_json::{Value, json}; @@ -24,10 +24,7 @@ pub(crate) fn sdk_field_possible(path: &str) -> bool { let Some(path) = path.strip_prefix('/') else { return false; }; - let parts = path - .split('/') - .map(|part| part.replace("~1", "/").replace("~0", "~")) - .collect::>(); + let parts = path.split('/').map(unescape).collect::>(); possible_in_schema(schema_root(), schema_root(), &parts, 0) } @@ -67,7 +64,8 @@ fn possible_in_schema(root: &Value, schema: &Value, parts: &[String], depth: usi .any(|branch| possible_in_schema(root, branch, parts, depth + 1)) } -fn schema_root() -> &'static Value { +/// The SDK input schema, built once. +pub(crate) fn schema_root() -> &'static Value { static SCHEMA: OnceLock = OnceLock::new(); SCHEMA.get_or_init(input_schema) } @@ -98,7 +96,7 @@ fn field_schema_in(root: &Value, values: &Value, path: &str) -> Option<(Value, b let segments = path.strip_prefix('/')?.split('/').collect::>(); for (index, part) in segments.iter().enumerate() { node = follow_ref(root, node)?; - let name = part.replace("~1", "/").replace("~0", "~"); + let name = unescape(part); if let Some((discriminator, choices)) = sdk_discriminator(node) { if name == discriminator { if index + 1 != segments.len() { diff --git a/crates/nemoclaw-authoring/src/settings.rs b/crates/nemoclaw-authoring/src/settings.rs index 52060d790d1..c160b3bdb79 100644 --- a/crates/nemoclaw-authoring/src/settings.rs +++ b/crates/nemoclaw-authoring/src/settings.rs @@ -1,7 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use crate::{Diagnostics, diagnostics::diagnostic, pointer::escape}; +use crate::{ + Diagnostics, + diagnostics::diagnostic, + pointer::{escape, unescape}, +}; use nemoclaw_sdk::json_schema::schema_accepts; use serde_json::{Map, Value}; @@ -22,11 +26,7 @@ pub(crate) fn put(root: &mut Value, path: &str, value: Option) -> Result< return Ok(()); } - let parts: Vec<_> = path - .split('/') - .skip(1) - .map(|part| part.replace("~1", "/").replace("~0", "~")) - .collect(); + let parts: Vec<_> = path.split('/').skip(1).map(unescape).collect(); let mut current = root; for part in &parts[..parts.len().saturating_sub(1)] { current = current diff --git a/crates/nemoclaw-authoring/tests/support.rs b/crates/nemoclaw-authoring/tests/support.rs index 3bd0109d5b4..4a0ec2d5a81 100644 --- a/crates/nemoclaw-authoring/tests/support.rs +++ b/crates/nemoclaw-authoring/tests/support.rs @@ -3,7 +3,10 @@ //! Helpers shared by the authoring tests. use nemoclaw_sdk::discovery::DiscoveryObservations; use nemoclaw_sdk::{ - config::{ComputeDriver, Document}, + config::{ + ComputeDriver, Document, ExternalGateway, ExternalTarget, Gateway, KubernetesDistribution, + ManagedGateway, ManagedTarget, + }, discovery::{ DiscoveryObservation, DiscoveryQuery, DiscoveryRequest, EngineObservation, FabricObservation, ObservationStatus, plan_queries, @@ -24,9 +27,24 @@ pub fn target(document: &Document) -> Target { let [sandbox] = document.spec.sandboxes.values().collect::>()[..] else { panic!("the document has one sandbox"); }; + let (engine, compute_driver) = match &document.spec.gateway { + Gateway::Managed(ManagedGateway { target }) => match target { + ManagedTarget::Docker(docker) => (docker.engine.as_str(), ComputeDriver::Docker), + ManagedTarget::Podman(podman) => (podman.engine.as_str(), ComputeDriver::Podman), + ManagedTarget::Kubernetes(cluster) => match cluster.distribution { + KubernetesDistribution::Kubernetes => ("", ComputeDriver::Kubernetes), + KubernetesDistribution::OpenShift => ("", ComputeDriver::OpenShift), + }, + }, + Gateway::External(ExternalGateway { target, .. }) => match target { + ExternalTarget::Docker(docker) => (docker.engine.as_str(), ComputeDriver::Docker), + ExternalTarget::Podman(podman) => (podman.engine.as_str(), ComputeDriver::Podman), + ExternalTarget::Kubernetes(_) => ("", ComputeDriver::Kubernetes), + }, + }; Target { - engine: document.spec.gateway.image_engine().to_owned(), - compute_driver: document.spec.gateway.compute_driver(), + engine: engine.to_owned(), + compute_driver, image: sandbox.image.ref_.clone(), } } diff --git a/crates/nemoclaw-e2e/tests/deployment.rs b/crates/nemoclaw-e2e/tests/deployment.rs index 6980b2b9a21..fd3c4d5cc12 100644 --- a/crates/nemoclaw-e2e/tests/deployment.rs +++ b/crates/nemoclaw-e2e/tests/deployment.rs @@ -623,9 +623,10 @@ impl Lifecycle { /// A search profile without endpoints, or a sandbox without its provider /// attachments, stops plan and export until the gateway is restored. async fn assert_search_registration_drift(&self) { - let (name, sandbox) = self.document.spec.sandboxes.first_key_value().unwrap(); - let search_provider = sandbox - .integration_bindings(name, &self.document.spec.integrations) + let (name, _) = self.document.spec.sandboxes.first_key_value().unwrap(); + let search_provider = self + .document + .sandbox_integration_bindings(name) .unwrap() .first() .map(|binding| match binding.definition { diff --git a/crates/nemoclaw-onboarding/src/lib.rs b/crates/nemoclaw-onboarding/src/lib.rs index fcb7a156c70..a8d6e8945f7 100644 --- a/crates/nemoclaw-onboarding/src/lib.rs +++ b/crates/nemoclaw-onboarding/src/lib.rs @@ -113,6 +113,9 @@ fn write_path(path: &Path, bytes: &[u8]) -> std::io::Result<()> { mod tests { use super::*; + const ONE_SANDBOX: &str = + "journey: The v1 journey requires exactly one sandbox keyed by a lowercase name."; + #[test] fn default_source_starts_a_sparse_journey_with_existing_questions() { let capabilities = Capabilities::available(); @@ -172,10 +175,30 @@ mod tests { values["spec"]["sandboxes"]["second"] = values["spec"]["sandboxes"]["assistant"].clone(); let yaml = serde_json::to_vec(&values).unwrap(); std::fs::write(&path, &yaml).unwrap(); - assert!(load_journey(Source::Template(&path), &Capabilities::available()).is_err()); + let error = load_journey(Source::Template(&path), &Capabilities::available()) + .err() + .unwrap() + .to_string(); + assert_eq!(error, ONE_SANDBOX); assert_eq!(std::fs::read(path).unwrap(), yaml); } + #[test] + fn a_template_without_a_sandbox_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("template.yaml"); + let mut values: serde_json::Value = + serde_saphyr::from_slice(include_bytes!("../../../examples/onboarding/openclaw.yaml")) + .unwrap(); + values["spec"]["sandboxes"] = serde_json::json!({}); + std::fs::write(&path, serde_json::to_vec(&values).unwrap()).unwrap(); + let error = load_journey(Source::Template(&path), &Capabilities::available()) + .err() + .unwrap() + .to_string(); + assert_eq!(error, ONE_SANDBOX); + } + #[test] fn a_template_sandbox_key_that_is_not_a_name_is_rejected_without_echoing_it() { let directory = tempfile::tempdir().unwrap(); @@ -191,10 +214,7 @@ mod tests { .err() .unwrap() .to_string(); - assert_eq!( - error, - "journey: The v1 journey requires exactly one sandbox keyed by a lowercase name." - ); + assert_eq!(error, ONE_SANDBOX); } #[test] diff --git a/crates/nemoclaw-onboarding/src/tui/app.rs b/crates/nemoclaw-onboarding/src/tui/app.rs index 29ab4b15ddd..cb7d9d0e092 100644 --- a/crates/nemoclaw-onboarding/src/tui/app.rs +++ b/crates/nemoclaw-onboarding/src/tui/app.rs @@ -1,9 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use super::labels::{display_value, pointer_text}; +use super::labels::display_value; use nemoclaw_authoring::{ - Capabilities, Diagnostics, JourneyQuestion, JourneyResolution, JourneyState, + Capabilities, Diagnostics, JourneyQuestion, JourneyResolution, JourneyState, mask_entry_keys, }; use nemoclaw_sdk::discovery::DiscoveryObservations; use nemoclaw_sdk::{config::Document, discovery::DiscoveryRequest}; @@ -290,7 +290,7 @@ impl JourneyWizard { .assessment() .issues() .iter() - .map(|issue| format!("{}: {}", pointer_text(issue.path()), issue.rule())) + .map(|issue| format!("{}: {}", mask_entry_keys(issue.path()), issue.rule())) .collect::>(); self.error = Some(format!( "Cannot save yet: {} {} {}", diff --git a/crates/nemoclaw-onboarding/src/tui/labels.rs b/crates/nemoclaw-onboarding/src/tui/labels.rs index 92d3a385617..d0441c115ff 100644 --- a/crates/nemoclaw-onboarding/src/tui/labels.rs +++ b/crates/nemoclaw-onboarding/src/tui/labels.rs @@ -2,9 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 use nemoclaw_authoring::{ - JourneyQuestion, JourneyQuestionKind, ProviderPreset, replace_entry_keys, + JourneyQuestion, JourneyQuestionKind, ProviderPreset, mask_entry_keys, replace_entry_keys, }; -use nemoclaw_sdk::config::valid_name; use serde::Deserialize; use serde_json::Value; use std::{collections::BTreeMap, sync::OnceLock}; @@ -143,18 +142,9 @@ pub(super) fn label(question: &JourneyQuestion) -> String { readable(id) } -/// A question ID or document pointer for display: a sandbox, provider, -/// service, or other definition key that is not a valid name reads as -/// `[entry]`, as in SDK diagnostics, so rejected input is never shown. -pub(super) fn pointer_text(pointer: &str) -> String { - replace_entry_keys(pointer, |key| { - if valid_name(key) { key } else { "[entry]" }.to_owned() - }) -} - /// `adapter:x:/interfaces/dashboard/port` reads as "Dashboard: port". fn readable(id: &str) -> String { - let id = pointer_text(id); + let id = mask_entry_keys(id); let pointer = id .rsplit_once(':') .map_or(id.as_str(), |(_, pointer)| pointer); @@ -225,13 +215,10 @@ fn words(part: &str) -> String { } /// The managed service a question belongs to, shown under its title. -pub(super) fn service(question: &JourneyQuestion) -> Option<&str> { - let name = question - .id() - .strip_prefix("/spec/services/")? - .split('/') - .next()?; - Some(if valid_name(name) { name } else { "[entry]" }) +pub(super) fn service(question: &JourneyQuestion) -> Option { + let id = mask_entry_keys(question.id()); + let name = id.strip_prefix("/spec/services/")?.split('/').next()?; + Some(name.to_owned()) } // External labels stay unchanged in authored values; escape them only for the terminal. diff --git a/crates/nemoclaw-onboarding/src/tui/view.rs b/crates/nemoclaw-onboarding/src/tui/view.rs index b2577dab761..41a27d81278 100644 --- a/crates/nemoclaw-onboarding/src/tui/view.rs +++ b/crates/nemoclaw-onboarding/src/tui/view.rs @@ -6,7 +6,7 @@ use super::{ labels::{self, terminal_text}, logo::BrandImage, }; -use nemoclaw_authoring::JourneyQuestion; +use nemoclaw_authoring::{JourneyQuestion, mask_entry_keys}; use ratatui::{ Frame, layout::{Constraint, Layout, Rect}, @@ -139,7 +139,7 @@ impl JourneyWizard { let mut lines = vec![Line::from(title)]; if let Some(service) = labels::service(question) { lines.push(Line::from(Span::styled( - format!("Service: {}", terminal_text(service)), + format!("Service: {}", terminal_text(&service)), Style::new().fg(MUTED), ))); } @@ -158,7 +158,7 @@ impl JourneyWizard { } else { "Optional" }, - terminal_text(&labels::pointer_text(question.id())) + terminal_text(&mask_entry_keys(question.id())) ), Style::new().fg(DIM), ))); @@ -246,7 +246,7 @@ impl JourneyWizard { Line::from(Span::styled( terminal_text(&format!( "{}: {}", - labels::pointer_text(issue.path()), + mask_entry_keys(issue.path()), issue.rule() )), Style::new().fg(WARNING), diff --git a/crates/nemoclaw-sdk/src/compile_runtime.rs b/crates/nemoclaw-sdk/src/compile_runtime.rs index 2c31ede8f90..b523352683c 100644 --- a/crates/nemoclaw-sdk/src/compile_runtime.rs +++ b/crates/nemoclaw-sdk/src/compile_runtime.rs @@ -76,10 +76,7 @@ fn runtime_targets_with_plans( }); return Ok(targets); } - let (Some(settings), Some(local)) = ( - document.spec.gateway.as_managed(), - document.spec.gateway.as_local_managed(), - ) else { + let Some(local) = document.spec.gateway.as_local_managed() else { return Ok(service_plans.targets().cloned().collect()); }; let gateway = Spec { @@ -89,7 +86,7 @@ fn runtime_targets_with_plans( name: format!("{}-gateway", document.workspace()), owner: document.metadata.uid.clone(), generation: generation(generations, GATEWAY_KIND)?.into(), - gateway: settings.runtime_settings(), + gateway: local.runtime_settings(), process: None, }; // The listen port changes Docker compute, not initialized data or credentials. diff --git a/crates/nemoclaw-sdk/src/config/integrations.rs b/crates/nemoclaw-sdk/src/config/integrations.rs index 29d0e8b92ab..48c7c262da3 100644 --- a/crates/nemoclaw-sdk/src/config/integrations.rs +++ b/crates/nemoclaw-sdk/src/config/integrations.rs @@ -35,7 +35,7 @@ pub struct IntegrationBinding<'a> { impl Sandbox { /// Resolve deployment and sandbox definitions without implicitly granting access. /// `name` is this sandbox's key, which diagnostics use to identify it. - pub fn integration_bindings<'a>( + pub(crate) fn integration_bindings<'a>( &'a self, name: &str, shared: &'a BTreeMap, @@ -117,14 +117,23 @@ impl Sandbox { } impl Document { + /// Resolve the deployment and sandbox integration definitions the named + /// sandbox selects, without implicitly granting access. + pub fn sandbox_integration_bindings( + &self, + sandbox: &str, + ) -> Result>, ConfigError> { + let (name, sandbox) = self.named_sandbox(sandbox)?; + sandbox.integration_bindings(name, &self.spec.integrations) + } + /// The web search attached to the named sandbox, if any. pub(crate) fn web_search( &self, sandbox: &str, ) -> Result, ConfigError> { - let (name, sandbox) = self.named_sandbox(sandbox)?; let mut selected = None; - for binding in sandbox.integration_bindings(name, &self.spec.integrations)? { + for binding in self.sandbox_integration_bindings(sandbox)? { match binding.definition { Integration::WebSearch(search) => { if selected.is_some() { diff --git a/crates/nemoclaw-sdk/src/config/mod.rs b/crates/nemoclaw-sdk/src/config/mod.rs index a850de121ef..0d04793fc72 100644 --- a/crates/nemoclaw-sdk/src/config/mod.rs +++ b/crates/nemoclaw-sdk/src/config/mod.rs @@ -197,8 +197,8 @@ impl Document { if let Some(metadata) = &sandbox.image.metadata { names.push(metadata.env.as_str()); } - for binding in sandbox - .integration_bindings(name, &self.spec.integrations) + for binding in self + .sandbox_integration_bindings(name) .expect("validated integration references") { match binding.definition { @@ -284,20 +284,8 @@ impl ManagedGateway { /// Kubernetes target. pub fn local(&self) -> Option> { match &self.target { - ManagedTarget::Docker(docker) => Some(LocalGateway { - compute_driver: ComputeDriver::Docker, - endpoint: &docker.endpoint, - engine: &docker.engine, - image_pull_policy: docker.image_pull_policy, - network_cidr: &docker.network_cidr, - }), - ManagedTarget::Podman(podman) => Some(LocalGateway { - compute_driver: ComputeDriver::Podman, - endpoint: &podman.endpoint, - engine: &podman.engine, - image_pull_policy: podman.image_pull_policy, - network_cidr: &podman.network_cidr, - }), + ManagedTarget::Docker(docker) => Some(docker.local()), + ManagedTarget::Podman(podman) => Some(podman.local()), ManagedTarget::Kubernetes(_) => None, } } @@ -315,6 +303,29 @@ impl ManagedGateway { } } +impl ManagedDocker { + pub(crate) fn local(&self) -> LocalGateway<'_> { + LocalGateway { + compute_driver: ComputeDriver::Docker, + endpoint: &self.endpoint, + engine: &self.engine, + image_pull_policy: self.image_pull_policy, + network_cidr: &self.network_cidr, + } + } +} +impl ManagedPodman { + pub(crate) fn local(&self) -> LocalGateway<'_> { + LocalGateway { + compute_driver: ComputeDriver::Podman, + endpoint: &self.endpoint, + engine: &self.engine, + image_pull_policy: self.image_pull_policy, + network_cidr: &self.network_cidr, + } + } +} + /// Borrowed settings of a managed gateway on a local Docker or Podman engine. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct LocalGateway<'a> { diff --git a/crates/nemoclaw-sdk/src/config/providers.rs b/crates/nemoclaw-sdk/src/config/providers.rs index e0fca8a8d06..71016da2b8c 100644 --- a/crates/nemoclaw-sdk/src/config/providers.rs +++ b/crates/nemoclaw-sdk/src/config/providers.rs @@ -2,9 +2,14 @@ // SPDX-License-Identifier: Apache-2.0 use super::references::{ScopedInference, diagnostic_name, missing_reference, sandbox_path}; use super::source::DefinitionSource; +use super::validation::valid_name; use super::{ConfigError, Document, Inference, InferenceProvider, Route}; use std::collections::{BTreeMap, BTreeSet}; +// Selection also runs without `validate`, as from `credential_names`, so a +// document built in Rust can reach it with names the schema rejects. +const INVALID_NAME: &str = "provider names must be lowercase names"; + // The resource key identifies the registration; the authored path distinguishes // separate definitions with identical values and lets export edit the right one. pub(crate) struct SelectedProvider<'a> { @@ -41,7 +46,7 @@ impl<'a> SelectedProvider<'a> { use sha2::{Digest, Sha256}; self.key = format!( "{}-{}", - &self.name[..self.name.len().min(12)], + self.name.chars().take(12).collect::(), &super::hex(&Sha256::digest(format!("{}\0{scope}", self.key)))[..24] ); self @@ -217,6 +222,15 @@ impl Document { pub(crate) fn selected_providers(&self) -> Result>, ConfigError> { let mut selected = BTreeMap::new(); for (name, sandbox) in &self.spec.sandboxes { + if !self + .spec + .inference_providers + .keys() + .chain(sandbox.inference_providers.keys()) + .all(|name| valid_name(name)) + { + return Err(ConfigError::new(INVALID_NAME)); + } if sandbox .inference_providers .keys() @@ -229,6 +243,10 @@ impl Document { let inference = self.scoped_inference(name)?; for route in &inference.inference.routes { let provider = self.sandbox_route_registration(name, route)?; + // An inline definition states its own name. + if !valid_name(provider.name) { + return Err(ConfigError::new(INVALID_NAME)); + } let path = provider.path.clone(); if let Some(previous) = selected.insert(provider.key.clone(), provider) && previous.path != path diff --git a/crates/nemoclaw-sdk/src/config/schema.rs b/crates/nemoclaw-sdk/src/config/schema.rs index 3d94b22d2f8..ae63c468750 100644 --- a/crates/nemoclaw-sdk/src/config/schema.rs +++ b/crates/nemoclaw-sdk/src/config/schema.rs @@ -65,6 +65,8 @@ fn remove_serde_defaults(schema: &mut serde_json::Value) { } mod runtime; +#[doc(hidden)] +pub use runtime::entry_key_shown; pub(crate) use runtime::{ validate_definition, validate_document, validate_input, validate_property, validate_service, validate_tuning, diff --git a/crates/nemoclaw-sdk/src/config/schema/runtime.rs b/crates/nemoclaw-sdk/src/config/schema/runtime.rs index e891abd1d23..9230a39b2b6 100644 --- a/crates/nemoclaw-sdk/src/config/schema/runtime.rs +++ b/crates/nemoclaw-sdk/src/config/schema/runtime.rs @@ -23,8 +23,6 @@ static TUNING_SCHEMA: LazyLock = LazyLock::new(|| { serde_json::to_value(schemars::schema_for!(RouteTuning)).expect("tuning schema") }); static TUNING: LazyLock = LazyLock::new(|| compile(&TUNING_SCHEMA)); -static NAME: LazyLock = - LazyLock::new(|| compile(&INPUT_SCHEMA["$defs"]["Metadata"]["properties"]["name"])); static FIELDS: LazyLock> = LazyLock::new(|| { fn collect(value: &Value, fields: &mut BTreeSet) { if let Some(properties) = value["properties"].as_object() { @@ -216,11 +214,10 @@ fn annotation<'s>( None } -/// The replacements for fields an earlier document shape accepted, when the -/// rejecting object lists them under `x-nemoclaw-removed-fields`, so an -/// earlier document gets every hint at once. `runtime` leads, since it chose -/// where the other fields now live; the rest follow the annotation's order. -/// Only the schema's text is rendered, never arbitrary input keys. +/// The hints for the unknown fields that the rejecting object lists under +/// `x-nemoclaw-removed-fields` as `[field, message]` pairs, joined in the +/// annotation's order so the input gets every hint at once. Only the schema's +/// text is rendered, never arbitrary input keys. fn removed_fields(schema: &Value, error: &jsonschema::ValidationError<'_>) -> Option { use jsonschema::error::ValidationErrorKind as Kind; let Kind::AdditionalProperties { unexpected } = error.kind() else { @@ -230,23 +227,17 @@ fn removed_fields(schema: &Value, error: &jsonschema::ValidationError<'_>) -> Op .schema_path() .as_str() .strip_suffix("/additionalProperties")?; - let removed = schema + let messages = schema .pointer(object)? .get("x-nemoclaw-removed-fields")? - .as_object()?; - let mut matched = removed + .as_array()? .iter() - .filter(|(field, _)| unexpected.contains(field)) - .filter_map(|(field, message)| Some((field.as_str(), message.as_str()?))) + .filter_map(|pair| match pair.as_array()?.as_slice() { + [field, message] if unexpected.iter().any(|name| field == name) => message.as_str(), + _ => None, + }) .collect::>(); - matched.sort_by_key(|(field, _)| *field != "runtime"); - (!matched.is_empty()).then(|| { - matched - .into_iter() - .map(|(_, message)| message) - .collect::>() - .join("; ") - }) + (!messages.is_empty()).then(|| messages.join("; ")) } fn count(limit: u64, one: &str, many: &str) -> String { @@ -269,6 +260,35 @@ fn scalar_constraint(schema: &Value) -> Option { } } +/// Whether a diagnostic shows `key` at the instance location after `parents`, +/// the unescaped JSON pointer segments from the document root, or `None` when +/// that location keys no named definition. Named definitions are sandboxes +/// and the providers, services, harnesses, inferences, and integrations of the +/// deployment or of a sandbox. Such a key is shown only when it, and the key +/// of a sandbox that encloses it, are valid names. Editors use this to hide +/// what diagnostics hide. +#[doc(hidden)] +pub fn entry_key_shown(parents: &[&str], key: &str) -> Option { + use crate::config::valid_name; + match parents { + [ + "spec", + "sandboxes" | "inferenceProviders" | "services" | "harnesses" | "inferences" + | "integrations", + ] => Some(valid_name(key)), + [ + "spec", + "sandboxes", + sandbox, + "inferenceProviders" | "harnesses" | "inferences" | "integrations", + ] + | ["spec", "sandboxes", sandbox, "agent", "integrations"] => { + Some(valid_name(sandbox) && valid_name(key)) + } + _ => None, + } +} + fn instance_path(pointer: &str, root: &Value) -> String { if pointer.is_empty() { return "document root".into(); @@ -289,33 +309,11 @@ fn instance_path(pointer: &str, root: &Value) -> String { } else { // Only names in declared application collections can be shown. Invalid // names and opaque map keys remain hidden even if they resemble values. - let named = match parts[..offset] + let parents = parts[..offset] .iter() .map(String::as_str) - .collect::>() - .as_slice() - { - [ - "spec", - "services" | "harnesses" | "inferences" | "integrations" | "inferenceProviders" - | "sandboxes", - ] => true, - [ - "spec", - "sandboxes", - sandbox, - "harnesses" | "inferences" | "integrations" | "inferenceProviders", - ] - | ["spec", "sandboxes", sandbox, "agent", "integrations"] => { - NAME.is_valid(&Value::String((*sandbox).to_owned())) - } - _ => false, - }; - let visible = if named { - NAME.is_valid(&Value::String(key.clone())) - } else { - FIELDS.contains(key) - }; + .collect::>(); + let visible = entry_key_shown(&parents, key).unwrap_or_else(|| FIELDS.contains(key)); if !path.is_empty() { path.push('.'); } @@ -626,6 +624,11 @@ mod tests { "/spec/sandboxes/Private-Sentinel/harnesses/shared", "spec.sandboxes.[entry].harnesses.[entry]", ), + // A name inside a hidden sandbox stays hidden, even a field name. + ( + "/spec/sandboxes/Private-Sentinel/harnesses/endpoint", + "spec.sandboxes.[entry].harnesses.[entry]", + ), ] { assert_eq!(instance_path(pointer, &root), expected, "{pointer}"); } diff --git a/crates/nemoclaw-sdk/src/config/schema/validation.rs b/crates/nemoclaw-sdk/src/config/schema/validation.rs index c80c556be30..e9f0deb933a 100644 --- a/crates/nemoclaw-sdk/src/config/schema/validation.rs +++ b/crates/nemoclaw-sdk/src/config/schema/validation.rs @@ -163,12 +163,14 @@ pub(super) fn constrain(root: &mut Value, normalized: bool) { "x-nemoclaw-error": format!("spec.sandboxes must map 1 to 32 lowercase names ({}) to sandbox definitions", c::SLUG) }), ); - // Earlier documents listed named entries; the key now carries the name. + // A keyed entry takes its name from its key; the hint answers a `name` + // copied from a v1alpha1 list entry. defs["Sandbox"]["x-nemoclaw-removed-fields"] = - json!({"name": "a sandbox's name is its key under spec.sandboxes"}); - defs["InferenceProvider"]["x-nemoclaw-removed-fields"] = json!({ - "name": "a provider's name is its key under inferenceProviders; only an inline route provider states name" - }); + json!([["name", "a sandbox's name is its key under spec.sandboxes"]]); + defs["InferenceProvider"]["x-nemoclaw-removed-fields"] = json!([[ + "name", + "a provider's name is its key under inferenceProviders; only an inline route provider states name" + ]]); defs["Sandbox"]["allOf"] = json!([]); optional_string( &mut defs["Image"], @@ -353,18 +355,35 @@ fn constrain_gateway(defs: &mut serde_json::Map, normalized: bool }; property(gateway, "target", json!({"default": target})); } + // `runtime` leads, since it chose where the other fields now live. if managed { - gateway["x-nemoclaw-removed-fields"] = json!({ - "runtime": runtime, - "endpoint": "spec.gateway.endpoint of a managed gateway moved to the endpoint of its spec.gateway.target key", - "engine": engine, - "image": "spec.gateway.image is removed because the SDK pins the gateway image", - "imagePullPolicy": "spec.gateway.imagePullPolicy moved to spec.gateway.target.docker or spec.gateway.target.podman", - "networkCIDR": "spec.gateway.networkCIDR moved to networkCidr under spec.gateway.target.docker or spec.gateway.target.podman", - "kubernetes": "spec.gateway.kubernetes moved to spec.gateway.target.kubernetes" - }); + gateway["x-nemoclaw-removed-fields"] = json!([ + ["runtime", runtime], + [ + "endpoint", + "spec.gateway.endpoint of a managed gateway moved to the endpoint of its spec.gateway.target key" + ], + ["engine", engine], + [ + "image", + "spec.gateway.image is removed because the SDK pins the gateway image" + ], + [ + "imagePullPolicy", + "spec.gateway.imagePullPolicy moved to spec.gateway.target.docker or spec.gateway.target.podman" + ], + [ + "networkCIDR", + "spec.gateway.networkCIDR moved to networkCidr under spec.gateway.target.docker or spec.gateway.target.podman" + ], + [ + "kubernetes", + "spec.gateway.kubernetes moved to spec.gateway.target.kubernetes" + ] + ]); } else { - gateway["x-nemoclaw-removed-fields"] = json!({"runtime": runtime, "engine": engine}); + gateway["x-nemoclaw-removed-fields"] = + json!([["runtime", runtime], ["engine", engine]]); property(gateway, "endpoint", json!({"pattern": "^https?://"})); gateway["if"] = at("endpoint", json!({"pattern": "^http:"}), true); gateway["then"] = forbid(&["credential", "tls"]); @@ -413,10 +432,18 @@ fn constrain_gateway(defs: &mut serde_json::Map, normalized: bool "imagePullPolicy", json!({"default": super::super::ImagePullPolicy::default()}), ); - target["x-nemoclaw-removed-fields"] = json!({ - "image": format!("spec.gateway.target.{key} takes no image because the SDK pins the gateway image"), - "networkCIDR": format!("spec.gateway.target.{key} spells networkCIDR as networkCidr") - }); + target["x-nemoclaw-removed-fields"] = json!([ + [ + "image", + format!( + "spec.gateway.target.{key} takes no image because the SDK pins the gateway image" + ) + ], + [ + "networkCIDR", + format!("spec.gateway.target.{key} spells networkCIDR as networkCidr") + ] + ]); } optional_string( &mut defs["ManagedDocker"], @@ -465,7 +492,8 @@ fn constrain_gateway(defs: &mut serde_json::Map, normalized: bool // which the removed-field hint can name. let existing = &mut defs["ExternalKubernetes"]; existing["properties"] = json!({}); - existing["x-nemoclaw-removed-fields"] = json!({ - "distribution": "distribution applies only to a managed gateway's spec.gateway.target.kubernetes; an existing gateway reports only the kubernetes driver" - }); + existing["x-nemoclaw-removed-fields"] = json!([[ + "distribution", + "distribution applies only to a managed gateway's spec.gateway.target.kubernetes; an existing gateway reports only the kubernetes driver" + ]]); } diff --git a/crates/nemoclaw-sdk/src/config/validation.rs b/crates/nemoclaw-sdk/src/config/validation.rs index 042824f5617..d834b628eca 100644 --- a/crates/nemoclaw-sdk/src/config/validation.rs +++ b/crates/nemoclaw-sdk/src/config/validation.rs @@ -107,12 +107,13 @@ impl Document { impl super::ManagedGateway { pub fn validate_managed(&self) -> Result<(), ConfigError> { schema::validate_definition("Gateway", &Gateway::Managed(self.clone()))?; - if let super::ManagedTarget::Kubernetes(cluster) = &self.target { - return validate_endpoint(&cluster.endpoint, true); - } - let local = self - .local() - .expect("Docker and Podman targets run on a local engine"); + let local = match &self.target { + ManagedTarget::Docker(docker) => docker.local(), + ManagedTarget::Podman(podman) => podman.local(), + ManagedTarget::Kubernetes(cluster) => { + return validate_endpoint(&cluster.endpoint, true); + } + }; let authority = local .endpoint .strip_prefix("http://") diff --git a/crates/nemoclaw-sdk/src/deployment/runtime/tests.rs b/crates/nemoclaw-sdk/src/deployment/runtime/tests.rs index 8f76108e89c..60d2b419817 100644 --- a/crates/nemoclaw-sdk/src/deployment/runtime/tests.rs +++ b/crates/nemoclaw-sdk/src/deployment/runtime/tests.rs @@ -177,6 +177,88 @@ fn kubernetes_gateway_requires_storage_and_fresh_readiness_without_replacement() assert!(check_runtime_plan(&plan, &checked.expected, &bindings).is_err()); } +const BOUND_STORAGE: &str = "bound storage specification differs from retained intent"; + +/// State binds a managed gateway's target key and every setting under it +/// except `imagePullPolicy`, so a retained gateway cannot move. +#[test] +fn a_bound_docker_gateway_refuses_another_target_key_or_network_but_not_a_pull_policy() { + let mut value: Value = serde_saphyr::from_slice( + include_bytes!("../../../tests/fixtures/config/local.yaml").as_slice(), + ) + .unwrap(); + value["spec"]["gateway"] = json!({"management": "managed"}); + let document = Document::parse(value.to_string().as_bytes()).unwrap(); + let generations = Record::new(document.clone()).unwrap().generations; + let targets = compile::runtime_targets(&document, &generations).unwrap(); + let bindings: BTreeMap = targets + .iter() + .map(|target| { + ( + target.address.clone(), + bound(format!("physical-{}", target.kind), target), + ) + }) + .collect(); + runtime_bindings(&targets, &bindings).unwrap(); + let docker = + serde_json::to_value(&document).unwrap()["spec"]["gateway"]["target"]["docker"].clone(); + let mut network = docker.clone(); + network["networkCidr"] = json!("172.30.250.0/24"); + let mut policy = docker.clone(); + policy["imagePullPolicy"] = json!("Never"); + for (target, refused) in [ + // The same engine socket and settings under another key. + (json!({"podman": docker}), true), + (json!({"docker": network}), true), + (json!({"docker": policy}), false), + ] { + value["spec"]["gateway"]["target"] = target.clone(); + let changed = Document::parse(value.to_string().as_bytes()).unwrap(); + let targets = compile::runtime_targets(&changed, &generations).unwrap(); + let result = runtime_bindings(&targets, &bindings); + if refused { + assert!( + matches!(result, Err(Error::Conflict(BOUND_STORAGE))), + "{target}" + ); + } else { + result.unwrap(); + } + } +} + +#[test] +fn a_bound_kubernetes_gateway_refuses_another_distribution_context_or_namespace() { + let (document, generations) = kubernetes_context(); + let targets = compile::runtime_targets(&document, &generations).unwrap(); + let bindings = kubernetes_bindings(&targets); + runtime_bindings(&targets, &bindings).unwrap(); + let edits: [fn(&mut crate::config::ManagedKubernetes); 3] = [ + |cluster| cluster.distribution = crate::config::KubernetesDistribution::OpenShift, + |cluster| cluster.context = "another-cluster".into(), + |cluster| cluster.namespace = "another-namespace".into(), + ]; + for (index, edit) in edits.into_iter().enumerate() { + let mut changed = document.clone(); + let Some(crate::config::ManagedGateway { + target: crate::config::ManagedTarget::Kubernetes(cluster), + }) = changed.spec.gateway.as_managed_mut() + else { + panic!("managed Kubernetes context"); + }; + edit(cluster); + let targets = compile::runtime_targets(&changed, &generations).unwrap(); + assert!( + matches!( + runtime_bindings(&targets, &bindings), + Err(Error::Conflict(BOUND_STORAGE)) + ), + "edit {index}" + ); + } +} + #[test] fn interrupted_kubernetes_platform_apply_cannot_move_to_another_namespace() { let (document, _) = kubernetes_context(); diff --git a/crates/nemoclaw-sdk/src/deployment/tests.rs b/crates/nemoclaw-sdk/src/deployment/tests.rs index d8aed0ae49c..806bb091398 100644 --- a/crates/nemoclaw-sdk/src/deployment/tests.rs +++ b/crates/nemoclaw-sdk/src/deployment/tests.rs @@ -938,7 +938,7 @@ fn removed_disposable_compute_accepts_confirmed_absence() { } #[tokio::test] -async fn changing_gateway_management_at_the_same_endpoint_preserves_saved_state() { +async fn changing_gateway_management_or_a_managed_endpoint_preserves_saved_state() { let bundle_directory = tempfile::tempdir().unwrap(); let mut manifest = crate::bundle::Manifest { version: "0.1.0".into(), @@ -972,7 +972,14 @@ async fn changing_gateway_management_at_the_same_endpoint_preserves_saved_state( }); managed.defaults(); managed.validate().unwrap(); - for (original, changed) in [(&external, &managed), (&managed, &external)] { + let mut moved = managed.clone(); + *moved.spec.gateway.endpoint_mut() = "http://127.0.0.1:17682".into(); + moved.validate().unwrap(); + for (original, changed) in [ + (&external, &managed), + (&managed, &external), + (&managed, &moved), + ] { let state_directory = tempfile::tempdir().unwrap(); let store = Store::open(state_directory.path()).unwrap(); store.save(&Record::new(original.clone()).unwrap()).unwrap(); diff --git a/crates/nemoclaw-sdk/src/managed/settings.rs b/crates/nemoclaw-sdk/src/managed/settings.rs index cd6eb769ddc..7d574d5cfb9 100644 --- a/crates/nemoclaw-sdk/src/managed/settings.rs +++ b/crates/nemoclaw-sdk/src/managed/settings.rs @@ -59,11 +59,10 @@ impl ManagedGateway { /// image on a local engine. The acquisition policy is a mutable provider /// attribute rather than container identity, so it is left out. pub(crate) fn runtime_settings(&self) -> GatewaySettings { - let ManagedTarget::Kubernetes(cluster) = &self.target else { - return self - .local() - .expect("Docker and Podman targets run on a local engine") - .runtime_settings(); + let cluster = match &self.target { + ManagedTarget::Docker(docker) => return docker.local().runtime_settings(), + ManagedTarget::Podman(podman) => return podman.local().runtime_settings(), + ManagedTarget::Kubernetes(cluster) => cluster, }; GatewaySettings { runtime: GatewayRuntime { diff --git a/crates/nemoclaw-sdk/src/state/mod.rs b/crates/nemoclaw-sdk/src/state/mod.rs index a4e56038e9f..1dd8824e607 100644 --- a/crates/nemoclaw-sdk/src/state/mod.rs +++ b/crates/nemoclaw-sdk/src/state/mod.rs @@ -18,7 +18,7 @@ use std::{ /// Format of `intent.json`. Version 8 holds a `nemoclaw.nvidia.com/v1alpha2` /// document; earlier versions held v1alpha1 documents. const RECORD_VERSION: u32 = 8; -const EARLIER_STATE: &str = "deployment state was written by an earlier NemoClaw for nemoclaw.nvidia.com/v1alpha1; retain it and use that NemoClaw to destroy it, or deploy this document as a separate deployment"; +const EARLIER_STATE: &str = "deployment state was written by an earlier NemoClaw for nemoclaw.nvidia.com/v1alpha1; retain it and use that NemoClaw to destroy it, or deploy this document as a separate deployment; see docs/migration.md"; #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", default, deny_unknown_fields)] @@ -288,9 +288,6 @@ impl Record { self.destroy_runtime } fn validate(&self) -> Result<(), Error> { - if self.version < RECORD_VERSION { - return Err(Error::State(EARLIER_STATE)); - } if self.version != RECORD_VERSION { return Err(Error::State( "deployment intent record has an unsupported format version; retain it for recovery", @@ -489,17 +486,19 @@ impl Store { let corrupt = || Error::State("deployment intent record is corrupt; retain it for recovery"); let raw: serde_json::Value = serde_json::from_slice(&bytes).map_err(|_| corrupt())?; - // An earlier record's document need not parse as the current type, so - // identify it before the typed parse would call it corrupt. - let earlier_version = raw + // Every format records an integer version; a missing one would + // otherwise parse as version 0. + let version = raw .get("version") .and_then(serde_json::Value::as_u64) - .is_some_and(|version| version < u64::from(RECORD_VERSION)); + .ok_or_else(corrupt)?; + // An earlier record's document need not parse as the current type, so + // identify it before the typed parse would call it corrupt. let earlier_document = raw .pointer("/document/apiVersion") .and_then(serde_json::Value::as_str) == Some(crate::config::EARLIER_API_VERSION); - if earlier_version || earlier_document { + if version < u64::from(RECORD_VERSION) || earlier_document { return Err(Error::State(EARLIER_STATE)); } let record: Record = serde_json::from_value(raw).map_err(|_| corrupt())?; diff --git a/crates/nemoclaw-sdk/src/state/tests.rs b/crates/nemoclaw-sdk/src/state/tests.rs index 17161121e44..d7ca454f41b 100644 --- a/crates/nemoclaw-sdk/src/state/tests.rs +++ b/crates/nemoclaw-sdk/src/state/tests.rs @@ -60,8 +60,35 @@ fn corrupt_intent_is_not_an_empty_deployment() { ); } #[test] +fn intent_without_an_integer_version_is_corrupt_and_stays_untouched() { + let document = crate::config::Document::parse( + include_str!("../../tests/fixtures/config/local.yaml").as_bytes(), + ) + .unwrap(); + let current = serde_json::to_value(Record::new(document).unwrap()).unwrap(); + let mut missing = current.clone(); + missing.as_object_mut().unwrap().remove("version"); + let mut fraction = current.clone(); + fraction["version"] = serde_json::json!(8.5); + let mut text = current; + text["version"] = serde_json::json!("8"); + for record in [serde_json::json!({}), missing, fraction, text] { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(dir.path()).unwrap(); + let bytes = serde_json::to_vec(&record).unwrap(); + let path = dir.path().join("intent.json"); + std::fs::write(&path, &bytes).unwrap(); + assert_eq!( + store.load().unwrap_err().to_string(), + "deployment intent record is corrupt; retain it for recovery", + "{record}" + ); + assert_eq!(std::fs::read(path).unwrap(), bytes); + } +} +#[test] fn intent_from_another_nemoclaw_format_is_rejected_by_version_and_stays_untouched() { - let earlier = "deployment state was written by an earlier NemoClaw for nemoclaw.nvidia.com/v1alpha1; retain it and use that NemoClaw to destroy it, or deploy this document as a separate deployment"; + let earlier = "deployment state was written by an earlier NemoClaw for nemoclaw.nvidia.com/v1alpha1; retain it and use that NemoClaw to destroy it, or deploy this document as a separate deployment; see docs/migration.md"; let document = crate::config::Document::parse( include_str!("../../tests/fixtures/config/local.yaml").as_bytes(), ) diff --git a/crates/nemoclaw-sdk/tests/provider_references.rs b/crates/nemoclaw-sdk/tests/provider_references.rs index 4361c89471a..47f390014f9 100644 --- a/crates/nemoclaw-sdk/tests/provider_references.rs +++ b/crates/nemoclaw-sdk/tests/provider_references.rs @@ -154,6 +154,46 @@ fn references_reject_missing_names_shadowing_and_distinct_inline_instances() { } } #[test] +fn a_rust_built_provider_name_outside_the_name_pattern_is_rejected_without_a_panic() { + // Its first 12 bytes end inside the final two-byte character. + let name = "aaaaaaaaaaaĆ©"; + let renamed = |mut value: Value| { + value["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["providerRef"] = + json!(name); + value + }; + let mut deployment = renamed(input()); + let providers = deployment["spec"]["inferenceProviders"] + .as_object_mut() + .unwrap(); + let provider = providers.remove("local").unwrap(); + providers.insert(name.into(), provider.clone()); + let mut sandbox = renamed(input()); + sandbox["spec"] + .as_object_mut() + .unwrap() + .remove("inferenceProviders"); + sandbox["spec"]["sandboxes"]["assistant"]["inferenceProviders"] = json!({name: provider}); + let mut route = inline(input()); + route["spec"]["sandboxes"]["assistant"]["agent"]["inference"]["routes"][0]["provider"]["name"] = + json!(name); + for value in [deployment, sandbox, route] { + // Deserializing directly skips the input schema, as a Rust caller can. + let mut document: Document = serde_json::from_value(value).unwrap(); + document.defaults(); + assert!(document.credential_names().is_empty()); + assert_eq!( + document + .selected_inference_providers() + .unwrap_err() + .to_string(), + "provider names must be lowercase names" + ); + let error = document.validate().unwrap_err().to_string(); + assert!(!error.contains(name), "{error}"); + } +} +#[test] fn inline_managed_providers_reuse_named_service_runtime_and_defaults() { for input in [ include_str!("../../../examples/managed-ollama.yaml"), diff --git a/crates/nemoclaw-sdk/tests/retargeting.rs b/crates/nemoclaw-sdk/tests/retargeting.rs index 42e712b4c53..27d7617d71e 100644 --- a/crates/nemoclaw-sdk/tests/retargeting.rs +++ b/crates/nemoclaw-sdk/tests/retargeting.rs @@ -14,16 +14,19 @@ enum Target { ManagedDocker, ManagedPodman, ManagedKubernetes, + /// Managed `kubernetes` with `distribution: openshift`. + ManagedOpenShift, ExternalDocker, ExternalPodman, ExternalKubernetes, } impl Target { - const ALL: [Self; 6] = [ + const ALL: [Self; 7] = [ Self::ManagedDocker, Self::ManagedPodman, Self::ManagedKubernetes, + Self::ManagedOpenShift, Self::ExternalDocker, Self::ExternalPodman, Self::ExternalKubernetes, @@ -34,6 +37,13 @@ impl Target { const DOCKER: &str = "unix:///var/run/docker.sock"; const PODMAN: &str = "unix:///run/user/1000/podman/podman.sock"; let managed = |target| json!({"management": "managed", "target": target}); + let cluster = json!({ + "endpoint": "https://127.0.0.1:17690", + "kubeconfig": {"env": "CLUSTER_KUBECONFIG"}, + "context": "cluster", + "namespace": "agents", + "authentication": {"profile": "development"} + }); let external = |target| { json!({ "management": "external", @@ -44,13 +54,12 @@ impl Target { match self { Self::ManagedDocker => managed(json!({"docker": {}})), Self::ManagedPodman => managed(json!({"podman": {"engine": PODMAN}})), - Self::ManagedKubernetes => managed(json!({"kubernetes": { - "endpoint": "https://127.0.0.1:17690", - "kubeconfig": {"env": "CLUSTER_KUBECONFIG"}, - "context": "cluster", - "namespace": "agents", - "authentication": {"profile": "development"} - }})), + Self::ManagedKubernetes => managed(json!({"kubernetes": cluster})), + Self::ManagedOpenShift => { + let mut cluster = cluster; + cluster["distribution"] = json!("openshift"); + managed(json!({"kubernetes": cluster})) + } Self::ExternalDocker => external(json!({"docker": {"engine": DOCKER}})), Self::ExternalPodman => external(json!({"podman": {"engine": PODMAN}})), Self::ExternalKubernetes => external(json!({"kubernetes": {}})), @@ -58,7 +67,10 @@ impl Target { } fn kubernetes(self) -> bool { - matches!(self, Self::ManagedKubernetes | Self::ExternalKubernetes) + matches!( + self, + Self::ManagedKubernetes | Self::ManagedOpenShift | Self::ExternalKubernetes + ) } } @@ -77,9 +89,11 @@ enum Edit { RemoveImageMetadata, /// Other than managed Docker: each Ollama and vLLM service needs explicit /// `placement` and `publication`, since only a managed Docker gateway - /// lends its engine and network to services. An `ollamaProxy` service - /// needs an explicit `engine` instead; no example declares one. + /// lends its engine and network to services. PlaceServices, + /// Other than managed Docker: each `ollamaProxy` service needs an explicit + /// `engine`, for the same reason. + SetProxyEngine, } /// The edits that resolve each violation a retargeted example reports. A @@ -104,6 +118,10 @@ const RESOLUTIONS: &[(&str, &[Edit])] = &[ "vLLM requires the managed gateway Docker engine or explicit placement", &[Edit::PlaceServices], ), + ( + "Ollama proxy requires a managed local Docker gateway or explicit local engine", + &[Edit::SetProxyEngine], + ), ]; /// The edits moving `example` to `target` needs, predicted from its features. @@ -112,8 +130,10 @@ fn predicted(example: &Value, target: Target) -> BTreeSet { let services = values(&example["spec"]["services"]); let named = |sandbox: &&Value| has_image_ref(sandbox); let described = |sandbox: &&Value| sandbox["image"].get("metadata").is_some(); - let placed = |service: &&Value| service.get("placement").is_some(); + let unplaced = |service: &&Value| !proxy(service) && service.get("placement").is_none(); + let engineless = |service: &&Value| proxy(service) && service.get("engine").is_none(); let cluster = target.kubernetes(); + let local_services = !cluster && target != Target::ManagedDocker; [ (Edit::SetImageRef, cluster && !sandboxes.iter().all(named)), ( @@ -127,7 +147,11 @@ fn predicted(example: &Value, target: Target) -> BTreeSet { ), ( Edit::PlaceServices, - !cluster && target != Target::ManagedDocker && !services.iter().all(placed), + local_services && services.iter().any(unplaced), + ), + ( + Edit::SetProxyEngine, + local_services && services.iter().any(engineless), ), ] .into_iter() @@ -138,15 +162,10 @@ fn predicted(example: &Value, target: Target) -> BTreeSet { #[test] fn retargeting_each_example_needs_only_the_documented_edits() { let validator = jsonschema::validator_for(&input_schema()).unwrap(); - let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); - let paths = examples::yaml_files(&root.join("examples")); - assert!(!paths.is_empty()); let mut failures = Vec::new(); - for path in paths { - let text = std::fs::read_to_string(&path).unwrap(); - let example: Value = serde_saphyr::from_str(&text).unwrap(); - let defaulted = serde_json::to_value(Document::parse(text.as_bytes()).unwrap()).unwrap(); - let name = path.strip_prefix(&root).unwrap().display(); + for (name, example) in inputs() { + let defaulted = + serde_json::to_value(Document::parse(example.to_string().as_bytes()).unwrap()).unwrap(); for target in Target::ALL { let expected = predicted(&example, target); match required_edits(&validator, &example, &defaulted, target) { @@ -161,6 +180,38 @@ fn retargeting_each_example_needs_only_the_documented_edits() { assert!(failures.is_empty(), "{}", failures.join("\n")); } +/// Each example by its path, and a document with an `ollamaProxy` service, +/// which no example declares. +fn inputs() -> Vec<(String, Value)> { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let mut inputs: Vec<(String, Value)> = examples::yaml_files(&root.join("examples")) + .into_iter() + .map(|path| { + let text = std::fs::read_to_string(&path).unwrap(); + let name = path.strip_prefix(&root).unwrap().display().to_string(); + (name, serde_saphyr::from_str(&text).unwrap()) + }) + .collect(); + let mut proxy = inputs + .iter() + .find(|(name, _)| name == "examples/managed-ollama.yaml") + .expect("the managed Ollama example") + .1 + .clone(); + proxy["spec"]["services"] = json!({"ollama-proxy": { + "kind": "ollamaProxy", + "image": format!("nc-prototype-ollama-proxy@sha256:{}", "a".repeat(64)), + "endpoint": "http://172.20.0.1:11435/v1", + "upstream": { + "endpoint": "http://127.0.0.1:11434/v1", + "model": {"name": "qwen3:0.6b", "digest": "a".repeat(64)} + } + }}); + proxy["spec"]["inferenceProviders"]["local"]["serviceRef"] = json!("ollama-proxy"); + inputs.push(("an ollamaProxy document".into(), proxy)); + inputs +} + /// Retarget `example`, then apply the documented edit for each violation /// until it parses. Returns the edits applied, or a violation that no edit /// resolves. @@ -268,7 +319,7 @@ impl Edit { } Self::PlaceServices => { for (name, service) in spec["services"].as_object_mut().unwrap() { - if service.get("placement").is_some() { + if proxy(service) || service.get("placement").is_some() { continue; } let port = &defaulted["spec"]["services"][name]["serving"]["port"]; @@ -280,6 +331,13 @@ impl Edit { }); } } + Self::SetProxyEngine => { + for service in values_mut(&mut spec["services"]) { + if proxy(service) && service.get("engine").is_none() { + service["engine"] = json!("unix:///var/run/docker.sock"); + } + } + } } } } @@ -298,6 +356,10 @@ fn use_external_endpoints(value: &mut Value) { } } +fn proxy(service: &Value) -> bool { + service["kind"] == "ollamaProxy" +} + /// The schema already requires an authored `image.ref` to be pinned by digest. fn has_image_ref(sandbox: &Value) -> bool { sandbox["image"]["ref"] diff --git a/docs/contributing/configuration-schema.md b/docs/contributing/configuration-schema.md index d6346563d62..0e43b6582e3 100644 --- a/docs/contributing/configuration-schema.md +++ b/docs/contributing/configuration-schema.md @@ -88,7 +88,7 @@ For a semantic check outside the schema, document the distinction in the generat Schema diagnostics identify document fields, array indices, and constraints without echoing rejected values or unknown properties. Valid names identify the failing definition in `spec.sandboxes`, `spec.inferenceProviders`, `spec.services`, `spec.harnesses`, `spec.inferences`, and `spec.integrations`, and in a validly named sandbox's `inferenceProviders`, `harnesses`, `inferences`, `integrations`, and `agent.integrations`; keys that are not valid names, and keys of other maps, appear as `[entry]`. Parsing a document also reports the source line and column for schema failures and YAML syntax errors. -When a field moves or is removed, map its old name to a message naming the replacement in the rejecting object's `x-nemoclaw-removed-fields` annotation; the diagnostic then reports the messages of all such fields in the input instead of an unknown field. +When a field moves, is removed, or is misplaced, add a `[field, message]` pair naming its replacement or correct location to the rejecting object's `x-nemoclaw-removed-fields` annotation; the diagnostic then reports the messages of all such fields in the input, in the annotation's order, instead of an unknown field. The `spec.gateway` variants list the fields that moved into `spec.gateway.target`; the reference generator does not render this annotation. The parser rejects all explicit YAML tags, including core tags such as `!!binary` and `!!str`; quoted strings containing tag text remain strings. The reference generator renders presence-conditioned scalar bounds beside the containing field table, including the conditional `kvCacheGiB` limits. diff --git a/docs/migration.md b/docs/migration.md index d4793ef2627..c57be800b91 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -76,7 +76,7 @@ This NemoClaw rejects that document, and state written by an earlier NemoClaw, w | Input | Error | |---|---| | A v1alpha1 document given to `plan` or `apply` | `configuration uses nemoclaw.nvidia.com/v1alpha1; this NemoClaw reads nemoclaw.nvidia.com/v1alpha2; re-author it as described in docs/migration.md` | -| A state directory written by an earlier NemoClaw, with any command that reads it | `deployment state was written by an earlier NemoClaw for nemoclaw.nvidia.com/v1alpha1; retain it and use that NemoClaw to destroy it, or deploy this document as a separate deployment` | +| A state directory written by an earlier NemoClaw, with any command that reads it | `deployment state was written by an earlier NemoClaw for nemoclaw.nvidia.com/v1alpha1; retain it and use that NemoClaw to destroy it, or deploy this document as a separate deployment; see docs/migration.md` | There is no conversion command, and this NemoClaw cannot adopt the earlier deployment's resources. Re-author the document by hand and apply it as a separate deployment. @@ -100,7 +100,7 @@ Check its exit status before using the file. Copy the document and make these changes: 1. Set `apiVersion: nemoclaw.nvidia.com/v1alpha2`. -2. Set `metadata.uid` to a fresh UUID, for example from `uuidgen`. +2. Set `metadata.uid` to a fresh lowercase UUID, for example from `uuidgen | tr '[:upper:]' '[:lower:]'`. A reused UID selects the earlier deployment's resource names. 3. Change a `# yaml-language-server: $schema=` comment to `nemoclaw-v1alpha2.schema.json`. 4. Move each field that v1alpha2 changed: @@ -153,8 +153,10 @@ spec: management: managed target: docker: - endpoint: http://127.0.0.1:17671 - networkCidr: 172.20.0.0/24 + # A separate deployment needs an endpoint and network that the + # earlier deployment does not use. + endpoint: http://127.0.0.1:17681 + networkCidr: 172.20.1.0/24 inferenceProviders: local: provider: openai diff --git a/docs/release-notes.md b/docs/release-notes.md index 4a1f41dc4a6..0e5542a788c 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -16,21 +16,25 @@ See [the overview](overview.md) for implemented boundaries and [the CLI referenc Earlier CLI commands, schemas, and state formats have no compatibility guarantees. See [migration](migration.md) for where each earlier task lives now, and [state](state.md) for data preservation. - -The configuration API version is now `nemoclaw.nvidia.com/v1alpha2`, with its schema at `schemas/nemoclaw-v1alpha2.schema.json`. -It makes five changes: - -- `spec.gateway.target` selects the backend with one key, `docker`, `podman`, or `kubernetes`, which holds that backend's settings. - It replaces `runtime.provider` and `spec.gateway.kubernetes` and takes the managed `endpoint`, `engine`, and `imagePullPolicy`; `distribution: openshift` replaces the `openshift` provider. -- `spec.gateway.image` is removed; the SDK pins the gateway image. -- The managed gateway's `networkCIDR` is spelled `networkCidr`. -- `spec.sandboxes`, `spec.inferenceProviders`, and a sandbox's `inferenceProviders` are maps keyed by name instead of lists of entries with `name`. -- Credential references are typed `SecretRef` or `FileRef` in the schema and the Rust SDK; the YAML form `{env: NAME}` is unchanged. - -Deployment state uses `intent.json` format version 8. -This NemoClaw rejects v1alpha1 documents and state written by an earlier NemoClaw without converting or adopting them; [re-author each document](migration.md#re-author-a-v1alpha1-document) and apply it as a separate deployment. - -Docker-managed vLLM and Ollama services default to [`updatePolicy: Preserve`](inference.md#set-container-limits-and-update-policy), which refuses an image, model, serving, or container-limit change that would replace a running container; set `spec.services..updatePolicy: Recreate` to permit the replacement and its downtime. +Recent development changes that affect existing deployments: + +- The configuration API version is now `nemoclaw.nvidia.com/v1alpha2`, with its schema at `schemas/nemoclaw-v1alpha2.schema.json`, and makes five changes: + - `spec.gateway.target` selects the compute driver for every sandbox with one key, `docker`, `podman`, or `kubernetes`, which holds that target's settings. + It replaces `runtime.provider` and `spec.gateway.kubernetes`. + A managed gateway's `endpoint`, `engine`, and `imagePullPolicy` move under the key; an external gateway's `engine` moves under `target.docker` or `target.podman`. + For a managed gateway, `distribution: openshift` under `target.kubernetes` replaces the `openshift` provider; an external OpenShift gateway uses `target.kubernetes: {}`. + - `spec.gateway.image` is removed; the SDK pins the gateway image. + - The managed gateway's `networkCIDR` is spelled `networkCidr`. + - `spec.sandboxes`, `spec.inferenceProviders`, and a sandbox's `inferenceProviders` are maps keyed by name instead of lists of entries with `name`. + - Credential references are typed `SecretRef` or `FileRef` in the schema and the Rust SDK; the YAML form `{env: NAME}` is unchanged. +- Deployment state uses `intent.json` format version 8. + This NemoClaw rejects v1alpha1 documents and state written by an earlier NemoClaw without converting or adopting them; [re-author each document](migration.md#re-author-a-v1alpha1-document) and apply it as a separate deployment. +- The Rust SDK follows the new document shape: + - Removed: `Runtime`, `Credential`, `Gateway::runtime()` and `runtime_mut()`, the `ManagedGateway` settings fields that moved under `target`, `ExternalGateway.runtime` and `engine`, `Sandbox.name`, and `InferenceProvider.name`. + - Added: `ManagedTarget`, `ExternalTarget`, `Gateway::compute_driver()`, `SecretRef`, `FileRef`, and `InlineInferenceProvider`. + `Spec.sandboxes`, `Spec.inference_providers`, and `Sandbox.inference_providers` are maps keyed by name. + - Sandbox lookups such as `Document::sandbox_inference()` and `Document::sandbox_harness()` take the sandbox name instead of a `&Sandbox`, and `Document::sandbox_integration_bindings()` replaces `Sandbox::integration_bindings()`. +- Docker-managed vLLM and Ollama services default to [`updatePolicy: Preserve`](inference.md#set-container-limits-and-update-policy), which refuses an image, model, serving, or container-limit change that would replace a running container; set `spec.services..updatePolicy: Recreate` to permit the replacement and its downtime. ## Qualification and Known Issues diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index b9381e620d1..36b00fc798f 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -64,6 +64,7 @@ Retain the original binding while investigating the selected gateway and engine. Schema errors identify the document field, the violated constraint, and the source line and column. For example, `spec.services.qwen.memory.kvCacheGiB` identifies the `qwen` service, and `spec.sandboxes.assistant.agent.inference.routes[1]` identifies the second route of the `assistant` sandbox. +Schema errors separate names with dots; semantic errors and the CLI's resource sources put each name in brackets, as in `spec.sandboxes[assistant].inferenceProviders[responses]`. Array indices start at zero; source lines and columns start at one, and columns count characters. Valid declaration names appear in paths, while arbitrary map keys appear as `[entry]` and rejected values remain omitted. YAML syntax and duplicate-key errors also include source positions without copying source snippets. diff --git a/schemas/nemoclaw-v1alpha2.schema.json b/schemas/nemoclaw-v1alpha2.schema.json index 74202cfce56..f34e02a40f3 100644 --- a/schemas/nemoclaw-v1alpha2.schema.json +++ b/schemas/nemoclaw-v1alpha2.schema.json @@ -338,9 +338,12 @@ "description": "An existing Kubernetes or OpenShift gateway takes no target settings; sandbox image metadata replaces engine inspection.", "properties": {}, "type": "object", - "x-nemoclaw-removed-fields": { - "distribution": "distribution applies only to a managed gateway's spec.gateway.target.kubernetes; an existing gateway reports only the kubernetes driver" - } + "x-nemoclaw-removed-fields": [ + [ + "distribution", + "distribution applies only to a managed gateway's spec.gateway.target.kubernetes; an existing gateway reports only the kubernetes driver" + ] + ] }, "ExternalOllama": { "additionalProperties": false, @@ -508,15 +511,36 @@ ], "title": "Managed gateway", "type": "object", - "x-nemoclaw-removed-fields": { - "endpoint": "spec.gateway.endpoint of a managed gateway moved to the endpoint of its spec.gateway.target key", - "engine": "spec.gateway.engine moved to spec.gateway.target.docker.engine or spec.gateway.target.podman.engine", - "image": "spec.gateway.image is removed because the SDK pins the gateway image", - "imagePullPolicy": "spec.gateway.imagePullPolicy moved to spec.gateway.target.docker or spec.gateway.target.podman", - "kubernetes": "spec.gateway.kubernetes moved to spec.gateway.target.kubernetes", - "networkCIDR": "spec.gateway.networkCIDR moved to networkCidr under spec.gateway.target.docker or spec.gateway.target.podman", - "runtime": "spec.gateway.runtime is replaced by the key under spec.gateway.target: docker, podman, or kubernetes" - } + "x-nemoclaw-removed-fields": [ + [ + "runtime", + "spec.gateway.runtime is replaced by the key under spec.gateway.target: docker, podman, or kubernetes" + ], + [ + "endpoint", + "spec.gateway.endpoint of a managed gateway moved to the endpoint of its spec.gateway.target key" + ], + [ + "engine", + "spec.gateway.engine moved to spec.gateway.target.docker.engine or spec.gateway.target.podman.engine" + ], + [ + "image", + "spec.gateway.image is removed because the SDK pins the gateway image" + ], + [ + "imagePullPolicy", + "spec.gateway.imagePullPolicy moved to spec.gateway.target.docker or spec.gateway.target.podman" + ], + [ + "networkCIDR", + "spec.gateway.networkCIDR moved to networkCidr under spec.gateway.target.docker or spec.gateway.target.podman" + ], + [ + "kubernetes", + "spec.gateway.kubernetes moved to spec.gateway.target.kubernetes" + ] + ] }, { "additionalProperties": false, @@ -580,10 +604,16 @@ }, "title": "External gateway", "type": "object", - "x-nemoclaw-removed-fields": { - "engine": "spec.gateway.engine moved to spec.gateway.target.docker.engine or spec.gateway.target.podman.engine", - "runtime": "spec.gateway.runtime is replaced by the key under spec.gateway.target: docker, podman, or kubernetes" - } + "x-nemoclaw-removed-fields": [ + [ + "runtime", + "spec.gateway.runtime is replaced by the key under spec.gateway.target: docker, podman, or kubernetes" + ], + [ + "engine", + "spec.gateway.engine moved to spec.gateway.target.docker.engine or spec.gateway.target.podman.engine" + ] + ] } ] }, @@ -870,9 +900,12 @@ "x-nemoclaw-error": "serviceRef excludes endpoint and credential and selects provider openai" }, "type": "object", - "x-nemoclaw-removed-fields": { - "name": "a provider's name is its key under inferenceProviders; only an inline route provider states name" - } + "x-nemoclaw-removed-fields": [ + [ + "name", + "a provider's name is its key under inferenceProviders; only an inline route provider states name" + ] + ] }, "InlineInferenceProvider": { "additionalProperties": false, @@ -1197,10 +1230,16 @@ } }, "type": "object", - "x-nemoclaw-removed-fields": { - "image": "spec.gateway.target.docker takes no image because the SDK pins the gateway image", - "networkCIDR": "spec.gateway.target.docker spells networkCIDR as networkCidr" - } + "x-nemoclaw-removed-fields": [ + [ + "image", + "spec.gateway.target.docker takes no image because the SDK pins the gateway image" + ], + [ + "networkCIDR", + "spec.gateway.target.docker spells networkCIDR as networkCidr" + ] + ] }, "ManagedKubernetes": { "additionalProperties": false, @@ -1412,10 +1451,16 @@ "engine" ], "type": "object", - "x-nemoclaw-removed-fields": { - "image": "spec.gateway.target.podman takes no image because the SDK pins the gateway image", - "networkCIDR": "spec.gateway.target.podman spells networkCIDR as networkCidr" - } + "x-nemoclaw-removed-fields": [ + [ + "image", + "spec.gateway.target.podman takes no image because the SDK pins the gateway image" + ], + [ + "networkCIDR", + "spec.gateway.target.podman spells networkCIDR as networkCidr" + ] + ] }, "ManagedTarget": { "description": "Exactly one target key: docker, podman, or kubernetes.", @@ -2541,9 +2586,12 @@ "agent" ], "type": "object", - "x-nemoclaw-removed-fields": { - "name": "a sandbox's name is its key under spec.sandboxes" - } + "x-nemoclaw-removed-fields": [ + [ + "name", + "a sandbox's name is its key under spec.sandboxes" + ] + ] }, "SearchProvider": { "description": "Search provider supported by the managed profile.", From 9319b75a1d7899004e54058acd63874b882ca2de Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Wed, 14 Oct 2026 07:10:47 +0000 Subject: [PATCH 9/9] test(config): find the Ollama proxy base example by path on Windows The retargeting test looked up `examples/managed-ollama.yaml` by string, but Windows renders the relative path with `\`, so the lookup failed and the Windows test job stopped. Compare paths instead. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Hai Nguyen --- crates/nemoclaw-sdk/tests/retargeting.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/nemoclaw-sdk/tests/retargeting.rs b/crates/nemoclaw-sdk/tests/retargeting.rs index 27d7617d71e..2bb30466edf 100644 --- a/crates/nemoclaw-sdk/tests/retargeting.rs +++ b/crates/nemoclaw-sdk/tests/retargeting.rs @@ -194,7 +194,10 @@ fn inputs() -> Vec<(String, Value)> { .collect(); let mut proxy = inputs .iter() - .find(|(name, _)| name == "examples/managed-ollama.yaml") + // Compare paths, not strings: Windows separates components with `\`. + .find(|(name, _)| { + std::path::Path::new(name) == std::path::Path::new("examples/managed-ollama.yaml") + }) .expect("the managed Ollama example") .1 .clone();