mecha10-core 0.8.0

Mecha10 core runtime and foundational types
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
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
//! Validation functions for project and node configurations.

use super::rules::validate_custom_rules;
use super::schemas::get_project_schema;
use crate::error::{Mecha10Error, Result};
use anyhow::Context as _;
use jsonschema::{Draft, ValidationError};
use serde_json::{Map, Value};
use std::fs;
use std::path::Path;
use tracing::{debug, info};

const PROJECT_CONFIG_FILENAME: &str = "mecha10.json";

const ENV_SECTION_KEYS: [&str; 6] = ["dev", "development", "prod", "production", "staging", "test"];

pub fn validate_project_json(config: &Value) -> Result<()> {
    validate_json_against_schema(
        config,
        &get_project_schema(),
        "Project configuration",
        "Configuration validation failed",
    )?;
    validate_custom_rules(config)
}

/// Validate a project configuration file
///
/// Validates `mecha10.json` itself (JSON-Schema plus the custom rules in
/// [`super::rules`]) and then recurses into every node's own config file
/// referenced via a node's `config` field (drivers/standard/custom), calling
/// [`validate_node_config_file`] for each one. Node config paths are resolved
/// relative to the directory containing `path`.
///
/// # Arguments
///
/// * `path` - Path to mecha10.json file
///
/// # Returns
///
/// Ok(()) if valid, Err with detailed validation errors
///
/// # Example
///
/// ```rust
/// use mecha10_core::schema_validation::validate_project_config;
///
/// # fn example() -> mecha10_core::Result<()> {
/// validate_project_config("mecha10.json")?;
/// # Ok(())
/// # }
/// ```
pub fn validate_project_config<P: AsRef<Path>>(path: P) -> Result<()> {
    let path = path.as_ref();

    info!("Validating project configuration: {}", path.display());

    let config: Value = load_value_from_file(path)?;

    validate_project_json(&config)?;

    let project_dir = path.parent().unwrap_or_else(|| Path::new("."));
    validate_referenced_node_configs(project_dir, &config)?;

    info!("Configuration validation passed");
    Ok(())
}

/// Validate a node config JSON value against its declared `schema` (LAB-4066: there is no
/// generic envelope to fall back to -- every node, built-in or custom, supplies its own
/// schema; see [`resolve_custom_node_schema_file`] for how a project-level caller resolves
/// one).
pub fn validate_node_config_json(config: &Value, schema: &Value) -> Result<()> {
    validate_json_against_schema(
        config,
        schema,
        "Node configuration",
        "Node configuration validation failed",
    )
}

/// Validate a single node config file on disk against its declared `schema`.
///
/// Supports JSON, YAML (`.yaml`/`.yml`), and TOML files, matching the
/// extensions [`crate::config::load_config`] accepts. A node config file may
/// either be flat (the schema's fields directly at the top level) or nested
/// by deployment environment -- `{ "dev": {...}, "production": {...} }` --
/// per `load_config`'s `extract_env_config` convention; when nested, every
/// present environment section is validated independently.
///
/// # Limitations
///
/// This only runs the structural JSON-Schema check against `schema` -- it
/// cannot also run a node's semantic [`crate::config::Validate::validate`],
/// because the concrete Rust config type for a node isn't known at this
/// layer (this module only ever sees `serde_json::Value`, not a node's Rust
/// struct). Stable Rust also has no specialization, so code paths that *do*
/// know the concrete type -- e.g. `Context::load_and_validate_node_config`
/// -- can't conditionally invoke `Validate` either; callers that need
/// semantic validation must call `validate()` explicitly on the loaded
/// config. See `docs/validate-configs.md` for the full picture.
pub fn validate_node_config_file<P: AsRef<Path>>(path: P, schema: &Value) -> Result<()> {
    validate_node_config_file_with_schema(path, schema)
}

fn validate_node_config_file_with_schema<P: AsRef<Path>>(path: P, schema: &Value) -> Result<()> {
    let path = path.as_ref();

    if !path.exists() {
        return Err(Mecha10Error::Configuration(format!(
            "Referenced node config file not found: {}",
            path.display()
        )));
    }

    let value = load_value_from_file(path)?;
    validate_node_config_value_with_schema(&value, path, schema)
}

