asupersync 0.3.1

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
//! System subject namespace and control handlers for the FABRIC control plane.
//!
//! Models the `$SYS.FABRIC.*` subject space inspired by NATS `$SYS.*`, with
//! region-owned handlers, reserved budgets, priority scheduling, and a
//! break-glass recovery path that operates even when the ordinary fabric is
//! degraded.
//!
//! # Design invariants
//!
//! - Control subjects live exclusively under `$SYS.FABRIC.` (enforced by
//!   [`SubjectSchema`] validation, which requires `$SYS.` or `sys.` prefix for
//!   `SubjectFamily::Control`).
//! - Control handlers run with a **reserved** budget and scheduling priority so
//!   they never compete with user traffic for resources.
//! - Advisory subjects must **NOT** automatically feed policy loops without
//!   explicit damping, stratification, or operator intent — otherwise the
//!   control plane would amplify its own observations.
//! - A minimal break-glass recovery surface is available even when ordinary
//!   fabric connectivity is degraded.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::time::Duration;

use franken_decision::{DecisionAuditEntry, DecisionOutcome};
use franken_evidence::EvidenceLedger;
use franken_kernel::{DecisionId, TraceId};

use crate::remote::NodeId;

use super::class::{AckKind, DeliveryClass};
use super::ir::{
    EvidencePolicy, MobilityPermission, PrivacyPolicy, RetentionPolicy, SubjectFamily,
    SubjectPattern, SubjectSchema,
};
use super::subject::{NamespaceComponent, NamespaceKernel, NamespaceKernelError, Subject};

// ---------------------------------------------------------------------------
// System subject families
// ---------------------------------------------------------------------------

/// Well-known system subject families under `$SYS.FABRIC.*`.
///
/// Each family covers a distinct control-plane concern.  The string
/// representation is the canonical subject prefix (e.g.
/// `$SYS.FABRIC.HEALTH`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SystemSubjectFamily {
    /// Health check probes and liveness status.
    Health,
    /// Import morphism lifecycle events.
    Import,
    /// Export morphism lifecycle events.
    Export,
    /// Routing table changes and announcements.
    Route,
    /// Graceful drain lifecycle signals.
    Drain,
    /// Authentication and authorization events.
    Auth,
    /// Consumer lifecycle and advisory events.
    Consumer,
    /// Stream lifecycle and advisory events.
    Stream,
    /// RaptorQ repair status and erasure-coding advisories.
    Repair,
    /// Replay and forensic-trace lifecycle signals.
    Replay,
}

impl SystemSubjectFamily {
    /// All known system subject families in canonical order.
    pub const ALL: [Self; 10] = [
        Self::Health,
        Self::Import,
        Self::Export,
        Self::Route,
        Self::Drain,
        Self::Auth,
        Self::Consumer,
        Self::Stream,
        Self::Repair,
        Self::Replay,
    ];

    /// Canonical upper-case name used in subject paths.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Health => "HEALTH",
            Self::Import => "IMPORT",
            Self::Export => "EXPORT",
            Self::Route => "ROUTE",
            Self::Drain => "DRAIN",
            Self::Auth => "AUTH",
            Self::Consumer => "CONSUMER",
            Self::Stream => "STREAM",
            Self::Repair => "REPAIR",
            Self::Replay => "REPLAY",
        }
    }

    /// Returns the canonical subject prefix, e.g. `$SYS.FABRIC.HEALTH`.
    #[must_use]
    pub fn prefix(self) -> String {
        format!("$SYS.FABRIC.{}", self.name())
    }

    /// Returns a wildcard pattern matching all subjects in this family,
    /// e.g. `$SYS.FABRIC.HEALTH.>`.
    #[must_use]
    pub fn wildcard_pattern(self) -> SubjectPattern {
        SubjectPattern::new(format!("$SYS.FABRIC.{}.>", self.name()))
    }

    /// The default delivery class for this control family.
    ///
    /// Health, Route, and Drain are ephemeral (best-effort); Auth and Replay
    /// are forensic-replayable for audit; the rest use obligation-backed
    /// semantics.
    #[must_use]
    pub const fn default_delivery_class(self) -> DeliveryClass {
        match self {
            // Hot ephemeral — control heartbeats must not impose durability tax.
            Self::Health | Self::Route | Self::Drain => DeliveryClass::EphemeralInteractive,
            // Import/export/consumer/stream/repair advisories are
            // obligation-backed so the operator has explicit ack semantics.
            Self::Import | Self::Export | Self::Consumer | Self::Stream | Self::Repair => {
                DeliveryClass::ObligationBacked
            }
            // Auth and Replay events carry audit-trail obligations.
            Self::Auth | Self::Replay => DeliveryClass::ForensicReplayable,
        }
    }

    /// The minimum ack kind for this control family.
    #[must_use]
    pub const fn minimum_ack(self) -> AckKind {
        match self {
            Self::Health | Self::Route | Self::Drain => AckKind::Accepted,
            Self::Import | Self::Export | Self::Consumer | Self::Stream | Self::Repair => {
                AckKind::Committed
            }
            Self::Auth | Self::Replay => AckKind::Recoverable,
        }
    }

    /// Construct a [`SubjectSchema`] for this control family with default
    /// policies.
    #[must_use]
    pub fn default_schema(self) -> SubjectSchema {
        SubjectSchema {
            pattern: self.wildcard_pattern(),
            family: SubjectFamily::Control,
            delivery_class: self.default_delivery_class(),
            evidence_policy: self.default_evidence_policy(),
            privacy_policy: PrivacyPolicy::default(),
            reply_space: None,
            mobility: MobilityPermission::LocalOnly,
            quantitative_obligation: None,
        }
    }

    /// Default evidence policy for this control family.
    ///
    /// Auth and Replay always sample at 100% with full control transition
    /// recording.  Other families sample at 100% but skip counterfactual
    /// branches.
    fn default_evidence_policy(self) -> EvidencePolicy {
        match self {
            Self::Auth | Self::Replay => EvidencePolicy {
                sampling_ratio: 1.0,
                retention: RetentionPolicy::default(),
                record_payload_hashes: true,
                record_control_transitions: true,
                record_counterfactual_branches: true,
            },
            _ => EvidencePolicy::default(),
        }
    }
}

impl fmt::Display for SystemSubjectFamily {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "$SYS.FABRIC.{}", self.name())
    }
}

// ---------------------------------------------------------------------------
// Control handler budget and priority
// ---------------------------------------------------------------------------

/// Reserved resource envelope for a control handler.
///
/// Control handlers must run with bounded resources that do NOT compete with
/// user-data traffic.  This struct captures the scheduling priority, poll
/// quota, and deadline budget that the runtime should reserve for a handler.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ControlBudget {
    /// Scheduling priority (0 = lowest, 255 = highest).
    /// Control handlers default to 240 — well above normal user traffic
    /// (typically 128) but below the break-glass emergency ceiling (255).
    pub priority: u8,
    /// Maximum number of polls before the handler must yield.
    pub poll_quota: u32,
    /// Soft deadline for a single handler invocation.
    pub deadline: Duration,
}

impl Default for ControlBudget {
    fn default() -> Self {
        Self {
            priority: 240,
            poll_quota: 256,
            deadline: Duration::from_millis(50),
        }
    }
}

impl ControlBudget {
    /// Break-glass budget: maximum priority, generous quota, short deadline.
    #[must_use]
    pub const fn break_glass() -> Self {
        Self {
            priority: 255,
            poll_quota: 512,
            deadline: Duration::from_millis(100),
        }
    }
}

// ---------------------------------------------------------------------------
// Advisory damping policy
// ---------------------------------------------------------------------------

/// Policy controlling how advisory subjects feed into policy loops.
///
/// **Critical guardrail:** advisories must NOT automatically trigger further
/// control-plane actions without explicit damping.  This prevents the control
/// plane from amplifying its own observations into a feedback storm.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AdvisoryDampingPolicy {
    /// Minimum interval between re-evaluation of the same advisory class.
    pub min_interval: Duration,
    /// Maximum number of advisory events that can contribute to a single
    /// policy evaluation window.
    pub max_events_per_window: u32,
    /// Whether an explicit operator intent (approval) is required before the
    /// advisory can trigger an automated action.
    pub requires_operator_intent: bool,
    /// Optional stratification tier — advisories at tier N cannot trigger
    /// actions that produce advisories at tier <= N.
    pub stratification_tier: Option<u8>,
}

impl Default for AdvisoryDampingPolicy {
    fn default() -> Self {
        Self {
            min_interval: Duration::from_secs(5),
            max_events_per_window: 10,
            requires_operator_intent: true,
            stratification_tier: None,
        }
    }
}

impl AdvisoryDampingPolicy {
    /// A permissive policy for non-recursive advisories that are known to be
    /// safe from feedback loops (e.g. health probes that produce no further
    /// control traffic).
    #[must_use]
    pub const fn non_recursive() -> Self {
        Self {
            min_interval: Duration::from_secs(1),
            max_events_per_window: 100,
            requires_operator_intent: false,
            stratification_tier: Some(0),
        }
    }
}

// ---------------------------------------------------------------------------
// Delta-CRDT metadata for non-authoritative control surfaces
// ---------------------------------------------------------------------------

/// Join-semilattice interface for control-plane delta CRDTs.
///
/// These types are explicitly reserved for non-authoritative metadata such as
/// aggregated interest, coarse checkpoints, membership hints, load sketches,
/// and advisory summaries. Authoritative state still belongs in fenced control
/// capsules and obligation-backed protocols.
pub trait JoinSemilattice: Clone + PartialEq {
    /// Sparse delta type that can be merged into a full state.
    type Delta: Clone + PartialEq + Default;

    /// Join another replica into `self`.
    fn merge(&mut self, other: &Self);

    /// Produce the sparse delta needed to advance `baseline` to `self`.
    fn delta(&self, baseline: &Self) -> Self::Delta;

    /// Return whether `delta` carries no material state change.
    fn delta_is_empty(delta: &Self::Delta) -> bool {
        delta == &Self::Delta::default()
    }

    /// Apply a sparse delta produced by [`Self::delta`].
    fn apply_delta(&mut self, delta: &Self::Delta) -> bool;
}

/// Version vector tracking the highest converged CRDT version per replica.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ReplicaVersionVector {
    versions: BTreeMap<NodeId, u64>,
}

impl ReplicaVersionVector {
    /// Return the current converged version for `replica`.
    #[must_use]
    pub fn version(&self, replica: &NodeId) -> u64 {
        self.versions.get(replica).copied().unwrap_or(0)
    }

    /// Advance the local version for `replica` and return the new value.
    pub fn advance(&mut self, replica: &NodeId) -> u64 {
        let entry = self.versions.entry(replica.clone()).or_insert(0);
        *entry = entry.saturating_add(1);
        *entry
    }

    /// Observe a remote version for `replica`.
    pub fn observe(&mut self, replica: &NodeId, version: u64) {
        let entry = self.versions.entry(replica.clone()).or_insert(0);
        *entry = (*entry).max(version);
    }

    /// Join another version vector into `self`.
    pub fn merge(&mut self, other: &Self) {
        for (replica, version) in &other.versions {
            self.observe(replica, *version);
        }
    }

    fn same_except(&self, other: &Self, except: &NodeId) -> bool {
        self.all_replicas(other)
            .into_iter()
            .filter(|replica| replica != except)
            .all(|replica| self.version(&replica) == other.version(&replica))
    }

    fn dominates_except(&self, other: &Self, except: &NodeId) -> bool {
        self.all_replicas(other)
            .into_iter()
            .filter(|replica| replica != except)
            .all(|replica| self.version(&replica) >= other.version(&replica))
    }

    fn dominates(&self, other: &Self) -> bool {
        self.all_replicas(other)
            .into_iter()
            .all(|replica| self.version(&replica) >= other.version(&replica))
    }

    fn all_replicas(&self, other: &Self) -> BTreeSet<NodeId> {
        self.versions
            .keys()
            .chain(other.versions.keys())
            .cloned()
            .collect()
    }
}

/// Digest exchanged during anti-entropy to detect CRDT frontier divergence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AntiEntropyDigest {
    steward: NodeId,
    frontier: ReplicaVersionVector,
}

impl AntiEntropyDigest {
    /// Steward that emitted this digest.
    #[must_use]
    pub fn steward(&self) -> &NodeId {
        &self.steward
    }

    /// Converged replica frontier advertised by the digest.
    #[must_use]
    pub fn frontier(&self) -> &ReplicaVersionVector {
        &self.frontier
    }
}

/// Propagation mode used for CRDT control metadata exchange.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PropagationMode {
    /// Peer is only one local step behind, so a narrow incremental delta is
    /// sufficient.
    Incremental,
    /// Peer is missing history or reconnecting after a partition, so send a
    /// full anti-entropy snapshot encoded as a CRDT delta from the empty state.
    AntiEntropy,
}

/// Delta envelope exchanged between stewards and relays.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PropagationEnvelope<D> {
    steward: NodeId,
    frontier: ReplicaVersionVector,
    mode: PropagationMode,
    delta: D,
}

impl<D> PropagationEnvelope<D> {
    /// Steward that emitted this envelope.
    #[must_use]
    pub fn steward(&self) -> &NodeId {
        &self.steward
    }

    /// Replica frontier carried by this envelope.
    #[must_use]
    pub fn frontier(&self) -> &ReplicaVersionVector {
        &self.frontier
    }

    /// Propagation mode for this envelope.
    #[must_use]
    pub const fn mode(&self) -> PropagationMode {
        self.mode
    }

    /// Delta payload carried by this envelope.
    #[must_use]
    pub fn delta(&self) -> &D {
        &self.delta
    }
}

/// Result of applying a propagation envelope to a local replica.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PropagationApply {
    /// Envelope advanced local convergence state.
    Applied,
    /// Envelope was already covered by local state.
    AlreadySatisfied,
    /// Envelope could not be applied incrementally and anti-entropy repair is
    /// now required.
    NeedsAntiEntropy,
}

/// Deterministic propagation helper for non-authoritative control CRDTs.
///
/// The propagation path stays optimistic when a peer is only one local version
/// behind the current steward. If a relay gap or partition is detected, the
/// replica switches to anti-entropy mode and emits a compressed snapshot delta
/// from the empty state to restore convergence.
#[derive(Debug, Clone, PartialEq)]
pub struct CrdtPropagationReplica<T: JoinSemilattice + Default> {
    steward: NodeId,
    state: T,
    frontier: ReplicaVersionVector,
    last_local_update: Option<(u64, T::Delta)>,
    repair_needed: BTreeMap<NodeId, u64>,
}

