mycelix-bridge-common 0.1.0

Cross-cluster coordination types and bridge infrastructure for Mycelix
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
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
pub type AgentPubKey = [u8; 32];
pub type CapSecret = Vec<u8>;

// Copyright (C) 2024-2026 Tristan Stoltz / Luminous Dynamics
// SPDX-License-Identifier: AGPL-3.0-or-later
// Commercial licensing: see COMMERCIAL_LICENSE.md at repository root
// Mycelix Bridge Common — Shared dispatch types and utilities
//
// Provides the cross-domain dispatch primitives used by both the
// Commons and Civic cluster bridge zomes. Each cluster's bridge
// coordinator imports these types and calls `dispatch_call_checked()`
// with its own allowlist.
//
// ## Civic Thresholds (always available)
//
// The `consciousness_thresholds` module (legacy name) contains the canonical
// threshold constants. The `sovereign_gate` module provides the 8D Sovereign
// Profile gating system that replaces the old 4D consciousness gating.

pub mod constitutional_envelope;
// ── Model governance extensions (feature-gated) ──────────────────────────
pub mod consciousness_thresholds;
pub mod consciousness_zkp;
pub mod membership_zkp;
#[cfg(feature = "model-governance")]
pub mod model_governance;
#[cfg(feature = "model-governance")]
pub mod scoring_model;
#[cfg(feature = "model-governance")]
pub mod shadow_evaluation;
/// Backward-compatible module alias — allows `mycelix_bridge_common::phi_thresholds::*` paths.
pub use consciousness_thresholds as phi_thresholds;
pub use consciousness_thresholds::{ConsciousnessThresholds, PhiThresholds};

pub mod consciousness_profile;
// Pure Rust re-exports (always available)
pub use consciousness_profile::{
    bootstrap_credential, decay_reputation, evaluate_bootstrap_governance, evaluate_governance,
    evaluate_governance_with_reputation, is_bootstrap_eligible, needs_refresh,
    requirement_for_basic, requirement_for_constitutional, requirement_for_guardian,
    requirement_for_proposal, requirement_for_voting, ConsciousnessCredential,
    ConsciousnessProfile, ConsciousnessTier, ExtensionKey, GateAuditInput, GovernanceAuditFilter,
    GovernanceAuditResult, GovernanceEligibility, GovernanceRequirement, ReputationState,
    GRACE_PERIOD_US, REFRESH_WINDOW_US, REPUTATION_BLACKLIST_THRESHOLD, REPUTATION_DECAY_PER_DAY,
    REPUTATION_MAX_SLASHES, REPUTATION_RESTORATION_INTERACTIONS, REPUTATION_SLASH_FACTOR,
};
// HDK-dependent re-exports
#[cfg(feature = "hdk")]
pub use consciousness_profile::gate_consciousness;

// 8D Sovereign Profile — anti-tyranny civic identity (replacing 4D ConsciousnessProfile)
pub mod sovereign_gate;
#[cfg(feature = "hdk")]
pub use sovereign_gate::gate_civic;
pub use sovereign_profile::weights::DimensionWeights;
pub use sovereign_profile::{
    civic_requirement_basic, civic_requirement_constitutional, civic_requirement_guardian,
    civic_requirement_proposal, civic_requirement_voting, CivicRequirement, CivicTier,
    SovereignCredential, SovereignDimension, SovereignProfile,
};

pub mod offline_credential;
pub mod sub_passport;

// ── Interplanetary extensions (feature-gated) ────────────────────────────
#[cfg(feature = "interplanetary")]
pub mod cross_planetary_fl;
#[cfg(feature = "interplanetary")]
pub mod earth_colony_protocol;
#[cfg(feature = "interplanetary")]
pub mod interplanetary_bridge;
#[cfg(all(feature = "interplanetary", feature = "hdk"))]
pub mod mars_isru;
#[cfg(feature = "interplanetary")]
pub mod planetary_governance;

// ── Federated learning extensions (feature-gated) ────────────────────────
#[cfg(feature = "federated")]
pub mod terrain_fl;
// #[cfg(feature = "federated")]
// pub mod consciousness_sync;
// #[cfg(feature = "federated")]
// pub mod federated_genomics;

#[cfg(feature = "hdk")]
pub mod validation;
#[cfg(feature = "hdk")]
pub use validation::{check_author_match, check_link_author_match};

pub mod collective_phi;
pub use collective_phi::{
    AgentConsciousnessVector, CollectivePhiEngine, CollectivePhiResult, COLLECTIVE_PHI_MAX_SYNC,
};

pub mod routing;
pub use routing::{
    resolve_civic_zome, resolve_commons_zome, BridgeDomain, CivicZome, CommonsZome,
    CrossClusterRole, CIVIC_DOMAINS, COMMONS_DOMAINS,
};

pub mod routing_registry;

pub mod metrics;

// ── Infrastructure extensions (feature-gated) ────────────────────────────
#[cfg(feature = "infrastructure")]
pub mod migration;
pub mod notifications;
#[cfg(feature = "infrastructure")]
pub mod saga; // Notifications are core — used by all clusters

#[cfg(feature = "infrastructure")]
pub mod license_enforcement;
#[cfg(feature = "infrastructure")]
pub mod merkle_timestamp;
#[cfg(feature = "infrastructure")]
pub mod timestamp_anchor;

#[cfg(kani)]
mod kani_proofs;

#[cfg(feature = "hdk")]
use hdk::prelude::*;
use serde::{Deserialize, Serialize};

// ============================================================================
// Dispatch types
// ============================================================================

/// Input for dispatching a call to any domain zome within a cluster DNA.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DispatchInput {
    /// Target zome name (e.g., "property_registry", "justice_cases").
    /// Must be in the cluster's allowed zomes list.
    pub zome: String,
    /// Target function name (e.g., "verify_ownership", "get_property").
    pub fn_name: String,
    /// MessagePack-serialized input payload. Use `()` serialized for no-arg functions.
    pub payload: Vec<u8>,
}

/// Result of a dispatched cross-domain call.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DispatchResult {
    /// Whether the call succeeded.
    pub success: bool,
    /// MessagePack-serialized response payload (on success).
    pub response: Option<Vec<u8>>,
    /// Error message (on failure).
    pub error: Option<String>,
    /// Structured error code (on failure). Enables programmatic error handling
    /// without parsing error message strings. Populated by dispatch functions;
    /// defaults to `None` for backward compatibility with existing callers.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_code: Option<BridgeErrorCode>,
}

impl DispatchResult {
    /// Create a success result.
    pub fn ok(response: Vec<u8>) -> Self {
        Self {
            success: true,
            response: Some(response),
            error: None,
            error_code: None,
        }
    }

    /// Create an error result with structured code.
    pub fn err(code: BridgeErrorCode, message: String) -> Self {
        Self {
            success: false,
            response: None,
            error: Some(message),
            error_code: Some(code),
        }
    }
}

/// Input for resolving a query with a result.
#[cfg(feature = "hdk")]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ResolveQueryInput {
    pub query_hash: ActionHash,
    pub result: String,
    pub success: bool,
}

/// Query for events by type within a domain.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EventTypeQuery {
    pub domain: String,
    pub event_type: String,
}

/// Health status for a cluster bridge.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BridgeHealth {
    pub healthy: bool,
    pub agent: String,
    pub total_events: u32,
    pub total_queries: u32,
    pub domains: Vec<String>,
}

// ============================================================================
// Bridge Error Codes — structured error classification for dispatch failures
// ============================================================================

