mecha10-core 0.6.3

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
//! Validation functions for project and node configurations.

use super::rules::validate_custom_rules;
use super::schemas::{get_node_config_schema, 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};

/// Filename that marks a config file as a project (`mecha10.json`) config
/// rather than a node config, when [`validate_config_file`] has to sniff the
/// kind of an arbitrary `--path`. Kept as a literal (rather than importing
/// `mecha10-cli-core::paths::PROJECT_CONFIG`) because `mecha10-cli-core`
/// depends on this crate, not the other way around.
const PROJECT_CONFIG_FILENAME: &str = "mecha10.json";

/// Top-level keys used to nest a node config by deployment environment (see
/// `crate::config::load_config`'s `extract_env_config`). A node config file
/// may either be flat (the schema's fields at the top level) or nested under
/// one or more of these keys.
const ENV_SECTION_KEYS: [&str; 6] = ["dev", "development", "prod", "production", "staging", "test"];

/// Dependency-injection hook (LAB-1772) that lets a caller downstream of
/// `mecha10_core` -- e.g. `packages/cli`, via a thin aggregation crate that
/// depends on every `packages/nodes/*` crate -- supply a node-type-specific
/// JSON Schema for a given node entry from `mecha10.json`'s
/// `nodes.{drivers,standard,custom}[]`, instead of always validating that
/// node's referenced config file against the single generic
/// [`get_node_config_schema`] envelope.
///
/// `mecha10_core` cannot depend on `packages/nodes/*` or `mecha10-models`
/// itself (both already depend on `mecha10_core` -- see
/// `docs/validate-configs.md`), so it never constructs one of these itself;
/// it only accepts one as an `Option` and falls back to the generic schema
/// when `None` is passed or the resolver returns `None` for a given node
/// (e.g. it's a third-party/unrecognized node type).
///
/// The closure receives the node's own JSON entry (not its config file
/// content) -- e.g. `{ "name": "front_camera", "path": "...", "config":
/// "./config/camera.json" }` -- so it can key off `name`/`path`/`package` to
/// decide which built-in node type this is, if any.
pub type NodeSchemaResolver<'a> = dyn Fn(&Value) -> Option<Value> + 'a;

// ============================================================================
// Validation Functions
// ============================================================================

/// Validate a JSON value against the project schema
///
/// # Arguments
///
/// * `config` - The configuration to validate (as serde_json::Value)
///
/// # Returns
///
/// Ok(()) if valid, Err with detailed validation errors if invalid
///
/// # Example
///
/// ```rust
/// use mecha10_core::schema_validation::validate_project_json;
///
/// let config = serde_json::json!({
///     "name": "my-robot",
///     "version": "1.0.0"
/// });
///
/// validate_project_json(&config)?;
/// ```
pub fn validate_project_json(config: &Value) -> Result<()> {
    validate_json_against_schema(
        config,
        &get_project_schema(),
        "Project configuration",
        "Configuration validation failed",
    )
}

/// 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;
///
/// validate_project_config("mecha10.json")?;
/// ```
pub fn validate_project_config<P: AsRef<Path>>(path: P) -> Result<()> {
    validate_project_config_with_node_schema_resolver(path, None)
}

/// Same as [`validate_project_config`], but lets a caller supply a
/// [`NodeSchemaResolver`] to validate each referenced node config against a
/// node-type-specific schema instead of the generic [`get_node_config_schema`]
/// envelope (LAB-1772). Passing `None` is exactly equivalent to
/// [`validate_project_config`].
pub fn validate_project_config_with_node_schema_resolver<P: AsRef<Path>>(
    path: P,
    node_schema_resolver: Option<&NodeSchemaResolver>,
) -> Result<()> {
    let path = path.as_ref();

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

    // Read and parse file
    let content = fs::read_to_string(path)
        .with_context(|| format!("Failed to read config file: {}", path.display()))
        .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)))?;

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

    // Validate against schema
    validate_project_json(&config)?;

    // Additional custom validations
    validate_custom_rules(&config)?;

    // Recurse into every node's own config file (the gap this ticket closes:
    // previously only mecha10.json itself was validated).
    let project_dir = path.parent().unwrap_or_else(|| Path::new("."));
    validate_referenced_node_configs(project_dir, &config, node_schema_resolver)?;

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