impl<T> CrdtPropagationReplica<T>
where
    T: JoinSemilattice + Default,
{
    /// Create a new empty propagation replica for `steward`.
    #[must_use]
    pub fn new(steward: NodeId) -> Self {
        Self {
            steward,
            state: T::default(),
            frontier: ReplicaVersionVector::default(),
            last_local_update: None,
            repair_needed: BTreeMap::new(),
        }
    }

    /// Steward identity for this replica.
    #[must_use]
    pub fn steward(&self) -> &NodeId {
        &self.steward
    }

    /// Current converged CRDT state.
    #[must_use]
    pub fn state(&self) -> &T {
        &self.state
    }

    /// Current replica frontier.
    #[must_use]
    pub fn frontier(&self) -> &ReplicaVersionVector {
        &self.frontier
    }

    /// Return the current anti-entropy digest.
    #[must_use]
    pub fn digest(&self) -> AntiEntropyDigest {
        AntiEntropyDigest {
            steward: self.steward.clone(),
            frontier: self.frontier.clone(),
        }
    }

    /// Whether a remote origin has been marked for anti-entropy repair.
    #[must_use]
    pub fn needs_anti_entropy(&self) -> bool {
        !self.repair_needed.is_empty()
    }

    /// Record a local mutation and produce an incremental propagation envelope.
    pub fn mutate<F>(&mut self, mutate: F) -> Option<PropagationEnvelope<T::Delta>>
    where
        F: FnOnce(&mut T),
    {
        let mut updated = self.state.clone();
        mutate(&mut updated);
        self.record_local_state(updated)
    }

    /// Record a new local CRDT state and produce an incremental envelope.
    pub fn record_local_state(&mut self, updated: T) -> Option<PropagationEnvelope<T::Delta>> {
        let delta = updated.delta(&self.state);
        if T::delta_is_empty(&delta) {
            return None;
        }

        self.state = updated;
        let version = self.frontier.advance(&self.steward);
        self.last_local_update = Some((version, delta.clone()));

        Some(PropagationEnvelope {
            steward: self.steward.clone(),
            frontier: self.frontier.clone(),
            mode: PropagationMode::Incremental,
            delta,
        })
    }

    /// Prepare the best envelope for a peer with `digest`.
    #[must_use]
    pub fn prepare_for(&self, digest: &AntiEntropyDigest) -> Option<PropagationEnvelope<T::Delta>> {
        if self.frontier == digest.frontier {
            return None;
        }

        if self.can_send_incremental(digest) {
            let (_, delta) = self.last_local_update.as_ref()?;
            return Some(PropagationEnvelope {
                steward: self.steward.clone(),
                frontier: self.frontier.clone(),
                mode: PropagationMode::Incremental,
                delta: delta.clone(),
            });
        }

        self.snapshot_envelope()
    }

    /// Encode the full current state as an anti-entropy snapshot envelope.
    #[must_use]
    pub fn snapshot_envelope(&self) -> Option<PropagationEnvelope<T::Delta>> {
        let delta = self.state.delta(&T::default());
        if T::delta_is_empty(&delta) {
            return None;
        }

        Some(PropagationEnvelope {
            steward: self.steward.clone(),
            frontier: self.frontier.clone(),
            mode: PropagationMode::AntiEntropy,
            delta,
        })
    }

    /// Apply a remote propagation envelope.
    pub fn apply(&mut self, envelope: &PropagationEnvelope<T::Delta>) -> PropagationApply {
        match envelope.mode {
            PropagationMode::Incremental => self.apply_incremental(envelope),
            PropagationMode::AntiEntropy => self.apply_snapshot(envelope),
        }
    }

    fn apply_incremental(&mut self, envelope: &PropagationEnvelope<T::Delta>) -> PropagationApply {
        let remote_version = envelope.frontier.version(&envelope.steward);
        let local_version = self.frontier.version(&envelope.steward);

        if remote_version <= local_version && self.frontier.dominates(&envelope.frontier) {
            return PropagationApply::AlreadySatisfied;
        }

        let expected_next = local_version.saturating_add(1);
        if remote_version != expected_next
            || !self
                .frontier
                .dominates_except(&envelope.frontier, &envelope.steward)
        {
            self.repair_needed
                .insert(envelope.steward.clone(), remote_version);
            return PropagationApply::NeedsAntiEntropy;
        }

        if !self.state.apply_delta(&envelope.delta) {
            self.repair_needed
                .insert(envelope.steward.clone(), remote_version);
            return PropagationApply::NeedsAntiEntropy;
        }
        self.frontier.merge(&envelope.frontier);
        self.repair_needed.remove(&envelope.steward);
        PropagationApply::Applied
    }

    fn apply_snapshot(&mut self, envelope: &PropagationEnvelope<T::Delta>) -> PropagationApply {
        if self.frontier.dominates(&envelope.frontier) {
            return PropagationApply::AlreadySatisfied;
        }

        if !self.state.apply_delta(&envelope.delta) {
            self.repair_needed.insert(
                envelope.steward.clone(),
                envelope.frontier.version(&envelope.steward),
            );
            return PropagationApply::NeedsAntiEntropy;
        }
        self.frontier.merge(&envelope.frontier);
        for replica in envelope.frontier.versions.keys() {
            self.repair_needed.remove(replica);
        }
        PropagationApply::Applied
    }

    fn can_send_incremental(&self, digest: &AntiEntropyDigest) -> bool {
        let Some((version, _)) = &self.last_local_update else {
            return false;
        };

        digest.frontier.version(&self.steward).saturating_add(1) == *version
            && self.frontier.same_except(&digest.frontier, &self.steward)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct ReplicaCounter {
    positive: BTreeMap<NodeId, u64>,
    negative: BTreeMap<NodeId, u64>,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct ReplicaCounterDelta {
    positive: BTreeMap<NodeId, u64>,
    negative: BTreeMap<NodeId, u64>,
}

impl ReplicaCounter {
    fn increment(&mut self, replica: &NodeId, amount: u64) {
        if amount == 0 {
            return;
        }
        let entry = self.positive.entry(replica.clone()).or_insert(0);
        *entry = (*entry).saturating_add(amount);
    }

    fn decrement(&mut self, replica: &NodeId, amount: u64) {
        if amount == 0 {
            return;
        }
        let entry = self.negative.entry(replica.clone()).or_insert(0);
        *entry = (*entry).saturating_add(amount);
    }

    fn value(&self) -> u64 {
        let positive = self
            .positive
            .values()
            .fold(0_u64, |total, value| total.saturating_add(*value));
        let negative = self
            .negative
            .values()
            .fold(0_u64, |total, value| total.saturating_add(*value));
        positive.saturating_sub(negative)
    }

    fn merge_map(target: &mut BTreeMap<NodeId, u64>, source: &BTreeMap<NodeId, u64>) {
        for (replica, value) in source {
            let entry = target.entry(replica.clone()).or_insert(0);
            *entry = (*entry).max(*value);
        }
    }

    fn delta_map(
        current: &BTreeMap<NodeId, u64>,
        baseline: &BTreeMap<NodeId, u64>,
    ) -> BTreeMap<NodeId, u64> {
        current
            .iter()
            .filter_map(|(replica, value)| {
                let baseline_value = baseline.get(replica).copied().unwrap_or(0);
                (*value > baseline_value).then_some((replica.clone(), *value))
            })
            .collect()
    }

    fn apply_map(target: &mut BTreeMap<NodeId, u64>, delta: &BTreeMap<NodeId, u64>) {
        Self::merge_map(target, delta);
    }
}

impl JoinSemilattice for ReplicaCounter {
    type Delta = ReplicaCounterDelta;

    fn merge(&mut self, other: &Self) {
        Self::merge_map(&mut self.positive, &other.positive);
        Self::merge_map(&mut self.negative, &other.negative);
    }

    fn delta(&self, baseline: &Self) -> Self::Delta {
        ReplicaCounterDelta {
            positive: Self::delta_map(&self.positive, &baseline.positive),
            negative: Self::delta_map(&self.negative, &baseline.negative),
        }
    }

    fn apply_delta(&mut self, delta: &Self::Delta) -> bool {
        Self::apply_map(&mut self.positive, &delta.positive);
        Self::apply_map(&mut self.negative, &delta.negative);
        true
    }
}

/// Delta-CRDT summary of subscriber interest counts by subject pattern.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct InterestSummary {
    counts: BTreeMap<SubjectPattern, ReplicaCounter>,
}

/// Sparse delta for [`InterestSummary`].
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct InterestSummaryDelta {
    counts: BTreeMap<SubjectPattern, ReplicaCounterDelta>,
}

impl InterestSummary {
    /// Register one subscriber interest for `pattern` on `replica`.
    pub fn subscribe(&mut self, replica: &NodeId, pattern: SubjectPattern) {
        self.counts
            .entry(pattern)
            .or_default()
            .increment(replica, 1);
    }

    /// Remove one subscriber interest for `pattern` on `replica`.
    ///
    /// Only decrements when the pattern already has local state (from a prior
    /// subscribe or an inbound delta).  Calling unsubscribe on a pattern that
    /// has never been observed is a no-op, preventing unbounded growth of
    /// zero-value entries from spurious or adversarial unsubscribe calls.
    pub fn unsubscribe(&mut self, replica: &NodeId, pattern: &SubjectPattern) {
        if let Some(counter) = self.counts.get_mut(pattern) {
            counter.decrement(replica, 1);
        }
    }

    /// Current converged subscriber count for `pattern`.
    #[must_use]
    pub fn interest_count(&self, pattern: &SubjectPattern) -> u64 {
        self.counts.get(pattern).map_or(0, ReplicaCounter::value)
    }
}

impl JoinSemilattice for InterestSummary {
    type Delta = InterestSummaryDelta;

    fn merge(&mut self, other: &Self) {
        for (pattern, counter) in &other.counts {
            self.counts
                .entry(pattern.clone())
                .or_default()
                .merge(counter);
        }
    }

    fn delta(&self, baseline: &Self) -> Self::Delta {
        let counts = self
            .counts
            .iter()
            .filter_map(|(pattern, counter)| {
                let baseline_counter = baseline.counts.get(pattern).cloned().unwrap_or_default();
                let delta = counter.delta(&baseline_counter);
                (!delta.positive.is_empty() || !delta.negative.is_empty())
                    .then_some((pattern.clone(), delta))
            })
            .collect();
        InterestSummaryDelta { counts }
    }

    fn apply_delta(&mut self, delta: &Self::Delta) -> bool {
        for (pattern, counter_delta) in &delta.counts {
            self.counts
                .entry(pattern.clone())
                .or_default()
                .apply_delta(counter_delta);
        }
        true
    }
}

/// Monotone coarse cursor position for one consumer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CursorMark {
    offset: u64,
    checkpoint_unix_ms: u64,
    steward: NodeId,
}

impl CursorMark {
    /// Create a new coarse cursor mark.
    #[must_use]
    pub fn new(offset: u64, checkpoint_unix_ms: u64, steward: NodeId) -> Self {
        Self {
            offset,
            checkpoint_unix_ms,
            steward,
        }
    }

    /// Highest fully observed offset represented by this mark.
    #[must_use]
    pub const fn offset(&self) -> u64 {
        self.offset
    }

    /// Capture timestamp for the mark.
    #[must_use]
    pub const fn checkpoint_unix_ms(&self) -> u64 {
        self.checkpoint_unix_ms
    }

    /// Steward that emitted this mark.
    #[must_use]
    pub fn steward(&self) -> &NodeId {
        &self.steward
    }

    fn is_newer_than(&self, other: &Self) -> bool {
        (self.offset, self.checkpoint_unix_ms, self.steward.as_str())
            > (
                other.offset,
                other.checkpoint_unix_ms,
                other.steward.as_str(),
            )
    }
}

/// Delta-CRDT summary of coarse consumer cursor positions.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CursorCheckpoint {
    checkpoints: BTreeMap<String, CursorMark>,
}

/// Sparse delta for [`CursorCheckpoint`].
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CursorCheckpointDelta {
    checkpoints: BTreeMap<String, CursorMark>,
}

impl CursorCheckpoint {
    /// Observe a newer checkpoint for `consumer`.
    pub fn observe(&mut self, consumer: impl Into<String>, mark: CursorMark) {
        let consumer = consumer.into();
        match self.checkpoints.get_mut(&consumer) {
            Some(existing) if mark.is_newer_than(existing) => *existing = mark,
            None => {
                self.checkpoints.insert(consumer, mark);
            }
            Some(_) => {}
        }
    }

    /// Return the current converged mark for `consumer`.
    #[must_use]
    pub fn checkpoint(&self, consumer: &str) -> Option<&CursorMark> {
        self.checkpoints.get(consumer)
    }
}

impl JoinSemilattice for CursorCheckpoint {
    type Delta = CursorCheckpointDelta;

    fn merge(&mut self, other: &Self) {
        for (consumer, mark) in &other.checkpoints {
            self.observe(consumer.clone(), mark.clone());
        }
    }

    fn delta(&self, baseline: &Self) -> Self::Delta {
        let checkpoints = self
            .checkpoints
            .iter()
            .filter_map(
                |(consumer, mark)| match baseline.checkpoints.get(consumer) {
                    Some(existing) if !mark.is_newer_than(existing) => None,
                    _ => Some((consumer.clone(), mark.clone())),
                },
            )
            .collect();
        CursorCheckpointDelta { checkpoints }
    }

    fn apply_delta(&mut self, delta: &Self::Delta) -> bool {
        for (consumer, mark) in &delta.checkpoints {
            self.observe(consumer.clone(), mark.clone());
        }
        true
    }
}

/// Coarse membership state used for non-authoritative control hints.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum MembershipState {
    /// No useful information yet.
    Unknown,
    /// Replica is joining the fabric.
    Joining,
    /// Replica is healthy and serving.
    Healthy,
    /// Replica is reachable but degraded.
    Degraded,
    /// Replica is draining or preparing to leave.
    Leaving,
    /// Replica has been removed from the non-authoritative view.
    Removed,
}

/// Versioned non-authoritative membership record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MembershipRecord {
    version: u64,
    state: MembershipState,
    last_heartbeat_unix_ms: u64,
    load_per_mille: u16,
}

impl MembershipRecord {
    /// Construct a new membership record snapshot.
    #[must_use]
    pub const fn new(
        version: u64,
        state: MembershipState,
        last_heartbeat_unix_ms: u64,
        load_per_mille: u16,
    ) -> Self {
        Self {
            version,
            state,
            last_heartbeat_unix_ms,
            load_per_mille,
        }
    }

    /// Monotone version stamp for this record.
    #[must_use]
    pub const fn version(&self) -> u64 {
        self.version
    }

    /// Current coarse membership state.
    #[must_use]
    pub const fn state(&self) -> MembershipState {
        self.state
    }

    /// Last heartbeat carried by the record.
    #[must_use]
    pub const fn last_heartbeat_unix_ms(&self) -> u64 {
        self.last_heartbeat_unix_ms
    }

    /// Advertised load in per-mille units.
    #[must_use]
    pub const fn load_per_mille(&self) -> u16 {
        self.load_per_mille
    }

    fn is_newer_than(&self, other: &Self) -> bool {
        (
            self.version,
            self.last_heartbeat_unix_ms,
            self.state,
            self.load_per_mille,
        ) > (
            other.version,
            other.last_heartbeat_unix_ms,
            other.state,
            other.load_per_mille,
        )
    }
}

/// Delta-CRDT view of non-authoritative replica membership.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct MembershipView {
    records: BTreeMap<NodeId, MembershipRecord>,
}

/// Sparse delta for [`MembershipView`].
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct MembershipViewDelta {
    records: BTreeMap<NodeId, MembershipRecord>,
}

impl MembershipView {
    /// Observe a versioned membership record for `node`.
    pub fn observe(&mut self, node: NodeId, record: MembershipRecord) {
        match self.records.get_mut(&node) {
            Some(existing) if record.is_newer_than(existing) => *existing = record,
            None => {
                self.records.insert(node, record);
            }
            Some(_) => {}
        }
    }

    /// Return the current converged record for `node`.
    #[must_use]
    pub fn record(&self, node: &NodeId) -> Option<&MembershipRecord> {
        self.records.get(node)
    }
}

impl JoinSemilattice for MembershipView {
    type Delta = MembershipViewDelta;

    fn merge(&mut self, other: &Self) {
        for (node, record) in &other.records {
            self.observe(node.clone(), record.clone());
        }
    }

    fn delta(&self, baseline: &Self) -> Self::Delta {
        let records = self
            .records
            .iter()
            .filter_map(|(node, record)| match baseline.records.get(node) {
                Some(existing) if !record.is_newer_than(existing) => None,
                _ => Some((node.clone(), record.clone())),
            })
            .collect();
        MembershipViewDelta { records }
    }

    fn apply_delta(&mut self, delta: &Self::Delta) -> bool {
        for (node, record) in &delta.records {
            self.observe(node.clone(), record.clone());
        }
        true
    }
}

/// Bucketed delta-CRDT sketch for lag and load observations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LagSketch {
    bucket_width: u64,
    buckets: BTreeMap<u64, ReplicaCounter>,
}

/// Sparse delta for [`LagSketch`].
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct LagSketchDelta {
    bucket_width: u64,
    buckets: BTreeMap<u64, ReplicaCounterDelta>,
}

impl LagSketch {
    /// Create a new sketch with a deterministic `bucket_width`.
    #[must_use]
    pub fn new(bucket_width: u64) -> Self {
        Self {
            bucket_width: bucket_width.max(1),
            buckets: BTreeMap::new(),
        }
    }

    /// Sketch bucket width in units of observed lag.
    #[must_use]
    pub const fn bucket_width(&self) -> u64 {
        self.bucket_width
    }

