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
//! Node-level configuration loading with environment-aware file fallback.
//!
//! Every load path here (see [`split_base_and_custom`]) resolves a node's config JSON into the
//! base+`custom` split documented on [`crate::node_config_base::NodeConfigBase`]
//! (`docs/adr/0001-node-config-base-schema.md`): `T`'s reserved/base fields (e.g.
//! `relay_topics`, via `#[serde(flatten)] pub base: NodeConfigBase` on `T`) are read from the
//! top level, `T`'s own node-specific fields are read exclusively from a nested `custom` object
//! (absent `custom` means no node-specific fields, not a fallback to reading them flat off the
//! top level - there is deliberately no dual-read support for that old shape).

use super::Context;
use crate::error::{Mecha10Error, Result};
use crate::node_config_base::NodeConfigBase;
use anyhow::Context as _;
use schemars::JsonSchema;
use serde::de::DeserializeOwned;
use serde_json::Value;

impl Context {
    /// Load node configuration with environment-aware file-level fallback
    ///
    /// This method implements the V2 configuration system with:
    /// - Environment-specific configs (dev/staging/production), selected *within* a config
    ///   file's `{"dev": {...}, "production": {...}}` envelope (see
    ///   [`Self::load_environment_aware_config`])
    /// - File-level fallback (no key-by-key merging)
    /// - Automatic project-root discovery via [`crate::fs_utils::find_project_root`]
    ///
    /// **Tier order** (mirrors `mecha10_cli_core::paths::config::node_config_candidates`, the
    /// canonical 2-tier resolution order for node configs -- this method can't call that helper
    /// directly since `mecha10-core` is a dependency *of* `mecha10-cli-core`, not the reverse,
    /// but it must stay in sync with it):
    /// 1. `configs/nodes/@mecha10/{node_name}/config.json` - Framework nodes
    /// 2. `configs/nodes/{node_name}/config.json` - Project nodes (preferred)
    /// 3. `T::default()` - Default implementation, if neither tier has a config file (or no
    ///    project root could be found)
    ///
    /// **Environment Detection:**
    /// - Uses `MECHA10_ENV` env var (default: "dev")
    /// - Supported values: "dev", "staging", "production", or custom
    ///
    /// **Semantic Validation:**
    /// - Not run here. This method is generic over `T` with only a
    ///   `DeserializeOwned + Default` bound, and stable Rust has no
    ///   specialization -- a function generic over `T` can't conditionally
    ///   call [`crate::config::Validate::validate`] only when `T` happens to
    ///   implement it. Node types that need semantic validation should call
    ///   `validate()` explicitly on the config returned here.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Configuration type that implements `DeserializeOwned` + `Default`
    ///
    /// # Arguments
    ///
    /// * `node_name` - Name of the node (e.g., "simulator", "camera-streamer")
    ///
    /// # Returns
    ///
    /// The loaded configuration of type `T`, using the first available source
    /// in the fallback chain.
    ///
    /// # Example
    ///
    /// ```rust
    /// use mecha10_core::prelude::*;
    /// use serde::{Deserialize, Serialize};
    ///
    /// #[derive(Debug, Clone, Deserialize, Serialize, Default)]
    /// struct SimBridgeConfig {
    ///     camera_width: u32,
    ///     camera_height: u32,
    ///     camera_fps: u32,
    /// }
    ///
    /// # async fn example(ctx: &Context) -> Result<()> {
    /// let config: SimBridgeConfig = ctx.load_node_config("simulator").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn load_node_config<T>(&self, node_name: &str) -> Result<T>
    where
        T: DeserializeOwned + Default,
    {
        self.load_node_config_for_instance(node_name, self.instance()).await
    }

    /// Like [`Self::load_node_config`], but with an explicit `instance_id` instead of this
    /// context's own [`Self::instance`].
    ///
    /// Node-runner (the supervisor process) is the main reason this is split out: it loads a
    /// node's `config.json` on that node's behalf, through a context that represents
    /// node-runner itself (not the node), so it can't rely on `self.instance()` - it passes
    /// the target node's `--instance-id` through explicitly instead. Every actual node binary
    /// (via `node_main!`/`#[derive(Node)]`) should just call [`Self::load_node_config`], which
    /// already does the right thing from its own `instance()`.
    ///
    /// # Instance-Keyed Config Files
    ///
    /// For a multi-instance node (two `camera` nodes - one real, one simulated - both declared
    /// in `mecha10.json` via the `{"name": "@mecha10/camera", "instance_id": "real"}` node-list
    /// entry shape, LAB-4131), the resolved config file's per-environment section may itself be
    /// a flat config object (today's behavior, unchanged, used when `instance_id` is `None`) or
    /// a JSON object keyed by instance id:
    /// ```json
    /// {
    ///   "dev": {
    ///     "real": { "source": { "type": "v4l2", "device_path": "/dev/video0" }, "id": "real" },
    ///     "sim":  { "source": { "type": "redis", "topic": "/camera/sim/raw" }, "id": "sim" }
    ///   }
    /// }
    /// ```
    /// When `instance_id` is `Some(id)`, the sub-object at that key is used as the node's
    /// config (same shape/validation as today's flat config). An `instance_id` that isn't
    /// present as a key is an error, rather than silently falling back to `T::default()` - a
    /// multi-instance node whose config is missing an instance's entry has a real
    /// misconfiguration, not an absent config file.
    pub async fn load_node_config_for_instance<T>(&self, node_name: &str, instance_id: Option<&str>) -> Result<T>
    where
        T: DeserializeOwned + Default,
    {
        Self::resolve_node_config(node_name, instance_id).await
    }

