mecha10-cli 0.8.0

Mecha10 CLI tool
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
//! Wires per-node-type and model-catalog schemas into the config-validation entry point
//! `mecha10 config validate`/`mecha10 lint`/`mecha10 build` share.
//!
//! `mecha10_core::schema_validation`'s generic functions and `ConfigService::resolve_and_validate`
//! are untouched by this module -- it's a thin dispatcher on top, not a reimplementation.

use anyhow::Result;
use std::path::{Path, PathBuf};

use crate::services::ConfigService;

/// Validate `path` (or, when `None`, the project's `mecha10.json` plus every node config it
/// references) the same way `mecha10 config validate` does.
///
/// `schemas_dir` is `configs/simulation/schemas` under a freshly-fetched `mecha10-assets`
/// extraction (see `mecha10_templates::services::assets_download::AssetsDownloadService`) --
/// required (as `Some`) when `path` is `None` and the project actually has a
/// `configs/simulation/environments/` directory (see [`needs_environment_schema`]), since that
/// branch then validates every `environment.json` under it. Callers that already know the
/// project has no environment configs can skip the `mecha10-assets` fetch and pass `None`.
///
/// # Errors
///
/// Returns an error with the underlying schema-validation failure details if the
/// target file doesn't exist or fails validation.
pub fn validate_config(path: Option<&Path>, schemas_dir: Option<&Path>) -> Result<PathBuf> {
    if let Some(p) = path {
        if is_model_catalog_file(p) {
            validate_model_catalog_file(p)
                .map_err(|e| anyhow::anyhow!("Configuration validation failed for {}: {}", p.display(), e))?;
            return Ok(p.to_path_buf());
        }

        if is_behavior_config_file(p) {
            let content = std::fs::read_to_string(p)
                .map_err(|e| anyhow::anyhow!("Failed to read behavior config file {}: {}", p.display(), e))?;
            let value: serde_json::Value = serde_json::from_str(&content)
                .map_err(|e| anyhow::anyhow!("Failed to parse JSON from {}: {}", p.display(), e))?;
            mecha10_behavior_runtime::config::validate_behavior_composition_json(&value)
                .map_err(|e| anyhow::anyhow!("Configuration validation failed for {}: {}", p.display(), e))?;
            return Ok(p.to_path_buf());
        }
    }

    let target = ConfigService::resolve_and_validate(path)?;

    if path.is_none() {
        let project_root = target.parent().unwrap_or_else(|| Path::new("."));
        validate_environment_configs(project_root, schemas_dir)?;
        validate_active_behavior_tree_config(project_root)?;
        validate_rl_job_configs(project_root)?;
    }

    Ok(target)
}

/// Whether `project_root` has a `configs/simulation/environments/` directory -- i.e. whether
/// [`validate_config`]/[`validate_configs`] (with [`ConfigKind::SimulationEnvironments`]) will
/// actually need a `schemas_dir` to validate anything, so callers can skip the `mecha10-assets`
/// fetch entirely for a project with no environment configs. Cheap and synchronous: just a
/// directory-existence check, no network.
pub fn needs_environment_schema(project_root: &Path) -> bool {
    project_root
        .join(mecha10_cli_core::paths::project::SIMULATION_ENVIRONMENTS_DIR)
        .exists()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ConfigKind {
    ProjectAndNodes,
    ModelCatalog,
    SimulationEnvironments,
    ActiveBehaviorTree,
    RlJobs,
}

impl ConfigKind {
    pub const ALL: &'static [ConfigKind] = &[
        ConfigKind::ProjectAndNodes,
        ConfigKind::ModelCatalog,
        ConfigKind::SimulationEnvironments,
        ConfigKind::ActiveBehaviorTree,
        ConfigKind::RlJobs,
    ];
}