/// Structured error codes for bridge dispatch failures.
///
/// Each code maps to a specific failure mode, making it easy to:
/// - Track error rates by type in metrics (via `BridgeMetricsSnapshot.error_counts`)
/// - Diagnose issues from logs without parsing error message strings
/// - Build alerting rules (e.g., alert on BRG-006 spike = cross-cluster partition)
///
/// Codes are stable — do not renumber or reuse after removal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BridgeErrorCode {
    /// BRG-001: Target zome not in allowlist (unauthorized dispatch attempt)
    AllowlistRejected,
    /// BRG-002: Network error during local dispatch
    LocalNetworkError,
    /// BRG-003: Local zome call rejected (non-Ok response)
    LocalCallRejected,
    /// BRG-004: No response from local zome call
    LocalNoResponse,
    /// BRG-005: Local HDK call failed (runtime error)
    LocalCallFailed,
    /// BRG-006: Network error during cross-cluster dispatch
    CrossClusterNetworkError,
    /// BRG-007: Cross-cluster call rejected (non-Ok response)
    CrossClusterCallRejected,
    /// BRG-008: No response from cross-cluster call
    CrossClusterNoResponse,
    /// BRG-009: Cross-cluster HDK call failed (runtime error)
    CrossClusterCallFailed,
    /// BRG-010: Dispatch input validation failed (oversized payload/identifier)
    ValidationFailed,
}

impl BridgeErrorCode {
    /// String code for metrics recording (e.g., "BRG-001").
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::AllowlistRejected => "BRG-001",
            Self::LocalNetworkError => "BRG-002",
            Self::LocalCallRejected => "BRG-003",
            Self::LocalNoResponse => "BRG-004",
            Self::LocalCallFailed => "BRG-005",
            Self::CrossClusterNetworkError => "BRG-006",
            Self::CrossClusterCallRejected => "BRG-007",
            Self::CrossClusterNoResponse => "BRG-008",
            Self::CrossClusterCallFailed => "BRG-009",
            Self::ValidationFailed => "BRG-010",
        }
    }
}

impl core::fmt::Display for BridgeErrorCode {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

// ============================================================================
// Dispatch size limits — prevent memory exhaustion via oversized payloads
// ============================================================================

/// Maximum dispatch payload size (1 MB). Prevents memory exhaustion from
/// oversized payloads being cloned into ExternIO.
pub const MAX_DISPATCH_PAYLOAD_BYTES: usize = 1_048_576;

/// Maximum dispatch zome/fn_name identifier length (256 bytes).
pub const MAX_DISPATCH_IDENTIFIER_BYTES: usize = 256;

/// Validate dispatch input field sizes.
fn validate_dispatch_sizes(zome: &str, fn_name: &str, payload: &[u8]) -> Result<(), String> {
    if zome.len() > MAX_DISPATCH_IDENTIFIER_BYTES {
        return Err(format!(
            "Zome name too long ({} bytes, max {})",
            zome.len(),
            MAX_DISPATCH_IDENTIFIER_BYTES
        ));
    }
    if fn_name.len() > MAX_DISPATCH_IDENTIFIER_BYTES {
        return Err(format!(
            "Function name too long ({} bytes, max {})",
            fn_name.len(),
            MAX_DISPATCH_IDENTIFIER_BYTES
        ));
    }
    if payload.len() > MAX_DISPATCH_PAYLOAD_BYTES {
        return Err(format!(
            "Payload too large ({} bytes, max {})",
            payload.len(),
            MAX_DISPATCH_PAYLOAD_BYTES
        ));
    }
    Ok(())
}

// ============================================================================
// Dispatch logic (HDK functions gated behind `hdk` feature)
// ============================================================================

/// Dispatch a synchronous call to a domain zome, with allowlist validation.
///
/// This is the core cross-domain integration primitive. It validates the
/// target zome against the provided allowlist, then uses
/// `call(CallTargetCell::Local, ...)` to invoke the function directly
/// within the same DNA.
///
/// The `payload` field in `DispatchInput` must already be MessagePack-encoded.
/// We bypass `ExternIO::encode()` to avoid double-serialization.
#[cfg(feature = "hdk")]
pub fn dispatch_call_checked(
    input: &DispatchInput,
    allowed_zomes: &[&str],
) -> ExternResult<DispatchResult> {
    if let Err(msg) = validate_dispatch_sizes(&input.zome, &input.fn_name, &input.payload) {
        metrics::record_error(
            &input.zome,
            &input.fn_name,
            BridgeErrorCode::ValidationFailed.as_str(),
        );
        return Ok(DispatchResult::err(BridgeErrorCode::ValidationFailed, msg));
    }
    if !allowed_zomes.contains(&input.zome.as_str()) {
        metrics::record_error(
            &input.zome,
            &input.fn_name,
            BridgeErrorCode::AllowlistRejected.as_str(),
        );
        return Ok(DispatchResult::err(
            BridgeErrorCode::AllowlistRejected,
            format!(
                "Zome '{}' is not in the allowed dispatch list. Valid zomes: {:?}",
                input.zome, allowed_zomes
            ),
        ));
    }

    let payload = ExternIO(input.payload.clone());
    let start_us = sys_time().ok().map(|t| t.as_micros() as u64);

    let result = HDK.with(|h| {
        h.borrow().call(vec![Call::new(
            CallTarget::ConductorCell(CallTargetCell::Local),
            ZomeName::from(input.zome.as_str()),
            FunctionName::from(input.fn_name.as_str()),
            None,
            payload,
        )])
    });

    let elapsed_us = start_us.and_then(|start| {
        sys_time()
            .ok()
            .map(|end| (end.as_micros() as u64).saturating_sub(start))
    });

    match result {
        Ok(responses) => match responses.into_iter().next() {
            Some(ZomeCallResponse::Ok(extern_io)) => {
                if let Some(latency) = elapsed_us {
                    metrics::record_success(&input.zome, &input.fn_name, latency);
                }
                Ok(DispatchResult::ok(extern_io.0))
            }
            Some(ZomeCallResponse::NetworkError(err)) => {
                let code = BridgeErrorCode::LocalNetworkError;
                metrics::record_error(&input.zome, &input.fn_name, code.as_str());
                Ok(DispatchResult::err(code, format!("Network error: {}", err)))
            }
            Some(other) => {
                let code = BridgeErrorCode::LocalCallRejected;
                metrics::record_error(&input.zome, &input.fn_name, code.as_str());
                Ok(DispatchResult::err(
                    code,
                    format!("Zome call rejected: {:?}", other),
                ))
            }
            None => {
                let code = BridgeErrorCode::LocalNoResponse;
                metrics::record_error(&input.zome, &input.fn_name, code.as_str());
                Ok(DispatchResult::err(
                    code,
                    "No response from zome call".into(),
                ))
            }
        },
        Err(e) => {
            let code = BridgeErrorCode::LocalCallFailed;
            metrics::record_error(&input.zome, &input.fn_name, code.as_str());
            Ok(DispatchResult::err(code, format!("Call failed: {:?}", e)))
        }
    }
}

// ============================================================================
// Cross-cluster dispatch (inter-DNA within the same hApp)
// ============================================================================

// =============================================================================
// CONSTELLATION PROTOCOL (Cross-hApp Call Routing)
// =============================================================================

/// Target for a constellation dispatch.
/// Can be internal (OtherRole) or external (RemoteAgent).
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum ConstellationTarget {
    /// Internal to the current hApp (Unified mode).
    Internal { role: String },
    /// External to the current hApp (Standalone mode).
    External {
        agent: AgentPubKey,
        cap_secret: Option<CapSecret>,
    },
}

/// Dispatch a synchronous call across the constellation (local or remote).
///
/// If target is Internal, it uses `CallTargetCell::OtherRole`.
/// If target is External, it uses `call_remote`.
#[cfg(feature = "hdk")]
pub fn dispatch_constellation_call(
    target: &ConstellationTarget,
    zome: &str,
    fn_name: &str,
    payload: Vec<u8>,
) -> ExternResult<DispatchResult> {
    let start_us = sys_time().ok().map(|t| t.as_micros() as u64);

    let result = match target {
        ConstellationTarget::Internal { role } => HDK.with(|h| {
            h.borrow().call(vec![Call::new(
                CallTarget::ConductorCell(CallTargetCell::OtherRole(role.clone())),
                ZomeName::from(zome),
                FunctionName::from(fn_name),
                None,
                ExternIO(payload),
            )])
        }),
        ConstellationTarget::External { agent, cap_secret } => {
            // Note: call_remote is asynchronous and returns a different type.
            // For MVP, we bridge this into the synchronous DispatchResult pattern.
            match call_remote(
                agent.clone(),
                zome,
                fn_name.into(),
                *cap_secret,
                ExternIO(payload),
            ) {
                Ok(ZomeCallResponse::Ok(extern_io)) => Ok(vec![ZomeCallResponse::Ok(extern_io)]),
                Ok(other) => Ok(vec![other]),
                Err(e) => Err(e),
            }
        }
    };

    let elapsed_us = start_us.and_then(|start| {
        sys_time()
            .ok()
            .map(|end| (end.as_micros() as u64).saturating_sub(start))
    });

    match result {
        Ok(responses) => match responses.into_iter().next() {
            Some(ZomeCallResponse::Ok(extern_io)) => {
                if let Some(latency) = elapsed_us {
                    metrics::record_success(zome, fn_name, latency);
                }
                Ok(DispatchResult::ok(extern_io.0))
            }
            Some(ZomeCallResponse::NetworkError(err)) => Ok(DispatchResult::err(
                BridgeErrorCode::LocalNetworkError,
                format!("Network error: {}", err),
            )),
            Some(other) => Ok(DispatchResult::err(
                BridgeErrorCode::LocalCallRejected,
                format!("Rejected: {:?}", other),
            )),
            None => Ok(DispatchResult::err(
                BridgeErrorCode::LocalNoResponse,
                "No response".into(),
            )),
        },
        Err(e) => Ok(DispatchResult::err(
            BridgeErrorCode::LocalCallFailed,
            format!("Call failed: {:?}", e),
        )),
    }
}

/// Input for dispatching a call to a zome in another DNA within the same hApp.
///
/// Used for commons↔civic cross-cluster communication.  The `role` field
/// identifies the target DNA by its hApp role name (e.g., `"commons"` or
/// `"civic"`).  The call is routed via `CallTargetCell::OtherRole`.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CrossClusterDispatchInput {
    /// hApp role name of the target DNA (e.g., "commons" or "civic").
    pub role: String,
    /// Target zome name within the other DNA.
    pub zome: String,
    /// Target function name.
    pub fn_name: String,
    /// MessagePack-serialized input payload.
    pub payload: Vec<u8>,
}