/// Validate a single arbitrary config file, auto-detecting whether it's a
/// project config (`mecha10.json`) or a node config.
///
/// This is the entry point for validating one file in isolation without
/// needing the rest of the project on disk -- e.g. a git pre-commit hook
/// validating only the files staged in a commit. When the file is a project
/// config, this still validates the project schema/custom rules and recurses
/// into its referenced node configs (same as [`validate_project_config`]);
/// when it's a node config, only that file is validated.
///
/// Detection is filename-based first (`mecha10.json`), falling back to
/// content sniffing: a node config's schema requires `id` + `executable`
/// (or an environment section wrapping them), while a project config
/// requires `name` + `version`. A file matching neither is treated as a
/// project config so the resulting schema error names the missing
/// `name`/`version` fields.
///
/// A bare node config file (no surrounding project context) can't be
/// validated at all (LAB-4066): resolving its declared schema needs the
/// owning project's node entry (`name`/`path`), which isn't available in
/// isolation. Validate it as part of the project instead (no `--path`, or
/// `--path mecha10.json`).
pub fn validate_config_file<P: AsRef<Path>>(path: P) -> Result<()> {
    let path = path.as_ref();

    if !path.exists() {
        return Err(Mecha10Error::Configuration(format!(
            "Config file not found: {}",
            path.display()
        )));
    }

    if path.file_name().and_then(|n| n.to_str()) == Some(PROJECT_CONFIG_FILENAME) {
        return validate_project_config(path);
    }

    let value = load_value_from_file(path)?;

    if looks_like_node_config(&value) {
        return Err(Mecha10Error::Configuration(format!(
            "{}: cannot validate a node configuration file on its own -- its declared schema can \
             only be resolved via the owning project's node entry (name/path in mecha10.json). \
             Validate the project instead (e.g. `mecha10 config validate`, or `--path` pointing at \
             mecha10.json), which resolves this node's declared schema via its built-in type or a \
             `<name>.schema.json` file shipped alongside it.",
            path.display()
        )));
    }

    validate_project_json(&value)?;
    let project_dir = path.parent().unwrap_or_else(|| Path::new("."));
    validate_referenced_node_configs(project_dir, &value)
}