/// Validate `kinds` for the project rooted at `project_root` (the directory containing
/// `mecha10.json`), collecting every failure across every kind into one combined error
/// instead of stopping at the first problem.
///
/// `schemas_dir` is `configs/simulation/schemas` under a freshly-fetched `mecha10-assets`
/// extraction -- required (as `Some`) when `kinds` includes [`ConfigKind::SimulationEnvironments`];
/// pass `None` when it doesn't, to skip the fetch entirely.
///
/// # Errors
///
/// Returns a single combined error listing every failing file/kind, if any `kinds` entry
/// fails validation.
pub fn validate_configs(project_root: &Path, kinds: &[ConfigKind], schemas_dir: Option<&Path>) -> Result<()> {
    let mut failures: Vec<String> = Vec::new();

    for kind in kinds {
        let result = match kind {
            ConfigKind::ProjectAndNodes => {
                let project_path = project_root.join(mecha10_cli_core::paths::PROJECT_CONFIG);
                ConfigService::resolve_and_validate(Some(&project_path)).map(|_| ())
            }
            ConfigKind::ModelCatalog => validate_model_catalog_if_present(project_root),
            ConfigKind::SimulationEnvironments => validate_environment_configs(project_root, schemas_dir),
            ConfigKind::ActiveBehaviorTree => validate_active_behavior_tree_config(project_root),
            ConfigKind::RlJobs => validate_rl_job_configs(project_root),
        };

        if let Err(e) = result {
            failures.push(format!("{:#}", e));
        }
    }

    if failures.is_empty() {
        Ok(())
    } else {
        Err(anyhow::anyhow!(
            "Config validation failed ({} problem{}):\n\n{}",
            failures.len(),
            if failures.len() == 1 { "" } else { "s" },
            failures.join("\n\n")
        ))
    }
}

/// Validate `model_catalog.toml` at this project's conventional locations, if present. See
/// [`ConfigKind::ModelCatalog`] for why there are two candidate locations and why neither
/// existing is not an error.
fn validate_model_catalog_if_present(project_root: &Path) -> Result<()> {
    for candidate in [
        project_root.join("model_catalog.toml"),
        project_root.join("configs").join("model_catalog.toml"),
    ] {
        if candidate.exists() {
            validate_model_catalog_file(&candidate)
                .map_err(|e| anyhow::anyhow!("Configuration validation failed for {}: {}", candidate.display(), e))?;
        }
    }
    Ok(())
}

