peat-protocol 0.9.0-rc.6

Peat Coordination Protocol — hierarchical capability composition over CRDTs for heterogeneous mesh networks
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
//! Emergent composition rules
//!
//! This module implements composition rules for emergent capabilities - new
//! capabilities that arise from specific combinations of individual capabilities.
//!
//! Examples:
//! - ISR Chain: Sensor + Compute + Communication → Intelligence gathering
//! - 3D Mapping: Camera + Lidar + Compute → Detailed 3D maps
//! - Strike Chain: ISR + Strike + BDA → Complete targeting cycle

use crate::composition::rules::{CompositionContext, CompositionResult, CompositionRule};
use crate::models::capability::{Capability, CapabilityType};
use crate::models::CapabilityExt;
use crate::Result;
use async_trait::async_trait;
use serde_json::{json, Value};

/// Rule for detecting ISR (Intelligence, Surveillance, Reconnaissance) chain capability
///
/// Requires: Sensor + Compute + Communication capabilities
/// Emergent capability: Complete ISR chain for intelligence gathering
pub struct IsrChainRule {
    /// Minimum confidence threshold for each component
    min_confidence: f32,
}

impl IsrChainRule {
    /// Create a new ISR chain rule
    pub fn new(min_confidence: f32) -> Self {
        Self { min_confidence }
    }
}

impl Default for IsrChainRule {
    fn default() -> Self {
        Self::new(0.7)
    }
}

#[async_trait]
impl CompositionRule for IsrChainRule {
    fn name(&self) -> &str {
        "isr_chain"
    }

    fn description(&self) -> &str {
        "Detects emergent ISR chain capability from sensor + compute + communication"
    }

    fn applies_to(&self, capabilities: &[Capability]) -> bool {
        let has_sensor = capabilities.iter().any(|c| {
            c.get_capability_type() == CapabilityType::Sensor && c.confidence >= self.min_confidence
        });

        let has_compute = capabilities.iter().any(|c| {
            c.get_capability_type() == CapabilityType::Compute
                && c.confidence >= self.min_confidence
        });

        let has_comms = capabilities.iter().any(|c| {
            c.get_capability_type() == CapabilityType::Communication
                && c.confidence >= self.min_confidence
        });

        has_sensor && has_compute && has_comms
    }

    async fn compose(
        &self,
        capabilities: &[Capability],
        _context: &CompositionContext,
    ) -> Result<CompositionResult> {
        // Find best capability of each required type
        let best_sensor = capabilities
            .iter()
            .filter(|c| c.get_capability_type() == CapabilityType::Sensor)
            .max_by(|a, b| a.confidence.partial_cmp(&b.confidence).unwrap());

        let best_compute = capabilities
            .iter()
            .filter(|c| c.get_capability_type() == CapabilityType::Compute)
            .max_by(|a, b| a.confidence.partial_cmp(&b.confidence).unwrap());

        let best_comms = capabilities
            .iter()
            .filter(|c| c.get_capability_type() == CapabilityType::Communication)
            .max_by(|a, b| a.confidence.partial_cmp(&b.confidence).unwrap());

        // Check if we have all required components
        if let (Some(sensor), Some(compute), Some(comms)) = (best_sensor, best_compute, best_comms)
        {
            // Emergent capability confidence is minimum of components (weakest link)
            let chain_confidence = sensor
                .confidence
                .min(compute.confidence)
                .min(comms.confidence);

            let mut composed = Capability::new(
                format!("emergent_isr_chain_{}", uuid::Uuid::new_v4()),
                "ISR Chain".to_string(),
                CapabilityType::Emergent,
                chain_confidence,
            );
            composed.metadata_json = serde_json::to_string(&json!({
                "composition_type": "emergent",
                "pattern": "isr_chain",
                "components": {
                    "sensor": sensor.id,
                    "compute": compute.id,
                    "communication": comms.id
                },
                "description": "Complete intelligence gathering capability"
            }))
            .unwrap_or_default();

            let contributors = vec![sensor.id.clone(), compute.id.clone(), comms.id.clone()];

            return Ok(CompositionResult::new(vec![composed], chain_confidence)
                .with_contributors(contributors));
        }

        Ok(CompositionResult::new(vec![], 0.0))
    }
}

/// Rule for detecting 3D mapping capability
///
/// Requires: Camera + Lidar + Compute capabilities
/// Emergent capability: Detailed 3D environment mapping
pub struct Mapping3dRule {
    /// Minimum confidence threshold for each component
    min_confidence: f32,
}

impl Mapping3dRule {
    /// Create a new 3D mapping rule
    pub fn new(min_confidence: f32) -> Self {
        Self { min_confidence }
    }
}

impl Default for Mapping3dRule {
    fn default() -> Self {
        Self::new(0.7)
    }
}

#[async_trait]
impl CompositionRule for Mapping3dRule {
    fn name(&self) -> &str {
        "mapping_3d"
    }

    fn description(&self) -> &str {
        "Detects emergent 3D mapping capability from camera + lidar + compute"
    }

