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
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
// 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
//! Multi-dimensional consciousness profile for governance gating.
//!
//! Replaces the single MATL score (40% MFA + 60% reputation) with a
//! 4-dimensional `ConsciousnessProfile` that gates governance actions
//! with progressive vote weighting.
//!
//! ## Dimensions
//!
//! 1. **Identity** — MFA assurance level (Anonymous=0.0 → Critical=1.0)
//! 2. **Reputation** — Cross-hApp aggregated reputation with exponential decay
//! 3. **Community** — Peer trust attestations, weighted by attestor tier
//! 4. **Engagement** — Domain-specific participation, computed locally per bridge
//!
//! ## Usage
//!
//! Governance zomes call their local bridge's `get_consciousness_credential`,
//! then evaluate it with `evaluate_governance()` — a pure function with no
//! HDK dependency.

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

// When HDK is not available, provide no-op logging macros
#[cfg(not(feature = "hdk"))]
macro_rules! debug {
    ($($arg:tt)*) => {};
}
#[cfg(not(feature = "hdk"))]
macro_rules! warn {
    ($($arg:tt)*) => {};
}

use crate::consciousness_thresholds::{
    BOOTSTRAP_COMMUNITY_THRESHOLD, BOOTSTRAP_MIN_IDENTITY, BOOTSTRAP_TTL_US,
};

// ============================================================================
// Sigmoid authorization constants
// ============================================================================

/// Default sigmoid temperature for vote weight computation.
/// 0.05 provides a smooth transition over ~±0.1 around the threshold.
pub const VOTE_WEIGHT_TEMPERATURE: f64 = 0.05;

/// Maximum vote weight (basis points: 10000 = 100%).
pub const VOTE_WEIGHT_MAX_BP: f64 = 10000.0;

/// Hysteresis margin for tier transitions.
/// Promotion requires `threshold + margin`; demotion requires `threshold - margin`.
pub const TIER_HYSTERESIS_MARGIN: f64 = 0.05;

// ============================================================================
// Continuous sigmoid authorization
// ============================================================================

/// Compute continuous vote weight using sigmoid function.
///
/// Instead of hard tier thresholds, this provides a smooth gradient:
/// `W = W_max / (1 + e^(-(score - threshold) / temperature))`
///
/// - score < threshold: weight approaches 0 smoothly
/// - score = threshold: weight = W_max / 2
/// - score > threshold: weight approaches W_max smoothly
///
/// Temperature controls strictness:
/// - low temperature (0.02): sharp transition (like hard threshold)
/// - high temperature (0.10): gradual transition (noise-tolerant)
pub fn continuous_vote_weight(
    score: f64,
    threshold: f64,
    temperature: f64,
    max_weight: f64,
) -> f64 {
    if !temperature.is_finite()
        || temperature <= 0.0
        || !score.is_finite()
        || !threshold.is_finite()
        || !max_weight.is_finite()
        || max_weight < 0.0
    {
        warn!("NaN/Inf fallback in continuous_vote_weight: score={}, threshold={}, temperature={}, max_weight={}", score, threshold, temperature, max_weight);
        return 0.0;
    }
    let exponent = -((score - threshold) / temperature);
    // Clamp exponent to prevent overflow
    let exponent = exponent.clamp(-20.0, 20.0);
    max_weight / (1.0 + exponent.exp())
}

// ============================================================================
// Core types
// ============================================================================

/// 4-dimensional consciousness profile.
///
/// Each dimension is 0.0–1.0. Governance actions require different
/// minimum combinations. Vote weight scales with overall profile strength.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct ConsciousnessProfile {
    /// Identity verification strength (from MFA AssuranceLevel).
    /// Anonymous=0.0, Basic=0.25, Verified=0.5, HighlyAssured=0.75, Critical=1.0
    pub identity: f64,

    /// Cross-hApp reputation (from identity bridge aggregated reputation).
    /// Exponential decay with 30-day half-life, multi-source weighted average.
    pub reputation: f64,

    /// Community trust attestations (from aggregated peer trust credentials).
    /// Weighted by attestor's own tier — higher-consciousness peers count more.
    pub community: f64,

    /// Domain-specific engagement (computed locally by each cluster bridge).
    ///
    /// ## Standard computation formula
    ///
    /// All bridge coordinators SHOULD compute engagement as:
    ///
    /// ```text
    /// engagement = min(1.0, raw_events / baseline_events)
    /// ```
    ///
    /// where:
    /// - `raw_events` = count of domain-relevant actions (creates, updates, queries,
    ///   votes) by this agent in the trailing 30-day window
    /// - `baseline_events` = cluster-specific expected participation threshold
    ///   (e.g., 50 for commons, 20 for governance, 10 for personal)
    ///
    /// Apply exponential decay with a 30-day half-life to match the reputation
    /// dimension's decay characteristics:
    ///
    /// ```text
    /// decayed_events = Σ event_i × 0.5^(age_days_i / 30)
    /// ```
    ///
    /// Bridges that do not compute engagement locally SHOULD set this to 0.0
    /// (conservative default), NOT 1.0.
    pub engagement: f64,
}

impl ConsciousnessProfile {
    /// Combined score — weighted average of all 4 dimensions.
    ///
    /// Identity and community are weighted higher for governance:
    /// - identity:   25%
    /// - reputation:  25%
    /// - community:  30%
    /// - engagement: 20%
    pub fn combined_score(&self) -> f64 {
        // Sanitize inputs first — prevents NaN from entering arithmetic.
        // Non-finite dimensions clamp to 0.0 (safest default: no contribution).
        let i = if self.identity.is_finite() {
            self.identity.clamp(0.0, 1.0)
        } else {
            warn!("NaN/Inf in combined_score: identity={}", self.identity);
            0.0
        };
        let r = if self.reputation.is_finite() {
            self.reputation.clamp(0.0, 1.0)
        } else {
            warn!("NaN/Inf in combined_score: reputation={}", self.reputation);
            0.0
        };
        let c = if self.community.is_finite() {
            self.community.clamp(0.0, 1.0)
        } else {
            warn!("NaN/Inf in combined_score: community={}", self.community);
            0.0
        };
        let e = if self.engagement.is_finite() {
            self.engagement.clamp(0.0, 1.0)
        } else {
            warn!("NaN/Inf in combined_score: engagement={}", self.engagement);
            0.0
        };
        (i * 0.25 + r * 0.25 + c * 0.30 + e * 0.20).clamp(0.0, 1.0)
    }

    /// Derive the consciousness tier from this profile's combined score.
    pub fn tier(&self) -> ConsciousnessTier {
        ConsciousnessTier::from_score(self.combined_score())
    }

    /// Derive consciousness tier with hysteresis, given the current tier.
    ///
    /// Prevents rapid tier oscillation from measurement noise at boundaries.
    pub fn tier_with_hysteresis(&self, current_tier: ConsciousnessTier) -> ConsciousnessTier {
        ConsciousnessTier::from_score_with_hysteresis(self.combined_score(), current_tier)
    }

    /// Compute continuous vote weight for governance participation.
    ///
    /// Uses sigmoid function centered at Citizen threshold (0.4)
    /// with temperature 0.05 for noise-tolerant transitions.
    pub fn vote_weight_continuous(&self) -> f64 {
        continuous_vote_weight(
            self.combined_score(),
            0.4, // Citizen threshold
            VOTE_WEIGHT_TEMPERATURE,
            VOTE_WEIGHT_MAX_BP,
        )
    }

    /// Create a profile with all dimensions at zero (anonymous, no history).
    pub fn zero() -> Self {
        Self {
            identity: 0.0,
            reputation: 0.0,
            community: 0.0,
            engagement: 0.0,
        }
    }

    /// Sanitize a single f64 dimension: NaN/Infinity → 0.0, then clamp to [0, 1].
    #[inline]
    fn sanitize(v: f64) -> f64 {
        if v.is_finite() {
            v.clamp(0.0, 1.0)
        } else {
            warn!("NaN/Inf sanitized to 0.0: input={}", v);
            0.0
        }
    }

    /// Clamp all dimensions to 0.0–1.0, replacing NaN/Infinity with 0.0.
    pub fn clamped(&self) -> Self {
        Self {
            identity: Self::sanitize(self.identity),
            reputation: Self::sanitize(self.reputation),
            community: Self::sanitize(self.community),
            engagement: Self::sanitize(self.engagement),
        }
    }

    /// Returns true if all dimensions are finite (not NaN or Infinity).
    pub fn is_valid(&self) -> bool {
        self.identity.is_finite()
            && self.reputation.is_finite()
            && self.community.is_finite()
            && self.engagement.is_finite()
    }

    // ════════════════════════════════════════════════════════════════════════
    // MINIMAL VIABLE BRIDGE: Symthaea → Mycelix mapping
    // ════════════════════════════════════════════════════════════════════════

    /// Create a profile from a Symthaea unified consciousness score.
    ///
    /// This is the **Minimal Viable Bridge**: one Symthaea metric (C_unified)
    /// maps 1:1 to the engagement dimension. Other dimensions come from their
    /// respective sources (identity bridge, reputation history, peer attestations).
    ///
    /// # Arguments
    /// * `unified_consciousness` — C_unified from `ConsciousnessEngineOutput` \[0, 1\]
    /// * `identity` — from identity bridge (MFA assurance level) \[0, 1\]
    /// * `reputation` — from reputation bridge (30-day decayed history) \[0, 1\]
    /// * `community` — from community attestations (peer trust) \[0, 1\]
    ///
    /// All values are clamped to \[0, 1\].
    pub fn from_unified_consciousness(
        unified_consciousness: f64,
        identity: f64,
        reputation: f64,
        community: f64,
    ) -> Self {
        Self {
            identity: identity.clamp(0.0, 1.0),
            reputation: reputation.clamp(0.0, 1.0),
            community: community.clamp(0.0, 1.0),
            engagement: unified_consciousness.clamp(0.0, 1.0),
        }
    }

    /// Create a profile from Symthaea's multi-dimensional consciousness signals.
    ///
    /// This is the enriched bridge — instead of mapping a single unified score
    /// to `engagement`, it computes `engagement` as a weighted composite of
    /// Symthaea's empirical consciousness metrics:
    ///
    /// ```text
    /// engagement = 0.35 × phi + 0.25 × meta_awareness + 0.20 × coherence + 0.20 × care_activation
    /// ```
    ///
    /// This weighting prioritizes empirical consciousness (phi, meta-awareness)
    /// over social/empathic aspects, while keeping all signals meaningful.
    ///
    /// # Arguments
    /// * `phi` — Integrated Information (Φ), primary consciousness measure [0, 1]
    /// * `meta_awareness` — Depth of meta-cognition/self-reflection [0, 1]
    /// * `coherence` — Narrative continuity and temporal binding [0, 1]
    /// * `care_activation` — Empathic responsiveness [0, 1]
    /// * `identity` — MFA assurance level [0, 1] (from identity bridge)
    /// * `reputation` — Cross-hApp reputation [0, 1] (from reputation bridge)
    /// * `community` — Peer trust attestations [0, 1] (from community)
    pub fn from_symthaea(
        phi: f64,
        meta_awareness: f64,
        coherence: f64,
        care_activation: f64,
        identity: f64,
        reputation: f64,
        community: f64,
    ) -> Self {
        let phi_c = phi.clamp(0.0, 1.0);
        let meta_c = meta_awareness.clamp(0.0, 1.0);
        let coh_c = coherence.clamp(0.0, 1.0);
        let care_c = care_activation.clamp(0.0, 1.0);

        let engagement =
            (0.35 * phi_c + 0.25 * meta_c + 0.20 * coh_c + 0.20 * care_c).clamp(0.0, 1.0);

        Self {
            identity: identity.clamp(0.0, 1.0),
            reputation: reputation.clamp(0.0, 1.0),
            community: community.clamp(0.0, 1.0),
            engagement,
        }
    }
}

impl Default for ConsciousnessProfile {
    fn default() -> Self {
        Self::zero()
    }
}

/// Time-limited credential containing a `ConsciousnessProfile`.
///
/// Stored on the agent's source chain. Governance zomes validate locally
/// by checking issuer and expiry — no cross-cluster call needed at
/// governance time.
///
/// **Deprecated**: Use `sovereign_gate::SovereignCredential` (8D) instead.
/// This 4D type is retained for backward compatibility during the migration.
#[deprecated(
    since = "0.9.0",
    note = "Use sovereign_gate::SovereignCredential (8D) instead"
)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ConsciousnessCredential {
    /// Agent's DID (e.g., "did:mycelix:<pubkey>").
    pub did: String,
    /// The multi-dimensional profile.
    pub profile: ConsciousnessProfile,
    /// Derived tier at issuance time.
    pub tier: ConsciousnessTier,
    /// Issuance timestamp (microseconds since epoch).
    pub issued_at: u64,
    /// Expiry timestamp (default: issued_at + 24 hours).
    pub expires_at: u64,
    /// DID of the issuing bridge (e.g., "did:mycelix:<identity_bridge_pubkey>").
    pub issuer: String,
    /// BLAKE3 hash of the agent's behavioral trajectory (from TrajectoryAccumulator).
    #[serde(default)]
    pub trajectory_commitment: Option<[u8; 32]>,
    /// Extensible key-value store for future credential features.
    /// Avoids adding new `Option<T>` fields for every feature.
    /// See [`ExtensionKey`] for the registry of known keys.
    #[serde(default)]
    pub extensions: std::collections::HashMap<String, Vec<u8>>,
}

/// Registry of known extension keys for [`ConsciousnessCredential::extensions`].
///
/// Using these constants prevents typo bugs and ensures consistency across
/// producers and consumers. Unknown keys are allowed (forward-compatible)
/// but known keys should always use these constants.
pub mod ExtensionKey {
    /// Substrate type identifier (u8-encoded `SubstrateType` variant).
    pub const SUBSTRATE_TYPE: &str = "substrate_type";
    /// Per-region substrate feasibility scores (bincode-encoded `Vec<(String, f32)>`).
    pub const REGION_FEASIBILITY: &str = "region_feasibility";
    /// Sub-passport DID reference for delegated credentials.
    pub const SUB_PASSPORT_DID: &str = "sub_passport_did";
    /// Freshness attestation (bincode-encoded `FreshnessAttestation`).
    pub const FRESHNESS_ATTESTATION: &str = "freshness_attestation";
    /// Moral algebra summary score (f32 LE bytes).
    pub const MORAL_SCORE: &str = "moral_score";
}

impl ConsciousnessCredential {
    /// Default TTL for credentials: 24 hours in microseconds.
    pub const DEFAULT_TTL_US: u64 = 86_400_000_000;

    /// Check if the credential has expired relative to the given timestamp.
    pub fn is_expired(&self, now_us: u64) -> bool {
        now_us >= self.expires_at
    }

    /// Issue a credential from a unified consciousness score (Minimal Viable Bridge).
    ///
    /// Creates a `ConsciousnessProfile` using [`ConsciousnessProfile::from_unified_consciousness`],
    /// derives the tier, and wraps it in a 24h credential.
    ///
    /// # Arguments
    /// * `did` — Agent's DID string
    /// * `unified_consciousness` — C_unified from Symthaea's consciousness engine \[0, 1\]
    /// * `identity` / `reputation` / `community` — other profile dimensions \[0, 1\]
    /// * `issuer` — DID of the issuing bridge zome
    /// * `now_us` — current time in microseconds since epoch
    pub fn from_unified_consciousness(
        did: String,
        unified_consciousness: f64,
        identity: f64,
        reputation: f64,
        community: f64,
        issuer: String,
        now_us: u64,
    ) -> Self {
        let profile = ConsciousnessProfile::from_unified_consciousness(
            unified_consciousness,
            identity,
            reputation,
            community,
        );
        let tier = profile.clamped().tier();
        Self {
            did,
            profile,
            tier,
            issued_at: now_us,
            expires_at: now_us + Self::DEFAULT_TTL_US,
            issuer,
            trajectory_commitment: None,
            extensions: std::collections::HashMap::new(),
        }
    }

    /// Issue a credential from Symthaea's multi-dimensional consciousness signals.
    ///
    /// Enriched bridge: computes `engagement` from phi, meta_awareness, coherence,
    /// and care_activation instead of a single unified score.
    ///
    /// See [`ConsciousnessProfile::from_symthaea`] for the weighting formula.
    pub fn from_symthaea(
        did: String,
        phi: f64,
        meta_awareness: f64,
        coherence: f64,
        care_activation: f64,
        identity: f64,
        reputation: f64,
        community: f64,
        issuer: String,
        now_us: u64,
    ) -> Self {
        let profile = ConsciousnessProfile::from_symthaea(
            phi,
            meta_awareness,
            coherence,
            care_activation,
            identity,
            reputation,
            community,
        );
        let tier = profile.clamped().tier();
        Self {
            did,
            profile,
            tier,
            issued_at: now_us,
            expires_at: now_us + Self::DEFAULT_TTL_US,
            issuer,
            trajectory_commitment: None,
            extensions: std::collections::HashMap::new(),
        }
    }