    fn bucket_index(&self, lag: u64) -> u64 {
        lag / self.bucket_width
    }

    fn bucket_midpoint(&self, bucket: u64) -> u64 {
        bucket
            .saturating_mul(self.bucket_width)
            .saturating_add(self.bucket_width / 2)
    }

    /// Record one lag observation for `replica`.
    pub fn observe(&mut self, replica: &NodeId, lag: u64) {
        self.buckets
            .entry(self.bucket_index(lag))
            .or_default()
            .increment(replica, 1);
    }

    /// Compatibility alias for recording one lag observation.
    pub fn record(&mut self, replica: &NodeId, lag: u64) {
        self.observe(replica, lag);
    }

    /// Total number of samples represented by the sketch.
    #[must_use]
    pub fn total_samples(&self) -> u64 {
        self.buckets.values().fold(0_u64, |total, counter| {
            total.saturating_add(counter.value())
        })
    }

    /// Number of populated buckets in the sketch.
    #[must_use]
    pub fn bucket_count(&self) -> usize {
        self.buckets.len()
    }

    /// Midpoint-based mean estimate.
    #[must_use]
    pub fn estimated_mean(&self) -> Option<u64> {
        let total_samples = self.total_samples();
        if total_samples == 0 {
            return None;
        }

        let weighted_sum = self
            .buckets
            .iter()
            .fold(0_u128, |total, (bucket, counter)| {
                total.saturating_add(
                    u128::from(self.bucket_midpoint(*bucket))
                        .saturating_mul(u128::from(counter.value())),
                )
            });
        Some((weighted_sum / u128::from(total_samples)) as u64)
    }

    /// Worst-case absolute error of [`Self::estimated_mean`] under midpoint
    /// reconstruction.
    #[must_use]
    pub const fn max_mean_error_bound(&self) -> u64 {
        self.bucket_width / 2
    }
}

impl Default for LagSketch {
    fn default() -> Self {
        Self::new(16)
    }
}

impl JoinSemilattice for LagSketch {
    type Delta = LagSketchDelta;

    fn merge(&mut self, other: &Self) {
        if self.bucket_width != other.bucket_width {
            // Adopt the peer's width when the local state is empty (fresh
            // replica).  Once data exists the width is locked in and
            // mismatched peers are silently ignored — this is a deployment
            // configuration error, not something merge can resolve.
            if self.buckets.is_empty() {
                self.bucket_width = other.bucket_width;
            } else {
                return;
            }
        }
        for (bucket, counter) in &other.buckets {
            self.buckets.entry(*bucket).or_default().merge(counter);
        }
    }

    fn delta(&self, baseline: &Self) -> Self::Delta {
        let buckets = if self.bucket_width == baseline.bucket_width {
            self.buckets
                .iter()
                .filter_map(|(bucket, counter)| {
                    let baseline_counter =
                        baseline.buckets.get(bucket).cloned().unwrap_or_default();
                    let delta = counter.delta(&baseline_counter);
                    (!delta.positive.is_empty() || !delta.negative.is_empty())
                        .then_some((*bucket, delta))
                })
                .collect()
        } else {
            self.buckets
                .iter()
                .map(|(bucket, counter)| (*bucket, counter.delta(&ReplicaCounter::default())))
                .collect()
        };
        LagSketchDelta {
            bucket_width: self.bucket_width,
            buckets,
        }
    }

    fn delta_is_empty(delta: &Self::Delta) -> bool {
        delta.buckets.is_empty()
    }

    fn apply_delta(&mut self, delta: &Self::Delta) -> bool {
        if self.bucket_width != delta.bucket_width {
            // Adopt the incoming width when the local state is empty (fresh
            // replica joining an established cluster).  When local data
            // already exists, return true to break the anti-entropy retry
            // loop — the mismatch is a configuration error that retrying
            // will never resolve.
            if self.buckets.is_empty() {
                self.bucket_width = delta.bucket_width;
            } else {
                return true;
            }
        }
        for (bucket, counter_delta) in &delta.buckets {
            self.buckets
                .entry(*bucket)
                .or_default()
                .apply_delta(counter_delta);
        }
        true
    }
}

/// Windowed delta-CRDT aggregate of advisory counts and rates.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AdvisoryAggregate {
    window_width_ms: u64,
    windows: BTreeMap<u64, BTreeMap<String, ReplicaCounter>>,
}

/// Sparse delta for [`AdvisoryAggregate`].
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct AdvisoryAggregateDelta {
    window_width_ms: u64,
    windows: BTreeMap<u64, BTreeMap<String, ReplicaCounterDelta>>,
}

impl AdvisoryAggregate {
    /// Create a new aggregate with fixed `window_width_ms`.
    #[must_use]
    pub fn new(window_width_ms: u64) -> Self {
        Self {
            window_width_ms: window_width_ms.max(1),
            windows: BTreeMap::new(),
        }
    }

    /// Width of each advisory aggregation window.
    #[must_use]
    pub const fn window_width_ms(&self) -> u64 {
        self.window_width_ms
    }

    fn window_start(&self, ts_unix_ms: u64) -> u64 {
        ts_unix_ms - (ts_unix_ms % self.window_width_ms)
    }

    /// Record one advisory kind observation in the corresponding window.
    pub fn record_kind(&mut self, replica: &NodeId, advisory_kind: &str, ts_unix_ms: u64) {
        self.windows
            .entry(self.window_start(ts_unix_ms))
            .or_default()
            .entry(advisory_kind.to_owned())
            .or_default()
            .increment(replica, 1);
    }

    /// Prune windows strictly older than the window containing `cutoff_unix_ms`.
    ///
    /// This is an explicit retention hook so callers can bound memory only once
    /// a cutoff is known to be causally safe for every steward.
    pub fn prune_before(&mut self, cutoff_unix_ms: u64) {
        let first_retained_window = self.window_start(cutoff_unix_ms);
        self.windows
            .retain(|window_start, _| *window_start >= first_retained_window);
    }

    /// Return the converged count for `advisory_kind` in `window_start`.
    #[must_use]
    pub fn count(&self, window_start: u64, advisory_kind: &str) -> u64 {
        self.windows
            .get(&window_start)
            .and_then(|kinds| kinds.get(advisory_kind))
            .map_or(0, ReplicaCounter::value)
    }

    /// Return the converged per-second rate for `advisory_kind` in
    /// `window_start`.
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn rate_per_second(&self, window_start: u64, advisory_kind: &str) -> f64 {
        let count = self.count(window_start, advisory_kind) as f64;
        count * 1000.0 / self.window_width_ms as f64
    }
}

impl Default for AdvisoryAggregate {
    fn default() -> Self {
        Self::new(60_000)
    }
}

impl JoinSemilattice for AdvisoryAggregate {
    type Delta = AdvisoryAggregateDelta;

    fn merge(&mut self, other: &Self) {
        if self.window_width_ms != other.window_width_ms {
            if self.windows.is_empty() {
                self.window_width_ms = other.window_width_ms;
            } else {
                return;
            }
        }
        for (window_start, kinds) in &other.windows {
            let window = self.windows.entry(*window_start).or_default();
            for (kind, counter) in kinds {
                window.entry(kind.clone()).or_default().merge(counter);
            }
        }
    }

    fn delta(&self, baseline: &Self) -> Self::Delta {
        let windows = if self.window_width_ms == baseline.window_width_ms {
            self.windows
                .iter()
                .filter_map(|(window_start, kinds)| {
                    let mut delta_kinds = BTreeMap::new();
                    for (kind, counter) in kinds {
                        let baseline_counter = baseline
                            .windows
                            .get(window_start)
                            .and_then(|baseline_kinds| baseline_kinds.get(kind))
                            .cloned()
                            .unwrap_or_default();
                        let delta = counter.delta(&baseline_counter);
                        if !delta.positive.is_empty() || !delta.negative.is_empty() {
                            delta_kinds.insert(kind.clone(), delta);
                        }
                    }
                    (!delta_kinds.is_empty()).then_some((*window_start, delta_kinds))
                })
                .collect()
        } else {
            self.windows
                .iter()
                .map(|(window_start, kinds)| {
                    let delta_kinds = kinds
                        .iter()
                        .map(|(kind, counter)| {
                            (kind.clone(), counter.delta(&ReplicaCounter::default()))
                        })
                        .collect();
                    (*window_start, delta_kinds)
                })
                .collect()
        };
        AdvisoryAggregateDelta {
            window_width_ms: self.window_width_ms,
            windows,
        }
    }

    fn delta_is_empty(delta: &Self::Delta) -> bool {
        delta.windows.is_empty()
    }

    fn apply_delta(&mut self, delta: &Self::Delta) -> bool {
        if self.window_width_ms != delta.window_width_ms {
            if self.windows.is_empty() {
                self.window_width_ms = delta.window_width_ms;
            } else {
                return true;
            }
        }
        for (window_start, kinds) in &delta.windows {
            let window = self.windows.entry(*window_start).or_default();
            for (kind, counter_delta) in kinds {
                window
                    .entry(kind.clone())
                    .or_default()
                    .apply_delta(counter_delta);
            }
        }
        true
    }
}

// ---------------------------------------------------------------------------
// Advisory types with FrankenSuite evidence
// ---------------------------------------------------------------------------

/// Classification of control-plane advisory events.
///
/// Each variant represents a material control-plane decision or state change
/// that operators need full provenance for — not just "gateway detached" but
/// *why*, *what edges were affected*, and *what evidence justified it*.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ControlAdvisoryType {
    /// A capability graph edge was added, removed, or modified.
    CapabilityGraphChange {
        /// Subject patterns whose capability edges were affected.
        affected_subjects: Vec<SubjectPattern>,
        /// Human-readable description of what changed.
        description: String,
    },
    /// An obligation was transferred, aborted, or scheduled for replay.
    ObligationTransfer {
        /// The kind of obligation lifecycle event.
        action: ObligationTransferAction,
        /// Subject carrying the obligation.
        subject: Subject,
    },
    /// A policy decision was made (e.g. failover, load-shed, drain).
    PolicyDecision {
        /// Name of the policy that made the decision.
        policy_name: String,
        /// The action chosen by the policy.
        action_chosen: String,
        /// Why this action was chosen (human-readable).
        justification: String,
    },
    /// A structured evidence record was emitted for operator review.
    EvidenceRecord {
        /// Stable identifier for the emitted evidence record.
        evidence_id: String,
        /// Subsystem/component that produced the evidence.
        component: String,
        /// Action or decision summarized by the evidence.
        action: String,
        /// Human-readable summary of why the evidence matters.
        summary: String,
    },
    /// A break-glass recovery action was taken.
    BreakGlassActivation {
        /// Reason the break-glass path was triggered.
        reason: String,
    },
}

impl ControlAdvisoryType {
    /// Stable advisory kind name used for filtering and serialized payloads.
    #[must_use]
    pub const fn kind(&self) -> &'static str {
        match self {
            Self::CapabilityGraphChange { .. } => "capability_graph_change",
            Self::ObligationTransfer { .. } => "obligation_transfer",
            Self::PolicyDecision { .. } => "policy_decision",
            Self::EvidenceRecord { .. } => "evidence_record",
            Self::BreakGlassActivation { .. } => "break_glass_activation",
        }
    }
}

/// Obligation lifecycle actions that produce advisories.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ObligationTransferAction {
    /// Obligation custody was transferred to another handler.
    Transferred,
    /// Obligation was aborted (could not be fulfilled).
    Aborted,
    /// Obligation was scheduled for replay/retry.
    ReplayScheduled,
}

impl fmt::Display for ObligationTransferAction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Transferred => write!(f, "transferred"),
            Self::Aborted => write!(f, "aborted"),
            Self::ReplayScheduled => write!(f, "replay_scheduled"),
        }
    }
}

/// A control-plane advisory with full FrankenSuite evidence provenance.
///
/// This is the primary artifact emitted when a material control-plane
/// decision occurs.  Operators get decision provenance — not just "what
/// happened" but "why, with what evidence, and what was the alternative".
#[derive(Debug, Clone)]
pub struct ControlAdvisory {
    /// Classification of the advisory event.
    pub advisory_type: ControlAdvisoryType,
    /// System subject family this advisory belongs to.
    pub family: SystemSubjectFamily,
    /// Subject the advisory should be published on.
    pub subject: Subject,
    /// Trace context linking this advisory to a distributed trace.
    pub trace_id: TraceId,
    /// Decision identifier linking to the FrankenSuite decision record.
    pub decision_id: DecisionId,
    /// Unix timestamp in milliseconds when the advisory was created.
    pub ts_unix_ms: u64,
    /// The full decision audit entry with posterior, losses, and
    /// calibration data.  `None` for advisories that are pure
    /// notifications without a decision contract evaluation.
    pub decision_audit: Option<DecisionAuditEntry>,
}

/// Typed filter for advisory subscription and operator views.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ControlAdvisoryFilter {
    /// Limit matches to one control-plane family.
    pub family: Option<SystemSubjectFamily>,
    /// Limit matches to a single advisory kind.
    pub advisory_kind: Option<&'static str>,
    /// If true, only advisories carrying FrankenSuite decision provenance
    /// should match.
    pub require_decision_provenance: bool,
}

impl ControlAdvisory {
    fn derived_evidence_id(family: SystemSubjectFamily, audit: &DecisionAuditEntry) -> String {
        format!(
            "control:{}:{}:{}",
            family.name().to_ascii_lowercase(),
            audit.decision_id,
            audit.ts_unix_ms
        )
    }

    /// Create a new advisory from a decision outcome.
    ///
    /// This is the preferred constructor when a FrankenSuite decision
    /// contract has been evaluated.
    #[must_use]
    pub fn from_decision(
        advisory_type: ControlAdvisoryType,
        family: SystemSubjectFamily,
        subject: Subject,
        outcome: &DecisionOutcome,
    ) -> Self {
        let audit = &outcome.audit_entry;
        Self {
            advisory_type,
            family,
            subject,
            trace_id: audit.trace_id,
            decision_id: audit.decision_id,
            ts_unix_ms: audit.ts_unix_ms,
            decision_audit: Some(audit.clone()),
        }
    }

    /// Create an explicit evidence-record advisory from a decision outcome.
    ///
    /// Use this when operators need an advisory that names the evidence bundle
    /// directly rather than inferring it from a policy-decision payload.
    #[must_use]
    pub fn evidence_record(
        family: SystemSubjectFamily,
        subject: Subject,
        outcome: &DecisionOutcome,
        summary: impl Into<String>,
    ) -> Self {
        let audit = &outcome.audit_entry;
        Self::from_decision(
            ControlAdvisoryType::EvidenceRecord {
                evidence_id: Self::derived_evidence_id(family, audit),
                component: audit.contract_name.clone(),
                action: audit.action_chosen.clone(),
                summary: summary.into(),
            },
            family,
            subject,
            outcome,
        )
    }

    /// Create a notification-only advisory (no decision contract).
    #[must_use]
    pub fn notification(
        advisory_type: ControlAdvisoryType,
        family: SystemSubjectFamily,
        subject: Subject,
        trace_id: TraceId,
        ts_unix_ms: u64,
    ) -> Self {
        Self {
            advisory_type,
            family,
            subject,
            trace_id,
            decision_id: DecisionId::from_raw(0),
            ts_unix_ms,
            decision_audit: None,
        }
    }

    /// Convert the decision audit (if present) to an evidence ledger entry.
    ///
    /// Returns `None` if this advisory has no associated decision audit.
    #[must_use]
    pub fn to_evidence_ledger(&self) -> Option<EvidenceLedger> {
        self.decision_audit
            .as_ref()
            .map(DecisionAuditEntry::to_evidence_ledger)
    }

    /// Stable evidence identifier for this advisory when provenance exists.
    #[must_use]
    pub fn evidence_id(&self) -> Option<String> {
        match &self.advisory_type {
            ControlAdvisoryType::EvidenceRecord { evidence_id, .. } => Some(evidence_id.clone()),
            _ => self
                .decision_audit
                .as_ref()
                .map(|audit| Self::derived_evidence_id(self.family, audit)),
        }
    }