    fn applies_to(&self, capabilities: &[Capability]) -> bool {
        // Look for camera sensor
        let has_camera = capabilities.iter().any(|c| {
            c.get_capability_type() == CapabilityType::Sensor
                && c.confidence >= self.min_confidence
                && serde_json::from_str::<Value>(&c.metadata_json)
                    .ok()
                    .and_then(|v| {
                        v.get("sensor_type")
                            .and_then(|s| s.as_str())
                            .map(|s| s == "camera")
                    })
                    .unwrap_or(false)
        });

        // Look for lidar sensor
        let has_lidar = capabilities.iter().any(|c| {
            c.get_capability_type() == CapabilityType::Sensor
                && c.confidence >= self.min_confidence
                && serde_json::from_str::<Value>(&c.metadata_json)
                    .ok()
                    .and_then(|v| {
                        v.get("sensor_type")
                            .and_then(|s| s.as_str())
                            .map(|s| s == "lidar")
                    })
                    .unwrap_or(false)
        });

        let has_compute = capabilities.iter().any(|c| {
            c.get_capability_type() == CapabilityType::Compute
                && c.confidence >= self.min_confidence
        });

        has_camera && has_lidar && has_compute
    }

    async fn compose(
        &self,
        capabilities: &[Capability],
        _context: &CompositionContext,
    ) -> Result<CompositionResult> {
        // Find required capabilities
        let camera = capabilities.iter().find(|c| {
            c.get_capability_type() == CapabilityType::Sensor
                && serde_json::from_str::<Value>(&c.metadata_json)
                    .ok()
                    .and_then(|v| {
                        v.get("sensor_type")
                            .and_then(|s| s.as_str())
                            .map(|s| s == "camera")
                    })
                    .unwrap_or(false)
        });

        let lidar = capabilities.iter().find(|c| {
            c.get_capability_type() == CapabilityType::Sensor
                && serde_json::from_str::<Value>(&c.metadata_json)
                    .ok()
                    .and_then(|v| {
                        v.get("sensor_type")
                            .and_then(|s| s.as_str())
                            .map(|s| s == "lidar")
                    })
                    .unwrap_or(false)
        });

        let compute = capabilities
            .iter()
            .filter(|c| c.get_capability_type() == CapabilityType::Compute)
            .max_by(|a, b| a.confidence.partial_cmp(&b.confidence).unwrap());

        if let (Some(camera), Some(lidar), Some(compute)) = (camera, lidar, compute) {
            // Confidence is minimum of all components
            let mapping_confidence = camera
                .confidence
                .min(lidar.confidence)
                .min(compute.confidence);

            let mut composed = Capability::new(
                format!("emergent_3d_mapping_{}", uuid::Uuid::new_v4()),
                "3D Mapping".to_string(),
                CapabilityType::Emergent,
                mapping_confidence,
            );
            composed.metadata_json = serde_json::to_string(&json!({
                "composition_type": "emergent",
                "pattern": "3d_mapping",
                "components": {
                    "camera": camera.id,
                    "lidar": lidar.id,
                    "compute": compute.id
                },
                "description": "Real-time 3D environment mapping"
            }))
            .unwrap_or_default();

            let contributors = vec![camera.id.clone(), lidar.id.clone(), compute.id.clone()];

            return Ok(CompositionResult::new(vec![composed], mapping_confidence)
                .with_contributors(contributors));
        }

        Ok(CompositionResult::new(vec![], 0.0))
    }
}

/// Rule for detecting strike chain capability
///
/// Requires: ISR + Strike + BDA (Battle Damage Assessment) capabilities
/// Emergent capability: Complete targeting and assessment cycle
pub struct StrikeChainRule {
    /// Minimum confidence threshold for each component
    min_confidence: f32,
}

impl StrikeChainRule {
    /// Create a new strike chain rule
    pub fn new(min_confidence: f32) -> Self {
        Self { min_confidence }
    }
}

impl Default for StrikeChainRule {
    fn default() -> Self {
        Self::new(0.8) // Higher threshold for lethal operations
    }
}

#[async_trait]
impl CompositionRule for StrikeChainRule {
    fn name(&self) -> &str {
        "strike_chain"
    }

    fn description(&self) -> &str {
        "Detects emergent strike chain capability from ISR + strike + BDA"
    }

    fn applies_to(&self, capabilities: &[Capability]) -> bool {
        // Look for ISR capability (could be emergent from another rule)
        let has_isr = capabilities.iter().any(|c| {
            c.get_capability_type() == CapabilityType::Emergent
                && c.confidence >= self.min_confidence
                && serde_json::from_str::<Value>(&c.metadata_json)
                    .ok()
                    .map(|v| {
                        let is_isr_pattern =
                            v.get("pattern").and_then(|p| p.as_str()) == Some("isr_chain");
                        let is_isr_capable = v
                            .get("isr_capable")
                            .and_then(|i| i.as_bool())
                            .unwrap_or(false);
                        is_isr_pattern || is_isr_capable
                    })
                    .unwrap_or(false)
        });

        // Look for strike/payload capability
        let has_strike = capabilities.iter().any(|c| {
            c.get_capability_type() == CapabilityType::Payload
                && c.confidence >= self.min_confidence
                && serde_json::from_str::<Value>(&c.metadata_json)
                    .ok()
                    .and_then(|v| v.get("strike_capable").and_then(|s| s.as_bool()))
                    .unwrap_or(false)
        });

        // Look for BDA capability (sensor for assessment)
        let has_bda = capabilities.iter().any(|c| {
            c.get_capability_type() == CapabilityType::Sensor && c.confidence >= self.min_confidence
        });

        has_isr && has_strike && has_bda
    }