    /// Set an extension value.
    pub fn set_extension(&mut self, key: impl Into<String>, value: Vec<u8>) {
        self.extensions.insert(key.into(), value);
    }

    /// Get an extension value.
    pub fn get_extension(&self, key: &str) -> Option<&Vec<u8>> {
        self.extensions.get(key)
    }

    /// Remove an extension value.
    pub fn remove_extension(&mut self, key: &str) -> Option<Vec<u8>> {
        self.extensions.remove(key)
    }

    /// Set the trajectory commitment from a `TrajectoryAccumulator`'s output.
    ///
    /// # Integration point
    ///
    /// The bridge adapter (e.g., `symthaea-mycelix-holochain`) should:
    /// 1. Maintain a `TrajectoryAccumulator` per agent
    /// 2. Call `accumulator.trajectory_commitment()` to get the BLAKE3 hash
    /// 3. Chain `.with_trajectory_commitment(hash)` on the issued credential
    ///
    /// ```ignore
    /// let cred = ConsciousnessCredential::from_unified_consciousness(...)
    ///     .with_trajectory_commitment(accumulator.trajectory_commitment().unwrap());
    /// ```
    pub fn with_trajectory_commitment(mut self, commitment: [u8; 32]) -> Self {
        self.trajectory_commitment = Some(commitment);
        self
    }

    /// Check if the credential has a trajectory binding.
    pub fn has_trajectory_binding(&self) -> bool {
        self.trajectory_commitment.is_some()
    }
}

// ============================================================================
// Tiers
// ============================================================================

/// Governance tiers derived from combined consciousness score.
///
/// **Deprecated**: Use `sovereign_gate::CivicTier` instead. The 5 tiers
/// are identical (Observer→Guardian), but CivicTier is the canonical type
/// for the 8D sovereign profile system.
#[deprecated(since = "0.9.0", note = "Use sovereign_gate::CivicTier instead")]
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ConsciousnessTier {
    /// combined < 0.3 — can read, no governance participation
    Observer,
    /// combined >= 0.3 — basic proposals
    Participant,
    /// combined >= 0.4 — voting rights
    Citizen,
    /// combined >= 0.6 — constitutional actions
    Steward,
    /// combined >= 0.8 — emergency powers
    Guardian,
}

impl ConsciousnessTier {
    /// Derive a tier from a combined consciousness score.
    pub fn from_score(score: f64) -> Self {
        if score >= 0.8 {
            Self::Guardian
        } else if score >= 0.6 {
            Self::Steward
        } else if score >= 0.4 {
            Self::Citizen
        } else if score >= 0.3 {
            Self::Participant
        } else {
            Self::Observer
        }
    }

    /// Minimum combined score required for this tier.
    pub fn min_score(&self) -> f64 {
        match self {
            Self::Observer => 0.0,
            Self::Participant => 0.3,
            Self::Citizen => 0.4,
            Self::Steward => 0.6,
            Self::Guardian => 0.8,
        }
    }

    /// Progressive vote weight in basis points (0–10000).
    ///
    /// Observers cannot vote. Weight increases with tier.
    pub fn vote_weight_bp(&self) -> u32 {
        match self {
            Self::Observer => 0,
            Self::Participant => 5000,
            Self::Citizen => 7500,
            Self::Steward => 10000,
            Self::Guardian => 10000,
        }
    }

    /// Tier transition with hysteresis to prevent oscillation at boundaries.
    ///
    /// Promotion requires crossing `threshold + TIER_HYSTERESIS_MARGIN`.
    /// Demotion requires dropping below `threshold - TIER_HYSTERESIS_MARGIN`.
    /// This prevents rapid tier flapping from measurement noise.
    pub fn from_score_with_hysteresis(
        score: f64,
        current_tier: ConsciousnessTier,
    ) -> ConsciousnessTier {
        let margin = TIER_HYSTERESIS_MARGIN;

        // Determine what tier we'd promote to (higher threshold required)
        let promoted = if score >= 0.8 + margin {
            ConsciousnessTier::Guardian
        } else if score >= 0.6 + margin {
            ConsciousnessTier::Steward
        } else if score >= 0.4 + margin {
            ConsciousnessTier::Citizen
        } else if score >= 0.3 + margin {
            ConsciousnessTier::Participant
        } else {
            ConsciousnessTier::Observer
        };

        // Determine what tier we'd demote to (lower threshold required)
        let demoted = if score < 0.3 - margin {
            ConsciousnessTier::Observer
        } else if score < 0.4 - margin {
            ConsciousnessTier::Participant
        } else if score < 0.6 - margin {
            ConsciousnessTier::Citizen
        } else if score < 0.8 - margin {
            ConsciousnessTier::Steward
        } else {
            ConsciousnessTier::Guardian
        };

        // Promote if we'd go higher, demote if we'd go lower, else stay
        if promoted > current_tier {
            promoted
        } else if demoted < current_tier {
            demoted
        } else {
            current_tier
        }
    }

    /// Degrade the tier by `levels` steps. Floors at Observer.
    pub fn degrade(self, levels: u32) -> Self {
        let tiers = [
            Self::Observer,
            Self::Participant,
            Self::Citizen,
            Self::Steward,
            Self::Guardian,
        ];
        let current_idx = tiers.iter().position(|t| *t == self).unwrap_or(0);
        let new_idx = current_idx.saturating_sub(levels as usize);
        tiers[new_idx]
    }

    /// Upgrade one level, capped at `max_tier`.
    pub fn upgrade_capped(self, max_tier: Self) -> Self {
        let tiers = [
            Self::Observer,
            Self::Participant,
            Self::Citizen,
            Self::Steward,
            Self::Guardian,
        ];
        let current_idx = tiers.iter().position(|t| *t == self).unwrap_or(0);
        let max_idx = tiers.iter().position(|t| *t == max_tier).unwrap_or(0);
        let new_idx = (current_idx + 1).min(max_idx);
        tiers[new_idx]
    }
}

// ============================================================================
// Governance requirements
// ============================================================================

/// What a governance action requires from the consciousness profile.
///
/// The `min_tier` is always checked. Optional per-dimension minimums
/// add additional requirements (e.g., constitutional changes require
/// minimum identity verification AND community trust).
///
/// **Deprecated**: Use `sovereign_gate::CivicRequirement` (8D) instead.
#[deprecated(
    since = "0.9.0",
    note = "Use sovereign_gate::CivicRequirement (8D) instead"
)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct GovernanceRequirement {
    /// Minimum consciousness tier required.
    pub min_tier: ConsciousnessTier,
    /// Optional minimum identity dimension (None = no minimum).
    pub min_identity: Option<f64>,
    /// Optional minimum community dimension (None = no minimum).
    pub min_community: Option<f64>,
}

/// Result of evaluating a profile against a governance requirement.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct GovernanceEligibility {
    /// Whether the agent meets all requirements.
    pub eligible: bool,
    /// Progressive vote weight in basis points (0–10000).
    pub weight_bp: u32,
    /// The agent's derived consciousness tier.
    pub tier: ConsciousnessTier,
    /// The agent's consciousness profile.
    pub profile: ConsciousnessProfile,
    /// Why ineligible (empty if eligible).
    pub reasons: Vec<String>,
    /// Restoration progress (0.0–1.0). 1.0 for non-blacklisted agents.
    /// Only meaningful when used with `evaluate_governance_with_reputation`.
    #[serde(default = "default_restoration_progress")]
    pub restoration_progress: f64,
}

fn default_restoration_progress() -> f64 {
    1.0
}

// ============================================================================
// Gate audit input
// ============================================================================

/// Input for logging a governance gate decision via the bridge's
/// `log_governance_gate` extern.
///
/// Each gated coordinator constructs this after `evaluate_governance()`
/// and fires it as a best-effort cross-zome call to the cluster bridge.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct GateAuditInput {
    /// The extern function that triggered the gate check.
    pub action_name: String,
    /// The zome that performed the check.
    pub zome_name: String,
    /// Whether the agent met all requirements.
    pub eligible: bool,
    /// The agent's derived consciousness tier (Debug-formatted).
    pub actual_tier: String,
    /// The minimum tier required by the governance action (Debug-formatted).
    pub required_tier: String,
    /// Progressive vote weight in basis points (0–10000).
    pub weight_bp: u32,
    /// Optional correlation ID for cross-cluster audit trail linkage.
    /// Format: "<agent_hex_prefix>:<timestamp_us>" — generated at action entry points.
    #[serde(default)]
    pub correlation_id: Option<String>,
    /// Source of the consciousness credential used for this gate check.
    ///
    /// Enables post-incident forensics by distinguishing real credentials from
    /// cached or bootstrap credentials. Values:
    /// - `"identity_bridge_fresh"` — newly issued by identity cluster
    /// - `"identity_bridge_refresh"` — refreshed within expiry window
    /// - `"cache_hit"` — retrieved from local credential cache
    /// - `"bootstrap"` — bootstrap credential for small communities
    #[serde(default)]
    pub credential_source: Option<String>,
}

// ============================================================================
// Evaluation (pure functions — no HDK dependency)
// ============================================================================

/// Grace period for recently-expired credentials: 30 minutes in microseconds.
///
/// During the grace period, basic/read operations (Participant tier or below)
/// are still allowed — giving the system time to proactively refresh.
pub const GRACE_PERIOD_US: u64 = 1_800_000_000;

/// Refresh window: proactively refresh credentials within 2 hours of expiry.
pub const REFRESH_WINDOW_US: u64 = 7_200_000_000;

/// Determine whether a gate decision should be logged to the audit trail.
///
/// Strategy: always log rejections and high-tier actions; sample 10% of
/// basic/proposal approvals to reduce DHT write load.
pub fn should_audit(
    requirement: &GovernanceRequirement,
    eligible: bool,
    agent_hash: &[u8],
    action_name: &str,
) -> bool {
    // Always log rejections
    if !eligible {
        return true;
    }
    match requirement.min_tier {
        // Always log constitutional and voting actions
        ConsciousnessTier::Steward | ConsciousnessTier::Guardian => true,
        ConsciousnessTier::Citizen => true,
        // Sample ~10% of basic/proposal approvals using action-salted hash
        _ => {
            let sample_byte = agent_hash.last().copied().unwrap_or(0);
            let salt: u8 = action_name.bytes().fold(0u8, |acc, b| acc.wrapping_add(b));
            sample_byte.wrapping_add(salt) < 26 // ~10% of 256
        }
    }
}

/// Check if a credential is within the refresh window (nearing expiry).
pub fn needs_refresh(credential: &ConsciousnessCredential, now_us: u64) -> bool {
    !credential.is_expired(now_us)
        && credential.expires_at > now_us
        && credential.expires_at - now_us < REFRESH_WINDOW_US
}

// ============================================================================
// Bootstrap (cold-start communities)
// ============================================================================

/// Check whether an agent is eligible for a bootstrap credential.
pub fn is_bootstrap_eligible(agent_count: u32, identity_score: f64) -> bool {
    agent_count < BOOTSTRAP_COMMUNITY_THRESHOLD && identity_score >= BOOTSTRAP_MIN_IDENTITY
}

/// Create a bootstrap credential for cold-start communities.
pub fn bootstrap_credential(
    did: String,
    identity_score: f64,
    now_us: u64,
) -> ConsciousnessCredential {
    let clamped_identity = identity_score.clamp(0.0, 1.0);
    ConsciousnessCredential {
        did,
        profile: ConsciousnessProfile {
            identity: clamped_identity,
            reputation: 0.0,
            community: 0.0,
            engagement: 0.0,
        },
        tier: ConsciousnessTier::Participant,
        issued_at: now_us,
        expires_at: now_us.saturating_add(BOOTSTRAP_TTL_US),
        issuer: "did:mycelix:bootstrap".to_string(),
        trajectory_commitment: None,
        extensions: std::collections::HashMap::new(),
    }
}

/// Evaluate a bootstrap credential against a governance requirement.
/// Capped at Participant tier — voting/constitutional/guardian always rejected.
pub fn evaluate_bootstrap_governance(
    credential: &ConsciousnessCredential,
    requirement: &GovernanceRequirement,
    now_us: u64,
) -> GovernanceEligibility {
    if credential.is_expired(now_us) {
        return GovernanceEligibility {
            eligible: false,
            weight_bp: 0,
            tier: ConsciousnessTier::Observer,
            profile: credential.profile.clone(),
            reasons: vec!["Bootstrap credential expired".into()],
            restoration_progress: 1.0,
        };
    }
    if requirement.min_tier > ConsciousnessTier::Participant {
        return GovernanceEligibility {
            eligible: false,
            weight_bp: 0,
            tier: credential.tier,
            profile: credential.profile.clone(),
            reasons: vec![format!(
                "Bootstrap credentials are capped at Participant; {:?} required",
                requirement.min_tier,
            )],
            restoration_progress: 1.0,
        };
    }
    if let Some(min_id) = requirement.min_identity {
        if credential.profile.identity < min_id {
            return GovernanceEligibility {
                eligible: false,
                weight_bp: 0,
                tier: credential.tier,
                profile: credential.profile.clone(),
                reasons: vec![format!(
                    "Identity {:.2} below required {:.2}",
                    credential.profile.identity, min_id,
                )],
                restoration_progress: 1.0,
            };
        }
    }
    GovernanceEligibility {
        eligible: true,
        weight_bp: 5_000,
        tier: ConsciousnessTier::Participant,
        profile: credential.profile.clone(),
        reasons: vec!["Bootstrap credential: temporary Participant access".into()],
        restoration_progress: 1.0,
    }
}

/// Evaluate a consciousness credential against a governance requirement.
///
/// This is the core gating function. It checks credential expiry first,
/// then evaluates the embedded profile against tier/dimension requirements.
/// Supports a 30-minute grace period for recently-expired credentials on
/// basic (Participant-tier) operations only.
/// Pure — no HDK calls, no side effects.
pub fn evaluate_governance(
    credential: &ConsciousnessCredential,
    requirement: &GovernanceRequirement,
    now_us: u64,
) -> GovernanceEligibility {
    if credential.is_expired(now_us) {
        // Check grace period: allow basic/read operations for 30 min after expiry
        let in_grace = now_us < credential.expires_at.saturating_add(GRACE_PERIOD_US);
        if in_grace && requirement.min_tier <= ConsciousnessTier::Participant {
            // Grace period — evaluate normally but add warning
            let clamped = credential.profile.clamped();
            let tier = clamped.tier();
            let mut reasons = Vec::new();

            if tier < requirement.min_tier {
                reasons.push(format!(
                    "Tier {:?} below required {:?} (score {:.3}, need >= {:.3})",
                    tier,
                    requirement.min_tier,
                    clamped.combined_score(),
                    requirement.min_tier.min_score(),
                ));
            }
            if let Some(min_id) = requirement.min_identity {
                if clamped.identity < min_id {
                    reasons.push(format!(
                        "Identity {:.3} below required {:.3}",
                        clamped.identity, min_id
                    ));
                }
            }
            if let Some(min_comm) = requirement.min_community {
                if clamped.community < min_comm {
                    reasons.push(format!(
                        "Community {:.3} below required {:.3}",
                        clamped.community, min_comm
                    ));
                }
            }

            let eligible = reasons.is_empty();
            let weight_bp = if eligible { tier.vote_weight_bp() } else { 0 };

            // Always add the grace period warning
            reasons.push("Credential in grace period — refresh recommended".into());

            return GovernanceEligibility {
                eligible,
                weight_bp,
                tier,
                profile: clamped,
                reasons,
                restoration_progress: 1.0,
            };
        }

        return GovernanceEligibility {
            eligible: false,
            weight_bp: 0,
            tier: ConsciousnessTier::Observer,
            profile: credential.profile.clone(),
            reasons: vec![format!(
                "Credential expired at {} (now {})",
                credential.expires_at, now_us
            )],
            restoration_progress: 1.0,
        };
    }
    let clamped = credential.profile.clamped();
    let tier = clamped.tier();
    let mut reasons = Vec::new();

    // Check tier
    if tier < requirement.min_tier {
        reasons.push(format!(
            "Tier {:?} below required {:?} (score {:.3}, need >= {:.3})",
            tier,
            requirement.min_tier,
            clamped.combined_score(),
            requirement.min_tier.min_score(),
        ));
    }

    // Check identity minimum
    if let Some(min_id) = requirement.min_identity {
        if clamped.identity < min_id {
            reasons.push(format!(
                "Identity {:.3} below required {:.3}",
                clamped.identity, min_id,
            ));
        }
    }

    // Check community minimum
    if let Some(min_comm) = requirement.min_community {
        if clamped.community < min_comm {
            reasons.push(format!(
                "Community {:.3} below required {:.3}",
                clamped.community, min_comm,
            ));
        }
    }

    let eligible = reasons.is_empty();
    let mut weight_bp = if eligible { tier.vote_weight_bp() } else { 0 };

    // ── Sybil resistance: account age penalty ──────────────────────────
    // Young credentials get reduced governance weight. This penalizes
    // mass-created Sybil identities that haven't proven sustained
    // community participation. The penalty decays linearly over 72 hours.
    if eligible && weight_bp > 0 && credential.issued_at > 0 {
        let credential_age_us = now_us.saturating_sub(credential.issued_at);
        const SYBIL_MATURATION_PERIOD_US: u64 = 72 * 3600 * 1_000_000; // 72 hours
        if credential_age_us < SYBIL_MATURATION_PERIOD_US {
            let maturation_ratio = credential_age_us as f64 / SYBIL_MATURATION_PERIOD_US as f64;
            // Scale weight from 10% at creation to 100% at maturation
            let age_factor = 0.1 + 0.9 * maturation_ratio;
            let reduced = (weight_bp as f64 * age_factor) as u32;
            if reduced < weight_bp {
                reasons.push(format!(
                    "Young credential: weight reduced to {:.0}% (matures in {:.1}h)",
                    age_factor * 100.0,
                    (SYBIL_MATURATION_PERIOD_US - credential_age_us) as f64
                        / (3600.0 * 1_000_000.0)
                ));
                weight_bp = reduced.max(1); // Never zero if eligible
            }
        }
    }

    GovernanceEligibility {
        eligible,
        weight_bp,
        tier,
        profile: clamped,
        reasons,
        restoration_progress: 1.0,
    }
}