/// Validate every `configs/simulation/environments/*/environment.json`, if any exist,
/// against the `environment.schema.json` schema. `schemas_dir` must be `Some` if any
/// `environment.json` is actually found (the short-circuit above never needs it, so a project
/// with no `configs/simulation/environments/` directory validates fine with `None`).
fn validate_environment_configs(project_root: &Path, schemas_dir: Option<&Path>) -> Result<()> {
    let environments_dir = project_root.join(mecha10_cli_core::paths::project::SIMULATION_ENVIRONMENTS_DIR);
    if !environments_dir.exists() {
        return Ok(());
    }

    let mut errors = Vec::new();

    let mut entries: Vec<_> = std::fs::read_dir(&environments_dir)
        .map_err(|e| anyhow::anyhow!("Failed to read {}: {}", environments_dir.display(), e))?
        .filter_map(|e| e.ok())
        .collect();
    entries.sort_by_key(std::fs::DirEntry::path);

    for entry in entries {
        let env_dir = entry.path();
        if !env_dir.is_dir() {
            continue;
        }

        let env_json = env_dir.join("environment.json");
        if !env_json.exists() {
            continue;
        }

        if let Err(e) = validate_one_environment_config(&env_json, schemas_dir) {
            errors.push(e.to_string());
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(anyhow::anyhow!(errors.join("\n\n")))
    }
}

fn validate_one_environment_config(path: &Path, schemas_dir: Option<&Path>) -> Result<()> {
    let schemas_dir = schemas_dir.ok_or_else(|| {
        anyhow::anyhow!(
            "No mecha10-assets schemas directory available to validate {} against",
            path.display()
        )
    })?;
    let content = std::fs::read_to_string(path)
        .map_err(|e| anyhow::anyhow!("Failed to read environment config {}: {}", path.display(), e))?;
    let value: serde_json::Value = serde_json::from_str(&content)
        .map_err(|e| anyhow::anyhow!("Failed to parse JSON from {}: {}", path.display(), e))?;
    mecha10_schema_registry::validate_environment_config_json(&value, schemas_dir)
        .map_err(|e| anyhow::anyhow!("Configuration validation failed for {}: {}", path.display(), e))
}

/// Validate the behavior-tree config selected by `mecha10.json`'s `behaviors.active`, if the
/// project declares one.
fn validate_active_behavior_tree_config(project_root: &Path) -> Result<()> {
    let project_path = project_root.join(mecha10_cli_core::paths::PROJECT_CONFIG);
    if !project_path.exists() {
        return Ok(());
    }

    let content = std::fs::read_to_string(&project_path)
        .map_err(|e| anyhow::anyhow!("Failed to read {}: {}", project_path.display(), e))?;
    let value: serde_json::Value = serde_json::from_str(&content)
        .map_err(|e| anyhow::anyhow!("Failed to parse JSON from {}: {}", project_path.display(), e))?;

    let Some(active) = value
        .get("behaviors")
        .and_then(|b| b.get("active"))
        .and_then(|a| a.as_str())
    else {
        return Ok(());
    };

    let config_path = mecha10_behavior_runtime::resolve_behavior_config_path(active, project_root)
        .map_err(|e| anyhow::anyhow!("Configuration validation failed for behaviors.active '{active}': {e}"))?;

    let content = std::fs::read_to_string(&config_path)
        .map_err(|e| anyhow::anyhow!("Failed to read behavior config {}: {}", config_path.display(), e))?;
    let behavior_value: serde_json::Value = serde_json::from_str(&content)
        .map_err(|e| anyhow::anyhow!("Failed to parse JSON from {}: {}", config_path.display(), e))?;
    mecha10_behavior_runtime::validate_behavior_composition_json(&behavior_value)
        .map_err(|e| anyhow::anyhow!("Configuration validation failed for {}: {}", config_path.display(), e))
}

/// Validate every `configs/rl/jobs/*.yml` job definition, if the project has any.
/// `load_job_catalog` already parses each file into `JobDefinition`, so a malformed
/// or schema-invalid job surfaces as a deserialization error here.
fn validate_rl_job_configs(project_root: &Path) -> Result<()> {
    crate::services::load_job_catalog(project_root)
        .map_err(|e| anyhow::anyhow!("Configuration validation failed for RL job configs: {:#}", e))?;
    Ok(())
}

/// Validate a `model_catalog.toml` file on disk: schema (via [`model_catalog_schema`]) plus
/// the `name`-uniqueness rule JSON Schema can't express.
///
/// # Errors
///
/// Returns an error if the file can't be read/parsed as TOML, fails schema validation, or has
/// a duplicate `name` across entries.
fn validate_model_catalog_file(path: &Path) -> Result<()> {
    let content = std::fs::read_to_string(path)
        .map_err(|e| anyhow::anyhow!("Failed to read model catalog file {}: {}", path.display(), e))?;

    let toml_value: toml::Value =
        toml::from_str(&content).map_err(|e| anyhow::anyhow!("Failed to parse TOML from {}: {}", path.display(), e))?;

    let json_value = serde_json::to_value(toml_value)
        .map_err(|e| anyhow::anyhow!("Failed to convert TOML from {}: {}", path.display(), e))?;

    validate_model_catalog_json(&json_value).map_err(|e| anyhow::anyhow!("{}: {}", path.display(), e))
}

/// Validate an already-parsed model catalog JSON value: schema plus the `name`-uniqueness
/// custom rule. See [`validate_model_catalog_file`].
fn validate_model_catalog_json(value: &serde_json::Value) -> Result<()> {
    validate_json_against_schema(value, &model_catalog_schema(), "Model catalog")?;
    validate_unique_model_names(value)?;
    Ok(())
}

/// The `schemars`-derived JSON Schema for `model_catalog.toml`'s shape: a top-level `models`
/// array of `ModelCatalogEntry`.
fn model_catalog_schema() -> serde_json::Value {
    let generator = schemars::SchemaGenerator::default();
    let root_schema = generator.into_root_schema_for::<mecha10_models::services::model_service::ModelCatalogEntry>();
    let mut entry_schema = serde_json::to_value(root_schema).expect("schemars Schema always serializes to JSON");

    let definitions = entry_schema.as_object_mut().and_then(|obj| obj.remove("$defs"));

    if let Some(obj) = entry_schema.as_object_mut() {
        obj.remove("$schema");
    }

    let mut schema = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "$id": "https://mecha10.dev/schemas/model-catalog.schema.json",
        "title": "Mecha10 Model Catalog",
        "description": "Schema for model_catalog.toml, the mecha10-models model catalog",
        "type": "object",
        "required": ["models"],
        "properties": {
            "models": {
                "type": "array",
                "items": entry_schema
            }
        }
    });

    if let Some(definitions) = definitions {
        schema["$defs"] = definitions;
    }

    schema
}