    async fn compose(
        &self,
        capabilities: &[Capability],
        _context: &CompositionContext,
    ) -> Result<CompositionResult> {
        // Find ISR capability
        let isr = capabilities.iter().find(|c| {
            c.get_capability_type() == CapabilityType::Emergent
                && serde_json::from_str::<Value>(&c.metadata_json)
                    .ok()
                    .and_then(|v| {
                        v.get("pattern")
                            .and_then(|p| p.as_str())
                            .map(|s| s == "isr_chain")
                    })
                    .unwrap_or(false)
        });

        // Find strike capability
        let strike = capabilities
            .iter()
            .filter(|c| {
                c.get_capability_type() == CapabilityType::Payload
                    && serde_json::from_str::<Value>(&c.metadata_json)
                        .ok()
                        .and_then(|v| v.get("strike_capable").and_then(|s| s.as_bool()))
                        .unwrap_or(false)
            })
            .max_by(|a, b| a.confidence.partial_cmp(&b.confidence).unwrap());

        // Find BDA sensor
        let bda = capabilities
            .iter()
            .filter(|c| c.get_capability_type() == CapabilityType::Sensor)
            .max_by(|a, b| a.confidence.partial_cmp(&b.confidence).unwrap());

        if let (Some(isr), Some(strike), Some(bda)) = (isr, strike, bda) {
            // Confidence is minimum of all components (critical for strike operations)
            let chain_confidence = isr.confidence.min(strike.confidence).min(bda.confidence);

            let mut composed = Capability::new(
                format!("emergent_strike_chain_{}", uuid::Uuid::new_v4()),
                "Strike Chain".to_string(),
                CapabilityType::Emergent,
                chain_confidence,
            );
            composed.metadata_json = serde_json::to_string(&json!({
                "composition_type": "emergent",
                "pattern": "strike_chain",
                "components": {
                    "isr": isr.id,
                    "strike": strike.id,
                    "bda": bda.id
                },
                "description": "Complete targeting cycle with assessment",
                "requires_human_approval": true // Safety critical
            }))
            .unwrap_or_default();

            let contributors = vec![isr.id.clone(), strike.id.clone(), bda.id.clone()];

            return Ok(CompositionResult::new(vec![composed], chain_confidence)
                .with_contributors(contributors));
        }

        Ok(CompositionResult::new(vec![], 0.0))
    }
}

/// Rule for detecting authorization coverage capability
///
/// Checks if the composition has human-in-the-loop authorization coverage.
/// Requires: Communication capability + Node with bound Operator having sufficient authority
/// Emergent capability: Authorization/command coverage for the party
pub struct AuthorizationCoverageRule {
    /// Minimum authority level required
    min_authority: crate::models::AuthorityLevel,
}

impl AuthorizationCoverageRule {
    /// Create a new authorization coverage rule
    pub fn new(min_authority: crate::models::AuthorityLevel) -> Self {
        Self { min_authority }
    }

    /// Create rule requiring Commander authority (for lethal/critical actions)
    pub fn commander_required() -> Self {
        Self::new(crate::models::AuthorityLevel::Commander)
    }

    /// Create rule requiring Supervisor authority (for general override)
    pub fn supervisor_required() -> Self {
        Self::new(crate::models::AuthorityLevel::Supervisor)
    }
}

impl Default for AuthorizationCoverageRule {
    fn default() -> Self {
        Self::commander_required()
    }
}

#[async_trait]
impl CompositionRule for AuthorizationCoverageRule {
    fn name(&self) -> &str {
        "authorization_coverage"
    }

    fn description(&self) -> &str {
        "Detects authorization coverage from communication + human operator with sufficient authority"
    }

    fn applies_to(&self, capabilities: &[Capability]) -> bool {
        // Requires at least Communication capability
        // The actual authority check happens in compose() using context.node_configs
        capabilities
            .iter()
            .any(|c| c.get_capability_type() == CapabilityType::Communication)
    }

    async fn compose(
        &self,
        capabilities: &[Capability],
        context: &CompositionContext,
    ) -> Result<CompositionResult> {
        use crate::models::{AuthorityLevelExt, HumanMachinePairExt};

        // Find best communication capability
        let best_comms = capabilities
            .iter()
            .filter(|c| c.get_capability_type() == CapabilityType::Communication)
            .max_by(|a, b| a.confidence.partial_cmp(&b.confidence).unwrap());

        // Check for operator with sufficient authority
        let max_authority = context.max_authority();

        let has_sufficient_authority = max_authority
            .map(|auth| auth >= self.min_authority)
            .unwrap_or(false);

        if let (Some(comms), true) = (best_comms, has_sufficient_authority) {
            let authority = max_authority.unwrap();
            let auth_score = authority.to_score() as f32;

            // Confidence is combination of comms quality and authority level
            let coverage_confidence = (comms.confidence * 0.4 + auth_score * 0.6).min(1.0);

            let mut composed = Capability::new(
                format!("emergent_auth_coverage_{}", uuid::Uuid::new_v4()),
                "Authorization Coverage".to_string(),
                CapabilityType::Emergent,
                coverage_confidence,
            );

            // Find the node with the authorizing operator
            let authorizing_node = context
                .node_configs
                .iter()
                .find(|config| {
                    config
                        .operator_binding
                        .as_ref()
                        .and_then(|b| b.max_authority())
                        .map(|a| a >= self.min_authority)
                        .unwrap_or(false)
                })
                .map(|c| c.id.clone());

            composed.metadata_json = serde_json::to_string(&json!({
                "composition_type": "emergent",
                "pattern": "authorization_coverage",
                "components": {
                    "communication": comms.id,
                    "authorizing_node": authorizing_node,
                },
                "authority_level": format!("{:?}", authority),
                "authorization_bonus": context.authorization_bonus(),
                "can_authorize_strike": authority == crate::models::AuthorityLevel::Commander,
                "description": "Human-in-the-loop authorization capability"
            }))
            .unwrap_or_default();

            let contributors = vec![comms.id.clone()];

            return Ok(CompositionResult::new(vec![composed], coverage_confidence)
                .with_contributors(contributors));
        }

        Ok(CompositionResult::new(vec![], 0.0))
    }
}

