mecha10-behavior-runtime 2.0.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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! Validation for behavior tree configurations
//!
//! Ensures that behavior tree JSON is well-formed, matches the `schemars`-derived JSON Schema

use super::types::BehaviorConfig;
use crate::registry::NodeRegistry;
use anyhow::{anyhow, Result};
use mecha10_core::node::Capability;
use serde_json::Value;
use std::collections::HashSet;
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 `schemars`-derived
/// [`BehaviorConfig`] JSON Schema -- structural validation only, no [`NodeRegistry`] required.
/// Returns an error describing every schema violation found.
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 it against the real `BehaviorConfig` JSON
/// Schema (see [`validate_behavior_composition_json`]), that every leaf node's `node` type
/// exists in `registry`, and that every capability it declares via `requires_capabilities` is
/// present in `available_capabilities` -- rules a JSON Schema can't express on its own since
/// they cross-reference the live node registry / the project's other nodes.
///
/// `available_capabilities` is expected to be `ProjectConfig::aggregated_capabilities()` (the
/// union of every enabled node's declared capabilities) for the project this behavior is being
/// validated against.
pub fn validate_behavior_config(
    config: &Value,
    registry: &NodeRegistry,
    available_capabilities: &HashSet<Capability>,
) -> 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");
    }

    validate_required_capabilities(config, available_capabilities, &mut result);

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

    Ok(result)
}

/// Check that every capability this behavior declares via `requires_capabilities` is present in
/// `available_capabilities` -- a rule the JSON Schema alone can't express since it cross-
/// references another config (`ProjectConfig::aggregated_capabilities()`). An unsatisfied
/// requirement is a hard validation error naming the missing capability, not a warning.
fn validate_required_capabilities(
    config: &Value,
    available_capabilities: &HashSet<Capability>,
    result: &mut ValidationResult,
) {
    let Some(required) = config.get("requires_capabilities").and_then(|v| v.as_array()) else {
        return;
    };

    for value in required {
        // An unparseable/unknown capability value is already reported by schema validation
        // above; don't double-report it here.
        let Ok(capability) = serde_json::from_value::<Capability>(value.clone()) else {
            continue;
        };

        if !available_capabilities.contains(&capability) {
            result.add_error(format!(
                "Behavior requires capability '{}', which is not provided by any enabled node in this project. \
                 Add a node that declares this capability, or remove it from 'requires_capabilities'.",
                value.as_str().unwrap_or("<unknown>")
            ));
        }
    }
}

/// Walk the composition tree checking that every leaf node's `node` identifier is
/// registered in `registry` -- the one rule JSON Schema can't express. Skips anything schema
/// validation already reports (non-object nodes, missing/invalid `type`/`children`).
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, &HashSet::new()).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, &HashSet::new()).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, &HashSet::new()).unwrap();
        assert!(result.valid, "{:?}", result.errors);
    }

    /// A behavior with no `requires_capabilities` at all (the common case) must be unaffected
    /// by the capability check, regardless of what the project does or doesn't provide.
    #[test]
    fn test_validate_behavior_with_no_requires_capabilities_is_unaffected() {
        let registry = NodeRegistry::new();
        let config = json!({
            "name": "test",
            "root": {
                "type": "sequence",
                "children": []
            }
        });

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

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

        let available = HashSet::from([Capability::Locomotion]);
        let result = validate_behavior_config(&config, &registry, &available).unwrap();
        assert!(result.valid, "{:?}", result.errors);
    }

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

        // The project has no node providing "flight" -- e.g. just a locomotion node.
        let available = HashSet::from([Capability::Locomotion]);
        let result = validate_behavior_config(&config, &registry, &available).unwrap();
        assert!(!result.valid);
        assert!(
            result.errors.iter().any(|e| e.contains("flight")),
            "expected an error naming the missing 'flight' capability, got: {:?}",
            result.errors
        );
    }

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

        let available = HashSet::from([Capability::Locomotion]);
        let result = validate_behavior_config(&config, &registry, &available).unwrap();
        assert!(!result.valid);
        assert_eq!(result.errors.len(), 1, "{:?}", result.errors);
        assert!(result.errors[0].contains("flight"));
    }

    #[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, &HashSet::new()).unwrap();
        assert!(!result.valid);
        assert!(result.errors.iter().any(|e| e.contains("unknown_type")));
    }

    /// A leaf node shaped as `{"type": "<node_type>"}` never matches the real
    /// `BehaviorConfig`/`CompositionConfig` struct (its `Node` variant tags as `"type": "node"`
    /// with the actual identifier in a separate `node` field) and must be rejected.
    #[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, &HashSet::new()).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, &HashSet::new()).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, &HashSet::new()).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, &HashSet::new()).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, &HashSet::new()).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, &HashSet::new()).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, &HashSet::new()).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("tests/fixtures/seed_behaviors")
            .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"
        );
    }

    /// LAB-4831: `find_target` is the one true seed behavior for the rl node's find_target
    /// task - it must exist, must validate against the real `NodeRegistry` (not just the bare
    /// JSON Schema), must still wire up the live target-class override (`set_rl_target`), and
    /// there must be no separate `rl`/`find_target_dynamic` seed directory left behind for this
    /// concept to accidentally fork back into two configs.
    #[test]
    fn find_target_seed_behavior_is_the_sole_rl_task_config_and_keeps_the_live_target_override() {
        let seed_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/seed_behaviors")
            .canonicalize()
            .unwrap();

        assert!(
            !seed_dir.join("rl").exists(),
            "the old 'rl' seed behavior directory should have been folded into 'find_target'"
        );
        assert!(
            !seed_dir.join("find_target_dynamic").exists(),
            "find_target_dynamic should be folded into a single 'find_target' behavior, not kept alongside it"
        );

        let config_path = seed_dir.join("find_target/config.json");
        let content = std::fs::read_to_string(&config_path)
            .unwrap_or_else(|e| panic!("{} should exist: {}", config_path.display(), e));
        let value: Value = serde_json::from_str(&content).unwrap();

        assert_eq!(value["name"], "find_target");

        let mut registry = crate::NodeRegistry::new();
        crate::register_builtin_actions(&mut registry);
        let result = validate_behavior_config(&value, &registry, &HashSet::new()).unwrap();
        assert!(result.valid, "{:?}", result.errors);

        let serialized = content;
        assert!(
            serialized.contains("\"rl_task\""),
            "find_target should still hand control to the rl node via the rl_task node"
        );
        assert!(
            serialized.contains("\"set_rl_target\""),
            "find_target should still relay live dashboard target-class overrides via set_rl_target, \
             regardless of whether the rl node's own config.json selects onnx or act_torchscript"
        );
    }
}