    /// Same as [`Self::load_node_config`], but also validates the loaded JSON against `T`'s own
    /// `schemars`-derived JSON Schema before deserializing into it (LAB-4066).
    ///
    /// This is the load-at-startup counterpart to `mecha10_core::schema_validation`'s preflight
    /// validation (`validate_project_config`/`mecha10 config validate`), using the same "every
    /// node supplies its own schema" principle that validation's declared-schema lookup is
    /// built on -- except here there is no lookup and no "missing schema" case to hard-error on:
    /// `T: JsonSchema` means `T`'s own derived schema always exists, enforced by the type system
    /// at compile time rather than by a runtime registry/convention check. `node_main!` and
    /// `#[derive(Node)]`'s generated `run()` call this (not [`Self::load_node_config`]) so every
    /// node -- built-in or custom -- gets this check for free the moment its `Config` struct
    /// derives `JsonSchema` (already required to export a schema for it at all, see
    /// `mecha10-schema-registry`).
    ///
    /// Not used for [`Self::load_node_config`] callers that read another node's config file
    /// generically through a deliberately-partial/lenient struct (e.g.
    /// `mecha10-node-runner`'s launcher-level `NodeConfig`) -- validating a partial struct's
    /// derived schema against another node's *full* config would reject fields the reader
    /// never claimed to model, which isn't this node's schema to enforce.
    ///
    /// # Errors
    ///
    /// Returns an error if the config file exists but fails to parse, fails schema validation,
    /// or fails to deserialize into `T`.
    pub async fn load_and_validate_node_config<T>(&self, node_name: &str) -> Result<T>
    where
        T: DeserializeOwned + Default + JsonSchema,
    {
        Self::resolve_node_config_validated(node_name).await
    }

    /// Find the config file [`Self::resolve_node_config`]/[`Self::resolve_node_config_validated`]
    /// should load for `node_name`, per the 2-tier resolution order documented on
    /// [`Self::load_node_config`]. Returns `None` when neither tier has a file (or no project
    /// root could be found), meaning the caller should fall back to `T::default()`.
    fn find_node_config_path(node_name: &str) -> Result<Option<std::path::PathBuf>> {
        use std::env;

        let current_dir = env::current_dir()
            .map_err(|e| Mecha10Error::Configuration(format!("Failed to get current directory: {}", e)))?;

        let Some(project_root) = crate::fs_utils::find_project_root(&current_dir) else {
            return Ok(None);
        };

        let flat_config_path = project_root
            .join("configs")
            .join("nodes")
            .join("@mecha10")
            .join(node_name)
            .join("config.json");
        if flat_config_path.exists() {
            return Ok(Some(flat_config_path));
        }

        let project_config_path = project_root
            .join("configs")
            .join("nodes")
            .join(node_name)
            .join("config.json");
        if project_config_path.exists() {
            return Ok(Some(project_config_path));
        }

        Ok(None)
    }