/// Rule for detecting multi-domain coverage capability
///
/// Requires: Sensors or capabilities that cover multiple domains (Air, Surface, Subsurface)
/// Emergent capability: Multi-domain battlespace awareness
pub struct MultiDomainCoverageRule {
    /// Minimum number of domains required for the rule to apply
    min_domains: usize,
    /// Minimum confidence threshold for sensors
    min_confidence: f32,
}

impl MultiDomainCoverageRule {
    /// Create a new multi-domain coverage rule
    pub fn new(min_domains: usize, min_confidence: f32) -> Self {
        Self {
            min_domains: min_domains.max(2), // At least 2 domains for "multi"
            min_confidence,
        }
    }

    /// Create rule requiring all three domains
    pub fn full_spectrum() -> Self {
        Self::new(3, 0.7)
    }

    /// Create rule requiring any two domains
    pub fn dual_domain() -> Self {
        Self::new(2, 0.7)
    }

    /// Extract sensor type and infer domains
    fn get_sensor_domains(cap: &Capability) -> crate::models::DomainSet {
        use crate::models::{DomainSet, SensorType};

        if cap.get_capability_type() != CapabilityType::Sensor {
            return DomainSet::empty();
        }

        // Try to get sensor type from metadata
        let sensor_type = serde_json::from_str::<serde_json::Value>(&cap.metadata_json)
            .ok()
            .and_then(|v| {
                v.get("sensor_type").and_then(|s| s.as_str()).and_then(|s| {
                    match s.to_lowercase().as_str() {
                        "electro_optical" | "eo" | "camera" => Some(SensorType::ElectroOptical),
                        "infrared" | "ir" | "thermal" => Some(SensorType::Infrared),
                        "radar" | "rad" => Some(SensorType::Radar),
                        "sonar" | "son" => Some(SensorType::Sonar),
                        "acoustic" | "aco" => Some(SensorType::Acoustic),
                        "sigint" | "sig" | "signals_intelligence" => Some(SensorType::Sigint),
                        "mad" | "magnetic" => Some(SensorType::Mad),
                        _ => None,
                    }
                })
            });

        if let Some(st) = sensor_type {
            st.detection_domains()
        } else {
            // If sensor type not specified, check for explicit domains
            serde_json::from_str::<serde_json::Value>(&cap.metadata_json)
                .ok()
                .and_then(|v| {
                    v.get("detection_domains").and_then(|domains| {
                        if let Some(arr) = domains.as_array() {
                            let mut set = DomainSet::empty();
                            for d in arr {
                                if let Some(s) = d.as_str() {
                                    if let Some(domain) = crate::models::Domain::parse(s) {
                                        set.add(domain);
                                    }
                                }
                            }
                            Some(set)
                        } else {
                            None
                        }
                    })
                })
                .unwrap_or_else(|| {
                    // Default: assume surface + air for unknown sensors
                    DomainSet::from_domains(&[
                        crate::models::Domain::Surface,
                        crate::models::Domain::Air,
                    ])
                })
        }
    }
}

impl Default for MultiDomainCoverageRule {
    fn default() -> Self {
        Self::dual_domain()
    }
}

#[async_trait]
impl CompositionRule for MultiDomainCoverageRule {
    fn name(&self) -> &str {
        "multi_domain_coverage"
    }

    fn description(&self) -> &str {
        "Detects multi-domain coverage from sensors spanning air, surface, and/or subsurface"
    }

    fn applies_to(&self, capabilities: &[Capability]) -> bool {
        use crate::models::DomainSet;

        // Aggregate domains from all capabilities
        let mut covered = DomainSet::empty();

        for cap in capabilities {
            if cap.confidence < self.min_confidence {
                continue;
            }

            // Get domains this capability covers
            let domains = Self::get_sensor_domains(cap);
            covered = covered.union(&domains);
        }

        covered.count() >= self.min_domains
    }