/// Wrapper for cross-cluster dispatch with audit correlation.
///
/// When a coordinator initiates a cross-cluster action, it generates a
/// correlation ID and wraps the dispatch so both sides can log the same
/// ID in their audit trail.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CorrelatedDispatch {
    /// Unique correlation ID linking audit events across clusters.
    /// Format: "<agent_hex_prefix>:<timestamp_us>"
    pub correlation_id: String,
    /// Target zome in the other cluster.
    pub target_zome: String,
    /// Target function name.
    pub target_fn: String,
    /// JSON-serialized payload.
    pub payload: String,
}

/// Dispatch a synchronous call to a zome in another DNA, with allowlist
/// validation.
///
/// This is the cross-cluster counterpart of [`dispatch_call_checked`].
/// Instead of `CallTargetCell::Local`, it uses
/// `CallTargetCell::OtherRole(role)` to reach a different DNA within the
/// same installed hApp.  The target zome must be in `allowed_zomes`.
#[cfg(feature = "hdk")]
pub fn dispatch_call_cross_cluster(
    input: &CrossClusterDispatchInput,
    allowed_zomes: &[&str],
) -> ExternResult<DispatchResult> {
    if let Err(msg) = validate_dispatch_sizes(&input.zome, &input.fn_name, &input.payload) {
        metrics::record_error(
            &input.zome,
            &input.fn_name,
            BridgeErrorCode::ValidationFailed.as_str(),
        );
        return Ok(DispatchResult::err(BridgeErrorCode::ValidationFailed, msg));
    }
    if input.role.len() > MAX_DISPATCH_IDENTIFIER_BYTES {
        metrics::record_error(
            &input.zome,
            &input.fn_name,
            BridgeErrorCode::ValidationFailed.as_str(),
        );
        return Ok(DispatchResult::err(
            BridgeErrorCode::ValidationFailed,
            format!(
                "Role name too long ({} bytes, max {})",
                input.role.len(),
                MAX_DISPATCH_IDENTIFIER_BYTES
            ),
        ));
    }

    if !allowed_zomes.contains(&input.zome.as_str()) {
        metrics::record_error(
            &input.zome,
            &input.fn_name,
            BridgeErrorCode::AllowlistRejected.as_str(),
        );
        return Ok(DispatchResult::err(
            BridgeErrorCode::AllowlistRejected,
            format!(
                "Zome '{}' is not in the allowed cross-cluster dispatch list. Valid zomes: {:?}",
                input.zome, allowed_zomes
            ),
        ));
    }

    metrics::record_cross_cluster();

    // Default to Internal target for backward compatibility with unified hApp
    let target = ConstellationTarget::Internal {
        role: input.role.clone(),
    };

    dispatch_constellation_call(&target, &input.zome, &input.fn_name, input.payload.clone())
}

/// Cross-cluster dispatch to commons with automatic sub-cluster role resolution.
///
/// Instead of using a fixed `"commons"` role, this resolves the target zome
/// to either `"commons_land"` or `"commons_care"` based on which sub-cluster
/// DNA contains that zome.
///
/// This is needed because the commons cluster is split into two DNA roles
/// in the unified hApp to fit under Holochain's 16MB DNA limit.
#[cfg(feature = "hdk")]
pub fn dispatch_call_cross_cluster_commons(
    input: &CrossClusterDispatchInput,
    allowed_zomes: &[&str],
) -> ExternResult<DispatchResult> {
    // Resolve which sub-cluster this zome belongs to
    let role = CommonsZome::resolve_role(&input.zome).unwrap_or("commons_land");

    let routed_input = CrossClusterDispatchInput {
        role: role.to_string(),
        zome: input.zome.clone(),
        fn_name: input.fn_name.clone(),
        payload: input.payload.clone(),
    };
    dispatch_call_cross_cluster(&routed_input, allowed_zomes)
}

// ============================================================================
// Rate limiting constants
// ============================================================================

/// Maximum dispatch calls per agent within the rate limit window.
pub const RATE_LIMIT_MAX_DISPATCH: usize = 100;

/// Rate limit window in seconds.
pub const RATE_LIMIT_WINDOW_SECS: i64 = 60;

/// Check whether the number of recent dispatches exceeds the rate limit.
///
/// Returns `Ok(())` if within limits, or an error string if exceeded.
/// This is a pure validation function — the caller is responsible for
/// counting recent dispatches (via `get_links` on the agent's rate-limit
/// links) and passing the count here.
pub fn check_rate_limit_count(recent_count: usize) -> Result<(), String> {
    if recent_count >= RATE_LIMIT_MAX_DISPATCH {
        Err(format!(
            "Rate limit exceeded: {} dispatches in {}s (max {})",
            recent_count, RATE_LIMIT_WINDOW_SECS, RATE_LIMIT_MAX_DISPATCH
        ))
    } else {
        Ok(())
    }
}

// ============================================================================
// Typed cross-domain dispatch helpers
// ============================================================================