    /// Whether this advisory carries decision provenance.
    #[must_use]
    pub fn has_decision_provenance(&self) -> bool {
        self.decision_audit.is_some()
    }

    /// Returns `true` when this advisory matches the given typed filter.
    #[must_use]
    pub fn matches_filter(&self, filter: &ControlAdvisoryFilter) -> bool {
        if let Some(family) = filter.family
            && self.family != family
        {
            return false;
        }
        if let Some(kind) = filter.advisory_kind
            && self.advisory_type.kind() != kind
        {
            return false;
        }
        if filter.require_decision_provenance && !self.has_decision_provenance() {
            return false;
        }
        true
    }

    /// Serialize the advisory payload to JSON bytes for publication.
    #[must_use]
    pub fn to_json_payload(&self) -> Vec<u8> {
        // Keep the payload deterministic, but preserve typed values and
        // variant-specific details instead of flattening everything into
        // string fields.
        let mut payload = BTreeMap::new();
        payload.insert(
            "decision_id",
            serde_json::Value::String(format!("{}", self.decision_id)),
        );
        payload.insert(
            "family",
            serde_json::Value::String(self.family.name().to_owned()),
        );
        payload.insert(
            "has_decision_provenance",
            serde_json::Value::Bool(self.has_decision_provenance()),
        );
        payload.insert(
            "subject",
            serde_json::Value::String(self.subject.as_str().to_owned()),
        );
        payload.insert(
            "trace_id",
            serde_json::Value::String(format!("{}", self.trace_id)),
        );
        payload.insert("ts_unix_ms", serde_json::Value::from(self.ts_unix_ms));
        payload.insert(
            "type",
            serde_json::Value::String(self.advisory_type.kind().to_owned()),
        );
        if let Some(evidence_id) = self.evidence_id() {
            payload.insert("evidence_id", serde_json::Value::String(evidence_id));
        }

        match &self.advisory_type {
            ControlAdvisoryType::CapabilityGraphChange {
                affected_subjects,
                description,
            } => {
                payload.insert(
                    "affected_subjects",
                    serde_json::Value::Array(
                        affected_subjects
                            .iter()
                            .map(|pattern| serde_json::Value::String(pattern.as_str().to_owned()))
                            .collect(),
                    ),
                );
                payload.insert(
                    "description",
                    serde_json::Value::String(description.clone()),
                );
            }
            ControlAdvisoryType::ObligationTransfer { action, subject } => {
                payload.insert("action", serde_json::Value::String(action.to_string()));
                payload.insert(
                    "obligation_subject",
                    serde_json::Value::String(subject.as_str().to_owned()),
                );
            }
            ControlAdvisoryType::PolicyDecision {
                policy_name,
                action_chosen,
                justification,
            } => {
                payload.insert(
                    "policy_name",
                    serde_json::Value::String(policy_name.clone()),
                );
                payload.insert(
                    "action_chosen",
                    serde_json::Value::String(action_chosen.clone()),
                );
                payload.insert(
                    "justification",
                    serde_json::Value::String(justification.clone()),
                );
            }
            ControlAdvisoryType::EvidenceRecord {
                component,
                action,
                summary,
                ..
            } => {
                payload.insert("component", serde_json::Value::String(component.clone()));
                payload.insert("action", serde_json::Value::String(action.clone()));
                payload.insert("summary", serde_json::Value::String(summary.clone()));
            }
            ControlAdvisoryType::BreakGlassActivation { reason } => {
                payload.insert("reason", serde_json::Value::String(reason.clone()));
            }
        }

        serde_json::to_vec(&payload).unwrap_or_default()
    }
}

// ---------------------------------------------------------------------------
// Control handler
// ---------------------------------------------------------------------------

/// Outcome of a control handler invocation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ControlOutcome {
    /// Handler processed the event successfully.
    Ok,
    /// Handler processed the event but produced an advisory that should be
    /// published on the given subject.
    Advisory {
        /// Subject for the advisory message.
        subject: Subject,
        /// Opaque advisory payload (JSON-encoded for interoperability).
        payload: Vec<u8>,
    },
    /// Handler could not process the event within its budget.
    BudgetExhausted,
    /// Handler encountered an error.
    Error {
        /// Human-readable error description.
        message: String,
    },
}

/// Registration record for a single control handler.
///
/// Each control handler is region-owned, which means it participates in
/// structured concurrency: the handler's region must close to quiescence
/// before the parent scope exits.
#[derive(Debug, Clone)]
pub struct ControlHandler {
    /// Unique handler identifier (scoped to the control namespace).
    pub id: ControlHandlerId,
    /// Which system subject family this handler serves.
    pub family: SystemSubjectFamily,
    /// Subject pattern the handler subscribes to within its family.
    pub pattern: SubjectPattern,
    /// Reserved budget for this handler.
    pub budget: ControlBudget,
    /// Advisory damping policy applied to any advisories this handler emits.
    pub damping: AdvisoryDampingPolicy,
    /// Whether this handler is a break-glass recovery handler.
    pub break_glass: bool,
}

/// Opaque identifier for a registered control handler.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ControlHandlerId(u64);

impl ControlHandlerId {
    /// Create a new handler identifier.
    #[must_use]
    pub const fn new(raw: u64) -> Self {
        Self(raw)
    }

    /// Return the raw identifier.
    #[must_use]
    pub const fn raw(self) -> u64 {
        self.0
    }
}

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

/// Tenant/service-scoped control surface under one `$SYS.FABRIC.<FAMILY>` root.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NamespaceControlScope {
    family: SystemSubjectFamily,
    tenant: NamespaceComponent,
    service: NamespaceComponent,
}

impl NamespaceControlScope {
    /// Build a control scope directly from an existing namespace kernel.
    #[must_use]
    pub fn from_namespace(family: SystemSubjectFamily, namespace: &NamespaceKernel) -> Self {
        Self {
            family,
            tenant: namespace.tenant().clone(),
            service: namespace.service().clone(),
        }
    }

    /// Build a validated tenant/service control scope for one system family.
    pub fn new(
        family: SystemSubjectFamily,
        tenant: impl AsRef<str>,
        service: impl AsRef<str>,
    ) -> Result<Self, NamespaceKernelError> {
        Ok(Self {
            family,
            tenant: NamespaceComponent::parse(tenant)?,
            service: NamespaceComponent::parse(service)?,
        })
    }

    /// Return the control family covered by this scope.
    #[must_use]
    pub const fn family(&self) -> SystemSubjectFamily {
        self.family
    }

    /// Return the tenant component.
    #[must_use]
    pub fn tenant(&self) -> &NamespaceComponent {
        &self.tenant
    }

    /// Return the service component.
    #[must_use]
    pub fn service(&self) -> &NamespaceComponent {
        &self.service
    }

    /// Return the namespace-scoped wildcard pattern for this control surface.
    #[must_use]
    pub fn wildcard_pattern(&self) -> SubjectPattern {
        SubjectPattern::new(format!(
            "{}.TENANT.{}.SERVICE.{}.>",
            self.family.prefix(),
            self.tenant,
            self.service
        ))
    }

    /// Return one concrete channel subject inside this control scope.
    pub fn subject(&self, channel: impl AsRef<str>) -> Result<Subject, NamespaceKernelError> {
        let channel = NamespaceComponent::parse(channel)?;
        Ok(Subject::new(format!(
            "{}.TENANT.{}.SERVICE.{}.{}",
            self.family.prefix(),
            self.tenant,
            self.service,
            channel
        )))
    }
}

// ---------------------------------------------------------------------------
// Control namespace registry
// ---------------------------------------------------------------------------

/// Error returned when registering or looking up control handlers.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ControlRegistryError {
    /// The subject pattern is not under `$SYS.FABRIC.`.
    #[error("control subject must be under $SYS.FABRIC.*: got `{pattern}`")]
    InvalidPrefix {
        /// The offending subject pattern.
        pattern: String,
    },
    /// The subject pattern is not scoped to the declared family.
    #[error("control subject `{pattern}` does not belong to family `{family}`")]
    FamilyMismatch {
        /// The declared family for the handler.
        family: SystemSubjectFamily,
        /// The offending subject pattern.
        pattern: String,
    },
    /// A handler with the same ID is already registered.
    #[error("duplicate handler id: {id}")]
    DuplicateId {
        /// The duplicate handler identifier.
        id: ControlHandlerId,
    },
    /// The system subject family is not recognized.
    #[error("unknown system subject family in pattern: `{pattern}`")]
    UnknownFamily {
        /// The unrecognized subject pattern.
        pattern: String,
    },
}

/// Registry of active control handlers.
///
/// The registry owns the set of control handler registrations and provides
/// dispatch lookup by subject.  It does NOT own the handler futures
/// themselves — those live in the runtime's region tree.
#[derive(Debug, Clone)]
pub struct ControlRegistry {
    handlers: BTreeMap<ControlHandlerId, ControlHandler>,
    next_id: u64,
    /// Break-glass handlers are always available, even when the ordinary
    /// fabric is degraded.  They are indexed separately for fast lookup.
    break_glass_ids: Vec<ControlHandlerId>,
}

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

impl ControlRegistry {
    /// Create an empty control registry.
    #[must_use]
    pub fn new() -> Self {
        Self {
            handlers: BTreeMap::new(),
            next_id: 0,
            break_glass_ids: Vec::new(),
        }
    }

    /// Register a control handler.
    ///
    /// The pattern must start with `$SYS.FABRIC.` and remain scoped to the
    /// declared family; otherwise [`ControlRegistryError::InvalidPrefix`] or
    /// [`ControlRegistryError::FamilyMismatch`] is returned.
    pub fn register(
        &mut self,
        family: SystemSubjectFamily,
        pattern: SubjectPattern,
        budget: ControlBudget,
        damping: AdvisoryDampingPolicy,
        break_glass: bool,
    ) -> Result<ControlHandlerId, ControlRegistryError> {
        let pat_str = pattern.as_str();
        if !pat_str.starts_with("$SYS.FABRIC.") {
            return Err(ControlRegistryError::InvalidPrefix {
                pattern: pat_str.to_owned(),
            });
        }
        let family_prefix = family.prefix();
        if pat_str != family_prefix
            && !pat_str
                .strip_prefix(&family_prefix)
                .is_some_and(|suffix| suffix.starts_with('.'))
        {
            return Err(ControlRegistryError::FamilyMismatch {
                family,
                pattern: pat_str.to_owned(),
            });
        }
        let id = ControlHandlerId::new(self.next_id);
        self.next_id = self
            .next_id
            .checked_add(1)
            .expect("control handler id counter exhausted");

        let handler = ControlHandler {
            id,
            family,
            pattern,
            budget,
            damping,
            break_glass,
        };
        self.handlers.insert(id, handler);
        if break_glass {
            self.break_glass_ids.push(id);
        }
        Ok(id)
    }

    /// Register a handler with default budget and damping for the given
    /// family.
    pub fn register_default(
        &mut self,
        family: SystemSubjectFamily,
    ) -> Result<ControlHandlerId, ControlRegistryError> {
        self.register(
            family,
            family.wildcard_pattern(),
            ControlBudget::default(),
            AdvisoryDampingPolicy::default(),
            false,
        )
    }

    /// Register a tenant/service-scoped control handler.
    pub fn register_namespace(
        &mut self,
        scope: &NamespaceControlScope,
        budget: ControlBudget,
        damping: AdvisoryDampingPolicy,
        break_glass: bool,
    ) -> Result<ControlHandlerId, ControlRegistryError> {
        self.register(
            scope.family(),
            scope.wildcard_pattern(),
            budget,
            damping,
            break_glass,
        )
    }

    /// Register a tenant/service-scoped handler with default policies.
    pub fn register_namespace_default(
        &mut self,
        scope: &NamespaceControlScope,
    ) -> Result<ControlHandlerId, ControlRegistryError> {
        self.register_namespace(
            scope,
            ControlBudget::default(),
            AdvisoryDampingPolicy::default(),
            false,
        )
    }

    /// Register a break-glass recovery handler for the given family.
    pub fn register_break_glass(
        &mut self,
        family: SystemSubjectFamily,
    ) -> Result<ControlHandlerId, ControlRegistryError> {
        self.register(
            family,
            family.wildcard_pattern(),
            ControlBudget::break_glass(),
            AdvisoryDampingPolicy::non_recursive(),
            true,
        )
    }

    /// Remove a handler by ID.
    ///
    /// Returns `true` if the handler was present.
    pub fn unregister(&mut self, id: ControlHandlerId) -> bool {
        if self.handlers.remove(&id).is_some() {
            self.break_glass_ids.retain(|&bg_id| bg_id != id);
            true
        } else {
            false
        }
    }

    /// Look up a handler by ID.
    #[must_use]
    pub fn get(&self, id: ControlHandlerId) -> Option<&ControlHandler> {
        self.handlers.get(&id)
    }

    /// Return all handlers whose pattern matches the given control subject.
    #[must_use]
    pub fn matching_handlers(&self, subject: &Subject) -> Vec<&ControlHandler> {
        self.handlers
            .values()
            .filter(|h| h.pattern.matches(subject))
            .collect()
    }

    /// Return all break-glass recovery handlers.
    #[must_use]
    pub fn break_glass_handlers(&self) -> Vec<&ControlHandler> {
        self.break_glass_ids
            .iter()
            .filter_map(|id| self.handlers.get(id))
            .collect()
    }

    /// Return all handlers for a specific system subject family.
    #[must_use]
    pub fn handlers_for_family(&self, family: SystemSubjectFamily) -> Vec<&ControlHandler> {
        self.handlers
            .values()
            .filter(|h| h.family == family)
            .collect()
    }

    /// Total number of registered handlers.
    #[must_use]
    pub fn len(&self) -> usize {
        self.handlers.len()
    }

