mecha10-cli 0.7.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
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
//! Wires per-node-type and model-catalog schemas into the config-validation entry point
//! `mecha10 config validate`/`mecha10 lint`/`mecha10 build` share (LAB-1772).
//!
//! This lives in `packages/cli` rather than `mecha10-cli-core` because `mecha10-cli-core`
//! can't depend on `mecha10-models` (which already depends on `mecha10-cli-core` -- see
//! `docs/validate-configs.md`). `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.
//!
//! # Wave 7: model-catalog/environment-config schema logic now lives here, not in
//! `mecha10-schema-registry`
//!
//! `mecha10-schema-registry` used to depend on every `packages/nodes/*` crate (for
//! `node_type_schema`/`composed_node_schema`), so depending on it from real (non-test,
//! non-example) binary code meant the shipped `mecha10` CLI binary transitively compiled in all
//! 14 node crates, even though the only real-binary uses of that crate were
//! `validate_model_catalog_file` and `validate_environment_config_json` -- neither of which
//! touches a node crate's types at all (the former only needs
//! `mecha10_models::services::model_service::ModelCatalogEntry`; the latter only needs the
//! bundled JSON Schema in `mecha10_templates::templates::ENVIRONMENT_CONFIG_SCHEMA_JSON`).
//!
//! So this module carries its own small, self-contained copies of that logic (below, private to
//! this module) instead of calling into `mecha10-schema-registry` for it. That split is now moot
//! for the node-crate-dependency reason it started from -- `mecha10-schema-registry` dropped its
//! `node_type_schema`/`composed_node_schema`/`BUILTIN_NODE_TYPES` surface (and so its last
//! dependency on `mecha10-nodes`) entirely, since node schemas are API-driven now (fetched live
//! from `mecha10-api`'s catalog, see `packages/robot-config/src/node_catalog.rs`) rather than
//! derived at this repo's compile time from node-crate Rust types -- but the logic already lived
//! here, so it stays.

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, but with
/// LAB-1772's two accuracy improvements layered on top of the existing generic
/// validation:
///
/// * A file named `model_catalog.toml` is recognized and validated against the
///   `schemars`-derived model-catalog schema plus the entry-name-uniqueness rule,
///   instead of being routed through the generic project/node config detection in
///   `mecha10_core::schema_validation::validate_config_file` (which has no concept
///   of this config kind at all -- see the crate-level docs above for why this
///   dispatch can't live inside `mecha10_core` itself).
/// * Every other path is validated via [`ConfigService::resolve_and_validate`]. Every built-in
///   node type ships its own `<name>.schema.json` file next to its source (LAB-4388), so each
///   node entry referenced from a project config -- built-in or custom/third-party (LAB-4066) --
///   is checked against that file the same way (LAB-4390). A node with no declared schema is a
///   hard validation error, not a silent pass against a generic envelope.
/// * When `path` is `None` (whole-project validation), also validates every
///   `configs/rl/jobs/*.yml` job definition, if present -- not reachable through a
///   node's `config` reference, so without this it would never be checked.
///
/// # 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>) -> 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());
        }
    }

    // Every built-in node type now ships its own `<name>.schema.json` file next to its source
    // (LAB-4388), so it resolves via the same file-based lookup a custom node already used, with
    // no hardcoded dispatch needed (LAB-4390).
    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)?;
        validate_active_behavior_tree_config(project_root)?;
        validate_rl_job_configs(project_root)?;
    }

    Ok(target)
}

#[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 -- so `mecha10 config push` (LAB-4246) can
/// report a clear per-file error for everything wrong in one pass rather than silently
/// succeeding, pushing partial/invalid config, or making the caller fix one error at a time.
///
/// Preset files (`configs/simulation/environments/*/presets/*/preset.json`, introduced by
/// LAB-3629) are intentionally not one of the [`ConfigKind`] variants yet: a preset schema now
/// exists ([`validate_preset_config_json`], already used ad hoc by `mecha10 dev`'s preflight
/// gate -- see `handlers/dev/ops/preflight.rs`'s `check_simulation_preset`), but wiring a
/// discovery pass over every environment's `presets/` directory into *this* gate is tracked
/// separately (LAB-3632) rather than folded into LAB-3629.
///
/// # 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]) -> 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),
            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 (LAB-4246; LAB-4245 promoted this schema
/// into `cargo run --example export_schemas`, but nothing validated real projects' `environment.json`
/// files against it before this).
fn validate_environment_configs(project_root: &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) {
            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) -> Result<()> {
    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))?;
    validate_environment_config_json(&value)
        .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 (LAB-4246). Resolves the active behavior's `config.json` the same
/// way the runtime does (project override, falling back to the bundled `@mecha10` default)
/// via [`mecha10_behavior_runtime::resolve_behavior_config_path`], then validates it with the
/// same [`mecha10_behavior_runtime::validate_behavior_composition_json`] used for an
/// explicit `--path` to a behavior config (see [`is_behavior_config_file`] above).
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 (same pattern as
/// `mecha10_core::schema_validation`'s node-name-uniqueness rule for `mecha10.json`).
///
/// Wave 7: this (and the handful of helpers below it) used to be
/// `mecha10_schema_registry::validate_model_catalog_file` -- see this module's crate-level doc
/// comment for why that dependency was dropped from the real binary target instead of kept.
///
/// # 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` (LAB-1772). Only needs `mecha10-models`' own catalog type --
/// no node crate is involved, which is exactly what let this move out of
/// `mecha10-schema-registry` in wave 7 (see this module's crate-level doc comment).
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(())
}