/// Validate every node config file referenced from a project's `nodes`
/// section (drivers/standard/custom), collecting all failures into a single
/// error rather than stopping at the first one.
///
/// Every node entry's declared schema is resolved via [`resolve_declared_node_schema`] -- a
/// `<name>.schema.json` shipped alongside the node (see [`resolve_custom_node_schema_file`]).
/// A node with no declared schema is a hard validation error (LAB-4066) naming the node and
/// how to fix it -- there is no generic envelope left to silently fall back to.
fn validate_referenced_node_configs(project_dir: &Path, config: &Value) -> Result<()> {
    let Some(nodes) = config.get("nodes") else {
        return Ok(());
    };

    let mut errors = Vec::new();

    for category in ["drivers", "standard", "custom"] {
        let Some(node_list) = nodes.get(category).and_then(|v| v.as_array()) else {
            continue;
        };

        for node in node_list {
            let Some(config_rel_path) = node.get("config").and_then(|c| c.as_str()) else {
                continue;
            };

            let node_label = node
                .get("name")
                .and_then(|n| n.as_str())
                .or_else(|| node.get("package").and_then(|n| n.as_str()))
                .unwrap_or("<unnamed>");

            let node_config_path = project_dir.join(config_rel_path);

            let declared_schema = match resolve_declared_node_schema(project_dir, node) {
                Ok(Some(schema)) => schema,
                Ok(None) => {
                    errors.push(format!(
                        "node '{}' ({}): no declared schema found -- ship a `{}.schema.json` file \
                         alongside this node's source (next to its `path`)",
                        node_label,
                        node_config_path.display(),
                        node_label,
                    ));
                    continue;
                }
                Err(e) => {
                    errors.push(format!(
                        "node '{}': failed to load its declared schema: {}",
                        node_label, e
                    ));
                    continue;
                }
            };

            if let Err(e) = validate_node_config_file_with_schema(&node_config_path, &declared_schema) {
                errors.push(format!("node '{}' ({}): {}", node_label, node_config_path.display(), e));
            }
        }
    }

    // Flat-map `nodes` shape (`{"@mecha10/camera": "0.1.0", "my-custom": "0.1.0"}`), the shape
    // `NodesConfig` (`mecha10-cli-core`) actually produces for every real `mecha10 add`/
    // `mecha10 init` project today -- as opposed to the legacy array shape handled above. Every
    // key other than the three reserved category names above is a node identifier; its value is
    // just a version pin, not a schema input. `mecha10-core` can't depend on `mecha10-cli-core`
    // (its `NodeSpec::config_dir`), so the `configs/nodes/...` convention is mirrored inline here
    // -- the same precedent `relay_topics.rs`'s `NODES_PROJECT_DIR`/`NODES_MECHA10_DIR` constants
    // already set for this exact reason.
    if let Some(nodes_map) = nodes.as_object() {
        for identifier in nodes_map.keys() {
            if matches!(identifier.as_str(), "drivers" | "standard" | "custom") {
                continue;
            }

            let name = identifier.rsplit('/').next().unwrap_or(identifier);

            let config_dir = match identifier.strip_prefix("@mecha10/") {
                Some(rest) => format!("configs/nodes/@mecha10/{}", rest),
                None => format!("configs/nodes/{}", identifier),
            };
            let config_rel_path = format!("{}/config.json", config_dir);
            let node_config_path = project_dir.join(&config_rel_path);

            // Schema lookup location: every node's schema lives under the project's `nodes/`
            // directory, never under `configs/nodes/` (wave 10). A framework node (`@mecha10/*`)
            // ships its `<name>.schema.json` at `nodes/@mecha10/<name>/`; a plain project node's
            // schema lives next to its own source at `nodes/<name>/`, per the existing
            // `resolve_custom_node_schema_file` convention. Any other `@scope/*` shape (a
            // hypothetical future registry node) follows the same `nodes/<identifier>` pattern
            // for consistency.
            let schema_lookup_path = format!("nodes/{}", identifier);

            let synthetic_node = serde_json::json!({"name": name, "path": schema_lookup_path});

            let declared_schema = match resolve_declared_node_schema(project_dir, &synthetic_node) {
                Ok(Some(schema)) => schema,
                Ok(None) => {
                    errors.push(format!(
                        "node '{}' ({}): no declared schema found -- ship a `{}.schema.json` file \
                         alongside this node's source (next to its `path`)",
                        name,
                        node_config_path.display(),
                        name,
                    ));
                    continue;
                }
                Err(e) => {
                    errors.push(format!("node '{}': failed to load its declared schema: {}", name, e));
                    continue;
                }
            };

            if let Err(e) = validate_node_config_file_with_schema(&node_config_path, &declared_schema) {
                errors.push(format!("node '{}' ({}): {}", name, node_config_path.display(), e));
            }
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(Mecha10Error::Configuration(format!(
            "Node configuration validation failed:\n{}",
            errors
                .iter()
                .map(|e| format!("  - {}", e))
                .collect::<Vec<_>>()
                .join("\n")
        )))
    }
}

/// Resolve a node entry's declared JSON Schema (LAB-4066; LAB-4390): the single lookup
/// built-in and custom node types now share, instead of built-in types getting a
/// special-cased dispatch branch next to a generic fallback for everything else. This is just
/// [`resolve_custom_node_schema_file`] -- a `<name>.schema.json` file shipped alongside the
/// node's own source -- which every node, built-in or custom, now resolves through identically.
///
/// Returns `Ok(None)` when that lookup finds nothing -- callers treat that as a hard error, not
/// a signal to fall back to anything else.
fn resolve_declared_node_schema(project_dir: &Path, node: &Value) -> Result<Option<Value>> {
    resolve_custom_node_schema_file(project_dir, node)
}

/// Look for a `<name>.schema.json` file next to a custom node's own source (its `path` field),
/// e.g. a node entry `{ "name": "my_sensor", "path": "./nodes/my_sensor", ... }` is expected to
/// ship its schema at `./nodes/my_sensor/my_sensor.schema.json`. This is the convention
/// `mecha10_core` can offer on its own (LAB-4066) without depending on any node crate: a custom
/// node's config shape isn't known as a Rust type here, only as a JSON file the node's author
/// chooses to commit.
///
/// Returns `Ok(None)` (not an error) when the node entry has no `path`/`name`, or no such file
/// exists -- that just means this lookup step found nothing, not that something went wrong.
///
/// # Errors
///
/// Returns an error if the schema file exists but isn't valid JSON.
fn resolve_custom_node_schema_file(project_dir: &Path, node: &Value) -> Result<Option<Value>> {
    let (Some(path), Some(name)) = (
        node.get("path").and_then(Value::as_str),
        node.get("name").and_then(Value::as_str),
    ) else {
        return Ok(None);
    };

    let schema_path = project_dir.join(path).join(format!("{name}.schema.json"));
    if !schema_path.exists() {
        return Ok(None);
    }

    let content = fs::read_to_string(&schema_path)
        .with_context(|| format!("Failed to read {}", schema_path.display()))
        .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)))?;
    let schema: Value = serde_json::from_str(&content)
        .with_context(|| format!("Failed to parse JSON from {}", schema_path.display()))
        .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)))?;

    Ok(Some(schema))
}

/// Validate an already-parsed node config value against `schema`, transparently handling the
/// flat vs. environment-nested cases (LAB-4066: `schema` is now mandatory -- there is no
/// generic envelope to fall back to when a caller has no specific schema in hand).
fn validate_node_config_value_with_schema(value: &Value, path: &Path, schema: &Value) -> Result<()> {
    let Some(obj) = value.as_object() else {
        return Err(Mecha10Error::Configuration(format!(
            "{}: expected a JSON object at the top level",
            path.display()
        )));
    };

    let env_sections = env_sections_present(obj);

    if env_sections.is_empty() {
        return validate_json_against_schema(
            value,
            schema,
            "Node configuration",
            "Node configuration validation failed",
        )
        .map_err(|e| Mecha10Error::Configuration(format!("{}: {}", path.display(), e)));
    }

    let mut errors = Vec::new();
    for env_key in env_sections {
        let section = &obj[env_key];
        if let Err(e) = validate_json_against_schema(
            section,
            schema,
            "Node configuration",
            "Node configuration validation failed",
        ) {
            errors.push(format!("[{}] {}", env_key, e));
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(Mecha10Error::Configuration(format!(
            "{}:\n{}",
            path.display(),
            errors.join("\n")
        )))
    }
}

/// Which of [`ENV_SECTION_KEYS`] are present as top-level keys in `obj`.
fn env_sections_present(obj: &Map<String, Value>) -> Vec<&'static str> {
    ENV_SECTION_KEYS
        .iter()
        .copied()
        .filter(|key| obj.contains_key(*key))
        .collect()
}