    async fn compose(
        &self,
        capabilities: &[Capability],
        _context: &CompositionContext,
    ) -> Result<CompositionResult> {
        use crate::models::{Domain, DomainSet};

        let mut covered = DomainSet::empty();
        let mut contributors: Vec<String> = Vec::new();
        let mut domain_sensors: std::collections::HashMap<Domain, Vec<String>> =
            std::collections::HashMap::new();
        let mut min_confidence = 1.0f32;

        for cap in capabilities {
            if cap.confidence < self.min_confidence {
                continue;
            }

            let domains = Self::get_sensor_domains(cap);

            if !domains.is_empty() {
                contributors.push(cap.id.clone());
                min_confidence = min_confidence.min(cap.confidence);

                for domain in domains.iter() {
                    covered.add(domain);
                    domain_sensors
                        .entry(domain)
                        .or_default()
                        .push(cap.id.clone());
                }
            }
        }

        if covered.count() < self.min_domains {
            return Ok(CompositionResult::new(vec![], 0.0));
        }

        // Calculate composition bonus based on coverage
        let coverage_bonus = match covered.count() {
            3 => 3, // Full spectrum
            2 => 2, // Dual domain
            _ => 1, // Single domain (shouldn't happen but safe)
        };

        // Confidence is minimum of all contributors, boosted slightly by coverage
        let coverage_confidence = (min_confidence + (coverage_bonus as f32 * 0.05)).min(1.0);

        let coverage_name = match covered.count() {
            3 => "Full Spectrum Coverage",
            2 => "Dual-Domain Coverage",
            _ => "Domain Coverage",
        };

        let mut composed = Capability::new(
            format!("emergent_multi_domain_{}", uuid::Uuid::new_v4()),
            coverage_name.to_string(),
            CapabilityType::Emergent,
            coverage_confidence,
        );

        // Build domain coverage map for metadata
        let domain_coverage: serde_json::Map<String, serde_json::Value> = domain_sensors
            .iter()
            .map(|(domain, sensors)| {
                (
                    domain.name().to_lowercase(),
                    serde_json::Value::Array(
                        sensors
                            .iter()
                            .map(|s| serde_json::Value::String(s.clone()))
                            .collect(),
                    ),
                )
            })
            .collect();

        composed.metadata_json = serde_json::to_string(&json!({
            "composition_type": "emergent",
            "pattern": "multi_domain_coverage",
            "domains_covered": covered.to_vec().iter().map(|d| d.name()).collect::<Vec<_>>(),
            "domain_count": covered.count(),
            "coverage_bonus": coverage_bonus,
            "domain_sensors": domain_coverage,
            "is_full_spectrum": covered.count() == 3,
            "can_detect_subsurface": covered.contains(Domain::Subsurface),
            "description": format!("Multi-domain awareness across {} domains", covered.count())
        }))
        .unwrap_or_default();

        Ok(CompositionResult::new(vec![composed], coverage_confidence)
            .with_contributors(contributors))
    }
}

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

    #[tokio::test]
    async fn test_isr_chain_detection() {
        let rule = IsrChainRule::default();

        let mut sensor = Capability::new(
            "sensor1".to_string(),
            "EO Camera".to_string(),
            CapabilityType::Sensor,
            0.9,
        );
        sensor.metadata_json =
            serde_json::to_string(&json!({"sensor_type": "camera"})).unwrap_or_default();

        let compute = Capability::new(
            "compute1".to_string(),
            "Edge Compute".to_string(),
            CapabilityType::Compute,
            0.85,
        );

        let mut comms = Capability::new(
            "comms1".to_string(),
            "Tactical Radio".to_string(),
            CapabilityType::Communication,
            0.8,
        );
        comms.metadata_json =
            serde_json::to_string(&json!({"bandwidth": 10.0})).unwrap_or_default();

        let caps = vec![sensor, compute, comms];
        let context = CompositionContext::new(vec!["node1".to_string()]);

        assert!(rule.applies_to(&caps));

        let result = rule.compose(&caps, &context).await.unwrap();
        assert!(result.has_compositions());
        assert_eq!(result.composed_capabilities.len(), 1);

        let composed = &result.composed_capabilities[0];
        assert_eq!(composed.get_capability_type(), CapabilityType::Emergent);
        assert_eq!(composed.name, "ISR Chain");
        // Confidence should be minimum of all components (0.8)
        assert_eq!(composed.confidence, 0.8);
        assert_eq!(result.contributing_capabilities.len(), 3);
    }

    #[tokio::test]
    async fn test_isr_chain_missing_component() {
        let rule = IsrChainRule::default();

        let sensor = Capability::new(
            "sensor1".to_string(),
            "Sensor".to_string(),
            CapabilityType::Sensor,
            0.9,
        );

        let compute = Capability::new(
            "compute1".to_string(),
            "Compute".to_string(),
            CapabilityType::Compute,
            0.85,
        );

        // Missing communication capability
        let caps = vec![sensor, compute];

        assert!(!rule.applies_to(&caps));
    }

    #[tokio::test]
    async fn test_3d_mapping_detection() {
        let rule = Mapping3dRule::default();

        let mut camera = Capability::new(
            "camera1".to_string(),
            "RGB Camera".to_string(),
            CapabilityType::Sensor,
            0.95,
        );
        camera.metadata_json =
            serde_json::to_string(&json!({"sensor_type": "camera"})).unwrap_or_default();

        let mut lidar = Capability::new(
            "lidar1".to_string(),
            "3D Lidar".to_string(),
            CapabilityType::Sensor,
            0.9,
        );
        lidar.metadata_json =
            serde_json::to_string(&json!({"sensor_type": "lidar"})).unwrap_or_default();

        let compute = Capability::new(
            "compute1".to_string(),
            "GPU Compute".to_string(),
            CapabilityType::Compute,
            0.85,
        );

        let caps = vec![camera, lidar, compute];
        let context = CompositionContext::new(vec!["node1".to_string()]);

        assert!(rule.applies_to(&caps));

        let result = rule.compose(&caps, &context).await.unwrap();
        assert!(result.has_compositions());

        let composed = &result.composed_capabilities[0];
        assert_eq!(composed.name, "3D Mapping");
        assert_eq!(composed.confidence, 0.85); // Min of components
        assert_eq!(result.contributing_capabilities.len(), 3);
    }

    #[tokio::test]
    async fn test_strike_chain_detection() {
        let rule = StrikeChainRule::default();

        // Create an ISR capability (would come from IsrChainRule)
        let mut isr = Capability::new(
            "isr1".to_string(),
            "ISR Chain".to_string(),
            CapabilityType::Emergent,
            0.9,
        );
        isr.metadata_json = serde_json::to_string(&json!({
            "pattern": "isr_chain"
        }))
        .unwrap_or_default();

        let mut strike = Capability::new(
            "strike1".to_string(),
            "Precision Munition".to_string(),
            CapabilityType::Payload,
            0.95,
        );
        strike.metadata_json =
            serde_json::to_string(&json!({"strike_capable": true})).unwrap_or_default();

        let bda_sensor = Capability::new(
            "bda1".to_string(),
            "BDA Camera".to_string(),
            CapabilityType::Sensor,
            0.85,
        );

        let caps = vec![isr, strike, bda_sensor];
        let context = CompositionContext::new(vec!["node1".to_string(), "node2".to_string()]);

        assert!(rule.applies_to(&caps));

        let result = rule.compose(&caps, &context).await.unwrap();
        assert!(result.has_compositions());

        let composed = &result.composed_capabilities[0];
        assert_eq!(composed.name, "Strike Chain");
        assert_eq!(composed.confidence, 0.85); // Min of all components
        let metadata: Value = serde_json::from_str(&composed.metadata_json).unwrap();
        assert!(metadata["requires_human_approval"].as_bool().unwrap());
        assert_eq!(result.contributing_capabilities.len(), 3);
    }

    #[tokio::test]
    async fn test_low_confidence_component_affects_emergent() {
        let rule = IsrChainRule::default();

        let sensor = Capability::new(
            "sensor1".to_string(),
            "Sensor".to_string(),
            CapabilityType::Sensor,
            0.95,
        );

        let compute = Capability::new(
            "compute1".to_string(),
            "Compute".to_string(),
            CapabilityType::Compute,
            0.9,
        );

        // Low confidence comms - this should drag down the emergent capability
        let comms = Capability::new(
            "comms1".to_string(),
            "Comms".to_string(),
            CapabilityType::Communication,
            0.5,
        );

        let caps = vec![sensor, compute, comms];
        let context = CompositionContext::new(vec!["node1".to_string()]);

        let result = rule.compose(&caps, &context).await.unwrap();

        // Emergent confidence should be limited by weakest link
        let composed = &result.composed_capabilities[0];
        assert_eq!(composed.confidence, 0.5);
    }

    #[tokio::test]
    async fn test_authorization_coverage_with_commander() {
        use crate::models::{
            AuthorityLevel, HumanMachinePair, HumanMachinePairExt, NodeConfig, NodeConfigExt,
            Operator, OperatorExt, OperatorRank,
        };

        let rule = AuthorizationCoverageRule::default();

        // Create communication capability
        let comms = Capability::new(
            "radio1".to_string(),
            "Tactical Radio".to_string(),
            CapabilityType::Communication,
            0.9,
        );

        let caps = vec![comms];

        // Create a node with a Commander-level operator
        let operator = Operator::new(
            "op1".to_string(),
            "CPT Smith".to_string(),
            OperatorRank::O3,
            AuthorityLevel::Commander,
            "11A".to_string(),
        );

        let binding = HumanMachinePair::one_to_one(operator, "node1".to_string());
        let config = NodeConfig::with_operator("Command Post".to_string(), binding);

        let context =
            CompositionContext::new(vec!["node1".to_string()]).with_node_configs(vec![config]);

        assert!(rule.applies_to(&caps));
        assert!(context.has_commander());
        assert_eq!(context.authorization_bonus(), 4); // Commander = 0.8 * 5 = 4

        let result = rule.compose(&caps, &context).await.unwrap();
        assert!(result.has_compositions());

        let composed = &result.composed_capabilities[0];
        assert_eq!(composed.name, "Authorization Coverage");

        let metadata: Value = serde_json::from_str(&composed.metadata_json).unwrap();
        assert!(metadata["can_authorize_strike"].as_bool().unwrap());
        assert_eq!(metadata["authorization_bonus"].as_i64().unwrap(), 4);
    }

    #[tokio::test]
    async fn test_authorization_coverage_without_operator() {
        let rule = AuthorizationCoverageRule::default();

        let comms = Capability::new(
            "radio1".to_string(),
            "Autonomous Radio".to_string(),
            CapabilityType::Communication,
            0.9,
        );

        let caps = vec![comms];

        // No operator binding
        let context = CompositionContext::new(vec!["node1".to_string()]);

        assert!(rule.applies_to(&caps));
        assert!(!context.has_commander());
        assert_eq!(context.authorization_bonus(), 0);

        let result = rule.compose(&caps, &context).await.unwrap();
        assert!(!result.has_compositions()); // No authorization without human
    }

    #[tokio::test]
    async fn test_authorization_coverage_supervisor_level() {
        use crate::models::{
            AuthorityLevel, HumanMachinePair, HumanMachinePairExt, NodeConfig, NodeConfigExt,
            Operator, OperatorExt, OperatorRank,
        };

        // Use supervisor-level rule
        let rule = AuthorizationCoverageRule::supervisor_required();

        let comms = Capability::new(
            "radio1".to_string(),
            "Radio".to_string(),
            CapabilityType::Communication,
            0.85,
        );

        let caps = vec![comms];

        // Create a node with Supervisor authority (not Commander)
        let operator = Operator::new(
            "op1".to_string(),
            "SGT Jones".to_string(),
            OperatorRank::E5,
            AuthorityLevel::Supervisor,
            "11B".to_string(),
        );

        let binding = HumanMachinePair::one_to_one(operator, "node1".to_string());
        let config = NodeConfig::with_operator("Control Station".to_string(), binding);

        let context =
            CompositionContext::new(vec!["node1".to_string()]).with_node_configs(vec![config]);

        // Supervisor level rule should find coverage
        let result = rule.compose(&caps, &context).await.unwrap();
        assert!(result.has_compositions());

        let composed = &result.composed_capabilities[0];
        let metadata: Value = serde_json::from_str(&composed.metadata_json).unwrap();
        // Supervisor can't authorize strikes
        assert!(!metadata["can_authorize_strike"].as_bool().unwrap());
        // Supervisor = 0.5 * 5 = 2.5 rounds to 2 or 3
        assert!(metadata["authorization_bonus"].as_i64().unwrap() >= 2);
    }

    #[tokio::test]
    async fn test_authorization_coverage_insufficient_authority() {
        use crate::models::{
            AuthorityLevel, HumanMachinePair, HumanMachinePairExt, NodeConfig, NodeConfigExt,
            Operator, OperatorExt, OperatorRank,
        };

        // Commander-level rule (default)
        let rule = AuthorizationCoverageRule::default();

        let comms = Capability::new(
            "radio1".to_string(),
            "Radio".to_string(),
            CapabilityType::Communication,
            0.9,
        );

        let caps = vec![comms];

        // Only Advisor authority - not sufficient for Commander requirement
        let operator = Operator::new(
            "op1".to_string(),
            "SPC Brown".to_string(),
            OperatorRank::E4,
            AuthorityLevel::Advisor,
            "11B".to_string(),
        );

        let binding = HumanMachinePair::one_to_one(operator, "node1".to_string());
        let config = NodeConfig::with_operator("Observation Post".to_string(), binding);

        let context =
            CompositionContext::new(vec!["node1".to_string()]).with_node_configs(vec![config]);

        let result = rule.compose(&caps, &context).await.unwrap();
        assert!(!result.has_compositions()); // Advisor can't satisfy Commander requirement
    }

    // MultiDomainCoverageRule tests

    #[tokio::test]
    async fn test_multi_domain_dual_domain_coverage() {
        let rule = MultiDomainCoverageRule::default(); // dual domain

        // Radar (air+surface) + Sonar (subsurface+surface)
        let mut radar = Capability::new(
            "radar1".to_string(),
            "Search Radar".to_string(),
            CapabilityType::Sensor,
            0.9,
        );
        radar.metadata_json = serde_json::to_string(&json!({
            "sensor_type": "radar"
        }))
        .unwrap();

        let mut sonar = Capability::new(
            "sonar1".to_string(),
            "Hull Sonar".to_string(),
            CapabilityType::Sensor,
            0.85,
        );
        sonar.metadata_json = serde_json::to_string(&json!({
            "sensor_type": "sonar"
        }))
        .unwrap();

        let caps = vec![radar, sonar];
        let context = CompositionContext::new(vec!["ship1".to_string()]);

        assert!(rule.applies_to(&caps));

        let result = rule.compose(&caps, &context).await.unwrap();
        assert!(result.has_compositions());

        let composed = &result.composed_capabilities[0];
        assert!(composed.name.contains("Coverage"));

        let metadata: Value = serde_json::from_str(&composed.metadata_json).unwrap();
        assert!(metadata["domain_count"].as_i64().unwrap() >= 2);
        assert!(metadata["can_detect_subsurface"].as_bool().unwrap());
    }

    #[tokio::test]
    async fn test_multi_domain_full_spectrum() {
        let rule = MultiDomainCoverageRule::full_spectrum();

        // Need sensors covering all three domains
        let mut radar = Capability::new(
            "radar1".to_string(),
            "Air Search Radar".to_string(),
            CapabilityType::Sensor,
            0.9,
        );
        radar.metadata_json = serde_json::to_string(&json!({
            "sensor_type": "radar"
        }))
        .unwrap();

        let mut sonar = Capability::new(
            "sonar1".to_string(),
            "Sonar".to_string(),
            CapabilityType::Sensor,
            0.85,
        );
        sonar.metadata_json = serde_json::to_string(&json!({
            "sensor_type": "sonar"
        }))
        .unwrap();

        // Together radar (air+surface) + sonar (subsurface+surface) = all 3 domains
        let caps = vec![radar, sonar];
        let context = CompositionContext::new(vec!["ship1".to_string()]);

        assert!(rule.applies_to(&caps));

        let result = rule.compose(&caps, &context).await.unwrap();
        assert!(result.has_compositions());

        let composed = &result.composed_capabilities[0];
        assert_eq!(composed.name, "Full Spectrum Coverage");

        let metadata: Value = serde_json::from_str(&composed.metadata_json).unwrap();
        assert!(metadata["is_full_spectrum"].as_bool().unwrap());
        assert_eq!(metadata["domain_count"].as_i64().unwrap(), 3);
        assert_eq!(metadata["coverage_bonus"].as_i64().unwrap(), 3);
    }

    #[tokio::test]
    async fn test_multi_domain_insufficient_coverage() {
        let rule = MultiDomainCoverageRule::full_spectrum();

        // Only one sensor type = not full spectrum
        let mut radar = Capability::new(
            "radar1".to_string(),
            "Radar".to_string(),
            CapabilityType::Sensor,
            0.9,
        );
        radar.metadata_json = serde_json::to_string(&json!({
            "sensor_type": "radar"
        }))
        .unwrap();

        let caps = vec![radar];
        let _context = CompositionContext::new(vec!["node1".to_string()]);

        // Radar only covers air+surface, not subsurface
        assert!(!rule.applies_to(&caps));
    }

    #[tokio::test]
    async fn test_multi_domain_low_confidence_filtered() {
        let rule = MultiDomainCoverageRule::new(2, 0.8); // min 0.8 confidence

        let mut radar = Capability::new(
            "radar1".to_string(),
            "Radar".to_string(),
            CapabilityType::Sensor,
            0.9, // Good
        );
        radar.metadata_json = serde_json::to_string(&json!({
            "sensor_type": "radar"
        }))
        .unwrap();

        let mut sonar = Capability::new(
            "sonar1".to_string(),
            "Sonar".to_string(),
            CapabilityType::Sensor,
            0.5, // Too low - should be filtered
        );
        sonar.metadata_json = serde_json::to_string(&json!({
            "sensor_type": "sonar"
        }))
        .unwrap();

        let caps = vec![radar, sonar];
        let context = CompositionContext::new(vec!["node1".to_string()]);

        // Sonar filtered due to low confidence, so only 2 domains from radar
        assert!(rule.applies_to(&caps)); // radar still covers air+surface = 2 domains

        let result = rule.compose(&caps, &context).await.unwrap();
        assert!(result.has_compositions());

        // Only radar should be a contributor
        assert_eq!(result.contributing_capabilities.len(), 1);
    }

    #[tokio::test]
    async fn test_multi_domain_explicit_domains_in_metadata() {
        let rule = MultiDomainCoverageRule::default();

        // Sensor with explicit domain specification
        let mut custom_sensor = Capability::new(
            "custom1".to_string(),
            "Custom Sensor".to_string(),
            CapabilityType::Sensor,
            0.9,
        );
        custom_sensor.metadata_json = serde_json::to_string(&json!({
            "detection_domains": ["subsurface", "surface", "air"]
        }))
        .unwrap();

        let caps = vec![custom_sensor];
        let context = CompositionContext::new(vec!["node1".to_string()]);

        // Single sensor covering all domains
        assert!(rule.applies_to(&caps));

        let result = rule.compose(&caps, &context).await.unwrap();
        assert!(result.has_compositions());

        let composed = &result.composed_capabilities[0];
        let metadata: Value = serde_json::from_str(&composed.metadata_json).unwrap();
        assert_eq!(metadata["domain_count"].as_i64().unwrap(), 3);
    }

    #[tokio::test]
    async fn test_multi_domain_acoustic_covers_all() {
        let rule = MultiDomainCoverageRule::full_spectrum();

        // Acoustic sensor covers all domains
        let mut acoustic = Capability::new(
            "acoustic1".to_string(),
            "Acoustic Array".to_string(),
            CapabilityType::Sensor,
            0.85,
        );
        acoustic.metadata_json = serde_json::to_string(&json!({
            "sensor_type": "acoustic"
        }))
        .unwrap();

        let caps = vec![acoustic];
        let context = CompositionContext::new(vec!["node1".to_string()]);

        assert!(rule.applies_to(&caps));

        let result = rule.compose(&caps, &context).await.unwrap();
        assert!(result.has_compositions());

        let composed = &result.composed_capabilities[0];
        assert_eq!(composed.name, "Full Spectrum Coverage");
    }

    #[tokio::test]
    async fn test_multi_domain_non_sensors_ignored() {
        let rule = MultiDomainCoverageRule::default();

        // Non-sensor capabilities should be ignored
        let compute = Capability::new(
            "compute1".to_string(),
            "Compute".to_string(),
            CapabilityType::Compute,
            0.9,
        );

        let comms = Capability::new(
            "comms1".to_string(),
            "Radio".to_string(),
            CapabilityType::Communication,
            0.9,
        );

        let caps = vec![compute, comms];
        let _context = CompositionContext::new(vec!["node1".to_string()]);

        // No sensors = no domain coverage
        assert!(!rule.applies_to(&caps));
    }

    #[tokio::test]
    async fn test_multi_domain_mad_for_asw() {
        let rule = MultiDomainCoverageRule::default();

        // MAD operates from air/surface but detects subsurface
        let mut mad = Capability::new(
            "mad1".to_string(),
            "MAD Boom".to_string(),
            CapabilityType::Sensor,
            0.8,
        );
        mad.metadata_json = serde_json::to_string(&json!({
            "sensor_type": "mad"
        }))
        .unwrap();

        let mut radar = Capability::new(
            "radar1".to_string(),
            "Surface Radar".to_string(),
            CapabilityType::Sensor,
            0.9,
        );
        radar.metadata_json = serde_json::to_string(&json!({
            "sensor_type": "radar"
        }))
        .unwrap();

        let caps = vec![mad, radar];
        let context = CompositionContext::new(vec!["p3c".to_string()]); // ASW aircraft

        assert!(rule.applies_to(&caps));

        let result = rule.compose(&caps, &context).await.unwrap();
        assert!(result.has_compositions());

        let composed = &result.composed_capabilities[0];
        let metadata: Value = serde_json::from_str(&composed.metadata_json).unwrap();
        // MAD detects subsurface, radar detects air+surface = 3 domains
        assert!(metadata["can_detect_subsurface"].as_bool().unwrap());
    }
}