/// The hand-written draft-07 JSON Schema for `environment.json`
/// (`packages/mecha10-templates/templates/configs/simulation/schemas/environment-config.schema.json`),
/// bundled at compile time via `mecha10_templates::templates::ENVIRONMENT_CONFIG_SCHEMA_JSON`.
/// Only needs `mecha10-templates`' bundled constant -- no node crate is involved, same as
/// [`model_catalog_schema`] above (see this module's crate-level doc comment on wave 7).
fn environment_config_schema() -> serde_json::Value {
    serde_json::from_str(mecha10_templates::templates::ENVIRONMENT_CONFIG_SCHEMA_JSON)
        .expect("bundled environment-config.schema.json is valid JSON")
}

/// Validate an already-parsed `environment.json` value against [`environment_config_schema`].
/// Used by [`validate_one_environment_config`] above.
fn validate_environment_config_json(value: &serde_json::Value) -> Result<()> {
    validate_json_against_schema(value, &environment_config_schema(), "Environment config")
}

/// The hand-written draft-07 JSON Schema for `preset.json`
/// (`packages/mecha10-templates/templates/configs/simulation/schemas/preset-config.schema.json`,
/// LAB-3629), bundled at compile time via
/// `mecha10_templates::templates::PRESET_CONFIG_SCHEMA_JSON`. Only needs `mecha10-templates`'
/// bundled constant -- no node crate is involved, same as [`model_catalog_schema`]/
/// [`environment_config_schema`] above.
fn preset_config_schema() -> serde_json::Value {
    serde_json::from_str(mecha10_templates::templates::PRESET_CONFIG_SCHEMA_JSON)
        .expect("bundled preset-config.schema.json is valid JSON")
}

/// Validate an already-parsed `preset.json` value against [`preset_config_schema`]. Used
/// ad hoc today by `mecha10 dev`'s preflight gate (`handlers/dev/ops/preflight.rs`'s
/// `check_simulation_preset`) rather than through [`validate_configs`]'s `kinds` dispatch --
/// see that function's doc comment on why a full discovery pass isn't wired in yet (LAB-3632).
pub fn validate_preset_config_json(value: &serde_json::Value) -> Result<()> {
    validate_json_against_schema(value, &preset_config_schema(), "Preset config")
}

/// Validate `value` against `schema`, formatting every failure into one combined error
/// prefixed by `context` (e.g. `"Model catalog"`/`"Environment config"`) -- shared by both
/// schema kinds above so neither hand-rolls its own `jsonschema` wiring and error formatting.
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` (LAB-1772's second config kind --
/// see [`validate_config`]'s doc comment for why this is checked ahead of the
/// generic project/node dispatch rather than inside it).
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 per the `configs/behaviors/**/config.json`
/// convention (LAB-2054's config kind -- see [`validate_config`]'s doc comment; the `behaviors/`
/// directory moved under `configs/` in LAB-2072 so `mecha10 config push`/`pull`/`list` actually
/// sync it, but this check only ever looked for a `behaviors` path component, not a top-level
/// one, so it still matches unchanged). Matches the same convention the git pre-commit hook and
/// `scripts/ci/config-lint.sh` use: 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;

    #[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));
        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)).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)).unwrap_err();
        assert!(err.to_string().to_lowercase().contains("duplicate"));
    }

    /// LAB-4389: a built-in node type's config is now checked against its specific schema via
    /// the same `<name>.schema.json`-file lookup a custom node already used -- there is no
    /// hardcoded resolver dispatch left to exercise instead. This ships a hand-written
    /// base+`custom` composed schema (the same base-fields-plus-nested-`custom` shape
    /// `mecha10_core::schema_validation::compose_node_schema` produces for a real built-in node,
    /// with a `required: ["behavior_name"]` field under `custom` standing in for
    /// `behavior-executor`'s real `BehaviorExecutorConfig`) next to the node's `path`, exactly as
    /// a real built-in node's own crate directory does, to prove that file is actually what gets
    /// checked.
    ///
    /// This manufactures its own schema file in a tempdir directly, rather than relying on the
    /// real, committed node-crate schema file (now published from `mecha-industries/mecha10-nodes`,
    /// not this repo) -- that's fine, and intentional, as coverage for the file-lookup/validation
    /// logic in isolation, not proof that the real files exist on disk.
    #[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)).unwrap_err();
        assert!(
            err.to_string().to_lowercase().contains("behavior_name"),
            "expected the specific BehaviorExecutorConfig schema error, got: {}",
            err
        );
    }

    /// LAB-2041: a project config still using the old top-level `logging` block
    /// (superseded by `environments.<env>.logging`) must fail `mecha10 config
    /// validate`/`mecha10 lint` (both of which call [`validate_config`]) with a message
    /// pointing at the new shape, instead of silently ignoring the obsolete field.
    #[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)).unwrap_err();
        assert!(
            err.to_string().contains("environments.<env>.logging"),
            "expected the error to point at the new per-environment shape, got: {}",
            err
        );
    }

    /// LAB-4066: an unrecognized (custom/third-party) node type is no longer validated against
    /// a generic envelope -- it resolves its declared schema the same way a built-in type
    /// would, just via a `<name>.schema.json` file shipped alongside its source instead of a
    /// `mecha10-schema-registry` dispatch entry.
    #[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)).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)).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()).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()).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()).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()).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()).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()).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()).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).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).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).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]
        )
        .is_ok());
    }
}