    /// The actual resolution logic behind [`Self::load_and_validate_node_config`] -- mirrors
    /// [`Self::resolve_node_config`] but additionally validates the environment section against
    /// `T`'s derived schema (via [`Self::load_environment_aware_config_validated`]) before
    /// deserializing it.
    async fn resolve_node_config_validated<T>(node_name: &str) -> Result<T>
    where
        T: DeserializeOwned + Default + JsonSchema,
    {
        use std::env;

        let environment = env::var("MECHA10_ENV").unwrap_or_else(|_| "dev".to_string());

        let Some(config_path) = Self::find_node_config_path(node_name)? else {
            tracing::debug!(
                "No config file found for node '{}', using Default implementation",
                node_name
            );
            return Ok(T::default());
        };

        tracing::debug!(
            "Loading node config for '{}' from: {}",
            node_name,
            config_path.display()
        );
        Self::load_environment_aware_config_validated(&config_path, &environment)
            .with_context(|| {
                format!(
                    "Failed to load node config for '{}' from '{}'",
                    node_name,
                    config_path.display()
                )
            })
            .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)))
    }

    /// Same as [`Self::load_environment_aware_config`], but validates the selected environment
    /// section against `T::schema_value()`-equivalent (`schemars::SchemaGenerator`-derived)
    /// before deserializing it, so a config that's structurally wrong (wrong types, violates a
    /// `#[schemars(...)]` constraint, unknown fields when `T` denies them) fails with a clear
    /// schema error instead of either a less-specific serde error or silently loading anyway.
    fn load_environment_aware_config_validated<T>(path: &std::path::Path, environment: &str) -> Result<T>
    where
        T: DeserializeOwned + Default + JsonSchema,
    {
        let content =
            std::fs::read_to_string(path).with_context(|| format!("Failed to read config file: {}", path.display()))?;

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

        let obj = json_value.as_object().ok_or_else(|| {
            Mecha10Error::Configuration(format!(
                "Config must be a JSON object with 'dev'/'production' keys: {}",
                path.display()
            ))
        })?;

        let env_key = match environment {
            "production" | "prod" => "production",
            _ => "dev",
        };

        let env_section = obj.get(env_key).ok_or_else(|| {
            Mecha10Error::Configuration(format!(
                "Config is missing its '{}' environment section (MECHA10_ENV='{}'): {}",
                env_key,
                environment,
                path.display()
            ))
        })?;

        let config_value = split_base_and_custom(env_section)?;
        validate_against_declared_schema::<T>(&config_value, path, env_key)?;

        tracing::debug!("Loading '{}' environment section from: {}", env_key, path.display());
        let config: T = serde_json::from_value(config_value)
            .with_context(|| format!("Failed to deserialize '{}' section from: {}", env_key, path.display()))
            .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)))?;

        Ok(config)
    }

    /// The actual resolution logic behind [`Self::load_node_config`], split out as a
    /// `self`-free associated function so it's unit-testable without constructing a full
    /// [`Context`] (which requires a live Redis connection).
    async fn resolve_node_config<T>(node_name: &str, instance_id: Option<&str>) -> Result<T>
    where
        T: DeserializeOwned + Default,
    {
        use std::env;

        let environment = env::var("MECHA10_ENV").unwrap_or_else(|_| "dev".to_string());

        let current_dir = env::current_dir()
            .map_err(|e| Mecha10Error::Configuration(format!("Failed to get current directory: {}", e)))?;

        if let Some(project_root) = crate::fs_utils::find_project_root(&current_dir) {
            let flat_config_path = project_root
                .join("configs")
                .join("nodes")
                .join("@mecha10")
                .join(node_name)
                .join("config.json");

            if flat_config_path.exists() {
                tracing::debug!(
                    "Loading node config for '{}' from flat path: {}",
                    node_name,
                    flat_config_path.display()
                );
                return Self::load_environment_aware_config(&flat_config_path, &environment, instance_id)
                    .with_context(|| {
                        format!(
                            "Failed to load node config for '{}' from '{}'",
                            node_name,
                            flat_config_path.display()
                        )
                    })
                    .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)));
            }

            let project_config_path = project_root
                .join("configs")
                .join("nodes")
                .join(node_name)
                .join("config.json");

            if project_config_path.exists() {
                tracing::debug!(
                    "Loading node config for '{}' from project path: {}",
                    node_name,
                    project_config_path.display()
                );
                return Self::load_environment_aware_config(&project_config_path, &environment, instance_id)
                    .with_context(|| {
                        format!(
                            "Failed to load node config for '{}' from '{}'",
                            node_name,
                            project_config_path.display()
                        )
                    })
                    .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)));
            }
        }

        tracing::debug!(
            "No config file found for node '{}', using Default implementation",
            node_name
        );
        let config = T::default();
        Ok(config)
    }

    /// Load a config file in environment-aware format.
    ///
    /// Config files must have the format:
    /// ```json
    /// {
    ///   "dev": { ... config ... },
    ///   "production": { ... config ... }
    /// }
    /// ```
    fn load_environment_aware_config<T>(
        path: &std::path::Path,
        environment: &str,
        instance_id: Option<&str>,
    ) -> Result<T>
    where
        T: DeserializeOwned + Default,
    {
        let content =
            std::fs::read_to_string(path).with_context(|| format!("Failed to read config file: {}", path.display()))?;

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

        let obj = json_value.as_object().ok_or_else(|| {
            Mecha10Error::Configuration(format!(
                "Config must be a JSON object with 'dev'/'production' keys: {}",
                path.display()
            ))
        })?;

        let env_key = match environment {
            "production" | "prod" => "production",
            _ => "dev",
        };

        let env_section = obj.get(env_key).ok_or_else(|| {
            Mecha10Error::Configuration(format!(
                "Config is missing its '{}' environment section (MECHA10_ENV='{}'): {}",
                env_key,
                environment,
                path.display()
            ))
        })?;

        tracing::debug!("Loading '{}' environment section from: {}", env_key, path.display());

        // Multi-instance support (LAB-4131): when loading on behalf of a specific
        // `instance_id`, the environment section is a JSON object keyed by instance id rather
        // than the flat config itself - look up that key and deserialize its value instead of
        // the section directly. No `instance_id` (the overwhelming majority of nodes, today's
        // only shape) means the environment section *is* the flat config, exactly as before.
        let config_value = match instance_id {
            Some(id) => env_section
                .get(id)
                .ok_or_else(|| {
                    Mecha10Error::Configuration(format!(
                        "Config for instance '{}' not found - expected a top-level '{}' key inside the '{}' \
                         environment section of: {}",
                        id,
                        id,
                        env_key,
                        path.display()
                    ))
                })?
                .clone(),
            None => env_section.clone(),
        };

        let config_value = split_base_and_custom(&config_value)?;
        let config: T = serde_json::from_value(config_value)
            .with_context(|| format!("Failed to deserialize '{}' section from: {}", env_key, path.display()))
            .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)))?;

        Ok(config)
    }
}

