phoxal 0.42.0

Phoxal - production-oriented autonomous robot framework: the runtime engine and model (the api contract tree lives in phoxal-api, the typed bus in phoxal-bus).
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
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::path::{Path, PathBuf};

use super::{Component, KinematicConfig, MotionLimits, Role, capability};

/// Top-level `robot:` section - the robot model, and exactly what
/// `ctx.robot()` exposes.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Robot {
    /// Ordered parent robot documents composed before this leaf manifest.
    ///
    /// Parent maps are deep-merged in declaration order, then the leaf wins.
    /// Sequence and scalar values replace earlier values.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub extends: Vec<PathBuf>,
    pub robot: RobotSection,
    /// Authoritative behavior root selected for this robot. Behavior
    /// definitions themselves live under `behaviors/` in the robot root.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub behavior: Option<BehaviorConfig>,
    /// The user services this robot runs, keyed by service identity, each with
    /// its user-owned configuration. The Cargo workspace is the candidate set
    /// (a declared service must have a matching workspace crate); this map
    /// selects which discovered services belong to the robot and are built,
    /// staged, and launched. An undeclared workspace service crate is legal
    /// and simply not part of the robot.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub services: BTreeMap<String, UserService>,
    /// The additional user tools this robot runs, keyed by tool identity, each
    /// with its user-owned configuration - symmetric with `services`. Official
    /// tools stay CLI-catalog-owned, always run, and take no configuration
    /// here; a `tools/` workspace crate overriding an official identity is a
    /// source override, not a declaration, and is never listed here.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub tools: BTreeMap<String, UserTool>,
    /// Optional project-relative Zenoh router configuration.
    #[serde(default, skip_serializing_if = "Router::is_empty")]
    pub router: Router,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct BehaviorConfig {
    pub root: String,
    #[serde(default)]
    pub autostart: bool,
}

/// `robot:` - the robot model: identity, structure, kinematic, and
/// components.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct RobotSection {
    /// The robot id (was `identity.id`).
    pub id: String,
    /// The bus namespace (was `identity.namespace`).
    pub namespace: String,
    /// Path to the URDF structure file, relative to the robot root.
    #[serde(default = "default_structure_path")]
    pub structure: PathBuf,
    /// The kinematic model (was `motion.kinematic`; the `motion:` wrapper is
    /// gone - `kinematic` is a direct field of `robot:`).
    pub kinematic: KinematicConfig,
    /// Robot-wide planar speed limits. Both `motion` and `drive` enforce these
    /// independently so an arbitration defect cannot bypass the actuator
    /// backstop.
    pub motion_limits: MotionLimits,
    /// Component instance map: instance-id -> instance.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub components: BTreeMap<String, Component>,
}

/// One declared user service: presence in `services` is the declaration;
/// `config` is its user-owned configuration.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct UserService {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config: Option<serde_json::Value>,
}

/// One declared additional user tool: presence in `tools` is the declaration;
/// `config` is its user-owned configuration. Same shape as [`UserService`],
/// kept distinct so the two declarations stay independently documented types.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct UserTool {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config: Option<serde_json::Value>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Router {
    /// Zenoh JSON5 configuration path relative to the resolved robot root.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config: Option<PathBuf>,
}

impl Router {
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.config.is_none()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationError {
    EmptyRobotId,
    EmptyRobotNamespace,
    EmptyRouterConfigPath,
    AbsoluteRouterConfigPath {
        path: PathBuf,
    },
    InvalidToken {
        field: String,
        value: String,
    },
    EmptyComponentType {
        instance: String,
    },
    EmptyMountLink {
        instance: String,
    },
    EmptyRoleList {
        instance: String,
        capability: String,
    },
    RepeatedRole {
        instance: String,
        capability: String,
        role: Role,
    },
    InvalidRuntimeClock {
        instance: String,
    },
    InvalidKinematicField {
        field: String,
        message: String,
    },
    InvalidMotionLimit {
        field: String,
        message: String,
    },
    InvalidDirectionSign {
        instance: String,
        capability: String,
    },
}

impl Robot {
    pub fn read_from_dir(path: impl AsRef<Path>) -> Result<Self> {
        crate::model::robot::Robot::read_from_dir(path).map(crate::model::robot::Robot::into_v0)
    }

    pub fn read_from_string(string: &str) -> Result<Self> {
        crate::model::robot::Robot::read_from_string(string)
            .map(crate::model::robot::Robot::into_v0)
    }