/// Validate NodeConfig JSON against schema
pub fn validate_node_config_json(config: &Value) -> Result<()> {
    validate_json_against_schema(
        config,
        &get_node_config_schema(),
        "Node configuration",
        "Node configuration validation failed",
    )
}

/// Validate a single node config file on disk.
///
/// 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 node config 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
/// ([`get_node_config_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_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) -> Result<()> {
    validate_node_config_file_with_schema(path, None)
}

/// Same as [`validate_node_config_file`], but validates against `schema` when
/// given instead of the generic [`get_node_config_schema`] envelope
/// (LAB-1772). Passing `None` is exactly equivalent to
/// [`validate_node_config_file`].
fn validate_node_config_file_with_schema<P: AsRef<Path>>(path: P, schema: Option<&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.
pub fn validate_config_file<P: AsRef<Path>>(path: P) -> Result<()> {
    validate_config_file_with_node_schema_resolver(path, None)
}

/// Same as [`validate_config_file`], but lets a caller supply a
/// [`NodeSchemaResolver`] -- forwarded to [`validate_project_config_with_node_schema_resolver`]
/// when `path` turns out to be a project config (LAB-1772). Passing `None` is
/// exactly equivalent to [`validate_config_file`].
pub fn validate_config_file_with_node_schema_resolver<P: AsRef<Path>>(
    path: P,
    node_schema_resolver: Option<&NodeSchemaResolver>,
) -> 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_with_node_schema_resolver(path, node_schema_resolver);
    }

    let value = load_value_from_file(path)?;

    if looks_like_node_config(&value) {
        return validate_node_config_value(&value, path);
    }

    // Either it looks like a project config, or it's ambiguous -- default to
    // project config so schema errors point at the missing `name`/`version`.
    validate_project_json(&value)?;
    validate_custom_rules(&value)?;
    let project_dir = path.parent().unwrap_or_else(|| Path::new("."));
    validate_referenced_node_configs(project_dir, &value, node_schema_resolver)
}

// ============================================================================
// Helper Functions
// ============================================================================

/// 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.
///
/// When `node_schema_resolver` is given, each node entry is first offered to
/// it; a `Some(schema)` result validates that node's config file against the
/// node-type-specific schema instead of the generic [`get_node_config_schema`]
/// envelope (LAB-1772). Unrecognized/custom/third-party nodes (resolver
/// returns `None`, or no resolver was given) still fall back to the generic
/// envelope -- this never hard-fails just because a node isn't a built-in type.
fn validate_referenced_node_configs(
    project_dir: &Path,
    config: &Value,
    node_schema_resolver: Option<&NodeSchemaResolver>,
) -> 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 specific_schema = node_schema_resolver.and_then(|resolve| resolve(node));

            if let Err(e) = validate_node_config_file_with_schema(&node_config_path, specific_schema.as_ref()) {
                errors.push(format!("node '{}' ({}): {}", node_label, 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")
        )))
    }
}

/// Validate an already-parsed node config value, transparently handling the
/// flat vs. environment-nested cases.
fn validate_node_config_value(value: &Value, path: &Path) -> Result<()> {
    validate_node_config_value_with_schema(value, path, None)
}