/// Input for verifying property ownership (commons: housing → property)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PropertyOwnershipQuery {
    pub property_id: String,
    pub requester_did: String,
}

/// Result of a property ownership verification
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PropertyOwnershipResult {
    pub is_owner: bool,
    pub owner_did: Option<String>,
    pub error: Option<String>,
}

/// Input for querying care provider availability (commons: mutualaid → care)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CareAvailabilityQuery {
    pub skill_needed: String,
    pub location: Option<String>,
}

/// Result of a care availability query
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CareAvailabilityResult {
    pub available_count: u32,
    pub recommendation: String,
    pub error: Option<String>,
}

/// Input for checking active cases in an area (civic: emergency → justice)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct JusticeAreaQuery {
    pub area: String,
    pub case_type: Option<String>,
}

/// Result of an area case query
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct JusticeAreaResult {
    pub active_cases: u32,
    pub recommendation: String,
    pub error: Option<String>,
}

/// Input for checking factcheck status (civic: justice → media)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct FactcheckStatusQuery {
    pub claim_id: String,
}

/// Result of a factcheck status query
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct FactcheckStatusResult {
    pub has_factcheck: bool,
    pub verdict: Option<String>,
    pub error: Option<String>,
}

/// Input for querying food availability (commons: emergency → food, mutualaid → food)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct FoodAvailabilityQuery {
    pub product_name: Option<String>,
    pub market_type: Option<String>,
    pub max_distance_km: Option<f64>,
}

/// Result of a food availability query
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct FoodAvailabilityResult {
    pub available_listings: u32,
    pub nearest_market: Option<String>,
    pub error: Option<String>,
}

/// Input for querying transport routes (commons: mutualaid → transport, care → transport)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TransportRouteQuery {
    pub origin_lat: f64,
    pub origin_lon: f64,
    pub destination_lat: f64,
    pub destination_lon: f64,
    pub mode: Option<String>,
}

/// Result of a transport route query
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TransportRouteResult {
    pub route_count: u32,
    pub estimated_minutes: Option<u32>,
    pub estimated_emissions_kg_co2: Option<f64>,
    pub error: Option<String>,
}

/// Input for querying carbon credits (commons: property → transport)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CarbonCreditQuery {
    pub agent_did: String,
}

/// Result of a carbon credit query
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CarbonCreditResult {
    pub total_credits_kg_co2: f64,
    pub trips_logged: u32,
    pub error: Option<String>,
}

// ============================================================================
// Cross-cluster emergency↔commons query types
// ============================================================================

/// Input for querying water safety in a disaster zone (emergency → water)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct WaterSafetyQuery {
    pub area_lat: f64,
    pub area_lon: f64,
    pub radius_km: f64,
}

/// Result of a water safety query
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct WaterSafetyResult {
    pub safe_sources: u32,
    pub contaminated_sources: u32,
    pub total_sources: u32,
}

/// Input for querying food availability during an emergency (emergency → food)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EmergencyFoodQuery {
    pub area_lat: f64,
    pub area_lon: f64,
    pub radius_km: f64,
    pub people_count: u32,
}

/// Result of an emergency food availability query
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EmergencyFoodResult {
    pub available_kg: f64,
    pub distribution_points: u32,
    pub estimated_days_supply: f64,
}

/// Input for querying shelter capacity during an emergency (emergency → housing)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ShelterCapacityQuery {
    pub area_lat: f64,
    pub area_lon: f64,
    pub radius_km: f64,
    pub beds_needed: u32,
}

/// Result of a shelter capacity query
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ShelterCapacityResult {
    pub available_beds: u32,
    pub total_shelters: u32,
    pub nearest_shelter_km: f64,
}

/// Input for querying available care providers during an emergency (emergency → care)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EmergencyCareQuery {
    pub area_lat: f64,
    pub area_lon: f64,
    pub skill_needed: String,
    pub urgency_level: u8,
}

/// Result of an emergency care provider query
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EmergencyCareResult {
    pub available_providers: u32,
    pub nearest_provider_km: f64,
}

// ============================================================================
// Audit trail query types
// ============================================================================

/// Input for querying events within a time range, optionally filtered by domain and type.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AuditTrailQuery {
    /// Start of the time range (inclusive), as microseconds since epoch.
    pub from_us: i64,
    /// End of the time range (inclusive), as microseconds since epoch.
    pub to_us: i64,
    /// Optional domain filter (e.g., "property", "justice").
    pub domain: Option<String>,
    /// Optional event type filter (e.g., "ownership_transferred").
    pub event_type: Option<String>,
}

/// Summary of a single audit trail entry (lightweight, no full record).
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AuditTrailEntry {
    pub domain: String,
    pub event_type: String,
    pub source_agent: String,
    pub payload_preview: String,
    pub created_at_us: i64,
    #[cfg(feature = "hdk")]
    pub action_hash: ActionHash,
    #[cfg(not(feature = "hdk"))]
    pub action_hash: String,
}

/// Result of an audit trail query.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AuditTrailResult {
    pub entries: Vec<AuditTrailEntry>,
    pub total_matched: u32,
    pub query_from_us: i64,
    pub query_to_us: i64,
}

// ============================================================================
// Typed hearth↔other cluster query/result helpers (require HDK types)
// ============================================================================

#[cfg(feature = "hdk")]
/// Input for querying hearth membership (civic/commons → hearth)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HearthMemberQuery {
    pub hearth_hash: ActionHash,
    pub agent: AgentPubKey,
}

/// Result of a hearth membership query
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HearthMemberResult {
    pub is_member: bool,
    pub role: Option<String>,
    pub display_name: Option<String>,
    pub error: Option<String>,
}

#[cfg(feature = "hdk")]
/// Input for querying hearth care availability (commons → hearth)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HearthCareQuery {
    pub hearth_hash: ActionHash,
    pub care_type: Option<String>,
}

/// Result of a hearth care query
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HearthCareResult {
    pub available_caregivers: u32,
    pub active_schedules: u32,
    pub error: Option<String>,
}

#[cfg(feature = "hdk")]
/// Input for querying hearth emergency status (civic → hearth)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HearthEmergencyQuery {
    pub hearth_hash: ActionHash,
}

/// Result of a hearth emergency status query
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HearthEmergencyResult {
    pub has_active_alerts: bool,
    pub active_alert_count: u32,
    pub members_checked_in: u32,
    pub members_missing: u32,
    pub error: Option<String>,
}

// ============================================================================
// Cross-cluster typed queries (Phase 1C — governance/finance/identity/health)
// ============================================================================

/// Query: Check budget proposal status (Finance ↔ Governance)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BudgetProposalQuery {
    pub proposal_id: String,
}

/// Result: Budget proposal status
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BudgetProposalResult {
    pub approved: bool,
    pub amount: u64,
    pub treasury_balance: u64,
    pub error: Option<String>,
}

/// Query: Verify property as collateral (Finance → Commons)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CollateralPropertyQuery {
    pub property_hash: String,
}

/// Result: Collateral property status
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CollateralPropertyResult {
    pub valid: bool,
    pub appraised_value: u64,
    pub encumbered: bool,
    pub error: Option<String>,
}

/// Query: Check restitution ability (Civic → Finance)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RestitutionQuery {
    pub case_id: String,
    pub defendant_did: String,
}

/// Result: Restitution check
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RestitutionResult {
    pub balance_sufficient: bool,
    pub amount_due: u64,
    pub error: Option<String>,
}

/// Notice: Credential revocation push (Identity → *)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RevocationNotice {
    pub credential_hash: String,
    pub did: String,
    pub reason: String,
    pub effective_at: u64,
}