/// Rule JSON Schema can't express: every catalog entry's `name` must be unique.
fn validate_unique_model_names(value: &serde_json::Value) -> Result<()> {
    let Some(models) = value.get("models").and_then(serde_json::Value::as_array) else {
        return Ok(());
    };

    let mut seen = std::collections::HashSet::new();
    for model in models {
        if let Some(name) = model.get("name").and_then(serde_json::Value::as_str) {
            if !seen.insert(name.to_string()) {
                anyhow::bail!(
                    "Duplicate model name '{}' found. Model catalog entry names must be unique.",
                    name
                );
            }
        }
    }

    Ok(())
}

/// Validate an already-parsed `preset.json` value against
/// `mecha10_schema_registry::preset_config_schema`. `schemas_dir` is `configs/simulation/schemas`
/// under a freshly-fetched `mecha10-assets` extraction.
pub fn validate_preset_config_json(value: &serde_json::Value, schemas_dir: &Path) -> Result<()> {
    mecha10_schema_registry::validate_preset_config_json(value, schemas_dir)
}

/// Validate `value` against `schema`, formatting every failure into one combined error
/// prefixed by `context` (e.g. `"Model catalog"`) -- shared by every schema kind this module
/// validates directly (environment/preset configs delegate to `mecha10_schema_registry`'s own
/// copy of this instead).
fn validate_json_against_schema(value: &serde_json::Value, schema: &serde_json::Value, context: &str) -> Result<()> {
    let validator = jsonschema::options()
        .with_draft(jsonschema::Draft::Draft7)
        .build(schema)
        .map_err(|e| anyhow::anyhow!("Invalid {context} schema: {e}"))?;

    if !validator.is_valid(value) {
        let messages: Vec<String> = validator
            .iter_errors(value)
            .map(|e| format!("  - {}: {} ({})", e.instance_path(), e, e.instance()))
            .collect();
        anyhow::bail!("{context} schema validation failed:\n{}", messages.join("\n"));
    }

    Ok(())
}

/// Whether `path`'s filename is `model_catalog.toml`.
fn is_model_catalog_file(path: &Path) -> bool {
    path.file_name().and_then(|n| n.to_str()) == Some("model_catalog.toml")
}

