phoxal 0.26.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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::ops::{Deref, DerefMut};
use std::path::{Path, PathBuf};

use super::{Component, Motion, Role, capability};

const ROBOT_FILE: &str = "robot.yaml";

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Robot {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_version: Option<String>,
    pub identity: Identity,
    #[serde(default = "default_structure_path")]
    pub structure: PathBuf,
    #[serde(default, skip_serializing_if = "PhoxalArtifacts::is_default")]
    pub phoxal_artifacts: PhoxalArtifacts,
    pub phoxal_participants: PhoxalParticipants,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub user_participants: BTreeMap<String, UserParticipant>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub tools: BTreeMap<String, Tool>,
    pub motion: Motion,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub network: Option<Network>,
    pub components: Components,
    #[serde(default, skip_serializing_if = "Bus::is_empty")]
    pub bus: Bus,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Identity {
    pub id: String,
    pub namespace: String,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Channel {
    #[default]
    Stable,
    Preview,
}

impl Channel {
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Stable => "stable",
            Self::Preview => "preview",
        }
    }
}

impl fmt::Display for Channel {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PhoxalArtifacts {
    /// Release channel used when resolving official framework artifacts.
    #[serde(default)]
    pub channel: Channel,
    /// Optional legacy target triple override; native-shape manifests infer this elsewhere.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
    /// Optional API generation ceiling or pin for official artifact resolution.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub generation: Option<String>,
    /// Unified fail-closed pin map keyed by kind-qualified artifact id.
    ///
    /// Keys use the resolved artifact id format, such as `service-drive`,
    /// `driver-ddsm115`, `tool-router`, or `simulator-webots`. The CLI validates
    /// prefixes, existence in the resolved graph, dev-overlay-only path pins, and
    /// whether each key is actually used; the model only rejects empty keys.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub pins: BTreeMap<String, ArtifactPin>,
}

impl PhoxalArtifacts {
    #[must_use]
    pub fn is_default(&self) -> bool {
        self.channel == Channel::Stable
            && self.target.is_none()
            && self.generation.is_none()
            && self.pins.is_empty()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ArtifactPin {
    /// Resolve this artifact from a local source checkout.
    Path(ArtifactPathPin),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ArtifactPathPin {
    /// Project-relative or overlay-relative source path for this artifact.
    pub path: PathBuf,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PhoxalParticipants {
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub images: BTreeMap<String, String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UserParticipant {
    pub path: PathBuf,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub image: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config: Option<serde_json::Value>,
    #[serde(
        default = "default_user_participant_framework",
        skip_serializing_if = "is_match_platform"
    )]
    pub framework: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build: Option<UserParticipantBuild>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UserParticipantBuild {
    #[serde(default = "default_build_context")]
    pub context: PathBuf,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dockerfile: Option<PathBuf>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Bus {
    /// Router listen endpoints merged into the default localhost listen set.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub listen: Vec<String>,
    /// Optional upstream router connection used for deployed robots.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub uplink: Option<BusUplink>,
}

impl Bus {
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.listen.is_empty() && self.uplink.is_none()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BusUplink {
    /// Upstream Zenoh endpoint the site router should connect to.
    pub connect: String,
    /// Optional project-local mTLS material for the upstream connection.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auth: Option<BusMtlsAuth>,
    /// Capped retry backoff; retry is forever and never gates readiness.
    #[serde(default, skip_serializing_if = "BusRetry::is_default")]
    pub retry: BusRetry,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BusMtlsAuth {
    /// Project-local root CA certificate path used to verify the upstream router.
    pub ca: PathBuf,
    /// Project-local client certificate path identifying this robot/site.
    pub cert: PathBuf,
    /// Project-local client private-key path paired with `cert`.
    pub key: PathBuf,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BusRetry {
    /// Initial retry delay in milliseconds.
    #[serde(default = "default_bus_retry_initial_ms")]
    pub initial_ms: u64,
    /// Maximum retry delay in milliseconds.
    #[serde(default = "default_bus_retry_max_ms")]
    pub max_ms: u64,
}

impl Default for BusRetry {
    fn default() -> Self {
        Self {
            initial_ms: default_bus_retry_initial_ms(),
            max_ms: default_bus_retry_max_ms(),
        }
    }
}

impl BusRetry {
    #[must_use]
    pub fn is_default(&self) -> bool {
        *self == Self::default()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Tool {
    pub version: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Network {
    #[serde(default)]
    pub uplink: Uplink,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tls: Option<NetworkTls>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Uplink {
    /// Production zenoh endpoints (e.g. "tls/uplink.phoxal.cloud:7447").
    /// Ignored in sim mode - phoxal-cli rewrites the upstream link.
    #[serde(default)]
    pub endpoints: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NetworkTls {
    pub cert: PathBuf,
    pub key: PathBuf,
    pub ca: PathBuf,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Components {
    pub sources: BTreeMap<String, ComponentSource>,
    pub instances: BTreeMap<String, Component>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ComponentSource {
    Git(SourceGit),
    Path(SourcePath),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SourceGit {
    pub git: String,
    pub tag: String,
    /// Optional subdirectory within the git repository that holds the
    /// component definition (`component.yaml` and friends). Absent means the
    /// component lives at the repository root - the historical single-component
    /// repository layout. Catalog components now live in this repository under
    /// `component/<name>`; robots select one by setting `git` to
    /// `https://github.com/phoxal/framework` and `directory` to
    /// `component/<name>`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub directory: Option<PathBuf>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SourcePath {
    pub path: PathBuf,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationError {
    EmptyApiVersion,
    EmptyIdentityId,
    EmptyIdentityNamespace,
    UnknownPlatformParticipantImage {
        name: String,
    },
    UserParticipantShadowsPlatformParticipant {
        name: String,
    },
    EmptyUserParticipantImage {
        participant: String,
    },
    EmptyBusListenEndpoint {
        index: usize,
    },
    UnsupportedBusListenEndpoint {
        endpoint: String,
    },
    NonLoopbackTcpBusListenEndpoint {
        endpoint: String,
    },
    EmptyBusUplinkConnect,
    EmptyBusUplinkAuthPath {
        field: String,
    },
    AbsoluteBusUplinkAuthPath {
        field: String,
        path: PathBuf,
    },
    InvalidBusRetryBackoff,
    EmptyArtifactPinKey,
    MissingComponentSource {
        instance: String,
        source: String,
    },
    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,
    },
    InvalidDirectionSign {
        instance: String,
        capability: String,
    },
}

impl Robot {
    pub fn read_from_dir(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        Self::read_from_string(
            &std::fs::read_to_string(path.join(ROBOT_FILE)).with_context(|| {
                format!(
                    "failed to read robot file {}",
                    path.join(ROBOT_FILE).display()
                )
            })?,
        )
    }

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

    pub fn parse_from_dir(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        Self::parse_from_string(
            &std::fs::read_to_string(path.join(ROBOT_FILE)).with_context(|| {
                format!(
                    "failed to read robot file {}",
                    path.join(ROBOT_FILE).display()
                )
            })?,
        )
    }

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

    pub fn write_to_dir(&self, path: impl AsRef<Path>) -> Result<()> {
        crate::model::robot::Robot::V1(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_bus(&mut errors);
        self.validate_artifact_pins(&mut errors);
        self.validate_user_participants(&mut errors);
        self.validate_component_sources(&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)
    }

    pub fn validate_with(
        &self,
        platform_participant_names: &[&str],
    ) -> std::result::Result<(), Vec<ValidationError>> {
        let mut errors = match self.validate() {
            Ok(()) => Vec::new(),
            Err(errors) => errors,
        };
        let platform_participant_names = platform_participant_names
            .iter()
            .copied()
            .collect::<BTreeSet<_>>();

        for participant_name in self.phoxal_participants.images.keys() {
            if !platform_participant_names.contains(participant_name.as_str()) {
                errors.push(ValidationError::UnknownPlatformParticipantImage {
                    name: participant_name.clone(),
                });
            }
        }
        for participant_name in self.user_participants.keys() {
            if platform_participant_names.contains(participant_name.as_str()) {
                errors.push(ValidationError::UserParticipantShadowsPlatformParticipant {
                    name: participant_name.clone(),
                });
            }
        }

        validation_result(errors)
    }

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

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

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

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

    #[must_use]
    pub fn parameter(
        &self,
        capability_ref: &crate::model::component::v1::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.components
            .instances
            .values()
            .map(|component| component.component.as_str())
            .collect()
    }

    fn validate_basics(&self, errors: &mut Vec<ValidationError>) {
        if self
            .api_version
            .as_deref()
            .is_some_and(|api_version| api_version.trim().is_empty())
        {
            errors.push(ValidationError::EmptyApiVersion);
        }
        if self.identity.id.trim().is_empty() {
            errors.push(ValidationError::EmptyIdentityId);
        }
        if self.identity.namespace.trim().is_empty() {
            errors.push(ValidationError::EmptyIdentityNamespace);
        }
    }

    fn validate_artifact_pins(&self, errors: &mut Vec<ValidationError>) {
        if self
            .phoxal_artifacts
            .pins
            .keys()
            .any(|artifact_id| artifact_id.trim().is_empty())
        {
            errors.push(ValidationError::EmptyArtifactPinKey);
        }
    }

    fn validate_component_sources(&self, errors: &mut Vec<ValidationError>) {
        for (instance_name, instance) in &self.components.instances {
            if !self.components.sources.contains_key(&instance.component) {
                errors.push(ValidationError::MissingComponentSource {
                    instance: instance_name.clone(),
                    source: instance.component.clone(),
                });
            }
        }
    }

    fn validate_bus(&self, errors: &mut Vec<ValidationError>) {
        for (index, endpoint) in self.bus.listen.iter().enumerate() {
            validate_bus_listen_endpoint(index, endpoint, errors);
        }

        if let Some(uplink) = &self.bus.uplink {
            if uplink.connect.trim().is_empty() {
                errors.push(ValidationError::EmptyBusUplinkConnect);
            }
            if let Some(auth) = &uplink.auth {
                validate_project_local_path("ca", &auth.ca, errors);
                validate_project_local_path("cert", &auth.cert, errors);
                validate_project_local_path("key", &auth.key, errors);
            }
            if uplink.retry.initial_ms == 0
                || uplink.retry.max_ms == 0
                || uplink.retry.initial_ms > uplink.retry.max_ms
            {
                errors.push(ValidationError::InvalidBusRetryBackoff);
            }
        }
    }

    fn validate_user_participants(&self, errors: &mut Vec<ValidationError>) {
        for (participant, config) in &self.user_participants {
            if config
                .image
                .as_deref()
                .is_some_and(|image| image.trim().is_empty())
            {
                errors.push(ValidationError::EmptyUserParticipantImage {
                    participant: participant.clone(),
                });
            }
        }
    }
}

impl Components {
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.sources.is_empty() && self.instances.is_empty()
    }
}

impl Deref for Components {
    type Target = BTreeMap<String, Component>;

    fn deref(&self) -> &Self::Target {
        &self.instances
    }
}

impl DerefMut for Components {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.instances
    }
}

impl<'a> IntoIterator for &'a Components {
    type Item = (&'a String, &'a Component);
    type IntoIter = std::collections::btree_map::Iter<'a, String, Component>;

    fn into_iter(self) -> Self::IntoIter {
        self.instances.iter()
    }
}

impl<'a> IntoIterator for &'a mut Components {
    type Item = (&'a String, &'a mut Component);
    type IntoIter = std::collections::btree_map::IterMut<'a, String, Component>;

    fn into_iter(self) -> Self::IntoIter {
        self.instances.iter_mut()
    }
}

impl fmt::Display for ValidationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyApiVersion => formatter.write_str("api_version must not be empty"),
            Self::EmptyIdentityId => formatter.write_str("identity.id must not be empty"),
            Self::EmptyIdentityNamespace => {
                formatter.write_str("identity.namespace must not be empty")
            }
            Self::UnknownPlatformParticipantImage { name } => write!(
                formatter,
                "phoxal_participants.images.{name} is not a platform participant"
            ),
            Self::UserParticipantShadowsPlatformParticipant { name } => {
                write!(
                    formatter,
                    "user_participants.{name} shadows a platform participant"
                )
            }
            Self::EmptyUserParticipantImage { participant } => {
                write!(
                    formatter,
                    "user_participants.{participant}.image must not be empty"
                )
            }
            Self::EmptyBusListenEndpoint { index } => {
                write!(formatter, "bus.listen[{index}] must not be empty")
            }
            Self::UnsupportedBusListenEndpoint { endpoint } => write!(
                formatter,
                "bus.listen endpoint '{endpoint}' must use serial/ or tcp/ on day one"
            ),
            Self::NonLoopbackTcpBusListenEndpoint { endpoint } => write!(
                formatter,
                "bus.listen TCP endpoint '{endpoint}' must bind loopback until listen auth ships"
            ),
            Self::EmptyBusUplinkConnect => {
                formatter.write_str("bus.uplink.connect must not be empty")
            }
            Self::EmptyBusUplinkAuthPath { field } => {
                write!(formatter, "bus.uplink.auth.{field} must not be empty")
            }
            Self::AbsoluteBusUplinkAuthPath { field, path } => write!(
                formatter,
                "bus.uplink.auth.{field} path '{}' must be project-local",
                path.display()
            ),
            Self::InvalidBusRetryBackoff => formatter.write_str(
                "bus.uplink.retry initial_ms and max_ms must be > 0 with initial_ms <= max_ms",
            ),
            Self::EmptyArtifactPinKey => {
                formatter.write_str("phoxal_artifacts.pins keys must not be empty")
            }
            Self::MissingComponentSource { instance, source } => write!(
                formatter,
                "components.instances.{instance}.component references missing source '{source}'"
            ),
            Self::InvalidToken { field, value } => write!(
                formatter,
                "{field} value '{value}' must contain only lowercase ASCII letters, digits, '_' or '-'"
            ),
            Self::EmptyComponentType { instance } => write!(
                formatter,
                "components.instances.{instance}.component must not be empty"
            ),
            Self::EmptyMountLink { instance } => {
                write!(
                    formatter,
                    "components.instances.{instance}.mount_link must not be empty"
                )
            }
            Self::EmptyRoleList {
                instance,
                capability,
            } => write!(
                formatter,
                "components.instances.{instance}.roles.{capability} must list at least one role"
            ),
            Self::RepeatedRole {
                instance,
                capability,
                role,
            } => write!(
                formatter,
                "components.instances.{instance}.roles.{capability} repeats role '{role}'"
            ),
            Self::InvalidRuntimeClock { instance } => write!(
                formatter,
                "components.instances.{instance}.driver.runtime_clock_ms must be > 0"
            ),
            Self::InvalidKinematicField { field, message } => {
                write!(formatter, "motion.kinematic.{field} {message}")
            }
            Self::InvalidDirectionSign {
                instance,
                capability,
            } => write!(
                formatter,
                "components.instances.{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")
}

fn default_user_participant_framework() -> String {
    "match-platform".to_string()
}

fn is_match_platform(framework: &str) -> bool {
    framework == "match-platform"
}

fn default_build_context() -> PathBuf {
    PathBuf::from(".")
}

fn default_bus_retry_initial_ms() -> u64 {
    1_000
}

fn default_bus_retry_max_ms() -> u64 {
    30_000
}

fn validate_bus_listen_endpoint(index: usize, endpoint: &str, errors: &mut Vec<ValidationError>) {
    let endpoint = endpoint.trim();
    if endpoint.is_empty() {
        errors.push(ValidationError::EmptyBusListenEndpoint { index });
    } else if endpoint.starts_with("serial/") {
        // Zenoh owns serial endpoint parsing; day-one framework validation only
        // gates the accepted listen schemes.
    } else if let Some(rest) = endpoint.strip_prefix("tcp/") {
        if !tcp_endpoint_is_loopback(rest) {
            errors.push(ValidationError::NonLoopbackTcpBusListenEndpoint {
                endpoint: endpoint.to_string(),
            });
        }
    } else {
        errors.push(ValidationError::UnsupportedBusListenEndpoint {
            endpoint: endpoint.to_string(),
        });
    }
}

fn tcp_endpoint_is_loopback(endpoint_tail: &str) -> bool {
    let host = endpoint_tail
        .strip_prefix('[')
        .and_then(|tail| tail.split_once(']').map(|(host, _rest)| host))
        .or_else(|| endpoint_tail.split_once(':').map(|(host, _port)| host))
        .unwrap_or(endpoint_tail);

    host == "localhost" || host == "::1" || host == "127.0.0.1" || host.starts_with("127.")
}

fn validate_project_local_path(field: &str, path: &Path, errors: &mut Vec<ValidationError>) {
    if path.as_os_str().is_empty() {
        errors.push(ValidationError::EmptyBusUplinkAuthPath {
            field: field.to_string(),
        });
    } else if path.is_absolute() {
        errors.push(ValidationError::AbsoluteBusUplinkAuthPath {
            field: field.to_string(),
            path: path.to_path_buf(),
        });
    }
}

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

    use super::{ArtifactPathPin, ArtifactPin, Channel, Robot, UserParticipantBuild};

    fn robot_yaml_with_phoxal_artifacts(phoxal_artifacts: &str) -> String {
        format!(
            r#"
schema: v0
identity:
  id: test-bot
  namespace: dev
phoxal_artifacts:
{phoxal_artifacts}
phoxal_participants: {{}}
motion:
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
components:
  sources: {{}}
  instances: {{}}
"#
        )
    }

    #[test]
    fn instance_parameters_parse_emergency_stop_capability() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(
            r#"
schema: v0
identity:
  id: test-bot
  namespace: dev
phoxal_participants: {}
motion:
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
components:
  sources:
    estop:
      path: components/estop
  instances:
    estop:
      component: estop
      mount_link: base_link
      parameters:
        e_stop:
          kind: emergency_stop
"#,
        )?;

        let instance = robot
            .components
            .instances
            .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_participant_with_only_path_defaults_framework_and_build() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(
            r#"
schema: v0
api_version: y2026_1
identity:
  id: test-bot
  namespace: dev
phoxal_participants: {}
user_participants:
  autonomy:
    path: participants/autonomy
motion:
  kinematic:
    kind: omnidirectional
    actuators:
    - drive.motor
    encoders: []
components:
  sources:
    drive:
      path: ../component/drive
  instances:
    drive:
      component: drive
      mount_link: drive_link
      parameters:
        motor:
          kind: motor
"#,
        )?;

        let participant = robot
            .user_participants
            .get("autonomy")
            .expect("user participant should parse");
        assert_eq!(participant.path, PathBuf::from("participants/autonomy"));
        assert_eq!(participant.framework, "match-platform");
        assert_eq!(participant.image, None);
        assert_eq!(participant.config, None);
        assert_eq!(participant.build, None);
        assert!(robot.bus.is_empty());

        Ok(())
    }

    #[test]
    fn user_participant_parses_framework_and_full_build_recipe() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(
            r#"
schema: v0
api_version: y2026_1
identity:
  id: test-bot
  namespace: dev
phoxal_participants: {}
user_participants:
  autonomy:
    path: participants/autonomy
    framework: "0.9.0"
    build:
      context: container
      dockerfile: Dockerfile.participant
      target: participant
motion:
  kinematic:
    kind: omnidirectional
    actuators:
    - drive.motor
    encoders: []
components:
  sources: {}
  instances: {}
"#,
        )?;

        let participant = robot
            .user_participants
            .get("autonomy")
            .expect("user participant should parse");
        assert_eq!(participant.framework, "0.9.0");
        assert_eq!(
            participant.build,
            Some(UserParticipantBuild {
                context: PathBuf::from("container"),
                dockerfile: Some(PathBuf::from("Dockerfile.participant")),
                target: Some("participant".to_string()),
            })
        );

        Ok(())
    }

    #[test]
    fn bus_listen_and_uplink_parse_and_validate() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(
            r#"
schema: v0
api_version: y2026_1
identity:
  id: test-bot
  namespace: dev
phoxal_participants: {}
user_participants:
  autonomy:
    path: participants/autonomy
    image: ghcr.io/acme/autonomy@sha256:abc
    config:
      max_linear_speed_mps: 0.6
      enabled: true
motion:
  kinematic:
    kind: omnidirectional
    actuators:
    - drive.motor
    encoders: []
components:
  sources:
    drive:
      path: ../component/drive
  instances:
    drive:
      component: drive
      mount_link: drive_link
      parameters:
        motor:
          kind: motor
bus:
  listen:
  - serial//dev/ttyACM0#baudrate=115200
  - tcp/127.0.0.1:7448
  uplink:
    connect: tls/uplink.phoxal.cloud:7447
    auth:
      ca: identity/ca.pem
      cert: identity/robot.pem
      key: identity/robot.key
    retry:
      initial_ms: 2000
      max_ms: 10000
"#,
        )?;

        let participant = robot
            .user_participants
            .get("autonomy")
            .expect("user participant should parse");
        assert_eq!(
            participant.image.as_deref(),
            Some("ghcr.io/acme/autonomy@sha256:abc")
        );
        assert_eq!(
            participant
                .config
                .as_ref()
                .and_then(|config| config.get("enabled"))
                .and_then(serde_json::Value::as_bool),
            Some(true)
        );
        assert_eq!(
            robot.bus.listen,
            vec![
                "serial//dev/ttyACM0#baudrate=115200".to_string(),
                "tcp/127.0.0.1:7448".to_string(),
            ]
        );
        let uplink = robot.bus.uplink.as_ref().expect("uplink should parse");
        assert_eq!(uplink.connect, "tls/uplink.phoxal.cloud:7447");
        assert_eq!(uplink.retry.initial_ms, 2000);
        assert_eq!(uplink.retry.max_ms, 10000);
        assert_eq!(
            uplink.auth.as_ref().map(|auth| auth.cert.as_path()),
            Some(Path::new("identity/robot.pem"))
        );
        robot
            .validate()
            .expect("bus listen and uplink should validate");

        Ok(())
    }

    #[test]
    fn bus_rejects_non_loopback_tcp_listen() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(
            r#"
schema: v0
api_version: y2026_1
identity:
  id: test-bot
  namespace: dev
phoxal_participants: {}
motion:
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
components:
  sources: {}
  instances: {}
bus:
  listen:
  - tcp/0.0.0.0:7447
"#,
        )?;

        let errors = robot
            .validate()
            .expect_err("non-loopback TCP listen should fail validation");
        assert!(
            errors.contains(&super::ValidationError::NonLoopbackTcpBusListenEndpoint {
                endpoint: "tcp/0.0.0.0:7447".to_string(),
            })
        );

        Ok(())
    }

    #[test]
    fn user_participant_rejects_retired_bus_profile_field() {
        let error = Robot::parse_from_string(
            r#"
schema: v0
api_version: y2026_1
identity:
  id: test-bot
  namespace: dev
phoxal_participants: {}
user_participants:
  autonomy:
    path: participants/autonomy
    bus_profile: default
motion:
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
components:
  sources: {}
  instances: {}
"#,
        )
        .expect_err("retired bus_profile field should fail to parse");

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

    #[test]
    fn user_participant_build_rejects_unknown_fields() {
        let error = Robot::parse_from_string(
            r#"
schema: v0
api_version: y2026_1
identity:
  id: test-bot
  namespace: dev
phoxal_participants: {}
user_participants:
  autonomy:
    path: participants/autonomy
    build:
      bogus: 1
motion:
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
components:
  sources: {}
  instances: {}
"#,
        )
        .expect_err("unknown build fields should fail to parse");

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

    #[test]
    fn user_participant_round_trips_and_omits_default_framework_and_empty_build()
    -> anyhow::Result<()> {
        let default_robot = Robot::parse_from_string(
            r#"
schema: v0
api_version: y2026_1
identity:
  id: test-bot
  namespace: dev
phoxal_participants: {}
user_participants:
  autonomy:
    path: participants/autonomy
motion:
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
components:
  sources: {}
  instances: {}
"#,
        )?;
        let default_yaml = serde_yaml::to_string(&crate::model::robot::Robot::V1(default_robot))?;

        assert!(
            !default_yaml.contains("framework:"),
            "default framework should be omitted: {default_yaml}"
        );
        assert!(
            !default_yaml.contains("build:"),
            "empty build recipe should be omitted: {default_yaml}"
        );

        let robot = Robot::parse_from_string(
            r#"
schema: v0
api_version: y2026_1
identity:
  id: test-bot
  namespace: dev
phoxal_participants: {}
user_participants:
  autonomy:
    path: participants/autonomy
    framework: "0.9.0"
    build:
      context: container
      dockerfile: Dockerfile.participant
      target: participant
motion:
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
components:
  sources: {}
  instances: {}
"#,
        )?;
        let yaml = serde_yaml::to_string(&crate::model::robot::Robot::V1(robot.clone()))?;
        let reparsed = Robot::parse_from_string(&yaml)?;

        assert_eq!(reparsed.user_participants, robot.user_participants);

        Ok(())
    }

    #[test]
    fn phoxal_artifacts_defaults_to_stable_without_pin_or_target() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(
            r#"
schema: v0
identity:
  id: test-bot
  namespace: dev
phoxal_participants: {}
motion:
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
components:
  sources: {}
  instances: {}
"#,
        )?;

        assert_eq!(robot.api_version, None);
        assert_eq!(robot.phoxal_artifacts.channel, Channel::Stable);
        assert_eq!(robot.phoxal_artifacts.channel.as_str(), "stable");
        assert_eq!(robot.phoxal_artifacts.channel.to_string(), "stable");
        assert_eq!(robot.phoxal_artifacts.target, None);
        assert_eq!(robot.phoxal_artifacts.generation, None);
        assert!(robot.phoxal_participants.images.is_empty());

        Ok(())
    }

    #[test]
    fn phoxal_artifacts_rejects_invalid_channel() {
        let error = Robot::parse_from_string(
            r#"
schema: v0
api_version: y2026_1
identity:
  id: test-bot
  namespace: dev
phoxal_artifacts:
  channel: experimental
phoxal_participants: {}
motion:
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
components:
  sources: {}
  instances: {}
"#,
        )
        .expect_err("invalid phoxal_artifacts channel should fail to parse");

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

    #[test]
    fn phoxal_artifacts_parses_preview_target_and_generation_pin() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(
            r#"
schema: v0
identity:
  id: test-bot
  namespace: dev
phoxal_artifacts:
  channel: preview
  target: aarch64-unknown-linux-gnu
  generation: y2026_2
phoxal_participants: {}
motion:
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
components:
  sources: {}
  instances: {}
"#,
        )?;

        assert_eq!(robot.phoxal_artifacts.channel, Channel::Preview);
        assert_eq!(
            robot.phoxal_artifacts.target.as_deref(),
            Some("aarch64-unknown-linux-gnu")
        );
        assert_eq!(
            robot.phoxal_artifacts.generation.as_deref(),
            Some("y2026_2")
        );

        Ok(())
    }

    #[test]
    fn phoxal_artifacts_pins_path_entry_round_trips() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(&robot_yaml_with_phoxal_artifacts(
            r#"  pins:
    service-drive:
      path: ../framework/service/drive"#,
        ))?;

        assert_eq!(
            robot.phoxal_artifacts.pins.get("service-drive"),
            Some(&ArtifactPin::Path(ArtifactPathPin {
                path: PathBuf::from("../framework/service/drive"),
            }))
        );

        let yaml = serde_yaml::to_string(&crate::model::robot::Robot::V1(robot.clone()))?;
        assert!(
            yaml.contains("pins:\n    service-drive:\n      path: ../framework/service/drive"),
            "path pin should serialize in the unified pins map: {yaml}"
        );

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

        Ok(())
    }

    #[test]
    fn phoxal_artifacts_pins_unknown_value_forms_are_errors() {
        for pin in [
            r#"  pins:
    service-drive: v0.8.4"#,
            r#"  pins:
    service-drive: "sha256:222222""#,
            r#"  pins:
    driver-ddsm115:
      git: https://github.com/you/ddsm115
      rev: 9f2c1e7"#,
            r#"  pins:
    tool-router:
      archive: router.tar.zst"#,
        ] {
            let error = Robot::parse_from_string(&robot_yaml_with_phoxal_artifacts(pin))
                .expect_err("unsupported pin form should fail to parse");

            assert!(
                format!("{error:#}").contains("data did not match any variant of untagged enum"),
                "got: {error:#}"
            );
        }
    }

    #[test]
    fn phoxal_artifacts_pins_rejects_unknown_fields_inside_path_pin() {
        let error = Robot::parse_from_string(&robot_yaml_with_phoxal_artifacts(
            r#"  pins:
    service-drive:
      path: ../framework/service/drive
      rev: 9f2c1e7"#,
        ))
        .expect_err("unknown path pin field should fail to parse");

        assert!(
            format!("{error:#}").contains("data did not match any variant of untagged enum"),
            "got: {error:#}"
        );
    }

    #[test]
    fn phoxal_artifacts_empty_pins_are_absent_from_serialization() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(&robot_yaml_with_phoxal_artifacts(
            r#"  channel: preview
  pins: {}"#,
        ))?;

        let yaml = serde_yaml::to_string(&crate::model::robot::Robot::V1(robot))?;

        assert!(
            yaml.contains("phoxal_artifacts:\n  channel: preview"),
            "non-default artifacts section should serialize: {yaml}"
        );
        assert!(
            !yaml.contains("pins:"),
            "empty pins map should be omitted from serialization: {yaml}"
        );

        Ok(())
    }

    #[test]
    fn phoxal_artifacts_empty_pin_key_is_validation_error() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(&robot_yaml_with_phoxal_artifacts(
            r#"  pins:
    "":
      path: ../framework/service/drive"#,
        ))?;

        let errors = robot
            .validate()
            .expect_err("empty artifact pin key should fail validation");

        assert!(errors.contains(&super::ValidationError::EmptyArtifactPinKey));
        assert_eq!(
            super::ValidationError::EmptyArtifactPinKey.to_string(),
            "phoxal_artifacts.pins keys must not be empty"
        );

        Ok(())
    }

    #[test]
    fn phoxal_participants_rejects_old_version_field() {
        let error = Robot::parse_from_string(
            r#"
schema: v0
api_version: y2026_1
identity:
  id: test-bot
  namespace: dev
phoxal_participants:
  version: "latest"
motion:
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
components:
  sources: {}
  instances: {}
"#,
        )
        .expect_err("old phoxal_participants version field should fail to parse");

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

    #[test]
    fn phoxal_participants_images_parse_and_validate_against_platform_participants()
    -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(
            r#"
schema: v0
api_version: y2026_1
identity:
  id: test-bot
  namespace: dev
phoxal_artifacts:
  channel: preview
phoxal_participants:
  images:
    drive: ghcr.io/phoxal/runtime-drive:y2026_1-v0.8.4
motion:
  kinematic:
    kind: omnidirectional
    actuators:
    - drive.motor
    encoders: []
components:
  sources: {}
  instances: {}
"#,
        )?;

        assert_eq!(robot.phoxal_artifacts.channel, Channel::Preview);
        assert_eq!(
            robot.phoxal_participants.images.get("drive"),
            Some(&"ghcr.io/phoxal/runtime-drive:y2026_1-v0.8.4".to_string())
        );
        robot
            .validate_with(&["drive"])
            .expect("known platform image key should validate");

        let errors = robot
            .validate_with(&["odometry"])
            .expect_err("unknown platform image key should fail validation");

        assert!(
            errors.contains(&super::ValidationError::UnknownPlatformParticipantImage {
                name: "drive".to_string(),
            })
        );
        assert_eq!(
            super::ValidationError::UnknownPlatformParticipantImage {
                name: "drive".to_string(),
            }
            .to_string(),
            "phoxal_participants.images.drive is not a platform participant"
        );

        Ok(())
    }

    #[test]
    fn robot_manifest_requires_schema_v0_and_allows_omitted_api_version() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(
            r#"
schema: v0
identity:
  id: test-bot
  namespace: dev
phoxal_participants: {}
motion:
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
components:
  sources: {}
  instances: {}
"#,
        )?;

        assert_eq!(robot.api_version, None);

        let yaml = serde_yaml::to_string(&crate::model::robot::Robot::V1(robot))?;
        assert!(
            yaml.starts_with("schema: v0\nidentity:\n"),
            "schema should be the first root key and api_version should be omitted by default: {yaml}"
        );

        let old_manifest_error = Robot::parse_from_string(
            r#"
version: v1
identity:
  id: test-bot
  namespace: dev
phoxal_participants: {}
motion:
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
components:
  sources: {}
  instances: {}
"#,
        )
        .expect_err("old version discriminator should no longer parse");

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

        Ok(())
    }

    #[test]
    fn present_blank_api_version_is_validation_error() -> anyhow::Result<()> {
        let robot = Robot::parse_from_string(
            r#"
schema: v0
api_version: " "
identity:
  id: test-bot
  namespace: dev
phoxal_participants: {}
motion:
  kinematic:
    kind: omnidirectional
    actuators: []
    encoders: []
components:
  sources: {}
  instances: {}
"#,
        )?;

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

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

        Ok(())
    }
}