/// Reshape a node's resolved config object into the base+`custom` split documented on
/// [`NodeConfigBase`] - the one place both [`Context::load_environment_aware_config`] and
/// [`Context::load_environment_aware_config_validated`] go through before deserializing into a
/// node's own `T`, so neither has to duplicate this logic.
///
/// `value` is expected to be the already environment-/instance-resolved config object (e.g. the
/// `"dev"` section, or the per-instance sub-object inside it) - a JSON object with the node's
/// reserved/base fields (`NodeConfigBase`, e.g. `relay_topics`) at the top level and its own
/// node-specific fields nested under a `custom` key, per LAB-4384's ADR
/// (`docs/adr/0001-node-config-base-schema.md`).
///
/// The returned object merges `NodeConfigBase`'s own fields (re-serialized, so only its
/// *recognized* reserved fields survive, never arbitrary top-level noise) with whatever is
/// nested under `custom` (defaulting to no fields at all when `custom` is absent - never a
/// fallback to reading node-specific fields flat off the top level). This is a hard breaking
/// change for a `config.json` still written in the old flat shape: a node-specific field left at
/// the top level (outside `custom`) is silently dropped here, not promoted - there is
/// deliberately no dual-read support for that old shape.
///
/// `pub` (re-exported as [`crate::context::split_base_and_custom`]) so that out-of-`Context`
/// callers which read a node's `config.json` straight off disk instead of through a live
/// `Context` (e.g. `mecha10-cli`'s standalone-mode model/Ollama preflight, which can't depend on
/// a live `Context` the way `mecha10-node-runner` does) can resolve the same base+`custom` split
/// by calling into this one real implementation, instead of each hand-rolling its own partial
/// reimplementation of this same logic that silently drifts out of sync whenever a field moves
/// between `NodeConfigBase` and `custom`.
pub fn split_base_and_custom(value: &Value) -> Result<Value> {
    let base: NodeConfigBase = serde_json::from_value(value.clone())
        .with_context(|| "Failed to deserialize reserved/base config fields")
        .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)))?;
    let base_fields = serde_json::to_value(&base)
        .expect("NodeConfigBase always serializes to a JSON object")
        .as_object()
        .expect("NodeConfigBase always serializes to a JSON object")
        .clone();

    // Only carry a reserved/base field into `merged` when `value` actually declared it -
    // `NodeConfigBase`'s own `Serialize` fills in every field it owns (even ones left at their
    // default, e.g. `topics` when the config never mentioned it), which is correct for
    // `NodeConfigBase` considered on its own, but would otherwise inject fields a node's own
    // config type (`T`) never asked for into every resolved config - breaking any `T` with
    // `#[serde(deny_unknown_fields)]` that only embeds a subset of `NodeConfigBase`'s fields
    // (e.g. just `crate::relay_topics::RelayTopicsField`, not the full struct) with an "unknown
    // field" error for a field it was never given in the first place.
    let mut merged = match value.as_object() {
        Some(input_obj) => base_fields
            .into_iter()
            .filter(|(key, _)| input_obj.contains_key(key))
            .collect::<serde_json::Map<String, Value>>(),
        None => base_fields,
    };

    let custom = value
        .get("custom")
        .cloned()
        .unwrap_or_else(|| Value::Object(Default::default()));
    let custom_obj = custom
        .as_object()
        .ok_or_else(|| Mecha10Error::Configuration("Node config's 'custom' field must be a JSON object".to_string()))?;
    merged.extend(custom_obj.clone());

    Ok(Value::Object(merged))
}

/// Validate `value` (an environment section, e.g. the `"dev"` object) against `T`'s own
/// `schemars`-derived JSON Schema, used by [`Context::load_environment_aware_config_validated`].
///
/// `env_label` (e.g. `"dev"`/`"production"`) is only used to make the error message point at
/// which section failed, since `path` alone doesn't say that.
fn validate_against_declared_schema<T: JsonSchema>(
    value: &Value,
    path: &std::path::Path,
    env_label: &str,
) -> Result<()> {
    let schema = schemars::SchemaGenerator::default().into_root_schema_for::<T>();
    let schema_value = serde_json::to_value(schema).expect("a schemars-derived root schema always serializes to JSON");

    let validator = jsonschema::options()
        .with_draft(jsonschema::Draft::Draft7)
        .build(&schema_value)
        .map_err(|e| Mecha10Error::Configuration(format!("Invalid schema derived for node config type: {}", e)))?;

    if validator.is_valid(value) {
        return Ok(());
    }

    let messages: Vec<String> = validator
        .iter_errors(value)
        .map(|e| format!("  - {}: {} ({})", e.instance_path(), e, e.instance()))
        .collect();

    Err(Mecha10Error::Configuration(format!(
        "Node config validation failed for '{}' [{}]:\n{}",
        path.display(),
        env_label,
        messages.join("\n")
    )))
}