/// Whether `path` is a behavior composition file: a file named `config.json` somewhere
/// under a `behaviors/` directory.
fn is_behavior_config_file(path: &Path) -> bool {
    if path.file_name().and_then(|n| n.to_str()) != Some("config.json") {
        return false;
    }
    path.components().any(|c| c.as_os_str().to_str() == Some("behaviors"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    /// The vendored copy of `configs/simulation/schemas/` under this crate's `tests/fixtures/`,
    /// standing in for a freshly-fetched `mecha10-assets` extraction so these tests don't need
    /// network access.
    fn schemas_dir() -> std::path::PathBuf {
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/schemas")
    }

    #[test]
    fn validate_config_validates_a_valid_model_catalog_file() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("model_catalog.toml");
        fs::write(
            &path,
            r#"
[[models]]
name = "yolov8n"
description = "YOLOv8 Nano"
task = "object-detection"
repo = "some/repo"
filename = "model.onnx"
"#,
        )
        .unwrap();

        let result = validate_config(Some(&path), Some(&schemas_dir()));
        assert!(result.is_ok(), "{:?}", result.err());
        assert_eq!(result.unwrap(), path);
    }

    #[test]
    fn validate_config_rejects_an_invalid_model_catalog_file() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("model_catalog.toml");
        fs::write(&path, "[[models]]\nname = \"bad\"\ndescription = \"d\"\n").unwrap();

        assert!(validate_config(Some(&path), Some(&schemas_dir())).is_err());
    }

    #[test]
    fn validate_config_rejects_duplicate_model_names() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("model_catalog.toml");
        fs::write(
            &path,
            r#"
[[models]]
name = "dup"
description = "d1"
task = "object-detection"
repo = "r"
filename = "f.onnx"

[[models]]
name = "dup"
description = "d2"
task = "object-detection"
repo = "r"
filename = "f2.onnx"
"#,
        )
        .unwrap();

        let err = validate_config(Some(&path), Some(&schemas_dir())).unwrap_err();
        assert!(err.to_string().to_lowercase().contains("duplicate"));
    }

    /// A built-in node type's config is checked against its specific `<name>.schema.json` file,
    /// the same lookup a custom node already uses.
    #[test]
    fn validate_config_resolves_a_built_in_node_type_via_its_shipped_schema_file() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("config")).unwrap();
        fs::write(
            dir.path().join("config/behavior.json"),
            serde_json::json!({"custom": {}}).to_string(),
        )
        .unwrap();

        let node_dir = dir.path().join("nodes/behavior");
        fs::create_dir_all(&node_dir).unwrap();
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "relay_topics": { "type": "array", "items": { "type": "string" } },
                "custom": {
                    "type": "object",
                    "properties": {
                        "behavior_name": { "type": "string" }
                    },
                    "required": ["behavior_name"],
                    "additionalProperties": false
                }
            },
            "additionalProperties": false
        });
        fs::write(
            node_dir.join("behavior_executor.schema.json"),
            serde_json::to_string(&schema).unwrap(),
        )
        .unwrap();

        let project_path = dir.path().join("mecha10.json");
        fs::write(
            &project_path,
            serde_json::json!({
                "name": "proj",
                "version": "1.0.0",
                "nodes": {
                    "custom": [
                        {"name": "behavior_executor", "path": "./nodes/behavior", "config": "./config/behavior.json"}
                    ]
                }
            })
            .to_string(),
        )
        .unwrap();

        let err = validate_config(Some(&project_path), Some(&schemas_dir())).unwrap_err();
        assert!(
            err.to_string().to_lowercase().contains("behavior_name"),
            "expected the specific BehaviorExecutorConfig schema error, got: {}",
            err
        );
    }

    /// A project config using the old top-level `logging` block must fail validation
    /// with a message pointing at the new per-environment shape.
    #[test]
    fn validate_config_rejects_legacy_top_level_logging_block() {
        let dir = tempdir().unwrap();
        let project_path = dir.path().join("mecha10.json");
        fs::write(
            &project_path,
            serde_json::json!({
                "name": "proj",
                "version": "1.0.0",
                "logging": { "disk_logging_enabled": false }
            })
            .to_string(),
        )
        .unwrap();

        let err = validate_config(Some(&project_path), Some(&schemas_dir())).unwrap_err();
        assert!(
            err.to_string().contains("environments.<env>.logging"),
            "expected the error to point at the new per-environment shape, got: {}",
            err
        );
    }

    /// An unrecognized (custom/third-party) node type resolves its declared schema via a
    /// `<name>.schema.json` file shipped alongside its source, same as a built-in type.
    #[test]
    fn validate_config_resolves_a_custom_schema_file_for_an_unrecognized_node_type() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("config")).unwrap();
        fs::write(
            dir.path().join("config/custom.json"),
            serde_json::json!({"id": "custom_node", "executable": "./bin/custom"}).to_string(),
        )
        .unwrap();
        fs::create_dir_all(dir.path().join("nodes/custom")).unwrap();
        fs::write(
            dir.path().join("nodes/custom/my_totally_custom_node.schema.json"),
            serde_json::json!({
                "type": "object",
                "required": ["id", "executable"],
                "properties": {
                    "id": {"type": "string"},
                    "executable": {"type": "string"}
                }
            })
            .to_string(),
        )
        .unwrap();

        let project_path = dir.path().join("mecha10.json");
        fs::write(
            &project_path,
            serde_json::json!({
                "name": "proj",
                "version": "1.0.0",
                "nodes": {
                    "custom": [
                        {"name": "my_totally_custom_node", "path": "./nodes/custom", "config": "./config/custom.json"}
                    ]
                }
            })
            .to_string(),
        )
        .unwrap();

        assert!(validate_config(Some(&project_path), Some(&schemas_dir())).is_ok());
    }

    /// LAB-4066: an unrecognized node type with no `<name>.schema.json` shipped alongside it
    /// is a hard validation error naming the node, not a silent pass.
    #[test]
    fn validate_config_errors_when_an_unrecognized_node_type_has_no_declared_schema() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("config")).unwrap();
        fs::write(
            dir.path().join("config/custom.json"),
            serde_json::json!({"id": "custom_node", "executable": "./bin/custom"}).to_string(),
        )
        .unwrap();

        let project_path = dir.path().join("mecha10.json");
        fs::write(
            &project_path,
            serde_json::json!({
                "name": "proj",
                "version": "1.0.0",
                "nodes": {
                    "custom": [
                        {"name": "my_totally_custom_node", "path": "./nodes/custom", "config": "./config/custom.json"}
                    ]
                }
            })
            .to_string(),
        )
        .unwrap();

        let err = validate_config(Some(&project_path), Some(&schemas_dir())).unwrap_err();
        assert!(
            err.to_string().contains("no declared schema"),
            "expected a hard error naming the missing declared schema, got: {}",
            err
        );
    }

    #[test]
    fn validate_rl_job_configs_ok_when_no_jobs_directory_present() {
        let dir = tempdir().unwrap();
        assert!(validate_rl_job_configs(dir.path()).is_ok());
    }

    #[test]
    fn validate_rl_job_configs_rejects_a_malformed_job_definition() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("configs/rl/jobs")).unwrap();
        fs::write(
            dir.path().join("configs/rl/jobs/broken.yml"),
            "not: [valid, job, definition",
        )
        .unwrap();

        assert!(validate_rl_job_configs(dir.path()).is_err());
    }

    fn valid_environment_json() -> serde_json::Value {
        serde_json::json!({
            "id": "basic_arena",
            "version": "1.0.0",
            "name": "Basic Arena",
            "description": "A test arena",
            "scene_path": "res://basic_arena.tscn",
            "dimensions": {"width": 20.0, "length": 20.0, "height": 3.0, "unit": "meters"},
            "features": {}
        })
    }

    #[test]
    fn validate_environment_configs_ok_when_no_environments_directory_present() {
        let dir = tempdir().unwrap();
        assert!(validate_environment_configs(dir.path(), Some(&schemas_dir())).is_ok());
    }

    #[test]
    fn validate_environment_configs_accepts_a_valid_environment() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("configs/simulation/environments/basic_arena")).unwrap();
        fs::write(
            dir.path()
                .join("configs/simulation/environments/basic_arena/environment.json"),
            valid_environment_json().to_string(),
        )
        .unwrap();

        assert!(validate_environment_configs(dir.path(), Some(&schemas_dir())).is_ok());
    }

    #[test]
    fn validate_environment_configs_rejects_a_config_missing_required_fields() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("configs/simulation/environments/broken_env")).unwrap();
        fs::write(
            dir.path()
                .join("configs/simulation/environments/broken_env/environment.json"),
            serde_json::json!({"id": "broken_env"}).to_string(),
        )
        .unwrap();

        let err = validate_environment_configs(dir.path(), Some(&schemas_dir())).unwrap_err();
        assert!(err.to_string().contains("broken_env"), "{err}");
    }

    #[test]
    fn validate_environment_configs_reports_every_invalid_environment_not_just_the_first() {
        let dir = tempdir().unwrap();
        for name in ["env_a", "env_b"] {
            fs::create_dir_all(dir.path().join("configs/simulation/environments").join(name)).unwrap();
            fs::write(
                dir.path()
                    .join("configs/simulation/environments")
                    .join(name)
                    .join("environment.json"),
                serde_json::json!({}).to_string(),
            )
            .unwrap();
        }

        let err = validate_environment_configs(dir.path(), Some(&schemas_dir()))
            .unwrap_err()
            .to_string();
        assert!(err.contains("env_a"), "{err}");
        assert!(err.contains("env_b"), "{err}");
    }

    #[test]
    fn validate_environment_configs_rejects_a_config_missing_scene_path() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("configs/simulation/environments/broken_env")).unwrap();
        let mut value = valid_environment_json();
        value.as_object_mut().unwrap().remove("scene_path");
        fs::write(
            dir.path()
                .join("configs/simulation/environments/broken_env/environment.json"),
            value.to_string(),
        )
        .unwrap();

        let err = validate_environment_configs(dir.path(), Some(&schemas_dir()))
            .unwrap_err()
            .to_string();
        assert!(err.contains("scene_path"), "{err}");
    }

    #[test]
    fn validate_environment_configs_rejects_a_config_missing_dimensions() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("configs/simulation/environments/broken_env")).unwrap();
        let mut value = valid_environment_json();
        value.as_object_mut().unwrap().remove("dimensions");
        fs::write(
            dir.path()
                .join("configs/simulation/environments/broken_env/environment.json"),
            value.to_string(),
        )
        .unwrap();

        let err = validate_environment_configs(dir.path(), Some(&schemas_dir()))
            .unwrap_err()
            .to_string();
        assert!(err.contains("dimensions"), "{err}");
    }

    #[test]
    fn validate_environment_configs_rejects_a_malformed_features_subfield() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("configs/simulation/environments/broken_env")).unwrap();
        let mut value = valid_environment_json();
        value["features"]["floor"] = serde_json::json!({
            "type": "flat",
            "material": "concrete",
            "friction": 0.8
        });
        fs::write(
            dir.path()
                .join("configs/simulation/environments/broken_env/environment.json"),
            value.to_string(),
        )
        .unwrap();

        let err = validate_environment_configs(dir.path(), Some(&schemas_dir()))
            .unwrap_err()
            .to_string();
        assert!(err.contains("collision"), "{err}");
    }

    #[test]
    fn validate_active_behavior_tree_config_ok_when_no_project_config_present() {
        let dir = tempdir().unwrap();
        assert!(validate_active_behavior_tree_config(dir.path()).is_ok());
    }

    #[test]
    fn validate_active_behavior_tree_config_ok_when_project_declares_no_behaviors() {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("mecha10.json"),
            serde_json::json!({"name": "proj", "version": "1.0.0"}).to_string(),
        )
        .unwrap();

        assert!(validate_active_behavior_tree_config(dir.path()).is_ok());
    }

    #[test]
    fn validate_active_behavior_tree_config_accepts_a_valid_active_behavior() {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("mecha10.json"),
            serde_json::json!({"name": "proj", "version": "1.0.0", "behaviors": {"active": "patrol"}}).to_string(),
        )
        .unwrap();
        fs::create_dir_all(dir.path().join("configs/behaviors/patrol")).unwrap();
        fs::write(
            dir.path().join("configs/behaviors/patrol/config.json"),
            serde_json::json!({"name": "patrol", "root": {"type": "sequence", "children": []}}).to_string(),
        )
        .unwrap();

        assert!(validate_active_behavior_tree_config(dir.path()).is_ok());
    }

    #[test]
    fn validate_active_behavior_tree_config_rejects_an_invalid_active_behavior() {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("mecha10.json"),
            serde_json::json!({"name": "proj", "version": "1.0.0", "behaviors": {"active": "patrol"}}).to_string(),
        )
        .unwrap();
        fs::create_dir_all(dir.path().join("configs/behaviors/patrol")).unwrap();
        fs::write(
            dir.path().join("configs/behaviors/patrol/config.json"),
            serde_json::json!({"root": {"type": "sequence", "children": []}}).to_string(),
        )
        .unwrap();

        assert!(validate_active_behavior_tree_config(dir.path()).is_err());
    }

    #[test]
    fn validate_active_behavior_tree_config_errors_when_active_behavior_resolves_to_nothing() {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("mecha10.json"),
            serde_json::json!({"name": "proj", "version": "1.0.0", "behaviors": {"active": "does_not_exist"}})
                .to_string(),
        )
        .unwrap();

        assert!(validate_active_behavior_tree_config(dir.path()).is_err());
    }

    #[test]
    fn validate_model_catalog_if_present_ok_when_absent() {
        let dir = tempdir().unwrap();
        assert!(validate_model_catalog_if_present(dir.path()).is_ok());
    }

    #[test]
    fn validate_model_catalog_if_present_validates_a_catalog_under_configs() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("configs")).unwrap();
        fs::write(
            dir.path().join("configs/model_catalog.toml"),
            "[[models]]\nname = \"bad\"\ndescription = \"missing required fields\"\n",
        )
        .unwrap();

        assert!(validate_model_catalog_if_present(dir.path()).is_err());
    }

    #[test]
    fn validate_configs_passes_for_a_minimal_valid_project() {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("mecha10.json"),
            serde_json::json!({"name": "proj", "version": "1.0.0"}).to_string(),
        )
        .unwrap();

        assert!(validate_configs(dir.path(), ConfigKind::ALL, Some(&schemas_dir())).is_ok());
    }

    #[test]
    fn validate_configs_fails_cleanly_when_an_environment_config_is_invalid() {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("mecha10.json"),
            serde_json::json!({"name": "proj", "version": "1.0.0"}).to_string(),
        )
        .unwrap();
        fs::create_dir_all(dir.path().join("configs/simulation/environments/broken_env")).unwrap();
        fs::write(
            dir.path()
                .join("configs/simulation/environments/broken_env/environment.json"),
            serde_json::json!({}).to_string(),
        )
        .unwrap();

        let err = validate_configs(dir.path(), ConfigKind::ALL, Some(&schemas_dir())).unwrap_err();
        assert!(err.to_string().contains("broken_env"), "{err}");
    }

    #[test]
    fn validate_configs_reports_failures_from_multiple_kinds_at_once() {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("mecha10.json"),
            serde_json::json!({"name": "proj", "version": "1.0.0", "behaviors": {"active": "does_not_exist"}})
                .to_string(),
        )
        .unwrap();
        fs::create_dir_all(dir.path().join("configs/simulation/environments/broken_env")).unwrap();
        fs::write(
            dir.path()
                .join("configs/simulation/environments/broken_env/environment.json"),
            serde_json::json!({}).to_string(),
        )
        .unwrap();
        fs::create_dir_all(dir.path().join("configs/rl/jobs")).unwrap();
        fs::write(
            dir.path().join("configs/rl/jobs/broken.yml"),
            "not: [valid, job, definition",
        )
        .unwrap();

        let err = validate_configs(dir.path(), ConfigKind::ALL, Some(&schemas_dir()))
            .unwrap_err()
            .to_string();
        assert!(err.contains("3 problems"), "{err}");
        assert!(err.contains("broken_env"), "{err}");
        assert!(err.contains("does_not_exist"), "{err}");
    }

    #[test]
    fn validate_configs_can_validate_a_narrower_subset() {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("mecha10.json"),
            serde_json::json!({"name": "proj", "version": "1.0.0", "behaviors": {"active": "does_not_exist"}})
                .to_string(),
        )
        .unwrap();

        assert!(validate_configs(
            dir.path(),
            &[ConfigKind::ProjectAndNodes, ConfigKind::SimulationEnvironments],
            Some(&schemas_dir())
        )
        .is_ok());
    }
}