/// Same as [`validate_node_config_value`], but validates against `schema`
/// when given instead of the generic [`get_node_config_schema`] envelope
/// (LAB-1772).
fn validate_node_config_value_with_schema(value: &Value, path: &Path, schema: Option<&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 owned_generic_schema;
    let effective_schema = match schema {
        Some(s) => s,
        None => {
            owned_generic_schema = get_node_config_schema();
            &owned_generic_schema
        }
    };

    let env_sections = env_sections_present(obj);

    if env_sections.is_empty() {
        return validate_json_against_schema(
            value,
            effective_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 {
        // Presence already checked by `env_sections_present`.
        let section = &obj[env_key];
        if let Err(e) = validate_json_against_schema(
            section,
            effective_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",
        })
    }

    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
                    }
                ]
            }
        })
    }

    #[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_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();

        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();
        // Missing required `executable` field.
        fs::write(
            dir.path().join("config/camera.json"),
            serde_json::to_string(&json!({"id": "camera_node"})).unwrap(),
        )
        .unwrap();

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

    #[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).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).unwrap_err().to_string();
        assert!(
            err.contains("production"),
            "error should name the failing env section: {}",
            err
        );
    }

    #[test]
    fn validate_config_file_auto_detects_node_config_by_content() {
        let dir = tempdir().unwrap();
        // Deliberately not named mecha10.json, so detection falls back to content sniffing.
        let node_config_path = dir.path().join("node.json");
        fs::write(&node_config_path, serde_json::to_string(&valid_node_config()).unwrap()).unwrap();

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

    #[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);
    }

    // ========================================================================
    // NodeSchemaResolver tests (LAB-1772)
    // ========================================================================

    /// A resolver standing in for `mecha10-schema-registry::node_schema_resolver`
    /// (which this crate can't depend on -- see `docs/validate-configs.md`): treats
    /// any node whose `name` is `"typed_node"` as having a specific schema requiring
    /// a `custom_field` string, and returns `None` (generic fallback) for everything
    /// else.
    fn stub_resolver(node: &Value) -> Option<Value> {
        if node.get("name").and_then(|n| n.as_str()) == Some("typed_node") {
            Some(json!({
                "type": "object",
                "required": ["custom_field"],
                "properties": {
                    "custom_field": { "type": "string" }
                }
            }))
        } else {
            None
        }
    }

    #[test]
    fn validate_project_config_with_node_schema_resolver_dispatches_to_specific_schema() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("config")).unwrap();
        // Passes the generic node envelope (no `id`/`executable` required by the
        // stub schema) but is missing the type-specific `custom_field`.
        fs::write(
            dir.path().join("config/typed.json"),
            serde_json::to_string(&json!({"id": "typed_node", "executable": "./bin"})).unwrap(),
        )
        .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",
                "nodes": {
                    "custom": [
                        {"name": "typed_node", "path": "./nodes/typed", "config": "./config/typed.json"}
                    ]
                }
            }))
            .unwrap(),
        )
        .unwrap();

        let err = validate_project_config_with_node_schema_resolver(&project_path, Some(&stub_resolver)).unwrap_err();
        assert!(
            err.to_string().contains("custom_field"),
            "expected the stub schema's error, got: {}",
            err
        );
    }

    #[test]
    fn validate_project_config_with_node_schema_resolver_passes_when_specific_schema_satisfied() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("config")).unwrap();
        fs::write(
            dir.path().join("config/typed.json"),
            serde_json::to_string(&json!({"custom_field": "hello"})).unwrap(),
        )
        .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",
                "nodes": {
                    "custom": [
                        {"name": "typed_node", "path": "./nodes/typed", "config": "./config/typed.json"}
                    ]
                }
            }))
            .unwrap(),
        )
        .unwrap();

        assert!(validate_project_config_with_node_schema_resolver(&project_path, Some(&stub_resolver)).is_ok());
    }

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

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

        // "camera" (the node name `project_config_with_node` uses) doesn't match
        // the stub resolver's "typed_node" -- so this falls back to the generic
        // envelope and passes, same as `validate_project_config` (no resolver) does.
        assert!(validate_project_config_with_node_schema_resolver(&project_path, Some(&stub_resolver)).is_ok());
    }

    #[test]
    fn validate_project_config_with_node_schema_resolver_none_matches_validate_project_config() {
        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_with_node_schema_resolver(&project_path, None).is_ok());
    }

    #[test]
    fn validate_config_file_with_node_schema_resolver_dispatches_for_project_config_path() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("config")).unwrap();
        fs::write(
            dir.path().join("config/typed.json"),
            serde_json::to_string(&json!({"id": "typed_node", "executable": "./bin"})).unwrap(),
        )
        .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",
                "nodes": {
                    "custom": [
                        {"name": "typed_node", "path": "./nodes/typed", "config": "./config/typed.json"}
                    ]
                }
            }))
            .unwrap(),
        )
        .unwrap();

        let err = validate_config_file_with_node_schema_resolver(&project_path, Some(&stub_resolver)).unwrap_err();
        assert!(err.to_string().contains("custom_field"));
    }
}