/// Heuristic: does `value` look like a node config (has either of the node
/// schema's required fields, `id` or `executable`, either flat or inside an
/// environment section) rather than a project config?
///
/// Checks `id` and `executable` independently (not both required to match)
/// so a node config that's *missing* one of its required fields -- exactly
/// the case validation exists to catch -- still routes to the node schema
/// and reports the right "missing `executable`" error, instead of falling
/// through to the project schema and reporting an unrelated "missing
/// `name`/`version`" error. Both fields are unique to the node schema: a
/// project config's `id` only ever appears nested under `robot`, never at
/// the top level.
fn looks_like_node_config(value: &Value) -> bool {
    let Some(obj) = value.as_object() else {
        return false;
    };

    let has_node_field = |o: &Map<String, Value>| o.contains_key("id") || o.contains_key("executable");

    if has_node_field(obj) {
        return true;
    }

    env_sections_present(obj)
        .into_iter()
        .filter_map(|key| obj[key].as_object())
        .any(has_node_field)
}

/// Read a config file (JSON, YAML/YML, or TOML) into a generic [`Value`],
/// mirroring the extensions [`crate::config::load_config`] accepts. Unlike
/// `load_config`, this does not substitute `${VAR}` environment variables --
/// validation should be deterministic and not depend on which env vars
/// happen to be set in the shell running `mecha10 config validate`.
fn load_value_from_file(path: &Path) -> Result<Value> {
    let content = fs::read_to_string(path)
        .with_context(|| format!("Failed to read config file: {}", path.display()))
        .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)))?;

    match path.extension().and_then(|s| s.to_str()) {
        Some("yaml") | Some("yml") => serde_yaml::from_str(&content)
            .with_context(|| format!("Failed to parse YAML from: {}", path.display()))
            .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e))),
        Some("toml") => {
            let toml_value: toml::Value = toml::from_str(&content)
                .with_context(|| format!("Failed to parse TOML from: {}", path.display()))
                .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)))?;
            serde_json::to_value(toml_value).map_err(|e| {
                Mecha10Error::Configuration(format!("Failed to convert TOML from '{}': {}", path.display(), e))
            })
        }
        _ => serde_json::from_str(&content)
            .with_context(|| format!("Failed to parse JSON from: {}", path.display()))
            .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e))),
    }
}

/// Validate a JSON value against a compiled schema, formatting any failures
/// into a single combined error message.
///
/// * `success_label` - describes the config kind in the debug log on success
/// * `failure_prefix` - prefixes the joined validation error messages on failure
fn validate_json_against_schema(
    config: &Value,
    schema: &Value,
    success_label: &str,
    failure_prefix: &str,
) -> Result<()> {
    let validator = jsonschema::options()
        .with_draft(Draft::Draft7)
        .build(schema)
        .map_err(|e| Mecha10Error::Configuration(format!("Invalid schema: {}", e)))?;

    if validator.is_valid(config) {
        debug!("{} validation passed", success_label);
        Ok(())
    } else {
        let error_messages: Vec<String> = validator
            .iter_errors(config)
            .map(|e| format_validation_error(&e))
            .collect();

        Err(Mecha10Error::Configuration(format!(
            "{}:\n{}",
            failure_prefix,
            error_messages.join("\n")
        )))
    }
}

