mecha10-behavior-runtime 0.7.0

Behavior tree runtime for Mecha10 - unified AI and logic composition system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! Validation for behavior tree configurations
//!
//! Ensures that behavior tree JSON is well-formed and references valid node types.
//!
//! Structural validation runs against the real `schemars`-derived Draft-7 JSON
//! Schema for [`BehaviorConfig`] (the same schema `cargo run --example export_schemas`
//! renders to `schemas/behavior.schema.json`, see that command's own regression tests)
//! via the `jsonschema` crate -- the same
//! pattern `mecha10-schema-registry::validate_model_catalog_json` uses for
//! `model_catalog.toml` (see `docs/validate-configs.md`'s "Adding a new config
//! kind" section). The schema is derived in-process from [`BehaviorConfig`] itself
//! rather than read from that file at validation time, so the enforced schema can
//! never drift from the real struct -- same reasoning as
//! `mecha10-schema-registry`'s node/model-catalog schemas.
//!
//! On top of that structural check, [`validate_behavior_config`] also enforces one
//! rule JSON Schema can't express: every leaf node's `node` identifier must be
//! registered in a live [`NodeRegistry`] -- schema validation only knows it's a
//! string, not whether it's an actually-registered behavior node type.

use super::types::BehaviorConfig;
use crate::registry::NodeRegistry;
use anyhow::{anyhow, Result};
use serde_json::Value;
use std::sync::LazyLock;

static BEHAVIOR_CONFIG_SCHEMA: LazyLock<Value> = LazyLock::new(|| {
    let root_schema = schemars::schema_for!(BehaviorConfig);
    serde_json::to_value(root_schema).expect("schemars schema always serializes to JSON")
});

static BEHAVIOR_CONFIG_VALIDATOR: LazyLock<jsonschema::Validator> = LazyLock::new(|| {
    jsonschema::validator_for(&BEHAVIOR_CONFIG_SCHEMA).expect("BehaviorConfig schema is a valid JSON Schema")
});

#[derive(Debug, Clone)]
pub struct ValidationResult {
    pub valid: bool,
    pub errors: Vec<String>,
    pub warnings: Vec<String>,
}

impl ValidationResult {
    /// Create a successful validation result
    pub fn success() -> Self {
        Self {
            valid: true,
            errors: Vec::new(),
            warnings: Vec::new(),
        }
    }

    /// Create a failed validation result with errors
    pub fn with_errors(errors: Vec<String>) -> Self {
        Self {
            valid: false,
            errors,
            warnings: Vec::new(),
        }
    }

    /// Add a warning to the result
    pub fn add_warning(&mut self, warning: String) {
        self.warnings.push(warning);
    }

    /// Add an error to the result
    pub fn add_error(&mut self, error: String) {
        self.errors.push(error);
        self.valid = false;
    }
}

/// Validate a behavior composition JSON value against the real
/// `schemars`-derived [`BehaviorConfig`] JSON Schema -- structural validation only,
/// no [`NodeRegistry`] required. This is the piece [`validate_behavior_config`]
/// layers its registry-based node-type check on top of, and is also what
/// `mecha10 config validate --path <file>` calls directly for a standalone behavior
/// config file with no project/registry context available (see
/// `packages/cli/src/config_validation.rs`).
///
/// # Errors
///
/// Returns an error describing every schema violation found if `config` doesn't
/// match [`BehaviorConfig`]'s shape.
pub fn validate_behavior_composition_json(config: &Value) -> Result<()> {
    if !BEHAVIOR_CONFIG_VALIDATOR.is_valid(config) {
        let messages: Vec<String> = BEHAVIOR_CONFIG_VALIDATOR
            .iter_errors(config)
            .map(|e| format!("  - {}: {} ({})", e.instance_path(), e, e.instance()))
            .collect();
        return Err(anyhow!(
            "Behavior config schema validation failed:\n{}",
            messages.join("\n")
        ));
    }

    Ok(())
}

/// Validate a behavior tree configuration
///
/// Checks:
/// - The config matches the real `BehaviorConfig` JSON Schema (required fields,
///   composition node shapes, etc.) -- see [`validate_behavior_composition_json`].
/// - Every leaf node's `node` type exists in `registry` -- a rule JSON Schema can't
///   express, since it depends on which behavior nodes are registered at runtime.
///
/// # Arguments
///
/// * `config` - Behavior tree configuration JSON
/// * `registry` - Node registry for validating node types
///
/// # Example
///
/// ```rust,ignore
/// use mecha10_behavior_runtime::config::validate_behavior_config;
/// use mecha10_behavior_runtime::NodeRegistry;
///
/// let registry = NodeRegistry::new();
/// let config = serde_json::json!({
///     "name": "test_behavior",
///     "root": {
///         "type": "sequence",
///         "children": []
///     }
/// });
///
/// let result = validate_behavior_config(&config, &registry)?;
/// assert!(result.valid);
/// ```
pub fn validate_behavior_config(config: &Value, registry: &NodeRegistry) -> Result<ValidationResult> {
    let mut result = ValidationResult::success();

    if let Err(schema_err) = validate_behavior_composition_json(config) {
        result.add_error(schema_err.to_string());
    }

    if let Some(root) = config.get("root") {
        validate_node_types(root, registry, &mut result, "root");
    }

    if config.get("$schema").is_none() {
        result
            .add_warning("No '$schema' field found. Consider adding schema reference for IDE validation.".to_string());
    }

    Ok(result)
}