    pub fn parse_from_dir(path: impl AsRef<Path>) -> Result<Self> {
        crate::model::robot::Robot::parse_from_dir(path).map(crate::model::robot::Robot::into_v0)
    }

    pub fn parse_from_string(string: &str) -> Result<Self> {
        crate::model::robot::Robot::parse_from_string(string)
            .map(crate::model::robot::Robot::into_v0)
    }

    pub fn write_to_dir(&self, path: impl AsRef<Path>) -> Result<()> {
        crate::model::robot::Robot::V0(self.clone()).write_to_dir(path)
    }

    pub fn validate(&self) -> std::result::Result<(), Vec<ValidationError>> {
        let mut errors = Vec::new();
        self.validate_basics(&mut errors);
        self.validate_router(&mut errors);
        self.validate_component_structure(&mut errors);
        self.validate_driver_structure(&mut errors);
        self.validate_role_hints(&mut errors);
        self.validate_kinematics(&mut errors);
        self.validate_numerics(&mut errors);
        validation_result(errors)
    }

    #[must_use]
    pub fn robot_id(&self) -> &str {
        &self.robot.id
    }

    #[must_use]
    pub fn namespace(&self) -> &str {
        &self.robot.namespace
    }

    #[must_use]
    pub fn components(&self) -> &BTreeMap<String, Component> {
        &self.robot.components
    }

    #[must_use]
    pub fn component_instance(&self, component_id: &str) -> Option<&Component> {
        self.robot.components.get(component_id)
    }

    #[must_use]
    pub fn parameter(
        &self,
        capability_ref: &crate::model::component::v0::CapabilityRef,
    ) -> Option<&capability::Parameters> {
        self.component_instance(&capability_ref.component_id)
            .and_then(|component| component.parameters.get(&capability_ref.capability_id))
    }

    #[must_use]
    pub fn used_component_types(&self) -> BTreeSet<&str> {
        self.robot
            .components
            .values()
            .map(|component| component.component.as_str())
            .collect()
    }

    fn validate_basics(&self, errors: &mut Vec<ValidationError>) {
        if self.robot.id.trim().is_empty() {
            errors.push(ValidationError::EmptyRobotId);
        }
        if self.robot.namespace.trim().is_empty() {
            errors.push(ValidationError::EmptyRobotNamespace);
        }
    }

    fn validate_router(&self, errors: &mut Vec<ValidationError>) {
        if let Some(path) = &self.router.config {
            if path.as_os_str().is_empty() {
                errors.push(ValidationError::EmptyRouterConfigPath);
            } else if path.is_absolute() {
                errors.push(ValidationError::AbsoluteRouterConfigPath { path: path.clone() });
            }
        }
    }
}

impl fmt::Display for ValidationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyRobotId => formatter.write_str("robot.id must not be empty"),
            Self::EmptyRobotNamespace => formatter.write_str("robot.namespace must not be empty"),
            Self::EmptyRouterConfigPath => formatter.write_str("router.config must not be empty"),
            Self::AbsoluteRouterConfigPath { path } => write!(
                formatter,
                "router.config path '{}' must be project-relative",
                path.display()
            ),
            Self::InvalidToken { field, value } => write!(
                formatter,
                "{field} value '{value}' must contain only lowercase ASCII letters, digits, '_' or '-'"
            ),
            Self::EmptyComponentType { instance } => write!(
                formatter,
                "robot.components.{instance}.component must not be empty"
            ),
            Self::EmptyMountLink { instance } => {
                write!(
                    formatter,
                    "robot.components.{instance}.mount_link must not be empty"
                )
            }
            Self::EmptyRoleList {
                instance,
                capability,
            } => write!(
                formatter,
                "robot.components.{instance}.roles.{capability} must list at least one role"
            ),
            Self::RepeatedRole {
                instance,
                capability,
                role,
            } => write!(
                formatter,
                "robot.components.{instance}.roles.{capability} repeats role '{role}'"
            ),
            Self::InvalidRuntimeClock { instance } => write!(
                formatter,
                "robot.components.{instance}.driver.runtime_clock_ms must be > 0"
            ),
            Self::InvalidKinematicField { field, message } => {
                write!(formatter, "robot.kinematic.{field} {message}")
            }
            Self::InvalidMotionLimit { field, message } => {
                write!(formatter, "robot.motion_limits.{field} {message}")
            }
            Self::InvalidDirectionSign {
                instance,
                capability,
            } => write!(
                formatter,
                "robot.components.{instance}.parameters.{capability}.direction_sign must be either -1 or 1"
            ),
        }
    }
}