/// Format a validation error into a human-readable message
fn format_validation_error(error: &ValidationError) -> String {
    let path_str = error.instance_path().to_string();
    let path = if path_str.is_empty() || path_str == "/" {
        "root".to_string()
    } else {
        path_str
    };

    format!("  - {}: {} ({})", path, error, error.instance())
}

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

    fn valid_node_config() -> Value {
        json!({
            "id": "camera_node",
            "executable": "./target/release/camera_node",
        })
    }

    /// A schema requiring `id` + `executable` -- the shape the old generic envelope
    /// (removed, LAB-4066) used to check every node config against unconditionally. Tests
    /// below declare this explicitly (as a resolver result or a `<name>.schema.json` file)
    /// to exercise the same shape through the new declared-schema mechanism.
    fn id_executable_schema() -> Value {
        json!({
            "type": "object",
            "required": ["id", "executable"],
            "properties": {
                "id": { "type": "string" },
                "executable": { "type": "string" }
            }
        })
    }

    fn project_config_with_node(node_config_rel_path: &str) -> Value {
        json!({
            "name": "my-robot",
            "version": "1.0.0",
            "nodes": {
                "drivers": [
                    {
                        "name": "camera",
                        "path": "./drivers/camera",
                        "config": node_config_rel_path
                    }
                ]
            }
        })
    }

    /// Write `<dir>/<node_path>/<node_name>.schema.json` -- the on-disk convention
    /// [`resolve_custom_node_schema_file`] looks for, so a test project's custom/driver node
    /// has a declared schema.
    fn write_custom_schema_file(project_dir: &std::path::Path, node_path: &str, node_name: &str, schema: &Value) {
        let node_dir = project_dir.join(node_path);
        fs::create_dir_all(&node_dir).unwrap();
        fs::write(
            node_dir.join(format!("{node_name}.schema.json")),
            serde_json::to_string(schema).unwrap(),
        )
        .unwrap();
    }

    #[test]
    fn validate_project_config_passes_when_no_node_config_referenced() {
        let dir = tempdir().unwrap();
        let project_path = dir.path().join("mecha10.json");
        fs::write(
            &project_path,
            serde_json::to_string(&json!({"name": "my-robot", "version": "1.0.0"})).unwrap(),
        )
        .unwrap();

        assert!(validate_project_config(&project_path).is_ok());
    }

    #[test]
    fn validate_project_config_accepts_known_robot_and_remote_build_target_triples() {
        let dir = tempdir().unwrap();
        let project_path = dir.path().join("mecha10.json");
        fs::write(
            &project_path,
            serde_json::to_string(&json!({
                "name": "my-robot",
                "version": "1.0.0",
                "robot_id": "robot-1",
                "targets": {
                    "robot": { "nodes": [], "platforms": ["aarch64-unknown-linux-gnu"] },
                    "remote": { "nodes": [], "platforms": ["x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu"] }
                }
            }))
            .unwrap(),
        )
        .unwrap();

        assert!(validate_project_config(&project_path).is_ok());
    }

    #[test]
    fn validate_project_config_accepts_dev_robot_and_remote_node_placement_targets() {
        let dir = tempdir().unwrap();
        let project_path = dir.path().join("mecha10.json");
        fs::write(
            &project_path,
            serde_json::to_string(&json!({
                "name": "my-robot",
                "version": "1.0.0",
                "targets": {
                    "dev": { "nodes": ["@mecha10/simulator"] },
                    "robot": { "nodes": ["@mecha10/motor"] },
                    "remote": { "nodes": ["@mecha10/object-detector"] }
                }
            }))
            .unwrap(),
        )
        .unwrap();

        assert!(validate_project_config(&project_path).is_ok());
    }

    #[test]
    fn validate_project_config_rejects_unknown_build_target_triple() {
        let dir = tempdir().unwrap();
        let project_path = dir.path().join("mecha10.json");
        fs::write(
            &project_path,
            serde_json::to_string(&json!({
                "name": "my-robot",
                "version": "1.0.0",
                "robot_id": "robot-1",
                "targets": {
                    "robot": { "nodes": [], "platforms": ["not-a-real-triple"] }
                }
            }))
            .unwrap(),
        )
        .unwrap();

        assert!(validate_project_config(&project_path).is_err());
    }

    #[test]
    fn validate_project_config_recurses_into_valid_node_config() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("config")).unwrap();
        fs::write(
            dir.path().join("config/camera.json"),
            serde_json::to_string(&valid_node_config()).unwrap(),
        )
        .unwrap();
        write_custom_schema_file(dir.path(), "./drivers/camera", "camera", &id_executable_schema());

        let project_path = dir.path().join("mecha10.json");
        fs::write(
            &project_path,
            serde_json::to_string(&project_config_with_node("./config/camera.json")).unwrap(),
        )
        .unwrap();

        assert!(validate_project_config(&project_path).is_ok());
    }

    #[test]
    fn validate_project_config_fails_on_invalid_node_config() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("config")).unwrap();
        fs::write(
            dir.path().join("config/camera.json"),
            serde_json::to_string(&json!({"id": "camera_node"})).unwrap(),
        )
        .unwrap();
        write_custom_schema_file(dir.path(), "./drivers/camera", "camera", &id_executable_schema());

        let project_path = dir.path().join("mecha10.json");
        fs::write(
            &project_path,
            serde_json::to_string(&project_config_with_node("./config/camera.json")).unwrap(),
        )
        .unwrap();

        let err = validate_project_config(&project_path).unwrap_err().to_string();
        assert!(err.contains("camera"), "error should name the node: {}", err);
        assert!(
            err.contains("executable"),
            "error should mention the missing field: {}",
            err
        );
    }

    #[test]
    fn validate_project_config_fails_when_referenced_node_config_missing() {
        let dir = tempdir().unwrap();
        write_custom_schema_file(dir.path(), "./drivers/camera", "camera", &id_executable_schema());

        let project_path = dir.path().join("mecha10.json");
        fs::write(
            &project_path,
            serde_json::to_string(&project_config_with_node("./config/does-not-exist.json")).unwrap(),
        )
        .unwrap();

        let err = validate_project_config(&project_path).unwrap_err().to_string();
        assert!(
            err.contains("does-not-exist.json"),
            "error should name the missing file: {}",
            err
        );
    }

    /// LAB-4066: a node with no declared schema at all (no resolver match, no
    /// `<name>.schema.json` shipped alongside it) is now a hard validation error naming the
    /// node -- it never silently falls back to a generic envelope.
    #[test]
    fn validate_project_config_fails_when_node_has_no_declared_schema() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("config")).unwrap();
        fs::write(
            dir.path().join("config/camera.json"),
            serde_json::to_string(&valid_node_config()).unwrap(),
        )
        .unwrap();
        // Deliberately no `<path>/camera.schema.json` and no resolver.

        let project_path = dir.path().join("mecha10.json");
        fs::write(
            &project_path,
            serde_json::to_string(&project_config_with_node("./config/camera.json")).unwrap(),
        )
        .unwrap();

        let err = validate_project_config(&project_path).unwrap_err().to_string();
        assert!(err.contains("camera"), "error should name the node: {}", err);
        assert!(
            err.contains("no declared schema"),
            "error should explain the node has no declared schema: {}",
            err
        );
    }

    #[test]
    fn validate_node_config_file_supports_environment_nested_yaml() {
        let dir = tempdir().unwrap();
        let node_config_path = dir.path().join("camera.yaml");
        fs::write(
            &node_config_path,
            serde_yaml::to_string(&json!({
                "dev": valid_node_config(),
                "production": valid_node_config(),
            }))
            .unwrap(),
        )
        .unwrap();

        assert!(validate_node_config_file(&node_config_path, &id_executable_schema()).is_ok());
    }

    #[test]
    fn validate_node_config_file_reports_invalid_environment_section() {
        let dir = tempdir().unwrap();
        let node_config_path = dir.path().join("camera.json");
        fs::write(
            &node_config_path,
            serde_json::to_string(&json!({
                "dev": valid_node_config(),
                "production": {"id": "camera_node"},
            }))
            .unwrap(),
        )
        .unwrap();

        let err = validate_node_config_file(&node_config_path, &id_executable_schema())
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("production"),
            "error should name the failing env section: {}",
            err
        );
    }

    /// LAB-4066: a bare node config file (no project context) can't have its declared schema
    /// resolved -- resolution needs the owning project's node entry (name/path) -- so this is
    /// now a hard error pointing the caller at project-level validation instead, not a silent
    /// pass against a generic envelope.
    #[test]
    fn validate_config_file_errors_on_a_bare_node_config_file_with_no_project_context() {
        let dir = tempdir().unwrap();
        let node_config_path = dir.path().join("node.json");
        fs::write(&node_config_path, serde_json::to_string(&valid_node_config()).unwrap()).unwrap();

        let err = validate_config_file(&node_config_path).unwrap_err().to_string();
        assert!(
            err.contains("cannot validate a node configuration file on its own"),
            "{}",
            err
        );
    }

    #[test]
    fn validate_config_file_auto_detects_project_config_by_filename() {
        let dir = tempdir().unwrap();
        let project_path = dir.path().join("mecha10.json");
        fs::write(
            &project_path,
            serde_json::to_string(&json!({"name": "my-robot", "version": "1.0.0"})).unwrap(),
        )
        .unwrap();

        assert!(validate_config_file(&project_path).is_ok());
    }

    #[test]
    fn validate_config_file_errors_on_missing_file() {
        let dir = tempdir().unwrap();
        let missing = dir.path().join("nope.json");

        let err = validate_config_file(&missing).unwrap_err().to_string();
        assert!(err.contains("not found"), "error should say not found: {}", err);
    }

    /// LAB-4390: a "built-in" node (simulated here -- this crate doesn't know about any real
    /// built-in node type, see `resolve_declared_node_schema`'s doc comment) and a genuinely
    /// custom node both resolve their declared schema via the exact same function call, with no
    /// node-type branching anywhere in between. Asserting both schemas come back from one
    /// direct call to [`resolve_declared_node_schema`] (not merely "both validate OK") is what
    /// proves there's no special-casing left, not just that both happen to work.
    #[test]
    fn resolve_declared_node_schema_resolves_builtin_and_custom_nodes_through_the_identical_call() {
        let dir = tempdir().unwrap();
        write_custom_schema_file(
            dir.path(),
            "./nodes/builtin_like",
            "builtin_like",
            &id_executable_schema(),
        );
        write_custom_schema_file(
            dir.path(),
            "./nodes/custom_sensor",
            "custom_sensor",
            &id_executable_schema(),
        );

        let builtin_node = json!({"name": "builtin_like", "path": "./nodes/builtin_like"});
        let custom_node = json!({"name": "custom_sensor", "path": "./nodes/custom_sensor"});

        let builtin_schema = resolve_declared_node_schema(dir.path(), &builtin_node).unwrap();
        let custom_schema = resolve_declared_node_schema(dir.path(), &custom_node).unwrap();

        assert_eq!(builtin_schema, Some(id_executable_schema()));
        assert_eq!(custom_schema, Some(id_executable_schema()));
    }

    /// Same as above, but through the full `validate_project_config` entry point with two
    /// distinct node entries in the same project -- both validate successfully against their
    /// own shipped `<name>.schema.json` file via the one unified lookup, with nothing in
    /// `validate_referenced_node_configs` distinguishing between them by node type.
    #[test]
    fn validate_project_config_validates_builtin_and_custom_nodes_through_the_same_path() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("config")).unwrap();
        fs::write(
            dir.path().join("config/builtin_like.json"),
            serde_json::to_string(&valid_node_config()).unwrap(),
        )
        .unwrap();
        fs::write(
            dir.path().join("config/custom_sensor.json"),
            serde_json::to_string(&valid_node_config()).unwrap(),
        )
        .unwrap();
        write_custom_schema_file(
            dir.path(),
            "./nodes/builtin_like",
            "builtin_like",
            &id_executable_schema(),
        );
        write_custom_schema_file(
            dir.path(),
            "./nodes/custom_sensor",
            "custom_sensor",
            &id_executable_schema(),
        );

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

        assert!(validate_project_config(&project_path).is_ok());
    }

    #[test]
    fn resolve_custom_node_schema_file_reads_schema_next_to_node_path() {
        let dir = tempdir().unwrap();
        write_custom_schema_file(dir.path(), "./nodes/my_sensor", "my_sensor", &id_executable_schema());

        let node = json!({"name": "my_sensor", "path": "./nodes/my_sensor"});
        let schema = resolve_custom_node_schema_file(dir.path(), &node).unwrap();
        assert_eq!(schema, Some(id_executable_schema()));
    }

    #[test]
    fn resolve_custom_node_schema_file_returns_none_when_absent() {
        let dir = tempdir().unwrap();
        let node = json!({"name": "my_sensor", "path": "./nodes/my_sensor"});
        assert_eq!(resolve_custom_node_schema_file(dir.path(), &node).unwrap(), None);
    }

    #[test]
    fn resolve_custom_node_schema_file_returns_none_when_node_has_no_path_or_name() {
        let dir = tempdir().unwrap();
        let node = json!({"package": "@mecha10/motor", "binary": "motor"});
        assert_eq!(resolve_custom_node_schema_file(dir.path(), &node).unwrap(), None);
    }

    #[test]
    fn resolve_custom_node_schema_file_errors_on_malformed_json() {
        let dir = tempdir().unwrap();
        let node_dir = dir.path().join("nodes/my_sensor");
        fs::create_dir_all(&node_dir).unwrap();
        fs::write(node_dir.join("my_sensor.schema.json"), "{ not valid json").unwrap();

        let node = json!({"name": "my_sensor", "path": "./nodes/my_sensor"});
        assert!(resolve_custom_node_schema_file(dir.path(), &node).is_err());
    }

    // --- Flat-map `nodes` shape (the real `NodesConfig` shape every actual `mecha10 add`/
    // `mecha10 init` project uses today, as opposed to the legacy array shape exercised above).

    fn write_project_config(dir: &std::path::Path, config: &Value) -> std::path::PathBuf {
        let project_path = dir.join("mecha10.json");
        fs::write(&project_path, serde_json::to_string(config).unwrap()).unwrap();
        project_path
    }

    #[test]
    fn validate_project_config_validates_flat_map_framework_node() {
        let dir = tempdir().unwrap();

        // Framework node: schema lives under nodes/@mecha10/camera (wave 10), while config.json
        // stays under configs/nodes/@mecha10/camera.
        write_custom_schema_file(dir.path(), "nodes/@mecha10/camera", "camera", &id_executable_schema());
        fs::create_dir_all(dir.path().join("configs/nodes/@mecha10/camera")).unwrap();
        fs::write(
            dir.path().join("configs/nodes/@mecha10/camera/config.json"),
            serde_json::to_string(&valid_node_config()).unwrap(),
        )
        .unwrap();

        let project_path = write_project_config(
            dir.path(),
            &json!({
                "name": "my-robot",
                "version": "1.0.0",
                "nodes": { "@mecha10/camera": "0.1.0" }
            }),
        );

        assert!(validate_project_config(&project_path).is_ok());
    }

    #[test]
    fn validate_project_config_validates_flat_map_project_node_schema_next_to_source() {
        let dir = tempdir().unwrap();

        // Plain project node: schema lives next to its own source (nodes/<name>/), NOT under
        // configs/nodes/<name>/ -- matching `resolve_custom_node_schema_file`'s convention.
        write_custom_schema_file(dir.path(), "nodes/my-custom", "my-custom", &id_executable_schema());
        fs::create_dir_all(dir.path().join("configs/nodes/my-custom")).unwrap();
        fs::write(
            dir.path().join("configs/nodes/my-custom/config.json"),
            serde_json::to_string(&valid_node_config()).unwrap(),
        )
        .unwrap();

        let project_path = write_project_config(
            dir.path(),
            &json!({
                "name": "my-robot",
                "version": "1.0.0",
                "nodes": { "my-custom": "0.1.0" }
            }),
        );

        assert!(validate_project_config(&project_path).is_ok());

        // Confirm the schema really is being read from nodes/<name>/, not
        // configs/nodes/<name>/, by proving the config.json-adjacent location (the wrong one for
        // a project node) having no schema wouldn't matter -- i.e. moving the schema away from
        // nodes/<name>/ makes it fail.
        fs::remove_file(dir.path().join("nodes/my-custom/my-custom.schema.json")).unwrap();
        let err = validate_project_config(&project_path).unwrap_err().to_string();
        assert!(
            err.contains("no declared schema"),
            "removing nodes/<name>/<name>.schema.json should break validation: {}",
            err
        );
    }

    #[test]
    fn validate_project_config_fails_when_flat_map_node_has_no_declared_schema() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("configs/nodes/@mecha10/camera")).unwrap();
        fs::write(
            dir.path().join("configs/nodes/@mecha10/camera/config.json"),
            serde_json::to_string(&valid_node_config()).unwrap(),
        )
        .unwrap();
        // Deliberately no camera.schema.json shipped alongside it.

        let project_path = write_project_config(
            dir.path(),
            &json!({
                "name": "my-robot",
                "version": "1.0.0",
                "nodes": { "@mecha10/camera": "0.1.0" }
            }),
        );

        let err = validate_project_config(&project_path).unwrap_err().to_string();
        assert!(err.contains("camera"), "error should name the node: {}", err);
        assert!(
            err.contains("no declared schema"),
            "error should explain the node has no declared schema: {}",
            err
        );
    }

    #[test]
    fn validate_project_config_fails_when_flat_map_node_config_missing() {
        let dir = tempdir().unwrap();
        write_custom_schema_file(dir.path(), "nodes/@mecha10/camera", "camera", &id_executable_schema());
        // Deliberately no configs/nodes/@mecha10/camera/config.json written.

        let project_path = write_project_config(
            dir.path(),
            &json!({
                "name": "my-robot",
                "version": "1.0.0",
                "nodes": { "@mecha10/camera": "0.1.0" }
            }),
        );

        let err = validate_project_config(&project_path).unwrap_err().to_string();
        assert!(
            err.contains("not found"),
            "error should say the config file was not found: {}",
            err
        );
    }

    /// A project mixing the legacy array shape (`nodes.drivers`) and the flat-map shape
    /// (`nodes.<identifier>`) in the same `nodes` object -- unlikely in practice, but parsing
    /// must not crash or double-process the `drivers`/`standard`/`custom` keys as if they were
    /// flat node identifiers themselves.
    #[test]
    fn validate_project_config_validates_mixed_legacy_array_and_flat_map_shapes() {
        let dir = tempdir().unwrap();

        // Legacy array entry.
        fs::create_dir_all(dir.path().join("config")).unwrap();
        fs::write(
            dir.path().join("config/camera.json"),
            serde_json::to_string(&valid_node_config()).unwrap(),
        )
        .unwrap();
        write_custom_schema_file(dir.path(), "./drivers/camera", "camera", &id_executable_schema());

        // Flat-map entry alongside it.
        write_custom_schema_file(dir.path(), "nodes/my-custom", "my-custom", &id_executable_schema());
        fs::create_dir_all(dir.path().join("configs/nodes/my-custom")).unwrap();
        fs::write(
            dir.path().join("configs/nodes/my-custom/config.json"),
            serde_json::to_string(&valid_node_config()).unwrap(),
        )
        .unwrap();

        let project_path = write_project_config(
            dir.path(),
            &json!({
                "name": "my-robot",
                "version": "1.0.0",
                "nodes": {
                    "drivers": [
                        {"name": "camera", "path": "./drivers/camera", "config": "./config/camera.json"}
                    ],
                    "my-custom": "0.1.0"
                }
            }),
        );

        assert!(validate_project_config(&project_path).is_ok());
    }
}