/// Walk the composition tree checking that every leaf node's `node` identifier is
/// registered in `registry` -- the one rule JSON Schema can't express (it doesn't
/// know what's registered at runtime). Skips anything schema validation already
/// reports (non-object nodes, missing/invalid `type`/`children`) rather than
/// duplicating those structural checks here.
fn validate_node_types(node: &Value, registry: &NodeRegistry, result: &mut ValidationResult, path: &str) {
    let Some(obj) = node.as_object() else {
        return;
    };

    let Some(node_type) = obj.get("type").and_then(|v| v.as_str()) else {
        return;
    };

    match node_type {
        "node" => {
            if let Some(node_name) = obj.get("node").and_then(|v| v.as_str()) {
                if !registry.has_node(node_name) {
                    result.add_error(format!(
                        "Node at '{}' has unknown type '{}'. Register this node type or check for typos.",
                        path, node_name
                    ));
                }
            }
        }
        "sequence" | "selector" | "parallel" | "watch" => {
            if let Some(children) = obj.get("children").and_then(|v| v.as_array()) {
                if children.is_empty() {
                    result.add_warning(format!(
                        "Composition node at '{}' has no children (will immediately return success/failure)",
                        path
                    ));
                }

                for (i, child) in children.iter().enumerate() {
                    let child_path = format!("{}.children[{}]", path, i);
                    validate_node_types(child, registry, result, &child_path);
                }
            }
        }
        "inverter" | "force_success" | "force_failure" | "repeat" | "retry" | "timeout" => {
            if let Some(child) = obj.get("child") {
                let child_path = format!("{}.child", path);
                validate_node_types(child, registry, result, &child_path);
            }
        }
        "subsumption" => {
            if let Some(layers) = obj.get("layers").and_then(|v| v.as_array()) {
                if layers.is_empty() {
                    result.add_warning(format!(
                        "Subsumption node at '{}' has no layers (will immediately return failure)",
                        path
                    ));
                }

                for (i, layer) in layers.iter().enumerate() {
                    if let Some(node) = layer.get("node") {
                        let child_path = format!("{}.layers[{}].node", path, i);
                        validate_node_types(node, registry, result, &child_path);
                    }
                }
            }
        }
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::NodeRegistry;
    use serde_json::json;

    #[test]
    fn test_validate_missing_name() {
        let registry = NodeRegistry::new();
        let config = json!({
            "root": {
                "type": "sequence",
                "children": []
            }
        });

        let result = validate_behavior_config(&config, &registry).unwrap();
        assert!(!result.valid);
        assert!(result.errors.iter().any(|e| e.contains("name")));
    }

    #[test]
    fn test_validate_missing_root() {
        let registry = NodeRegistry::new();
        let config = json!({
            "name": "test"
        });

        let result = validate_behavior_config(&config, &registry).unwrap();
        assert!(!result.valid);
        assert!(result.errors.iter().any(|e| e.contains("root")));
    }

    #[test]
    fn test_validate_valid_config() {
        let registry = NodeRegistry::new();
        let config = json!({
            "name": "test",
            "root": {
                "type": "sequence",
                "children": []
            }
        });

        let result = validate_behavior_config(&config, &registry).unwrap();
        assert!(result.valid, "{:?}", result.errors);
    }

    #[test]
    fn test_validate_unknown_node_type() {
        let registry = NodeRegistry::new();
        let config = json!({
            "name": "test",
            "root": {
                "type": "node",
                "node": "unknown_type"
            }
        });

        let result = validate_behavior_config(&config, &registry).unwrap();
        assert!(!result.valid);
        assert!(result.errors.iter().any(|e| e.contains("unknown_type")));
    }

    /// LAB-2054: before this, the hand-rolled validator accepted a leaf node shaped
    /// as `{"type": "<node_type>"}` directly -- a shape that never matched the real
    /// `BehaviorConfig`/`CompositionConfig` struct at all (its `Node` variant tags
    /// as `"type": "node"` with the actual identifier in a separate `node` field,
    /// per `#[serde(tag = "type")]`). Real schema enforcement must reject it.
    #[test]
    fn test_validate_rejects_legacy_leaf_shape_that_never_matched_the_real_struct() {
        let registry = NodeRegistry::new();
        let config = json!({
            "name": "test",
            "root": {
                "type": "wander",
                "config": {}
            }
        });

        let result = validate_behavior_config(&config, &registry).unwrap();
        assert!(!result.valid);
    }

    #[test]
    fn test_validate_valid_leaf_node_config() {
        let mut registry = NodeRegistry::new();
        crate::register_builtin_actions(&mut registry);

        let config = json!({
            "name": "test",
            "root": {
                "type": "node",
                "node": "wander",
                "config": { "speed": 0.5 }
            }
        });

        let result = validate_behavior_config(&config, &registry).unwrap();
        assert!(result.valid, "{:?}", result.errors);
    }

    #[test]
    fn test_validate_empty_children_warns() {
        let registry = NodeRegistry::new();
        let config = json!({
            "name": "test",
            "root": {
                "type": "sequence",
                "children": []
            }
        });

        let result = validate_behavior_config(&config, &registry).unwrap();
        assert!(result.valid);
        assert!(result.warnings.iter().any(|w| w.contains("no children")));
    }

    #[test]
    fn test_validate_watch_recurses_into_children_like_parallel() {
        let registry = NodeRegistry::new();
        let config = json!({
            "name": "test",
            "root": {
                "type": "watch",
                "policy": "require_one",
                "children": [
                    { "type": "node", "node": "unknown_type" }
                ]
            }
        });

        let result = validate_behavior_config(&config, &registry).unwrap();
        assert!(!result.valid);
        assert!(result.errors.iter().any(|e| e.contains("unknown_type")));
    }

    #[test]
    fn test_validate_subsumption_recurses_into_layer_nodes() {
        let registry = NodeRegistry::new();
        let config = json!({
            "name": "test",
            "root": {
                "type": "subsumption",
                "layers": [
                    { "priority": 10, "node": { "type": "node", "node": "unknown_type" } },
                    { "priority": 0, "node": { "type": "sequence", "children": [] } }
                ]
            }
        });

        let result = validate_behavior_config(&config, &registry).unwrap();
        assert!(!result.valid);
        assert!(result.errors.iter().any(|e| e.contains("unknown_type")));
    }

    #[test]
    fn test_validate_decorator_recurses_into_child() {
        let registry = NodeRegistry::new();
        for decorator_type in [
            "inverter",
            "force_success",
            "force_failure",
            "repeat",
            "retry",
            "timeout",
        ] {
            let config = json!({
                "name": "test",
                "root": {
                    "type": decorator_type,
                    "max_attempts": 1,
                    "timeout_secs": 1.0,
                    "child": { "type": "node", "node": "unknown_type" }
                }
            });

            let result = validate_behavior_config(&config, &registry).unwrap();
            assert!(
                result.errors.iter().any(|e| e.contains("unknown_type")),
                "decorator '{}' should recurse into its child: {:?}",
                decorator_type,
                result.errors
            );
        }
    }

    #[test]
    fn test_validate_subsumption_empty_layers_warns() {
        let registry = NodeRegistry::new();
        let config = json!({
            "name": "test",
            "root": {
                "type": "subsumption",
                "layers": []
            }
        });

        let result = validate_behavior_config(&config, &registry).unwrap();
        assert!(result.valid);
        assert!(result.warnings.iter().any(|w| w.contains("no layers")));
    }

    #[test]
    fn validate_behavior_composition_json_rejects_non_object() {
        assert!(validate_behavior_composition_json(&json!("not an object")).is_err());
    }

    #[test]
    fn validate_behavior_composition_json_rejects_wrong_children_type() {
        let config = json!({
            "name": "test",
            "root": {
                "type": "sequence",
                "children": "not an array"
            }
        });

        assert!(validate_behavior_composition_json(&config).is_err());
    }

    #[test]
    fn validate_behavior_composition_json_accepts_the_real_repo_seed_templates() {
        let templates_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../mecha10-templates/templates/configs/behaviors/@mecha10")
            .canonicalize()
            .unwrap();

        let mut checked = 0;
        for entry in std::fs::read_dir(&templates_dir).unwrap() {
            let config_path = entry.unwrap().path().join("config.json");
            if !config_path.is_file() {
                continue;
            }
            let content = std::fs::read_to_string(&config_path).unwrap();
            let value: Value = serde_json::from_str(&content).unwrap();
            assert!(
                validate_behavior_composition_json(&value).is_ok(),
                "{} should validate against the real BehaviorConfig schema",
                config_path.display()
            );
            checked += 1;
        }
        assert!(
            checked > 0,
            "expected at least one seed behavior config template to check"
        );
    }
}