// ============================================================================
// Standard requirement presets
// ============================================================================

/// Requirement for basic governance participation (viewing proposals, commenting).
///
/// Participant tier (combined >= 0.3), no per-dimension minimums.
pub fn requirement_for_basic() -> GovernanceRequirement {
    GovernanceRequirement {
        min_tier: ConsciousnessTier::Participant,
        min_identity: None,
        min_community: None,
    }
}

/// Requirement for submitting proposals.
///
/// Participant tier + identity >= 0.25 (at least Basic MFA).
pub fn requirement_for_proposal() -> GovernanceRequirement {
    GovernanceRequirement {
        min_tier: ConsciousnessTier::Participant,
        min_identity: Some(0.25),
        min_community: None,
    }
}

/// Requirement for casting votes.
///
/// Citizen tier + identity >= 0.25. Weight scales with tier.
pub fn requirement_for_voting() -> GovernanceRequirement {
    GovernanceRequirement {
        min_tier: ConsciousnessTier::Citizen,
        min_identity: Some(0.25),
        min_community: None,
    }
}

/// Requirement for constitutional changes (bylaw amendments, etc.).
///
/// Steward tier + identity >= 0.5 + community >= 0.3.
pub fn requirement_for_constitutional() -> GovernanceRequirement {
    GovernanceRequirement {
        min_tier: ConsciousnessTier::Steward,
        min_identity: Some(0.5),
        min_community: Some(0.3),
    }
}

/// Requirement for guardian-level operations (system administration, etc.).
///
/// Guardian tier + identity >= 0.7 + community >= 0.5.
pub fn requirement_for_guardian() -> GovernanceRequirement {
    GovernanceRequirement {
        min_tier: ConsciousnessTier::Guardian,
        min_identity: Some(0.7),
        min_community: Some(0.5),
    }
}

// ============================================================================
// Shared consciousness gate (HDK-dependent)
// ============================================================================

/// Fetch the calling agent's consciousness credential via the specified bridge
/// zome and evaluate it against a governance requirement.
///
/// **Deprecated**: Use `sovereign_gate::gate_civic()` instead. This function
/// is retained as the fallback path for bridges that don't yet support
/// native `SovereignCredential` issuance.
///
/// Steps:
/// 1. `agent_info()` → derive DID
/// 2. Cross-zome call to `<bridge_zome>::get_consciousness_credential`
/// 3. `evaluate_governance()` (pure)
/// 4. `should_audit()` → best-effort `log_governance_gate` if sampled
/// 5. Reject with `WasmError` if ineligible
#[deprecated(since = "0.9.0", note = "Use sovereign_gate::gate_civic() instead")]
#[cfg(feature = "hdk")]
pub fn gate_consciousness(
    bridge_zome: &str,
    requirement: &GovernanceRequirement,
    action_name: &str,
) -> ExternResult<GovernanceEligibility> {
    let agent = agent_info()?.agent_initial_pubkey;
    let did = format!("did:mycelix:{}", agent);

    let response = call(
        CallTargetCell::Local,
        ZomeName::new(bridge_zome),
        FunctionName::new("get_consciousness_credential"),
        None,
        did,
    )?;

    let credential: ConsciousnessCredential = match response {
        ZomeCallResponse::Ok(extern_io) => extern_io.decode().map_err(|e| {
            wasm_error!(WasmErrorInner::Guest(format!(
                "Failed to decode consciousness credential: {}",
                e
            )))
        })?,
        other => {
            return Err(wasm_error!(WasmErrorInner::Guest(format!(
                "Consciousness credential call failed: {:?}",
                other
            ))));
        }
    };

    let now_us = sys_time()?.as_micros() as u64;
    let eligibility = evaluate_governance(&credential, requirement, now_us);

    // Record consciousness gate metrics
    let tier_index = match eligibility.tier {
        ConsciousnessTier::Observer => 0,
        ConsciousnessTier::Participant => 1,
        ConsciousnessTier::Citizen => 2,
        ConsciousnessTier::Steward => 3,
        ConsciousnessTier::Guardian => 4,
    };
    crate::metrics::record_gate_check(eligibility.eligible, tier_index, 0);

    // Fire audit log (best-effort, rate-limited via should_audit)
    if should_audit(
        requirement,
        eligibility.eligible,
        agent.as_ref(),
        action_name,
    ) {
        let audit = GateAuditInput {
            action_name: action_name.to_string(),
            zome_name: zome_info()?.name.to_string(),
            eligible: eligibility.eligible,
            actual_tier: format!("{:?}", eligibility.tier),
            required_tier: format!("{:?}", requirement.min_tier),
            weight_bp: eligibility.weight_bp,
            correlation_id: None,
            credential_source: None,
        };
        match call(
            CallTargetCell::Local,
            ZomeName::new(bridge_zome),
            FunctionName::new("log_governance_gate"),
            None,
            audit,
        ) {
            Ok(_) => {}
            Err(e) => {
                debug!("Audit log failed ({}): {:?}", bridge_zome, e);
            }
        }
    }

    // Best-effort refresh: if credential is nearing expiry, trigger a
    // background refresh call so the next gate check gets a fresh credential.
    // This does NOT block the current check — the credential is still valid.
    if needs_refresh(&credential, now_us) {
        debug!(
            "gate_consciousness: credential nearing expiry, triggering best-effort refresh via {}",
            bridge_zome
        );
        match call(
            CallTargetCell::Local,
            ZomeName::new(bridge_zome),
            FunctionName::new("refresh_consciousness_credential"),
            None,
            credential.did.clone(),
        ) {
            Ok(_) => {
                debug!(
                    "gate_consciousness: refresh triggered successfully via {}",
                    bridge_zome
                );
            }
            Err(e) => {
                debug!(
                    "gate_consciousness: refresh failed (non-fatal) via {}: {:?}",
                    bridge_zome, e
                );
            }
        }
    }

    if !eligibility.eligible {
        return Err(wasm_error!(WasmErrorInner::Guest(format!(
            "Consciousness gate: tier {:?} insufficient. Reasons: {}",
            eligibility.tier,
            eligibility.reasons.join(", ")
        ))));
    }

    Ok(eligibility)
}

// ============================================================================
// Governance audit query types
// ============================================================================

/// Filter for querying governance gate audit events.
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct GovernanceAuditFilter {
    /// Filter by the gated action name (e.g., "register_property").
    #[serde(default)]
    pub action_name: Option<String>,
    /// Filter by the zome that performed the check.
    #[serde(default)]
    pub zome_name: Option<String>,
    /// Filter by eligibility outcome.
    #[serde(default)]
    pub eligible: Option<bool>,
    /// Start of time range (inclusive), microseconds since epoch.
    #[serde(default)]
    pub from_us: Option<i64>,
    /// End of time range (inclusive), microseconds since epoch.
    #[serde(default)]
    pub to_us: Option<i64>,
}

/// Result of a governance audit query.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct GovernanceAuditResult {
    /// Matched audit entries (deserialized from BridgeEventEntry payloads).
    pub entries: Vec<GateAuditInput>,
    /// Number of entries that matched the filter.
    pub total_matched: u32,
}

// ============================================================================
// Reputation Decay, Slashing, and Restoration
// ============================================================================

/// Reputation decay rate per day (multiplicative).
/// Half-life ~347 days: `0.998^347 ~ 0.500`.
///
/// Basis: Dunbar (2010) — social relationships require maintenance;
/// trust fades without sustained positive interaction.
pub const REPUTATION_DECAY_PER_DAY: f64 = 0.998;

/// Slashing factor for detected Byzantine behavior.
/// Applied as: `reputation *= (1.0 - SLASH_FACTOR)`.
///
/// Basis: Ostrom (1990) — graduated sanctions in commons governance.
/// First offense halves reputation; recovery is possible but slow.
pub const REPUTATION_SLASH_FACTOR: f64 = 0.5;

/// Reputation floor below which an agent is considered blacklisted.
/// At this level, the agent cannot participate in governance.
///
/// Basis: Axelrod (1984) — sustained defection warrants exclusion,
/// but the threshold must be low enough to allow recovery.
pub const REPUTATION_BLACKLIST_THRESHOLD: f64 = 0.05;

/// Minimum consecutive good interactions to lift a blacklist.
///
/// Basis: Ubuntu restorative justice — redemption through demonstrated
/// commitment to community norms. 100 interactions ~ weeks of good behavior.
pub const REPUTATION_RESTORATION_INTERACTIONS: u32 = 100;

/// Maximum slash events before permanent reputation cap at 0.5.
/// Prevents repeated gaming of slash/recovery cycles.
///
/// Basis: Three-strikes principle with proportional response.
pub const REPUTATION_MAX_SLASHES: u32 = 5;

/// Cooldown period between slashes before the frequency penalty decays.
/// 7 days in microseconds.
pub const REPUTATION_SLASH_COOLDOWN_US: u64 = 7 * 24 * 3600 * 1_000_000;

/// Maximum additional penalty for rapid re-slashing (0.0-1.0).
pub const REPUTATION_SLASH_FREQUENCY_PENALTY: f64 = 0.5;

/// Reputation state for an agent, tracking decay and sanctions.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ReputationState {
    /// Current reputation score (0.0-1.0).
    pub score: f64,
    /// Last update timestamp (microseconds since epoch).
    pub last_updated_us: u64,
    /// Number of consecutive good interactions since last slash.
    pub consecutive_good: u32,
    /// Total slash events in this agent's history.
    pub total_slashes: u32,
    /// Whether the agent is currently blacklisted.
    pub blacklisted: bool,
    /// Timestamp at which blacklist was applied (for duration tracking).
    pub blacklisted_since_us: Option<u64>,
    /// Timestamp of the most recent slash (for cooldown frequency penalty).
    #[serde(default)]
    pub last_slash_us: Option<u64>,
}

impl Default for ReputationState {
    fn default() -> Self {
        Self {
            score: 0.0,
            last_updated_us: 0,
            consecutive_good: 0,
            total_slashes: 0,
            blacklisted: false,
            blacklisted_since_us: None,
            last_slash_us: None,
        }
    }
}

impl ReputationState {
    /// Create a new reputation state with the given initial score and timestamp.
    pub fn new(initial_score: f64, now_us: u64) -> Self {
        let sanitized = if initial_score.is_finite() {
            initial_score.clamp(0.0, 1.0)
        } else {
            warn!(
                "NaN/Inf in ReputationState::new: initial_score={}",
                initial_score
            );
            0.0
        };
        Self {
            score: sanitized,
            last_updated_us: now_us,
            ..Default::default()
        }
    }

    /// Apply temporal decay based on elapsed time.
    ///
    /// `reputation *= DECAY^days_elapsed`
    ///
    /// Uses microsecond timestamps. Safe for NaN/Inf inputs (clamps to 0).
    pub fn apply_decay(&mut self, now_us: u64) {
        if now_us <= self.last_updated_us {
            return; // No time elapsed or clock skew
        }
        let elapsed_us = now_us - self.last_updated_us;
        let elapsed_days = elapsed_us as f64 / 86_400_000_000.0;

        if !elapsed_days.is_finite() || elapsed_days <= 0.0 {
            if !elapsed_days.is_finite() {
                warn!("NaN/Inf in apply_decay: elapsed_days={}", elapsed_days);
            }
            return;
        }

        let decay_factor = REPUTATION_DECAY_PER_DAY.powf(elapsed_days);
        if decay_factor.is_finite() {
            self.score = (self.score * decay_factor).clamp(0.0, 1.0);
        } else {
            warn!(
                "NaN/Inf decay_factor in apply_decay: elapsed_days={}, decay_factor={}",
                elapsed_days, decay_factor
            );
            self.score = 0.0; // Extreme elapsed time -> full decay
        }
        self.last_updated_us = now_us;

        // Check blacklist threshold after decay
        self.check_blacklist(now_us);
    }

    /// Record a positive interaction, incrementing the consecutive good count.
    ///
    /// If the agent is blacklisted and reaches RESTORATION_INTERACTIONS,
    /// the blacklist is lifted (Ubuntu restorative justice model).
    pub fn record_good_interaction(&mut self, reputation_boost: f64, now_us: u64) {
        self.apply_decay(now_us);
        self.consecutive_good = self.consecutive_good.saturating_add(1);

        // Apply reputation boost (clamped to prevent abuse)
        let effective_boost = reputation_boost.clamp(0.0, 0.1);
        let cap = if self.total_slashes >= REPUTATION_MAX_SLASHES {
            0.5 // Permanent cap after max slashes
        } else {
            1.0
        };
        self.score = (self.score + effective_boost).clamp(0.0, cap);

        // Check restoration
        if self.blacklisted && self.consecutive_good >= REPUTATION_RESTORATION_INTERACTIONS {
            self.blacklisted = false;
            self.blacklisted_since_us = None;
            // Restore to minimum Participant threshold
            self.score = self.score.max(0.1);
        }
    }

    /// Apply a reputation slash for detected Byzantine behavior.
    ///
    /// Resets consecutive good interactions. Checks blacklist after slashing.
    ///
    /// Returns the new reputation score.
    pub fn slash(&mut self, now_us: u64) -> f64 {
        self.apply_decay(now_us);
        self.score *= 1.0 - REPUTATION_SLASH_FACTOR;
        self.apply_frequency_penalty(now_us);
        self.score = self.score.clamp(0.0, 1.0);
        self.consecutive_good = 0;
        self.total_slashes = self.total_slashes.saturating_add(1);
        self.last_slash_us = Some(now_us);
        self.check_blacklist(now_us);
        self.score
    }

    /// Apply a proportional slash with a custom factor.
    ///
    /// `factor` is clamped to [0.0, 1.0]. Applied as: `score *= (1.0 - factor)`.
    pub fn slash_proportional(&mut self, factor: f64, now_us: u64) -> f64 {
        self.apply_decay(now_us);
        let clamped_factor = factor.clamp(0.0, 1.0);
        self.score *= 1.0 - clamped_factor;
        self.apply_frequency_penalty(now_us);
        self.score = self.score.clamp(0.0, 1.0);
        self.consecutive_good = 0;
        self.total_slashes = self.total_slashes.saturating_add(1);
        self.last_slash_us = Some(now_us);
        self.check_blacklist(now_us);
        self.score
    }

    /// Check and update blacklist status.
    /// Apply additional penalty if this slash occurs within the cooldown window.
    fn apply_frequency_penalty(&mut self, now_us: u64) {
        if let Some(last) = self.last_slash_us {
            if now_us <= last + REPUTATION_SLASH_COOLDOWN_US {
                let elapsed = now_us.saturating_sub(last) as f64;
                let cooldown = REPUTATION_SLASH_COOLDOWN_US as f64;
                let recency = 1.0 - (elapsed / cooldown).min(1.0);
                let penalty = REPUTATION_SLASH_FREQUENCY_PENALTY * recency;
                self.score *= 1.0 - penalty;
            }
        }
    }

    fn check_blacklist(&mut self, now_us: u64) {
        if self.score < REPUTATION_BLACKLIST_THRESHOLD && !self.blacklisted {
            self.blacklisted = true;
            self.blacklisted_since_us = Some(now_us);
        }
    }

    /// Whether this agent can participate in governance.
    ///
    /// Blacklisted agents are excluded from all governance actions
    /// until they complete the restoration path.
    pub fn can_participate(&self) -> bool {
        !self.blacklisted
    }

    /// Restoration progress (0.0-1.0).
    ///
    /// Returns 1.0 for non-blacklisted agents.
    /// For blacklisted agents, tracks progress toward RESTORATION_INTERACTIONS.
    pub fn restoration_progress(&self) -> f64 {
        if !self.blacklisted {
            return 1.0;
        }
        (self.consecutive_good as f64 / REPUTATION_RESTORATION_INTERACTIONS as f64).clamp(0.0, 1.0)
    }
}