#[cfg(test)]
mod tests {
    use super::Context;
    use schemars::JsonSchema;
    use serde::{Deserialize, Serialize};
    use serial_test::serial;
    use std::fs;

    #[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, JsonSchema)]
    struct TestNodeConfig {
        #[serde(default)]
        value: String,
    }

    #[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, JsonSchema)]
    #[serde(deny_unknown_fields)]
    struct StrictTestNodeConfig {
        #[serde(default)]
        value: String,
        #[serde(flatten)]
        base: crate::node_config_base::NodeConfigBase,
    }

    /// A configuration with a positive-rate constraint enforced by schema validation.
    #[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, JsonSchema)]
    struct StrictPositiveConfig {
        #[serde(default)]
        #[schemars(range(min = 1))]
        rate_hz: i32,
    }

    /// `value` (every test type's lone node-specific field) now has to be nested under `custom`
    /// per the base+`custom` split (`crate::node_config_base::NodeConfigBase`) -
    /// `split_base_and_custom` only ever reads node-specific fields from there.
    fn envelope(dev_value: &str) -> String {
        format!(
            r#"{{"dev": {{"custom": {{"value": "{dev_value}"}}}}, "production": {{"custom": {{"value": "{dev_value}-prod"}}}}}}"#
        )
    }

    #[tokio::test]
    #[serial]
    async fn resolve_node_config_loads_from_project_tier_when_only_project_config_exists() {
        let original_dir = std::env::current_dir().unwrap();

        let project = tempfile::tempdir().unwrap();
        fs::write(project.path().join("mecha10.json"), "{}").unwrap();
        let node_dir = project.path().join("configs").join("nodes").join("my-node");
        fs::create_dir_all(&node_dir).unwrap();
        fs::write(node_dir.join("config.json"), envelope("project")).unwrap();

        std::env::set_current_dir(project.path()).unwrap();
        let result = Context::resolve_node_config::<TestNodeConfig>("my-node", None).await;
        std::env::set_current_dir(original_dir).unwrap();

        assert_eq!(result.unwrap().value, "project");
    }

    #[tokio::test]
    #[serial]
    async fn resolve_node_config_prefers_framework_tier_over_project_tier() {
        let original_dir = std::env::current_dir().unwrap();

        let project = tempfile::tempdir().unwrap();
        fs::write(project.path().join("mecha10.json"), "{}").unwrap();

        let framework_dir = project
            .path()
            .join("configs")
            .join("nodes")
            .join("@mecha10")
            .join("my-node");
        fs::create_dir_all(&framework_dir).unwrap();
        fs::write(framework_dir.join("config.json"), envelope("framework")).unwrap();

        let project_dir = project.path().join("configs").join("nodes").join("my-node");
        fs::create_dir_all(&project_dir).unwrap();
        fs::write(project_dir.join("config.json"), envelope("project")).unwrap();

        std::env::set_current_dir(project.path()).unwrap();
        let result = Context::resolve_node_config::<TestNodeConfig>("my-node", None).await;
        std::env::set_current_dir(original_dir).unwrap();

        assert_eq!(result.unwrap().value, "framework");
    }

    /// `LAB-4131`: a multi-instance node's config file nests a flat config object per
    /// instance id inside its environment section, instead of being the flat config itself.
    #[tokio::test]
    #[serial]
    async fn resolve_node_config_with_instance_id_loads_the_keyed_sub_object() {
        let original_dir = std::env::current_dir().unwrap();

        let project = tempfile::tempdir().unwrap();
        fs::write(project.path().join("mecha10.json"), "{}").unwrap();
        let node_dir = project.path().join("configs").join("nodes").join("camera");
        fs::create_dir_all(&node_dir).unwrap();
        fs::write(
            node_dir.join("config.json"),
            r#"{
                "dev": {
                    "real": {"custom": {"value": "real"}},
                    "sim": {"custom": {"value": "sim"}}
                },
                "production": {
                    "real": {"custom": {"value": "real-prod"}},
                    "sim": {"custom": {"value": "sim-prod"}}
                }
            }"#,
        )
        .unwrap();

        std::env::set_current_dir(project.path()).unwrap();
        let real = Context::resolve_node_config::<TestNodeConfig>("camera", Some("real")).await;
        let sim = Context::resolve_node_config::<TestNodeConfig>("camera", Some("sim")).await;
        std::env::set_current_dir(original_dir).unwrap();