/// Acknowledgment: Revocation received
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RevocationAck {
    pub received: bool,
    pub affected_entries: u32,
    pub error: Option<String>,
}

/// Query: Consented health record access (Health → Personal)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ConsentedRecordQuery {
    pub patient_did: String,
    pub record_type: String,
}

/// Result: Consented record access
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ConsentedRecordResult {
    pub authorized: bool,
    pub record_hash: Option<String>,
    pub error: Option<String>,
}

/// Query: Energy project governance approval (Energy → Governance)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ProjectProposalQuery {
    pub project_id: String,
}

/// Result: Project governance approval
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ProjectProposalResult {
    pub governance_approved: bool,
    pub conditions: Vec<String>,
    pub error: Option<String>,
}

/// Query: Verify knowledge claim (Knowledge → Media)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ClaimVerificationQuery {
    pub claim_hash: String,
}

/// Result: Claim verification
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ClaimVerificationResult {
    pub verified: bool,
    pub confidence: f64,
    pub sources: Vec<String>,
    pub error: Option<String>,
}

/// Query: Carbon offset from transport (Climate → Transport/Commons)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CarbonOffsetQuery {
    pub route_id: String,
    pub distance_km: f64,
}

/// Result: Carbon offset calculation
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CarbonOffsetResult {
    pub credits_earned: f64,
    pub offset_hash: Option<String>,
    pub error: Option<String>,
}

/// Priority levels for cross-cluster notifications.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NotificationPriority {
    /// Batched into daily digest
    Low = 0,
    /// Delivered on next poll
    Normal = 1,
    /// Immediate signal
    High = 2,
    /// Bypass quiet hours, multi-channel delivery
    Emergency = 3,
}

impl NotificationPriority {
    pub const fn from_u8(v: u8) -> Self {
        match v {
            0 => Self::Low,
            1 => Self::Normal,
            2 => Self::High,
            3 => Self::Emergency,
            _ => Self::Normal,
        }
    }

    pub const fn as_u8(&self) -> u8 {
        *self as u8
    }
}

// ============================================================================
// Utilities
// ============================================================================