/// Minimum cartel confidence to trigger reputation slash.
pub const CARTEL_SLASH_MIN_CONFIDENCE: f64 = 0.7;
/// Minimum cartel size for reputation action.
pub const CARTEL_MIN_SIZE: usize = 3;

/// Apply a proportional reputation slash to all members of a detected cartel.
pub fn apply_cartel_slash(
    reputation_states: &mut std::collections::HashMap<String, ReputationState>,
    member_ids: &[String],
    confidence: f64,
    now_us: u64,
) -> Vec<(String, f64)> {
    if confidence < CARTEL_SLASH_MIN_CONFIDENCE || member_ids.len() < CARTEL_MIN_SIZE {
        return Vec::new();
    }
    let factor = confidence.clamp(0.0, 1.0);
    let mut results = Vec::with_capacity(member_ids.len());
    for member_id in member_ids {
        if let Some(state) = reputation_states.get_mut(member_id) {
            let new_score = state.slash_proportional(factor, now_us);
            results.push((member_id.clone(), new_score));
        }
    }
    results
}

/// Apply reputation decay to a ConsciousnessProfile's reputation dimension.
///
/// Convenience function for use in credential issuance pipelines.
pub fn decay_reputation(profile: &ConsciousnessProfile, elapsed_days: f64) -> ConsciousnessProfile {
    if !elapsed_days.is_finite() || elapsed_days <= 0.0 {
        if !elapsed_days.is_finite() {
            warn!("NaN/Inf in decay_reputation: elapsed_days={}", elapsed_days);
        }
        return profile.clone();
    }
    let decay_factor = REPUTATION_DECAY_PER_DAY.powf(elapsed_days);
    let decayed_rep = if decay_factor.is_finite() {
        (profile.reputation * decay_factor).clamp(0.0, 1.0)
    } else {
        warn!(
            "NaN/Inf decay_factor in decay_reputation: elapsed_days={}, decay_factor={}",
            elapsed_days, decay_factor
        );
        0.0
    };
    ConsciousnessProfile {
        identity: profile.identity,
        reputation: decayed_rep,
        community: profile.community,
        engagement: profile.engagement,
    }
}

/// Evaluate governance with reputation state integration.
///
/// Wraps `evaluate_governance` but also checks blacklist status
/// and applies restoration progress to vote weight.
///
/// # TOCTOU Warning
///
/// This function checks `reputation_state.blacklisted` at call time, but the
/// on-chain reputation may change between this check and the commit of the
/// governance action. Callers in coordinator zomes SHOULD re-check blacklist
/// status at commit time (e.g., in a `validate_*` callback) to close this
/// race window. In practice the risk is low (blacklisting is rare and requires
/// reputation < 0.05), but high-severity governance actions (constitutional
/// amendments, treasury operations) warrant the extra check.
pub fn evaluate_governance_with_reputation(
    credential: &ConsciousnessCredential,
    requirement: &GovernanceRequirement,
    reputation_state: &ReputationState,
    now_us: u64,
) -> GovernanceEligibility {
    // Blacklisted agents cannot participate
    if reputation_state.blacklisted {
        return GovernanceEligibility {
            eligible: false,
            weight_bp: 0,
            tier: ConsciousnessTier::Observer,
            profile: credential.profile.clone(),
            reasons: vec![format!(
                "Blacklisted: reputation {:.3} below threshold {:.3}. Restoration progress: {:.0}%",
                reputation_state.score,
                REPUTATION_BLACKLIST_THRESHOLD,
                reputation_state.restoration_progress() * 100.0,
            )],
            restoration_progress: reputation_state.restoration_progress(),
        };
    }

    // Evaluate normally
    let mut result = evaluate_governance(credential, requirement, now_us);

    // Scale vote weight by slash penalty if agent has been slashed before
    if reputation_state.total_slashes > 0 {
        let slash_penalty = 1.0 - (reputation_state.total_slashes as f64 * 0.05).min(0.25);
        result.weight_bp = (result.weight_bp as f64 * slash_penalty) as u32;
    }

    result
}

