mecha10-behavior-runtime 0.9.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
//! 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 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 `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`]), and that every leaf node's `node` type
/// exists in `registry` (a rule JSON Schema can't express).
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. 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).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")));
    }

    /// 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).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("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"
        );
    }
}