    /// Whether the registry has no handlers.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.handlers.is_empty()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn node(id: &str) -> NodeId {
        NodeId::new(id)
    }

    fn pattern(value: &str) -> SubjectPattern {
        SubjectPattern::new(value)
    }

    fn assert_delta_round_trip<T>(baseline: T, updated: T)
    where
        T: JoinSemilattice + std::fmt::Debug,
        T::Delta: std::fmt::Debug,
    {
        let delta = updated.delta(&baseline);
        let mut applied = baseline;
        assert!(applied.apply_delta(&delta));
        assert_eq!(applied, updated);
    }

    fn assert_converges<T>(left: T, middle: T, right: T)
    where
        T: JoinSemilattice + std::fmt::Debug,
    {
        let mut lhs = left.clone();
        lhs.merge(&middle);
        lhs.merge(&right);

        let mut rhs = right.clone();
        rhs.merge(&middle);
        rhs.merge(&left);

        assert_eq!(lhs, rhs);
    }

    // -- Delta-CRDT control metadata ----------------------------------------

    #[test]
    fn interest_summary_round_trips_delta() {
        let replica_a = node("replica-a");
        let replica_b = node("replica-b");
        let orders = pattern("tenant.orders.>");
        let invoices = pattern("tenant.invoices.>");

        let baseline = InterestSummary::default();
        let mut updated = InterestSummary::default();
        updated.subscribe(&replica_a, orders.clone());
        updated.subscribe(&replica_b, orders.clone());
        updated.unsubscribe(&replica_a, &orders);
        updated.subscribe(&replica_b, invoices.clone());

        assert_eq!(updated.interest_count(&orders), 1);
        assert_eq!(updated.interest_count(&invoices), 1);
        assert_delta_round_trip(baseline, updated);
    }

    #[test]
    fn interest_summary_converges_across_merge_orders() {
        let replica_a = node("replica-a");
        let replica_b = node("replica-b");
        let orders = pattern("tenant.orders.>");

        let mut left = InterestSummary::default();
        left.subscribe(&replica_a, orders.clone());

        let mut middle = InterestSummary::default();
        middle.subscribe(&replica_b, orders.clone());

        let mut right = InterestSummary::default();
        right.unsubscribe(&replica_a, &orders);

        assert_converges(left, middle, right);
    }

    #[test]
    fn cursor_checkpoint_prefers_newest_mark() {
        let replica_a = node("replica-a");
        let replica_b = node("replica-b");
        let baseline = CursorCheckpoint::default();

        let mut updated = CursorCheckpoint::default();
        updated.observe("consumer-a", CursorMark::new(10, 1_000, replica_a));
        updated.observe("consumer-a", CursorMark::new(12, 1_100, replica_b.clone()));

        let checkpoint = updated.checkpoint("consumer-a").expect("checkpoint");
        assert_eq!(checkpoint.offset(), 12);
        assert_eq!(checkpoint.checkpoint_unix_ms(), 1_100);
        assert_eq!(checkpoint.steward(), &replica_b);
        assert_delta_round_trip(baseline, updated);
    }

    #[test]
    fn membership_view_prefers_higher_version_and_converges() {
        let replica_a = node("replica-a");
        let replica_b = node("replica-b");

        let mut left = MembershipView::default();
        left.observe(
            replica_a.clone(),
            MembershipRecord::new(1, MembershipState::Healthy, 1_000, 125),
        );

        let mut middle = MembershipView::default();
        middle.observe(
            replica_a.clone(),
            MembershipRecord::new(2, MembershipState::Degraded, 1_100, 600),
        );

        let mut right = MembershipView::default();
        right.observe(
            replica_b,
            MembershipRecord::new(1, MembershipState::Joining, 900, 50),
        );

        let mut merged = left.clone();
        merged.merge(&middle);
        let record = merged.record(&replica_a).expect("membership record");
        assert_eq!(record.version(), 2);
        assert_eq!(record.state(), MembershipState::Degraded);
        assert_eq!(record.load_per_mille(), 600);

        assert_delta_round_trip(MembershipView::default(), merged);
        assert_converges(left, middle, right);
    }

    #[test]
    fn lag_sketch_round_trips_delta_and_respects_error_bound() {
        let replica_a = node("replica-a");
        let replica_b = node("replica-b");
        let mut sketch = LagSketch::new(8);

        let samples = [3_u64, 9, 12, 18];
        sketch.observe(&replica_a, samples[0]);
        sketch.observe(&replica_a, samples[1]);
        sketch.observe(&replica_b, samples[2]);
        sketch.observe(&replica_b, samples[3]);

        assert_eq!(sketch.total_samples(), samples.len() as u64);
        let estimated_mean = sketch.estimated_mean().expect("mean estimate");
        let actual_mean = samples.iter().sum::<u64>() / samples.len() as u64;
        let error = estimated_mean.abs_diff(actual_mean);
        assert!(error <= sketch.max_mean_error_bound());

        assert_delta_round_trip(LagSketch::new(8), sketch);
    }

    #[test]
    fn lag_sketch_empty_delta_with_only_bucket_width_change_is_noop() {
        let baseline = LagSketch::default();
        let updated = LagSketch::new(8);
        let delta = updated.delta(&baseline);

        assert!(<LagSketch as JoinSemilattice>::delta_is_empty(&delta));
    }

    #[test]
    fn advisory_aggregate_round_trips_delta_and_reports_rate() {
        let replica_a = node("replica-a");
        let replica_b = node("replica-b");
        let mut aggregate = AdvisoryAggregate::new(1_000);

        aggregate.record_kind(&replica_a, "policy_decision", 1_200);
        aggregate.record_kind(&replica_b, "policy_decision", 1_400);
        aggregate.record_kind(&replica_b, "evidence_record", 1_800);

        assert_eq!(aggregate.count(1_000, "policy_decision"), 2);
        assert_eq!(aggregate.count(1_000, "evidence_record"), 1);
        assert_eq!(aggregate.rate_per_second(1_000, "policy_decision"), 2.0);

        assert_delta_round_trip(AdvisoryAggregate::new(1_000), aggregate);
    }

    #[test]
    fn advisory_aggregate_empty_delta_with_only_window_width_change_is_noop() {
        let baseline = AdvisoryAggregate::default();
        let updated = AdvisoryAggregate::new(1_000);
        let delta = updated.delta(&baseline);

        assert!(<AdvisoryAggregate as JoinSemilattice>::delta_is_empty(
            &delta
        ));
    }

    #[test]
    fn lag_sketch_adopts_incoming_width_when_local_state_is_empty() {
        let mut empty = LagSketch::new(16);
        let mut other = LagSketch::new(8);
        let replica = node("r1");
        other.record(&replica, 42);

        empty.merge(&other);

        assert_eq!(empty.bucket_width, 8);
        assert_eq!(empty.bucket_count(), 1);
    }

    #[test]
    fn lag_sketch_apply_delta_adopts_width_when_empty_and_breaks_loop_when_non_empty() {
        let replica = node("r1");

        // Empty local adopts incoming width via apply_delta.
        let mut empty = LagSketch::new(16);
        let mut source = LagSketch::new(8);
        source.record(&replica, 42);
        let delta = source.delta(&LagSketch::new(8));
        assert!(empty.apply_delta(&delta));
        assert_eq!(empty.bucket_width, 8);
        assert_eq!(empty.bucket_count(), 1);

        // Non-empty local with different width returns true (breaks loop)
        // but does NOT adopt the data.
        let mut established = LagSketch::new(16);
        established.record(&replica, 99);
        let before_count = established.bucket_count();
        let mismatched_delta = source.delta(&LagSketch::new(8));
        assert!(established.apply_delta(&mismatched_delta));
        assert_eq!(established.bucket_width, 16); // width unchanged
        assert_eq!(established.bucket_count(), before_count); // data unchanged
    }

    #[test]
    fn advisory_aggregate_adopts_incoming_window_width_when_empty() {
        let mut empty = AdvisoryAggregate::new(500);
        let mut other = AdvisoryAggregate::new(1_000);
        other.record_kind(&node("r1"), "evt", 1_200);

        empty.merge(&other);
        assert_eq!(empty.window_width_ms, 1_000);
        assert_eq!(empty.count(1_000, "evt"), 1);
    }

    #[test]
    fn advisory_aggregate_apply_delta_breaks_loop_when_non_empty() {
        let r = node("r1");
        let mut established = AdvisoryAggregate::new(500);
        established.record_kind(&r, "evt", 200);

        let mut source = AdvisoryAggregate::new(1_000);
        source.record_kind(&r, "evt", 1_200);
        let delta = source.delta(&AdvisoryAggregate::new(1_000));

        // Returns true to break anti-entropy loop, but doesn't adopt data.
        assert!(established.apply_delta(&delta));
        assert_eq!(established.window_width_ms, 500);
    }

    #[test]
    fn unsubscribe_on_absent_pattern_does_not_create_entry() {
        let r = node("r1");
        let mut summary = InterestSummary::default();

        // Unsubscribe from a pattern that was never subscribed to.
        summary.unsubscribe(&r, &pattern("absent.>"));

        // No entry should have been created.
        assert_eq!(summary.interest_count(&pattern("absent.>")), 0);
        assert!(summary.counts.is_empty());
    }

    #[test]
    fn unsubscribe_after_subscribe_decrements_normally() {
        let r = node("r1");
        let p = pattern("orders.>");
        let mut summary = InterestSummary::default();

        summary.subscribe(&r, p.clone());
        assert_eq!(summary.interest_count(&p), 1);

        summary.unsubscribe(&r, &p);
        assert_eq!(summary.interest_count(&p), 0);
        // Entry exists (from subscribe) but value is zero.
        assert_eq!(summary.counts.len(), 1);
    }

    #[test]
    fn propagation_applies_incremental_delta_when_peer_is_one_step_behind() {
        let replica_a = node("replica-a");
        let replica_b = node("replica-b");
        let orders = pattern("tenant.orders.>");

        let mut steward = CrdtPropagationReplica::<InterestSummary>::new(replica_a.clone());
        let mut peer = CrdtPropagationReplica::<InterestSummary>::new(replica_b);

        let envelope = steward
            .mutate(|summary| summary.subscribe(&replica_a, orders.clone()))
            .expect("incremental envelope");

        assert_eq!(envelope.mode(), PropagationMode::Incremental);
        assert_eq!(peer.apply(&envelope), PropagationApply::Applied);
        assert_eq!(peer.state().interest_count(&orders), 1);
        assert_eq!(peer.frontier().version(&replica_a), 1);
    }

    #[test]
    fn propagation_relay_uses_snapshot_for_downstream_peer() {
        let replica_a = node("replica-a");
        let replica_b = node("replica-b");
        let replica_c = node("replica-c");
        let orders = pattern("tenant.orders.>");

        let mut steward = CrdtPropagationReplica::<InterestSummary>::new(replica_a.clone());
        let mut relay = CrdtPropagationReplica::<InterestSummary>::new(replica_b);
        let mut downstream = CrdtPropagationReplica::<InterestSummary>::new(replica_c);

        let first_hop = steward
            .mutate(|summary| summary.subscribe(&replica_a, orders.clone()))
            .expect("first-hop envelope");
        assert_eq!(relay.apply(&first_hop), PropagationApply::Applied);

        let second_hop = relay
            .prepare_for(&downstream.digest())
            .expect("relay snapshot");
        assert_eq!(second_hop.mode(), PropagationMode::AntiEntropy);
        assert_eq!(downstream.apply(&second_hop), PropagationApply::Applied);
        assert_eq!(downstream.state().interest_count(&orders), 1);
    }

    #[test]
    fn propagation_detects_partition_gap_and_repairs_via_snapshot() {
        let replica_a = node("replica-a");
        let replica_b = node("replica-b");
        let orders = pattern("tenant.orders.>");
        let invoices = pattern("tenant.invoices.>");

        let mut steward = CrdtPropagationReplica::<InterestSummary>::new(replica_a.clone());
        let mut peer = CrdtPropagationReplica::<InterestSummary>::new(replica_b);

        let first = steward
            .mutate(|summary| summary.subscribe(&replica_a, orders.clone()))
            .expect("first delta");
        let second = steward
            .mutate(|summary| summary.subscribe(&replica_a, invoices.clone()))
            .expect("second delta");

        assert_eq!(peer.apply(&second), PropagationApply::NeedsAntiEntropy);
        assert!(peer.needs_anti_entropy());

        let repair = steward
            .prepare_for(&peer.digest())
            .expect("repair snapshot");
        assert_eq!(repair.mode(), PropagationMode::AntiEntropy);
        assert_eq!(peer.apply(&repair), PropagationApply::Applied);
        assert!(!peer.needs_anti_entropy());
        assert_eq!(peer.state().interest_count(&orders), 1);
        assert_eq!(peer.state().interest_count(&invoices), 1);
        assert_eq!(peer.frontier().version(&replica_a), 2);
        assert_eq!(peer.apply(&first), PropagationApply::AlreadySatisfied);
    }

    #[test]
    fn propagation_converges_leaderlessly_after_partition_via_relay() {
        let replica_a = node("replica-a");
        let replica_b = node("replica-b");
        let replica_c = node("replica-c");
        let orders = pattern("tenant.orders.>");
        let invoices = pattern("tenant.invoices.>");

        let mut left = CrdtPropagationReplica::<InterestSummary>::new(replica_a.clone());
        let mut right = CrdtPropagationReplica::<InterestSummary>::new(replica_b.clone());
        let mut relay = CrdtPropagationReplica::<InterestSummary>::new(replica_c);

        let left_delta = left
            .mutate(|summary| summary.subscribe(&replica_a, orders.clone()))
            .expect("left delta");
        let _right_delta = right
            .mutate(|summary| summary.subscribe(&replica_b, invoices.clone()))
            .expect("right delta");

        assert_eq!(relay.apply(&left_delta), PropagationApply::Applied);
        let from_right = right
            .prepare_for(&relay.digest())
            .expect("relay repair from right");
        assert_eq!(from_right.mode(), PropagationMode::AntiEntropy);
        assert_eq!(relay.apply(&from_right), PropagationApply::Applied);

        let relay_to_left = relay.prepare_for(&left.digest()).expect("relay to left");
        let relay_to_right = relay.prepare_for(&right.digest()).expect("relay to right");

        assert_eq!(left.apply(&relay_to_left), PropagationApply::Applied);
        assert_eq!(right.apply(&relay_to_right), PropagationApply::Applied);

        let mut expected = InterestSummary::default();
        expected.subscribe(&replica_a, orders.clone());
        expected.subscribe(&replica_b, invoices.clone());

        assert_eq!(left.state(), &expected);
        assert_eq!(right.state(), &expected);
        assert_eq!(relay.state(), &expected);
    }

    #[test]
    fn propagation_prefers_incremental_delta_when_it_is_smaller_than_snapshot() {
        let replica_a = node("replica-a");
        let replica_b = node("replica-b");
        let orders = pattern("tenant.orders.>");
        let invoices = pattern("tenant.invoices.>");

        let mut steward = CrdtPropagationReplica::<InterestSummary>::new(replica_a.clone());
        let mut peer = CrdtPropagationReplica::<InterestSummary>::new(replica_b);

        let first = steward
            .mutate(|summary| summary.subscribe(&replica_a, orders.clone()))
            .expect("first delta");
        assert_eq!(peer.apply(&first), PropagationApply::Applied);

        let incremental = steward
            .mutate(|summary| summary.subscribe(&replica_a, invoices.clone()))
            .expect("incremental delta");
        let snapshot = steward.snapshot_envelope().expect("snapshot delta");

        assert_eq!(incremental.mode(), PropagationMode::Incremental);
        assert_eq!(snapshot.mode(), PropagationMode::AntiEntropy);

        let incremental_counts = match incremental.delta() {
            InterestSummaryDelta { counts } => counts.len(),
        };
        let snapshot_counts = match snapshot.delta() {
            InterestSummaryDelta { counts } => counts.len(),
        };

        assert_eq!(incremental_counts, 1);
        assert_eq!(snapshot_counts, 2);
        assert!(incremental_counts < snapshot_counts);
    }

    #[test]
    fn cursor_checkpoint_converges_and_ignores_stale_observations() {
        let replica_a = node("replica-a");
        let replica_b = node("replica-b");
        let replica_c = node("replica-c");

        let mut left = CursorCheckpoint::default();
        left.observe("consumer-a", CursorMark::new(12, 1_200, replica_a.clone()));
        left.observe("consumer-a", CursorMark::new(11, 1_300, replica_b.clone()));

        let checkpoint = left.checkpoint("consumer-a").expect("checkpoint");
        assert_eq!(checkpoint.offset(), 12);
        assert_eq!(checkpoint.checkpoint_unix_ms(), 1_200);
        assert_eq!(checkpoint.steward(), &replica_a);

        let mut middle = CursorCheckpoint::default();
        middle.observe("consumer-b", CursorMark::new(4, 900, replica_b));

        let mut right = CursorCheckpoint::default();
        right.observe("consumer-c", CursorMark::new(2, 800, replica_c));

        assert_converges(left, middle, right);
    }

    #[test]
    fn lag_sketch_converges_across_merge_orders() {
        let replica_a = node("replica-a");
        let replica_b = node("replica-b");
        let replica_c = node("replica-c");

        let mut left = LagSketch::new(8);
        left.observe(&replica_a, 3);
        left.observe(&replica_a, 7);

        let mut middle = LagSketch::new(8);
        middle.observe(&replica_b, 11);

        let mut right = LagSketch::new(8);
        right.observe(&replica_c, 19);

        assert_converges(left, middle, right);
    }

    #[test]
    fn propagation_duplicate_incremental_delta_is_idempotent() {
        let replica_a = node("replica-a");
        let replica_b = node("replica-b");
        let orders = pattern("tenant.orders.>");

        let mut steward = CrdtPropagationReplica::<InterestSummary>::new(replica_a.clone());
        let mut peer = CrdtPropagationReplica::<InterestSummary>::new(replica_b);

        let envelope = steward
            .mutate(|summary| summary.subscribe(&replica_a, orders.clone()))
            .expect("incremental envelope");

        assert_eq!(peer.apply(&envelope), PropagationApply::Applied);
        assert_eq!(peer.apply(&envelope), PropagationApply::AlreadySatisfied);
        assert_eq!(peer.state().interest_count(&orders), 1);
    }

    #[test]
    fn propagation_resumes_incremental_after_snapshot_repair() {
        let replica_a = node("replica-a");
        let replica_b = node("replica-b");
        let orders = pattern("tenant.orders.>");
        let invoices = pattern("tenant.invoices.>");
        let payments = pattern("tenant.payments.>");

        let mut steward = CrdtPropagationReplica::<InterestSummary>::new(replica_a.clone());
        let mut peer = CrdtPropagationReplica::<InterestSummary>::new(replica_b);

        let first = steward
            .mutate(|summary| summary.subscribe(&replica_a, orders.clone()))
            .expect("first delta");
        let second = steward
            .mutate(|summary| summary.subscribe(&replica_a, invoices.clone()))
            .expect("second delta");

        assert_eq!(peer.apply(&second), PropagationApply::NeedsAntiEntropy);
        let repair = steward
            .prepare_for(&peer.digest())
            .expect("repair snapshot");
        assert_eq!(repair.mode(), PropagationMode::AntiEntropy);
        assert_eq!(peer.apply(&repair), PropagationApply::Applied);
        assert_eq!(peer.apply(&first), PropagationApply::AlreadySatisfied);

        let third = steward
            .mutate(|summary| summary.subscribe(&replica_a, payments.clone()))
            .expect("third delta");
        assert_eq!(third.mode(), PropagationMode::Incremental);
        assert_eq!(peer.apply(&third), PropagationApply::Applied);
        assert_eq!(peer.state().interest_count(&orders), 1);
        assert_eq!(peer.state().interest_count(&invoices), 1);
        assert_eq!(peer.state().interest_count(&payments), 1);
        assert_eq!(peer.frontier().version(&replica_a), 3);
    }

    #[test]
    fn propagation_snapshot_applies_mismatched_lag_sketch_delta_to_break_retry_loop() {
        let replica_a = node("replica-a");
        let replica_b = node("replica-b");

        let mut peer = CrdtPropagationReplica::<LagSketch>::new(replica_b.clone());
        let _ = peer.mutate(|sketch| sketch.observe(&replica_b, 42));

        let mut frontier = ReplicaVersionVector::default();
        frontier.advance(&replica_a);

        let mut counter_delta = ReplicaCounterDelta::default();
        counter_delta.positive.insert(replica_a.clone(), 1);

        let mut buckets = BTreeMap::new();
        buckets.insert(0, counter_delta);

        let envelope = PropagationEnvelope {
            steward: replica_a.clone(),
            frontier,
            mode: PropagationMode::AntiEntropy,
            delta: LagSketchDelta {
                bucket_width: 8,
                buckets,
            },
        };

        assert_eq!(peer.apply(&envelope), PropagationApply::Applied);
        assert_eq!(peer.frontier().version(&replica_a), 1);
        assert!(!peer.needs_anti_entropy());
    }

    #[test]
    fn advisory_aggregate_collapses_decision_identity_to_kind_counts() {
        let replica_a = node("replica-a");
        let replica_b = node("replica-b");

        let audit_a = make_test_audit_entry();
        let mut audit_b = make_test_audit_entry();
        audit_b.decision_id = DecisionId::from_raw(77);
        audit_b.trace_id = TraceId::from_raw(200);
        audit_b.action_chosen = "hold".to_owned();
        audit_b.expected_loss = 0.7;
        audit_b.ts_unix_ms = 1_700_000_000_500;

        let outcome_a = DecisionOutcome {
            action_index: 0,
            action_name: audit_a.action_chosen.clone(),
            expected_loss: audit_a.expected_loss,
            expected_losses: audit_a.expected_loss_by_action.clone(),
            fallback_active: false,
            audit_entry: audit_a,
        };
        let outcome_b = DecisionOutcome {
            action_index: 1,
            action_name: audit_b.action_chosen.clone(),
            expected_loss: audit_b.expected_loss,
            expected_losses: audit_b.expected_loss_by_action.clone(),
            fallback_active: false,
            audit_entry: audit_b,
        };

        let advisory_a = ControlAdvisory::evidence_record(
            SystemSubjectFamily::Drain,
            Subject::new("$SYS.FABRIC.DRAIN.evidence"),
            &outcome_a,
            "drain evidence a",
        );
        let advisory_b = ControlAdvisory::evidence_record(
            SystemSubjectFamily::Drain,
            Subject::new("$SYS.FABRIC.DRAIN.evidence"),
            &outcome_b,
            "drain evidence b",
        );

        let mut aggregate = AdvisoryAggregate::new(1_000);
        aggregate.record_kind(
            &replica_a,
            advisory_a.advisory_type.kind(),
            advisory_a.ts_unix_ms,
        );
        aggregate.record_kind(
            &replica_b,
            advisory_b.advisory_type.kind(),
            advisory_b.ts_unix_ms,
        );

        let window_start = 1_700_000_000_000;
        let kind_window = aggregate.windows.get(&window_start).expect("window");
        assert_eq!(aggregate.count(window_start, "evidence_record"), 2);
        assert_eq!(kind_window.len(), 1);
        assert!(kind_window.contains_key("evidence_record"));

        let evidence_id_a = advisory_a.evidence_id();
        let evidence_id_b = advisory_b.evidence_id();
        assert!(
            matches!((&evidence_id_a, &evidence_id_b), (Some(left), Some(right)) if left != right)
        );
        if let Some(evidence_id_a) = evidence_id_a {
            assert!(!kind_window.contains_key(&evidence_id_a));
        }
        if let Some(evidence_id_b) = evidence_id_b {
            assert!(!kind_window.contains_key(&evidence_id_b));
        }
    }

    #[test]
    fn advisory_aggregate_prune_before_retains_cutoff_window_and_newer() {
        let replica_a = node("replica-a");
        let mut aggregate = AdvisoryAggregate::new(1_000);

        aggregate.record_kind(&replica_a, "evidence_record", 1_100);
        aggregate.record_kind(&replica_a, "evidence_record", 2_100);
        aggregate.record_kind(&replica_a, "evidence_record", 3_100);

        aggregate.prune_before(2_500);

        assert_eq!(aggregate.count(1_000, "evidence_record"), 0);
        assert_eq!(aggregate.count(2_000, "evidence_record"), 1);
        assert_eq!(aggregate.count(3_000, "evidence_record"), 1);
    }

    // -- SystemSubjectFamily -------------------------------------------------

    #[test]
    fn all_families_have_unique_names() {
        let mut names: Vec<&str> = SystemSubjectFamily::ALL.iter().map(|f| f.name()).collect();
        let original_len = names.len();
        names.sort_unstable();
        names.dedup();
        assert_eq!(names.len(), original_len, "duplicate family names");
    }

    #[test]
    fn all_families_produce_valid_subject_patterns() {
        for family in &SystemSubjectFamily::ALL {
            let pattern = family.wildcard_pattern();
            assert!(
                pattern.as_str().starts_with("$SYS.FABRIC."),
                "pattern does not start with $SYS.FABRIC.: {}",
                pattern.as_str()
            );
            assert!(
                pattern.as_str().ends_with(".>"),
                "pattern does not end with .>: {}",
                pattern.as_str()
            );
        }
    }

    #[test]
    fn all_families_produce_valid_schemas() {
        for family in &SystemSubjectFamily::ALL {
            let schema = family.default_schema();
            assert_eq!(schema.family, SubjectFamily::Control);
            assert_eq!(schema.mobility, MobilityPermission::LocalOnly);
            assert!(schema.reply_space.is_none());
        }
    }

    #[test]
    fn delivery_class_monotonicity() {
        // Health/Route/Drain are cheapest (ephemeral), Auth/Replay most
        // expensive (forensic).
        assert_eq!(
            SystemSubjectFamily::Health.default_delivery_class(),
            DeliveryClass::EphemeralInteractive
        );
        assert_eq!(
            SystemSubjectFamily::Auth.default_delivery_class(),
            DeliveryClass::ForensicReplayable
        );
        assert_eq!(
            SystemSubjectFamily::Consumer.default_delivery_class(),
            DeliveryClass::ObligationBacked
        );
    }

    #[test]
    fn display_shows_prefix() {
        assert_eq!(
            format!("{}", SystemSubjectFamily::Health),
            "$SYS.FABRIC.HEALTH"
        );
        assert_eq!(
            format!("{}", SystemSubjectFamily::Replay),
            "$SYS.FABRIC.REPLAY"
        );
    }

    // -- ControlBudget -------------------------------------------------------

    #[test]
    fn default_budget_below_break_glass() {
        let normal = ControlBudget::default();
        let bg = ControlBudget::break_glass();
        assert!(normal.priority < bg.priority);
        assert!(normal.poll_quota < bg.poll_quota);
    }

    // -- AdvisoryDampingPolicy -----------------------------------------------

    #[test]
    fn default_damping_requires_operator_intent() {
        let policy = AdvisoryDampingPolicy::default();
        assert!(policy.requires_operator_intent);
    }

    #[test]
    fn non_recursive_damping_does_not_require_intent() {
        let policy = AdvisoryDampingPolicy::non_recursive();
        assert!(!policy.requires_operator_intent);
        assert_eq!(policy.stratification_tier, Some(0));
    }

    // -- ControlOutcome ------------------------------------------------------

    #[test]
    fn outcome_advisory_round_trip() {
        let outcome = ControlOutcome::Advisory {
            subject: Subject::new("$SYS.FABRIC.HEALTH.ok"),
            payload: b"{\"status\":\"ok\"}".to_vec(),
        };
        if let ControlOutcome::Advisory { subject, payload } = &outcome {
            assert_eq!(subject.as_str(), "$SYS.FABRIC.HEALTH.ok");
            assert!(!payload.is_empty());
        } else {
            panic!("expected Advisory variant");
        }
    }

    // -- ControlRegistry -----------------------------------------------------

    #[test]
    fn register_and_lookup() {
        let mut registry = ControlRegistry::new();
        let id = registry
            .register_default(SystemSubjectFamily::Health)
            .expect("register");
        assert_eq!(registry.len(), 1);
        let handler = registry.get(id).expect("lookup");
        assert_eq!(handler.family, SystemSubjectFamily::Health);
        assert!(!handler.break_glass);
    }

    #[test]
    fn register_rejects_non_sys_prefix() {
        let mut registry = ControlRegistry::new();
        let result = registry.register(
            SystemSubjectFamily::Health,
            SubjectPattern::new("user.health.>"),
            ControlBudget::default(),
            AdvisoryDampingPolicy::default(),
            false,
        );
        assert!(result.is_err());
        match result.unwrap_err() {
            ControlRegistryError::InvalidPrefix { pattern } => {
                assert_eq!(pattern, "user.health.>");
            }
            other => panic!("unexpected error: {other}"),
        }
    }

    #[test]
    fn register_rejects_family_mismatch() {
        let mut registry = ControlRegistry::new();
        let result = registry.register(
            SystemSubjectFamily::Health,
            SubjectPattern::new("$SYS.FABRIC.AUTH.>"),
            ControlBudget::default(),
            AdvisoryDampingPolicy::default(),
            false,
        );
        match result.expect_err("family mismatch must fail") {
            ControlRegistryError::FamilyMismatch { family, pattern } => {
                assert_eq!(family, SystemSubjectFamily::Health);
                assert_eq!(pattern, "$SYS.FABRIC.AUTH.>");
            }
            other => panic!("unexpected error: {other}"),
        }
    }

    #[test]
    fn register_rejects_similar_prefix_outside_family_boundary() {
        let mut registry = ControlRegistry::new();
        let result = registry.register(
            SystemSubjectFamily::Health,
            SubjectPattern::new("$SYS.FABRIC.HEALTHY.>"),
            ControlBudget::default(),
            AdvisoryDampingPolicy::default(),
            false,
        );
        match result.expect_err("family boundary mismatch must fail") {
            ControlRegistryError::FamilyMismatch { family, pattern } => {
                assert_eq!(family, SystemSubjectFamily::Health);
                assert_eq!(pattern, "$SYS.FABRIC.HEALTHY.>");
            }
            other => panic!("unexpected error: {other}"),
        }
    }

    #[test]
    fn break_glass_registration() {
        let mut registry = ControlRegistry::new();
        let bg_id = registry
            .register_break_glass(SystemSubjectFamily::Health)
            .expect("bg register");
        let normal_id = registry
            .register_default(SystemSubjectFamily::Route)
            .expect("normal register");
        assert_eq!(registry.len(), 2);

        let bg = registry.break_glass_handlers();
        assert_eq!(bg.len(), 1);
        assert_eq!(bg[0].id, bg_id);
        assert!(bg[0].break_glass);

        // Normal handler should not appear in break-glass list.
        assert!(bg.iter().all(|h| h.id != normal_id));
    }

    #[test]
    fn matching_handlers_filters_by_subject() {
        let mut registry = ControlRegistry::new();
        registry
            .register_default(SystemSubjectFamily::Health)
            .expect("register health");
        registry
            .register_default(SystemSubjectFamily::Auth)
            .expect("register auth");

        let health_subj = Subject::new("$SYS.FABRIC.HEALTH.ok");
        let matches = registry.matching_handlers(&health_subj);
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].family, SystemSubjectFamily::Health);

        let auth_subj = Subject::new("$SYS.FABRIC.AUTH.login.failed");
        let matches = registry.matching_handlers(&auth_subj);
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].family, SystemSubjectFamily::Auth);

        // Unregistered family yields no matches.
        let drain_subj = Subject::new("$SYS.FABRIC.DRAIN.start");
        let matches = registry.matching_handlers(&drain_subj);
        assert!(matches.is_empty());
    }

    #[test]
    fn namespace_control_scope_builds_tenant_service_system_subjects() {
        let scope = NamespaceControlScope::new(SystemSubjectFamily::Health, "acme", "orders")
            .expect("namespace control scope");

        assert_eq!(scope.family(), SystemSubjectFamily::Health);
        assert_eq!(scope.tenant().as_str(), "acme");
        assert_eq!(scope.service().as_str(), "orders");
        assert_eq!(
            scope.wildcard_pattern().as_str(),
            "$SYS.FABRIC.HEALTH.TENANT.acme.SERVICE.orders.>"
        );
        assert_eq!(
            scope.subject("status").expect("status subject").as_str(),
            "$SYS.FABRIC.HEALTH.TENANT.acme.SERVICE.orders.status"
        );
    }

    #[test]
    fn namespace_control_scope_can_be_derived_from_namespace_kernel() {
        let namespace = NamespaceKernel::new("acme", "orders").expect("namespace kernel");
        let scope = NamespaceControlScope::from_namespace(SystemSubjectFamily::Route, &namespace);

        assert_eq!(scope.family(), SystemSubjectFamily::Route);
        assert_eq!(scope.tenant(), namespace.tenant());
        assert_eq!(scope.service(), namespace.service());
        assert_eq!(
            scope.wildcard_pattern().as_str(),
            "$SYS.FABRIC.ROUTE.TENANT.acme.SERVICE.orders.>"
        );
        assert_eq!(
            scope
                .subject("rebalance")
                .expect("route control subject")
                .as_str(),
            "$SYS.FABRIC.ROUTE.TENANT.acme.SERVICE.orders.rebalance"
        );
    }

    #[test]
    fn control_registry_keeps_namespace_control_handlers_isolated() {
        let mut registry = ControlRegistry::new();
        let acme_orders_ns = NamespaceKernel::new("acme", "orders").expect("acme orders kernel");
        let bravo_orders_ns = NamespaceKernel::new("bravo", "orders").expect("bravo orders kernel");
        let acme_orders =
            NamespaceControlScope::from_namespace(SystemSubjectFamily::Health, &acme_orders_ns);
        let bravo_orders =
            NamespaceControlScope::from_namespace(SystemSubjectFamily::Health, &bravo_orders_ns);

        let acme_id = registry
            .register_namespace_default(&acme_orders)
            .expect("register acme orders");
        let bravo_id = registry
            .register_namespace_default(&bravo_orders)
            .expect("register bravo orders");

        let acme_status = acme_orders.subject("status").expect("acme status");
        let matches = registry.matching_handlers(&acme_status);
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].id, acme_id);
        assert_eq!(
            matches[0].pattern.as_str(),
            acme_orders.wildcard_pattern().as_str()
        );

        let bravo_status = bravo_orders.subject("status").expect("bravo status");
        let matches = registry.matching_handlers(&bravo_status);
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].id, bravo_id);
        assert_eq!(
            matches[0].pattern.as_str(),
            bravo_orders.wildcard_pattern().as_str()
        );
    }

    #[test]
    fn handlers_for_family() {
        let mut registry = ControlRegistry::new();
        registry
            .register_default(SystemSubjectFamily::Health)
            .expect("register 1");
        registry
            .register_break_glass(SystemSubjectFamily::Health)
            .expect("register 2");
        registry
            .register_default(SystemSubjectFamily::Route)
            .expect("register 3");

        let health = registry.handlers_for_family(SystemSubjectFamily::Health);
        assert_eq!(health.len(), 2);
        let route = registry.handlers_for_family(SystemSubjectFamily::Route);
        assert_eq!(route.len(), 1);
    }

    #[test]
    fn unregister_removes_handler() {
        let mut registry = ControlRegistry::new();
        let id = registry
            .register_default(SystemSubjectFamily::Health)
            .expect("register");
        assert_eq!(registry.len(), 1);
        assert!(registry.unregister(id));
        assert_eq!(registry.len(), 0);
        assert!(registry.get(id).is_none());
    }

    #[test]
    fn unregister_clears_break_glass_index() {
        let mut registry = ControlRegistry::new();
        let bg_id = registry
            .register_break_glass(SystemSubjectFamily::Drain)
            .expect("bg");
        assert_eq!(registry.break_glass_handlers().len(), 1);
        registry.unregister(bg_id);
        assert!(registry.break_glass_handlers().is_empty());
    }

    #[test]
    fn unregister_one_break_glass_preserves_remaining_handlers() {
        let mut registry = ControlRegistry::new();
        let health = registry
            .register_break_glass(SystemSubjectFamily::Health)
            .expect("health break-glass");
        let drain = registry
            .register_break_glass(SystemSubjectFamily::Drain)
            .expect("drain break-glass");

        assert!(registry.unregister(health));

        let remaining = registry.break_glass_handlers();
        assert_eq!(remaining.len(), 1);
        assert_eq!(remaining[0].id, drain);
        assert_eq!(remaining[0].family, SystemSubjectFamily::Drain);
    }

    #[test]
    fn unregister_returns_false_for_missing() {
        let mut registry = ControlRegistry::new();
        assert!(!registry.unregister(ControlHandlerId::new(999)));
    }

    #[test]
    fn empty_registry() {
        let registry = ControlRegistry::new();
        assert!(registry.is_empty());
        assert_eq!(registry.len(), 0);
        assert!(registry.break_glass_handlers().is_empty());
    }

    // -- ControlHandlerId ----------------------------------------------------

    #[test]
    fn handler_id_display() {
        let id = ControlHandlerId::new(42);
        assert_eq!(format!("{id}"), "ctrl-42");
    }

    #[test]
    fn handler_id_round_trip() {
        let id = ControlHandlerId::new(7);
        assert_eq!(id.raw(), 7);
    }

    // -- Evidence policy per family ------------------------------------------

    #[test]
    fn auth_replay_have_full_evidence() {
        for family in &[SystemSubjectFamily::Auth, SystemSubjectFamily::Replay] {
            let schema = family.default_schema();
            assert!(
                schema.evidence_policy.record_counterfactual_branches,
                "{family} should record counterfactual branches"
            );
            assert_eq!(schema.evidence_policy.sampling_ratio, 1.0);
        }
    }

    #[test]
    fn health_has_default_evidence() {
        let schema = SystemSubjectFamily::Health.default_schema();
        assert!(!schema.evidence_policy.record_counterfactual_branches);
        assert_eq!(schema.evidence_policy.sampling_ratio, 1.0);
    }

    // -- Minimum ack ---------------------------------------------------------

    #[test]
    fn minimum_ack_matches_delivery_class() {
        // EphemeralInteractive → Accepted
        assert_eq!(SystemSubjectFamily::Health.minimum_ack(), AckKind::Accepted);
        // ObligationBacked → Committed
        assert_eq!(
            SystemSubjectFamily::Consumer.minimum_ack(),
            AckKind::Committed
        );
        // ForensicReplayable → Recoverable
        assert_eq!(
            SystemSubjectFamily::Auth.minimum_ack(),
            AckKind::Recoverable
        );
    }

    // -- ControlAdvisoryType -------------------------------------------------

    #[test]
    fn advisory_type_capability_graph_change() {
        let advisory = ControlAdvisoryType::CapabilityGraphChange {
            affected_subjects: vec![SubjectPattern::new("$SYS.FABRIC.AUTH.>")],
            description: "revoked admin capability".to_owned(),
        };
        match &advisory {
            ControlAdvisoryType::CapabilityGraphChange {
                affected_subjects,
                description,
            } => {
                assert_eq!(affected_subjects.len(), 1);
                assert_eq!(description, "revoked admin capability");
            }
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn advisory_type_evidence_record_has_explicit_identity() {
        let advisory = ControlAdvisoryType::EvidenceRecord {
            evidence_id: "control:drain:42:1700000000000".to_owned(),
            component: "drain_policy".to_owned(),
            action: "failover".to_owned(),
            summary: "latency SLO breach justified failover".to_owned(),
        };
        match &advisory {
            ControlAdvisoryType::EvidenceRecord {
                evidence_id,
                component,
                action,
                summary,
            } => {
                assert_eq!(evidence_id, "control:drain:42:1700000000000");
                assert_eq!(component, "drain_policy");
                assert_eq!(action, "failover");
                assert!(summary.contains("SLO breach"));
                assert_eq!(advisory.kind(), "evidence_record");
            }
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn obligation_transfer_action_display() {
        assert_eq!(
            format!("{}", ObligationTransferAction::Transferred),
            "transferred"
        );
        assert_eq!(format!("{}", ObligationTransferAction::Aborted), "aborted");
        assert_eq!(
            format!("{}", ObligationTransferAction::ReplayScheduled),
            "replay_scheduled"
        );
    }

    // -- ControlAdvisory with FrankenSuite evidence --------------------------

    fn make_test_audit_entry() -> DecisionAuditEntry {
        let mut losses = BTreeMap::new();
        losses.insert("failover".to_owned(), 0.3);
        losses.insert("hold".to_owned(), 0.7);
        DecisionAuditEntry {
            decision_id: DecisionId::from_raw(42),
            trace_id: TraceId::from_raw(100),
            contract_name: "drain_policy".to_owned(),
            action_chosen: "failover".to_owned(),
            expected_loss: 0.3,
            calibration_score: 0.85,
            fallback_active: false,
            posterior_snapshot: vec![0.6, 0.4],
            expected_loss_by_action: losses,
            ts_unix_ms: 1_700_000_000_000,
        }
    }

    #[test]
    fn advisory_from_decision_carries_provenance() {
        let audit = make_test_audit_entry();
        let outcome = DecisionOutcome {
            action_index: 0,
            action_name: "failover".to_owned(),
            expected_loss: 0.3,
            expected_losses: audit.expected_loss_by_action.clone(),
            fallback_active: false,
            audit_entry: audit,
        };

        let advisory = ControlAdvisory::from_decision(
            ControlAdvisoryType::PolicyDecision {
                policy_name: "drain_policy".to_owned(),
                action_chosen: "failover".to_owned(),
                justification: "downstream latency exceeded SLO".to_owned(),
            },
            SystemSubjectFamily::Drain,
            Subject::new("$SYS.FABRIC.DRAIN.failover"),
            &outcome,
        );

        assert!(advisory.has_decision_provenance());
        assert_eq!(advisory.family, SystemSubjectFamily::Drain);
        assert_eq!(advisory.trace_id, TraceId::from_raw(100));
        assert_eq!(advisory.decision_id, DecisionId::from_raw(42));
    }

    #[test]
    fn advisory_to_evidence_ledger() {
        let audit = make_test_audit_entry();
        let outcome = DecisionOutcome {
            action_index: 0,
            action_name: "failover".to_owned(),
            expected_loss: 0.3,
            expected_losses: audit.expected_loss_by_action.clone(),
            fallback_active: false,
            audit_entry: audit,
        };

        let advisory = ControlAdvisory::from_decision(
            ControlAdvisoryType::PolicyDecision {
                policy_name: "drain_policy".to_owned(),
                action_chosen: "failover".to_owned(),
                justification: "SLO breach".to_owned(),
            },
            SystemSubjectFamily::Drain,
            Subject::new("$SYS.FABRIC.DRAIN.failover"),
            &outcome,
        );

        let evidence = advisory.to_evidence_ledger();
        assert!(evidence.is_some());
        let ledger = evidence.unwrap();
        assert!(ledger.is_valid());
        assert_eq!(ledger.component, "drain_policy");
        assert_eq!(ledger.action, "failover");
        assert!((ledger.calibration_score - 0.85).abs() < f64::EPSILON);
        assert!(!ledger.fallback_active);
    }

    #[test]
    fn evidence_record_advisory_uses_stable_evidence_id() {
        let audit = make_test_audit_entry();
        let outcome = DecisionOutcome {
            action_index: 0,
            action_name: "failover".to_owned(),
            expected_loss: 0.3,
            expected_losses: audit.expected_loss_by_action.clone(),
            fallback_active: false,
            audit_entry: audit,
        };

        let advisory = ControlAdvisory::evidence_record(
            SystemSubjectFamily::Drain,
            Subject::new("$SYS.FABRIC.DRAIN.evidence"),
            &outcome,
            "drain failover evidence bundle",
        );

        let evidence_id = advisory.evidence_id().expect("evidence id");
        assert!(evidence_id.starts_with("control:drain:"));
        assert!(advisory.has_decision_provenance());
    }

    #[test]
    fn notification_advisory_has_no_provenance() {
        let advisory = ControlAdvisory::notification(
            ControlAdvisoryType::BreakGlassActivation {
                reason: "fabric unreachable".to_owned(),
            },
            SystemSubjectFamily::Health,
            Subject::new("$SYS.FABRIC.HEALTH.break_glass"),
            TraceId::from_raw(200),
            1_700_000_000_000,
        );

        assert!(!advisory.has_decision_provenance());
        assert!(advisory.to_evidence_ledger().is_none());
        assert_eq!(advisory.trace_id, TraceId::from_raw(200));
    }

    #[test]
    fn advisory_json_payload_contains_type_and_provenance() {
        let advisory = ControlAdvisory::notification(
            ControlAdvisoryType::ObligationTransfer {
                action: ObligationTransferAction::Aborted,
                subject: Subject::new("$SYS.FABRIC.CONSUMER.lease.expired"),
            },
            SystemSubjectFamily::Consumer,
            Subject::new("$SYS.FABRIC.CONSUMER.advisory"),
            TraceId::from_raw(300),
            1_700_000_000_000,
        );

        let payload = advisory.to_json_payload();
        assert!(!payload.is_empty());
        let parsed: serde_json::Value = serde_json::from_slice(&payload).expect("valid JSON");
        assert_eq!(
            parsed.get("type").and_then(serde_json::Value::as_str),
            Some("obligation_transfer")
        );
        assert_eq!(
            parsed.get("action").and_then(serde_json::Value::as_str),
            Some("aborted")
        );
        assert_eq!(
            parsed.get("family").and_then(serde_json::Value::as_str),
            Some("CONSUMER")
        );
        assert_eq!(
            parsed
                .get("obligation_subject")
                .and_then(serde_json::Value::as_str),
            Some("$SYS.FABRIC.CONSUMER.lease.expired")
        );
        assert_eq!(
            parsed
                .get("has_decision_provenance")
                .and_then(serde_json::Value::as_bool),
            Some(false)
        );
        assert_eq!(
            parsed.get("ts_unix_ms").and_then(serde_json::Value::as_u64),
            Some(1_700_000_000_000)
        );
    }

    #[test]
    fn advisory_json_payload_policy_decision() {
        let audit = make_test_audit_entry();
        let outcome = DecisionOutcome {
            action_index: 0,
            action_name: "failover".to_owned(),
            expected_loss: 0.3,
            expected_losses: audit.expected_loss_by_action.clone(),
            fallback_active: false,
            audit_entry: audit,
        };

        let advisory = ControlAdvisory::from_decision(
            ControlAdvisoryType::PolicyDecision {
                policy_name: "load_shed".to_owned(),
                action_chosen: "reject_new".to_owned(),
                justification: "queue depth exceeded threshold".to_owned(),
            },
            SystemSubjectFamily::Route,
            Subject::new("$SYS.FABRIC.ROUTE.shed"),
            &outcome,
        );

        let payload = advisory.to_json_payload();
        let parsed: serde_json::Value = serde_json::from_slice(&payload).expect("valid JSON");
        assert_eq!(
            parsed.get("type").and_then(serde_json::Value::as_str),
            Some("policy_decision")
        );
        assert_eq!(
            parsed
                .get("policy_name")
                .and_then(serde_json::Value::as_str),
            Some("load_shed")
        );
        assert_eq!(
            parsed
                .get("action_chosen")
                .and_then(serde_json::Value::as_str),
            Some("reject_new")
        );
        assert_eq!(
            parsed
                .get("has_decision_provenance")
                .and_then(serde_json::Value::as_bool),
            Some(true)
        );
    }

    #[test]
    fn advisory_json_payload_evidence_record() {
        let audit = make_test_audit_entry();
        let outcome = DecisionOutcome {
            action_index: 0,
            action_name: "failover".to_owned(),
            expected_loss: 0.3,
            expected_losses: audit.expected_loss_by_action.clone(),
            fallback_active: false,
            audit_entry: audit,
        };

        let advisory = ControlAdvisory::evidence_record(
            SystemSubjectFamily::Drain,
            Subject::new("$SYS.FABRIC.DRAIN.evidence"),
            &outcome,
            "bounded drain failover evidence",
        );

        let payload = advisory.to_json_payload();
        let parsed: serde_json::Value = serde_json::from_slice(&payload).expect("valid JSON");
        assert_eq!(
            parsed.get("type").and_then(serde_json::Value::as_str),
            Some("evidence_record")
        );
        assert!(
            parsed
                .get("evidence_id")
                .and_then(serde_json::Value::as_str)
                .expect("string evidence_id")
                .starts_with("control:drain:")
        );
        assert_eq!(
            parsed.get("component").and_then(serde_json::Value::as_str),
            Some("drain_policy")
        );
        assert_eq!(
            parsed.get("action").and_then(serde_json::Value::as_str),
            Some("failover")
        );
        assert_eq!(
            parsed.get("summary").and_then(serde_json::Value::as_str),
            Some("bounded drain failover evidence")
        );
    }

    #[test]
    fn break_glass_advisory_payload() {
        let advisory = ControlAdvisory::notification(
            ControlAdvisoryType::BreakGlassActivation {
                reason: "network partition detected".to_owned(),
            },
            SystemSubjectFamily::Health,
            Subject::new("$SYS.FABRIC.HEALTH.break_glass"),
            TraceId::from_raw(400),
            1_700_000_000_000,
        );

        let payload = advisory.to_json_payload();
        let parsed: serde_json::Value = serde_json::from_slice(&payload).expect("valid JSON");
        assert_eq!(
            parsed.get("type").and_then(serde_json::Value::as_str),
            Some("break_glass_activation")
        );
        assert_eq!(
            parsed.get("reason").and_then(serde_json::Value::as_str),
            Some("network partition detected")
        );
    }

    #[test]
    fn capability_graph_change_payload_preserves_affected_subjects() {
        let advisory = ControlAdvisory::notification(
            ControlAdvisoryType::CapabilityGraphChange {
                affected_subjects: vec![
                    SubjectPattern::new("tenant.acme.service.orders.>"),
                    SubjectPattern::new("tenant.acme.service.inventory.lookup"),
                ],
                description: "added bounded import edge".to_owned(),
            },
            SystemSubjectFamily::Route,
            Subject::new("$SYS.FABRIC.ROUTE.capability_change"),
            TraceId::from_raw(401),
            1_700_000_000_100,
        );

        let payload = advisory.to_json_payload();
        let parsed: serde_json::Value = serde_json::from_slice(&payload).expect("valid JSON");
        let affected_subjects = parsed
            .get("affected_subjects")
            .and_then(serde_json::Value::as_array)
            .expect("affected_subjects array");

        assert_eq!(
            parsed.get("type").and_then(serde_json::Value::as_str),
            Some("capability_graph_change")
        );
        assert_eq!(
            parsed
                .get("description")
                .and_then(serde_json::Value::as_str),
            Some("added bounded import edge")
        );
        assert_eq!(affected_subjects.len(), 2);
        assert_eq!(
            affected_subjects[0].as_str(),
            Some("tenant.acme.service.orders.>")
        );
        assert_eq!(
            affected_subjects[1].as_str(),
            Some("tenant.acme.service.inventory.lookup")
        );
    }

    #[test]
    fn advisory_filter_matches_family_kind_and_provenance() {
        let audit = make_test_audit_entry();
        let outcome = DecisionOutcome {
            action_index: 0,
            action_name: "failover".to_owned(),
            expected_loss: 0.3,
            expected_losses: audit.expected_loss_by_action.clone(),
            fallback_active: false,
            audit_entry: audit,
        };

        let evidence_advisory = ControlAdvisory::evidence_record(
            SystemSubjectFamily::Drain,
            Subject::new("$SYS.FABRIC.DRAIN.evidence"),
            &outcome,
            "drain evidence",
        );
        let notification = ControlAdvisory::notification(
            ControlAdvisoryType::BreakGlassActivation {
                reason: "fabric unreachable".to_owned(),
            },
            SystemSubjectFamily::Health,
            Subject::new("$SYS.FABRIC.HEALTH.break_glass"),
            TraceId::from_raw(9),
            1_700_000_000_123,
        );

        let drain_evidence_only = ControlAdvisoryFilter {
            family: Some(SystemSubjectFamily::Drain),
            advisory_kind: Some("evidence_record"),
            require_decision_provenance: true,
        };
        assert!(evidence_advisory.matches_filter(&drain_evidence_only));
        assert!(!notification.matches_filter(&drain_evidence_only));

        let health_break_glass = ControlAdvisoryFilter {
            family: Some(SystemSubjectFamily::Health),
            advisory_kind: Some("break_glass_activation"),
            require_decision_provenance: false,
        };
        assert!(notification.matches_filter(&health_break_glass));
        assert!(!evidence_advisory.matches_filter(&health_break_glass));
    }

    // ========================================================================
    // Comprehensive control plane tests (bead 8w83i.8.3)
    // ========================================================================

    // -- Capability domain enforcement ---------------------------------------

    #[test]
    fn control_subjects_require_sys_fabric_prefix() {
        // All system subject families produce subjects under $SYS.FABRIC.
        for family in &SystemSubjectFamily::ALL {
            let prefix = family.prefix();
            assert!(
                prefix.starts_with("$SYS.FABRIC."),
                "family {family} prefix `{prefix}` must start with $SYS.FABRIC."
            );
        }
    }

    #[test]
    fn registry_rejects_non_fabric_sys_prefix() {
        let mut registry = ControlRegistry::new();
        // $SYS.OTHER.* is NOT $SYS.FABRIC.* — should be rejected.
        let result = registry.register(
            SystemSubjectFamily::Health,
            SubjectPattern::new("$SYS.OTHER.health.>"),
            ControlBudget::default(),
            AdvisoryDampingPolicy::default(),
            false,
        );
        assert!(result.is_err());
    }

    #[test]
    fn admin_control_capability_scope_maps_correctly() {
        // Verify that control handler families are associated with the
        // AdminControl capability scope (the capability module enforces
        // this at runtime; here we verify the type-level contract).
        use super::super::capability::FabricCapabilityScope;
        assert_eq!(
            format!("{}", FabricCapabilityScope::AdminControl),
            "admin_control"
        );
    }

    // -- Reserved budget under load ------------------------------------------

    #[test]
    fn control_budget_priority_above_user_traffic() {
        let budget = ControlBudget::default();
        // User traffic typically runs at priority 128.  Control handlers
        // must be above that.
        assert!(
            budget.priority > 128,
            "control budget priority {} must exceed user traffic (128)",
            budget.priority
        );
    }

    #[test]
    fn break_glass_budget_is_maximum_priority() {
        let bg = ControlBudget::break_glass();
        assert_eq!(bg.priority, 255, "break-glass must be max priority");
    }

    #[test]
    fn control_budget_deadline_is_bounded() {
        let budget = ControlBudget::default();
        // Control handlers should finish quickly — sub-second.
        assert!(budget.deadline < Duration::from_secs(1));
        let bg = ControlBudget::break_glass();
        assert!(bg.deadline < Duration::from_secs(1));
    }

    // -- Break-glass recovery path -------------------------------------------

    #[test]
    fn break_glass_available_when_main_fabric_degraded() {
        // Simulate: register several normal handlers + one break-glass.
        // Then unregister all normal handlers (simulating degradation).
        // The break-glass handler must still be reachable.
        let mut registry = ControlRegistry::new();
        let normal1 = registry
            .register_default(SystemSubjectFamily::Health)
            .expect("normal 1");
        let normal2 = registry
            .register_default(SystemSubjectFamily::Route)
            .expect("normal 2");
        let bg = registry
            .register_break_glass(SystemSubjectFamily::Health)
            .expect("break-glass");

        // Simulate degradation: remove all normal handlers.
        registry.unregister(normal1);
        registry.unregister(normal2);

        // Break-glass handler survives.
        assert_eq!(registry.len(), 1);
        let bg_handlers = registry.break_glass_handlers();
        assert_eq!(bg_handlers.len(), 1);
        assert_eq!(bg_handlers[0].id, bg);
        assert!(bg_handlers[0].break_glass);
    }

    #[test]
    fn break_glass_handler_has_non_recursive_damping() {
        let mut registry = ControlRegistry::new();
        let bg_id = registry
            .register_break_glass(SystemSubjectFamily::Drain)
            .expect("bg");
        let handler = registry.get(bg_id).unwrap();
        // Break-glass handlers use non-recursive damping — they must not
        // require operator intent (recovery must be autonomous).
        assert!(!handler.damping.requires_operator_intent);
        assert_eq!(handler.damping.stratification_tier, Some(0));
    }

    // -- Advisory damping enforcement ----------------------------------------

    #[test]
    fn damping_default_prevents_feedback_loops() {
        let policy = AdvisoryDampingPolicy::default();
        // Default damping requires operator intent — advisories cannot
        // autonomously trigger further control-plane actions.
        assert!(policy.requires_operator_intent);
        // Minimum interval prevents rapid-fire re-evaluation.
        assert!(policy.min_interval >= Duration::from_secs(1));
        // Window cap prevents event flood from overwhelming evaluator.
        assert!(policy.max_events_per_window <= 100);
    }

    #[test]
    fn damping_stratification_prevents_recursive_amplification() {
        // A tier-1 advisory should not be able to trigger actions that
        // produce tier-0 or tier-1 advisories.
        let tier1 = AdvisoryDampingPolicy {
            stratification_tier: Some(1),
            ..AdvisoryDampingPolicy::default()
        };
        let tier0 = AdvisoryDampingPolicy::non_recursive();

        // Tier 1 > tier 0 — a higher-tier advisory can only trigger
        // actions at a strictly higher tier.
        assert!(tier1.stratification_tier.unwrap() > tier0.stratification_tier.unwrap());
    }

    // -- Registration edge cases ---------------------------------------------

    #[test]
    fn multiple_handlers_same_family_all_match() {
        let mut registry = ControlRegistry::new();
        let id1 = registry
            .register_default(SystemSubjectFamily::Health)
            .expect("h1");
        let id2 = registry
            .register_break_glass(SystemSubjectFamily::Health)
            .expect("h2");

        let subj = Subject::new("$SYS.FABRIC.HEALTH.probe");
        let matches = registry.matching_handlers(&subj);
        assert_eq!(matches.len(), 2);

        let ids: Vec<_> = matches.iter().map(|h| h.id).collect();
        assert!(ids.contains(&id1));
        assert!(ids.contains(&id2));
    }

    #[test]
    fn family_scoped_pattern_routes_only_within_declared_prefix() {
        let mut registry = ControlRegistry::new();
        let narrow = registry
            .register(
                SystemSubjectFamily::Health,
                SubjectPattern::new("$SYS.FABRIC.HEALTH.break_glass.>"),
                ControlBudget::default(),
                AdvisoryDampingPolicy::default(),
                false,
            )
            .expect("narrow register");
        let wildcard = registry
            .register_default(SystemSubjectFamily::Health)
            .expect("wildcard register");

        let narrow_matches =
            registry.matching_handlers(&Subject::new("$SYS.FABRIC.HEALTH.break_glass.activate"));
        let narrow_ids: Vec<_> = narrow_matches.iter().map(|handler| handler.id).collect();
        assert_eq!(narrow_ids, vec![narrow, wildcard]);

        let general_matches = registry.matching_handlers(&Subject::new("$SYS.FABRIC.HEALTH.probe"));
        let general_ids: Vec<_> = general_matches.iter().map(|handler| handler.id).collect();
        assert_eq!(general_ids, vec![wildcard]);
    }

    #[test]
    fn handler_ids_are_monotonically_increasing() {
        let mut registry = ControlRegistry::new();
        let id1 = registry
            .register_default(SystemSubjectFamily::Health)
            .expect("1");
        let id2 = registry
            .register_default(SystemSubjectFamily::Route)
            .expect("2");
        let id3 = registry
            .register_default(SystemSubjectFamily::Auth)
            .expect("3");
        assert!(id1.raw() < id2.raw());
        assert!(id2.raw() < id3.raw());
    }

    #[test]
    fn unregister_then_reregister_gets_new_id() {
        let mut registry = ControlRegistry::new();
        let id1 = registry
            .register_default(SystemSubjectFamily::Health)
            .expect("first");
        registry.unregister(id1);
        let id2 = registry
            .register_default(SystemSubjectFamily::Health)
            .expect("second");
        // New registration gets a fresh ID, not the old one.
        assert_ne!(id1, id2);
        assert!(id2.raw() > id1.raw());
    }

    // -- All advisory types produce valid JSON ------------------------------

    #[test]
    fn all_advisory_types_produce_valid_json() {
        let types = vec![
            ControlAdvisoryType::CapabilityGraphChange {
                affected_subjects: vec![SubjectPattern::new("$SYS.FABRIC.AUTH.>")],
                description: "test".to_owned(),
            },
            ControlAdvisoryType::ObligationTransfer {
                action: ObligationTransferAction::Transferred,
                subject: Subject::new("$SYS.FABRIC.CONSUMER.tx"),
            },
            ControlAdvisoryType::PolicyDecision {
                policy_name: "test_policy".to_owned(),
                action_chosen: "accept".to_owned(),
                justification: "test reason".to_owned(),
            },
            ControlAdvisoryType::EvidenceRecord {
                evidence_id: "control:health:1:1700000000000".to_owned(),
                component: "health_policy".to_owned(),
                action: "mark_degraded".to_owned(),
                summary: "health evidence bundle".to_owned(),
            },
            ControlAdvisoryType::BreakGlassActivation {
                reason: "test reason".to_owned(),
            },
        ];

        for advisory_type in types {
            let advisory = ControlAdvisory::notification(
                advisory_type,
                SystemSubjectFamily::Health,
                Subject::new("$SYS.FABRIC.HEALTH.test"),
                TraceId::from_raw(1),
                1_700_000_000_000,
            );
            let payload = advisory.to_json_payload();
            let parsed: Result<serde_json::Value, _> = serde_json::from_slice(&payload);
            assert!(parsed.is_ok(), "advisory payload must be valid JSON");
            let map = parsed.unwrap();
            assert!(map.get("type").is_some(), "payload must contain 'type' key");
            assert!(
                map.get("family").is_some(),
                "payload must contain 'family' key"
            );
        }
    }

    // -- Evidence ledger validation ------------------------------------------

    #[test]
    fn evidence_ledger_posterior_sums_to_one() {
        let audit = make_test_audit_entry();
        let outcome = DecisionOutcome {
            action_index: 0,
            action_name: "failover".to_owned(),
            expected_loss: 0.3,
            expected_losses: audit.expected_loss_by_action.clone(),
            fallback_active: false,
            audit_entry: audit,
        };

        let advisory = ControlAdvisory::from_decision(
            ControlAdvisoryType::PolicyDecision {
                policy_name: "test".to_owned(),
                action_chosen: "failover".to_owned(),
                justification: "test".to_owned(),
            },
            SystemSubjectFamily::Drain,
            Subject::new("$SYS.FABRIC.DRAIN.test"),
            &outcome,
        );

        let ledger = advisory.to_evidence_ledger().unwrap();
        let sum: f64 = ledger.posterior.iter().sum();
        assert!(
            (sum - 1.0).abs() < 1e-10,
            "posterior must sum to ~1.0, got {sum}"
        );
    }

    #[test]
    fn evidence_ledger_has_expected_losses_for_all_actions() {
        let audit = make_test_audit_entry();
        let outcome = DecisionOutcome {
            action_index: 0,
            action_name: "failover".to_owned(),
            expected_loss: 0.3,
            expected_losses: audit.expected_loss_by_action.clone(),
            fallback_active: false,
            audit_entry: audit,
        };

        let advisory = ControlAdvisory::from_decision(
            ControlAdvisoryType::PolicyDecision {
                policy_name: "drain".to_owned(),
                action_chosen: "failover".to_owned(),
                justification: "test".to_owned(),
            },
            SystemSubjectFamily::Drain,
            Subject::new("$SYS.FABRIC.DRAIN.test"),
            &outcome,
        );

        let ledger = advisory.to_evidence_ledger().unwrap();
        // Should have expected losses for both "failover" and "hold".
        assert_eq!(ledger.expected_loss_by_action.len(), 2);
        assert!(ledger.expected_loss_by_action.contains_key("failover"));
        assert!(ledger.expected_loss_by_action.contains_key("hold"));
    }

    #[test]
    fn evidence_ledger_fallback_flag_propagates() {
        let mut audit = make_test_audit_entry();
        audit.fallback_active = true;
        let outcome = DecisionOutcome {
            action_index: 0,
            action_name: "failover".to_owned(),
            expected_loss: 0.3,
            expected_losses: audit.expected_loss_by_action.clone(),
            fallback_active: true,
            audit_entry: audit,
        };

        let advisory = ControlAdvisory::from_decision(
            ControlAdvisoryType::PolicyDecision {
                policy_name: "test".to_owned(),
                action_chosen: "failover".to_owned(),
                justification: "test".to_owned(),
            },
            SystemSubjectFamily::Route,
            Subject::new("$SYS.FABRIC.ROUTE.test"),
            &outcome,
        );

        let ledger = advisory.to_evidence_ledger().unwrap();
        assert!(
            ledger.fallback_active,
            "fallback flag must propagate to evidence"
        );
    }

    // -- Subject matching precision ------------------------------------------

    #[test]
    fn wildcard_pattern_matches_deep_subjects() {
        let pattern = SystemSubjectFamily::Auth.wildcard_pattern();
        // Tail wildcard ">" should match any depth.
        assert!(pattern.matches(&Subject::new("$SYS.FABRIC.AUTH.login")));
        assert!(pattern.matches(&Subject::new("$SYS.FABRIC.AUTH.login.failed")));
        assert!(pattern.matches(&Subject::new("$SYS.FABRIC.AUTH.login.failed.ip.127.0.0.1")));
    }

    #[test]
    fn wildcard_pattern_does_not_cross_families() {
        let health_pattern = SystemSubjectFamily::Health.wildcard_pattern();
        // Should NOT match Auth subjects.
        assert!(!health_pattern.matches(&Subject::new("$SYS.FABRIC.AUTH.login")));
        // Should NOT match the bare family prefix without a trailing token.
        // (The ">" wildcard requires at least one token after the prefix.)
    }

    // -- ControlHandlerId edge cases -----------------------------------------

    #[test]
    fn handler_id_zero_is_valid() {
        let id = ControlHandlerId::new(0);
        assert_eq!(id.raw(), 0);
        assert_eq!(format!("{id}"), "ctrl-0");
    }

    #[test]
    fn handler_id_max_is_valid() {
        let id = ControlHandlerId::new(u64::MAX);
        assert_eq!(id.raw(), u64::MAX);
    }
}