fn validation_result(
    errors: Vec<ValidationError>,
) -> std::result::Result<(), Vec<ValidationError>> {
    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

fn default_structure_path() -> PathBuf {
    PathBuf::from("structure.urdf")
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};

    use super::Robot;

    /// Minimal canonical five-root-key manifest that also passes
    /// [`Robot::validate`] (the kinematic model has one actuator so the
    /// "must not be empty" check does not fire). `extra_top_level` is
    /// appended as additional top-level sections after `robot:`.
    fn minimal_manifest(extra_top_level: &str) -> String {
        format!(
            r#"
schema: robot/v0
robot:
  id: test-bot
  namespace: dev
  motion_limits:
    max_linear_speed_mps: 0.6
    max_angular_speed_radps: 2.0
  kinematic:
    kind: omnidirectional
    actuators: [drive.motor]
    encoders: []
  components: {{}}
{extra_top_level}"#
        )
    }

    #[test]
    fn canonical_five_root_key_manifest_parses_and_round_trips() -> anyhow::Result<()> {
        let yaml = r#"
schema: robot/v0
robot:
  id: rover
  namespace: dev
  structure: structure.urdf
  motion_limits:
    max_linear_speed_mps: 0.6
    max_angular_speed_radps: 2.0
  kinematic:
    kind: differential
    left_actuators: [left_drive.motor]
    right_actuators: [right_drive.motor]
    left_encoders: [left_drive.encoder]
    right_encoders: [right_drive.encoder]
    wheel_radius_m: 0.12
    wheel_base_m: 0.6
  components:
    left_drive:
      component: ddsm115
      mount_link: left_wheel_mount
      driver:
        connection: { type: can, bus: 0, node_id: 1 }
      parameters:
        motor:   { kind: motor,   direction_sign: 1 }
        encoder: { kind: encoder, direction_sign: 1 }
services:
  avoid-obstacles:
    config: { max_linear_speed_mps: 0.6 }
router:
  config: config/router.json5
"#;
        let robot = Robot::parse_from_string(yaml)?;

        assert_eq!(robot.robot.id, "rover");
        assert_eq!(robot.robot.namespace, "dev");
        assert_eq!(robot.robot.structure, PathBuf::from("structure.urdf"));
        let service = robot
            .services
            .get("avoid-obstacles")
            .expect("service should parse");
        assert_eq!(
            service
                .config
                .as_ref()
                .and_then(|config| config.get("max_linear_speed_mps"))
                .and_then(serde_json::Value::as_f64),
            Some(0.6)
        );
        assert_eq!(
            robot.router.config.as_deref(),
            Some(Path::new("config/router.json5"))
        );
        robot
            .validate()
            .expect("canonical manifest should validate");

        let serialized = serde_yaml::to_string(&crate::model::robot::Robot::V0(robot.clone()))?;
        let reparsed = Robot::parse_from_string(&serialized)?;
        assert_eq!(reparsed, robot);

        Ok(())
    }

    #[test]
    fn instance_parameters_parse_emergency_stop_capability() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(
            r#"
schema: robot/v0
robot:
  id: test-bot
  namespace: dev
  motion_limits:
    max_linear_speed_mps: 0.6
    max_angular_speed_radps: 2.0
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
  components:
    estop:
      component: estop
      mount_link: base_link
      parameters:
        e_stop:
          kind: emergency_stop
"#,
        )?;

        let instance = robot
            .robot
            .components
            .get("estop")
            .expect("estop instance should parse");
        let parameters = instance
            .parameters
            .get("e_stop")
            .expect("e_stop capability parameters should parse");
        assert_eq!(parameters.kind_name(), "emergency_stop");

        Ok(())
    }

    #[test]
    fn user_service_config_parses() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(&minimal_manifest(
            r#"services:
  autonomy:
    config:
      max_linear_speed_mps: 0.6
      enabled: true
"#,
        ))?;

        let service = robot
            .services
            .get("autonomy")
            .expect("user service should parse");
        assert_eq!(
            service
                .config
                .as_ref()
                .and_then(|config| config.get("enabled"))
                .and_then(serde_json::Value::as_bool),
            Some(true)
        );
        assert!(robot.router.is_empty());

        Ok(())
    }

    #[test]
    fn user_service_without_config_round_trips_and_omits_config() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(&minimal_manifest(
            r#"services:
  autonomy: {}
"#,
        ))?;
        let yaml = serde_yaml::to_string(&crate::model::robot::Robot::V0(robot.clone()))?;

        assert!(
            !yaml.contains("config:"),
            "absent config should be omitted: {yaml}"
        );

        let reparsed = Robot::parse_from_string(&yaml)?;
        assert_eq!(reparsed.services, robot.services);

        Ok(())
    }

    #[test]
    fn router_config_parses_and_validates() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(&minimal_manifest(
            r#"router:
  config: config/router.json5
"#,
        ))?;

        assert_eq!(
            robot.router.config.as_deref(),
            Some(Path::new("config/router.json5"))
        );
        robot
            .validate()
            .expect("project-relative router config should validate");

        Ok(())
    }

    #[test]
    fn router_rejects_absolute_config_path() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(&minimal_manifest(
            r#"router:
  config: /etc/phoxal/router.json5
"#,
        ))?;

        let errors = robot
            .validate()
            .expect_err("absolute router config should fail validation");
        assert!(
            errors.contains(&super::ValidationError::AbsoluteRouterConfigPath {
                path: PathBuf::from("/etc/phoxal/router.json5"),
            })
        );

        Ok(())
    }

    #[test]
    fn router_rejects_empty_config_path() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(&minimal_manifest(
            r#"router:
  config: ""
"#,
        ))?;

        let errors = robot
            .validate()
            .expect_err("empty router config should fail validation");
        assert!(errors.contains(&super::ValidationError::EmptyRouterConfigPath));
        Ok(())
    }

    #[test]
    fn legacy_bus_section_is_rejected() {
        let error = Robot::parse_from_string(&minimal_manifest(
            r#"bus:
  listen: ["tcp/127.0.0.1:7447"]
"#,
        ))
        .expect_err("legacy bus section should no longer parse");

        assert!(
            format!("{error:#}").contains("unknown field `bus`"),
            "got: {error:#}"
        );
    }

    #[test]
    fn robot_section_rejects_identity_wrapper() {
        let error = Robot::parse_from_string(
            r#"
schema: robot/v0
robot:
  identity:
    id: test-bot
    namespace: dev
  motion_limits:
    max_linear_speed_mps: 0.6
    max_angular_speed_radps: 2.0
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
  components: {}
"#,
        )
        .expect_err("nested identity: wrapper should no longer parse");

        assert!(
            format!("{error:#}").contains("missing field `id`")
                || format!("{error:#}").contains("unknown field `identity`"),
            "got: {error:#}"
        );
    }

    #[test]
    fn robot_section_rejects_motion_wrapper() {
        let error = Robot::parse_from_string(
            r#"
schema: robot/v0
robot:
  id: test-bot
  namespace: dev
  motion:
    kinematic:
      kind: omnidirectional
      actuators: []
      encoders: []
  components: {}
"#,
        )
        .expect_err("motion: wrapper should no longer parse");

        assert!(
            format!("{error:#}").contains("unknown field `motion`")
                || format!("{error:#}").contains("missing field `kinematic`"),
            "got: {error:#}"
        );
    }

    #[test]
    fn manifest_rejects_phoxal_artifacts_key() {
        let error = Robot::parse_from_string(
            r#"
schema: robot/v0
robot:
  id: test-bot
  namespace: dev
  motion_limits:
    max_linear_speed_mps: 0.6
    max_angular_speed_radps: 2.0
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
  components: {}
phoxal_artifacts:
  channel: stable
"#,
        )
        .expect_err("phoxal_artifacts root key should no longer parse");

        assert!(
            format!("{error:#}").contains("unknown field `phoxal_artifacts`"),
            "got: {error:#}"
        );
    }

    #[test]
    fn manifest_rejects_phoxal_participants_key() {
        let error = Robot::parse_from_string(
            r#"
schema: robot/v0
robot:
  id: test-bot
  namespace: dev
  motion_limits:
    max_linear_speed_mps: 0.6
    max_angular_speed_radps: 2.0
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
  components: {}
phoxal_participants: {}
"#,
        )
        .expect_err("phoxal_participants root key should no longer parse");

        assert!(
            format!("{error:#}").contains("unknown field `phoxal_participants`"),
            "got: {error:#}"
        );
    }

    #[test]
    fn manifest_rejects_version_discriminator() {
        let error = Robot::parse_from_string(
            r#"
version: legacy
robot:
  id: test-bot
  namespace: dev
  motion_limits:
    max_linear_speed_mps: 0.6
    max_angular_speed_radps: 2.0
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
  components: {}
"#,
        )
        .expect_err("version discriminator should no longer parse");

        assert!(format!("{error:#}").contains("schema"), "got: {error:#}");
    }

    #[test]
    fn root_tools_map_declares_user_tools_with_config() -> anyhow::Result<()> {
        // The `tools:` map declares additional user tools symmetrically with
        // `services:` (#950); the old pin-style entries (`version:`) stay
        // rejected as unknown fields inside a declaration.
        let robot = Robot::parse_from_string(&minimal_manifest(
            r#"tools:
  lidar-viz:
    config:
      port: 9000
  plain: {}
"#,
        ))?;
        let tool = robot.tools.get("lidar-viz").expect("tool should parse");
        assert_eq!(
            tool.config
                .as_ref()
                .and_then(|config| config.get("port"))
                .and_then(serde_json::Value::as_u64),
            Some(9000)
        );
        assert!(
            robot
                .tools
                .get("plain")
                .expect("plain tool")
                .config
                .is_none()
        );

        let yaml = serde_yaml::to_string(&crate::model::robot::Robot::V0(robot.clone()))?;
        let reparsed = Robot::parse_from_string(&yaml)?;
        assert_eq!(reparsed.tools, robot.tools);

        let error = Robot::parse_from_string(&minimal_manifest(
            "tools:\n  router:\n    version: \"0.4.2\"\n",
        ))
        .expect_err("pin-style tool entries stay rejected");
        assert!(
            format!("{error:#}").contains("unknown field `version`"),
            "got: {error:#}"
        );
        Ok(())
    }

    #[test]
    fn components_sources_nesting_no_longer_parses() {
        let error = Robot::parse_from_string(
            r#"
schema: robot/v0
robot:
  id: test-bot
  namespace: dev
  motion_limits:
    max_linear_speed_mps: 0.6
    max_angular_speed_radps: 2.0
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
  components:
    sources: {}
    instances: {}
"#,
        )
        .expect_err("components.sources/.instances nesting should no longer parse");

        assert!(
            format!("{error:#}").contains("component")
                || format!("{error:#}").contains("missing field"),
            "got: {error:#}"
        );
    }

    #[test]
    fn component_driver_rejects_image_field() {
        let error = Robot::parse_from_string(
            r#"
schema: robot/v0
robot:
  id: test-bot
  namespace: dev
  motion_limits:
    max_linear_speed_mps: 0.6
    max_angular_speed_radps: 2.0
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
  components:
    drive:
      component: ddsm115
      mount_link: drive_mount
      driver:
        image: phoxal/component-ddsm115-driver:v0.1.5
        connection: { type: can, bus: 0, node_id: 1 }
"#,
        )
        .expect_err("driver.image should no longer parse");

        assert!(
            format!("{error:#}").contains("unknown field `image`"),
            "got: {error:#}"
        );
    }

    #[test]
    fn artifacts_and_service_path_are_rejected() {
        let artifacts = Robot::parse_from_string(&minimal_manifest("artifacts:\n  pins: {}\n"))
            .expect_err("Cargo owns source selection");
        assert!(format!("{artifacts:#}").contains("unknown field `artifacts`"));

        let service_path = Robot::parse_from_string(&minimal_manifest(
            "services:\n  autonomy:\n    path: services/autonomy\n",
        ))
        .expect_err("workspace membership owns service discovery");
        assert!(format!("{service_path:#}").contains("unknown field `path`"));
    }

    #[test]
    fn robot_manifest_requires_schema_v0() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(&minimal_manifest(""))?;

        let yaml = serde_yaml::to_string(&crate::model::robot::Robot::V0(robot))?;
        assert!(
            yaml.starts_with("schema: robot/v0\nrobot:\n"),
            "schema should be the first root key: {yaml}"
        );

        Ok(())
    }

    #[test]
    fn empty_robot_id_is_validation_error() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(
            r#"
schema: robot/v0
robot:
  id: ""
  namespace: dev
  motion_limits:
    max_linear_speed_mps: 0.6
    max_angular_speed_radps: 2.0
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
  components: {}
"#,
        )?;

        let errors = robot
            .validate()
            .expect_err("blank robot id should fail validation");

        assert!(errors.contains(&super::ValidationError::EmptyRobotId));
        assert_eq!(
            super::ValidationError::EmptyRobotId.to_string(),
            "robot.id must not be empty"
        );

        Ok(())
    }
}