/// Convert links to their target records, skipping any that have been deleted.
#[cfg(feature = "hdk")]
pub fn records_from_links(links: Vec<Link>) -> ExternResult<Vec<Record>> {
    let mut records = Vec::new();
    for link in links {
        let action_hash = ActionHash::try_from(link.target)
            .map_err(|_| wasm_error!(WasmErrorInner::Guest("Invalid link target".into())))?;
        if let Some(record) = get(action_hash, GetOptions::default())? {
            records.push(record);
        }
    }
    Ok(records)
}

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

    // dispatch_call_checked: the disallowed-zome path returns before
    // touching HDK, so we can test it without a running conductor.

    #[test]
    fn dispatch_rejects_disallowed_zome() {
        let input = DispatchInput {
            zome: "evil_zome".into(),
            fn_name: "steal_data".into(),
            payload: vec![],
        };
        let allowed = &["property_registry", "housing_units"];
        let result = dispatch_call_checked(&input, allowed).unwrap();
        assert!(!result.success);
        assert!(result.response.is_none());
        let err = result.error.unwrap();
        assert!(err.contains("not in the allowed dispatch list"));
        assert!(err.contains("evil_zome"));
    }

    #[test]
    fn dispatch_rejects_empty_allowlist() {
        let input = DispatchInput {
            zome: "property_registry".into(),
            fn_name: "get_property".into(),
            payload: vec![],
        };
        let result = dispatch_call_checked(&input, &[]).unwrap();
        assert!(!result.success);
        assert!(result.error.is_some());
    }

    #[test]
    fn dispatch_rejects_similar_zome_name() {
        let input = DispatchInput {
            zome: "property_registry_evil".into(),
            fn_name: "get_property".into(),
            payload: vec![],
        };
        let allowed = &["property_registry"];
        let result = dispatch_call_checked(&input, allowed).unwrap();
        assert!(!result.success);
    }

    #[test]
    fn dispatch_error_lists_valid_zomes() {
        let input = DispatchInput {
            zome: "bad".into(),
            fn_name: "fn".into(),
            payload: vec![],
        };
        let allowed = &["alpha", "beta", "gamma"];
        let result = dispatch_call_checked(&input, allowed).unwrap();
        let err = result.error.unwrap();
        assert!(err.contains("alpha"));
        assert!(err.contains("beta"));
        assert!(err.contains("gamma"));
    }

    // Type serde roundtrips

    #[test]
    fn dispatch_input_serde_roundtrip() {
        let input = DispatchInput {
            zome: "property_registry".into(),
            fn_name: "get_property".into(),
            payload: vec![1, 2, 3, 4],
        };
        let json = serde_json::to_string(&input).unwrap();
        let input2: DispatchInput = serde_json::from_str(&json).unwrap();
        assert_eq!(input.zome, input2.zome);
        assert_eq!(input.fn_name, input2.fn_name);
        assert_eq!(input.payload, input2.payload);
    }

    #[test]
    fn dispatch_result_success_serde_roundtrip() {
        let result = DispatchResult::ok(vec![10, 20, 30]);
        let json = serde_json::to_string(&result).unwrap();
        let r2: DispatchResult = serde_json::from_str(&json).unwrap();
        assert!(r2.success);
        assert_eq!(r2.response, Some(vec![10, 20, 30]));
        assert!(r2.error.is_none());
        assert!(r2.error_code.is_none());
    }

    #[test]
    fn dispatch_result_error_serde_roundtrip() {
        let result =
            DispatchResult::err(BridgeErrorCode::LocalCallFailed, "something failed".into());
        let json = serde_json::to_string(&result).unwrap();
        assert!(json.contains("error_code")); // error code field present
        let r2: DispatchResult = serde_json::from_str(&json).unwrap();
        assert!(!r2.success);
        assert!(r2.response.is_none());
        assert_eq!(r2.error.as_deref(), Some("something failed"));
        assert_eq!(r2.error_code, Some(BridgeErrorCode::LocalCallFailed));
    }

    #[test]
    fn dispatch_result_backward_compat_without_error_code() {
        // Old serialized results without error_code should deserialize fine
        let json = r#"{"success":false,"response":null,"error":"old error"}"#;
        let r: DispatchResult = serde_json::from_str(json).unwrap();
        assert!(!r.success);
        assert_eq!(r.error.as_deref(), Some("old error"));
        assert_eq!(r.error_code, None); // backward compatible default
    }

    #[test]
    fn event_type_query_serde_roundtrip() {
        let q = EventTypeQuery {
            domain: "housing".into(),
            event_type: "lease_created".into(),
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: EventTypeQuery = serde_json::from_str(&json).unwrap();
        assert_eq!(q.domain, q2.domain);
        assert_eq!(q.event_type, q2.event_type);
    }

    // Cross-cluster dispatch validation tests

    #[test]
    fn cross_cluster_rejects_disallowed_zome() {
        let input = CrossClusterDispatchInput {
            role: "civic".into(),
            zome: "evil_zome".into(),
            fn_name: "steal_data".into(),
            payload: vec![],
        };
        let allowed = &["justice_cases", "emergency_incidents"];
        let result = dispatch_call_cross_cluster(&input, allowed).unwrap();
        assert!(!result.success);
        assert!(result.response.is_none());
        let err = result.error.unwrap();
        assert!(err.contains("not in the allowed cross-cluster dispatch list"));
        assert!(err.contains("evil_zome"));
    }

    #[test]
    fn cross_cluster_rejects_empty_allowlist() {
        let input = CrossClusterDispatchInput {
            role: "commons".into(),
            zome: "property_registry".into(),
            fn_name: "get_property".into(),
            payload: vec![],
        };
        let result = dispatch_call_cross_cluster(&input, &[]).unwrap();
        assert!(!result.success);
        assert!(result.error.is_some());
    }

    #[test]
    fn cross_cluster_rejects_similar_zome_name() {
        let input = CrossClusterDispatchInput {
            role: "civic".into(),
            zome: "justice_cases_evil".into(),
            fn_name: "get_case".into(),
            payload: vec![],
        };
        let allowed = &["justice_cases"];
        let result = dispatch_call_cross_cluster(&input, allowed).unwrap();
        assert!(!result.success);
    }

    #[test]
    fn cross_cluster_error_lists_valid_zomes() {
        let input = CrossClusterDispatchInput {
            role: "civic".into(),
            zome: "bad".into(),
            fn_name: "fn".into(),
            payload: vec![],
        };
        let allowed = &["justice_cases", "emergency_incidents", "media_publication"];
        let result = dispatch_call_cross_cluster(&input, allowed).unwrap();
        let err = result.error.unwrap();
        assert!(err.contains("justice_cases"));
        assert!(err.contains("emergency_incidents"));
        assert!(err.contains("media_publication"));
    }

    #[test]
    fn cross_cluster_dispatch_input_serde_roundtrip() {
        let input = CrossClusterDispatchInput {
            role: "civic".into(),
            zome: "justice_cases".into(),
            fn_name: "get_case".into(),
            payload: vec![5, 6, 7],
        };
        let json = serde_json::to_string(&input).unwrap();
        let input2: CrossClusterDispatchInput = serde_json::from_str(&json).unwrap();
        assert_eq!(input.role, input2.role);
        assert_eq!(input.zome, input2.zome);
        assert_eq!(input.fn_name, input2.fn_name);
        assert_eq!(input.payload, input2.payload);
    }

    #[test]
    fn bridge_health_serde_roundtrip() {
        let h = BridgeHealth {
            healthy: true,
            agent: "uhCAk_test_agent".into(),
            total_events: 42,
            total_queries: 7,
            domains: vec!["property".into(), "housing".into()],
        };
        let json = serde_json::to_string(&h).unwrap();
        let h2: BridgeHealth = serde_json::from_str(&json).unwrap();
        assert!(h2.healthy);
        assert_eq!(h2.total_events, 42);
        assert_eq!(h2.total_queries, 7);
        assert_eq!(h2.domains.len(), 2);
    }

    // Rate limit tests

    #[test]
    fn rate_limit_zero_calls_passes() {
        assert!(check_rate_limit_count(0).is_ok());
    }

    #[test]
    fn rate_limit_under_max_passes() {
        assert!(check_rate_limit_count(99).is_ok());
    }

    #[test]
    fn rate_limit_at_max_rejects() {
        let err = check_rate_limit_count(RATE_LIMIT_MAX_DISPATCH).unwrap_err();
        assert!(err.contains("Rate limit exceeded"));
    }

    #[test]
    fn rate_limit_over_max_rejects() {
        let err = check_rate_limit_count(1000).unwrap_err();
        assert!(err.contains("Rate limit exceeded"));
        assert!(err.contains("1000"));
    }

    #[test]
    fn rate_limit_error_includes_window() {
        let err = check_rate_limit_count(200).unwrap_err();
        assert!(err.contains(&format!("{}s", RATE_LIMIT_WINDOW_SECS)));
    }

    // Typed helper serde tests

    #[test]
    fn property_ownership_query_serde_roundtrip() {
        let q = PropertyOwnershipQuery {
            property_id: "PROP-001".into(),
            requester_did: "did:mycelix:abc".into(),
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: PropertyOwnershipQuery = serde_json::from_str(&json).unwrap();
        assert_eq!(q.property_id, q2.property_id);
        assert_eq!(q.requester_did, q2.requester_did);
    }

    #[test]
    fn property_ownership_result_serde_roundtrip() {
        let r = PropertyOwnershipResult {
            is_owner: true,
            owner_did: Some("did:mycelix:owner".into()),
            error: None,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: PropertyOwnershipResult = serde_json::from_str(&json).unwrap();
        assert!(r2.is_owner);
        assert_eq!(r2.owner_did, Some("did:mycelix:owner".into()));
    }

    #[test]
    fn care_availability_query_serde_roundtrip() {
        let q = CareAvailabilityQuery {
            skill_needed: "nursing".into(),
            location: None,
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: CareAvailabilityQuery = serde_json::from_str(&json).unwrap();
        assert_eq!(q.skill_needed, q2.skill_needed);
        assert!(q2.location.is_none());
    }

    #[test]
    fn justice_area_query_serde_roundtrip() {
        let q = JusticeAreaQuery {
            area: "north-side".into(),
            case_type: Some("civil".into()),
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: JusticeAreaQuery = serde_json::from_str(&json).unwrap();
        assert_eq!(q.area, q2.area);
        assert_eq!(q.case_type, q2.case_type);
    }

    #[test]
    fn factcheck_status_query_serde_roundtrip() {
        let q = FactcheckStatusQuery {
            claim_id: "CL-42".into(),
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: FactcheckStatusQuery = serde_json::from_str(&json).unwrap();
        assert_eq!(q.claim_id, q2.claim_id);
    }

    #[test]
    fn factcheck_status_result_serde_roundtrip() {
        let r = FactcheckStatusResult {
            has_factcheck: true,
            verdict: Some("verified".into()),
            error: None,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: FactcheckStatusResult = serde_json::from_str(&json).unwrap();
        assert!(r2.has_factcheck);
        assert_eq!(r2.verdict, Some("verified".into()));
    }

    // Audit trail type serde tests

    #[test]
    fn audit_trail_query_full_serde() {
        let q = AuditTrailQuery {
            from_us: 1_700_000_000_000_000,
            to_us: 1_700_001_000_000_000,
            domain: Some("property".into()),
            event_type: Some("ownership_transferred".into()),
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: AuditTrailQuery = serde_json::from_str(&json).unwrap();
        assert_eq!(q2.from_us, 1_700_000_000_000_000);
        assert_eq!(q2.domain.as_deref(), Some("property"));
        assert_eq!(q2.event_type.as_deref(), Some("ownership_transferred"));
    }

    #[test]
    fn audit_trail_query_no_filters() {
        let q = AuditTrailQuery {
            from_us: 0,
            to_us: i64::MAX,
            domain: None,
            event_type: None,
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: AuditTrailQuery = serde_json::from_str(&json).unwrap();
        assert!(q2.domain.is_none());
        assert!(q2.event_type.is_none());
    }

    #[test]
    fn audit_trail_entry_serde() {
        let e = AuditTrailEntry {
            domain: "justice".into(),
            event_type: "case_filed".into(),
            source_agent: "uhCAk_agent1".into(),
            payload_preview: "{\"case_id\":\"CASE-1\"}".into(),
            created_at_us: 1_700_000_500_000_000,
            action_hash: ActionHash::from_raw_36(vec![0u8; 36]),
        };
        let json = serde_json::to_string(&e).unwrap();
        let e2: AuditTrailEntry = serde_json::from_str(&json).unwrap();
        assert_eq!(e2.domain, "justice");
        assert_eq!(e2.event_type, "case_filed");
    }

    #[test]
    fn audit_trail_result_serde() {
        let r = AuditTrailResult {
            entries: vec![],
            total_matched: 0,
            query_from_us: 0,
            query_to_us: 1_000_000,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: AuditTrailResult = serde_json::from_str(&json).unwrap();
        assert!(r2.entries.is_empty());
        assert_eq!(r2.total_matched, 0);
    }

    // Food/Transport/Carbon typed helper serde tests

    #[test]
    fn food_availability_query_serde_roundtrip() {
        let q = FoodAvailabilityQuery {
            product_name: Some("tomatoes".into()),
            market_type: Some("FarmersMarket".into()),
            max_distance_km: Some(15.0),
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: FoodAvailabilityQuery = serde_json::from_str(&json).unwrap();
        assert_eq!(q2.product_name.as_deref(), Some("tomatoes"));
        assert_eq!(q2.market_type.as_deref(), Some("FarmersMarket"));
        assert_eq!(q2.max_distance_km, Some(15.0));
    }

    #[test]
    fn food_availability_query_no_filters() {
        let q = FoodAvailabilityQuery {
            product_name: None,
            market_type: None,
            max_distance_km: None,
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: FoodAvailabilityQuery = serde_json::from_str(&json).unwrap();
        assert!(q2.product_name.is_none());
    }

    #[test]
    fn food_availability_result_serde_roundtrip() {
        let r = FoodAvailabilityResult {
            available_listings: 12,
            nearest_market: Some("Southside Farmers Market".into()),
            error: None,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: FoodAvailabilityResult = serde_json::from_str(&json).unwrap();
        assert_eq!(r2.available_listings, 12);
        assert_eq!(
            r2.nearest_market.as_deref(),
            Some("Southside Farmers Market")
        );
        assert!(r2.error.is_none());
    }

    #[test]
    fn transport_route_query_serde_roundtrip() {
        let q = TransportRouteQuery {
            origin_lat: 32.9483,
            origin_lon: -96.7299,
            destination_lat: 32.7767,
            destination_lon: -96.7970,
            mode: Some("Cycling".into()),
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: TransportRouteQuery = serde_json::from_str(&json).unwrap();
        assert!((q2.origin_lat - 32.9483).abs() < 1e-4);
        assert_eq!(q2.mode.as_deref(), Some("Cycling"));
    }

    #[test]
    fn transport_route_result_serde_roundtrip() {
        let r = TransportRouteResult {
            route_count: 3,
            estimated_minutes: Some(45),
            estimated_emissions_kg_co2: Some(0.0),
            error: None,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: TransportRouteResult = serde_json::from_str(&json).unwrap();
        assert_eq!(r2.route_count, 3);
        assert_eq!(r2.estimated_minutes, Some(45));
        assert_eq!(r2.estimated_emissions_kg_co2, Some(0.0));
    }

    #[test]
    fn carbon_credit_query_serde_roundtrip() {
        let q = CarbonCreditQuery {
            agent_did: "did:mycelix:agent123".into(),
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: CarbonCreditQuery = serde_json::from_str(&json).unwrap();
        assert_eq!(q2.agent_did, "did:mycelix:agent123");
    }

    #[test]
    fn carbon_credit_result_serde_roundtrip() {
        let r = CarbonCreditResult {
            total_credits_kg_co2: 127.5,
            trips_logged: 34,
            error: None,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: CarbonCreditResult = serde_json::from_str(&json).unwrap();
        assert!((r2.total_credits_kg_co2 - 127.5).abs() < 1e-6);
        assert_eq!(r2.trips_logged, 34);
        assert!(r2.error.is_none());
    }

    // Emergency↔Commons cross-cluster type serde tests

    #[test]
    fn water_safety_query_serde_roundtrip() {
        let q = WaterSafetyQuery {
            area_lat: 32.9483,
            area_lon: -96.7299,
            radius_km: 10.0,
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: WaterSafetyQuery = serde_json::from_str(&json).unwrap();
        assert!((q2.area_lat - 32.9483).abs() < 1e-4);
        assert!((q2.area_lon - (-96.7299)).abs() < 1e-4);
        assert!((q2.radius_km - 10.0).abs() < 1e-6);
    }

    #[test]
    fn water_safety_result_serde_roundtrip() {
        let r = WaterSafetyResult {
            safe_sources: 8,
            contaminated_sources: 2,
            total_sources: 10,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: WaterSafetyResult = serde_json::from_str(&json).unwrap();
        assert_eq!(r2.safe_sources, 8);
        assert_eq!(r2.contaminated_sources, 2);
        assert_eq!(r2.total_sources, 10);
    }

    #[test]
    fn water_safety_result_all_contaminated() {
        let r = WaterSafetyResult {
            safe_sources: 0,
            contaminated_sources: 5,
            total_sources: 5,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: WaterSafetyResult = serde_json::from_str(&json).unwrap();
        assert_eq!(r2.safe_sources, 0);
        assert_eq!(r2.contaminated_sources, 5);
    }

    #[test]
    fn emergency_food_query_serde_roundtrip() {
        let q = EmergencyFoodQuery {
            area_lat: 29.7604,
            area_lon: -95.3698,
            radius_km: 25.0,
            people_count: 500,
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: EmergencyFoodQuery = serde_json::from_str(&json).unwrap();
        assert!((q2.area_lat - 29.7604).abs() < 1e-4);
        assert!((q2.area_lon - (-95.3698)).abs() < 1e-4);
        assert!((q2.radius_km - 25.0).abs() < 1e-6);
        assert_eq!(q2.people_count, 500);
    }

    #[test]
    fn emergency_food_result_serde_roundtrip() {
        let r = EmergencyFoodResult {
            available_kg: 2500.5,
            distribution_points: 4,
            estimated_days_supply: 3.5,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: EmergencyFoodResult = serde_json::from_str(&json).unwrap();
        assert!((r2.available_kg - 2500.5).abs() < 1e-6);
        assert_eq!(r2.distribution_points, 4);
        assert!((r2.estimated_days_supply - 3.5).abs() < 1e-6);
    }

    #[test]
    fn emergency_food_result_zero_supply() {
        let r = EmergencyFoodResult {
            available_kg: 0.0,
            distribution_points: 0,
            estimated_days_supply: 0.0,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: EmergencyFoodResult = serde_json::from_str(&json).unwrap();
        assert!((r2.available_kg).abs() < 1e-6);
        assert_eq!(r2.distribution_points, 0);
        assert!((r2.estimated_days_supply).abs() < 1e-6);
    }

    #[test]
    fn shelter_capacity_query_serde_roundtrip() {
        let q = ShelterCapacityQuery {
            area_lat: 30.2672,
            area_lon: -97.7431,
            radius_km: 15.0,
            beds_needed: 200,
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: ShelterCapacityQuery = serde_json::from_str(&json).unwrap();
        assert!((q2.area_lat - 30.2672).abs() < 1e-4);
        assert!((q2.area_lon - (-97.7431)).abs() < 1e-4);
        assert!((q2.radius_km - 15.0).abs() < 1e-6);
        assert_eq!(q2.beds_needed, 200);
    }

    #[test]
    fn shelter_capacity_result_serde_roundtrip() {
        let r = ShelterCapacityResult {
            available_beds: 150,
            total_shelters: 3,
            nearest_shelter_km: 2.4,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: ShelterCapacityResult = serde_json::from_str(&json).unwrap();
        assert_eq!(r2.available_beds, 150);
        assert_eq!(r2.total_shelters, 3);
        assert!((r2.nearest_shelter_km - 2.4).abs() < 1e-6);
    }

    #[test]
    fn shelter_capacity_result_no_shelters() {
        let r = ShelterCapacityResult {
            available_beds: 0,
            total_shelters: 0,
            nearest_shelter_km: 0.0,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: ShelterCapacityResult = serde_json::from_str(&json).unwrap();
        assert_eq!(r2.available_beds, 0);
        assert_eq!(r2.total_shelters, 0);
    }

    #[test]
    fn emergency_care_query_serde_roundtrip() {
        let q = EmergencyCareQuery {
            area_lat: 32.7767,
            area_lon: -96.7970,
            skill_needed: "trauma_surgeon".into(),
            urgency_level: 5,
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: EmergencyCareQuery = serde_json::from_str(&json).unwrap();
        assert!((q2.area_lat - 32.7767).abs() < 1e-4);
        assert!((q2.area_lon - (-96.7970)).abs() < 1e-4);
        assert_eq!(q2.skill_needed, "trauma_surgeon");
        assert_eq!(q2.urgency_level, 5);
    }

    #[test]
    fn emergency_care_query_low_urgency() {
        let q = EmergencyCareQuery {
            area_lat: 0.0,
            area_lon: 0.0,
            skill_needed: "first_aid".into(),
            urgency_level: 1,
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: EmergencyCareQuery = serde_json::from_str(&json).unwrap();
        assert_eq!(q2.urgency_level, 1);
        assert_eq!(q2.skill_needed, "first_aid");
    }

    #[test]
    fn emergency_care_result_serde_roundtrip() {
        let r = EmergencyCareResult {
            available_providers: 7,
            nearest_provider_km: 1.2,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: EmergencyCareResult = serde_json::from_str(&json).unwrap();
        assert_eq!(r2.available_providers, 7);
        assert!((r2.nearest_provider_km - 1.2).abs() < 1e-6);
    }

    #[test]
    fn emergency_care_result_no_providers() {
        let r = EmergencyCareResult {
            available_providers: 0,
            nearest_provider_km: 0.0,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: EmergencyCareResult = serde_json::from_str(&json).unwrap();
        assert_eq!(r2.available_providers, 0);
    }

    // Boundary validation tests for emergency↔commons types

    #[test]
    fn water_safety_query_extreme_coordinates() {
        let q = WaterSafetyQuery {
            area_lat: 90.0,
            area_lon: 180.0,
            radius_km: 0.001,
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: WaterSafetyQuery = serde_json::from_str(&json).unwrap();
        assert!((q2.area_lat - 90.0).abs() < 1e-6);
        assert!((q2.area_lon - 180.0).abs() < 1e-6);
    }

    #[test]
    fn water_safety_query_negative_coordinates() {
        let q = WaterSafetyQuery {
            area_lat: -90.0,
            area_lon: -180.0,
            radius_km: 100.0,
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: WaterSafetyQuery = serde_json::from_str(&json).unwrap();
        assert!((q2.area_lat - (-90.0)).abs() < 1e-6);
        assert!((q2.area_lon - (-180.0)).abs() < 1e-6);
    }

    #[test]
    fn shelter_capacity_query_zero_beds_needed() {
        let q = ShelterCapacityQuery {
            area_lat: 0.0,
            area_lon: 0.0,
            radius_km: 1.0,
            beds_needed: 0,
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: ShelterCapacityQuery = serde_json::from_str(&json).unwrap();
        assert_eq!(q2.beds_needed, 0);
    }

    #[test]
    fn emergency_food_query_zero_people() {
        let q = EmergencyFoodQuery {
            area_lat: 0.0,
            area_lon: 0.0,
            radius_km: 1.0,
            people_count: 0,
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: EmergencyFoodQuery = serde_json::from_str(&json).unwrap();
        assert_eq!(q2.people_count, 0);
    }

    #[test]
    fn emergency_care_query_max_urgency_level() {
        let q = EmergencyCareQuery {
            area_lat: 0.0,
            area_lon: 0.0,
            skill_needed: "any".into(),
            urgency_level: 255,
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: EmergencyCareQuery = serde_json::from_str(&json).unwrap();
        assert_eq!(q2.urgency_level, 255);
    }

    #[test]
    fn emergency_care_query_empty_skill() {
        let q = EmergencyCareQuery {
            area_lat: 0.0,
            area_lon: 0.0,
            skill_needed: "".into(),
            urgency_level: 3,
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: EmergencyCareQuery = serde_json::from_str(&json).unwrap();
        assert_eq!(q2.skill_needed, "");
    }

    // Hearth↔cluster typed helper serde tests

    #[test]
    fn hearth_member_query_serde_roundtrip() {
        let q = HearthMemberQuery {
            hearth_hash: ActionHash::from_raw_36(vec![1u8; 36]),
            agent: AgentPubKey::from_raw_36(vec![2u8; 36]),
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: HearthMemberQuery = serde_json::from_str(&json).unwrap();
        assert_eq!(q.hearth_hash, q2.hearth_hash);
        assert_eq!(q.agent, q2.agent);
    }

    #[test]
    fn hearth_member_result_found() {
        let r = HearthMemberResult {
            is_member: true,
            role: Some("Adult".into()),
            display_name: Some("Alice".into()),
            error: None,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: HearthMemberResult = serde_json::from_str(&json).unwrap();
        assert!(r2.is_member);
        assert_eq!(r2.role.as_deref(), Some("Adult"));
        assert_eq!(r2.display_name.as_deref(), Some("Alice"));
        assert!(r2.error.is_none());
    }

    #[test]
    fn hearth_member_result_not_found() {
        let r = HearthMemberResult {
            is_member: false,
            role: None,
            display_name: None,
            error: None,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: HearthMemberResult = serde_json::from_str(&json).unwrap();
        assert!(!r2.is_member);
        assert!(r2.role.is_none());
    }

    #[test]
    fn hearth_care_query_serde_roundtrip() {
        let q = HearthCareQuery {
            hearth_hash: ActionHash::from_raw_36(vec![3u8; 36]),
            care_type: Some("Childcare".into()),
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: HearthCareQuery = serde_json::from_str(&json).unwrap();
        assert_eq!(q.hearth_hash, q2.hearth_hash);
        assert_eq!(q2.care_type.as_deref(), Some("Childcare"));
    }

    #[test]
    fn hearth_care_query_no_filter() {
        let q = HearthCareQuery {
            hearth_hash: ActionHash::from_raw_36(vec![4u8; 36]),
            care_type: None,
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: HearthCareQuery = serde_json::from_str(&json).unwrap();
        assert!(q2.care_type.is_none());
    }

    #[test]
    fn hearth_care_result_serde_roundtrip() {
        let r = HearthCareResult {
            available_caregivers: 3,
            active_schedules: 7,
            error: None,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: HearthCareResult = serde_json::from_str(&json).unwrap();
        assert_eq!(r2.available_caregivers, 3);
        assert_eq!(r2.active_schedules, 7);
        assert!(r2.error.is_none());
    }

    #[test]
    fn hearth_emergency_query_serde_roundtrip() {
        let q = HearthEmergencyQuery {
            hearth_hash: ActionHash::from_raw_36(vec![5u8; 36]),
        };
        let json = serde_json::to_string(&q).unwrap();
        let q2: HearthEmergencyQuery = serde_json::from_str(&json).unwrap();
        assert_eq!(q.hearth_hash, q2.hearth_hash);
    }

    #[test]
    fn hearth_emergency_result_active() {
        let r = HearthEmergencyResult {
            has_active_alerts: true,
            active_alert_count: 2,
            members_checked_in: 4,
            members_missing: 1,
            error: None,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: HearthEmergencyResult = serde_json::from_str(&json).unwrap();
        assert!(r2.has_active_alerts);
        assert_eq!(r2.active_alert_count, 2);
        assert_eq!(r2.members_checked_in, 4);
        assert_eq!(r2.members_missing, 1);
        assert!(r2.error.is_none());
    }

    #[test]
    fn hearth_emergency_result_clear() {
        let r = HearthEmergencyResult {
            has_active_alerts: false,
            active_alert_count: 0,
            members_checked_in: 5,
            members_missing: 0,
            error: None,
        };
        let json = serde_json::to_string(&r).unwrap();
        let r2: HearthEmergencyResult = serde_json::from_str(&json).unwrap();
        assert!(!r2.has_active_alerts);
        assert_eq!(r2.active_alert_count, 0);
        assert_eq!(r2.members_missing, 0);
    }
}