        assert_eq!(real.unwrap().value, "real");
        assert_eq!(sim.unwrap().value, "sim");
    }

    /// An `instance_id` that isn't a key in the environment section is a real
    /// misconfiguration and must error, not silently fall back to `T::default()`.
    #[tokio::test]
    #[serial]
    async fn resolve_node_config_errors_when_instance_id_key_is_missing() {
        let original_dir = std::env::current_dir().unwrap();

        let project = tempfile::tempdir().unwrap();
        fs::write(project.path().join("mecha10.json"), "{}").unwrap();
        let node_dir = project.path().join("configs").join("nodes").join("camera");
        fs::create_dir_all(&node_dir).unwrap();
        fs::write(node_dir.join("config.json"), envelope("project")).unwrap();

        std::env::set_current_dir(project.path()).unwrap();
        let result = Context::resolve_node_config::<TestNodeConfig>("camera", Some("missing")).await;
        std::env::set_current_dir(original_dir).unwrap();

        let err = result.unwrap_err();
        assert!(err.to_string().contains("missing"));
    }

    /// A flat (single-instance, unkeyed) config file must keep loading exactly as before when
    /// no `instance_id` is passed, even though this module now supports keyed configs too.
    #[tokio::test]
    #[serial]
    async fn resolve_node_config_without_instance_id_is_unaffected_by_keyed_config_support() {
        let original_dir = std::env::current_dir().unwrap();

        let project = tempfile::tempdir().unwrap();
        fs::write(project.path().join("mecha10.json"), "{}").unwrap();
        let node_dir = project.path().join("configs").join("nodes").join("my-node");
        fs::create_dir_all(&node_dir).unwrap();
        fs::write(node_dir.join("config.json"), envelope("project")).unwrap();

        std::env::set_current_dir(project.path()).unwrap();
        let result = Context::resolve_node_config::<TestNodeConfig>("my-node", None).await;
        std::env::set_current_dir(original_dir).unwrap();

        assert_eq!(result.unwrap().value, "project");
    }

    /// Regression test (LAB-2270): a config declaring `relay_topics` must load into a strict
    /// (`deny_unknown_fields`) node config that embeds `crate::relay_topics::RelayTopicsField`
    /// via `#[serde(flatten)]` - and the value must actually come through typed, not be
    /// discarded. (An earlier design had `Context::load_node_config` silently strip the field
    /// out of the JSON before deserializing, so no node needed to declare it at all - correct,
    /// but opaque: a node's own type gave no hint the field existed, and it could never
    /// meaningfully read the value even if it wanted to. Flattening a shared field in is the
    /// same "no per-node reimplementation" property, but explicit and typed instead.)
    #[tokio::test]
    #[serial]
    async fn resolve_node_config_populates_flattened_relay_topics_field_on_a_strict_node_config() {
        let original_dir = std::env::current_dir().unwrap();

        let project = tempfile::tempdir().unwrap();
        fs::write(project.path().join("mecha10.json"), "{}").unwrap();
        let node_dir = project.path().join("configs").join("nodes").join("my-node");
        fs::create_dir_all(&node_dir).unwrap();
        fs::write(
            node_dir.join("config.json"),
            r#"{
                "dev": { "custom": { "value": "project" }, "relay_topics": ["/my-node/status"] },
                "production": { "custom": { "value": "project-prod" }, "relay_topics": ["/my-node/status"] }
            }"#,
        )
        .unwrap();

        std::env::set_current_dir(project.path()).unwrap();
        let result = Context::resolve_node_config::<StrictTestNodeConfig>("my-node", None).await;
        std::env::set_current_dir(original_dir).unwrap();

        let config = result.unwrap();
        assert_eq!(config.value, "project");
        assert_eq!(
            config.base.relay.relay_topics,
            Some(vec!["/my-node/status".to_string()])
        );
    }

    #[tokio::test]
    #[serial]
    async fn resolve_node_config_ignores_dead_v1_and_common_tiers_and_falls_back_to_default() {
        let original_dir = std::env::current_dir().unwrap();

        let project = tempfile::tempdir().unwrap();
        fs::write(project.path().join("mecha10.json"), "{}").unwrap();

        let env_tier_dir = project.path().join("configs").join("dev").join("nodes").join("my-node");
        fs::create_dir_all(&env_tier_dir).unwrap();
        fs::write(env_tier_dir.join("config.json"), r#"{"value": "dead-env-tier"}"#).unwrap();

        let common_tier_dir = project
            .path()
            .join("configs")
            .join("common")
            .join("nodes")
            .join("my-node");
        fs::create_dir_all(&common_tier_dir).unwrap();
        fs::write(common_tier_dir.join("config.json"), r#"{"value": "dead-common-tier"}"#).unwrap();

        std::env::set_current_dir(project.path()).unwrap();
        let result = Context::resolve_node_config::<TestNodeConfig>("my-node", None).await;
        std::env::set_current_dir(original_dir).unwrap();

        assert_eq!(result.unwrap(), TestNodeConfig::default());
    }

    /// `LAB-4129`: a config missing its active environment's section must fail to load instead
    /// of silently resolving to the other environment's values.
    #[tokio::test]
    #[serial]
    async fn resolve_node_config_errors_when_active_environment_section_is_missing() {
        let original_dir = std::env::current_dir().unwrap();
        let original_env = std::env::var("MECHA10_ENV").ok();

        let project = tempfile::tempdir().unwrap();
        fs::write(project.path().join("mecha10.json"), "{}").unwrap();
        let node_dir = project.path().join("configs").join("nodes").join("my-node");
        fs::create_dir_all(&node_dir).unwrap();
        fs::write(node_dir.join("config.json"), r#"{"dev": {"value": "project"}}"#).unwrap();

        std::env::set_var("MECHA10_ENV", "production");
        std::env::set_current_dir(project.path()).unwrap();
        let result = Context::resolve_node_config::<TestNodeConfig>("my-node", None).await;
        std::env::set_current_dir(original_dir).unwrap();
        match original_env {
            Some(value) => std::env::set_var("MECHA10_ENV", value),
            None => std::env::remove_var("MECHA10_ENV"),
        }

        let err = result.unwrap_err();
        assert!(err.to_string().contains("production"));
    }

    #[tokio::test]
    #[serial]
    async fn resolve_node_config_falls_back_to_default_when_no_project_root_is_found() {
        let original_dir = std::env::current_dir().unwrap();

        let dir = tempfile::tempdir().unwrap();

        std::env::set_current_dir(dir.path()).unwrap();
        let result = Context::resolve_node_config::<TestNodeConfig>("my-node", None).await;
        std::env::set_current_dir(original_dir).unwrap();

        assert_eq!(result.unwrap(), TestNodeConfig::default());
    }

    #[tokio::test]
    #[serial]
    async fn resolve_node_config_validated_passes_for_a_schema_satisfying_config() {
        let original_dir = std::env::current_dir().unwrap();

        let project = tempfile::tempdir().unwrap();
        fs::write(project.path().join("mecha10.json"), "{}").unwrap();
        let node_dir = project.path().join("configs").join("nodes").join("my-node");
        fs::create_dir_all(&node_dir).unwrap();
        fs::write(node_dir.join("config.json"), envelope("project")).unwrap();

        std::env::set_current_dir(project.path()).unwrap();
        let result = Context::resolve_node_config_validated::<TestNodeConfig>("my-node").await;
        std::env::set_current_dir(original_dir).unwrap();

        assert_eq!(result.unwrap().value, "project");
    }

    /// LAB-4066: a config that satisfies `serde` deserialization (every field is the right
    /// Rust type) but violates a `#[schemars(...)]` constraint the struct declares -- something
    /// plain deserialization can never catch -- must fail under
    /// `resolve_node_config_validated`, proving it actually runs schema validation and isn't
    /// just a thin wrapper around deserialization.
    #[tokio::test]
    #[serial]
    async fn resolve_node_config_validated_rejects_a_value_violating_a_schemars_constraint() {
        let original_dir = std::env::current_dir().unwrap();

        let project = tempfile::tempdir().unwrap();
        fs::write(project.path().join("mecha10.json"), "{}").unwrap();
        let node_dir = project.path().join("configs").join("nodes").join("my-node");
        fs::create_dir_all(&node_dir).unwrap();
        fs::write(
            node_dir.join("config.json"),
            r#"{"dev": {"custom": {"rate_hz": 0}}, "production": {"custom": {"rate_hz": 1}}}"#,
        )
        .unwrap();

        std::env::set_current_dir(project.path()).unwrap();
        let result = Context::resolve_node_config_validated::<StrictPositiveConfig>("my-node").await;
        std::env::set_current_dir(original_dir).unwrap();

        let err = result.unwrap_err().to_string();
        assert!(err.contains("rate_hz"), "error should name the failing field: {}", err);
    }

    #[tokio::test]
    #[serial]
    async fn resolve_node_config_validated_falls_back_to_default_when_no_config_file_exists() {
        let original_dir = std::env::current_dir().unwrap();

        let dir = tempfile::tempdir().unwrap();

        std::env::set_current_dir(dir.path()).unwrap();
        let result = Context::resolve_node_config_validated::<TestNodeConfig>("my-node").await;
        std::env::set_current_dir(original_dir).unwrap();

        assert_eq!(result.unwrap(), TestNodeConfig::default());
    }

    /// Mirrors `resolve_node_config_populates_flattened_relay_topics_field_on_a_strict_node_config`
    /// (the unvalidated path) -- a `deny_unknown_fields` config with a flattened shared field
    /// must still validate and deserialize correctly under the schema-validated path too.
    #[tokio::test]
    #[serial]
    async fn resolve_node_config_validated_populates_flattened_relay_topics_field() {
        let original_dir = std::env::current_dir().unwrap();

        let project = tempfile::tempdir().unwrap();
        fs::write(project.path().join("mecha10.json"), "{}").unwrap();
        let node_dir = project.path().join("configs").join("nodes").join("my-node");
        fs::create_dir_all(&node_dir).unwrap();
        fs::write(
            node_dir.join("config.json"),
            r#"{
                "dev": { "custom": { "value": "project" }, "relay_topics": ["/my-node/status"] },
                "production": { "custom": { "value": "project-prod" }, "relay_topics": ["/my-node/status"] }
            }"#,
        )
        .unwrap();

        std::env::set_current_dir(project.path()).unwrap();
        let result = Context::resolve_node_config_validated::<StrictTestNodeConfig>("my-node").await;
        std::env::set_current_dir(original_dir).unwrap();

        let config = result.unwrap();
        assert_eq!(config.value, "project");
        assert_eq!(
            config.base.relay.relay_topics,
            Some(vec!["/my-node/status".to_string()])
        );
    }

    /// LAB-4385: a node-specific field left at the top level, sibling to (not nested inside)
    /// `custom`, must not be picked up - there is no dual-read fallback to the old flat shape
    /// (`crate::node_config_base::NodeConfigBase`'s module docs, `docs/adr/0001-node-config-base-schema.md`).
    #[tokio::test]
    #[serial]
    async fn resolve_node_config_ignores_a_node_specific_field_left_flat_at_the_top_level() {
        let original_dir = std::env::current_dir().unwrap();

        let project = tempfile::tempdir().unwrap();
        fs::write(project.path().join("mecha10.json"), "{}").unwrap();
        let node_dir = project.path().join("configs").join("nodes").join("my-node");
        fs::create_dir_all(&node_dir).unwrap();
        fs::write(
            node_dir.join("config.json"),
            r#"{
                "dev": { "value": "flat-and-ignored" },
                "production": { "value": "flat-and-ignored-prod" }
            }"#,
        )
        .unwrap();

        std::env::set_current_dir(project.path()).unwrap();
        let result = Context::resolve_node_config::<TestNodeConfig>("my-node", None).await;
        std::env::set_current_dir(original_dir).unwrap();

        assert_eq!(result.unwrap().value, "");
    }

    /// LAB-4385: a config section that omits `custom` entirely just means "no node-specific
    /// fields" - the base/reserved fields still load normally.
    #[tokio::test]
    #[serial]
    async fn resolve_node_config_treats_missing_custom_as_no_custom_fields() {
        let original_dir = std::env::current_dir().unwrap();

        let project = tempfile::tempdir().unwrap();
        fs::write(project.path().join("mecha10.json"), "{}").unwrap();
        let node_dir = project.path().join("configs").join("nodes").join("my-node");
        fs::create_dir_all(&node_dir).unwrap();
        fs::write(
            node_dir.join("config.json"),
            r#"{
                "dev": { "relay_topics": ["/my-node/status"] },
                "production": { "relay_topics": ["/my-node/status"] }
            }"#,
        )
        .unwrap();

        std::env::set_current_dir(project.path()).unwrap();
        let result = Context::resolve_node_config::<StrictTestNodeConfig>("my-node", None).await;
        std::env::set_current_dir(original_dir).unwrap();

        let config = result.unwrap();
        assert_eq!(config.value, "");
        assert_eq!(
            config.base.relay.relay_topics,
            Some(vec!["/my-node/status".to_string()])
        );
    }

    /// Regression test (LAB-4536) for [`super::split_base_and_custom`] directly: it must not
    /// inject a `NodeConfigBase`-recognized field (`topics`, `model`, `provider`) that the
    /// original section never mentioned, even though `NodeConfigBase`'s own `Serialize` fills
    /// those fields in with their defaults. Doing so used to leak `"topics": {...}` into every
    /// merged config regardless of whether the caller's section ever declared it, breaking any
    /// `#[serde(deny_unknown_fields)]` config type that doesn't itself declare a `topics` field
    /// (e.g. one that only embeds `crate::relay_topics::RelayTopicsField`, not the full
    /// `NodeConfigBase`).
    #[test]
    fn split_base_and_custom_does_not_inject_an_unmentioned_base_field() {
        let section = serde_json::json!({
            "relay_topics": ["/my-node/status"],
            "custom": { "value": "project" }
        });

        let merged = super::split_base_and_custom(&section).unwrap();
        let merged = merged.as_object().unwrap();

        assert!(merged.contains_key("relay_topics"), "mentioned field must survive");
        assert!(
            merged.contains_key("value"),
            "custom field must be promoted to the top level"
        );
        assert!(
            !merged.contains_key("topics"),
            "a base field never mentioned by the section must not be injected: {:?}",
            merged
        );
        assert!(
            !merged.contains_key("model") && !merged.contains_key("provider"),
            "unmentioned Option base fields must not be injected either: {:?}",
            merged
        );
    }

    /// Mirrors `split_base_and_custom_does_not_inject_an_unmentioned_base_field`, but proves the
    /// positive case still works: a base field the section *does* mention must still come
    /// through, re-serialized via `NodeConfigBase` (not read verbatim off the input).
    #[test]
    fn split_base_and_custom_still_carries_through_a_mentioned_base_field() {
        let section = serde_json::json!({
            "topics": { "publishes": [{"output": "/a/b"}], "subscribes": [] },
            "custom": {}
        });

        let merged = super::split_base_and_custom(&section).unwrap();
        assert_eq!(
            merged["topics"],
            serde_json::json!({ "publishes": [{"output": "/a/b"}], "subscribes": [] })
        );
    }
}