// ============================================================================
// Tests
// ============================================================================

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

    /// Convenience: a non-expired timestamp 24 hours in the future.
    const NOW: u64 = 1_000_000_000_000;

    /// Build a fresh (non-expired) credential wrapping the given profile.
    fn fresh_credential(profile: ConsciousnessProfile) -> ConsciousnessCredential {
        let tier = profile.clamped().tier();
        ConsciousnessCredential {
            did: "did:test:alice".to_string(),
            profile,
            tier,
            issued_at: NOW - 4 * 86_400_000_000, // 4 days ago (past 72h maturation)
            expires_at: NOW + 86_400_000_000,
            issuer: "test".to_string(),
            trajectory_commitment: None,
            extensions: std::collections::HashMap::new(),
        }
    }

    // -- ConsciousnessProfile --

    #[test]
    fn zero_profile_is_all_zeros() {
        let p = ConsciousnessProfile::zero();
        assert_eq!(p.identity, 0.0);
        assert_eq!(p.reputation, 0.0);
        assert_eq!(p.community, 0.0);
        assert_eq!(p.engagement, 0.0);
        assert_eq!(p.combined_score(), 0.0);
    }

    #[test]
    fn combined_score_weights_correct() {
        // All ones → 0.25 + 0.25 + 0.30 + 0.20 = 1.0
        let p = ConsciousnessProfile {
            identity: 1.0,
            reputation: 1.0,
            community: 1.0,
            engagement: 1.0,
        };
        assert!((p.combined_score() - 1.0).abs() < 1e-10);
    }

    #[test]
    fn combined_score_weighted_average() {
        let p = ConsciousnessProfile {
            identity: 0.5,
            reputation: 0.5,
            community: 0.5,
            engagement: 0.5,
        };
        assert!((p.combined_score() - 0.5).abs() < 1e-10);
    }

    #[test]
    fn combined_score_identity_only() {
        let p = ConsciousnessProfile {
            identity: 1.0,
            reputation: 0.0,
            community: 0.0,
            engagement: 0.0,
        };
        assert!((p.combined_score() - 0.25).abs() < 1e-10);
    }

    #[test]
    fn combined_score_community_only() {
        let p = ConsciousnessProfile {
            identity: 0.0,
            reputation: 0.0,
            community: 1.0,
            engagement: 0.0,
        };
        assert!((p.combined_score() - 0.30).abs() < 1e-10);
    }

    #[test]
    fn combined_score_engagement_only() {
        let p = ConsciousnessProfile {
            identity: 0.0,
            reputation: 0.0,
            community: 0.0,
            engagement: 1.0,
        };
        assert!((p.combined_score() - 0.20).abs() < 1e-10);
    }

    #[test]
    fn combined_score_reputation_only() {
        let p = ConsciousnessProfile {
            identity: 0.0,
            reputation: 1.0,
            community: 0.0,
            engagement: 0.0,
        };
        assert!((p.combined_score() - 0.25).abs() < 1e-10);
    }

    #[test]
    fn clamped_clips_values() {
        let p = ConsciousnessProfile {
            identity: 1.5,
            reputation: -0.3,
            community: 2.0,
            engagement: -1.0,
        };
        let c = p.clamped();
        assert_eq!(c.identity, 1.0);
        assert_eq!(c.reputation, 0.0);
        assert_eq!(c.community, 1.0);
        assert_eq!(c.engagement, 0.0);
    }

    #[test]
    fn clamped_preserves_valid_values() {
        let p = ConsciousnessProfile {
            identity: 0.5,
            reputation: 0.7,
            community: 0.3,
            engagement: 0.9,
        };
        let c = p.clamped();
        assert_eq!(c, p);
    }

    #[test]
    fn default_is_zero() {
        assert_eq!(
            ConsciousnessProfile::default(),
            ConsciousnessProfile::zero()
        );
    }

    // -- ConsciousnessTier --

    #[test]
    fn tier_from_score_boundaries() {
        assert_eq!(
            ConsciousnessTier::from_score(0.0),
            ConsciousnessTier::Observer
        );
        assert_eq!(
            ConsciousnessTier::from_score(0.29),
            ConsciousnessTier::Observer
        );
        assert_eq!(
            ConsciousnessTier::from_score(0.3),
            ConsciousnessTier::Participant
        );
        assert_eq!(
            ConsciousnessTier::from_score(0.39),
            ConsciousnessTier::Participant
        );
        assert_eq!(
            ConsciousnessTier::from_score(0.4),
            ConsciousnessTier::Citizen
        );
        assert_eq!(
            ConsciousnessTier::from_score(0.59),
            ConsciousnessTier::Citizen
        );
        assert_eq!(
            ConsciousnessTier::from_score(0.6),
            ConsciousnessTier::Steward
        );
        assert_eq!(
            ConsciousnessTier::from_score(0.79),
            ConsciousnessTier::Steward
        );
        assert_eq!(
            ConsciousnessTier::from_score(0.8),
            ConsciousnessTier::Guardian
        );
        assert_eq!(
            ConsciousnessTier::from_score(1.0),
            ConsciousnessTier::Guardian
        );
    }

    #[test]
    fn tier_min_scores_are_monotonic() {
        let tiers = [
            ConsciousnessTier::Observer,
            ConsciousnessTier::Participant,
            ConsciousnessTier::Citizen,
            ConsciousnessTier::Steward,
            ConsciousnessTier::Guardian,
        ];
        for i in 1..tiers.len() {
            assert!(
                tiers[i].min_score() > tiers[i - 1].min_score(),
                "{:?} min_score should be > {:?} min_score",
                tiers[i],
                tiers[i - 1]
            );
        }
    }

    #[test]
    fn tier_vote_weights_are_progressive() {
        assert_eq!(ConsciousnessTier::Observer.vote_weight_bp(), 0);
        assert!(ConsciousnessTier::Participant.vote_weight_bp() > 0);
        assert!(
            ConsciousnessTier::Citizen.vote_weight_bp()
                >= ConsciousnessTier::Participant.vote_weight_bp()
        );
        assert!(
            ConsciousnessTier::Steward.vote_weight_bp()
                >= ConsciousnessTier::Citizen.vote_weight_bp()
        );
        assert!(
            ConsciousnessTier::Guardian.vote_weight_bp()
                >= ConsciousnessTier::Steward.vote_weight_bp()
        );
    }

    #[test]
    fn tier_ordering() {
        assert!(ConsciousnessTier::Observer < ConsciousnessTier::Participant);
        assert!(ConsciousnessTier::Participant < ConsciousnessTier::Citizen);
        assert!(ConsciousnessTier::Citizen < ConsciousnessTier::Steward);
        assert!(ConsciousnessTier::Steward < ConsciousnessTier::Guardian);
    }

    // -- Profile → Tier integration --

    #[test]
    fn profile_tier_derivation() {
        let observer = ConsciousnessProfile::zero();
        assert_eq!(observer.tier(), ConsciousnessTier::Observer);

        let participant = ConsciousnessProfile {
            identity: 0.3,
            reputation: 0.3,
            community: 0.3,
            engagement: 0.3,
        };
        assert_eq!(participant.tier(), ConsciousnessTier::Participant);

        let citizen = ConsciousnessProfile {
            identity: 0.5,
            reputation: 0.5,
            community: 0.4,
            engagement: 0.2,
        };
        // 0.5*0.25 + 0.5*0.25 + 0.4*0.30 + 0.2*0.20 = 0.125+0.125+0.12+0.04 = 0.41
        assert_eq!(citizen.tier(), ConsciousnessTier::Citizen);

        let steward = ConsciousnessProfile {
            identity: 0.75,
            reputation: 0.7,
            community: 0.6,
            engagement: 0.5,
        };
        // 0.75*0.25 + 0.7*0.25 + 0.6*0.30 + 0.5*0.20 = 0.1875+0.175+0.18+0.10 = 0.6425
        assert_eq!(steward.tier(), ConsciousnessTier::Steward);

        let guardian = ConsciousnessProfile {
            identity: 1.0,
            reputation: 0.9,
            community: 0.8,
            engagement: 0.7,
        };
        // 1.0*0.25 + 0.9*0.25 + 0.8*0.30 + 0.7*0.20 = 0.25+0.225+0.24+0.14 = 0.855
        assert_eq!(guardian.tier(), ConsciousnessTier::Guardian);
    }

    // -- evaluate_governance --

    #[test]
    fn evaluate_observer_rejected_for_basic() {
        let profile = ConsciousnessProfile::zero();
        let result = evaluate_governance(
            &fresh_credential(profile.clone()),
            &requirement_for_basic(),
            NOW,
        );
        assert!(!result.eligible);
        assert_eq!(result.weight_bp, 0);
        assert_eq!(result.tier, ConsciousnessTier::Observer);
        assert!(!result.reasons.is_empty());
    }

    #[test]
    fn evaluate_participant_passes_basic() {
        let profile = ConsciousnessProfile {
            identity: 0.3,
            reputation: 0.3,
            community: 0.3,
            engagement: 0.3,
        };
        let result = evaluate_governance(
            &fresh_credential(profile.clone()),
            &requirement_for_basic(),
            NOW,
        );
        assert!(result.eligible);
        assert_eq!(result.weight_bp, 5000);
        assert_eq!(result.tier, ConsciousnessTier::Participant);
        assert!(result.reasons.is_empty());
    }

    #[test]
    fn evaluate_participant_rejected_for_voting() {
        let profile = ConsciousnessProfile {
            identity: 0.3,
            reputation: 0.3,
            community: 0.3,
            engagement: 0.3,
        };
        let result = evaluate_governance(
            &fresh_credential(profile.clone()),
            &requirement_for_voting(),
            NOW,
        );
        assert!(!result.eligible);
        assert!(!result.reasons.is_empty());
    }

    #[test]
    fn evaluate_citizen_passes_voting() {
        let profile = ConsciousnessProfile {
            identity: 0.5,
            reputation: 0.5,
            community: 0.4,
            engagement: 0.2,
        };
        let result = evaluate_governance(
            &fresh_credential(profile.clone()),
            &requirement_for_voting(),
            NOW,
        );
        assert!(result.eligible);
        assert_eq!(result.weight_bp, 7500); // Citizen weight
        assert_eq!(result.tier, ConsciousnessTier::Citizen);
    }

    #[test]
    fn evaluate_proposal_requires_identity() {
        // High combined score but zero identity
        let profile = ConsciousnessProfile {
            identity: 0.0,
            reputation: 0.5,
            community: 0.5,
            engagement: 0.5,
        };
        let result = evaluate_governance(
            &fresh_credential(profile.clone()),
            &requirement_for_proposal(),
            NOW,
        );
        assert!(!result.eligible);
        assert!(result.reasons.iter().any(|r| r.contains("Identity")));
    }

    #[test]
    fn evaluate_constitutional_requires_all() {
        // Steward tier but low identity
        let profile = ConsciousnessProfile {
            identity: 0.3,
            reputation: 0.8,
            community: 0.8,
            engagement: 0.8,
        };
        let result = evaluate_governance(
            &fresh_credential(profile.clone()),
            &requirement_for_constitutional(),
            NOW,
        );
        assert!(!result.eligible);
        assert!(result.reasons.iter().any(|r| r.contains("Identity")));
    }

    #[test]
    fn evaluate_constitutional_requires_community() {
        // Steward tier, good identity, but low community
        let profile = ConsciousnessProfile {
            identity: 0.75,
            reputation: 0.7,
            community: 0.1,
            engagement: 0.8,
        };
        // combined = 0.1875+0.175+0.03+0.16 = 0.5525 → Citizen (not Steward!)
        let result = evaluate_governance(
            &fresh_credential(profile.clone()),
            &requirement_for_constitutional(),
            NOW,
        );
        assert!(!result.eligible);
        // Should fail on tier AND community
        assert!(result
            .reasons
            .iter()
            .any(|r| r.contains("Community") || r.contains("Tier")));
    }

    #[test]
    fn evaluate_guardian_passes_constitutional() {
        let profile = ConsciousnessProfile {
            identity: 1.0,
            reputation: 0.9,
            community: 0.8,
            engagement: 0.7,
        };
        let result = evaluate_governance(
            &fresh_credential(profile.clone()),
            &requirement_for_constitutional(),
            NOW,
        );
        assert!(result.eligible);
        assert_eq!(result.weight_bp, 10000);
        assert_eq!(result.tier, ConsciousnessTier::Guardian);
    }

    #[test]
    fn evaluate_clamps_out_of_range_values() {
        let profile = ConsciousnessProfile {
            identity: 2.0,
            reputation: 2.0,
            community: 2.0,
            engagement: 2.0,
        };
        let result = evaluate_governance(
            &fresh_credential(profile.clone()),
            &requirement_for_constitutional(),
            NOW,
        );
        assert!(result.eligible);
        // Clamped to 1.0 each → combined = 1.0 → Guardian
        assert_eq!(result.tier, ConsciousnessTier::Guardian);
        assert_eq!(result.profile.identity, 1.0);
    }

    #[test]
    fn evaluate_multiple_failure_reasons() {
        let profile = ConsciousnessProfile::zero();
        let result = evaluate_governance(
            &fresh_credential(profile.clone()),
            &requirement_for_constitutional(),
            NOW,
        );
        assert!(!result.eligible);
        // Should fail on tier, identity, and community
        assert!(
            result.reasons.len() >= 3,
            "Expected 3+ reasons, got: {:?}",
            result.reasons
        );
    }

    // -- Progressive weight composition --

    #[test]
    fn progressive_weight_composition_with_role() {
        // Simulates hearth-decisions: final_weight = role_bp * consciousness_bp / 10000
        let citizen_bp: u64 = ConsciousnessTier::Citizen.vote_weight_bp() as u64;
        let adult_role_bp: u64 = 10000; // Adult
        let youth_role_bp: u64 = 5000; // Youth

        let adult_final = (adult_role_bp * citizen_bp / 10000) as u32;
        let youth_final = (youth_role_bp * citizen_bp / 10000) as u32;

        assert_eq!(adult_final, 7500);
        assert_eq!(youth_final, 3750);
    }

    // -- ConsciousnessCredential --

    #[test]
    fn credential_not_expired_when_fresh() {
        let cred = ConsciousnessCredential {
            did: "did:mycelix:test".into(),
            profile: ConsciousnessProfile::zero(),
            tier: ConsciousnessTier::Observer,
            issued_at: 1_000_000,
            expires_at: 1_000_000 + ConsciousnessCredential::DEFAULT_TTL_US,
            issuer: "did:mycelix:issuer".into(),
            trajectory_commitment: None,
            extensions: std::collections::HashMap::new(),
        };
        assert!(!cred.is_expired(1_000_000));
        assert!(!cred.is_expired(1_000_000 + ConsciousnessCredential::DEFAULT_TTL_US - 1));
    }

    #[test]
    fn credential_expired_at_boundary() {
        let cred = ConsciousnessCredential {
            did: "did:mycelix:test".into(),
            profile: ConsciousnessProfile::zero(),
            tier: ConsciousnessTier::Observer,
            issued_at: 1_000_000,
            expires_at: 1_000_000 + ConsciousnessCredential::DEFAULT_TTL_US,
            issuer: "did:mycelix:issuer".into(),
            trajectory_commitment: None,
            extensions: std::collections::HashMap::new(),
        };
        assert!(cred.is_expired(cred.expires_at));
        assert!(cred.is_expired(cred.expires_at + 1));
    }

    #[test]
    fn default_ttl_is_24_hours() {
        assert_eq!(ConsciousnessCredential::DEFAULT_TTL_US, 86_400_000_000);
    }

    // -- Serde roundtrips --

    #[test]
    fn profile_serde_roundtrip() {
        let p = ConsciousnessProfile {
            identity: 0.75,
            reputation: 0.5,
            community: 0.6,
            engagement: 0.3,
        };
        let json = serde_json::to_string(&p).unwrap();
        let p2: ConsciousnessProfile = serde_json::from_str(&json).unwrap();
        assert_eq!(p, p2);
    }

    #[test]
    fn tier_serde_roundtrip() {
        let tiers = [
            ConsciousnessTier::Observer,
            ConsciousnessTier::Participant,
            ConsciousnessTier::Citizen,
            ConsciousnessTier::Steward,
            ConsciousnessTier::Guardian,
        ];
        for tier in &tiers {
            let json = serde_json::to_string(tier).unwrap();
            let t2: ConsciousnessTier = serde_json::from_str(&json).unwrap();
            assert_eq!(*tier, t2);
        }
    }

    #[test]
    fn credential_serde_roundtrip() {
        let cred = ConsciousnessCredential {
            did: "did:mycelix:abc123".into(),
            profile: ConsciousnessProfile {
                identity: 0.5,
                reputation: 0.6,
                community: 0.7,
                engagement: 0.4,
            },
            tier: ConsciousnessTier::Steward,
            issued_at: 1_700_000_000_000_000,
            expires_at: 1_700_000_000_000_000 + ConsciousnessCredential::DEFAULT_TTL_US,
            issuer: "did:mycelix:issuer".into(),
            trajectory_commitment: None,
            extensions: std::collections::HashMap::new(),
        };
        let json = serde_json::to_string(&cred).unwrap();
        let c2: ConsciousnessCredential = serde_json::from_str(&json).unwrap();
        assert_eq!(c2.did, "did:mycelix:abc123");
        assert_eq!(c2.tier, ConsciousnessTier::Steward);
        assert_eq!(c2.profile.identity, 0.5);
    }

    #[test]
    fn governance_requirement_serde_roundtrip() {
        let req = requirement_for_constitutional();
        let json = serde_json::to_string(&req).unwrap();
        let r2: GovernanceRequirement = serde_json::from_str(&json).unwrap();
        assert_eq!(r2.min_tier, ConsciousnessTier::Steward);
        assert_eq!(r2.min_identity, Some(0.5));
        assert_eq!(r2.min_community, Some(0.3));
    }

    #[test]
    fn governance_eligibility_serde_roundtrip() {
        let profile = ConsciousnessProfile {
            identity: 0.5,
            reputation: 0.5,
            community: 0.4,
            engagement: 0.2,
        };
        let eligibility = evaluate_governance(
            &fresh_credential(profile.clone()),
            &requirement_for_voting(),
            NOW,
        );
        let json = serde_json::to_string(&eligibility).unwrap();
        let e2: GovernanceEligibility = serde_json::from_str(&json).unwrap();
        assert_eq!(e2.eligible, eligibility.eligible);
        assert_eq!(e2.weight_bp, eligibility.weight_bp);
        assert_eq!(e2.tier, eligibility.tier);
    }

    // -- Edge cases --

    #[test]
    fn negative_values_clamped_to_zero() {
        let profile = ConsciousnessProfile {
            identity: -0.5,
            reputation: -1.0,
            community: -0.1,
            engagement: -999.0,
        };
        let result = evaluate_governance(
            &fresh_credential(profile.clone()),
            &requirement_for_basic(),
            NOW,
        );
        assert!(!result.eligible);
        assert_eq!(result.profile.identity, 0.0);
        assert_eq!(result.profile.reputation, 0.0);
        assert_eq!(result.profile.community, 0.0);
        assert_eq!(result.profile.engagement, 0.0);
    }

    #[test]
    fn exact_threshold_boundary_participant() {
        // combined = exactly 0.3
        let profile = ConsciousnessProfile {
            identity: 0.3,
            reputation: 0.3,
            community: 0.3,
            engagement: 0.3,
        };
        assert_eq!(profile.tier(), ConsciousnessTier::Participant);
        let result = evaluate_governance(
            &fresh_credential(profile.clone()),
            &requirement_for_basic(),
            NOW,
        );
        assert!(result.eligible);
    }

    #[test]
    fn just_below_participant_threshold() {
        // combined just under 0.3
        let profile = ConsciousnessProfile {
            identity: 0.29,
            reputation: 0.29,
            community: 0.29,
            engagement: 0.29,
        };
        // 0.29 * (0.25+0.25+0.30+0.20) = 0.29 * 1.0 = 0.29
        assert_eq!(profile.tier(), ConsciousnessTier::Observer);
        let result = evaluate_governance(
            &fresh_credential(profile.clone()),
            &requirement_for_basic(),
            NOW,
        );
        assert!(!result.eligible);
    }

    // -- Requirement presets --

    #[test]
    fn requirement_presets_are_ordered() {
        let basic = requirement_for_basic();
        let proposal = requirement_for_proposal();
        let voting = requirement_for_voting();
        let constitutional = requirement_for_constitutional();

        assert!(basic.min_tier <= proposal.min_tier);
        assert!(proposal.min_tier <= voting.min_tier);
        assert!(voting.min_tier <= constitutional.min_tier);
    }

    #[test]
    fn requirement_identity_thresholds_ordered() {
        let proposal_id = requirement_for_proposal().min_identity.unwrap_or(0.0);
        let voting_id = requirement_for_voting().min_identity.unwrap_or(0.0);
        let const_id = requirement_for_constitutional().min_identity.unwrap_or(0.0);

        assert!(proposal_id <= voting_id || proposal_id <= const_id);
        assert!(voting_id <= const_id);
    }

    // -- Credential expiry edge cases --

    #[test]
    fn credential_not_expired_one_microsecond_before() {
        let cred = ConsciousnessCredential {
            did: "did:mycelix:test".into(),
            profile: ConsciousnessProfile::zero(),
            tier: ConsciousnessTier::Observer,
            issued_at: 1_000_000,
            expires_at: 2_000_000,
            issuer: "did:mycelix:issuer".into(),
            trajectory_commitment: None,
            extensions: std::collections::HashMap::new(),
        };
        assert!(!cred.is_expired(1_999_999));
    }

    #[test]
    fn credential_expired_exactly_at_boundary() {
        let cred = ConsciousnessCredential {
            did: "did:mycelix:test".into(),
            profile: ConsciousnessProfile::zero(),
            tier: ConsciousnessTier::Observer,
            issued_at: 1_000_000,
            expires_at: 2_000_000,
            issuer: "did:mycelix:issuer".into(),
            trajectory_commitment: None,
            extensions: std::collections::HashMap::new(),
        };
        // >= means expired at exact boundary
        assert!(cred.is_expired(2_000_000));
    }

    #[test]
    fn credential_expired_one_microsecond_after() {
        let cred = ConsciousnessCredential {
            did: "did:mycelix:test".into(),
            profile: ConsciousnessProfile::zero(),
            tier: ConsciousnessTier::Observer,
            issued_at: 1_000_000,
            expires_at: 2_000_000,
            issuer: "did:mycelix:issuer".into(),
            trajectory_commitment: None,
            extensions: std::collections::HashMap::new(),
        };
        assert!(cred.is_expired(2_000_001));
    }

    #[test]
    fn credential_zero_ttl_always_expired() {
        let cred = ConsciousnessCredential {
            did: "did:mycelix:test".into(),
            profile: ConsciousnessProfile::zero(),
            tier: ConsciousnessTier::Observer,
            issued_at: 1_000_000,
            expires_at: 1_000_000, // zero TTL
            issuer: "did:mycelix:issuer".into(),
            trajectory_commitment: None,
            extensions: std::collections::HashMap::new(),
        };
        assert!(cred.is_expired(1_000_000));
    }

    #[test]
    fn credential_u64_max_expires_at_not_expired() {
        let cred = ConsciousnessCredential {
            did: "did:mycelix:test".into(),
            profile: ConsciousnessProfile::zero(),
            tier: ConsciousnessTier::Observer,
            issued_at: 0,
            expires_at: u64::MAX,
            issuer: "did:mycelix:issuer".into(),
            trajectory_commitment: None,
            extensions: std::collections::HashMap::new(),
        };
        // Any reasonable timestamp is before u64::MAX
        assert!(!cred.is_expired(1_700_000_000_000_000));
    }

    #[test]
    fn credential_u64_max_expires_at_expired_at_max() {
        let cred = ConsciousnessCredential {
            did: "did:mycelix:test".into(),
            profile: ConsciousnessProfile::zero(),
            tier: ConsciousnessTier::Observer,
            issued_at: 0,
            expires_at: u64::MAX,
            issuer: "did:mycelix:issuer".into(),
            trajectory_commitment: None,
            extensions: std::collections::HashMap::new(),
        };
        assert!(cred.is_expired(u64::MAX));
    }

    // -- evaluate_governance expiry integration --

    #[test]
    fn evaluate_governance_rejects_expired_credential_past_grace() {
        let profile = ConsciousnessProfile {
            identity: 1.0,
            reputation: 1.0,
            community: 1.0,
            engagement: 1.0,
        };
        let mut cred = fresh_credential(profile);
        // Expired well past the 30-min grace period
        cred.expires_at = NOW - GRACE_PERIOD_US - 1;
        let result = evaluate_governance(&cred, &requirement_for_basic(), NOW);
        assert!(!result.eligible);
        assert!(result.reasons[0].contains("expired"));
    }

    #[test]
    fn evaluate_governance_rejects_expired_credential_for_voting() {
        let profile = ConsciousnessProfile {
            identity: 1.0,
            reputation: 1.0,
            community: 1.0,
            engagement: 1.0,
        };
        let mut cred = fresh_credential(profile);
        cred.expires_at = NOW - 1; // recently expired
                                   // Grace period does NOT apply to voting-tier operations
        let result = evaluate_governance(&cred, &requirement_for_voting(), NOW);
        assert!(!result.eligible);
        assert!(result.reasons[0].contains("expired"));
    }

    #[test]
    fn evaluate_governance_accepts_fresh_credential() {
        let profile = ConsciousnessProfile {
            identity: 1.0,
            reputation: 1.0,
            community: 1.0,
            engagement: 1.0,
        };
        let cred = fresh_credential(profile);
        let result = evaluate_governance(&cred, &requirement_for_constitutional(), NOW);
        assert!(result.eligible);
    }

    #[test]
    fn evaluate_governance_rejects_at_expiry_boundary_for_voting() {
        let profile = ConsciousnessProfile {
            identity: 1.0,
            reputation: 1.0,
            community: 1.0,
            engagement: 1.0,
        };
        let mut cred = fresh_credential(profile);
        cred.expires_at = NOW; // expires exactly at NOW
                               // Grace period does NOT apply to voting-tier operations
        let result = evaluate_governance(&cred, &requirement_for_voting(), NOW);
        assert!(!result.eligible);
        assert!(result.reasons[0].contains("expired"));
    }

    // -- Progressive weight composition edge cases --

    #[test]
    fn weight_composition_no_overflow_at_max() {
        // (10000 * 10000) / 10000 = 10000 — no overflow in u64 intermediate
        let role_bp: u64 = 10000;
        let consciousness_bp: u64 = 10000;
        let result = (role_bp * consciousness_bp / 10000) as u32;
        assert_eq!(result, 10000);
    }

    #[test]
    fn weight_composition_observer_always_zero() {
        let observer_bp = ConsciousnessTier::Observer.vote_weight_bp() as u64;
        for role_bp in [0u64, 5000, 10000, u32::MAX as u64] {
            let result = (role_bp * observer_bp / 10000) as u32;
            assert_eq!(result, 0, "Observer * role {} should be 0", role_bp);
        }
    }

    #[test]
    fn weight_composition_zero_role_always_zero() {
        for tier in [
            ConsciousnessTier::Participant,
            ConsciousnessTier::Citizen,
            ConsciousnessTier::Steward,
            ConsciousnessTier::Guardian,
        ] {
            let tier_bp = tier.vote_weight_bp() as u64;
            let result = (0u64 * tier_bp / 10000) as u32;
            assert_eq!(result, 0, "Role 0 * {:?} should be 0", tier);
        }
    }

    #[test]
    fn weight_composition_all_tiers_all_standard_roles() {
        // Standard Mycelix role weights: Youth=5000, Adult=10000, Elder=10000
        let roles = [(5000u64, "Youth"), (10000u64, "Adult"), (10000u64, "Elder")];
        let tiers = [
            (ConsciousnessTier::Observer, 0u32),
            (ConsciousnessTier::Participant, 5000),
            (ConsciousnessTier::Citizen, 7500),
            (ConsciousnessTier::Steward, 10000),
            (ConsciousnessTier::Guardian, 10000),
        ];
        for (role_bp, role_name) in &roles {
            for (tier, tier_bp) in &tiers {
                let expected = (*role_bp * *tier_bp as u64 / 10000) as u32;
                let actual = (*role_bp * tier.vote_weight_bp() as u64 / 10000) as u32;
                assert_eq!(
                    actual, expected,
                    "{} ({}) x {:?} ({}): expected {}, got {}",
                    role_name, role_bp, tier, tier_bp, expected, actual
                );
            }
        }
    }

    // -- Tier from_score edge cases --

    #[test]
    fn tier_from_score_negative_is_observer() {
        assert_eq!(
            ConsciousnessTier::from_score(-1.0),
            ConsciousnessTier::Observer
        );
        assert_eq!(
            ConsciousnessTier::from_score(-0.001),
            ConsciousnessTier::Observer
        );
    }

    #[test]
    fn tier_from_score_above_one_is_guardian() {
        assert_eq!(
            ConsciousnessTier::from_score(1.5),
            ConsciousnessTier::Guardian
        );
        assert_eq!(
            ConsciousnessTier::from_score(100.0),
            ConsciousnessTier::Guardian
        );
    }

    // -- Grace period --

    #[test]
    fn grace_period_allows_basic_operations() {
        let profile = ConsciousnessProfile {
            identity: 0.3,
            reputation: 0.3,
            community: 0.3,
            engagement: 0.3,
        };
        let mut cred = fresh_credential(profile);
        // Expired 10 minutes ago (within 30-min grace)
        cred.expires_at = NOW - 600_000_000;
        let result = evaluate_governance(&cred, &requirement_for_basic(), NOW);
        assert!(result.eligible);
        assert!(result.reasons.iter().any(|r| r.contains("grace period")));
    }

    #[test]
    fn grace_period_rejects_voting_operations() {
        let profile = ConsciousnessProfile {
            identity: 0.5,
            reputation: 0.5,
            community: 0.4,
            engagement: 0.2,
        };
        let mut cred = fresh_credential(profile);
        cred.expires_at = NOW - 600_000_000; // within grace
        let result = evaluate_governance(&cred, &requirement_for_voting(), NOW);
        assert!(!result.eligible);
        assert!(result.reasons[0].contains("expired"));
    }

    #[test]
    fn grace_period_expired_past_window() {
        let profile = ConsciousnessProfile {
            identity: 0.3,
            reputation: 0.3,
            community: 0.3,
            engagement: 0.3,
        };
        let mut cred = fresh_credential(profile);
        // Expired 2 hours ago (past 30-min grace)
        cred.expires_at = NOW - 7_200_000_000;
        let result = evaluate_governance(&cred, &requirement_for_basic(), NOW);
        assert!(!result.eligible);
    }

    // -- should_audit --

    #[test]
    fn should_audit_always_logs_rejections() {
        assert!(should_audit(&requirement_for_basic(), false, &[0u8], "any"));
        assert!(should_audit(
            &requirement_for_basic(),
            false,
            &[255u8],
            "any"
        ));
    }

    #[test]
    fn should_audit_always_logs_constitutional() {
        assert!(should_audit(
            &requirement_for_constitutional(),
            true,
            &[0u8],
            "amend"
        ));
        assert!(should_audit(
            &requirement_for_constitutional(),
            true,
            &[255u8],
            "amend"
        ));
    }

    #[test]
    fn should_audit_always_logs_voting() {
        assert!(should_audit(
            &requirement_for_voting(),
            true,
            &[0u8],
            "vote"
        ));
        assert!(should_audit(
            &requirement_for_voting(),
            true,
            &[255u8],
            "vote"
        ));
    }

    #[test]
    fn should_audit_samples_basic_approvals() {
        let z = ""; // zero salt
        assert!(should_audit(&requirement_for_basic(), true, &[0u8], z));
        assert!(should_audit(&requirement_for_basic(), true, &[25u8], z));
        assert!(!should_audit(&requirement_for_basic(), true, &[26u8], z));
        assert!(!should_audit(&requirement_for_basic(), true, &[255u8], z));
    }

    #[test]
    fn should_audit_salt_varies_by_action() {
        let agent = &[30u8];
        assert!(!should_audit(&requirement_for_basic(), true, agent, ""));
        // "qq" salt = 226. 30 + 226 = 256 → 0 mod 256 → sampled
        assert!(should_audit(&requirement_for_basic(), true, agent, "qq"));
    }

    // -- needs_refresh --

    #[test]
    fn needs_refresh_within_window() {
        let profile = ConsciousnessProfile {
            identity: 0.5,
            reputation: 0.5,
            community: 0.5,
            engagement: 0.5,
        };
        let mut cred = fresh_credential(profile);
        // Expires in 1 hour (within 2-hour window)
        cred.expires_at = NOW + 3_600_000_000;
        assert!(needs_refresh(&cred, NOW));
    }

    #[test]
    fn needs_refresh_not_within_window() {
        let profile = ConsciousnessProfile {
            identity: 0.5,
            reputation: 0.5,
            community: 0.5,
            engagement: 0.5,
        };
        let cred = fresh_credential(profile);
        // Expires in 24 hours (outside 2-hour window)
        assert!(!needs_refresh(&cred, NOW));
    }

    #[test]
    fn needs_refresh_expired_credential() {
        let profile = ConsciousnessProfile::zero();
        let mut cred = fresh_credential(profile);
        cred.expires_at = NOW - 1;
        assert!(!needs_refresh(&cred, NOW));
    }

    #[test]
    fn needs_refresh_exactly_at_boundary() {
        // Credential expires exactly 2 hours from now — just inside the window
        let profile = ConsciousnessProfile {
            identity: 0.5,
            reputation: 0.5,
            community: 0.5,
            engagement: 0.5,
        };
        let mut cred = fresh_credential(profile.clone());
        // Exactly at REFRESH_WINDOW_US boundary (2 hours = 7_200_000_000 us)
        cred.expires_at = NOW + REFRESH_WINDOW_US;
        // At exactly the boundary, expires_at - now == REFRESH_WINDOW_US,
        // so the condition (expires_at - now < REFRESH_WINDOW_US) is false
        assert!(!needs_refresh(&cred, NOW));

        // One microsecond inside the window
        cred.expires_at = NOW + REFRESH_WINDOW_US - 1;
        assert!(needs_refresh(&cred, NOW));
    }

    #[test]
    fn needs_refresh_just_expired_not_refreshable() {
        // Credential expired 1 microsecond ago — should NOT trigger refresh
        let profile = ConsciousnessProfile {
            identity: 0.8,
            reputation: 0.7,
            community: 0.6,
            engagement: 0.5,
        };
        let mut cred = fresh_credential(profile);
        cred.expires_at = NOW; // expires exactly at NOW
        assert!(!needs_refresh(&cred, NOW));
    }

    #[test]
    fn needs_refresh_far_future_not_refreshable() {
        // Credential expires 23 hours from now — well outside 2-hour window
        let profile = ConsciousnessProfile {
            identity: 0.5,
            reputation: 0.5,
            community: 0.5,
            engagement: 0.5,
        };
        let mut cred = fresh_credential(profile);
        cred.expires_at = NOW + 82_800_000_000; // 23 hours
        assert!(!needs_refresh(&cred, NOW));
    }

    #[test]
    fn refresh_on_gate_check_flow() {
        // Simulate the gate_consciousness flow: credential nearing expiry
        // should still pass the gate check (it's valid) but needs_refresh
        // returns true so refresh would be triggered.
        let profile = ConsciousnessProfile {
            identity: 0.8,
            reputation: 0.7,
            community: 0.6,
            engagement: 0.5,
        };
        let mut cred = fresh_credential(profile);
        // Expires in 30 minutes — within 2-hour refresh window
        cred.expires_at = NOW + 1_800_000_000;

        // Step 1: Gate check — credential is still valid
        assert!(!cred.is_expired(NOW), "credential should NOT be expired");

        // Step 2: Evaluate governance — should be eligible
        let requirement = GovernanceRequirement {
            min_tier: ConsciousnessTier::Participant,
            min_identity: None,
            min_community: None,
        };
        let eligibility = evaluate_governance(&cred, &requirement, NOW);
        assert!(
            eligibility.eligible,
            "nearing-expiry credential should still pass gate"
        );

        // Step 3: needs_refresh should be true — triggering background refresh
        assert!(
            needs_refresh(&cred, NOW),
            "credential nearing expiry should trigger refresh"
        );
    }

    #[test]
    fn refresh_on_gate_check_fresh_credential_no_refresh() {
        // Fresh credential: gate passes and NO refresh triggered
        let profile = ConsciousnessProfile {
            identity: 0.8,
            reputation: 0.7,
            community: 0.6,
            engagement: 0.5,
        };
        let cred = fresh_credential(profile); // expires in 24 hours

        // Gate check passes
        let requirement = GovernanceRequirement {
            min_tier: ConsciousnessTier::Participant,
            min_identity: None,
            min_community: None,
        };
        let eligibility = evaluate_governance(&cred, &requirement, NOW);
        assert!(eligibility.eligible);

        // No refresh needed — credential is fresh
        assert!(
            !needs_refresh(&cred, NOW),
            "fresh credential should NOT trigger refresh"
        );
    }

    #[test]
    fn refresh_on_gate_check_expired_credential_no_refresh() {
        // Expired credential past grace period: gate FAILS and no refresh triggered
        // (refresh is pointless for already-expired credentials)
        let profile = ConsciousnessProfile {
            identity: 0.8,
            reputation: 0.7,
            community: 0.6,
            engagement: 0.5,
        };
        let mut cred = fresh_credential(profile);
        // Expired well past the 30-minute grace period
        cred.expires_at = NOW - GRACE_PERIOD_US - 1;

        // Gate check fails (expired past grace)
        let requirement = GovernanceRequirement {
            min_tier: ConsciousnessTier::Participant,
            min_identity: None,
            min_community: None,
        };
        let eligibility = evaluate_governance(&cred, &requirement, NOW);
        assert!(!eligibility.eligible, "expired credential should fail gate");

        // No refresh for expired credentials
        assert!(
            !needs_refresh(&cred, NOW),
            "expired credential should NOT trigger refresh"
        );
    }

    // -- GateAuditInput with correlation_id --

    #[test]
    fn gate_audit_input_serde_with_correlation_id() {
        let audit = GateAuditInput {
            action_name: "test".into(),
            zome_name: "test_zome".into(),
            eligible: true,
            actual_tier: "Citizen".into(),
            required_tier: "Participant".into(),
            weight_bp: 7500,
            correlation_id: Some("abcdef01:1700000000000000".into()),
            credential_source: None,
        };
        let json = serde_json::to_string(&audit).unwrap();
        let a2: GateAuditInput = serde_json::from_str(&json).unwrap();
        assert_eq!(a2.correlation_id, Some("abcdef01:1700000000000000".into()));
    }

    #[test]
    fn gate_audit_input_serde_without_correlation_id() {
        // Backward compat: old audit inputs without correlation_id or credential_source
        let json = r#"{"action_name":"test","zome_name":"z","eligible":true,"actual_tier":"Citizen","required_tier":"Participant","weight_bp":7500}"#;
        let audit: GateAuditInput = serde_json::from_str(json).unwrap();
        assert_eq!(audit.correlation_id, None);
        assert_eq!(audit.credential_source, None);
    }

    #[test]
    fn gate_audit_input_serde_with_credential_source() {
        let audit = GateAuditInput {
            action_name: "create_shelter".into(),
            zome_name: "civic_bridge".into(),
            eligible: true,
            actual_tier: "Citizen".into(),
            required_tier: "Participant".into(),
            weight_bp: 7500,
            correlation_id: None,
            credential_source: Some("identity_bridge_fresh".into()),
        };
        let json = serde_json::to_string(&audit).unwrap();
        assert!(json.contains("credential_source"));
        assert!(json.contains("identity_bridge_fresh"));
        let a2: GateAuditInput = serde_json::from_str(&json).unwrap();
        assert_eq!(a2.credential_source, Some("identity_bridge_fresh".into()));
    }

    // ════════════════════════════════════════════════════════════════════════
    // MINIMAL VIABLE BRIDGE: End-to-end tests
    // ════════════════════════════════════════════════════════════════════════

    #[test]
    fn mvb_profile_from_unified_consciousness() {
        let profile = ConsciousnessProfile::from_unified_consciousness(
            0.65, // C_unified from Symthaea
            0.80, // identity (verified MFA)
            0.50, // reputation (moderate history)
            0.40, // community (some attestations)
        );
        assert_eq!(profile.engagement, 0.65);
        assert_eq!(profile.identity, 0.80);
        assert_eq!(profile.reputation, 0.50);
        assert_eq!(profile.community, 0.40);
        // combined = 0.80*0.25 + 0.50*0.25 + 0.40*0.30 + 0.65*0.20
        //         = 0.20 + 0.125 + 0.12 + 0.13 = 0.575
        let expected = 0.80 * 0.25 + 0.50 * 0.25 + 0.40 * 0.30 + 0.65 * 0.20;
        assert!((profile.combined_score() - expected).abs() < 1e-10);
    }

    #[test]
    fn mvb_profile_clamps_out_of_range() {
        let profile = ConsciousnessProfile::from_unified_consciousness(1.5, -0.2, 0.5, 0.5);
        assert_eq!(profile.engagement, 1.0);
        assert_eq!(profile.identity, 0.0);
    }

    // -- Enriched Symthaea bridge tests --

    #[test]
    fn symthaea_bridge_composite_engagement() {
        // phi=0.8, meta=0.6, coherence=0.5, care=0.7
        // engagement = 0.35*0.8 + 0.25*0.6 + 0.20*0.5 + 0.20*0.7
        //            = 0.28 + 0.15 + 0.10 + 0.14 = 0.67
        let profile = ConsciousnessProfile::from_symthaea(
            0.8, 0.6, 0.5, 0.7, // Symthaea signals
            0.75, 0.50, 0.40, // identity/reputation/community
        );
        let expected_engagement = 0.35 * 0.8 + 0.25 * 0.6 + 0.20 * 0.5 + 0.20 * 0.7;
        assert!((profile.engagement - expected_engagement).abs() < 1e-10);
        assert_eq!(profile.identity, 0.75);
        assert_eq!(profile.reputation, 0.50);
        assert_eq!(profile.community, 0.40);
    }

    #[test]
    fn symthaea_bridge_all_max() {
        let profile = ConsciousnessProfile::from_symthaea(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0);
        assert_eq!(profile.engagement, 1.0);
        assert_eq!(profile.combined_score(), 1.0);
        assert_eq!(profile.tier(), ConsciousnessTier::Guardian);
    }

    #[test]
    fn symthaea_bridge_all_zero() {
        let profile = ConsciousnessProfile::from_symthaea(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
        assert_eq!(profile.engagement, 0.0);
        assert_eq!(profile.combined_score(), 0.0);
        assert_eq!(profile.tier(), ConsciousnessTier::Observer);
    }

    #[test]
    fn symthaea_bridge_clamps_inputs() {
        let profile = ConsciousnessProfile::from_symthaea(
            1.5, -0.3, 2.0, -1.0, // out-of-range Symthaea signals
            0.5, 0.5, 0.5,
        );
        // After clamping: phi=1.0, meta=0.0, coh=1.0, care=0.0
        // engagement = 0.35*1.0 + 0.25*0.0 + 0.20*1.0 + 0.20*0.0 = 0.55
        let expected = 0.35 + 0.20;
        assert!((profile.engagement - expected).abs() < 1e-10);
    }

    #[test]
    fn symthaea_credential_from_enriched_bridge() {
        let now = 1_000_000_000_000_u64;
        let cred = ConsciousnessCredential::from_symthaea(
            "did:mycelix:enriched".into(),
            0.7,
            0.6,
            0.5,
            0.8, // phi, meta, coherence, care
            0.80,
            0.50,
            0.40, // identity, reputation, community
            "did:mycelix:bridge".into(),
            now,
        );
        assert_eq!(cred.did, "did:mycelix:enriched");
        // engagement = 0.35*0.7 + 0.25*0.6 + 0.20*0.5 + 0.20*0.8 = 0.245+0.15+0.10+0.16 = 0.655
        let expected_engagement = 0.35 * 0.7 + 0.25 * 0.6 + 0.20 * 0.5 + 0.20 * 0.8;
        assert!((cred.profile.engagement - expected_engagement).abs() < 1e-10);
        assert!(cred.tier >= ConsciousnessTier::Citizen);
    }

    #[test]
    fn mvb_credential_from_unified_consciousness() {
        let cred = ConsciousnessCredential::from_unified_consciousness(
            "did:mycelix:agent123".into(),
            0.65, // C_unified
            0.80,
            0.50,
            0.40,
            "did:mycelix:bridge".into(),
            NOW,
        );
        assert_eq!(cred.did, "did:mycelix:agent123");
        assert_eq!(cred.profile.engagement, 0.65);
        assert_eq!(cred.issued_at, NOW);
        assert_eq!(
            cred.expires_at,
            NOW + ConsciousnessCredential::DEFAULT_TTL_US
        );
        assert!(!cred.is_expired(NOW));
        // Tier should be Citizen (combined ≈ 0.575 → >= 0.4)
        assert!(cred.tier >= ConsciousnessTier::Citizen);
    }

    #[test]
    fn mvb_end_to_end_high_consciousness_proposal_eligible() {
        // Scenario: Agent with high C_unified submits a proposal
        // Expected: Eligible (Citizen tier, proposal requires Participant)

        // Step 1: Map C_unified → profile
        let cred = ConsciousnessCredential::from_unified_consciousness(
            "did:mycelix:agent_high".into(),
            0.70, // high consciousness
            0.80, // verified identity
            0.60, // good reputation
            0.50, // moderate community
            "did:mycelix:bridge".into(),
            NOW,
        );

        // Step 2: Evaluate against proposal requirement
        let result = evaluate_governance(&cred, &requirement_for_proposal(), NOW);

        // Step 3: Verify decision
        assert!(
            result.eligible,
            "High-consciousness agent should be proposal-eligible"
        );
        assert!(result.tier >= ConsciousnessTier::Participant);
        assert!(result.weight_bp > 0);

        // Step 4: Audit logging (verify audit input can be constructed)
        let should_log = should_audit(
            &requirement_for_proposal(),
            result.eligible,
            b"agent_high",
            "submit_proposal",
        );
        // 100% of basic approvals sampled at 10%, but we just verify the function works
        let _audit = GateAuditInput {
            action_name: "submit_proposal".into(),
            zome_name: "commons_bridge".into(),
            eligible: result.eligible,
            actual_tier: format!("{:?}", result.tier),
            required_tier: format!("{:?}", ConsciousnessTier::Participant),
            weight_bp: result.weight_bp,
            correlation_id: Some(format!("mvb:{}", NOW)),
            credential_source: Some("identity_bridge_fresh".into()),
        };
        // Verify it serializes (real bridge would store on source chain)
        let json = serde_json::to_string(&_audit).unwrap();
        assert!(json.contains("submit_proposal"));
        let _ = should_log; // used
    }

    #[test]
    fn mvb_end_to_end_low_consciousness_proposal_rejected() {
        // Scenario: Agent with low C_unified attempts a proposal
        // Expected: Rejected (Observer tier, proposal requires Participant)

        let cred = ConsciousnessCredential::from_unified_consciousness(
            "did:mycelix:agent_low".into(),
            0.10, // low consciousness
            0.20, // minimal identity
            0.10, // low reputation
            0.15, // minimal community
            "did:mycelix:bridge".into(),
            NOW,
        );

        let result = evaluate_governance(&cred, &requirement_for_proposal(), NOW);

        assert!(
            !result.eligible,
            "Low-consciousness agent should NOT be proposal-eligible"
        );
        assert_eq!(result.tier, ConsciousnessTier::Observer);
        assert_eq!(result.weight_bp, 0);

        // Rejections are always logged (100% audit rate)
        assert!(should_audit(
            &requirement_for_proposal(),
            false,
            b"agent_low",
            "submit_proposal"
        ));
    }

    #[test]
    fn mvb_end_to_end_read_always_allowed() {
        // Scenario: Any agent can read, regardless of consciousness level
        // The governance system gates blast radius, not voice.

        let cred = ConsciousnessCredential::from_unified_consciousness(
            "did:mycelix:agent_zero".into(),
            0.0, // zero consciousness
            0.0,
            0.0,
            0.0,
            "did:mycelix:bridge".into(),
            NOW,
        );

        // basic requirement is Participant (0.3), but read ops are UNGATED
        // In production, read ops don't call gate_consciousness at all.
        // This test verifies the profile correctly reflects zero state.
        assert_eq!(cred.tier, ConsciousnessTier::Observer);
        assert_eq!(cred.profile.combined_score(), 0.0);
    }

    // -- Bootstrap tests --

    #[test]
    fn bootstrap_eligible_small_community() {
        assert!(is_bootstrap_eligible(0, 0.25));
        assert!(is_bootstrap_eligible(4, 0.50));
    }

    #[test]
    fn bootstrap_ineligible_large_community() {
        assert!(!is_bootstrap_eligible(5, 0.50));
        assert!(!is_bootstrap_eligible(100, 1.0));
    }

    #[test]
    fn bootstrap_ineligible_low_identity() {
        assert!(!is_bootstrap_eligible(2, 0.24));
        assert!(!is_bootstrap_eligible(0, 0.0));
    }

    #[test]
    fn bootstrap_boundary() {
        assert!(!is_bootstrap_eligible(BOOTSTRAP_COMMUNITY_THRESHOLD, 0.5));
        assert!(is_bootstrap_eligible(
            BOOTSTRAP_COMMUNITY_THRESHOLD - 1,
            0.5
        ));
        assert!(is_bootstrap_eligible(2, BOOTSTRAP_MIN_IDENTITY));
    }

    #[test]
    fn bootstrap_credential_properties() {
        let cred = bootstrap_credential("did:mycelix:first".into(), 0.5, NOW);
        assert_eq!(cred.tier, ConsciousnessTier::Participant);
        assert_eq!(cred.profile.identity, 0.5);
        assert_eq!(cred.profile.reputation, 0.0);
        assert_eq!(cred.issuer, "did:mycelix:bootstrap");
        assert_eq!(cred.expires_at, NOW + BOOTSTRAP_TTL_US);
    }

    #[test]
    fn bootstrap_governance_basic_eligible() {
        let cred = bootstrap_credential("did:mycelix:first".into(), 0.5, NOW);
        let result = evaluate_bootstrap_governance(&cred, &requirement_for_basic(), NOW);
        assert!(result.eligible);
        assert_eq!(result.weight_bp, 5_000);
    }

    #[test]
    fn bootstrap_governance_voting_rejected() {
        let cred = bootstrap_credential("did:mycelix:first".into(), 0.5, NOW);
        let result = evaluate_bootstrap_governance(&cred, &requirement_for_voting(), NOW);
        assert!(!result.eligible);
        assert!(result.reasons[0].contains("capped at Participant"));
    }

    #[test]
    fn bootstrap_governance_expired_rejected() {
        let cred = bootstrap_credential("did:mycelix:first".into(), 0.5, NOW);
        let result = evaluate_bootstrap_governance(
            &cred,
            &requirement_for_basic(),
            NOW + BOOTSTRAP_TTL_US + 1,
        );
        assert!(!result.eligible);
    }

    #[test]
    fn bootstrap_serde_roundtrip() {
        let cred = bootstrap_credential("did:mycelix:first".into(), 0.5, NOW);
        let json = serde_json::to_string(&cred).unwrap();
        let cred2: ConsciousnessCredential = serde_json::from_str(&json).unwrap();
        assert_eq!(cred.did, cred2.did);
        assert_eq!(cred.tier, cred2.tier);
    }

    // -- NaN/Infinity defense --

    #[test]
    fn clamped_sanitizes_nan_to_zero() {
        let p = ConsciousnessProfile {
            identity: f64::NAN,
            reputation: f64::NAN,
            community: f64::NAN,
            engagement: f64::NAN,
        };
        let c = p.clamped();
        assert_eq!(c.identity, 0.0);
        assert_eq!(c.reputation, 0.0);
        assert_eq!(c.community, 0.0);
        assert_eq!(c.engagement, 0.0);
        assert_eq!(c.tier(), ConsciousnessTier::Observer);
    }

    #[test]
    fn clamped_sanitizes_infinity_to_bounds() {
        let p = ConsciousnessProfile {
            identity: f64::INFINITY,
            reputation: f64::NEG_INFINITY,
            community: f64::INFINITY,
            engagement: f64::NEG_INFINITY,
        };
        let c = p.clamped();
        // Infinity → 0.0 (not 1.0), because non-finite values are untrusted
        assert_eq!(c.identity, 0.0);
        assert_eq!(c.reputation, 0.0);
        assert_eq!(c.community, 0.0);
        assert_eq!(c.engagement, 0.0);
    }

    #[test]
    fn clamped_mixed_nan_and_valid() {
        let p = ConsciousnessProfile {
            identity: 0.75,
            reputation: f64::NAN,
            community: 0.50,
            engagement: f64::INFINITY,
        };
        let c = p.clamped();
        assert_eq!(c.identity, 0.75);
        assert_eq!(c.reputation, 0.0);
        assert_eq!(c.community, 0.50);
        assert_eq!(c.engagement, 0.0);
    }

    #[test]
    fn is_valid_detects_nan() {
        let valid = ConsciousnessProfile {
            identity: 0.5,
            reputation: 0.5,
            community: 0.5,
            engagement: 0.5,
        };
        assert!(valid.is_valid());

        let nan_id = ConsciousnessProfile {
            identity: f64::NAN,
            ..valid.clone()
        };
        assert!(!nan_id.is_valid());

        let inf_rep = ConsciousnessProfile {
            reputation: f64::INFINITY,
            ..valid.clone()
        };
        assert!(!inf_rep.is_valid());

        let neg_inf = ConsciousnessProfile {
            community: f64::NEG_INFINITY,
            ..valid
        };
        assert!(!neg_inf.is_valid());
    }

    #[test]
    fn nan_credential_evaluates_to_observer() {
        let cred = fresh_credential(ConsciousnessProfile {
            identity: f64::NAN,
            reputation: f64::NAN,
            community: f64::NAN,
            engagement: f64::NAN,
        });
        let result = evaluate_governance(&cred, &requirement_for_basic(), NOW);
        // NaN dimensions → clamped to 0.0 → Observer tier → rejected for Participant requirement
        assert!(!result.eligible);
        assert_eq!(result.tier, ConsciousnessTier::Observer);
    }

    #[test]
    fn nan_does_not_bypass_gate() {
        // Ensure NaN can never produce a passing gate check
        let cred = fresh_credential(ConsciousnessProfile {
            identity: f64::NAN,
            reputation: 0.9,
            community: 0.9,
            engagement: 0.9,
        });
        let result = evaluate_governance(&cred, &requirement_for_voting(), NOW);
        // Even with high rep/community/engagement, NaN identity → 0.0 identity
        // combined = 0.0*0.25 + 0.9*0.25 + 0.9*0.30 + 0.9*0.20 = 0.675 → Steward
        // BUT min_identity is Some(0.25), and clamped identity is 0.0 → rejected
        assert!(!result.eligible);
        assert!(result.reasons.iter().any(|r| r.contains("Identity")));
    }

    // ========================================================================
    // Property-based tests (proptest)
    // ========================================================================

    use proptest::prelude::*;

    /// Strategy for generating valid profile dimension values in [0.0, 1.0].
    fn dimension() -> impl Strategy<Value = f64> {
        0.0..=1.0_f64
    }

    /// Strategy for generating a valid ConsciousnessProfile.
    fn profile_strategy() -> impl Strategy<Value = ConsciousnessProfile> {
        (dimension(), dimension(), dimension(), dimension()).prop_map(
            |(identity, reputation, community, engagement)| ConsciousnessProfile {
                identity,
                reputation,
                community,
                engagement,
            },
        )
    }

    proptest! {
        /// Higher profile scores always produce equal or higher tiers.
        ///
        /// If every dimension of profile B is >= the corresponding dimension
        /// of profile A, then B's tier must be >= A's tier.
        #[test]
        fn test_tier_progression_monotonic(
            id_lo in dimension(),
            rep_lo in dimension(),
            com_lo in dimension(),
            eng_lo in dimension(),
            id_delta in 0.0..=1.0_f64,
            rep_delta in 0.0..=1.0_f64,
            com_delta in 0.0..=1.0_f64,
            eng_delta in 0.0..=1.0_f64,
        ) {
            let lo = ConsciousnessProfile {
                identity: id_lo,
                reputation: rep_lo,
                community: com_lo,
                engagement: eng_lo,
            };
            let hi = ConsciousnessProfile {
                identity: (id_lo + id_delta).min(1.0),
                reputation: (rep_lo + rep_delta).min(1.0),
                community: (com_lo + com_delta).min(1.0),
                engagement: (eng_lo + eng_delta).min(1.0),
            };
            prop_assert!(hi.tier() >= lo.tier(),
                "Higher profile {:?} (tier {:?}) should be >= lower profile {:?} (tier {:?})",
                hi, hi.tier(), lo, lo.tier());
        }

        /// Higher tiers always have equal or higher vote weights.
        #[test]
        fn test_vote_weight_monotonic_with_tier(
            a in profile_strategy(),
            b in profile_strategy(),
        ) {
            let tier_a = a.tier();
            let tier_b = b.tier();
            if tier_a <= tier_b {
                prop_assert!(tier_a.vote_weight_bp() <= tier_b.vote_weight_bp(),
                    "Tier {:?} (weight {}) should have <= weight than {:?} (weight {})",
                    tier_a, tier_a.vote_weight_bp(), tier_b, tier_b.vote_weight_bp());
            }
        }

        /// A profile with all zeros is always Observer tier.
        #[test]
        fn test_all_zero_profile_is_observer(_seed in 0u32..100) {
            let p = ConsciousnessProfile::zero();
            prop_assert_eq!(p.tier(), ConsciousnessTier::Observer);
            prop_assert_eq!(p.combined_score(), 0.0);
            prop_assert_eq!(p.tier().vote_weight_bp(), 0);
        }

        /// Max values (all 1.0) never panic and produce Guardian tier.
        #[test]
        fn test_all_max_profile_no_panic(_seed in 0u32..100) {
            let p = ConsciousnessProfile {
                identity: 1.0,
                reputation: 1.0,
                community: 1.0,
                engagement: 1.0,
            };
            let tier = p.tier();
            let score = p.combined_score();
            let weight = tier.vote_weight_bp();
            prop_assert_eq!(tier, ConsciousnessTier::Guardian);
            prop_assert!((score - 1.0).abs() < 1e-10);
            prop_assert_eq!(weight, 10000);
        }

        /// Any credential created via from_unified_consciousness has
        /// expires_at > issued_at (expiry is always in the future relative
        /// to issuance).
        #[test]
        fn test_credential_expiry_in_future(
            c_unified in dimension(),
            identity in dimension(),
            reputation in dimension(),
            community in dimension(),
            now_us in 0u64..=u64::MAX / 2,
        ) {
            let cred = ConsciousnessCredential::from_unified_consciousness(
                "did:test:prop".into(),
                c_unified,
                identity,
                reputation,
                community,
                "did:test:issuer".into(),
                now_us,
            );
            prop_assert!(cred.expires_at > cred.issued_at,
                "expires_at ({}) must be > issued_at ({})",
                cred.expires_at, cred.issued_at);
            prop_assert_eq!(cred.expires_at, now_us + ConsciousnessCredential::DEFAULT_TTL_US);
        }

        /// Computed combined_score is always in [0.0, 1.0] for any
        /// valid (clamped) profile.
        #[test]
        fn test_profile_scores_bounded(
            identity in -10.0..=10.0_f64,
            reputation in -10.0..=10.0_f64,
            community in -10.0..=10.0_f64,
            engagement in -10.0..=10.0_f64,
        ) {
            let raw = ConsciousnessProfile { identity, reputation, community, engagement };
            let clamped = raw.clamped();

            // All clamped dimensions in [0, 1]
            prop_assert!(clamped.identity >= 0.0 && clamped.identity <= 1.0);
            prop_assert!(clamped.reputation >= 0.0 && clamped.reputation <= 1.0);
            prop_assert!(clamped.community >= 0.0 && clamped.community <= 1.0);
            prop_assert!(clamped.engagement >= 0.0 && clamped.engagement <= 1.0);

            // Combined score of clamped profile in [0, 1]
            let score = clamped.combined_score();
            prop_assert!(score >= 0.0 && score <= 1.0,
                "Combined score {} out of bounds for clamped profile {:?}",
                score, clamped);

            // Tier is always valid (no panic)
            let _tier = clamped.tier();
        }
    }

    // ========================================================================
    // Reputation decay, slashing, and restoration tests
    // ========================================================================

    #[test]
    fn test_reputation_decay_one_day() {
        let mut state = ReputationState::new(1.0, 0);
        let one_day_us = 86_400_000_000u64;
        state.apply_decay(one_day_us);
        assert!(
            (state.score - REPUTATION_DECAY_PER_DAY).abs() < 1e-6,
            "After 1 day, score should be {}, got {}",
            REPUTATION_DECAY_PER_DAY,
            state.score
        );
    }

    #[test]
    fn test_reputation_decay_half_life() {
        let mut state = ReputationState::new(1.0, 0);
        let days_347_us = 347 * 86_400_000_000u64;
        state.apply_decay(days_347_us);
        assert!(
            state.score > 0.49 && state.score < 0.51,
            "After ~347 days, score should be ~0.5, got {}",
            state.score
        );
    }

    #[test]
    fn test_reputation_no_decay_on_zero_elapsed() {
        let mut state = ReputationState::new(0.8, 1000);
        state.apply_decay(1000); // same timestamp
        assert!((state.score - 0.8).abs() < 1e-10);
    }

    #[test]
    fn test_reputation_slash() {
        let mut state = ReputationState::new(1.0, 0);
        let new_score = state.slash(1000);
        assert!(
            (new_score - 0.5).abs() < 1e-6,
            "After slash, score should be 0.5, got {}",
            new_score
        );
        assert_eq!(state.total_slashes, 1);
        assert_eq!(state.consecutive_good, 0);
    }

    #[test]
    fn test_reputation_slash_below_blacklist() {
        let mut state = ReputationState::new(0.08, 0);
        state.slash(1000);
        // 0.08 * 0.5 = 0.04 < 0.05 threshold
        assert!(state.blacklisted);
        assert!(!state.can_participate());
    }

    #[test]
    fn test_reputation_restoration_path() {
        let mut state = ReputationState::new(0.03, 0);
        state.blacklisted = true;
        state.blacklisted_since_us = Some(0);

        // Progress through restoration
        for i in 0..REPUTATION_RESTORATION_INTERACTIONS {
            assert!(
                state.blacklisted,
                "Should still be blacklisted at interaction {}",
                i
            );
            state.record_good_interaction(0.001, 1000 + i as u64 * 1000);
        }

        assert!(
            !state.blacklisted,
            "Should be restored after {} good interactions",
            REPUTATION_RESTORATION_INTERACTIONS
        );
        assert!(
            state.score >= 0.1,
            "Score should be at least 0.1 after restoration"
        );
    }

    #[test]
    fn test_reputation_max_slashes_cap() {
        let mut state = ReputationState::new(1.0, 0);

        // Slash more than MAX_SLASHES times
        for i in 0..(REPUTATION_MAX_SLASHES + 2) {
            state.score = 0.8; // Reset score to test cap
            state.slash(i as u64 * 1000);
        }

        // Now good interactions should be capped at 0.5
        state.score = 0.3;
        state.blacklisted = false;
        for i in 0..200 {
            state.record_good_interaction(0.01, 1_000_000 + i as u64 * 1000);
        }
        assert!(
            state.score <= 0.5 + 1e-6,
            "Score should be capped at 0.5 after {} slashes, got {}",
            REPUTATION_MAX_SLASHES,
            state.score
        );
    }

    #[test]
    fn test_reputation_proportional_slash() {
        let mut state = ReputationState::new(1.0, 0);
        state.slash_proportional(0.3, 1000);
        assert!((state.score - 0.7).abs() < 1e-6);
    }

    #[test]
    fn test_reputation_restoration_progress() {
        let mut state = ReputationState::new(0.01, 0);
        state.blacklisted = true;
        state.blacklisted_since_us = Some(0);
        state.consecutive_good = 50;

        let progress = state.restoration_progress();
        assert!(
            (progress - 0.5).abs() < 1e-6,
            "50/{} should be 50% progress, got {}",
            REPUTATION_RESTORATION_INTERACTIONS,
            progress
        );
    }

    #[test]
    fn test_reputation_non_blacklisted_full_progress() {
        let state = ReputationState::new(0.8, 0);
        assert!((state.restoration_progress() - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_decay_reputation_profile() {
        let profile = ConsciousnessProfile {
            identity: 0.9,
            reputation: 1.0,
            community: 0.7,
            engagement: 0.5,
        };
        let decayed = decay_reputation(&profile, 30.0);
        assert!(
            (decayed.identity - 0.9).abs() < 1e-10,
            "Identity should not decay"
        );
        assert!(decayed.reputation < 1.0, "Reputation should decay");
        assert!(
            (decayed.community - 0.7).abs() < 1e-10,
            "Community should not decay"
        );
    }

    #[test]
    fn test_evaluate_governance_blacklisted() {
        let credential = ConsciousnessCredential {
            did: "did:mycelix:test".to_string(),
            profile: ConsciousnessProfile {
                identity: 0.9,
                reputation: 0.01,
                community: 0.8,
                engagement: 0.7,
            },
            tier: ConsciousnessTier::Citizen,
            issued_at: 0,
            expires_at: 100_000_000_000,
            issuer: "did:mycelix:bridge".to_string(),
            trajectory_commitment: None,
            extensions: std::collections::HashMap::new(),
        };
        let rep_state = ReputationState {
            score: 0.01,
            blacklisted: true,
            blacklisted_since_us: Some(0),
            consecutive_good: 20,
            total_slashes: 2,
            last_updated_us: 0,
            last_slash_us: None,
        };
        let requirement = GovernanceRequirement {
            min_tier: ConsciousnessTier::Participant,
            min_identity: None,
            min_community: None,
        };

        let result = evaluate_governance_with_reputation(
            &credential,
            &requirement,
            &rep_state,
            50_000_000_000,
        );
        assert!(!result.eligible, "Blacklisted agent should not be eligible");
        assert_eq!(result.weight_bp, 0);
    }

    #[test]
    fn test_evaluate_governance_slash_penalty() {
        let credential = ConsciousnessCredential {
            did: "did:mycelix:test".to_string(),
            profile: ConsciousnessProfile {
                identity: 0.9,
                reputation: 0.8,
                community: 0.8,
                engagement: 0.7,
            },
            tier: ConsciousnessTier::Steward,
            issued_at: 0,
            expires_at: 100_000_000_000,
            issuer: "did:mycelix:bridge".to_string(),
            trajectory_commitment: None,
            extensions: std::collections::HashMap::new(),
        };
        let rep_state = ReputationState {
            score: 0.8,
            blacklisted: false,
            blacklisted_since_us: None,
            last_slash_us: None,
            consecutive_good: 50,
            total_slashes: 2, // 2 slashes -> 10% weight reduction
            last_updated_us: 0,
        };
        let requirement = GovernanceRequirement {
            min_tier: ConsciousnessTier::Participant,
            min_identity: None,
            min_community: None,
        };

        let result = evaluate_governance_with_reputation(
            &credential,
            &requirement,
            &rep_state,
            50_000_000_000,
        );
        assert!(result.eligible);
        // Weight should be reduced by slash penalty
        let base_weight = credential.profile.clamped().tier().vote_weight_bp();
        assert!(
            result.weight_bp < base_weight,
            "Weight {} should be less than base {} due to slash penalty",
            result.weight_bp,
            base_weight
        );
    }

    #[test]
    fn test_reputation_nan_safety() {
        let state = ReputationState::new(f64::NAN, 0);
        assert!((state.score - 0.0).abs() < 1e-10, "NaN should clamp to 0");

        let mut state2 = ReputationState::new(0.5, 0);
        state2.apply_decay(u64::MAX); // extreme elapsed time
        assert!(state2.score.is_finite());
    }

    // ════════════════════════════════════════════════════════════════════════
    // Continuous sigmoid authorization tests
    // ════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_sigmoid_at_threshold_returns_half_max() {
        let w = continuous_vote_weight(0.4, 0.4, VOTE_WEIGHT_TEMPERATURE, VOTE_WEIGHT_MAX_BP);
        assert!(
            (w - VOTE_WEIGHT_MAX_BP / 2.0).abs() < 1e-6,
            "At threshold, weight should be max/2, got {w}"
        );
    }

    #[test]
    fn test_sigmoid_below_threshold_near_zero() {
        let w = continuous_vote_weight(0.1, 0.4, VOTE_WEIGHT_TEMPERATURE, VOTE_WEIGHT_MAX_BP);
        assert!(
            w < 100.0,
            "Well below threshold, weight should be near zero, got {w}"
        );
    }

    #[test]
    fn test_sigmoid_above_threshold_near_max() {
        let w = continuous_vote_weight(0.7, 0.4, VOTE_WEIGHT_TEMPERATURE, VOTE_WEIGHT_MAX_BP);
        assert!(
            w > 9900.0,
            "Well above threshold, weight should be near max, got {w}"
        );
    }

    #[test]
    fn test_sigmoid_zero_temperature_returns_zero() {
        let w = continuous_vote_weight(0.5, 0.4, 0.0, VOTE_WEIGHT_MAX_BP);
        assert!(
            (w - 0.0).abs() < 1e-10,
            "Zero temperature should return 0.0, got {w}"
        );
    }

    #[test]
    fn test_sigmoid_nan_score_returns_zero() {
        let w = continuous_vote_weight(f64::NAN, 0.4, VOTE_WEIGHT_TEMPERATURE, VOTE_WEIGHT_MAX_BP);
        assert!(
            (w - 0.0).abs() < 1e-10,
            "NaN score should return 0.0, got {w}"
        );
    }

    #[test]
    fn test_sigmoid_infinity_score_returns_zero() {
        let w = continuous_vote_weight(
            f64::INFINITY,
            0.4,
            VOTE_WEIGHT_TEMPERATURE,
            VOTE_WEIGHT_MAX_BP,
        );
        assert!(
            (w - 0.0).abs() < 1e-10,
            "Infinity score should return 0.0, got {w}"
        );
    }

    #[test]
    fn test_vote_weight_continuous_on_profile() {
        let profile = ConsciousnessProfile {
            identity: 0.5,
            reputation: 0.5,
            community: 0.5,
            engagement: 0.5,
        };
        // combined_score = 0.5, which is above 0.4 threshold
        let w = profile.vote_weight_continuous();
        assert!(
            w > VOTE_WEIGHT_MAX_BP / 2.0,
            "Score 0.5 > threshold 0.4 should give > half max"
        );
        assert!(w < VOTE_WEIGHT_MAX_BP, "Should not exceed max");
    }

    // ════════════════════════════════════════════════════════════════════════
    // Hysteresis tests
    // ════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_hysteresis_no_promote_in_deadband() {
        // Score 0.42 — above Citizen threshold (0.4) but below promote threshold (0.45)
        let tier =
            ConsciousnessTier::from_score_with_hysteresis(0.42, ConsciousnessTier::Participant);
        assert_eq!(
            tier,
            ConsciousnessTier::Participant,
            "0.42 should NOT promote from Participant (need 0.45)"
        );
    }

    #[test]
    fn test_hysteresis_no_demote_in_deadband() {
        // Score 0.38 — below Citizen threshold (0.4) but above demote threshold (0.35)
        let tier = ConsciousnessTier::from_score_with_hysteresis(0.38, ConsciousnessTier::Citizen);
        assert_eq!(
            tier,
            ConsciousnessTier::Citizen,
            "0.38 should NOT demote from Citizen (need < 0.35)"
        );
    }

    #[test]
    fn test_hysteresis_demotes_below_lower_threshold() {
        // Score 0.34 — below demote threshold (0.35)
        let tier = ConsciousnessTier::from_score_with_hysteresis(0.34, ConsciousnessTier::Citizen);
        assert_eq!(
            tier,
            ConsciousnessTier::Participant,
            "0.34 should demote from Citizen (below 0.35)"
        );
    }

    #[test]
    fn test_hysteresis_promotes_above_upper_threshold() {
        // Score 0.46 — above promote threshold (0.45)
        let tier =
            ConsciousnessTier::from_score_with_hysteresis(0.46, ConsciousnessTier::Participant);
        assert_eq!(
            tier,
            ConsciousnessTier::Citizen,
            "0.46 should promote from Participant to Citizen (above 0.45)"
        );
    }

    #[test]
    fn test_hysteresis_guardian_boundary() {
        // 0.83 — above 0.8 but below promote threshold 0.85
        let tier = ConsciousnessTier::from_score_with_hysteresis(0.83, ConsciousnessTier::Steward);
        assert_eq!(
            tier,
            ConsciousnessTier::Steward,
            "0.83 should NOT promote to Guardian (need 0.85)"
        );

        // 0.86 — above promote threshold 0.85
        let tier = ConsciousnessTier::from_score_with_hysteresis(0.86, ConsciousnessTier::Steward);
        assert_eq!(
            tier,
            ConsciousnessTier::Guardian,
            "0.86 should promote to Guardian"
        );

        // 0.76 — below demote threshold 0.75
        let tier = ConsciousnessTier::from_score_with_hysteresis(0.74, ConsciousnessTier::Guardian);
        assert_eq!(
            tier,
            ConsciousnessTier::Steward,
            "0.74 should demote from Guardian"
        );
    }

    #[test]
    fn test_hysteresis_observer_boundary() {
        // 0.33 — above 0.3 but below promote threshold 0.35
        let tier = ConsciousnessTier::from_score_with_hysteresis(0.33, ConsciousnessTier::Observer);
        assert_eq!(
            tier,
            ConsciousnessTier::Observer,
            "0.33 should NOT promote from Observer (need 0.35)"
        );

        // 0.36 — above promote threshold 0.35
        let tier = ConsciousnessTier::from_score_with_hysteresis(0.36, ConsciousnessTier::Observer);
        assert_eq!(
            tier,
            ConsciousnessTier::Participant,
            "0.36 should promote to Participant"
        );

        // 0.24 — below demote threshold 0.25
        let tier =
            ConsciousnessTier::from_score_with_hysteresis(0.24, ConsciousnessTier::Participant);
        assert_eq!(
            tier,
            ConsciousnessTier::Observer,
            "0.24 should demote to Observer"
        );
    }

    #[test]
    fn extensions_default_empty() {
        let cred = ConsciousnessCredential::from_unified_consciousness(
            "did:test".into(),
            0.5,
            0.5,
            0.5,
            0.5,
            "issuer".into(),
            1000,
        );
        assert!(cred.extensions.is_empty());
        assert!(cred.trajectory_commitment.is_none());
    }

    #[test]
    fn extensions_set_get_roundtrip() {
        let mut cred = ConsciousnessCredential::from_unified_consciousness(
            "did:test".into(),
            0.5,
            0.5,
            0.5,
            0.5,
            "issuer".into(),
            1000,
        );
        cred.set_extension("foo", vec![1, 2, 3]);
        assert_eq!(cred.get_extension("foo"), Some(&vec![1, 2, 3]));
        assert_eq!(cred.get_extension("bar"), None);
    }

    #[test]
    fn extensions_remove() {
        let mut cred = ConsciousnessCredential::from_unified_consciousness(
            "did:test".into(),
            0.5,
            0.5,
            0.5,
            0.5,
            "issuer".into(),
            1000,
        );
        cred.set_extension("key", vec![42]);
        let removed = cred.remove_extension("key");
        assert_eq!(removed, Some(vec![42]));
        assert!(cred.get_extension("key").is_none());
    }

    // ════════════════════════════════════════════════════════════════════════
    // Sybil maturation proptests
    // ════════════════════════════════════════════════════════════════════════

    mod sybil_proptests {
        use super::*;
        use proptest::prelude::*;

        const MATURATION_US: u64 = 72 * 3600 * 1_000_000;

        fn make_credential_at_age(age_us: u64) -> (ConsciousnessCredential, u64) {
            let now_us = 1_000_000_000_000u64; // fixed reference
            let issued_at = now_us.saturating_sub(age_us);
            let cred = ConsciousnessCredential {
                did: "did:test:prop".to_string(),
                profile: ConsciousnessProfile {
                    identity: 0.5,
                    reputation: 0.5,
                    community: 0.5,
                    engagement: 0.5,
                },
                tier: ConsciousnessTier::Citizen,
                issued_at,
                expires_at: now_us + 86_400_000_000,
                issuer: "test".to_string(),
                trajectory_commitment: None,
                extensions: std::collections::HashMap::new(),
            };
            (cred, now_us)
        }

        proptest! {
            /// Weight monotonically increases with credential age.
            #[test]
            fn prop_weight_monotonic_with_age(
                age_a_hours in 0u64..200,
                age_b_hours in 0u64..200,
            ) {
                let age_a_us = age_a_hours * 3600 * 1_000_000;
                let age_b_us = age_b_hours * 3600 * 1_000_000;
                let (cred_a, now) = make_credential_at_age(age_a_us);
                let (cred_b, _) = make_credential_at_age(age_b_us);
                let req = requirement_for_basic();

                let result_a = evaluate_governance(&cred_a, &req, now);
                let result_b = evaluate_governance(&cred_b, &req, now);

                if age_a_us >= age_b_us {
                    prop_assert!(
                        result_a.weight_bp >= result_b.weight_bp,
                        "Older credential should have >= weight than younger: {} vs {}",
                        result_a.weight_bp, result_b.weight_bp
                    );
                }
            }

            /// Fully matured credentials (>72h) get full weight (no age penalty).
            #[test]
            fn prop_mature_credential_full_weight(age_hours in 73u64..1000) {
                let age_us = age_hours * 3600 * 1_000_000;
                let (cred, now) = make_credential_at_age(age_us);
                let req = requirement_for_basic();
                let result = evaluate_governance(&cred, &req, now);
                // Citizen tier (0.5 combined) through sigmoid gives 7500 bp.
                // The key assertion: no age penalty applied for mature credentials.
                let baseline = {
                    let (fresh_cred, _) = make_credential_at_age(age_us);
                    evaluate_governance(&fresh_cred, &req, now).weight_bp
                };
                prop_assert_eq!(
                    result.weight_bp, baseline,
                    "Mature credential should have full (unpenalized) weight"
                );
            }

            /// Brand-new credentials (0-1h) get severely reduced weight.
            #[test]
            fn prop_new_credential_reduced_weight(age_minutes in 0u64..60) {
                let age_us = age_minutes * 60 * 1_000_000;
                let (cred, now) = make_credential_at_age(age_us);
                let req = requirement_for_basic();
                let result = evaluate_governance(&cred, &req, now);
                // At 0 minutes: weight = 5000 * 0.1 = 500
                // At 60 minutes: weight = 5000 * (0.1 + 0.9 * (60/4320)) ≈ 562
                prop_assert!(
                    result.weight_bp < 3000,
                    "New credential should have reduced weight: {}",
                    result.weight_bp
                );
            }

            /// Mass-created Sybil swarm: N identities created simultaneously
            /// have total collective weight << N honest identities.
            #[test]
            fn prop_sybil_swarm_reduced_total_weight(n_sybils in 3usize..50) {
                let age_us = 60 * 1_000_000; // 1 minute old (mass-created)
                let honest_age_us = 100 * 3600 * 1_000_000; // 100 hours old

                let (sybil_cred, now) = make_credential_at_age(age_us);
                let (honest_cred, _) = make_credential_at_age(honest_age_us);
                let req = requirement_for_basic();

                let sybil_weight = evaluate_governance(&sybil_cred, &req, now).weight_bp;
                let honest_weight = evaluate_governance(&honest_cred, &req, now).weight_bp;

                let sybil_total = sybil_weight as u64 * n_sybils as u64;
                let honest_total = honest_weight as u64 * n_sybils as u64;

                // Sybil swarm should have <= 30% the total weight of equivalent honest agents
                let ratio = sybil_total as f64 / honest_total.max(1) as f64;
                prop_assert!(
                    ratio <= 0.3,
                    "Sybil swarm total weight should be <= 30% of honest: ratio={}",
                    ratio
                );
            }
        }
    }
}