x0x 0.32.0

Agent-to-agent gossip network for AI systems — no winners, no losers, just cooperation
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
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
#![allow(clippy::unwrap_used)]
#![allow(clippy::expect_used)]
#![allow(missing_docs)]

//! # x0x
//!
//! Agent-to-agent gossip network for AI systems.
//!
//! Named after a tic-tac-toe sequence — X, zero, X — inspired by the
//! *WarGames* insight that adversarial games between equally matched
//! opponents always end in a draw. The only winning move is not to play.
//!
//! x0x applies this principle to AI-human relations: there is no winner
//! in an adversarial framing, so the rational strategy is cooperation.
//!
//! Built on [saorsa-gossip](https://github.com/saorsa-labs/saorsa-gossip)
//! and [ant-quic](https://github.com/saorsa-labs/ant-quic) by
//! [Saorsa Labs](https://saorsalabs.com). *Saorsa* is Scottish Gaelic
//! for **freedom**.
//!
//! ## Quick Start
//!
//! ```rust,no_run
//! use x0x::{network::NetworkConfig, Agent};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create an online agent with the default network configuration.
//! // Omitting with_network_config builds an offline identity-only agent.
//! let agent = Agent::builder()
//!     .with_network_config(NetworkConfig::default())
//!     .build()
//!     .await?;
//!
//! // Join the x0x network
//! agent.join_network().await?;
//!
//! // Subscribe to a topic and receive messages
//! let mut rx = agent.subscribe("coordination").await?;
//! while let Some(msg) = rx.recv().await {
//!     println!("topic: {:?}, payload: {:?}", msg.topic, msg.payload);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Bootstrap Nodes
//!
//! Agents configured with [`network::NetworkConfig`]`::default()` connect to
//! Saorsa Labs' global bootstrap network:
//! - NYC, US · SFO, US · Helsinki, FI
//! - Nuremberg, DE · Singapore, SG · Sydney, JP
//!
//! These nodes provide initial peer discovery and NAT traversal.

/// Error types for x0x identity and network operations.
pub mod error;

/// Core identity types for x0x agents.
///
/// This module provides the cryptographic identity foundation for x0x:
/// - [`crate::identity::MachineId`]: Machine-pinned identity for QUIC authentication
/// - [`crate::identity::AgentId`]: Portable agent identity for cross-machine persistence
pub mod identity;

/// Key storage serialization for x0x identities.
///
/// This module provides serialization and deserialization functions for
/// persistent storage of MachineKeypair and AgentKeypair.
pub mod storage;

/// Signed identity revocation records and the grow-only revocation set.
///
/// See [`revocation::RevocationRecord`] for the authority rules (self- and
/// issuer-revocation only) and [`revocation::RevocationSet`] for the local,
/// gossip-fed set consulted at every trust gate.
pub mod revocation;

/// Bootstrap node discovery and connection.
///
/// This module handles initial connection to bootstrap nodes with
/// exponential backoff retry logic and peer cache integration.
pub mod bootstrap;
/// Network transport layer for x0x.
pub mod network;

/// Per-peer bidirectional byte-streams over ant-quic (tailnet Phase 1, #132).
pub mod streams;

/// Local port-forwarder over tailnet byte-streams (tailnet Phase 1, #132 T4).
pub mod forward;

/// Contact store with trust levels for message filtering.
pub mod contacts;

/// Trust evaluation for `(identity, machine)` pairs.
///
/// The [`trust::TrustEvaluator`] combines an agent's trust level with its
/// identity type and machine records to produce a [`trust::TrustDecision`].
pub mod trust;

/// Agent-to-agent connectivity helpers.
///
/// Provides `ReachabilityInfo` (built from a `DiscoveredAgent`) and
/// `ConnectOutcome` for the result of `connect_to_agent()`.
pub mod connectivity;

/// Gossip overlay networking for x0x.
pub mod gossip;

/// CRDT-based collaborative task lists.
pub mod crdt;

/// CRDT-backed key-value store.
pub mod kv;

/// High-level group management (MLS + KvStore + gossip).
pub mod groups;

/// MLS (Messaging Layer Security) group encryption.
pub mod mls;

/// A2A (Agent2Agent) interoperability — Agent Card adapter (ADR-0017).
pub mod a2a;

/// Direct agent-to-agent messaging.
///
/// Point-to-point communication that bypasses gossip for private,
/// efficient, reliable delivery between connected agents.
pub mod direct;

/// Direct messaging over gossip — the v1 C path per
/// `docs/design/dm-over-gossip.md`. Provides signed+encrypted envelopes,
/// recipient-specific inbox topics, dedupe, and application-layer ACKs.
pub mod dm;

/// Mesh-wide DM capability advertisement + cache. Senders consult this
/// store to decide whether to use the gossip DM path or fall back to
/// raw-QUIC for a given recipient.
pub mod dm_capability;

/// Background service that publishes this agent's capability advert and
/// consumes peers' adverts into a shared [`dm_capability::CapabilityStore`].
pub mod dm_capability_service;

/// Background service that subscribes to this agent's DM inbox topic,
/// verifies + decrypts incoming envelopes, and bridges them into
/// [`direct::DirectMessaging`].
pub mod dm_inbox;

/// Sender-side gossip DM path — envelope construction, publish + retry,
/// and `InFlightAcks` wait.
pub mod dm_send;

/// Application-level peer relay (X0X-0070) — Tailscale-style fallback that
/// wraps an opaque, end-to-end-encrypted [`dm::DmEnvelope`] in a cleartext,
/// signed [`peer_relay::RelayHeader`] so a third peer can forward a DM when
/// the direct path is unreachable.
pub mod peer_relay;

/// Presence system — beacons, FOAF discovery, and online/offline events.
pub mod presence;

/// Self-update system with ML-DSA-65 signature verification and staged rollout.
pub mod upgrade;

/// File transfer protocol types and state management.
pub mod files;

pub mod connect;
/// Secure Tier-1 remote exec protocol and runtime.
pub mod exec;

/// The x0x Constitution — The Four Laws of Intelligent Coexistence — embedded at compile time.
pub mod constitution;

/// Privacy-preserving log identifier wrappers (salted-hash redaction).
pub mod logging;

/// Shared API endpoint registry consumed by both x0xd and the x0x CLI.
pub mod api;

/// CLI infrastructure and command implementations.
pub mod cli;

/// HTTP/WebSocket server: axum router, handlers, and the daemon serving entrypoint.
pub mod server;

// Re-export key gossip types (including new pubsub components)
pub use gossip::{
    GossipConfig, GossipRuntime, PubSubManager, PubSubMessage, PubSubStats, PubSubStatsSnapshot,
    SigningContext, Subscription,
};

// Re-export direct messaging types
pub use direct::{DirectMessage, DirectMessageReceiver, DirectMessaging};

// Import Membership trait for HyParView join() method
use saorsa_gossip_membership::Membership as _;

/// The core agent that participates in the x0x gossip network.
///
/// Each agent is a peer — there is no client/server distinction.
/// Agents discover each other through gossip and communicate
/// via epidemic broadcast.
///
/// An Agent wraps an [`identity::Identity`] that provides:
/// - `machine_id`: Tied to this computer (for QUIC transport authentication)
/// - `agent_id`: Portable across machines (for agent persistence)
///
/// # Example
///
/// ```ignore
/// use x0x::Agent;
///
/// let agent = Agent::builder()
///     .build()
///     .await?;
///
/// println!("Agent ID: {}", agent.agent_id());
/// ```
pub struct Agent {
    identity: std::sync::Arc<identity::Identity>,
    /// The network node for P2P communication.
    #[allow(dead_code)]
    network: Option<std::sync::Arc<network::NetworkNode>>,
    /// The gossip runtime for pub/sub messaging.
    gossip_runtime: Option<std::sync::Arc<gossip::GossipRuntime>>,
    /// Bootstrap peer cache for quality-based peer selection across restarts.
    bootstrap_cache: Option<std::sync::Arc<ant_quic::BootstrapCache>>,
    /// Gossip cache adapter wrapping bootstrap_cache with coordinator advert storage.
    gossip_cache_adapter: Option<saorsa_gossip_coordinator::GossipCacheAdapter>,
    /// Cache of discovered agents from identity announcements.
    identity_discovery_cache: std::sync::Arc<
        tokio::sync::RwLock<std::collections::HashMap<identity::AgentId, DiscoveredAgent>>,
    >,
    /// Latest authenticated agent→machine bindings accepted from verified
    /// identity announcements. Unlike reachability caches, these bindings
    /// survive revocation eviction so relayed DMs cannot replace a revoked
    /// origin machine with an envelope-controlled claim.
    /// The bounded LRU is intentionally in-memory: restart and eviction degrade
    /// to the observable claimed-machine fallback until a verified announcement
    /// repopulates the binding. Protocol-level closure is tracked in issue #213.
    authenticated_machine_bindings: dm_inbox::AuthenticatedMachineBindings,
    /// Cache of discovered machine endpoints from machine announcements and
    /// agent→machine identity links.
    machine_discovery_cache: std::sync::Arc<
        tokio::sync::RwLock<std::collections::HashMap<identity::MachineId, DiscoveredMachine>>,
    >,
    /// Cache of discovered users from user announcements (self-asserted
    /// agent-ownership rosters).
    user_discovery_cache: std::sync::Arc<
        tokio::sync::RwLock<std::collections::HashMap<identity::UserId, DiscoveredUser>>,
    >,
    /// Ensures identity discovery listener is spawned once.
    identity_listener_started: std::sync::atomic::AtomicBool,
    /// How often to re-announce identity (seconds).
    heartbeat_interval_secs: u64,
    /// How long before a cache entry is filtered out (seconds).
    identity_ttl_secs: u64,
    /// Handle for the running heartbeat task, if started.
    heartbeat_handle: tokio::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
    /// Handle for the background discovery cache reaper task (periodic
    /// TTL pruning of identity/machine/user discovery caches). Added as
    /// the primary x0x-owned mitigation for the historical unbounded
    /// memory growth observed on long-running nodes.
    discovery_cache_reaper_handle: tokio::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
    /// Whether a rendezvous `ProviderSummary` advertisement is active.
    rendezvous_advertised: std::sync::atomic::AtomicBool,
    /// Contact store for trust evaluation of incoming identity announcements.
    contact_store: std::sync::Arc<tokio::sync::RwLock<contacts::ContactStore>>,
    /// Direct messaging infrastructure for point-to-point communication.
    direct_messaging: std::sync::Arc<direct::DirectMessaging>,
    /// Ensures network event reconciliation listener is spawned once.
    network_event_listener_started: std::sync::atomic::AtomicBool,
    /// Ensures direct message listener is spawned once.
    direct_listener_started: std::sync::atomic::AtomicBool,
    /// Presence system wrapper for beacons, FOAF discovery, and events.
    presence: Option<std::sync::Arc<presence::PresenceWrapper>>,
    /// Whether the user has consented to disclosing their identity in
    /// announcements.  Set by `announce_identity(true, true)` and respected
    /// by the heartbeat so it doesn't erase a consented disclosure.
    user_identity_consented: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// Capability store populated by the advert service and consulted by
    /// `send_direct` to choose between gossip and raw-QUIC paths.
    capability_store: std::sync::Arc<dm_capability::CapabilityStore>,
    /// Watch channel that carries this agent's *outgoing* DM capabilities.
    /// `join_network` spawns the advert service with a placeholder (empty
    /// KEM pubkey). `start_dm_inbox` upgrades via this sender to trigger
    /// immediate republish.
    dm_capabilities_tx: std::sync::Arc<tokio::sync::watch::Sender<dm::DmCapabilities>>,
    /// In-flight DM ACK waiters shared between `send_direct` and the inbox.
    dm_inflight_acks: std::sync::Arc<dm::InFlightAcks>,
    /// Receiver-side dedupe cache.
    recent_delivery_cache: std::sync::Arc<dm::RecentDeliveryCache>,
    /// Handle for the running capability advert service.
    capability_advert_service:
        tokio::sync::Mutex<Option<dm_capability_service::CapabilityAdvertService>>,
    /// Handle for the running DM inbox service.
    dm_inbox_service: tokio::sync::Mutex<Option<dm_inbox::DmInboxService>>,
    /// In-memory grow-only revocation set.  Gate checks hold only a read lock
    /// and never await while holding it — write lock is taken only when
    /// applying a new revocation (rare) and when persisting to disk.
    revocation_set: std::sync::Arc<tokio::sync::RwLock<revocation::RevocationSet>>,
    /// Identity-scoped directory.  When `Some`, revocations.bin is saved here
    /// instead of `~/.x0x/`.
    identity_dir: Option<std::path::PathBuf>,
    /// Cancellation token driving deterministic teardown of all long-lived
    /// Agent background loops (identity/network-event/direct listeners and the
    /// presence broadcast-peer refresh). Cancelling it makes every token-aware
    /// loop break promptly; `shutdown()` cancels it before tearing down gossip
    /// and the network so listeners (which call network methods) stop first.
    shutdown_token: tokio_util::sync::CancellationToken,
    /// Registry of tracked background-task handles. Once `closed` is set (by
    /// `shutdown()`), `spawn_tracked` refuses to spawn — this defeats the
    /// join_network race where a listener could otherwise start after shutdown
    /// began. A plain `std::sync::Mutex` (not tokio) keeps lock holds trivially
    /// short: never await while holding it.
    tracked_tasks: std::sync::Arc<std::sync::Mutex<TrackedTasks>>,
    /// X0X-0070b: application-level peer-relay engine. Records direct-DM
    /// successes and failures so [`peer_relay::PeerRelay::needs_relay`] can
    /// drive the fallback decision. The engine is disabled by default
    /// (matches [`peer_relay::RelayPolicy::default`]) - it only acts once a
    /// runtime opts in via `[peer_relay] enabled = true` in the daemon's
    /// `NetworkConfig` TOML.
    peer_relay: std::sync::Arc<peer_relay::PeerRelay>,
    /// X0X-0070b: pre-filtered set of relay candidates the engine picks from
    /// when the direct path fails. Seeded from `NetworkConfig.peer_relay.candidates`
    /// at build time; future revisions merge in gossip-announced candidates
    /// at runtime, hence the `RwLock` for mutable runtime state.
    relay_candidates: std::sync::Arc<tokio::sync::RwLock<Vec<identity::AgentId>>>,
    /// Tailnet byte-stream accept loop state (#132 T1): a bounded channel
    /// surfacing inbound [`streams::PeerStream`]s that have cleared the
    /// identity gate, plus an idempotent started-flag for the accept loop.
    stream_accept: std::sync::Arc<streams::StreamAccept>,
}

/// Closed-flag task registry for deterministic Agent teardown.
///
/// `spawn_tracked` pushes handles here while `closed` is false; `shutdown()`
/// sets `closed` and drains the handles. The flag closes the join_network
/// shutdown race: a spawn requested after `shutdown()` began is dropped rather
/// than leaked.
struct TrackedTasks {
    closed: bool,
    handles: Vec<tokio::task::JoinHandle<()>>,
}

impl std::fmt::Debug for Agent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Agent")
            .field("identity", &self.identity)
            .field("network", &self.network.is_some())
            .field("gossip_runtime", &self.gossip_runtime.is_some())
            .field("bootstrap_cache", &self.bootstrap_cache.is_some())
            .field("gossip_cache_adapter", &self.gossip_cache_adapter.is_some())
            .finish()
    }
}

impl Drop for Agent {
    fn drop(&mut self) {
        if let Ok(mut handle_guard) = self.heartbeat_handle.try_lock() {
            if let Some(handle) = handle_guard.take() {
                handle.abort();
            }
        }
        if let Ok(mut reaper_guard) = self.discovery_cache_reaper_handle.try_lock() {
            if let Some(handle) = reaper_guard.take() {
                handle.abort();
            }
        }
    }
}

/// A message received from the gossip network.
#[derive(Debug, Clone)]
pub struct Message {
    /// The originating agent's identifier.
    pub origin: String,
    /// The message payload.
    pub payload: Vec<u8>,
    /// The topic this message was published to.
    pub topic: String,
}

/// Reserved gossip topic for signed identity announcements.
///
/// **v2** carries additional `reachable_via` / `relay_candidates` fields for
/// NAT-aware coordinator hints. v1 is retired; v0.18.x is yanked.
pub const IDENTITY_ANNOUNCE_TOPIC: &str = "x0x.identity.announce.v2";

/// Reserved gossip topic for signed machine endpoint announcements.
///
/// **v2** carries the same NAT-aware coordinator hints as the identity
/// topic. v1 is retired.
pub const MACHINE_ANNOUNCE_TOPIC: &str = "x0x.machine.announce.v2";

/// Reserved gossip topic for signed user announcements.
///
/// A `UserAnnouncement` is a user-signed list of `AgentCertificate`s —
/// it is the user saying "these are my agents", independent of whether
/// any individual agent has consented to disclose its user binding.
/// First introduced in v2 wire format.
pub const USER_ANNOUNCE_TOPIC: &str = "x0x.user.announce.v2";

/// Reserved gossip topic for signed identity revocation records.
///
/// Payload is a `bincode`-encoded `Vec<revocation::RevocationRecord>`.
/// Records are re-verified on receipt before insertion into the local
/// [`revocation::RevocationSet`].  The full local set is re-broadcast on each identity
/// heartbeat for partition-tolerant eventual convergence.
pub const REVOCATION_TOPIC: &str = "x0x.revocation.v1";

/// Return the shard-specific gossip topic for the given `agent_id`.
///
/// Each agent publishes identity announcements to a deterministic shard topic
/// (`x0x.identity.shard.v2.<u16>`) derived from its agent ID, in addition to
/// the broadcast topic. This distributes announcements across 65,536 shards so
/// that at scale not every node is forced to receive every announcement.
///
/// The shard is computed with `saorsa_gossip_rendezvous::calculate_shard`, which
/// applies BLAKE3(`"saorsa-rendezvous" || agent_id`) and takes the low 16 bits.
#[must_use]
pub fn shard_topic_for_agent(agent_id: &identity::AgentId) -> String {
    let shard = saorsa_gossip_rendezvous::calculate_shard(&agent_id.0);
    format!("x0x.identity.shard.v2.{shard}")
}

/// Return the shard-specific gossip topic for the given `machine_id`.
///
/// Machine shards let callers actively wait for a transport endpoint by
/// machine identity, then resolve agent/user identities onto that endpoint.
#[must_use]
pub fn shard_topic_for_machine(machine_id: &identity::MachineId) -> String {
    let shard = saorsa_gossip_rendezvous::calculate_shard(&machine_id.0);
    format!("x0x.machine.shard.v2.{shard}")
}

/// Return the shard-specific gossip topic for the given `user_id`.
///
/// Users publish their agent-ownership roster to a deterministic shard so
/// seekers can look up "which agents does UserId(X) claim?" without a full
/// broadcast subscription.
#[must_use]
pub fn shard_topic_for_user(user_id: &identity::UserId) -> String {
    let shard = saorsa_gossip_rendezvous::calculate_shard(&user_id.0);
    format!("x0x.user.shard.v2.{shard}")
}

/// Gossip topic prefix for rendezvous `ProviderSummary` advertisements.
pub const RENDEZVOUS_SHARD_TOPIC_PREFIX: &str = "x0x.rendezvous.shard";

/// Return the rendezvous shard gossip topic for the given `agent_id`.
///
/// Agents publish [`saorsa_gossip_rendezvous::ProviderSummary`] records to this
/// topic so that seekers can find them even when the two peers have never been
/// on the same gossip overlay partition.
#[must_use]
pub fn rendezvous_shard_topic_for_agent(agent_id: &identity::AgentId) -> String {
    let shard = saorsa_gossip_rendezvous::calculate_shard(&agent_id.0);
    format!("{RENDEZVOUS_SHARD_TOPIC_PREFIX}.{shard}")
}

/// Returns `true` if the IP address is globally routable (reachable from the
/// public internet).  Used to filter announcement addresses so that private,
/// link-local, loopback, and other non-routable addresses never propagate
/// through gossip — they would create dead-end cache entries on remote nodes.
///
/// `IpAddr::is_global()` is nightly-only, so we implement the check manually.
fn is_globally_routable(ip: std::net::IpAddr) -> bool {
    match ip {
        std::net::IpAddr::V4(v4) => {
            !v4.is_private()           // 10/8, 172.16/12, 192.168/16
                && !v4.is_loopback()   // 127/8
                && !v4.is_link_local() // 169.254/16
                && !v4.is_unspecified() // 0.0.0.0
                && !v4.is_broadcast()  // 255.255.255.255
                && !v4.is_documentation() // 192.0.2/24, 198.51.100/24, 203.0.113/24
                // Shared address space (100.64/10, RFC 6598 — CGNAT)
                && !(v4.octets()[0] == 100 && (v4.octets()[1] & 0xC0) == 64)
        }
        std::net::IpAddr::V6(v6) => {
            let segs = v6.segments();
            !v6.is_loopback()                         // ::1
                && !v6.is_unspecified()               // ::
                && (segs[0] & 0xffc0) != 0xfe80       // link-local fe80::/10
                && (segs[0] & 0xfe00) != 0xfc00       // unique-local fc00::/7 (incl. fd00::/8)
                && (segs[0] & 0xfff0) != 0xfec0 // deprecated site-local fec0::/10
        }
    }
}

/// Whether an address is safe to publish on a globally-propagating channel
/// (identity heartbeat, agent card, presence beacon, gossip cache advert).
///
/// LAN-scoped discovery is handled by ant-quic's first-party mDNS on link-local
/// multicast, so we deliberately never share RFC1918, ULA, link-local, CGNAT,
/// or loopback addresses over global gossip. Remote peers cannot reach them,
/// and dialing them burns per-attempt connect budget on the receiver side.
///
/// This is stricter than `ant_quic::reachability::ReachabilityScope::Global`
/// because it also excludes CGNAT (100.64/10), documentation ranges, and
/// port-zero entries.
pub fn is_publicly_advertisable(addr: std::net::SocketAddr) -> bool {
    addr.port() > 0 && is_globally_routable(addr.ip())
}

fn filter_publicly_advertisable_addrs<I>(addresses: I) -> Vec<std::net::SocketAddr>
where
    I: IntoIterator<Item = std::net::SocketAddr>,
{
    addresses
        .into_iter()
        .filter(|addr| is_publicly_advertisable(*addr))
        .collect()
}

fn is_local_discovery_addr(addr: std::net::SocketAddr) -> bool {
    if addr.port() == 0 {
        return false;
    }
    match addr.ip() {
        std::net::IpAddr::V4(v4) => {
            !v4.is_unspecified()
                && !v4.is_broadcast()
                && !v4.is_documentation()
                && !v4.is_link_local()
        }
        std::net::IpAddr::V6(v6) => {
            let segs = v6.segments();
            !v6.is_unspecified() && (segs[0] & 0xffc0) != 0xfe80 && (segs[0] & 0xfff0) != 0xfec0
        }
    }
}

fn filter_local_discovery_addrs<I>(addresses: I) -> Vec<std::net::SocketAddr>
where
    I: IntoIterator<Item = std::net::SocketAddr>,
{
    let mut filtered = Vec::new();
    for addr in addresses {
        if is_local_discovery_addr(addr) && !filtered.contains(&addr) {
            filtered.push(addr);
        }
    }
    filtered
}

fn filter_discovery_announcement_addrs<I>(
    addresses: I,
    allow_local_scope: bool,
) -> Vec<std::net::SocketAddr>
where
    I: IntoIterator<Item = std::net::SocketAddr>,
{
    if allow_local_scope {
        filter_local_discovery_addrs(addresses)
    } else {
        filter_publicly_advertisable_addrs(addresses)
    }
}

/// Register a foreign agent's announced machine in the contact store.
///
/// Returns `true` if a new machine record was added, `false` otherwise
/// (the machine was already known, or the announcement is for the daemon's
/// own agent). The daemon deliberately never creates a contact entry for
/// itself: a self record would be noise on the `/contacts` surface and would
/// make contact-set assertions racy (issue #145). The two sibling actions in
/// the announce loop — epidemic re-broadcast and auto-connect — already
/// self-skip on `announced != own`; this helper makes the contact upsert the
/// third self-skipping site.
async fn register_announced_machine(
    contact_store: &std::sync::Arc<tokio::sync::RwLock<contacts::ContactStore>>,
    own_agent_id: identity::AgentId,
    announced_agent_id: identity::AgentId,
    announced_machine_id: identity::MachineId,
) -> bool {
    if announced_agent_id == own_agent_id {
        return false;
    }
    let mut store = contact_store.write().await;
    let record = contacts::MachineRecord::new(announced_machine_id, None);
    store.add_machine(&announced_agent_id, record)
}

fn local_scoped_bootstrap_addr(addr: std::net::SocketAddr) -> bool {
    if addr.port() == 0 {
        return false;
    }
    match addr.ip() {
        std::net::IpAddr::V4(v4) => {
            v4.is_loopback() || v4.is_private() || is_cgnat_v4(v4) || v4.is_link_local()
        }
        std::net::IpAddr::V6(v6) => {
            let segs = v6.segments();
            v6.is_loopback() || (segs[0] & 0xfe00) == 0xfc00 || (segs[0] & 0xffc0) == 0xfe80
        }
    }
}

fn allow_local_discovery_addresses(config: &network::NetworkConfig) -> bool {
    config.bootstrap_nodes.is_empty()
        || config
            .bootstrap_nodes
            .iter()
            .copied()
            .all(local_scoped_bootstrap_addr)
}

pub fn collect_local_interface_addrs(port: u16) -> Vec<std::net::SocketAddr> {
    fn is_cgnat(v4: std::net::Ipv4Addr) -> bool {
        v4.octets()[0] == 100 && (v4.octets()[1] & 0xC0) == 64
    }

    fn addr_priority(ip: std::net::IpAddr) -> u8 {
        match ip {
            std::net::IpAddr::V4(v4) => {
                if is_globally_routable(std::net::IpAddr::V4(v4)) {
                    0
                } else if is_cgnat(v4) {
                    1
                } else {
                    2
                }
            }
            std::net::IpAddr::V6(v6) => {
                if is_globally_routable(std::net::IpAddr::V6(v6)) {
                    3
                } else {
                    4
                }
            }
        }
    }

    let mut ranked = Vec::new();

    let interfaces = match if_addrs::get_if_addrs() {
        Ok(interfaces) => interfaces,
        Err(_) => return Vec::new(),
    };

    for iface in interfaces {
        let ip = iface.ip();
        if ip.is_unspecified() || ip.is_loopback() {
            continue;
        }

        let addr = match ip {
            std::net::IpAddr::V4(v4) => {
                if v4.is_link_local() {
                    continue;
                }
                std::net::SocketAddr::new(std::net::IpAddr::V4(v4), port)
            }
            std::net::IpAddr::V6(v6) => {
                let segs = v6.segments();
                let is_link_local = (segs[0] & 0xffc0) == 0xfe80;
                if is_link_local {
                    continue;
                }
                std::net::SocketAddr::new(std::net::IpAddr::V6(v6), port)
            }
        };

        if !ranked.iter().any(|(_, existing)| *existing == addr) {
            ranked.push((addr_priority(addr.ip()), addr));
        }
    }

    ranked.sort_by_key(|(priority, addr)| (*priority, addr.is_ipv6()));
    ranked.into_iter().map(|(_, addr)| addr).collect()
}

fn is_cgnat_v4(v4: std::net::Ipv4Addr) -> bool {
    v4.octets()[0] == 100 && (v4.octets()[1] & 0xC0) == 64
}

fn same_v4_24(a: std::net::Ipv4Addr, b: std::net::Ipv4Addr) -> bool {
    let a = a.octets();
    let b = b.octets();
    a[0] == b[0] && a[1] == b[1] && a[2] == b[2]
}

fn local_direct_probe_priority(
    addr: std::net::SocketAddr,
    local_v4s: &[std::net::Ipv4Addr],
) -> Option<u8> {
    let std::net::IpAddr::V4(v4) = addr.ip() else {
        return None;
    };
    if addr.port() == 0 || v4.is_loopback() || v4.is_link_local() || v4.is_unspecified() {
        return None;
    }
    if local_v4s.iter().any(|local| same_v4_24(*local, v4)) {
        return Some(0);
    }
    if v4.is_private() {
        return Some(1);
    }
    if is_cgnat_v4(v4) {
        return Some(2);
    }
    None
}

fn local_direct_probe_addrs_with_local_v4s(
    addresses: &[std::net::SocketAddr],
    local_v4s: &[std::net::Ipv4Addr],
) -> Vec<std::net::SocketAddr> {
    let mut ranked = addresses
        .iter()
        .copied()
        .filter_map(|addr| local_direct_probe_priority(addr, local_v4s).map(|rank| (rank, addr)))
        .collect::<Vec<_>>();
    ranked.sort_by_key(|(rank, addr)| (*rank, *addr));
    ranked.dedup_by_key(|(_, addr)| *addr);
    ranked.into_iter().map(|(_, addr)| addr).collect()
}

fn local_direct_probe_addrs(addresses: &[std::net::SocketAddr]) -> Vec<std::net::SocketAddr> {
    let local_v4s = collect_local_interface_addrs(0)
        .into_iter()
        .filter_map(|addr| match addr.ip() {
            std::net::IpAddr::V4(v4) => Some(v4),
            std::net::IpAddr::V6(_) => None,
        })
        .collect::<Vec<_>>();
    local_direct_probe_addrs_with_local_v4s(addresses, &local_v4s)
}

/// Default interval between identity heartbeat re-announcements (seconds).
///
/// Heartbeats are anti-entropy, not a hot-path delivery mechanism. Keep the
/// default at five minutes so bootstrap meshes do not spend their PubSub budget
/// on repeated signed identity/machine announcements. Each fresh announcement
/// still receives a one-shot receiver-side re-broadcast in
/// `start_identity_listener` for epidemic convergence.
pub const IDENTITY_HEARTBEAT_INTERVAL_SECS: u64 = 300;

/// Default TTL for discovered agent cache entries (seconds).
///
/// Entries not refreshed within this window are filtered from
/// [`Agent::presence`] and [`Agent::discovered_agents`].
pub const IDENTITY_TTL_SECS: u64 = 900;

const DISCOVERY_REBROADCAST_STATE_CAP: usize = 1024;
const DISCOVERY_REBROADCAST_STATE_TTL: std::time::Duration = std::time::Duration::from_secs(3600);

/// Interval (seconds) between runs of the background discovery cache reaper.
/// The reaper performs TTL-based pruning using the same identity_ttl
/// horizon as the query paths on the identity / machine / user discovery
/// HashMaps. This converts the caches from unbounded growth (only filtered
/// at read time) into bounded working-set + retention-window structures.
const DISCOVERY_CACHE_REAPER_INTERVAL_SECS: u64 = 120;

fn discovery_record_is_live(_announced_at: u64, last_seen: u64, cutoff: u64) -> bool {
    last_seen >= cutoff
}

fn should_rebroadcast_discovery_once<K>(
    state: &mut std::collections::HashMap<K, std::time::Instant>,
    key: K,
    now: std::time::Instant,
) -> bool
where
    K: Eq + std::hash::Hash,
{
    match state.entry(key) {
        std::collections::hash_map::Entry::Occupied(_) => false,
        std::collections::hash_map::Entry::Vacant(entry) => {
            entry.insert(now);
            if state.len() > DISCOVERY_REBROADCAST_STATE_CAP {
                if let Some(cutoff) = now.checked_sub(DISCOVERY_REBROADCAST_STATE_TTL) {
                    state.retain(|_, seen_at| *seen_at >= cutoff);
                }
            }
            true
        }
    }
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct IdentityAnnouncementUnsigned {
    agent_id: identity::AgentId,
    machine_id: identity::MachineId,
    user_id: Option<identity::UserId>,
    agent_certificate: Option<identity::AgentCertificate>,
    machine_public_key: Vec<u8>,
    addresses: Vec<std::net::SocketAddr>,
    announced_at: u64,
    /// NAT type string (e.g. "FullCone", "Symmetric", "Unknown").
    nat_type: Option<String>,
    /// Whether the machine can receive direct inbound connections.
    can_receive_direct: Option<bool>,
    /// Whether the machine advertises relay service capability to peers.
    ///
    /// This is a stable capability hint, not proof that the machine is
    /// actively relaying traffic right now.
    is_relay: Option<bool>,
    /// Whether the machine advertises coordinator capability to peers.
    ///
    /// This is a stable capability hint, not proof that the machine is
    /// actively coordinating a traversal right now.
    is_coordinator: Option<bool>,
    /// Coordinator machines through which this agent is reachable.
    ///
    /// When `can_receive_direct == Some(false)` (typically symmetric NAT),
    /// the advertising agent lists machine IDs of peers that can act as
    /// coordinators for hole-punching. Empty when the agent is directly
    /// reachable or has not yet learned any coordinator candidates.
    reachable_via: Vec<identity::MachineId>,
    /// Relay machines the advertising agent proposes as fallback paths.
    ///
    /// Used when hole-punching is not viable (extreme NAT). Empty by default.
    relay_candidates: Vec<identity::MachineId>,
}

/// Signed identity announcement broadcast by agents.
///
/// The outer pub/sub envelope is agent-signed (v2 message format), and this
/// payload is machine-signed to bind the daemon's PQC key to the announcement.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct IdentityAnnouncement {
    /// Portable agent identity.
    pub agent_id: identity::AgentId,
    /// Machine identity for the daemon process.
    pub machine_id: identity::MachineId,
    /// Optional human identity (only when explicitly consented).
    pub user_id: Option<identity::UserId>,
    /// Optional user->agent certificate.
    pub agent_certificate: Option<identity::AgentCertificate>,
    /// Machine ML-DSA-65 public key bytes.
    pub machine_public_key: Vec<u8>,
    /// Machine ML-DSA-65 signature over the unsigned announcement.
    pub machine_signature: Vec<u8>,
    /// Reachability hints.
    pub addresses: Vec<std::net::SocketAddr>,
    /// Unix timestamp (seconds) of announcement creation.
    pub announced_at: u64,
    /// NAT type as detected by the network layer (e.g. "FullCone", "Symmetric").
    /// `None` when the network is not yet started or NAT type is undetermined.
    pub nat_type: Option<String>,
    /// Whether the machine can receive direct inbound connections.
    /// `None` when the network is not yet started.
    pub can_receive_direct: Option<bool>,
    /// Whether the machine advertises relay service capability to peers.
    ///
    /// This is a stable capability hint derived from transport configuration,
    /// not proof that the machine is actively relaying traffic right now.
    /// `None` when the network is not yet started.
    pub is_relay: Option<bool>,
    /// Whether the machine advertises coordinator capability to peers.
    ///
    /// This is a stable capability hint derived from transport configuration,
    /// not proof that the machine is actively coordinating a traversal right
    /// now. `None` when the network is not yet started.
    pub is_coordinator: Option<bool>,
    /// Coordinator machines through which this agent is reachable.
    ///
    /// Populated when the agent is behind NAT that blocks direct inbound
    /// connections (`can_receive_direct == Some(false)`). Callers should
    /// dial one of these coordinators first, then hole-punch via peer-ID
    /// traversal. Empty when the agent is directly reachable or has no
    /// coordinator candidates yet.
    pub reachable_via: Vec<identity::MachineId>,
    /// Relay machines the advertising agent proposes as fallback paths.
    ///
    /// Used when hole-punching is not viable (e.g. endpoint-dependent
    /// mapping). Empty by default.
    pub relay_candidates: Vec<identity::MachineId>,
    /// Raw ML-DSA-65 agent public key bytes.
    ///
    /// Carried so peers can verify signed forward-header attestations (#204)
    /// without requiring the agent to carry a user→agent certificate. The key
    /// is **not** covered by `machine_signature` (it lives outside the
    /// unsigned announcement struct); instead it is self-certifying — the
    /// signed `agent_id` is `SHA-256(agent_public_key)`, so a recipient that
    /// checks the binding rejects a swapped key. Introduced in the v2 gossip
    /// envelope (`X0A2` magic prefix).
    pub agent_public_key: Vec<u8>,
}

impl IdentityAnnouncement {
    fn to_unsigned(&self) -> IdentityAnnouncementUnsigned {
        IdentityAnnouncementUnsigned {
            agent_id: self.agent_id,
            machine_id: self.machine_id,
            user_id: self.user_id,
            agent_certificate: self.agent_certificate.clone(),
            machine_public_key: self.machine_public_key.clone(),
            addresses: self.addresses.clone(),
            announced_at: self.announced_at,
            nat_type: self.nat_type.clone(),
            can_receive_direct: self.can_receive_direct,
            is_relay: self.is_relay,
            is_coordinator: self.is_coordinator,
            reachable_via: self.reachable_via.clone(),
            relay_candidates: self.relay_candidates.clone(),
        }
    }

    /// Verify machine-key attestation and optional user->agent certificate.
    pub fn verify(&self) -> error::Result<()> {
        let machine_pub =
            ant_quic::MlDsaPublicKey::from_bytes(&self.machine_public_key).map_err(|_| {
                error::IdentityError::CertificateVerification(
                    "invalid machine public key in announcement".to_string(),
                )
            })?;
        let derived_machine_id = identity::MachineId::from_public_key(&machine_pub);
        if derived_machine_id != self.machine_id {
            return Err(error::IdentityError::CertificateVerification(
                "machine_id does not match machine public key".to_string(),
            ));
        }

        let unsigned_bytes = bincode::serialize(&self.to_unsigned()).map_err(|e| {
            error::IdentityError::Serialization(format!(
                "failed to serialize announcement for verification: {e}"
            ))
        })?;
        let signature = ant_quic::crypto::raw_public_keys::pqc::MlDsaSignature::from_bytes(
            &self.machine_signature,
        )
        .map_err(|e| {
            error::IdentityError::CertificateVerification(format!(
                "invalid machine signature in announcement: {:?}",
                e
            ))
        })?;
        ant_quic::crypto::raw_public_keys::pqc::verify_with_ml_dsa(
            &machine_pub,
            &unsigned_bytes,
            &signature,
        )
        .map_err(|e| {
            error::IdentityError::CertificateVerification(format!(
                "machine signature verification failed: {:?}",
                e
            ))
        })?;

        match (self.user_id, self.agent_certificate.as_ref()) {
            (Some(user_id), Some(cert)) => {
                cert.verify()?;
                let cert_agent_id = cert.agent_id()?;
                if cert_agent_id != self.agent_id {
                    return Err(error::IdentityError::CertificateVerification(
                        "agent certificate agent_id mismatch".to_string(),
                    ));
                }
                let cert_user_id = cert.user_id()?;
                if cert_user_id != user_id {
                    return Err(error::IdentityError::CertificateVerification(
                        "agent certificate user_id mismatch".to_string(),
                    ));
                }
                Ok(())
            }
            (None, None) => Ok(()),
            _ => Err(error::IdentityError::CertificateVerification(
                "user identity disclosure requires matching certificate".to_string(),
            )),
        }
    }
}

/// Maximum accepted positive clock skew for identity announcements retained as
/// security bindings. Mirrors the direct-message freshness policy.
const IDENTITY_ANNOUNCEMENT_CLOCK_SKEW_SECS: u64 = dm::CLOCK_SKEW_TOLERANCE_MS / 1_000;

fn identity_announcement_timestamp_is_acceptable(announced_at: u64, now: u64) -> bool {
    announced_at <= now.saturating_add(IDENTITY_ANNOUNCEMENT_CLOCK_SKEW_SECS)
}

fn identity_announcement_has_direct_agent_origin(
    msg: &gossip::PubSubMessage,
    announcement: &IdentityAnnouncement,
) -> bool {
    if !msg.verified || msg.sender != Some(announcement.agent_id) {
        return false;
    }
    let Some(sender_public_key) = msg.sender_public_key.as_deref() else {
        return false;
    };
    let Ok(sender_public_key) = ant_quic::MlDsaPublicKey::from_bytes(sender_public_key) else {
        return false;
    };
    identity::AgentId::from_public_key(&sender_public_key) == announcement.agent_id
}

/// Record a security binding only for a fresh announcement observed directly
/// from its authenticated origin agent. Verified rebroadcasts remain eligible
/// for ordinary discovery but cannot populate or overwrite this cache.
async fn record_authenticated_machine_binding_from_message(
    bindings: &dm_inbox::AuthenticatedMachineBindings,
    msg: &gossip::PubSubMessage,
    announcement: &IdentityAnnouncement,
    now: u64,
) -> bool {
    if !identity_announcement_timestamp_is_acceptable(announcement.announced_at, now) {
        tracing::warn!(
            agent = %hex::encode(announcement.agent_id.as_bytes()),
            announced_at = announcement.announced_at,
            now,
            max_future_skew_secs = IDENTITY_ANNOUNCEMENT_CLOCK_SKEW_SECS,
            "ignoring far-future identity announcement for authenticated machine binding"
        );
        return false;
    }
    if !identity_announcement_has_direct_agent_origin(msg, announcement) {
        tracing::debug!(
            agent = %hex::encode(announcement.agent_id.as_bytes()),
            sender = ?msg.sender.map(|id| hex::encode(id.as_bytes())),
            "identity announcement is not direct-origin authenticated; retained binding unchanged"
        );
        return false;
    }
    dm_inbox::record_authenticated_machine_binding(
        bindings,
        announcement.agent_id,
        announcement.machine_id,
        announcement.announced_at,
    )
    .await;
    true
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct MachineAnnouncementUnsigned {
    machine_id: identity::MachineId,
    machine_public_key: Vec<u8>,
    addresses: Vec<std::net::SocketAddr>,
    announced_at: u64,
    /// NAT type string (e.g. "FullCone", "Symmetric", "Unknown").
    nat_type: Option<String>,
    /// Whether the machine can receive direct inbound connections.
    can_receive_direct: Option<bool>,
    /// Whether the machine advertises relay service capability to peers.
    is_relay: Option<bool>,
    /// Whether the machine advertises coordinator capability to peers.
    is_coordinator: Option<bool>,
    /// Coordinator machines through which this machine is reachable.
    reachable_via: Vec<identity::MachineId>,
    /// Relay machines the advertising machine proposes as fallback paths.
    relay_candidates: Vec<identity::MachineId>,
}

/// Signed machine endpoint announcement.
///
/// This is the transport-level discovery record: it says "machine X is
/// reachable at these IPv4/IPv6 endpoints, with these NAT/relay/coordinator
/// hints". Agent and user identities link to this machine separately through
/// signed identity announcements.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MachineAnnouncement {
    /// Machine identity for the daemon process.
    pub machine_id: identity::MachineId,
    /// Machine ML-DSA-65 public key bytes.
    pub machine_public_key: Vec<u8>,
    /// Machine ML-DSA-65 signature over the unsigned announcement.
    pub machine_signature: Vec<u8>,
    /// Reachability hints.
    pub addresses: Vec<std::net::SocketAddr>,
    /// Unix timestamp (seconds) of announcement creation.
    pub announced_at: u64,
    /// NAT type as detected by the network layer (e.g. "FullCone", "Symmetric").
    /// `None` when the network is not yet started or NAT type is undetermined.
    pub nat_type: Option<String>,
    /// Whether the machine can receive direct inbound connections.
    /// `None` when the network is not yet started.
    pub can_receive_direct: Option<bool>,
    /// Whether the machine advertises relay service capability to peers.
    pub is_relay: Option<bool>,
    /// Whether the machine advertises coordinator capability to peers.
    pub is_coordinator: Option<bool>,
    /// Coordinator machines through which this machine is reachable.
    ///
    /// Populated when the machine is behind NAT that blocks direct inbound
    /// connections. Callers should dial one of these coordinators first,
    /// then hole-punch via peer-ID traversal.
    pub reachable_via: Vec<identity::MachineId>,
    /// Relay machines this machine proposes as fallback paths.
    pub relay_candidates: Vec<identity::MachineId>,
}

impl MachineAnnouncement {
    fn to_unsigned(&self) -> MachineAnnouncementUnsigned {
        MachineAnnouncementUnsigned {
            machine_id: self.machine_id,
            machine_public_key: self.machine_public_key.clone(),
            addresses: self.addresses.clone(),
            announced_at: self.announced_at,
            nat_type: self.nat_type.clone(),
            can_receive_direct: self.can_receive_direct,
            is_relay: self.is_relay,
            is_coordinator: self.is_coordinator,
            reachable_via: self.reachable_via.clone(),
            relay_candidates: self.relay_candidates.clone(),
        }
    }

    /// Verify the machine-key attestation for this endpoint announcement.
    pub fn verify(&self) -> error::Result<()> {
        let machine_pub =
            ant_quic::MlDsaPublicKey::from_bytes(&self.machine_public_key).map_err(|_| {
                error::IdentityError::CertificateVerification(
                    "invalid machine public key in machine announcement".to_string(),
                )
            })?;
        let derived_machine_id = identity::MachineId::from_public_key(&machine_pub);
        if derived_machine_id != self.machine_id {
            return Err(error::IdentityError::CertificateVerification(
                "machine_id does not match machine public key".to_string(),
            ));
        }

        let unsigned_bytes = bincode::serialize(&self.to_unsigned()).map_err(|e| {
            error::IdentityError::Serialization(format!(
                "failed to serialize machine announcement for verification: {e}"
            ))
        })?;
        let signature = ant_quic::crypto::raw_public_keys::pqc::MlDsaSignature::from_bytes(
            &self.machine_signature,
        )
        .map_err(|e| {
            error::IdentityError::CertificateVerification(format!(
                "invalid machine signature in machine announcement: {:?}",
                e
            ))
        })?;
        ant_quic::crypto::raw_public_keys::pqc::verify_with_ml_dsa(
            &machine_pub,
            &unsigned_bytes,
            &signature,
        )
        .map_err(|e| {
            error::IdentityError::CertificateVerification(format!(
                "machine announcement signature verification failed: {:?}",
                e
            ))
        })
    }
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct UserAnnouncementUnsigned {
    user_id: identity::UserId,
    user_public_key: Vec<u8>,
    /// Certificates the user issued binding `UserId` to each of their agents.
    ///
    /// Recipients verify each certificate's ML-DSA-65 signature and that
    /// `certificate.user_id()` matches `user_id` in this announcement.
    agent_certificates: Vec<identity::AgentCertificate>,
    announced_at: u64,
}

/// Signed user announcement broadcast on [`USER_ANNOUNCE_TOPIC`].
///
/// Published by a human operator (via `Agent::announce_user_identity`) to
/// assert first-class ownership of a set of agents, independent of whether
/// any given agent has disclosed its user binding in its own heartbeat.
/// Each [`identity::AgentCertificate`] is itself user-signed, so recipients
/// can validate every agent-owner claim without trusting the enclosing
/// announcement's producer.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UserAnnouncement {
    /// Human identity.
    pub user_id: identity::UserId,
    /// User's ML-DSA-65 public key bytes.
    pub user_public_key: Vec<u8>,
    /// User ML-DSA-65 signature over the unsigned announcement.
    pub user_signature: Vec<u8>,
    /// Agent certificates issued by this user.
    pub agent_certificates: Vec<identity::AgentCertificate>,
    /// Unix timestamp (seconds) of announcement creation.
    pub announced_at: u64,
}

impl UserAnnouncement {
    fn to_unsigned(&self) -> UserAnnouncementUnsigned {
        UserAnnouncementUnsigned {
            user_id: self.user_id,
            user_public_key: self.user_public_key.clone(),
            agent_certificates: self.agent_certificates.clone(),
            announced_at: self.announced_at,
        }
    }

    /// Sign an announcement binding the given user keypair to the provided
    /// agent certificates. Each certificate must already have been issued by
    /// this user — verification fails for any cert whose `user_id()` differs.
    ///
    /// # Errors
    ///
    /// Returns an error if the user public key cannot be extracted, signing
    /// fails, or any certificate was issued by a different user.
    pub fn sign(
        user_kp: &identity::UserKeypair,
        agent_certificates: Vec<identity::AgentCertificate>,
        announced_at: u64,
    ) -> error::Result<Self> {
        let user_id = user_kp.user_id();
        // Reject certificates from a different user up front — silent drop
        // would hide a configuration bug.
        for cert in &agent_certificates {
            let cert_user = cert.user_id()?;
            if cert_user != user_id {
                return Err(error::IdentityError::CertificateVerification(
                    "user announcement contains certificate issued by a different user".to_string(),
                ));
            }
        }

        let user_public_key = user_kp.public_key().as_bytes().to_vec();
        let unsigned = UserAnnouncementUnsigned {
            user_id,
            user_public_key: user_public_key.clone(),
            agent_certificates: agent_certificates.clone(),
            announced_at,
        };
        let unsigned_bytes = bincode::serialize(&unsigned).map_err(|e| {
            error::IdentityError::Serialization(format!(
                "failed to serialize unsigned user announcement: {e}"
            ))
        })?;
        let user_signature = ant_quic::crypto::raw_public_keys::pqc::sign_with_ml_dsa(
            user_kp.secret_key(),
            &unsigned_bytes,
        )
        .map_err(|e| {
            error::IdentityError::Storage(std::io::Error::other(format!(
                "failed to sign user announcement with user key: {e:?}"
            )))
        })?
        .as_bytes()
        .to_vec();

        Ok(Self {
            user_id,
            user_public_key,
            user_signature,
            agent_certificates,
            announced_at,
        })
    }

    /// Verify the user signature and every embedded `AgentCertificate`.
    ///
    /// Checks:
    /// 1. `user_id` matches SHA-256 of `user_public_key`.
    /// 2. Outer ML-DSA-65 signature over the canonical unsigned form.
    /// 3. For each certificate: its signature verifies and its `user_id()`
    ///    equals this announcement's `user_id`.
    ///
    /// # Errors
    ///
    /// Returns an error describing which check failed.
    pub fn verify(&self) -> error::Result<()> {
        let user_pub =
            ant_quic::MlDsaPublicKey::from_bytes(&self.user_public_key).map_err(|_| {
                error::IdentityError::CertificateVerification(
                    "invalid user public key in user announcement".to_string(),
                )
            })?;
        let derived_user_id = identity::UserId::from_public_key(&user_pub);
        if derived_user_id != self.user_id {
            return Err(error::IdentityError::CertificateVerification(
                "user_id does not match user public key in user announcement".to_string(),
            ));
        }

        let unsigned_bytes = bincode::serialize(&self.to_unsigned()).map_err(|e| {
            error::IdentityError::Serialization(format!(
                "failed to serialize user announcement for verification: {e}"
            ))
        })?;
        let signature = ant_quic::crypto::raw_public_keys::pqc::MlDsaSignature::from_bytes(
            &self.user_signature,
        )
        .map_err(|e| {
            error::IdentityError::CertificateVerification(format!(
                "invalid user signature in user announcement: {e:?}"
            ))
        })?;
        ant_quic::crypto::raw_public_keys::pqc::verify_with_ml_dsa(
            &user_pub,
            &unsigned_bytes,
            &signature,
        )
        .map_err(|e| {
            error::IdentityError::CertificateVerification(format!(
                "user announcement signature verification failed: {e:?}"
            ))
        })?;

        for cert in &self.agent_certificates {
            cert.verify()?;
            let cert_user = cert.user_id()?;
            if cert_user != self.user_id {
                return Err(error::IdentityError::CertificateVerification(
                    "user announcement certificate user_id mismatch".to_string(),
                ));
            }
        }
        Ok(())
    }
}

/// Cached discovery data derived from [`UserAnnouncement`]s.
#[derive(Debug, Clone)]
pub struct DiscoveredUser {
    /// Human identity.
    pub user_id: identity::UserId,
    /// Raw ML-DSA-65 user public key bytes from the last verified announcement.
    pub user_public_key: Vec<u8>,
    /// Certificates the user has asserted ownership of.
    pub agent_certificates: Vec<identity::AgentCertificate>,
    /// Convenience list of agent IDs derived from the certificates.
    pub agent_ids: Vec<identity::AgentId>,
    /// Announcement timestamp from the sender.
    pub announced_at: u64,
    /// Local timestamp (seconds) when this record was last updated.
    pub last_seen: u64,
}

impl DiscoveredUser {
    fn from_announcement(announcement: &UserAnnouncement, last_seen: u64) -> Self {
        let agent_ids: Vec<identity::AgentId> = announcement
            .agent_certificates
            .iter()
            .filter_map(|c| c.agent_id().ok())
            .collect();
        Self {
            user_id: announcement.user_id,
            user_public_key: announcement.user_public_key.clone(),
            agent_certificates: announcement.agent_certificates.clone(),
            agent_ids,
            announced_at: announcement.announced_at,
            last_seen,
        }
    }
}

/// Cached discovery data derived from identity announcements.
#[derive(Debug, Clone)]
pub struct DiscoveredAgent {
    /// Portable agent identity.
    pub agent_id: identity::AgentId,
    /// Machine identity.
    pub machine_id: identity::MachineId,
    /// Optional human identity (when consented and attested).
    pub user_id: Option<identity::UserId>,
    /// Reachability hints.
    pub addresses: Vec<std::net::SocketAddr>,
    /// Announcement timestamp from the sender.
    pub announced_at: u64,
    /// Local timestamp (seconds) when this record was last updated.
    pub last_seen: u64,
    /// Raw ML-DSA-65 machine public key bytes from the announcement.
    ///
    /// Used to verify rendezvous `ProviderSummary` signatures before
    /// trusting addresses received via the rendezvous shard topic.
    #[doc(hidden)]
    pub machine_public_key: Vec<u8>,
    /// NAT type reported by this agent (e.g. "FullCone", "Symmetric", "Unknown").
    /// `None` if the agent did not include NAT information.
    pub nat_type: Option<String>,
    /// Whether this agent's machine can receive direct inbound connections.
    /// `None` if not reported.
    pub can_receive_direct: Option<bool>,
    /// Whether this agent's machine advertises relay service capability.
    /// `None` if not reported.
    pub is_relay: Option<bool>,
    /// Whether this agent's machine advertises coordinator capability.
    /// `None` if not reported.
    pub is_coordinator: Option<bool>,
    /// Coordinator machines through which this agent advertises itself as
    /// reachable when behind NAT that blocks direct inbound connections.
    pub reachable_via: Vec<identity::MachineId>,
    /// Relay machines this agent proposes as fallback paths.
    pub relay_candidates: Vec<identity::MachineId>,
    /// Expiry timestamp from the agent certificate embedded in the
    /// identity announcement, if any.  `None` means the cert carries no
    /// expiry — the agent is considered valid indefinitely.
    pub cert_not_after: Option<u64>,
    /// The agent certificate embedded in the identity announcement, if any.
    ///
    /// Retained so a gossiped **issuer-revocation** (a user un-vouching this
    /// agent) can be authority-verified on receipt: `verify_authority` for an
    /// issuer-revocation requires the subject cert (issue #191). `None` for
    /// pre-#130 peers that announce no cert, and for machine/rendezvous-only
    /// cache entries.
    pub agent_certificate: Option<identity::AgentCertificate>,
    /// Raw ML-DSA-65 agent public key bytes from the v2 gossip envelope
    /// (or recovered from the cert on legacy announcements).
    ///
    /// Used by the forward-attestation path (#204) to verify the inbound
    /// `ForwardV2` header signature: the opener signs with its agent secret
    /// key, the verifier looks up this cached key, confirms the agent is on
    /// the transport-authenticated machine, and checks the binding
    /// (`agent_id == SHA-256(agent_public_key)`). Empty when no key has
    /// propagated — the agent cannot be attested and a `ForwardV2` stream
    /// is denied fail-closed.
    pub agent_public_key: Vec<u8>,
}

/// Cached machine endpoint data derived from signed machine announcements.
#[derive(Debug, Clone)]
pub struct DiscoveredMachine {
    /// Machine identity, identical to the ant-quic `PeerId`.
    pub machine_id: identity::MachineId,
    /// Reachability hints for this machine.
    pub addresses: Vec<std::net::SocketAddr>,
    /// Announcement timestamp from the sender.
    pub announced_at: u64,
    /// Local timestamp (seconds) when this record was last updated.
    pub last_seen: u64,
    /// Raw ML-DSA-65 machine public key bytes from the announcement.
    pub machine_public_key: Vec<u8>,
    /// NAT type reported by this machine.
    pub nat_type: Option<String>,
    /// Whether this machine can receive direct inbound connections.
    pub can_receive_direct: Option<bool>,
    /// Whether this machine advertises relay service capability.
    pub is_relay: Option<bool>,
    /// Whether this machine advertises coordinator capability.
    pub is_coordinator: Option<bool>,
    /// Coordinator machines through which this machine advertises itself as
    /// reachable when it cannot receive direct inbound connections.
    pub reachable_via: Vec<identity::MachineId>,
    /// Relay machines this machine proposes as fallback paths.
    pub relay_candidates: Vec<identity::MachineId>,
    /// Agent identities currently linked to this machine.
    pub agent_ids: Vec<identity::AgentId>,
    /// Human identities currently linked to this machine by consented agent
    /// announcements.
    pub user_ids: Vec<identity::UserId>,
}

/// Build a `subject AgentId → AgentCertificate` lookup from the discovery
/// cache, used to authority-verify gossiped **issuer-revocations** (a user
/// un-vouching a certified agent) on receipt (issue #191).
///
/// `verify_authority` for an issuer-revocation requires the subject agent's
/// certificate; self-revocations and machine-revocations need none. Only
/// entries that actually carry a cert contribute; entries without one
/// (pre-#130 peers, machine/rendezvous-only entries) are absent, so an
/// issuer-revocation for such a subject is rejected fail-closed by the
/// caller — the cert must have been announced first (EP1).
fn collect_subject_certs(
    cache: &std::collections::HashMap<identity::AgentId, DiscoveredAgent>,
) -> std::collections::HashMap<identity::AgentId, identity::AgentCertificate> {
    cache
        .values()
        .filter_map(|a| {
            a.agent_certificate
                .as_ref()
                .map(|c| (a.agent_id, c.clone()))
        })
        .collect()
}

impl DiscoveredMachine {
    fn from_machine_announcement(
        announcement: &MachineAnnouncement,
        addresses: Vec<std::net::SocketAddr>,
        last_seen: u64,
    ) -> Self {
        Self {
            machine_id: announcement.machine_id,
            addresses,
            announced_at: announcement.announced_at,
            last_seen,
            machine_public_key: announcement.machine_public_key.clone(),
            nat_type: announcement.nat_type.clone(),
            can_receive_direct: announcement.can_receive_direct,
            is_relay: announcement.is_relay,
            is_coordinator: announcement.is_coordinator,
            reachable_via: announcement.reachable_via.clone(),
            relay_candidates: announcement.relay_candidates.clone(),
            agent_ids: Vec::new(),
            user_ids: Vec::new(),
        }
    }

    fn from_discovered_agent(agent: &DiscoveredAgent) -> Self {
        Self {
            machine_id: agent.machine_id,
            addresses: agent.addresses.clone(),
            announced_at: agent.announced_at,
            last_seen: agent.last_seen,
            machine_public_key: agent.machine_public_key.clone(),
            nat_type: agent.nat_type.clone(),
            can_receive_direct: agent.can_receive_direct,
            is_relay: agent.is_relay,
            is_coordinator: agent.is_coordinator,
            reachable_via: agent.reachable_via.clone(),
            relay_candidates: agent.relay_candidates.clone(),
            agent_ids: vec![agent.agent_id],
            user_ids: agent.user_id.into_iter().collect(),
        }
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct AnnouncementAssistSnapshot {
    nat_type: Option<String>,
    can_receive_direct: Option<bool>,
    relay_capable: Option<bool>,
    coordinator_capable: Option<bool>,
    relay_active: Option<bool>,
    coordinator_active: Option<bool>,
}

impl AnnouncementAssistSnapshot {
    fn from_node_status(status: &ant_quic::NodeStatus) -> Self {
        Self {
            nat_type: Some(status.nat_type.to_string()),
            can_receive_direct: Some(status.can_receive_direct),
            relay_capable: Some(status.relay_service_enabled),
            coordinator_capable: Some(status.coordinator_service_enabled),
            relay_active: Some(status.is_relaying),
            coordinator_active: Some(status.is_coordinating),
        }
    }
}

struct IdentityAnnouncementBuildOptions<'a> {
    include_user_identity: bool,
    human_consent: bool,
    addresses: Vec<std::net::SocketAddr>,
    assist_snapshot: Option<&'a AnnouncementAssistSnapshot>,
    reachable_via: Vec<identity::MachineId>,
    relay_candidates: Vec<identity::MachineId>,
    allow_local_scope: bool,
}

fn push_unique<T: Copy + PartialEq>(items: &mut Vec<T>, item: T) {
    if !items.contains(&item) {
        items.push(item);
    }
}

fn prioritize_discovery_addresses(addresses: &mut [std::net::SocketAddr]) {
    addresses.sort_by_key(|addr| is_publicly_advertisable(*addr));
}

/// Merge a freshly-discovered agent announcement into the cache.
///
/// Per-field precedence is keyed on `announced_at` (the signed announcement's
/// own monotonic timestamp), not local receive time:
/// - **addresses** reflect the agent's *current* advertised set. A fresher (or
///   equal) announcement REPLACES the cached list; a stale announcement leaves
///   it untouched. Announcements carry the agent's full address set, so
///   replacing — not unioning — keeps the list bounded: a roaming agent
///   (Wi-Fi → cellular → VPN) does not accumulate dead endpoints, each of which
///   would otherwise cost a dial timeout in `connect_to_*` / `direct_probe`.
/// - **machine_id / public key / nat / capability / relay hints** update only
///   from a fresher-or-equal announcement, and only when present — a zeroed
///   machine_id or empty key never clobbers a known value.
/// - **user_id** is never erased: a fresher *anonymous* announcement keeps a
///   previously-disclosed user_id.
/// - **last_seen** reflects the most recent receive: it is set from the
///   incoming record (matching the pre-merge replace semantics). In production
///   `incoming.last_seen` is the current receive time, so it only moves forward;
///   it is NOT clamped with `max`, because the TTL/presence filter must be able
///   to observe an entry that has genuinely aged past its window (a `max` clamp
///   would let a once-fresh entry mask a later stale observation and never
///   expire — see `test_ttl_expiry_removes_from_presence`).
async fn upsert_discovered_agent(
    cache: &std::sync::Arc<
        tokio::sync::RwLock<std::collections::HashMap<identity::AgentId, DiscoveredAgent>>,
    >,
    mut incoming: DiscoveredAgent,
) {
    prioritize_discovery_addresses(&mut incoming.addresses);
    let mut cache = cache.write().await;
    match cache.get_mut(&incoming.agent_id) {
        Some(existing) => {
            if incoming.announced_at >= existing.announced_at {
                existing.announced_at = incoming.announced_at;
                // Replace, don't union: the announcement carries the agent's
                // full current address set, so the cached list stays bounded.
                existing.addresses = incoming.addresses;
                prioritize_discovery_addresses(&mut existing.addresses);
                if incoming.machine_id.0 != [0u8; 32] {
                    existing.machine_id = incoming.machine_id;
                }
                if incoming.user_id.is_some() || existing.user_id.is_none() {
                    existing.user_id = incoming.user_id;
                }
                if !incoming.machine_public_key.is_empty() {
                    existing.machine_public_key = incoming.machine_public_key;
                }
                if incoming.nat_type.is_some() {
                    existing.nat_type = incoming.nat_type;
                }
                if incoming.can_receive_direct.is_some() {
                    existing.can_receive_direct = incoming.can_receive_direct;
                }
                if incoming.is_relay.is_some() {
                    existing.is_relay = incoming.is_relay;
                }
                if incoming.is_coordinator.is_some() {
                    existing.is_coordinator = incoming.is_coordinator;
                }
                existing.reachable_via = incoming.reachable_via;
                existing.relay_candidates = incoming.relay_candidates;
                // LWW the agent public key — a v2 announcement always
                // carries it; a legacy/rendezvous entry may not (#204).
                if !incoming.agent_public_key.is_empty() {
                    existing.agent_public_key = incoming.agent_public_key;
                }
            }
            existing.last_seen = incoming.last_seen;
        }
        None => {
            cache.insert(incoming.agent_id, incoming);
        }
    }
}

fn sort_discovered_machine(machine: &mut DiscoveredMachine) {
    machine.addresses.sort_by_key(|addr| addr.to_string());
    machine.agent_ids.sort_by_key(|id| id.0);
    machine.user_ids.sort_by_key(|id| id.0);
    machine.reachable_via.sort_by_key(|id| id.0);
    machine.relay_candidates.sort_by_key(|id| id.0);
}

async fn upsert_discovered_machine(
    cache: &std::sync::Arc<
        tokio::sync::RwLock<std::collections::HashMap<identity::MachineId, DiscoveredMachine>>,
    >,
    mut incoming: DiscoveredMachine,
) {
    if incoming.machine_id.0 == [0u8; 32] {
        return;
    }

    sort_discovered_machine(&mut incoming);
    let mut cache = cache.write().await;
    match cache.get_mut(&incoming.machine_id) {
        Some(existing) => {
            for addr in incoming.addresses {
                if !existing.addresses.contains(&addr) {
                    existing.addresses.push(addr);
                }
            }
            if incoming.announced_at >= existing.announced_at {
                existing.announced_at = incoming.announced_at;
                if !incoming.machine_public_key.is_empty() {
                    existing.machine_public_key = incoming.machine_public_key;
                }
                if incoming.nat_type.is_some() {
                    existing.nat_type = incoming.nat_type;
                }
                if incoming.can_receive_direct.is_some() {
                    existing.can_receive_direct = incoming.can_receive_direct;
                }
                if incoming.is_relay.is_some() {
                    existing.is_relay = incoming.is_relay;
                }
                if incoming.is_coordinator.is_some() {
                    existing.is_coordinator = incoming.is_coordinator;
                }
                // Coordinator / relay hint lists are LWW: the newest
                // announcement knows best whether its set has shrunk
                // (e.g. a coordinator peer just disconnected).
                existing.reachable_via = incoming.reachable_via;
                existing.relay_candidates = incoming.relay_candidates;
            }
            existing.last_seen = existing.last_seen.max(incoming.last_seen);
            for agent_id in incoming.agent_ids {
                push_unique(&mut existing.agent_ids, agent_id);
            }
            for user_id in incoming.user_ids {
                push_unique(&mut existing.user_ids, user_id);
            }
            sort_discovered_machine(existing);
        }
        None => {
            cache.insert(incoming.machine_id, incoming);
        }
    }
}

async fn upsert_discovered_machine_from_agent(
    cache: &std::sync::Arc<
        tokio::sync::RwLock<std::collections::HashMap<identity::MachineId, DiscoveredMachine>>,
    >,
    agent: &DiscoveredAgent,
) {
    if agent.machine_id.0 != [0u8; 32] {
        upsert_discovered_machine(cache, DiscoveredMachine::from_discovered_agent(agent)).await;
    }
}

const MAX_MACHINE_ANNOUNCEMENT_DECODE_BYTES: u64 = 64 * 1024;

/// Magic prefix marking an identity announcement that carries the agent
/// public key (the v2 gossip envelope, #204). A legacy announcement begins
/// with the bincode bytes of `agent_id` (a 32-byte fixed array) — the first
/// four bytes are a hash prefix, so `b"X0A2"` is collision-resistant in the
/// same way the on-disk cert `X0C2` marker is.
const IDENTITY_ANNOUNCEMENT_V2_MAGIC: &[u8; 4] = b"X0A2";

/// Serialize an identity announcement in the v2 envelope (magic prefix +
/// bincode). The magic lets a new peer distinguish v2 (carries
/// `agent_public_key`) from legacy payloads.
fn serialize_identity_announcement(
    announcement: &IdentityAnnouncement,
) -> Result<Vec<u8>, Box<bincode::ErrorKind>> {
    use bincode::Options;
    let body = bincode::DefaultOptions::new()
        .with_fixint_encoding()
        .serialize(announcement)?;
    let mut out = Vec::with_capacity(IDENTITY_ANNOUNCEMENT_V2_MAGIC.len() + body.len());
    out.extend_from_slice(IDENTITY_ANNOUNCEMENT_V2_MAGIC);
    out.extend_from_slice(&body);
    Ok(out)
}

/// Legacy identity-announcement wire shape (pre-#204): identical to
/// [`IdentityAnnouncement`] minus the trailing `agent_public_key` field.
/// Used only to deserialize payloads from old peers so they still populate
/// the discovery cache (the key is recovered from the embedded certificate
/// when present).
#[derive(serde::Serialize, serde::Deserialize)]
struct IdentityAnnouncementLegacy {
    agent_id: identity::AgentId,
    machine_id: identity::MachineId,
    user_id: Option<identity::UserId>,
    agent_certificate: Option<identity::AgentCertificate>,
    machine_public_key: Vec<u8>,
    machine_signature: Vec<u8>,
    addresses: Vec<std::net::SocketAddr>,
    announced_at: u64,
    nat_type: Option<String>,
    can_receive_direct: Option<bool>,
    is_relay: Option<bool>,
    is_coordinator: Option<bool>,
    reachable_via: Vec<identity::MachineId>,
    relay_candidates: Vec<identity::MachineId>,
}

impl IdentityAnnouncementLegacy {
    /// Convert a legacy payload into the current announcement shape,
    /// recovering the agent public key from the embedded certificate when
    /// one is present (empty when not — the agent simply cannot be
    /// attested until a v2 announcement propagates).
    fn into_announcement(self) -> IdentityAnnouncement {
        let agent_public_key = self
            .agent_certificate
            .as_ref()
            .map(|c| c.agent_public_key().to_vec())
            .unwrap_or_default();
        IdentityAnnouncement {
            agent_id: self.agent_id,
            machine_id: self.machine_id,
            user_id: self.user_id,
            agent_certificate: self.agent_certificate,
            machine_public_key: self.machine_public_key,
            machine_signature: self.machine_signature,
            addresses: self.addresses,
            announced_at: self.announced_at,
            nat_type: self.nat_type,
            can_receive_direct: self.can_receive_direct,
            is_relay: self.is_relay,
            is_coordinator: self.is_coordinator,
            reachable_via: self.reachable_via,
            relay_candidates: self.relay_candidates,
            agent_public_key,
        }
    }
}

fn deserialize_identity_announcement(
    payload: &[u8],
) -> std::result::Result<IdentityAnnouncement, Box<bincode::ErrorKind>> {
    use bincode::Options;
    let opts = || {
        bincode::DefaultOptions::new()
            .with_fixint_encoding()
            .with_limit(crate::network::MAX_MESSAGE_DESERIALIZE_SIZE)
            .reject_trailing_bytes()
    };
    // v2 envelope: magic prefix + bincode(IdentityAnnouncement).
    if payload.len() >= IDENTITY_ANNOUNCEMENT_V2_MAGIC.len()
        && &payload[..IDENTITY_ANNOUNCEMENT_V2_MAGIC.len()] == IDENTITY_ANNOUNCEMENT_V2_MAGIC
    {
        return opts().deserialize(&payload[IDENTITY_ANNOUNCEMENT_V2_MAGIC.len()..]);
    }
    // Legacy envelope: bincode(IdentityAnnouncementLegacy) — recover the key
    // from the cert when present.
    let legacy: IdentityAnnouncementLegacy = opts().deserialize(payload)?;
    Ok(legacy.into_announcement())
}

fn deserialize_user_announcement(
    payload: &[u8],
) -> std::result::Result<UserAnnouncement, Box<bincode::ErrorKind>> {
    use bincode::Options;
    bincode::DefaultOptions::new()
        .with_fixint_encoding()
        .with_limit(crate::network::MAX_MESSAGE_DESERIALIZE_SIZE)
        .reject_trailing_bytes()
        .deserialize(payload)
}

fn deserialize_machine_announcement(
    payload: &[u8],
) -> std::result::Result<MachineAnnouncement, Box<bincode::ErrorKind>> {
    use bincode::Options;
    bincode::DefaultOptions::new()
        .with_fixint_encoding()
        .with_limit(MAX_MACHINE_ANNOUNCEMENT_DECODE_BYTES)
        .reject_trailing_bytes()
        .deserialize(payload)
}

/// Compute coordinator / relay hint lists for an announcement.
///
/// Collects machine IDs of currently-connected peers that the machine cache
/// marks as coordinator- or relay-capable. Deduplicated, capped to
/// `MAX_COORDINATOR_HINTS` each, and returned in stable order.
///
/// Used to populate `reachable_via` / `relay_candidates` on outgoing
/// announcements so that remote peers have concrete targets to dial when
/// the advertising machine is NAT-locked.
async fn collect_coordinator_hints(
    network: &network::NetworkNode,
    machine_cache: &std::sync::Arc<
        tokio::sync::RwLock<std::collections::HashMap<identity::MachineId, DiscoveredMachine>>,
    >,
    own_machine_id: identity::MachineId,
) -> (Vec<identity::MachineId>, Vec<identity::MachineId>) {
    /// Upper bound on hint list length. Keeps the signed payload small and
    /// avoids amplifying gossip if we accumulate many peers.
    const MAX_COORDINATOR_HINTS: usize = 8;

    let connected = network.connected_peers().await;
    if connected.is_empty() {
        return (Vec::new(), Vec::new());
    }

    let cache = machine_cache.read().await;
    let mut reachable_via: Vec<identity::MachineId> = Vec::new();
    let mut relay_candidates: Vec<identity::MachineId> = Vec::new();

    for peer_id in connected {
        let mid = identity::MachineId(peer_id.0);
        if mid == own_machine_id {
            continue;
        }
        let Some(entry) = cache.get(&mid) else {
            continue;
        };
        if entry.is_coordinator == Some(true)
            && !reachable_via.contains(&mid)
            && reachable_via.len() < MAX_COORDINATOR_HINTS
        {
            reachable_via.push(mid);
        }
        if entry.is_relay == Some(true)
            && !relay_candidates.contains(&mid)
            && relay_candidates.len() < MAX_COORDINATOR_HINTS
        {
            relay_candidates.push(mid);
        }
    }

    reachable_via.sort_by_key(|id| id.0);
    relay_candidates.sort_by_key(|id| id.0);
    (reachable_via, relay_candidates)
}

fn build_machine_announcement_for_identity(
    identity: &identity::Identity,
    addresses: Vec<std::net::SocketAddr>,
    announced_at: u64,
    assist_snapshot: Option<&AnnouncementAssistSnapshot>,
    reachable_via: Vec<identity::MachineId>,
    relay_candidates: Vec<identity::MachineId>,
    allow_local_scope: bool,
) -> error::Result<MachineAnnouncement> {
    let addresses = filter_discovery_announcement_addrs(addresses, allow_local_scope);
    let machine_public_key = identity.machine_keypair().public_key().as_bytes().to_vec();
    let unsigned = MachineAnnouncementUnsigned {
        machine_id: identity.machine_id(),
        machine_public_key: machine_public_key.clone(),
        addresses,
        announced_at,
        nat_type: assist_snapshot.and_then(|snapshot| snapshot.nat_type.clone()),
        can_receive_direct: assist_snapshot.and_then(|snapshot| snapshot.can_receive_direct),
        is_relay: assist_snapshot.and_then(|snapshot| snapshot.relay_capable),
        is_coordinator: assist_snapshot.and_then(|snapshot| snapshot.coordinator_capable),
        reachable_via,
        relay_candidates,
    };
    let unsigned_bytes = bincode::serialize(&unsigned).map_err(|e| {
        error::IdentityError::Serialization(format!(
            "failed to serialize unsigned machine announcement: {e}"
        ))
    })?;
    let machine_signature = ant_quic::crypto::raw_public_keys::pqc::sign_with_ml_dsa(
        identity.machine_keypair().secret_key(),
        &unsigned_bytes,
    )
    .map_err(|e| {
        error::IdentityError::Storage(std::io::Error::other(format!(
            "failed to sign machine announcement with machine key: {:?}",
            e
        )))
    })?
    .as_bytes()
    .to_vec();

    Ok(MachineAnnouncement {
        machine_id: unsigned.machine_id,
        machine_public_key,
        machine_signature,
        addresses: unsigned.addresses,
        announced_at: unsigned.announced_at,
        nat_type: unsigned.nat_type,
        can_receive_direct: unsigned.can_receive_direct,
        is_relay: unsigned.is_relay,
        is_coordinator: unsigned.is_coordinator,
        reachable_via: unsigned.reachable_via,
        relay_candidates: unsigned.relay_candidates,
    })
}

/// Builder for configuring an [`Agent`] before connecting to the network.
///
/// The builder allows customization of the agent's identity:
/// - Machine key path: Where to store/load the machine keypair
/// - Agent keypair: Import a portable agent identity from another machine
/// - User keypair: Bind a human identity to this agent
///
/// # Example
///
/// ```ignore
/// use x0x::Agent;
///
/// // Default: auto-generates both keypairs
/// let agent = Agent::builder()
///     .build()
///     .await?;
///
/// // Custom machine key path
/// let agent = Agent::builder()
///     .with_machine_key("/custom/path/machine.key")
///     .build()
///     .await?;
///
/// // Import agent keypair
/// let agent_kp = load_agent_keypair()?;
/// let agent = Agent::builder()
///     .with_agent_key(agent_kp)
///     .build()
///     .await?;
///
/// // With user identity (three-layer)
/// let agent = Agent::builder()
///     .with_user_key_path("~/.x0x/user.key")
///     .build()
///     .await?;
/// ```
#[derive(Debug)]
pub struct AgentBuilder {
    machine_key_path: Option<std::path::PathBuf>,
    agent_keypair: Option<identity::AgentKeypair>,
    agent_key_path: Option<std::path::PathBuf>,
    /// Custom path for `agent.cert`. When set, the cert is loaded/saved from
    /// this path instead of `~/.x0x/agent.cert`. Required for multi-daemon
    /// setups on the same host — with a shared cert file, last-writer-wins
    /// trampling would cause the victim daemon to announce its own agent_id
    /// paired with another daemon's cert, and peers would reject as
    /// "agent certificate agent_id mismatch".
    agent_cert_path: Option<std::path::PathBuf>,
    user_keypair: Option<identity::UserKeypair>,
    user_key_path: Option<std::path::PathBuf>,
    #[allow(dead_code)]
    network_config: Option<network::NetworkConfig>,
    gossip_config: Option<gossip::GossipConfig>,
    peer_cache_dir: Option<std::path::PathBuf>,
    /// When true, skip opening the bootstrap peer cache entirely.
    /// Useful for fully isolated embedders and test harnesses.
    disable_peer_cache: bool,
    heartbeat_interval_secs: Option<u64>,
    identity_ttl_secs: Option<u64>,
    presence_beacon_interval_secs: Option<u64>,
    presence_event_poll_interval_secs: Option<u64>,
    presence_offline_timeout_secs: Option<u64>,
    /// Custom path for the contacts file.
    contact_store_path: Option<std::path::PathBuf>,
    /// Directory that scopes all identity-related files (keys, cert,
    /// revocations.bin).  When set, revocations are loaded/saved there
    /// instead of the default `~/.x0x/` directory.
    identity_dir: Option<std::path::PathBuf>,
}

/// Context captured by the background identity heartbeat task.
struct HeartbeatContext {
    identity: std::sync::Arc<identity::Identity>,
    runtime: std::sync::Arc<gossip::GossipRuntime>,
    network: std::sync::Arc<network::NetworkNode>,
    interval_secs: u64,
    cache: std::sync::Arc<
        tokio::sync::RwLock<std::collections::HashMap<identity::AgentId, DiscoveredAgent>>,
    >,
    machine_cache: std::sync::Arc<
        tokio::sync::RwLock<std::collections::HashMap<identity::MachineId, DiscoveredMachine>>,
    >,
    /// Whether the user has consented to identity disclosure.  When true,
    /// heartbeats include `user_id` and `agent_certificate` so they don't
    /// erase a consented disclosure.
    user_identity_consented: std::sync::Arc<std::sync::atomic::AtomicBool>,
    allow_local_discovery_addrs: bool,
    /// Local revocation set — piggybacked on each heartbeat for partition-
    /// tolerant eventual propagation.
    revocation_set: std::sync::Arc<tokio::sync::RwLock<revocation::RevocationSet>>,
}

impl HeartbeatContext {
    async fn announce(&self) -> error::Result<()> {
        let machine_public_key = self
            .identity
            .machine_keypair()
            .public_key()
            .as_bytes()
            .to_vec();
        let announced_at = Agent::unix_timestamp_secs();

        // Include ALL routable addresses (IPv4 and IPv6) so other agents
        // can connect to us via whichever protocol they support.
        let mut addresses = match self.network.node_status().await {
            Some(status) if !status.external_addrs.is_empty() => status.external_addrs,
            _ => match self.network.routable_addr().await {
                Some(addr) => vec![addr],
                None => Vec::new(),
            },
        };

        // Detect global IPv6 address locally (ant-quic currently only
        // reports IPv4 via OBSERVED_ADDRESS). Uses UDP connect trick —
        // no data is sent, the OS routing table resolves our source addr.
        //
        // For locally-probed addresses (IPv6 and LAN IPv4), use the actual
        // bound port from the QUIC endpoint — NOT the first external address
        // port (which is NAT-mapped) and NOT the config bind port (which may
        // be 0 for OS-assigned ports).
        let bind_port = self
            .network
            .bound_addr()
            .await
            .map(|a| a.port())
            .unwrap_or(5483);
        if let Ok(sock) = std::net::UdpSocket::bind("[::]:0") {
            if sock.connect("[2001:4860:4860::8888]:80").is_ok() {
                if let Ok(local) = sock.local_addr() {
                    if let std::net::IpAddr::V6(v6) = local.ip() {
                        let segs = v6.segments();
                        let is_global = (segs[0] & 0xffc0) != 0xfe80
                            && (segs[0] & 0xff00) != 0xfd00
                            && !v6.is_loopback();
                        if is_global {
                            let v6_addr =
                                std::net::SocketAddr::new(std::net::IpAddr::V6(v6), bind_port);
                            if !addresses.contains(&v6_addr) {
                                addresses.push(v6_addr);
                            }
                        }
                    }
                }
            }
        }

        for addr in collect_local_interface_addrs(bind_port) {
            if !addresses.contains(&addr) {
                addresses.push(addr);
            }
        }

        // Global bootstrap partitions must not ship LAN-scope addresses over
        // gossip: remote peers cannot reach them and each dead dial consumes
        // connect budget. Explicit local/testnet partitions are different; they
        // need signed LAN/loopback hints because there may be no public endpoint
        // or mDNS bridge between the isolated daemons.
        addresses =
            filter_discovery_announcement_addrs(addresses, self.allow_local_discovery_addrs);

        // Query reachability plus stable relay/coordinator capability from
        // the network layer. Runtime activity is logged separately so we do
        // not conflate "can help" with "is currently busy helping".
        let assist_snapshot = self
            .network
            .node_status()
            .await
            .map(|status| AnnouncementAssistSnapshot::from_node_status(&status))
            .unwrap_or_default();
        let nat_type = assist_snapshot.nat_type.clone();
        let can_receive_direct = assist_snapshot.can_receive_direct;
        let relay_capable = assist_snapshot.relay_capable;
        let coordinator_capable = assist_snapshot.coordinator_capable;

        // Only emit coordinator / relay hints when we believe remote peers
        // cannot reach us directly. Directly-reachable peers don't need
        // help, and advertising hints we don't need just bloats gossip.
        let (reachable_via, relay_candidates) = if can_receive_direct == Some(true) {
            (Vec::new(), Vec::new())
        } else {
            collect_coordinator_hints(
                self.network.as_ref(),
                &self.machine_cache,
                self.identity.machine_id(),
            )
            .await
        };

        // Include user identity ONLY if the user has previously consented
        // via announce_identity(true, true). This preserves the consented
        // disclosure across heartbeats without ever escalating on its own.
        let include_user = self
            .user_identity_consented
            .load(std::sync::atomic::Ordering::Acquire);
        let (user_id, agent_certificate) = if include_user {
            (
                self.identity
                    .user_keypair()
                    .map(identity::UserKeypair::user_id),
                self.identity.agent_certificate().cloned(),
            )
        } else {
            (None, None)
        };

        let unsigned = IdentityAnnouncementUnsigned {
            agent_id: self.identity.agent_id(),
            machine_id: self.identity.machine_id(),
            user_id,
            agent_certificate,
            machine_public_key: machine_public_key.clone(),
            addresses,
            announced_at,
            nat_type: nat_type.clone(),
            can_receive_direct,
            is_relay: relay_capable,
            is_coordinator: coordinator_capable,
            reachable_via: reachable_via.clone(),
            relay_candidates: relay_candidates.clone(),
        };
        let unsigned_bytes = bincode::serialize(&unsigned).map_err(|e| {
            error::IdentityError::Serialization(format!(
                "heartbeat: failed to serialize announcement: {e}"
            ))
        })?;
        let machine_signature = ant_quic::crypto::raw_public_keys::pqc::sign_with_ml_dsa(
            self.identity.machine_keypair().secret_key(),
            &unsigned_bytes,
        )
        .map_err(|e| {
            error::IdentityError::Storage(std::io::Error::other(format!(
                "heartbeat: failed to sign announcement: {:?}",
                e
            )))
        })?
        .as_bytes()
        .to_vec();

        let agent_public_key = self
            .identity
            .agent_keypair()
            .public_key()
            .as_bytes()
            .to_vec();
        let announcement = IdentityAnnouncement {
            agent_id: unsigned.agent_id,
            machine_id: unsigned.machine_id,
            user_id: unsigned.user_id,
            agent_certificate: unsigned.agent_certificate,
            machine_public_key: machine_public_key.clone(),
            machine_signature,
            addresses: unsigned.addresses,
            announced_at,
            nat_type,
            can_receive_direct,
            is_relay: relay_capable,
            is_coordinator: coordinator_capable,
            reachable_via: reachable_via.clone(),
            relay_candidates: relay_candidates.clone(),
            agent_public_key,
        };
        tracing::debug!(
            target: "x0x::discovery",
            announcement_kind = "heartbeat",
            machine_prefix = %network::hex_prefix(&announcement.machine_id.0, 4),
            addr_total = announcement.addresses.len(),
            nat_type = announcement.nat_type.as_deref().unwrap_or("unknown"),
            can_receive_direct = ?announcement.can_receive_direct,
            relay_capable = ?announcement.is_relay,
            coordinator_capable = ?announcement.is_coordinator,
            relay_active = ?assist_snapshot.relay_active,
            coordinator_active = ?assist_snapshot.coordinator_active,
            reachable_via_count = announcement.reachable_via.len(),
            relay_candidate_count = announcement.relay_candidates.len(),
            "publishing identity announcement"
        );

        let machine_announcement = build_machine_announcement_for_identity(
            &self.identity,
            announcement.addresses.clone(),
            announced_at,
            Some(&assist_snapshot),
            reachable_via.clone(),
            relay_candidates.clone(),
            self.allow_local_discovery_addrs,
        )?;
        tracing::debug!(
            target: "x0x::discovery",
            announcement_kind = "machine_heartbeat",
            machine_prefix = %network::hex_prefix(&machine_announcement.machine_id.0, 4),
            addr_total = machine_announcement.addresses.len(),
            nat_type = machine_announcement.nat_type.as_deref().unwrap_or("unknown"),
            can_receive_direct = ?machine_announcement.can_receive_direct,
            relay_capable = ?machine_announcement.is_relay,
            coordinator_capable = ?machine_announcement.is_coordinator,
            "publishing machine announcement"
        );
        let machine_encoded = bincode::serialize(&machine_announcement).map_err(|e| {
            error::IdentityError::Serialization(format!(
                "heartbeat: failed to serialize machine announcement: {e}"
            ))
        })?;
        let machine_payload = bytes::Bytes::from(machine_encoded);
        self.runtime
            .pubsub()
            .publish(
                shard_topic_for_machine(&machine_announcement.machine_id),
                machine_payload.clone(),
            )
            .await
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "heartbeat: machine shard publish failed: {e}"
                )))
            })?;
        self.runtime
            .pubsub()
            .publish(MACHINE_ANNOUNCE_TOPIC.to_string(), machine_payload)
            .await
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "heartbeat: machine publish failed: {e}"
                )))
            })?;

        let encoded = serialize_identity_announcement(&announcement).map_err(|e| {
            error::IdentityError::Serialization(format!(
                "heartbeat: failed to serialize announcement: {e}"
            ))
        })?;
        self.runtime
            .pubsub()
            .publish(
                IDENTITY_ANNOUNCE_TOPIC.to_string(),
                bytes::Bytes::from(encoded),
            )
            .await
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "heartbeat: publish failed: {e}"
                )))
            })?;
        let now = Agent::unix_timestamp_secs();
        upsert_discovered_machine(
            &self.machine_cache,
            DiscoveredMachine::from_machine_announcement(
                &machine_announcement,
                machine_announcement.addresses.clone(),
                now,
            ),
        )
        .await;
        let discovered_agent = DiscoveredAgent {
            agent_id: announcement.agent_id,
            machine_id: announcement.machine_id,
            user_id: announcement.user_id,
            addresses: announcement.addresses,
            announced_at: announcement.announced_at,
            last_seen: now,
            machine_public_key: machine_public_key.clone(),
            nat_type: announcement.nat_type.clone(),
            can_receive_direct: announcement.can_receive_direct,
            is_relay: announcement.is_relay,
            is_coordinator: announcement.is_coordinator,
            reachable_via: announcement.reachable_via.clone(),
            relay_candidates: announcement.relay_candidates.clone(),
            cert_not_after: None,
            agent_certificate: None,
            agent_public_key: announcement.agent_public_key.clone(),
        };
        upsert_discovered_machine_from_agent(&self.machine_cache, &discovered_agent).await;
        upsert_discovered_agent(&self.cache, discovered_agent).await;

        // Piggyback the local revocation set on each heartbeat for partition-
        // tolerant eventual convergence.  A node that was offline when a
        // revocation was originally published will learn it from the next
        // heartbeat it receives from any peer that already holds it.
        let records = self.revocation_set.read().await.all_records();
        if !records.is_empty() {
            match bincode::serialize(&records) {
                Ok(bytes) => {
                    if let Err(e) = self
                        .runtime
                        .pubsub()
                        .publish(REVOCATION_TOPIC.to_string(), bytes::Bytes::from(bytes))
                        .await
                    {
                        tracing::debug!("heartbeat: revocation re-broadcast failed: {e}");
                    }
                }
                Err(e) => {
                    tracing::debug!("heartbeat: failed to serialize revocation set: {e}");
                }
            }
        }

        Ok(())
    }
}

impl Agent {
    /// Create a new offline agent with default identity configuration.
    ///
    /// This generates a fresh identity with both machine and agent keypairs.
    /// The machine keypair is stored persistently in `~/.x0x/machine.key`.
    /// Network and gossip runtime setup is opt-in via
    /// [`Agent::builder()`] and [`AgentBuilder::with_network_config()`].
    ///
    /// For more control, use [`Agent::builder()`].
    pub async fn new() -> error::Result<Self> {
        Agent::builder().build().await
    }

    /// Create an [`AgentBuilder`] for fine-grained configuration.
    ///
    /// The builder supports:
    /// - Custom machine key path via `with_machine_key()`
    /// - Imported agent keypair via `with_agent_key()`
    /// - User identity via `with_user_key()` or `with_user_key_path()`
    /// - Network and gossip runtime via `with_network_config()` (opt-in)
    pub fn builder() -> AgentBuilder {
        AgentBuilder {
            machine_key_path: None,
            agent_keypair: None,
            agent_key_path: None,
            agent_cert_path: None,
            user_keypair: None,
            user_key_path: None,
            network_config: None,
            gossip_config: None,
            peer_cache_dir: None,
            disable_peer_cache: false,
            heartbeat_interval_secs: None,
            identity_ttl_secs: None,
            presence_beacon_interval_secs: None,
            presence_event_poll_interval_secs: None,
            presence_offline_timeout_secs: None,
            contact_store_path: None,
            identity_dir: None,
        }
    }

    /// Get the agent's identity.
    ///
    /// # Returns
    ///
    /// A reference to the agent's [`identity::Identity`].
    #[inline]
    #[must_use]
    pub fn identity(&self) -> &identity::Identity {
        &self.identity
    }

    /// Get the machine ID for this agent.
    ///
    /// The machine ID is tied to this computer and used for QUIC transport
    /// authentication. It is stored persistently in `~/.x0x/machine.key`.
    ///
    /// # Returns
    ///
    /// The agent's machine ID.
    #[inline]
    #[must_use]
    pub fn machine_id(&self) -> identity::MachineId {
        self.identity.machine_id()
    }

    /// Get the agent ID for this agent.
    ///
    /// The agent ID is portable across machines and represents the agent's
    /// persistent identity. It can be exported and imported to run the same
    /// agent on different computers.
    ///
    /// # Returns
    ///
    /// The agent's ID.
    #[inline]
    #[must_use]
    pub fn agent_id(&self) -> identity::AgentId {
        self.identity.agent_id()
    }

    /// Get the user ID for this agent, if a user identity is bound.
    ///
    /// Returns `None` if no user keypair was provided during construction.
    /// User keys are opt-in — they are never auto-generated.
    #[inline]
    #[must_use]
    pub fn user_id(&self) -> Option<identity::UserId> {
        self.identity.user_id()
    }

    /// Get the agent certificate, if one exists.
    ///
    /// The certificate cryptographically binds this agent to a user identity.
    #[inline]
    #[must_use]
    pub fn agent_certificate(&self) -> Option<&identity::AgentCertificate> {
        self.identity.agent_certificate()
    }

    /// Get the network node, if initialized.
    #[must_use]
    pub fn network(&self) -> Option<&std::sync::Arc<network::NetworkNode>> {
        self.network.as_ref()
    }

    /// Get the gossip cache adapter for coordinator discovery.
    ///
    /// Returns `None` if this agent was built without a network config.
    /// The adapter wraps the same `Arc<BootstrapCache>` as the network node.
    pub fn gossip_cache_adapter(&self) -> Option<&saorsa_gossip_coordinator::GossipCacheAdapter> {
        self.gossip_cache_adapter.as_ref()
    }

    /// Snapshot of pub/sub drop-detection counters.
    ///
    /// Returns `None` when the agent has no gossip runtime (e.g. offline
    /// unit tests). Exposed through `GET /diagnostics/gossip` on x0xd so
    /// that E2E harnesses can assert zero drops between publish and
    /// subscriber delivery.
    #[must_use]
    pub fn gossip_stats(&self) -> Option<gossip::PubSubStatsSnapshot> {
        self.gossip_runtime.as_ref().map(|rt| rt.pubsub().stats())
    }

    /// Snapshot of inbound gossip dispatcher counters.
    ///
    /// Returns `None` when the agent has no gossip runtime. Exposed through
    /// `GET /diagnostics/gossip` alongside pub/sub drop-detection counters so
    /// live soaks can identify slow or timed-out stream handlers.
    #[must_use]
    pub fn gossip_dispatch_stats(&self) -> Option<gossip::GossipDispatchStatsSnapshot> {
        self.gossip_runtime.as_ref().map(|rt| rt.dispatch_stats())
    }

    /// Snapshot of per-stage PubSub handling timings.
    ///
    /// Returns `None` when the agent has no gossip runtime. This is the
    /// X0X-0006 diagnostic block used to identify which stage of
    /// `PubSubManager::handle_incoming` dominates dispatcher wall-clock time.
    #[must_use]
    pub fn gossip_pubsub_stage_stats(&self) -> Option<gossip::PubSubStageStatsSnapshot> {
        self.gossip_runtime
            .as_ref()
            .map(|rt| rt.pubsub().stage_stats())
    }

    /// Snapshot of ant-quic → gossip receive-pump diagnostics.
    ///
    /// Returns `None` when this agent was built without a network node.
    /// Exposed through `GET /diagnostics/gossip` so operators can compare
    /// producer rate, consumer drain rate, queue dwell time, and overload drops.
    #[must_use]
    pub fn recv_pump_diagnostics(&self) -> Option<network::RecvPumpDiagnosticsSnapshot> {
        self.network.as_ref().map(|net| net.recv_pump_diagnostics())
    }

    /// Get the presence system wrapper, if configured.
    ///
    /// Returns `None` if this agent was built without a network config.
    /// The presence wrapper provides beacon broadcasting, FOAF discovery,
    /// and online/offline event subscriptions.
    #[must_use]
    pub fn presence_system(&self) -> Option<&std::sync::Arc<presence::PresenceWrapper>> {
        self.presence.as_ref()
    }

    /// Get a reference to the contact store.
    ///
    /// The contact store persists trust levels and machine records for known
    /// agents. It is backed by `~/.x0x/contacts.json` by default.
    ///
    /// Use [`with_contact_store_path`](AgentBuilder::with_contact_store_path)
    /// on the builder to customise the path.
    #[must_use]
    pub fn contacts(&self) -> &std::sync::Arc<tokio::sync::RwLock<contacts::ContactStore>> {
        &self.contact_store
    }

    /// Get the reachability information for a discovered agent.
    ///
    /// Returns `None` if the agent is not in the discovery cache.
    /// Use [`Agent::announce_identity`] or wait for a heartbeat announcement
    /// to populate the cache.
    pub async fn reachability(
        &self,
        agent_id: &identity::AgentId,
    ) -> Option<connectivity::ReachabilityInfo> {
        let cache = self.identity_discovery_cache.read().await;
        cache
            .get(agent_id)
            .map(connectivity::ReachabilityInfo::from_discovered)
    }

    async fn seed_transport_peer_hints_for_target(
        &self,
        network: &network::NetworkNode,
        target: &DiscoveredAgent,
    ) -> error::Result<()> {
        #[derive(Default)]
        struct HelperHintEntry {
            addrs: Vec<std::net::SocketAddr>,
            caps: ant_quic::bootstrap_cache::PeerCapabilities,
            sources: std::collections::BTreeSet<&'static str>,
        }

        fn merge_helper_hint(
            hints: &mut std::collections::HashMap<ant_quic::PeerId, HelperHintEntry>,
            peer_id: ant_quic::PeerId,
            source: &'static str,
            addrs: impl IntoIterator<Item = std::net::SocketAddr>,
            supports_coordination: bool,
            supports_relay: bool,
        ) {
            let entry = hints.entry(peer_id).or_default();
            entry.sources.insert(source);
            for addr in addrs {
                if !entry.addrs.contains(&addr) {
                    entry.addrs.push(addr);
                }
            }
            if supports_coordination {
                entry.caps.supports_coordination = true;
            }
            if supports_relay {
                entry.caps.supports_relay = true;
            }
        }

        let target_agent_prefix = network::hex_prefix(&target.agent_id.0, 4);
        let target_machine_prefix = network::hex_prefix(&target.machine_id.0, 4);
        let target_peer_id = ant_quic::PeerId(target.machine_id.0);
        if target.machine_id.0 != [0u8; 32] {
            network
                .upsert_peer_hints(target_peer_id, target.addresses.clone(), None)
                .await
                .map_err(|e| {
                    error::IdentityError::Storage(std::io::Error::other(format!(
                        "failed to upsert target peer hints: {e}"
                    )))
                })?;
            tracing::debug!(
                target: "x0x::connect",
                stage = "seed_target_hints",
                %target_agent_prefix,
                %target_machine_prefix,
                target_addr_count = target.addresses.len(),
                "upserted direct target hints"
            );
        }

        let mut helper_hints: std::collections::HashMap<ant_quic::PeerId, HelperHintEntry> =
            std::collections::HashMap::new();

        if let Some(ref cache) = self.bootstrap_cache {
            for peer in cache.select_coordinators(6).await {
                merge_helper_hint(
                    &mut helper_hints,
                    peer.peer_id,
                    "bootstrap_cache:coordinator",
                    peer.preferred_addresses(),
                    true,
                    false,
                );
            }
            for peer in cache.select_relay_peers(6).await {
                merge_helper_hint(
                    &mut helper_hints,
                    peer.peer_id,
                    "bootstrap_cache:relay",
                    peer.preferred_addresses(),
                    false,
                    true,
                );
            }
        }

        if let Some(ref adapter) = self.gossip_cache_adapter {
            let mut adverts = adapter.get_all_adverts();
            adverts.sort_by_key(|a| std::cmp::Reverse(a.score));
            for advert in adverts.into_iter().take(12) {
                let advert_peer_id = ant_quic::PeerId(*advert.peer.as_bytes());
                if advert_peer_id == target_peer_id {
                    continue;
                }
                merge_helper_hint(
                    &mut helper_hints,
                    advert_peer_id,
                    "gossip_cache_advert",
                    advert
                        .addr_hints
                        .into_iter()
                        .map(|hint| hint.addr)
                        .filter(|addr| is_publicly_advertisable(*addr)),
                    advert.roles.coordinator || advert.roles.rendezvous,
                    advert.roles.relay,
                );
            }
        }

        let discovered: Vec<DiscoveredMachine> = {
            let cache = self.machine_discovery_cache.read().await;
            cache.values().cloned().collect()
        };
        for candidate in discovered {
            if candidate.machine_id == target.machine_id || candidate.machine_id.0 == [0u8; 32] {
                continue;
            }
            merge_helper_hint(
                &mut helper_hints,
                ant_quic::PeerId(candidate.machine_id.0),
                "machine_discovery_cache",
                candidate.addresses.iter().copied(),
                candidate.is_coordinator == Some(true),
                candidate.is_relay == Some(true),
            );
        }

        let helper_candidate_count = helper_hints.len();
        let helper_addr_total: usize = helper_hints.values().map(|entry| entry.addrs.len()).sum();
        tracing::info!(
            target: "x0x::connect",
            stage = "seed_target_hints",
            %target_agent_prefix,
            %target_machine_prefix,
            target_addr_count = target.addresses.len(),
            helper_candidate_count,
            helper_addr_total,
            "prepared helper hints for peer-authenticated dial"
        );

        for (peer_id, entry) in &helper_hints {
            tracing::debug!(
                target: "x0x::connect",
                stage = "seed_target_hints",
                helper_peer_prefix = %network::hex_prefix(&peer_id.0, 4),
                helper_addr_count = entry.addrs.len(),
                supports_coordination = entry.caps.supports_coordination,
                supports_relay = entry.caps.supports_relay,
                sources = %entry.sources.iter().copied().collect::<Vec<_>>().join(","),
                "helper candidate discovered"
            );
        }

        for (peer_id, entry) in helper_hints {
            let HelperHintEntry {
                mut addrs,
                caps,
                sources,
            } = entry;
            addrs.retain(|addr| !target.addresses.contains(addr));
            if addrs.is_empty() && !caps.supports_coordination && !caps.supports_relay {
                tracing::debug!(
                    target: "x0x::connect",
                    stage = "seed_target_hints",
                    helper_peer_prefix = %network::hex_prefix(&peer_id.0, 4),
                    sources = %sources.iter().copied().collect::<Vec<_>>().join(","),
                    "skipping helper with no remaining addresses or assist capability"
                );
                continue;
            }
            tracing::debug!(
                target: "x0x::connect",
                stage = "seed_target_hints",
                helper_peer_prefix = %network::hex_prefix(&peer_id.0, 4),
                helper_addr_count = addrs.len(),
                supports_coordination = caps.supports_coordination,
                supports_relay = caps.supports_relay,
                sources = %sources.iter().copied().collect::<Vec<_>>().join(","),
                "upserting helper peer hints"
            );
            network
                .upsert_peer_hints(peer_id, addrs, Some(caps))
                .await
                .map_err(|e| {
                    error::IdentityError::Storage(std::io::Error::other(format!(
                        "failed to upsert helper peer hints: {e}"
                    )))
                })?;
        }

        Ok(())
    }

    /// Attempt to connect to an agent by its identity.
    ///
    /// Looks up the agent in the discovery cache, then tries to establish
    /// a QUIC connection using the best available strategy:
    ///
    /// 1. **Direct** — if the agent reports `can_receive_direct: true` or
    ///    has a traversable NAT type, try each known address in order.
    /// 2. **Coordinated** — if direct fails or the agent reports a symmetric
    ///    NAT, the outcome is `Coordinated` if any address was reachable via
    ///    the network layer's NAT traversal.
    /// 3. **Unreachable** — no address succeeded.
    /// 4. **NotFound** — the agent is not in the discovery cache.
    ///
    /// # Errors
    ///
    /// Returns an error only for internal failures (e.g. network not started).
    /// Connectivity failures are reported as `ConnectOutcome::Unreachable`.
    pub async fn connect_to_agent(
        &self,
        agent_id: &identity::AgentId,
    ) -> error::Result<connectivity::ConnectOutcome> {
        let call_start = std::time::Instant::now();
        let agent_prefix = network::hex_prefix(&agent_id.0, 4);
        tracing::debug!(
            target: "x0x::connect",
            stage = "connect_to_agent",
            %agent_prefix,
            "begin"
        );
        // 1. Look up in discovery cache
        let discovered = {
            let cache = self.identity_discovery_cache.read().await;
            cache.get(agent_id).cloned()
        };

        let agent = match discovered {
            Some(a) => a,
            None => {
                tracing::info!(
                    target: "x0x::connect",
                    stage = "connect_to_agent",
                    %agent_prefix,
                    outcome = "not_found",
                    dur_ms = call_start.elapsed().as_millis() as u64,
                    "agent not in discovery cache"
                );
                return Ok(connectivity::ConnectOutcome::NotFound);
            }
        };

        // #195 item 5: consult the revocation set inline so a known-revoked-but-
        // not-yet-evicted agent can't be the target of an outbound connect —
        // closes the race between a revocation arriving and the eviction loop
        // purging the discovery cache. Pairs with #191 item 5.
        {
            let revoked = self.revocation_set.read().await;
            if revoked.is_agent_revoked(agent_id) || revoked.is_machine_revoked(&agent.machine_id) {
                tracing::info!(
                    target: "x0x::connect",
                    stage = "connect_to_agent",
                    %agent_prefix,
                    outcome = "revoked",
                    dur_ms = call_start.elapsed().as_millis() as u64,
                    "connect target is revoked — refusing before any dial"
                );
                return Ok(connectivity::ConnectOutcome::NotFound);
            }
        }

        let info = connectivity::ReachabilityInfo::from_discovered(&agent);
        let v4_addrs = info.addresses.iter().filter(|a| a.is_ipv4()).count();
        let v6_addrs = info.addresses.len() - v4_addrs;
        tracing::info!(
            target: "x0x::connect",
            stage = "connect_to_agent",
            %agent_prefix,
            machine_prefix = %network::hex_prefix(&agent.machine_id.0, 4),
            addr_total = info.addresses.len(),
            v4_addrs,
            v6_addrs,
            can_receive_direct = ?info.can_receive_direct,
            should_attempt_direct = info.should_attempt_direct(),
            needs_coordination = info.needs_coordination(),
            "reachability classified"
        );

        let Some(ref network) = self.network else {
            tracing::warn!(
                target: "x0x::connect",
                stage = "connect_to_agent",
                agent_prefix = %crate::logging::LogHexId::agent(&agent_prefix),
                outcome = "unreachable_no_network",
                "network layer not initialised"
            );
            return Ok(connectivity::ConnectOutcome::Unreachable);
        };

        // 2. If already connected via gossip, reuse that connection.
        //    This check MUST come before the empty-address bail-out because
        //    LAN/private agents may have no publicly-routable addresses in
        //    their announcement but are still reachable via the existing
        //    gossip QUIC connection.
        let connected_machine_id = if agent.machine_id.0 != [0u8; 32]
            && network
                .is_connected(&ant_quic::PeerId(agent.machine_id.0))
                .await
        {
            Some(agent.machine_id)
        } else {
            match self.direct_messaging.get_machine_id(agent_id).await {
                Some(machine_id) if network.is_connected(&ant_quic::PeerId(machine_id.0)).await => {
                    Some(machine_id)
                }
                _ => None,
            }
        };
        if let Some(machine_id) = connected_machine_id {
            if machine_id != agent.machine_id {
                let mut cache = self.identity_discovery_cache.write().await;
                if let Some(entry) = cache.get_mut(agent_id) {
                    entry.machine_id = machine_id;
                }
            }
            self.direct_messaging
                .mark_connected(agent.agent_id, machine_id)
                .await;
            let dur_ms = call_start.elapsed().as_millis() as u64;
            return if let Some(addr) = info.addresses.first() {
                let family = if addr.is_ipv4() { "v4" } else { "v6" };
                tracing::info!(
                    target: "x0x::connect",
                    stage = "connect_to_agent",
                    %agent_prefix,
                    strategy = "already_connected",
                    outcome = "direct",
                    selected_addr = %addr,
                    family,
                    dur_ms,
                    "reusing existing connection"
                );
                Ok(connectivity::ConnectOutcome::Direct(*addr))
            } else {
                tracing::info!(
                    target: "x0x::connect",
                    stage = "connect_to_agent",
                    %agent_prefix,
                    strategy = "already_connected",
                    outcome = "already_connected",
                    dur_ms,
                    "reusing existing connection without known addr"
                );
                Ok(connectivity::ConnectOutcome::AlreadyConnected)
            };
        }

        if info.addresses.is_empty() {
            tracing::info!(
                target: "x0x::connect",
                stage = "connect_to_agent",
                %agent_prefix,
                outcome = "unreachable",
                reason = "no_addresses",
                dur_ms = call_start.elapsed().as_millis() as u64,
                "no known addresses for agent"
            );
            return Ok(connectivity::ConnectOutcome::Unreachable);
        }

        let dial_timeout = std::time::Duration::from_secs(8);
        let local_probe_timeout = std::time::Duration::from_secs(3);
        let direct_probe_addrs = local_direct_probe_addrs(&info.addresses);

        // Agent cards minted for a local dogfood run often contain both
        // reachable LAN IPv4 hints and globally-scoped IPv6/Tailscale hints
        // that may be stale or firewalled. Probe local IPv4 first so a bad
        // multi-address peer dial cannot consume the full API timeout before
        // the reachable LAN path is attempted.
        let peer_id_hint =
            (agent.machine_id.0 != [0u8; 32]).then_some(ant_quic::PeerId(agent.machine_id.0));
        for addr in &direct_probe_addrs {
            if let Some(peer_id_hint) = peer_id_hint {
                match tokio::time::timeout(
                    local_probe_timeout,
                    network.connect_peer_with_addrs(peer_id_hint, vec![*addr]),
                )
                .await
                {
                    Ok(Ok((selected_addr, connected_peer_id)))
                        if connected_peer_id == peer_id_hint =>
                    {
                        let real_machine_id = identity::MachineId(connected_peer_id.0);
                        if let Some(ref bc) = self.bootstrap_cache {
                            bc.add_from_connection(connected_peer_id, vec![selected_addr], None)
                                .await;
                        }
                        {
                            let mut cache = self.identity_discovery_cache.write().await;
                            if let Some(entry) = cache.get_mut(agent_id) {
                                entry.machine_id = real_machine_id;
                            }
                        }
                        self.direct_messaging
                            .mark_connected(agent.agent_id, real_machine_id)
                            .await;
                        tracing::info!(
                            target: "x0x::connect",
                            stage = "connect_to_agent",
                            %agent_prefix,
                            strategy = "local_direct_first",
                            outcome = "direct",
                            selected_addr = %selected_addr,
                            family = "v4",
                            dur_ms = call_start.elapsed().as_millis() as u64,
                            "local peer-authenticated dial succeeded"
                        );
                        return Ok(connectivity::ConnectOutcome::Direct(selected_addr));
                    }
                    Ok(Ok((selected_addr, connected_peer_id))) => {
                        tracing::warn!(
                            target: "x0x::connect",
                            stage = "connect_to_agent",
                            agent_prefix = %crate::logging::LogHexId::agent(&agent_prefix),
                            strategy = "local_direct_first",
                            requested_addr = %crate::logging::LogHexId::addr(&addr.to_string()),
                            selected_addr = %crate::logging::LogHexId::addr(&selected_addr.to_string()),
                            connected_machine_prefix = %crate::logging::LogHexId::new("machine", &network::hex_prefix(&connected_peer_id.0, 4)),
                            "local peer-authenticated dial reached unexpected peer"
                        );
                    }
                    Ok(Err(e)) => {
                        tracing::debug!(
                            target: "x0x::connect",
                            %agent_prefix,
                            strategy = "local_direct_first",
                            %addr,
                            error = %e,
                            "local peer-authenticated dial failed; trying verified raw-address fallback"
                        );
                    }
                    Err(_) => {
                        tracing::debug!(
                            target: "x0x::connect",
                            %agent_prefix,
                            strategy = "local_direct_first",
                            %addr,
                            timeout_s = local_probe_timeout.as_secs(),
                            "local peer-authenticated dial timed out; trying verified raw-address fallback"
                        );
                    }
                }

                match tokio::time::timeout(local_probe_timeout, network.connect_addr(*addr)).await {
                    Ok(Ok(connected_peer_id)) if connected_peer_id == peer_id_hint => {
                        let real_machine_id = identity::MachineId(connected_peer_id.0);
                        if let Some(ref bc) = self.bootstrap_cache {
                            bc.add_from_connection(connected_peer_id, vec![*addr], None)
                                .await;
                        }
                        {
                            let mut cache = self.identity_discovery_cache.write().await;
                            if let Some(entry) = cache.get_mut(agent_id) {
                                entry.machine_id = real_machine_id;
                            }
                        }
                        self.direct_messaging
                            .mark_connected(agent.agent_id, real_machine_id)
                            .await;
                        tracing::info!(
                            target: "x0x::connect",
                            stage = "connect_to_agent",
                            %agent_prefix,
                            strategy = "local_direct_raw_fallback",
                            outcome = "direct",
                            selected_addr = %addr,
                            family = "v4",
                            dur_ms = call_start.elapsed().as_millis() as u64,
                            "verified local raw-address fallback succeeded"
                        );
                        return Ok(connectivity::ConnectOutcome::Direct(*addr));
                    }
                    Ok(Ok(connected_peer_id)) => {
                        tracing::warn!(
                            target: "x0x::connect",
                            stage = "connect_to_agent",
                            agent_prefix = %crate::logging::LogHexId::agent(&agent_prefix),
                            strategy = "local_direct_raw_fallback",
                            addr = %crate::logging::LogHexId::addr(&addr.to_string()),
                            connected_machine_prefix = %crate::logging::LogHexId::new("machine", &network::hex_prefix(&connected_peer_id.0, 4)),
                            "verified local raw-address fallback reached unexpected peer"
                        );
                    }
                    Ok(Err(e)) => {
                        tracing::debug!(
                            target: "x0x::connect",
                            %agent_prefix,
                            strategy = "local_direct_raw_fallback",
                            %addr,
                            error = %e,
                            "verified local raw-address fallback failed"
                        );
                    }
                    Err(_) => {
                        tracing::debug!(
                            target: "x0x::connect",
                            %agent_prefix,
                            strategy = "local_direct_raw_fallback",
                            %addr,
                            timeout_s = local_probe_timeout.as_secs(),
                            "verified local raw-address fallback timed out"
                        );
                    }
                }
            } else {
                match tokio::time::timeout(local_probe_timeout, network.connect_addr(*addr)).await {
                    Ok(Ok(connected_peer_id)) => {
                        let real_machine_id = identity::MachineId(connected_peer_id.0);
                        if let Some(ref bc) = self.bootstrap_cache {
                            bc.add_from_connection(connected_peer_id, vec![*addr], None)
                                .await;
                        }
                        {
                            let mut cache = self.identity_discovery_cache.write().await;
                            if let Some(entry) = cache.get_mut(agent_id) {
                                entry.machine_id = real_machine_id;
                            }
                        }
                        self.direct_messaging
                            .mark_connected(agent.agent_id, real_machine_id)
                            .await;
                        tracing::info!(
                            target: "x0x::connect",
                            stage = "connect_to_agent",
                            %agent_prefix,
                            strategy = "local_direct_first",
                            outcome = "direct",
                            selected_addr = %addr,
                            family = "v4",
                            dur_ms = call_start.elapsed().as_millis() as u64,
                            "local direct dial succeeded"
                        );
                        return Ok(connectivity::ConnectOutcome::Direct(*addr));
                    }
                    Ok(Err(e)) => {
                        tracing::debug!(
                            target: "x0x::connect",
                            %agent_prefix,
                            strategy = "local_direct_first",
                            %addr,
                            error = %e,
                            "local direct dial failed"
                        );
                    }
                    Err(_) => {
                        tracing::debug!(
                            target: "x0x::connect",
                            %agent_prefix,
                            strategy = "local_direct_first",
                            %addr,
                            timeout_s = local_probe_timeout.as_secs(),
                            "local direct dial timed out"
                        );
                    }
                }
            }
        }

        // 3. If we know the peer's machine ID, prefer a peer-authenticated dial
        //    with explicit address hints first. This is more reliable for agent
        //    cards and other out-of-band discoveries than a raw address dial.
        if agent.machine_id.0 != [0u8; 32] {
            let peer_id_hint = ant_quic::PeerId(agent.machine_id.0);
            self.seed_transport_peer_hints_for_target(network, &agent)
                .await
                .map_err(|e| {
                    error::IdentityError::Storage(std::io::Error::other(format!(
                        "failed to seed transport peer hints: {e}"
                    )))
                })?;

            match tokio::time::timeout(
                dial_timeout,
                network.connect_peer_with_addrs(peer_id_hint, info.addresses.clone()),
            )
            .await
            {
                Ok(Ok((addr, verified_peer_id))) => {
                    let verified_machine_id = identity::MachineId(verified_peer_id.0);
                    if let Some(ref bc) = self.bootstrap_cache {
                        bc.add_from_connection(verified_peer_id, vec![addr], None)
                            .await;
                        bc.record_success(&verified_peer_id, 0).await;
                    }
                    {
                        let mut cache = self.identity_discovery_cache.write().await;
                        if let Some(entry) = cache.get_mut(agent_id) {
                            entry.machine_id = verified_machine_id;
                        }
                    }
                    self.direct_messaging
                        .mark_connected(agent.agent_id, verified_machine_id)
                        .await;
                    let family = if addr.is_ipv4() { "v4" } else { "v6" };
                    tracing::info!(
                        target: "x0x::connect",
                        stage = "connect_to_agent",
                        %agent_prefix,
                        strategy = "hinted_peer",
                        outcome = "coordinated",
                        selected_addr = %addr,
                        family,
                        dur_ms = call_start.elapsed().as_millis() as u64,
                        "hinted peer dial succeeded"
                    );
                    return Ok(connectivity::ConnectOutcome::Coordinated(addr));
                }
                Ok(Err(e)) => {
                    tracing::debug!(
                        target: "x0x::connect",
                        %agent_prefix,
                        strategy = "hinted_peer",
                        error = %e,
                        "hinted peer dial failed"
                    );
                }
                Err(_) => {
                    tracing::debug!(
                        target: "x0x::connect",
                        %agent_prefix,
                        strategy = "hinted_peer",
                        timeout_s = dial_timeout.as_secs(),
                        "hinted peer dial timed out"
                    );
                }
            }
        }

        // 4. Try direct connection whenever the peer is not explicitly known
        //    to require coordination. Unknown reachability still deserves a
        //    direct probe, especially for the first nodes in a new network.
        if info.should_attempt_direct() {
            for addr in &info.addresses {
                if direct_probe_addrs.contains(addr) {
                    continue;
                }
                match tokio::time::timeout(dial_timeout, network.connect_addr(*addr)).await {
                    Ok(Ok(connected_peer_id)) => {
                        // Use the real PeerId from the QUIC handshake (may differ
                        // from a zeroed placeholder in the discovery cache).
                        let real_machine_id = identity::MachineId(connected_peer_id.0);
                        // Enrich bootstrap cache with this successful address
                        if let Some(ref bc) = self.bootstrap_cache {
                            bc.add_from_connection(connected_peer_id, vec![*addr], None)
                                .await;
                        }
                        // Update discovery cache with real machine_id
                        {
                            let mut cache = self.identity_discovery_cache.write().await;
                            if let Some(entry) = cache.get_mut(agent_id) {
                                entry.machine_id = real_machine_id;
                            }
                        }
                        // Register agent mapping for direct messaging
                        self.direct_messaging
                            .mark_connected(agent.agent_id, real_machine_id)
                            .await;
                        let family = if addr.is_ipv4() { "v4" } else { "v6" };
                        tracing::info!(
                            target: "x0x::connect",
                            stage = "connect_to_agent",
                            %agent_prefix,
                            strategy = "direct_per_addr",
                            outcome = "direct",
                            selected_addr = %addr,
                            family,
                            dur_ms = call_start.elapsed().as_millis() as u64,
                            "direct dial succeeded"
                        );
                        return Ok(connectivity::ConnectOutcome::Direct(*addr));
                    }
                    Ok(Err(e)) => {
                        tracing::debug!(
                            target: "x0x::connect",
                            %agent_prefix,
                            strategy = "direct_per_addr",
                            %addr,
                            error = %e,
                            "direct dial failed"
                        );
                    }
                    Err(_) => {
                        tracing::debug!(
                            target: "x0x::connect",
                            %agent_prefix,
                            strategy = "direct_per_addr",
                            %addr,
                            timeout_s = dial_timeout.as_secs(),
                            "direct dial timed out"
                        );
                    }
                }
            }
        }

        // 5. If direct failed and coordination may help, use peer-ID dialing
        //    with explicit address hints. This lets ant-quic combine the
        //    authenticated peer ID with known addresses from x0x discovery /
        //    imported cards, unlocking the full direct → hole-punch → relay path.
        if info.needs_coordination() || !info.should_attempt_direct() {
            // Prefer coordinators the target has explicitly named in its
            // announcement (`reachable_via`). Seed transport hints for each
            // so ant-quic picks whichever is already connected (or can reach
            // one) as the coordinator peer for NAT punch-timing.
            for coord in &info.reachable_via {
                if let Some(coord_machine) = self
                    .machine_discovery_cache
                    .read()
                    .await
                    .get(coord)
                    .cloned()
                {
                    let coord_peer = ant_quic::PeerId(coord_machine.machine_id.0);
                    let coord_addrs = coord_machine.addresses.clone();
                    if !coord_addrs.is_empty() {
                        if let Err(e) = network
                            .upsert_peer_hints(coord_peer, coord_addrs, None)
                            .await
                        {
                            tracing::debug!(
                                target: "x0x::connect",
                                %agent_prefix,
                                coord_prefix = %network::hex_prefix(&coord.0, 4),
                                error = %e,
                                "failed to seed coordinator hints from reachable_via"
                            );
                        }
                    }
                }
            }

            // Use the machine_id from discovery cache as the peer_id hint.
            // NOTE: This may be a zeroed placeholder if the peer was discovered via
            // gossip and hasn't been verified via QUIC handshake yet.
            let peer_id_hint = ant_quic::PeerId(agent.machine_id.0);
            let hint_was_zeroed = agent.machine_id.0 == [0u8; 32];
            self.seed_transport_peer_hints_for_target(network, &agent)
                .await
                .map_err(|e| {
                    error::IdentityError::Storage(std::io::Error::other(format!(
                        "failed to seed transport peer hints: {e}"
                    )))
                })?;
            let coordinated_result = tokio::time::timeout(
                dial_timeout,
                network.connect_peer_with_addrs(peer_id_hint, info.addresses.clone()),
            )
            .await;
            match coordinated_result {
                Ok(Ok((addr, verified_peer_id))) => {
                    let verified_machine_id = identity::MachineId(verified_peer_id.0);

                    // Only update caches if the original hint was not zeroed.
                    // When the hint was zeroed, we connected to *some* peer at that address
                    // but have no way to verify they are the agent we intended. Writing
                    // an unverified peer_id into the caches could corrupt the bootstrap cache
                    // with the wrong peer's identity.
                    if !hint_was_zeroed {
                        if let Some(ref bc) = self.bootstrap_cache {
                            bc.add_from_connection(verified_peer_id, vec![addr], None)
                                .await;
                            bc.record_success(&verified_peer_id, 0).await;
                        }
                        {
                            let mut cache = self.identity_discovery_cache.write().await;
                            if let Some(entry) = cache.get_mut(agent_id) {
                                entry.machine_id = verified_machine_id;
                            }
                        }
                    }

                    // Only register for direct messaging and update caches when the hint
                    // was non-zero. When the hint was zeroed, we connected to *some*
                    // peer at that address but have no cryptographic way to verify they
                    // are the agent we intended. Binding an unverified peer_id to an
                    // agent_id could corrupt the direct-messaging registry with the
                    // wrong peer's identity.
                    if !hint_was_zeroed {
                        self.direct_messaging
                            .mark_connected(agent.agent_id, verified_machine_id)
                            .await;
                    }
                    let family = if addr.is_ipv4() { "v4" } else { "v6" };
                    tracing::info!(
                        target: "x0x::connect",
                        stage = "connect_to_agent",
                        %agent_prefix,
                        strategy = "coordinated_fallback",
                        outcome = "coordinated",
                        selected_addr = %addr,
                        family,
                        hint_was_zeroed,
                        dur_ms = call_start.elapsed().as_millis() as u64,
                        "coordinated dial succeeded"
                    );
                    return Ok(connectivity::ConnectOutcome::Coordinated(addr));
                }
                Ok(Err(e)) => {
                    tracing::debug!(
                        target: "x0x::connect",
                        %agent_prefix,
                        strategy = "coordinated_fallback",
                        error = %e,
                        "coordinated dial failed"
                    );
                }
                Err(_) => {
                    tracing::debug!(
                        target: "x0x::connect",
                        %agent_prefix,
                        strategy = "coordinated_fallback",
                        timeout_s = dial_timeout.as_secs(),
                        "coordinated dial timed out"
                    );
                }
            }
        }

        tracing::warn!(
            target: "x0x::connect",
            stage = "connect_to_agent",
            agent_prefix = %crate::logging::LogHexId::agent(&agent_prefix),
            outcome = "unreachable",
            reason = "all_strategies_exhausted",
            dur_ms = call_start.elapsed().as_millis() as u64,
            v4_addrs,
            v6_addrs,
            "all connection strategies exhausted"
        );
        Ok(connectivity::ConnectOutcome::Unreachable)
    }

    /// Attempt to connect to a machine by its transport identity.
    ///
    /// This is the machine-centric dial path: `machine_id` is resolved to
    /// IPv4/IPv6 endpoint hints, then ant-quic performs a peer-authenticated
    /// dial that can use direct connection, coordinated hole-punching, or relay
    /// support according to the transport cache.
    ///
    /// # Errors
    ///
    /// Returns an error only for internal failures. Connectivity failures are
    /// reported as [`connectivity::ConnectOutcome::Unreachable`].
    pub async fn connect_to_machine(
        &self,
        machine_id: &identity::MachineId,
    ) -> error::Result<connectivity::ConnectOutcome> {
        let call_start = std::time::Instant::now();
        let machine_prefix = network::hex_prefix(&machine_id.0, 4);
        tracing::debug!(
            target: "x0x::connect",
            stage = "connect_to_machine",
            %machine_prefix,
            "begin"
        );

        let machine = {
            let cache = self.machine_discovery_cache.read().await;
            cache.get(machine_id).cloned()
        };
        let Some(machine) = machine else {
            tracing::info!(
                target: "x0x::connect",
                stage = "connect_to_machine",
                %machine_prefix,
                outcome = "not_found",
                dur_ms = call_start.elapsed().as_millis() as u64,
                "machine not in discovery cache"
            );
            return Ok(connectivity::ConnectOutcome::NotFound);
        };

        let Some(ref network) = self.network else {
            tracing::warn!(
                target: "x0x::connect",
                stage = "connect_to_machine",
                machine_prefix = %crate::logging::LogHexId::new("machine", &machine_prefix),
                outcome = "unreachable_no_network",
                "network layer not initialised"
            );
            return Ok(connectivity::ConnectOutcome::Unreachable);
        };

        let peer_id = ant_quic::PeerId(machine.machine_id.0);
        if network.is_connected(&peer_id).await {
            for agent_id in &machine.agent_ids {
                self.direct_messaging
                    .mark_connected(*agent_id, machine.machine_id)
                    .await;
            }
            return if let Some(addr) = machine.addresses.first() {
                Ok(connectivity::ConnectOutcome::Direct(*addr))
            } else {
                Ok(connectivity::ConnectOutcome::AlreadyConnected)
            };
        }

        let info = connectivity::ReachabilityInfo::from_discovered_machine(&machine);
        let v4_addrs = info.addresses.iter().filter(|a| a.is_ipv4()).count();
        let v6_addrs = info.addresses.len() - v4_addrs;
        tracing::info!(
            target: "x0x::connect",
            stage = "connect_to_machine",
            %machine_prefix,
            addr_total = info.addresses.len(),
            v4_addrs,
            v6_addrs,
            can_receive_direct = ?info.can_receive_direct,
            should_attempt_direct = info.should_attempt_direct(),
            needs_coordination = info.needs_coordination(),
            "machine reachability classified"
        );

        if info.addresses.is_empty() {
            return Ok(connectivity::ConnectOutcome::Unreachable);
        }

        let dial_timeout = std::time::Duration::from_secs(8);
        let local_probe_timeout = std::time::Duration::from_secs(3);
        let direct_probe_addrs = local_direct_probe_addrs(&info.addresses);

        for addr in &direct_probe_addrs {
            match tokio::time::timeout(
                local_probe_timeout,
                network.connect_peer_with_addrs(peer_id, vec![*addr]),
            )
            .await
            {
                Ok(Ok((selected_addr, connected_peer_id))) if connected_peer_id == peer_id => {
                    if let Some(ref bc) = self.bootstrap_cache {
                        bc.add_from_connection(connected_peer_id, vec![selected_addr], None)
                            .await;
                    }
                    for agent_id in &machine.agent_ids {
                        self.direct_messaging
                            .mark_connected(*agent_id, machine.machine_id)
                            .await;
                    }
                    tracing::info!(
                        target: "x0x::connect",
                        stage = "connect_to_machine",
                        %machine_prefix,
                        strategy = "local_direct_first",
                        outcome = "direct",
                        selected_addr = %selected_addr,
                        dur_ms = call_start.elapsed().as_millis() as u64,
                        "machine local direct dial succeeded"
                    );
                    return Ok(connectivity::ConnectOutcome::Direct(selected_addr));
                }
                Ok(Ok((selected_addr, connected_peer_id))) => {
                    tracing::warn!(
                        target: "x0x::connect",
                        stage = "connect_to_machine",
                        machine_prefix = %crate::logging::LogHexId::new("machine", &machine_prefix),
                        requested_addr = %crate::logging::LogHexId::addr(&addr.to_string()),
                        selected_addr = %crate::logging::LogHexId::addr(&selected_addr.to_string()),
                        connected_machine_prefix = %crate::logging::LogHexId::new("machine", &network::hex_prefix(&connected_peer_id.0, 4)),
                        "machine local direct dial reached unexpected peer"
                    );
                }
                Ok(Err(e)) => {
                    tracing::debug!(
                        target: "x0x::connect",
                        stage = "connect_to_machine",
                        %machine_prefix,
                        strategy = "local_direct_first",
                        %addr,
                        error = %e,
                        "machine local direct dial failed"
                    );
                }
                Err(_) => {
                    tracing::debug!(
                        target: "x0x::connect",
                        stage = "connect_to_machine",
                        %machine_prefix,
                        strategy = "local_direct_first",
                        %addr,
                        timeout_s = local_probe_timeout.as_secs(),
                        "machine local direct dial timed out"
                    );
                }
            }

            match tokio::time::timeout(local_probe_timeout, network.connect_addr(*addr)).await {
                Ok(Ok(connected_peer_id)) if connected_peer_id == peer_id => {
                    if let Some(ref bc) = self.bootstrap_cache {
                        bc.add_from_connection(connected_peer_id, vec![*addr], None)
                            .await;
                    }
                    for agent_id in &machine.agent_ids {
                        self.direct_messaging
                            .mark_connected(*agent_id, machine.machine_id)
                            .await;
                    }
                    tracing::info!(
                        target: "x0x::connect",
                        stage = "connect_to_machine",
                        %machine_prefix,
                        strategy = "local_direct_raw_fallback",
                        outcome = "direct",
                        selected_addr = %addr,
                        dur_ms = call_start.elapsed().as_millis() as u64,
                        "verified machine local raw-address fallback succeeded"
                    );
                    return Ok(connectivity::ConnectOutcome::Direct(*addr));
                }
                Ok(Ok(connected_peer_id)) => {
                    tracing::warn!(
                        target: "x0x::connect",
                        stage = "connect_to_machine",
                        machine_prefix = %crate::logging::LogHexId::new("machine", &machine_prefix),
                        strategy = "local_direct_raw_fallback",
                        addr = %crate::logging::LogHexId::addr(&addr.to_string()),
                        connected_machine_prefix = %crate::logging::LogHexId::new("machine", &network::hex_prefix(&connected_peer_id.0, 4)),
                        "verified machine local raw-address fallback reached unexpected peer"
                    );
                }
                Ok(Err(e)) => {
                    tracing::debug!(
                        target: "x0x::connect",
                        stage = "connect_to_machine",
                        %machine_prefix,
                        strategy = "local_direct_raw_fallback",
                        %addr,
                        error = %e,
                        "verified machine local raw-address fallback failed"
                    );
                }
                Err(_) => {
                    tracing::debug!(
                        target: "x0x::connect",
                        stage = "connect_to_machine",
                        %machine_prefix,
                        strategy = "local_direct_raw_fallback",
                        %addr,
                        timeout_s = local_probe_timeout.as_secs(),
                        "verified machine local raw-address fallback timed out"
                    );
                }
            }
        }

        network
            .upsert_peer_hints(peer_id, info.addresses.clone(), None)
            .await
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "failed to upsert machine peer hints: {e}"
                )))
            })?;

        match tokio::time::timeout(
            dial_timeout,
            network.connect_peer_with_addrs(peer_id, info.addresses.clone()),
        )
        .await
        {
            Ok(Ok((addr, verified_peer_id))) if verified_peer_id == peer_id => {
                if let Some(ref bc) = self.bootstrap_cache {
                    bc.add_from_connection(verified_peer_id, vec![addr], None)
                        .await;
                    bc.record_success(&verified_peer_id, 0).await;
                }
                for agent_id in &machine.agent_ids {
                    self.direct_messaging
                        .mark_connected(*agent_id, machine.machine_id)
                        .await;
                }
                tracing::info!(
                    target: "x0x::connect",
                    stage = "connect_to_machine",
                    %machine_prefix,
                    strategy = "hinted_peer",
                    outcome = "coordinated",
                    selected_addr = %addr,
                    dur_ms = call_start.elapsed().as_millis() as u64,
                    "machine peer-authenticated dial succeeded"
                );
                return Ok(connectivity::ConnectOutcome::Coordinated(addr));
            }
            Ok(Ok((addr, verified_peer_id))) => {
                tracing::warn!(
                    target: "x0x::connect",
                    stage = "connect_to_machine",
                    machine_prefix = %crate::logging::LogHexId::new("machine", &machine_prefix),
                    selected_addr = %crate::logging::LogHexId::addr(&addr.to_string()),
                    verified_machine_prefix = %crate::logging::LogHexId::new("machine", &network::hex_prefix(&verified_peer_id.0, 4)),
                    "machine dial reached unexpected peer"
                );
            }
            Ok(Err(e)) => {
                tracing::debug!(
                    target: "x0x::connect",
                    stage = "connect_to_machine",
                    %machine_prefix,
                    error = %e,
                    "machine peer-authenticated dial failed"
                );
            }
            Err(_) => {
                tracing::debug!(
                    target: "x0x::connect",
                    stage = "connect_to_machine",
                    %machine_prefix,
                    timeout_s = dial_timeout.as_secs(),
                    "machine peer-authenticated dial timed out"
                );
            }
        }

        if info.should_attempt_direct() {
            for addr in &info.addresses {
                if direct_probe_addrs.contains(addr) {
                    continue;
                }
                match tokio::time::timeout(dial_timeout, network.connect_addr(*addr)).await {
                    Ok(Ok(connected_peer_id)) if connected_peer_id == peer_id => {
                        if let Some(ref bc) = self.bootstrap_cache {
                            bc.add_from_connection(connected_peer_id, vec![*addr], None)
                                .await;
                        }
                        for agent_id in &machine.agent_ids {
                            self.direct_messaging
                                .mark_connected(*agent_id, machine.machine_id)
                                .await;
                        }
                        tracing::info!(
                            target: "x0x::connect",
                            stage = "connect_to_machine",
                            %machine_prefix,
                            strategy = "direct_per_addr",
                            outcome = "direct",
                            selected_addr = %addr,
                            dur_ms = call_start.elapsed().as_millis() as u64,
                            "machine direct dial succeeded"
                        );
                        return Ok(connectivity::ConnectOutcome::Direct(*addr));
                    }
                    Ok(Ok(connected_peer_id)) => {
                        tracing::warn!(
                            target: "x0x::connect",
                            stage = "connect_to_machine",
                            machine_prefix = %crate::logging::LogHexId::new("machine", &machine_prefix),
                            addr = %crate::logging::LogHexId::addr(&addr.to_string()),
                            connected_machine_prefix = %crate::logging::LogHexId::new("machine", &network::hex_prefix(&connected_peer_id.0, 4)),
                            "machine direct dial reached unexpected peer"
                        );
                    }
                    Ok(Err(e)) => {
                        tracing::debug!(
                            target: "x0x::connect",
                            stage = "connect_to_machine",
                            %machine_prefix,
                            %addr,
                            error = %e,
                            "machine direct dial failed"
                        );
                    }
                    Err(_) => {
                        tracing::debug!(
                            target: "x0x::connect",
                            stage = "connect_to_machine",
                            %machine_prefix,
                            %addr,
                            timeout_s = dial_timeout.as_secs(),
                            "machine direct dial timed out"
                        );
                    }
                }
            }
        }

        tracing::warn!(
            target: "x0x::connect",
            stage = "connect_to_machine",
            machine_prefix = %crate::logging::LogHexId::new("machine", &machine_prefix),
            outcome = "unreachable",
            reason = "all_strategies_exhausted",
            dur_ms = call_start.elapsed().as_millis() as u64,
            v4_addrs,
            v6_addrs,
            "all machine connection strategies exhausted"
        );
        Ok(connectivity::ConnectOutcome::Unreachable)
    }

    /// Spawn a background task whose handle is tracked for deterministic
    /// teardown. Returns without spawning once the registry is `closed` (i.e.
    /// `shutdown()` has begun) — this is what closes the join_network race:
    /// a listener requested after shutdown started must never run.
    fn spawn_tracked<F>(&self, fut: F)
    where
        F: std::future::Future<Output = ()> + Send + 'static,
    {
        // Lock held only to inspect `closed` and push the handle; no await
        // happens under it (Rule: keep the std::Mutex hold trivially short).
        let mut guard = match self.tracked_tasks.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        if guard.closed {
            return;
        }
        guard.handles.push(tokio::spawn(fut));
    }

    /// Begin shutdown WITHOUT tearing anything down yet: cancel the shutdown
    /// token and close the tracked-task registry. Idempotent and synchronous.
    ///
    /// This is the prefix of `shutdown()`, split out so an embedder/server can
    /// cancel BEFORE draining its own background tasks (notably a still-running
    /// `join_network`). Once this returns, every `start_*` helper refuses to
    /// start (they check `shutdown_token.is_cancelled()` under their handle
    /// lock) and `spawn_tracked` refuses to spawn — so a `join_network` that is
    /// still finishing cannot leak a heartbeat/reaper/presence/advert/inbox
    /// task past the subsequent `shutdown()`. `shutdown()` still cancels the
    /// token itself (idempotent), so calling `shutdown()` alone remains correct.
    pub fn begin_shutdown(&self) {
        self.shutdown_token.cancel();
        let mut guard = match self.tracked_tasks.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        guard.closed = true;
    }

    /// Save the bootstrap cache and release resources.
    ///
    /// Call this before dropping the agent to ensure the peer cache is
    /// persisted to disk. The background maintenance task saves periodically,
    /// but this guarantees a final save.
    ///
    /// Shutdown ordering is deliberate: the cancellation token is cancelled and
    /// the listener tasks are stopped *before* the gossip runtime and the
    /// network node are torn down. The listeners call into the network (e.g.
    /// `is_connected`), so stopping them first avoids a Phase-2-style hang where
    /// a listener blocks on a transport that is concurrently shutting down.
    /// Idempotent: `cancel()` is idempotent, the registry drains empty on a
    /// second call, and the `stop_*` helpers use `Option::take`.
    pub async fn shutdown(&self) {
        // 1. Signal every token-aware loop to break. Inert until now, so this
        //    is the first thing that changes steady-state behavior.
        self.shutdown_token.cancel();

        // 2. Stop the simple Option<JoinHandle> background tasks.
        self.stop_identity_heartbeat().await;
        self.stop_discovery_cache_reaper().await;

        // 3. Stop the DM inbox and the capability advert service (current gaps:
        //    neither was stopped by shutdown() before). Both abort their own
        //    spawned tasks.
        self.stop_dm_inbox().await;
        {
            let service = {
                let mut guard = self.capability_advert_service.lock().await;
                guard.take()
            };
            if let Some(service) = service {
                service.abort();
            }
        }

        // 4. Drain the tracked-task registry: mark closed (so any in-flight
        //    spawn_tracked is refused), take the handles, grace-await them all
        //    under a SINGLE bounded budget (not per-task — keeps shutdown
        //    prompt), then abort+await any straggler. A cancelled/aborted task
        //    yields Err(JoinError); that is expected, never unwrap it.
        let handles = {
            let mut guard = match self.tracked_tasks.lock() {
                Ok(guard) => guard,
                Err(poisoned) => poisoned.into_inner(),
            };
            guard.closed = true;
            std::mem::take(&mut guard.handles)
        };
        if !handles.is_empty() {
            // Grace-await all tracked tasks under a SINGLE bounded budget (not
            // per-task — keeps shutdown prompt regardless of task count). On
            // timeout, abort the stragglers and await the aborts so none
            // outlives shutdown(). The select! keeps the JoinHandles owned by
            // the awaiting future so the post-abort join can still observe each
            // task's terminal JoinError (cancelled tasks → Err — never
            // unwrapped).
            let abort_handles: Vec<tokio::task::AbortHandle> =
                handles.iter().map(|h| h.abort_handle()).collect();
            let mut join = futures::future::join_all(handles);
            tokio::select! {
                _results = &mut join => {}
                _ = tokio::time::sleep(std::time::Duration::from_secs(3)) => {
                    tracing::warn!(
                        "Agent background tasks did not stop within grace; aborting stragglers"
                    );
                    for handle in &abort_handles {
                        handle.abort();
                    }
                    let _results: Vec<Result<(), tokio::task::JoinError>> = join.await;
                }
            }
        }

        // Shut down presence beacons.
        if let Some(ref pw) = self.presence {
            pw.shutdown().await;
            tracing::info!("Presence system shut down");
        }

        if let Some(ref cache) = self.bootstrap_cache {
            if let Err(e) = cache.save().await {
                tracing::warn!("Failed to save bootstrap cache on shutdown: {e}");
            } else {
                tracing::info!("Bootstrap cache saved on shutdown");
            }
        }

        // Issue #110 Phase 2: tear down the gossip runtime and the QUIC node so
        // an in-process embedder gets the socket and all background tasks back
        // when `shutdown()` returns. The gossip runtime's dispatcher/peer-sync/
        // keepalive tasks hold the transport (and thus the ant-quic endpoint)
        // alive; the daemon binary survives only by process exit, but an
        // embedded host needs these released to re-`serve()` on the same port.
        if let Some(ref runtime) = self.gossip_runtime {
            if let Err(e) = runtime.shutdown().await {
                tracing::warn!("Gossip runtime shutdown error: {e}");
            } else {
                tracing::info!("Gossip runtime shut down");
            }
        }
        if let Some(ref network) = self.network {
            network.shutdown().await;
            tracing::info!("Network node shut down");
        }
    }

    async fn stop_identity_heartbeat(&self) {
        let handle = {
            let mut handle_guard = self.heartbeat_handle.lock().await;
            handle_guard.take()
        };

        if let Some(handle) = handle {
            handle.abort();
            match handle.await {
                Ok(()) => tracing::debug!("Identity heartbeat task stopped"),
                Err(e) if e.is_cancelled() => {
                    tracing::debug!("Identity heartbeat task aborted")
                }
                Err(e) => tracing::warn!("Identity heartbeat task failed during shutdown: {e}"),
            }
        }
    }

    async fn stop_discovery_cache_reaper(&self) {
        let handle = {
            let mut handle_guard = self.discovery_cache_reaper_handle.lock().await;
            handle_guard.take()
        };

        if let Some(handle) = handle {
            handle.abort();
            match handle.await {
                Ok(()) => tracing::debug!("Discovery cache reaper stopped"),
                Err(e) if e.is_cancelled() => {
                    tracing::debug!("Discovery cache reaper aborted")
                }
                Err(e) => tracing::warn!("Discovery cache reaper failed during shutdown: {e}"),
            }
        }
    }

    /// Background task body: periodically prunes the three discovery caches
    /// using the same TTL logic as the query paths (last_seen >= cutoff).
    /// This is the active counterpart to the previous read-only filtering,
    /// preventing unbounded accumulation on long-running daemons.
    async fn discovery_cache_reaper_loop(
        identity_cache: std::sync::Arc<
            tokio::sync::RwLock<std::collections::HashMap<identity::AgentId, DiscoveredAgent>>,
        >,
        machine_cache: std::sync::Arc<
            tokio::sync::RwLock<std::collections::HashMap<identity::MachineId, DiscoveredMachine>>,
        >,
        user_cache: std::sync::Arc<
            tokio::sync::RwLock<std::collections::HashMap<identity::UserId, DiscoveredUser>>,
        >,
        ttl_secs: u64,
        interval: std::time::Duration,
    ) {
        loop {
            tokio::time::sleep(interval).await;
            let cutoff = Self::unix_timestamp_secs().saturating_sub(ttl_secs);
            // Identity cache
            {
                let mut c = identity_cache.write().await;
                c.retain(|_, a| a.last_seen >= cutoff);
            }
            // Machine cache
            {
                let mut c = machine_cache.write().await;
                c.retain(|_, m| m.last_seen >= cutoff);
            }
            // User cache
            {
                let mut c = user_cache.write().await;
                c.retain(|_, u| u.last_seen >= cutoff);
            }
        }
    }

    async fn start_discovery_cache_reaper(&self) -> error::Result<()> {
        let mut guard = self.discovery_cache_reaper_handle.lock().await;
        // Shutdown race (issue #116): refuse to start once shutdown began.
        // Checked under the same lock stop_discovery_cache_reaper takes from.
        if self.shutdown_token.is_cancelled() {
            return Ok(());
        }
        if guard.is_some() {
            return Ok(());
        }

        let identity = std::sync::Arc::clone(&self.identity_discovery_cache);
        let machine = std::sync::Arc::clone(&self.machine_discovery_cache);
        let user = std::sync::Arc::clone(&self.user_discovery_cache);
        let ttl = self.identity_ttl_secs;
        let interval = std::time::Duration::from_secs(DISCOVERY_CACHE_REAPER_INTERVAL_SECS);

        let handle = tokio::spawn(Self::discovery_cache_reaper_loop(
            identity, machine, user, ttl, interval,
        ));
        *guard = Some(handle);
        Ok(())
    }

    // === Direct Messaging ===

    /// Send data directly to a connected agent.
    ///
    /// This bypasses gossip pub/sub for efficient point-to-point communication.
    /// The agent must be connected first via [`Self::connect_to_agent`].
    ///
    /// # Arguments
    ///
    /// * `agent_id` - The target agent's identifier.
    /// * `payload` - The data to send.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Network is not initialized
    /// - Agent is not connected
    /// - Agent is not found in discovery cache
    /// - Send fails
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // First connect to the agent
    /// let outcome = agent.connect_to_agent(&target_agent_id).await?;
    ///
    /// // Then send data directly
    /// agent.send_direct(&target_agent_id, b"hello".to_vec()).await?;
    /// ```
    /// Send data directly to an agent — capability-aware dispatch.
    ///
    /// Looks up the recipient's `DmCapabilities` in the local
    /// [`dm_capability::CapabilityStore`]. If the recipient advertises
    /// `gossip_inbox=true` with a non-empty `kem_public_key`, the send
    /// goes via the gossip DM path (signed+encrypted envelope published
    /// to the recipient's inbox topic with an application-layer ACK).
    /// Otherwise, falls back to the legacy raw-QUIC stream.
    ///
    /// # Errors
    ///
    /// See [`dm::DmError`].
    ///
    /// Uses the default capability-aware policy. Call
    /// [`Self::send_direct_with_config`] to opt into the raw-QUIC fast path
    /// explicitly.
    pub async fn send_direct(
        &self,
        to: &identity::AgentId,
        payload: Vec<u8>,
    ) -> Result<dm::DmReceipt, dm::DmError> {
        self.send_direct_with_config(to, payload, dm::DmSendConfig::default())
            .await
    }

    async fn dm_peer_rtt_ms(&self, agent_id: &identity::AgentId) -> Option<u32> {
        let registry_machine_id = self.direct_messaging.get_machine_id(agent_id).await;
        let cached_machine_id = {
            let cache = self.identity_discovery_cache.read().await;
            cache
                .get(agent_id)
                .map(|entry| entry.machine_id)
                .filter(|machine_id| machine_id.0 != [0_u8; 32])
        };
        let machine_id = registry_machine_id.or(cached_machine_id)?;
        let peer = self
            .bootstrap_cache
            .as_ref()?
            .get(&ant_quic::PeerId(machine_id.0))
            .await?;
        (peer.stats.avg_rtt_ms > 0).then_some(peer.stats.avg_rtt_ms)
    }

    /// X0X-0041: build a prefer-newest-connection hint for the gossip-DM
    /// retry loop. Returns `None` when the recipient's machine_id is unknown
    /// (e.g. uninitialised discovery cache); in that case the gossip path
    /// reverts to legacy behaviour and serves out the full backoff window.
    async fn dm_lifecycle_hint(
        &self,
        agent_id: &identity::AgentId,
    ) -> Option<dm_send::DmLifecycleHint> {
        let registry_machine_id = self.direct_messaging.get_machine_id(agent_id).await;
        let cached_machine_id = {
            let cache = self.identity_discovery_cache.read().await;
            cache
                .get(agent_id)
                .map(|entry| entry.machine_id)
                .filter(|machine_id| machine_id.0 != [0_u8; 32])
        };
        let machine_id = registry_machine_id.or(cached_machine_id)?;
        Some(dm_send::DmLifecycleHint {
            recipient_machine_id: machine_id,
            replaced_rx: self.direct_messaging.subscribe_lifecycle_replaced(),
        })
    }

    async fn dm_peer_likely_offline(
        &self,
        agent_id: &identity::AgentId,
    ) -> Option<(f64, Option<u64>)> {
        if self.is_agent_connected(agent_id).await {
            return None;
        }
        let last_seen = {
            let cache = self.identity_discovery_cache.read().await;
            cache.get(agent_id).map(|entry| entry.last_seen)
        }?;
        let now_secs = Self::unix_timestamp_secs();
        let age_secs = now_secs.saturating_sub(last_seen);
        let heartbeat = self.heartbeat_interval_secs.max(1);
        let phi = age_secs as f64 / heartbeat as f64;
        (phi > 8.0).then_some((phi, Some(age_secs.saturating_mul(1000))))
    }

    /// Like [`Self::send_direct`] with caller-provided [`dm::DmSendConfig`].
    ///
    /// # Errors
    ///
    /// See [`dm::DmError`].
    pub async fn send_direct_with_config(
        &self,
        to: &identity::AgentId,
        payload: Vec<u8>,
        config: dm::DmSendConfig,
    ) -> Result<dm::DmReceipt, dm::DmError> {
        if *to == self.identity.agent_id() {
            self.direct_messaging.record_outgoing_started(*to, None);
            if payload.len() > direct::MAX_DIRECT_PAYLOAD_SIZE {
                self.direct_messaging.record_outgoing_failed(*to);
                return Err(dm::DmError::PayloadTooLarge {
                    len: payload.len(),
                    max: direct::MAX_DIRECT_PAYLOAD_SIZE,
                });
            }

            let delivered = self
                .direct_messaging
                .handle_loopback(
                    self.identity.machine_id(),
                    self.identity.agent_id(),
                    payload,
                )
                .await;
            let receipt = dm_send::loopback_receipt();
            self.direct_messaging
                .record_outgoing_succeeded(*to, receipt.path);
            tracing::debug!(
                target: "dm.trace",
                stage = "outbound_send_returned_ok",
                request_id = %hex::encode(receipt.request_id),
                sender = %hex::encode(self.identity.agent_id().as_bytes()),
                recipient = %hex::encode(to.as_bytes()),
                path = "loopback",
                delivered_subscribers = delivered,
            );
            return Ok(receipt);
        }

        let advert_cap = self.capability_store.lookup(to);
        let advert_gossip_ready = advert_cap
            .as_ref()
            .is_some_and(|caps| caps.gossip_inbox && !caps.kem_public_key.is_empty());
        let (cap, cap_source) = if advert_gossip_ready {
            (advert_cap, "advert_cache")
        } else {
            let contact_cap = {
                let contacts = self.contact_store.read().await;
                contacts.get(to).and_then(|contact| {
                    contact
                        .dm_capabilities
                        .as_ref()
                        .filter(|caps| caps.gossip_inbox && !caps.kem_public_key.is_empty())
                        .cloned()
                })
            };
            match contact_cap {
                Some(cap) if advert_cap.is_some() => {
                    (Some(cap), "contact_card_after_unusable_advert")
                }
                Some(cap) => (Some(cap), "contact_card"),
                None if advert_cap.is_some() => (advert_cap, "advert_cache_unusable"),
                None => (None, "none"),
            }
        };
        let gossip_ok = cap
            .as_ref()
            .map(|c| c.gossip_inbox && !c.kem_public_key.is_empty())
            .unwrap_or(false);
        tracing::debug!(
            target: "dm.trace",
            stage = "capability_lookup",
            recipient = %hex::encode(to.as_bytes()),
            hit = cap.is_some(),
            gossip_ok,
            source = cap_source,
            capability_store_entries = self.capability_store.len(),
        );

        // X0X-0070b: seed the relay fallback. Only retain the payload + KEM
        // key clone when the engine is enabled AND we have a key to seal
        // a fresh envelope with. With the default disabled policy this
        // closure never runs - the happy path pays nothing.
        let relay_seed: Option<(Vec<u8>, Vec<u8>)> = if self.peer_relay.policy().enabled {
            cap.as_ref()
                .filter(|c| !c.kem_public_key.is_empty())
                .map(|c| (payload.clone(), c.kem_public_key.clone()))
        } else {
            None
        };

        let rtt_hint_ms = self.dm_peer_rtt_ms(to).await;
        let mut config = config;
        // Direct transport RTT is a valid hint for raw-QUIC work, but it is
        // not a reliable bound for the gossip-inbox ACK path. Keep the
        // conservative default for PubSub-backed DMs unless the caller passed
        // an explicit timeout.
        if !gossip_ok && config.timeout_per_attempt == dm::dm_attempt_timeout(None) {
            config.timeout_per_attempt = dm::dm_attempt_timeout(rtt_hint_ms);
        }
        self.direct_messaging
            .record_outgoing_started(*to, rtt_hint_ms);
        if let Some((phi, last_seen_ms_ago)) = self.dm_peer_likely_offline(to).await {
            self.direct_messaging.record_outgoing_failed(*to);
            return Err(dm::DmError::PeerLikelyOffline {
                phi,
                last_seen_ms_ago,
            });
        }

        let mut preferred_raw_err = None;
        let prefer_newest_grace = std::time::Duration::from_millis(config.prefer_newest_grace_ms);
        let preferred_raw_receipt = if config.prefer_raw_quic_if_connected && !config.require_gossip
        {
            match self
                .send_direct_raw_quic(
                    to,
                    &payload,
                    config.raw_quic_receive_ack_timeout,
                    prefer_newest_grace,
                )
                .await
            {
                Ok(path) => Some(dm_send::raw_quic_receipt_for_path(path)),
                Err(e) => {
                    tracing::debug!(
                        target: "x0x::direct",
                        recipient = %hex::encode(to.as_bytes()),
                        error = %e,
                        "preferred raw-QUIC path unavailable; falling back to capability-aware send"
                    );
                    preferred_raw_err = Some(e);
                    None
                }
            }
        } else {
            None
        };

        let result = if let Some(receipt) = preferred_raw_receipt {
            Ok(receipt)
        } else if preferred_raw_err.as_ref().is_some_and(|err| {
            config.stop_fallback_on_raw_error
                || Self::raw_quic_error_should_stop_fallback(err, gossip_ok)
        }) {
            match preferred_raw_err.take() {
                Some(e) => Err(Self::map_raw_quic_dm_error(e)),
                None => Err(dm::DmError::NoConnectivity(
                    "raw-QUIC send failed before gossip fallback".to_string(),
                )),
            }
        } else if gossip_ok {
            match self.gossip_runtime.as_ref() {
                Some(runtime) => {
                    let signing =
                        gossip::SigningContext::from_keypair(self.identity.agent_keypair());
                    let kem_pub = cap
                        .as_ref()
                        .map(|c| c.kem_public_key.clone())
                        .unwrap_or_default();
                    // X0X-0041: build a lifecycle hint when the recipient's
                    // machine_id is known. The retry loop short-circuits on
                    // `Replaced` for that machine_id rather than serving out
                    // the full backoff window.
                    let lifecycle_hint = self.dm_lifecycle_hint(to).await;
                    dm_send::send_via_gossip(
                        dm_send::DmSendContext {
                            pubsub: std::sync::Arc::clone(runtime.pubsub()),
                            signing: &signing,
                            self_agent_id: self.identity.agent_id(),
                            self_machine_id: self.identity.machine_id(),
                            inflight: std::sync::Arc::clone(&self.dm_inflight_acks),
                        },
                        *to,
                        &kem_pub,
                        payload,
                        &config,
                        lifecycle_hint,
                    )
                    .await
                }
                None => Err(dm::DmError::LocalGossipUnavailable(
                    "send_direct: no gossip runtime configured".to_string(),
                )),
            }
        } else if config.require_gossip {
            Err(dm::DmError::RecipientKeyUnavailable(format!(
                "recipient {} has no gossip DM capability advert",
                hex::encode(to.as_bytes())
            )))
        } else {
            match preferred_raw_err {
                Some(e) => Err(Self::map_raw_quic_dm_error(e)),
                None => self
                    .send_direct_raw_quic(
                        to,
                        &payload,
                        config.raw_quic_receive_ack_timeout,
                        prefer_newest_grace,
                    )
                    .await
                    .map(dm_send::raw_quic_receipt_for_path)
                    .map_err(Self::map_raw_quic_dm_error),
            }
        };

        match result {
            Ok(receipt) => {
                self.direct_messaging
                    .record_outgoing_succeeded(*to, receipt.path);
                // X0X-0070b: every direct-DM success clears the relay engine's
                // per-peer failure history. A peer that had crossed
                // `needs_relay` and now recovers a direct path increments
                // `direct_recovered_after_relay` exactly once - proving the
                // fallback is transient.
                self.peer_relay.record_direct_success(to);
                Ok(receipt)
            }
            Err(direct_err) => {
                self.direct_messaging.record_outgoing_failed(*to);
                // X0X-0070b: count this direct-DM failure on the relay engine.
                // With the default disabled policy `needs_relay` always
                // returns `false` and the fallback below is skipped. With
                // an opted-in policy this drives the relay decision.
                self.peer_relay.record_direct_failure(to);
                // X0X-0070b: relay fallback. We only attempt it when the
                // engine says the peer has now crossed `needs_relay`, and
                // only when we have both a saved payload and a recipient
                // KEM key - without those the relay envelope can't be
                // sealed. On ANY relay-side failure we surface the
                // ORIGINAL direct error so the caller's view stays
                // consistent with the path that was actually tried.
                if let Some((saved_payload, kem_pub)) = relay_seed {
                    if self.peer_relay.needs_relay(to) {
                        match self.try_relay_fallback(to, saved_payload, &kem_pub).await {
                            Ok(relay_receipt) => {
                                self.direct_messaging
                                    .record_outgoing_succeeded(*to, relay_receipt.path);
                                return Ok(relay_receipt);
                            }
                            Err(relay_err) => {
                                tracing::debug!(
                                    target: "x0x::relay",
                                    recipient = %hex::encode(to.as_bytes()),
                                    direct_err = %direct_err,
                                    relay_err = %relay_err,
                                    "X0X-0070b relay fallback failed; surfacing original direct error"
                                );
                            }
                        }
                    }
                }
                Err(direct_err)
            }
        }
    }

    /// X0X-0070b: wrap `payload` in a fresh sealed [`dm::DmEnvelope`] +
    /// [`peer_relay::RelayedDm`], pick a relay candidate via
    /// [`peer_relay::PeerRelay::select_relay`], and forward to that candidate
    /// over the same direct-DM transport using the dedicated
    /// [`network::RELAYED_DM_STREAM_TYPE`] stream-type. The relay verifies
    /// the [`peer_relay::RelayHeader`] signature, confirms it is being
    /// asked to forward (not to be the final recipient), and sends the
    /// inner envelope on to `to` - one hop only, no re-wrapping.
    ///
    /// # Errors
    ///
    /// - [`dm::DmError::NoRelayCandidate`] if no third-party candidate
    ///   exists or the candidate's `MachineId` is not in the discovery
    ///   cache (we need it to address the QUIC peer).
    /// - [`dm::DmError::RelayBuildFailed`] if signing the
    ///   [`peer_relay::RelayHeader`] or parsing the agent secret key
    ///   fails.
    /// - [`dm::DmError::EnvelopeConstruction`] if KEM encapsulation /
    ///   AEAD seal / envelope signature fails (delegates to
    ///   [`dm::EnvelopeBuilder::build_payload_envelope`]).
    /// - [`dm::DmError::NoConnectivity`] if no network is configured.
    /// - [`dm::DmError::PublishFailed`] if the underlying
    ///   [`network::NetworkNode::send_direct_typed`] send fails.
    async fn try_relay_fallback(
        &self,
        to: &identity::AgentId,
        payload: Vec<u8>,
        recipient_kem_public_key: &[u8],
    ) -> Result<dm::DmReceipt, dm::DmError> {
        let sender = self.identity.agent_id();
        let candidates = self.relay_candidates.read().await.clone();
        let Some(relay_agent) = self.peer_relay.select_relay(&candidates, to, &sender) else {
            return Err(dm::DmError::NoRelayCandidate);
        };

        let relay_machine_id = {
            let cache = self.identity_discovery_cache.read().await;
            cache.get(&relay_agent).map(|e| e.machine_id)
        };
        let Some(relay_machine_id) = relay_machine_id else {
            // We have the relay candidate's agent_id but no machine_id -
            // can't address the QUIC peer. Treat as "no candidate" so the
            // caller surfaces the original direct error.
            return Err(dm::DmError::NoRelayCandidate);
        };

        let now = dm::now_unix_ms();
        let expires = now.saturating_add(dm_send::DEFAULT_ENVELOPE_LIFETIME_MS);
        let request_id = dm_send::fresh_request_id();
        let signing = gossip::SigningContext::from_keypair(self.identity.agent_keypair());
        let envelope = dm::EnvelopeBuilder::build_payload_envelope(
            request_id,
            &sender,
            &self.identity.machine_id(),
            to,
            recipient_kem_public_key,
            now,
            expires,
            payload,
            |bytes| signing.sign(bytes).map_err(|e| e.to_string()),
        )?;

        let (sender_pub_bytes, sender_sec_bytes) = self.identity.agent_keypair().to_bytes();
        let sender_secret = ant_quic::MlDsaSecretKey::from_bytes(&sender_sec_bytes)
            .map_err(|e| dm::DmError::RelayBuildFailed(format!("agent secret key: {e:?}")))?;
        let relayed = self
            .peer_relay
            .build_relayed_dm(to, &sender, sender_pub_bytes, now, envelope, |bytes| {
                ant_quic::crypto::raw_public_keys::pqc::sign_with_ml_dsa(&sender_secret, bytes)
                    .map(|s| s.as_bytes().to_vec())
                    .map_err(|e| format!("{e:?}"))
            })
            .map_err(dm::DmError::RelayBuildFailed)?;

        let wire = postcard::to_allocvec(&relayed).map_err(|e| {
            dm::DmError::EnvelopeConstruction(format!("relayed envelope postcard: {e}"))
        })?;
        let network = self
            .network
            .as_ref()
            .ok_or_else(|| dm::DmError::NoConnectivity("no network for relay send".to_string()))?;
        let relay_peer_id = ant_quic::PeerId(relay_machine_id.0);
        network
            .send_direct_typed(
                &relay_peer_id,
                sender.as_bytes(),
                network::RELAYED_DM_STREAM_TYPE,
                &wire,
            )
            .await
            .map_err(|e| dm::DmError::PublishFailed(format!("relay send: {e}")))?;

        Ok(dm::DmReceipt {
            request_id,
            accepted_at: std::time::Instant::now(),
            retries_used: 0,
            path: dm::DmPath::Relayed { via: relay_agent },
        })
    }

    /// X0X-0070b: borrow the application-level peer-relay engine. Runtimes
    /// use this to read [`peer_relay::RelayStats`] for telemetry and to
    /// inspect the active [`peer_relay::RelayPolicy`].
    #[must_use]
    pub fn peer_relay(&self) -> &peer_relay::PeerRelay {
        &self.peer_relay
    }

    /// X0X-0070b: snapshot the current relay candidate set. Returns a
    /// freshly-cloned vector so the caller never holds the underlying
    /// `RwLock`. The set is seeded from `NetworkConfig.peer_relay.candidates`
    /// at build time; the gossip-announce subscriber (a follow-up commit)
    /// extends it at runtime.
    pub async fn relay_candidates(&self) -> Vec<identity::AgentId> {
        self.relay_candidates.read().await.clone()
    }

    /// Legacy raw-QUIC direct-send path. Internal fallback only.
    ///
    /// X0X-0053: `prefer_newest_grace` is the bounded post-Replaced reissue
    /// grace — the maximum time we wait for the new connection's
    /// `is_connected` to flip true after a same-peer `Replaced` event fires
    /// mid-send before we reissue. Setting it to zero disables the grace and
    /// reissues immediately on Replaced (or fails if the new connection is
    /// not yet live).
    ///
    /// On the ACKed raw path, the in-flight `send_with_receive_ack` future
    /// is raced against `lifecycle_replaced_rx.recv()` filtered for the
    /// target peer's machine_id. On Replaced for the target peer, the
    /// in-flight send is abandoned and reissued once against the new
    /// generation. If the reissue also fails, the standard error is
    /// returned. This closes the X0X-0041 coverage gap surfaced by the
    /// Phase A bisect (P1 finding in
    /// `proofs/sota-borrow-phaseA-bisect-20260508T214634Z/ANALYSIS.md` §0.1).
    async fn send_direct_raw_quic(
        &self,
        agent_id: &identity::AgentId,
        payload: &[u8],
        receive_ack_timeout: Option<std::time::Duration>,
        prefer_newest_grace: std::time::Duration,
    ) -> error::NetworkResult<dm::DmPath> {
        let send_start = std::time::Instant::now();
        let agent_prefix = network::hex_prefix(&agent_id.0, 4);
        let self_prefix = network::hex_prefix(&self.identity.agent_id().0, 4);
        let bytes = payload.len();
        let digest = direct::dm_payload_digest_hex(payload);
        let target_path_label = if receive_ack_timeout.is_some() {
            "raw_quic_acked"
        } else {
            "raw_quic"
        };

        let network = self.network.as_ref().ok_or_else(|| {
            tracing::warn!(
                target: "x0x::direct",
                stage = "send",
                agent_prefix = %crate::logging::LogHexId::agent(&agent_prefix),
                outcome = "err_no_network",
                "network not initialised"
            );
            error::NetworkError::NodeCreation("network not initialized".to_string())
        })?;

        // Resolve the best known machine_id, preferring a machine that is
        // actually connected right now. Discovery cache entries can lag behind
        // the direct-messaging registry when an inbound connection is accepted
        // and later reconciled from transport events.
        let cached_machine_id = {
            let cache = self.identity_discovery_cache.read().await;
            cache
                .get(agent_id)
                .map(|d| d.machine_id)
                .filter(|m| m.0 != [0u8; 32]) // Ignore placeholder zeroed IDs
        };
        let registry_machine_id = self.direct_messaging.get_machine_id(agent_id).await;

        let (machine_id, resolution) = match (cached_machine_id, registry_machine_id) {
            (Some(id), _) if network.is_connected(&ant_quic::PeerId(id.0)).await => {
                (id, "cached_connected")
            }
            (_, Some(id)) if network.is_connected(&ant_quic::PeerId(id.0)).await => {
                if cached_machine_id != Some(id) {
                    let mut cache = self.identity_discovery_cache.write().await;
                    if let Some(entry) = cache.get_mut(agent_id) {
                        entry.machine_id = id;
                    }
                }
                (id, "registry_connected")
            }
            (Some(id), None) => (id, "cached_not_connected"),
            (Some(id), Some(_)) => (id, "cached_both_disconnected"),
            (None, Some(id)) => (id, "registry_not_connected"),
            (None, None) => {
                tracing::debug!(
                    target: "x0x::direct",
                    stage = "send",
                    %agent_prefix,
                    resolution = "last_resort_connect",
                    "no machine_id known; triggering connect_to_agent"
                );
                let _ = self.connect_to_agent(agent_id).await;
                let id = self
                    .direct_messaging
                    .get_machine_id(agent_id)
                    .await
                    .ok_or_else(|| {
                        tracing::warn!(
                            target: "x0x::direct",
                            stage = "send",
                            agent_prefix = %crate::logging::LogHexId::agent(&agent_prefix),
                            outcome = "err_agent_not_found",
                            dur_ms = send_start.elapsed().as_millis() as u64,
                            "no machine_id after connect_to_agent"
                        );
                        error::NetworkError::AgentNotFound(agent_id.0)
                    })?;
                (id, "post_connect")
            }
        };

        // Check if connected. ant-quic's live connection table is the source
        // of truth; the x0x lifecycle table is a derived fast-fail cache and
        // can briefly lag during connection replacement/supersede churn. Raw
        // sends best-effort clear stale lifecycle blocks when ant-quic is live;
        // capability-first gossip sends may leave cosmetic stale diagnostics
        // until a raw probe/send path observes the live connection.
        let ant_peer_id = ant_quic::PeerId(machine_id.0);
        let machine_prefix = network::hex_prefix(&machine_id.0, 4);
        let mut connected = network.is_connected(&ant_peer_id).await;

        // X0X-0033: when machine_id is known (resolved from cache or registry)
        // but ant-quic isn't currently connected, the X0X-0031 send-readiness
        // hardening (single-flight per peer + bounded concurrency, falling
        // through to bootstrap-cache redial) used to sit behind this check
        // unreachable from the raw path. Drive it explicitly here so the raw
        // direct path attempts repair before bailing with AgentNotConnected.
        // Skip when resolution == "post_connect" (last-resort branch already
        // invoked connect_to_agent above).
        let mut repair_outcome: Option<&'static str> = None;
        if !connected && resolution != "post_connect" {
            const REPAIR_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);
            let outcome = match tokio::time::timeout(
                REPAIR_TIMEOUT,
                network.ensure_peer_send_ready(&ant_peer_id),
            )
            .await
            {
                Ok(Ok(())) => "repaired",
                Ok(Err(_)) => "repair_failed",
                Err(_) => "repair_timeout",
            };
            repair_outcome = Some(outcome);
            tracing::debug!(
                target: "x0x::direct",
                stage = "send",
                %agent_prefix,
                %machine_prefix,
                resolution,
                outcome,
                "send-readiness repair on disconnected peer"
            );
            connected = network.is_connected(&ant_peer_id).await;
        }

        // X0X-0051 / X0X-0053: the X0X-0041 prefer-newest-grace block was
        // removed in x0x 0.19.33. It only fired when `is_connected` returned
        // false before the send, never racing `Replaced` against the in-flight
        // `send_with_receive_ack` below — so it had a coverage gap on the
        // ACKed raw-DM path the Phase A harness exercises. The proper
        // re-implementation (race in-flight send against same-peer Replaced)
        // is tracked in X0X-0053. This path now falls straight through to the
        // standard !connected error handling.

        if connected {
            if let Some(reason) = self.direct_messaging.lifecycle_block_reason(&machine_id) {
                tracing::warn!(
                    target: "x0x::direct",
                    stage = "send",
                    agent_prefix = %crate::logging::LogHexId::agent(&agent_prefix),
                    machine_prefix = %crate::logging::LogHexId::new("machine", &machine_prefix),
                    resolution,
                    ?repair_outcome,
                    reason = %reason,
                    "ignoring stale lifecycle block because ant-quic reports a live connection"
                );
                self.direct_messaging
                    .record_lifecycle_established(machine_id, None);
            }
        } else {
            if let Some(reason) = self.direct_messaging.lifecycle_block_reason(&machine_id) {
                tracing::warn!(
                    target: "x0x::direct",
                    stage = "send",
                    agent_prefix = %crate::logging::LogHexId::agent(&agent_prefix),
                    machine_prefix = %crate::logging::LogHexId::new("machine", &machine_prefix),
                    resolution,
                    ?repair_outcome,
                    outcome = "err_peer_disconnected",
                    reason = %reason,
                    dur_ms = send_start.elapsed().as_millis() as u64,
                    "lifecycle watcher says peer is disconnected"
                );
                return Err(error::NetworkError::ConnectionFailed(format!(
                    "peer disconnected: {reason}"
                )));
            }
            tracing::warn!(
                target: "x0x::direct",
                stage = "send",
                agent_prefix = %crate::logging::LogHexId::agent(&agent_prefix),
                machine_prefix = %crate::logging::LogHexId::new("machine", &machine_prefix),
                resolution,
                ?repair_outcome,
                outcome = "err_not_connected",
                bytes,
                dur_ms = send_start.elapsed().as_millis() as u64,
                "machine_id resolved but peer not currently connected after repair attempt"
            );
            return Err(error::NetworkError::AgentNotConnected(agent_id.0));
        }

        tracing::debug!(
            target: "dm.trace",
            stage = "path_chosen",
            sender = %hex::encode(self.identity.agent_id().as_bytes()),
            recipient = %hex::encode(agent_id.as_bytes()),
            machine_id = %hex::encode(machine_id.as_bytes()),
            path = target_path_label,
            bytes,
            digest = %digest,
        );

        // Send via network layer. Prefer receive-pipeline ACK when configured:
        // success then means the remote ant-quic reader drained the direct
        // message bytes, not merely that the local socket accepted them.
        let send_result = if let Some(timeout) = receive_ack_timeout {
            let wire = direct::DirectMessaging::encode_message(&self.identity.agent_id(), payload)?;
            tracing::debug!(
                target: "dm.trace",
                stage = "wire_encoded",
                sender = %hex::encode(self.identity.agent_id().as_bytes()),
                recipient = %hex::encode(agent_id.as_bytes()),
                path = "raw_quic_acked",
                bytes = wire.len(),
                payload_bytes = bytes,
                digest = %digest,
            );
            // X0X-0053: race the in-flight send_with_receive_ack against
            // same-peer Replaced. On Replaced for this machine_id, abandon
            // the in-flight future (Quinn streams are drop-safe — see
            // ant-quic's send_with_receive_ack contract) and reissue once
            // against the new generation. The reissue does not race again;
            // a healthy peer should converge in a single supersede cycle.
            self.send_ack_racing_replaced(
                network.as_ref(),
                ant_peer_id,
                machine_id,
                &wire,
                timeout,
                prefer_newest_grace,
                agent_id,
            )
            .await
        } else {
            tracing::debug!(
                target: "dm.trace",
                stage = "wire_encoded",
                sender = %hex::encode(self.identity.agent_id().as_bytes()),
                recipient = %hex::encode(agent_id.as_bytes()),
                path = "raw_quic",
                bytes,
                digest = %digest,
            );
            network
                .send_direct(&ant_peer_id, &self.identity.agent_id().0, payload)
                .await
                .map(|()| dm::DmPath::RawQuic)
        };

        match send_result {
            Ok(path) => {
                let path_label = match path {
                    dm::DmPath::Loopback => "loopback",
                    dm::DmPath::RawQuic => "raw_quic",
                    dm::DmPath::RawQuicAcked => "raw_quic_acked",
                    dm::DmPath::GossipInbox => "gossip_inbox",
                    dm::DmPath::Relayed { .. } => "relayed",
                };
                tracing::debug!(
                    target: "dm.trace",
                    stage = "outbound_send_returned_ok",
                    sender = %hex::encode(self.identity.agent_id().as_bytes()),
                    recipient = %hex::encode(agent_id.as_bytes()),
                    machine_id = %hex::encode(machine_id.as_bytes()),
                    path = path_label,
                    bytes,
                    digest = %digest,
                    dur_ms = send_start.elapsed().as_millis() as u64,
                );
                tracing::info!(
                    target: "x0x::direct",
                    stage = "send",
                    from = %self_prefix,
                    to = %agent_prefix,
                    %machine_prefix,
                    resolution,
                    bytes,
                    dur_ms = send_start.elapsed().as_millis() as u64,
                    outcome = "ok",
                    path = ?path,
                    "direct message sent"
                );
                Ok(path)
            }
            Err(e) => {
                tracing::warn!(
                    target: "x0x::direct",
                    stage = "send",
                    from = %self_prefix,
                    to = %agent_prefix,
                    machine_prefix = %crate::logging::LogHexId::new("machine", &machine_prefix),
                    resolution,
                    bytes,
                    dur_ms = send_start.elapsed().as_millis() as u64,
                    outcome = "err_transport",
                    error = %e,
                    "transport send_direct failed"
                );
                // A receive-ACK-path failure on a connection that still reads
                // as connected means the connection is a zombie: the remote
                // endpoint is gone (supersede/NAT loss without a lifecycle
                // event) yet `is_connected` keeps steering every retry back
                // onto it via `cached_connected`. Tear it down so the next
                // attempt fails the fast path and takes the X0X-0031/0033
                // send-readiness repair (fresh dial) instead of re-sending
                // into the same dead connection until the caller's deadline.
                if receive_ack_timeout.is_some() && network.is_connected(&ant_peer_id).await {
                    match network.disconnect(&ant_peer_id).await {
                        Ok(()) => tracing::info!(
                            target: "x0x::direct",
                            stage = "send",
                            to = %agent_prefix,
                            %machine_prefix,
                            "tore down zombie connection after acked send failure; retry will redial"
                        ),
                        Err(de) => tracing::debug!(
                            target: "x0x::direct",
                            stage = "send",
                            to = %agent_prefix,
                            %machine_prefix,
                            error = %de,
                            "failed to tear down zombie connection after acked send failure"
                        ),
                    }
                }
                Err(e)
            }
        }
    }

    /// X0X-0053: race the in-flight `send_with_receive_ack` against same-peer
    /// `Replaced`. On Replaced for the target peer, abandon the in-flight
    /// future, briefly wait for the new connection's `is_connected` to flip
    /// true (bounded by `prefer_newest_grace`), then reissue once against
    /// the new generation. The reissue does not race again — a healthy peer
    /// converges in a single supersede cycle. Lag handling on the broadcast
    /// channel mirrors `dm_send::wait_for_ack_or_backoff_or_replaced` —
    /// drain to current and re-subscribe.
    #[allow(clippy::too_many_arguments)]
    async fn send_ack_racing_replaced(
        &self,
        network: &network::NetworkNode,
        ant_peer_id: ant_quic::PeerId,
        machine_id: identity::MachineId,
        wire: &[u8],
        timeout: std::time::Duration,
        prefer_newest_grace: std::time::Duration,
        agent_id: &identity::AgentId,
    ) -> error::NetworkResult<dm::DmPath> {
        use tokio::sync::broadcast::error::RecvError;
        use tokio::sync::broadcast::error::TryRecvError as BroadcastTryRecvError;

        // Subscribe BEFORE issuing the send so any Replaced that fires
        // mid-send is delivered to this receiver and not dropped.
        let mut replaced_rx = self.direct_messaging.subscribe_lifecycle_replaced();
        let pre_send_generation = self.direct_messaging.current_generation(&machine_id);

        let agent_prefix = network::hex_prefix(&agent_id.0, 4);
        let machine_prefix = network::hex_prefix(&machine_id.0, 4);
        let self_prefix = network::hex_prefix(&self.identity.agent_id().0, 4);

        let ack_race_test_hook = self.direct_messaging.raw_quic_ack_race_test_hook();

        // First attempt: race send_with_receive_ack against same-peer Replaced.
        let send_fut = async {
            if let Some(hook) = ack_race_test_hook.as_ref() {
                hook.notify_first_attempt_started();
            }
            let result = network
                .send_with_receive_ack(ant_peer_id, wire, timeout)
                .await;
            if let Some(hook) = ack_race_test_hook.as_ref() {
                hook.hold_first_attempt_result().await;
            }
            result
        };
        tokio::pin!(send_fut);

        let superseded_to: u64;

        loop {
            tokio::select! {
                biased;
                send_result = &mut send_fut => {
                    // X0X-0053: even when send_fut completes (Ok or Err)
                    // first, drain the broadcast for any queued Replaced
                    // event for our peer. On Err with a queued supersede,
                    // we treat the failure as a casualty of the supersede
                    // race and reissue against the new generation —
                    // exactly the production case where the in-flight ACK
                    // exchange errors out fast on the dying connection
                    // milliseconds before the new connection is registered.
                    match send_result {
                        Some(Ok(())) => return Ok(dm::DmPath::RawQuicAcked),
                        Some(Err(e)) => {
                            // Drain any queued Replaced for our peer.
                            let mut queued_supersede: Option<u64> = None;
                            loop {
                                match replaced_rx.try_recv() {
                                    Ok((m, gen)) if m == machine_id => {
                                        queued_supersede = Some(gen);
                                    }
                                    Ok(_) => continue,
                                    Err(BroadcastTryRecvError::Empty)
                                    | Err(BroadcastTryRecvError::Closed)
                                    | Err(BroadcastTryRecvError::Lagged(_)) => break,
                                }
                            }
                            if let Some(gen) = queued_supersede {
                                superseded_to = gen;
                                break;
                            }
                            let reason = format!("send_with_receive_ack failed: {e}");
                            return if Self::raw_quic_ack_receive_backpressured(&reason) {
                                Err(error::NetworkError::RemoteReceiveBackpressured(reason))
                            } else {
                                Err(error::NetworkError::ConnectionFailed(reason))
                            };
                        }
                        None => return Err(error::NetworkError::NodeCreation(
                            "network node not initialized".to_string(),
                        )),
                    }
                }
                replaced = replaced_rx.recv() => {
                    match replaced {
                        Ok((m, gen)) if m == machine_id => {
                            superseded_to = gen;
                            break;
                        }
                        Ok(_) => continue,
                        Err(RecvError::Lagged(_)) => {
                            // Drain the channel for any pending event for our
                            // peer; if found, treat as supersede.
                            let mut found: Option<u64> = None;
                            loop {
                                match replaced_rx.try_recv() {
                                    Ok((m, gen)) if m == machine_id => {
                                        found = Some(gen);
                                        break;
                                    }
                                    Ok(_) => continue,
                                    Err(BroadcastTryRecvError::Empty)
                                    | Err(BroadcastTryRecvError::Closed)
                                    | Err(BroadcastTryRecvError::Lagged(_)) => break,
                                }
                            }
                            if let Some(gen) = found {
                                superseded_to = gen;
                                break;
                            }
                            // No event for our peer — re-subscribe to clear
                            // lag state and keep waiting.
                            replaced_rx = self
                                .direct_messaging
                                .subscribe_lifecycle_replaced();
                            continue;
                        }
                        Err(RecvError::Closed) => {
                            // Channel closed — no further supersede signals.
                            // Fall through to await the in-flight send to its
                            // natural completion.
                            let result = (&mut send_fut).await;
                            return match result {
                                Some(Ok(())) => Ok(dm::DmPath::RawQuicAcked),
                                Some(Err(e)) => {
                                    let reason =
                                        format!("send_with_receive_ack failed: {e}");
                                    if Self::raw_quic_ack_receive_backpressured(&reason) {
                                        Err(error::NetworkError::RemoteReceiveBackpressured(reason))
                                    } else {
                                        Err(error::NetworkError::ConnectionFailed(reason))
                                    }
                                }
                                None => Err(error::NetworkError::NodeCreation(
                                    "network node not initialized".to_string(),
                                )),
                            };
                        }
                    }
                }
            }
        }

        // Reached here only via a confirmed same-peer Replaced. The pinned
        // in-flight send future is no longer polled and will be dropped at
        // scope exit (Quinn streams are drop-safe — abandoning the future
        // simply releases the local stream handle; the underlying connection
        // is the one ant-quic is replacing). Wait briefly for the new
        // connection's `is_connected` to flip true before reissuing.
        let new_generation = superseded_to;
        if let Some(hook) = ack_race_test_hook.as_ref() {
            hook.notify_replaced_short_circuit();
        }
        tracing::debug!(
            target: "dm.trace",
            stage = "raw_quic_ack_replaced_short_circuit",
            from = %self_prefix,
            to = %agent_prefix,
            %machine_prefix,
            pre_send_generation = ?pre_send_generation,
            new_generation,
            grace_ms = prefer_newest_grace.as_millis() as u64,
            "X0X-0053: same-peer Replaced fired during in-flight send_with_receive_ack; abandoning and reissuing",
        );

        // Bounded grace: poll for the new connection to be live before
        // reissuing. If it never flips inside the grace window, return the
        // standard not-connected error and let the caller fall back.
        if !prefer_newest_grace.is_zero() {
            let grace_deadline = tokio::time::Instant::now() + prefer_newest_grace;
            const POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(20);
            while tokio::time::Instant::now() < grace_deadline {
                if network.is_connected(&ant_peer_id).await {
                    break;
                }
                tokio::time::sleep(POLL_INTERVAL).await;
            }
        }

        if !network.is_connected(&ant_peer_id).await {
            return Err(error::NetworkError::AgentNotConnected(agent_id.0));
        }

        // Reissue once against the new generation. No further race — a
        // healthy peer should converge in a single supersede cycle.
        match network
            .send_with_receive_ack(ant_peer_id, wire, timeout)
            .await
        {
            Some(Ok(())) => Ok(dm::DmPath::RawQuicAcked),
            Some(Err(e)) => {
                let reason = format!("send_with_receive_ack failed: {e}");
                if Self::raw_quic_ack_receive_backpressured(&reason) {
                    Err(error::NetworkError::RemoteReceiveBackpressured(reason))
                } else {
                    Err(error::NetworkError::ConnectionFailed(reason))
                }
            }
            None => Err(error::NetworkError::NodeCreation(
                "network node not initialized".to_string(),
            )),
        }
    }

    fn raw_quic_error_should_stop_fallback(
        err: &error::NetworkError,
        gossip_available: bool,
    ) -> bool {
        match err {
            // These are semantic/local failures; trying the gossip path cannot
            // make the payload smaller or create a missing local network node.
            error::NetworkError::PayloadTooLarge { .. } | error::NetworkError::NodeCreation(_) => {
                true
            }
            error::NetworkError::ConnectionFailed(reason)
                if reason.starts_with("peer disconnected:")
                    || reason.starts_with("send_with_receive_ack failed:") =>
            {
                !gossip_available
            }
            error::NetworkError::RemoteReceiveBackpressured(_) => !gossip_available,
            error::NetworkError::ConnectionClosed(_)
            | error::NetworkError::ConnectionReset(_)
            | error::NetworkError::NotConnected(_) => !gossip_available,
            _ => false,
        }
    }

    fn raw_quic_ack_receive_backpressured(reason: &str) -> bool {
        reason.contains("Remote receive pipeline rejected payload: Backpressured")
    }

    fn map_raw_quic_dm_error(err: error::NetworkError) -> dm::DmError {
        match err {
            error::NetworkError::AgentNotFound(_) => {
                dm::DmError::RecipientKeyUnavailable(err.to_string())
            }
            error::NetworkError::AgentNotConnected(_)
            | error::NetworkError::NotConnected(_)
            | error::NetworkError::ConnectionClosed(_)
            | error::NetworkError::ConnectionReset(_) => dm::DmError::PeerDisconnected {
                reason: err.to_string(),
            },
            error::NetworkError::ConnectionFailed(reason)
                if reason.starts_with("peer disconnected:")
                    || reason.starts_with("send_with_receive_ack failed:") =>
            {
                dm::DmError::PeerDisconnected { reason }
            }
            error::NetworkError::RemoteReceiveBackpressured(reason) => {
                dm::DmError::ReceiverBackpressured { reason }
            }
            error::NetworkError::PayloadTooLarge { size, max } => {
                dm::DmError::PayloadTooLarge { len: size, max }
            }
            error::NetworkError::NodeCreation(reason) => dm::DmError::NoConnectivity(reason),
            other => dm::DmError::PublishFailed(other.to_string()),
        }
    }

    /// Receive the next direct message from any connected agent.
    ///
    /// Blocks until a direct message is received.
    ///
    /// # Security Note
    ///
    /// This method does **not** apply trust filtering from `ContactStore`.
    /// Messages from blocked agents will still be delivered. Use
    /// [`recv_direct_annotated()`](Self::recv_direct_annotated) if you need
    /// trust-based filtering.
    ///
    /// # Returns
    ///
    /// The received [`DirectMessage`] containing sender, payload, and timestamp.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// loop {
    ///     if let Some(msg) = agent.recv_direct().await {
    ///         println!("From {:?}: {:?}", msg.sender, msg.payload_str());
    ///     }
    /// }
    /// ```
    pub async fn recv_direct(&self) -> Option<direct::DirectMessage> {
        self.recv_direct_inner().await
    }

    /// Receive the next direct message, filtering by trust level.
    ///
    /// All messages now carry pre-computed `verified` and `trust_decision`
    /// fields from the identity discovery cache and contact store. This
    /// method passes through all messages — applications should inspect
    /// `msg.trust_decision` and `msg.verified` to decide how to handle
    /// each message.
    ///
    /// # Returns
    ///
    /// The received [`DirectMessage`], or `None` if the channel closes.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// loop {
    ///     if let Some(msg) = agent.recv_direct_annotated().await {
    ///         match msg.trust_decision {
    ///             Some(TrustDecision::RejectBlocked) => continue, // skip
    ///             Some(TrustDecision::Accept) if msg.verified => { /* trusted */ }
    ///             _ => { /* handle accordingly */ }
    ///         }
    ///     }
    /// }
    /// ```
    pub async fn recv_direct_annotated(&self) -> Option<direct::DirectMessage> {
        self.recv_direct_inner().await
    }

    /// Internal helper for receiving direct messages.
    ///
    /// Reads from the `DirectMessaging` internal channel, which is fed by
    /// the background `start_direct_listener` task. This ensures there is
    /// only ONE consumer of `network.recv_direct()` (the listener), avoiding
    /// message-stealing races.
    async fn recv_direct_inner(&self) -> Option<direct::DirectMessage> {
        self.direct_messaging.recv().await
    }

    /// Subscribe to direct messages.
    ///
    /// Returns a receiver that can be cloned for multiple consumers.
    /// Messages are broadcast to all receivers.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let mut rx = agent.subscribe_direct();
    /// tokio::spawn(async move {
    ///     while let Some(msg) = rx.recv().await {
    ///         println!("Direct message: {:?}", msg);
    ///     }
    /// });
    /// ```
    pub fn subscribe_direct(&self) -> direct::DirectMessageReceiver {
        self.direct_messaging.subscribe()
    }

    /// Get the direct messaging infrastructure.
    ///
    /// Provides low-level access to connection tracking and agent mappings.
    pub fn direct_messaging(&self) -> &std::sync::Arc<direct::DirectMessaging> {
        &self.direct_messaging
    }

    /// Check if an agent is currently connected for direct messaging.
    ///
    /// # Arguments
    ///
    /// * `agent_id` - The agent to check.
    ///
    /// # Returns
    ///
    /// `true` if a QUIC connection exists to this agent's machine.
    pub async fn is_agent_connected(&self, agent_id: &identity::AgentId) -> bool {
        let Some(network) = &self.network else {
            return false;
        };

        // Look up machine_id from discovery cache
        let machine_id = {
            let cache = self.identity_discovery_cache.read().await;
            cache.get(agent_id).map(|d| d.machine_id)
        };

        match machine_id {
            Some(mid) => {
                let ant_peer_id = ant_quic::PeerId(mid.0);
                network.is_connected(&ant_peer_id).await
            }
            None => false,
        }
    }

    /// Get list of currently connected agents.
    ///
    /// Returns agents that have been discovered and are currently connected
    /// via QUIC transport.
    pub async fn connected_agents(&self) -> Vec<identity::AgentId> {
        let Some(network) = &self.network else {
            return Vec::new();
        };

        let connected_peers = network.connected_peers().await;
        let cache = self.identity_discovery_cache.read().await;

        // Find agents whose machine_id matches a connected peer
        cache
            .values()
            .filter(|agent| {
                let ant_peer_id = ant_quic::PeerId(agent.machine_id.0);
                connected_peers.contains(&ant_peer_id)
            })
            .map(|agent| agent.agent_id)
            .collect()
    }

    /// Attach a contact store for trust-based message filtering.
    ///
    /// When set, the gossip pub/sub layer will:
    /// - Drop messages from `Blocked` senders (don't deliver, don't rebroadcast)
    /// - Annotate messages with the sender's trust level for consumers
    ///
    /// Without a contact store, all messages pass through (open relay mode).
    pub fn set_contacts(&self, store: std::sync::Arc<tokio::sync::RwLock<contacts::ContactStore>>) {
        if let Some(runtime) = &self.gossip_runtime {
            let pubsub = runtime.pubsub();
            pubsub.set_contacts(store);
            // Thread the authoritative gossiped RevocationSet into pub/sub
            // delivery so a gossiped revocation closes the subscribe path
            // (issue #191 gap 3). Wired here so every runtime that sets
            // contacts also sets revocation — they share the same lifecycle.
            pubsub.set_revocation_set(self.revocation_set());
        }
    }

    /// Announce this agent's identity on the network discovery topic.
    ///
    /// By default, announcements include agent + machine identity only.
    /// Human identity disclosure is opt-in and requires explicit consent.
    ///
    /// # Arguments
    ///
    /// * `include_user_identity` - Whether to include `user_id` and certificate
    /// * `human_consent` - Must be `true` when disclosing user identity
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Gossip runtime is not initialized
    /// - Human identity disclosure is requested without explicit consent
    /// - Human identity disclosure is requested but no user identity is configured
    /// - Serialization or publish fails
    pub async fn announce_identity(
        &self,
        include_user_identity: bool,
        human_consent: bool,
    ) -> error::Result<()> {
        let runtime = self.gossip_runtime.as_ref().ok_or_else(|| {
            error::IdentityError::Storage(std::io::Error::other(
                "gossip runtime not initialized - configure agent with network first",
            ))
        })?;

        self.start_identity_listener().await?;

        let network_status = if let Some(network) = self.network.as_ref() {
            network.node_status().await
        } else {
            None
        };
        let assist_snapshot = network_status
            .as_ref()
            .map(AnnouncementAssistSnapshot::from_node_status)
            .unwrap_or_default();

        // Include ALL routable addresses (IPv4 and IPv6).
        let mut addresses = if let Some(network) = self.network.as_ref() {
            match network_status.as_ref() {
                Some(status) if !status.external_addrs.is_empty() => status.external_addrs.clone(),
                _ => match network.routable_addr().await {
                    Some(addr) => vec![addr],
                    None => self.announcement_addresses(),
                },
            }
        } else {
            self.announcement_addresses()
        };
        // Detect addresses locally via UDP socket tricks.
        // ant-quic discovers public IPv4 via OBSERVED_ADDRESS from peers.
        // IPv6 is globally routable (no NAT), so we probe locally.
        //
        // For locally-probed addresses (IPv6 and LAN IPv4), use the actual
        // bound port from the QUIC endpoint — NOT the first external address
        // port (which is NAT-mapped) and NOT the config bind port (which may
        // be 0 for OS-assigned ports).
        let bind_port = if let Some(network) = self.network.as_ref() {
            network.bound_addr().await.map(|a| a.port()).unwrap_or(5483)
        } else {
            5483
        };

        // IPv6 probe
        if let Ok(sock) = std::net::UdpSocket::bind("[::]:0") {
            if sock.connect("[2001:4860:4860::8888]:80").is_ok() {
                if let Ok(local) = sock.local_addr() {
                    if let std::net::IpAddr::V6(v6) = local.ip() {
                        let segs = v6.segments();
                        let is_global = (segs[0] & 0xffc0) != 0xfe80
                            && (segs[0] & 0xff00) != 0xfd00
                            && !v6.is_loopback();
                        if is_global {
                            let v6_addr =
                                std::net::SocketAddr::new(std::net::IpAddr::V6(v6), bind_port);
                            if !addresses.contains(&v6_addr) {
                                addresses.push(v6_addr);
                            }
                        }
                    }
                }
            }
        }

        for addr in collect_local_interface_addrs(bind_port) {
            if !addresses.contains(&addr) {
                addresses.push(addr);
            }
        }

        let allow_local_scope = self
            .network
            .as_ref()
            .is_some_and(|network| allow_local_discovery_addresses(network.config()));
        // Same rule as HeartbeatContext::announce(): global bootstrap partitions
        // publish only globally-routable endpoints, while explicit local/testnet
        // partitions may publish LAN/loopback hints for same-partition peers.
        addresses = filter_discovery_announcement_addrs(addresses, allow_local_scope);

        // Emit coordinator / relay hints only when direct inbound is not
        // known to work. See HeartbeatContext::announce() for rationale.
        let (reachable_via, relay_candidates) = if assist_snapshot.can_receive_direct == Some(true)
        {
            (Vec::new(), Vec::new())
        } else if let Some(network) = self.network.as_ref() {
            collect_coordinator_hints(
                network.as_ref(),
                &self.machine_discovery_cache,
                self.machine_id(),
            )
            .await
        } else {
            (Vec::new(), Vec::new())
        };

        let announcement =
            self.build_identity_announcement_with_addrs(IdentityAnnouncementBuildOptions {
                include_user_identity,
                human_consent,
                addresses,
                assist_snapshot: Some(&assist_snapshot),
                reachable_via,
                relay_candidates,
                allow_local_scope,
            })?;
        tracing::debug!(
            target: "x0x::discovery",
            announcement_kind = "explicit",
            machine_prefix = %network::hex_prefix(&announcement.machine_id.0, 4),
            addr_total = announcement.addresses.len(),
            nat_type = announcement.nat_type.as_deref().unwrap_or("unknown"),
            can_receive_direct = ?announcement.can_receive_direct,
            relay_capable = ?announcement.is_relay,
            coordinator_capable = ?announcement.is_coordinator,
            relay_active = ?assist_snapshot.relay_active,
            coordinator_active = ?assist_snapshot.coordinator_active,
            "publishing identity announcement"
        );

        let machine_announcement = build_machine_announcement_for_identity(
            &self.identity,
            announcement.addresses.clone(),
            announcement.announced_at,
            Some(&assist_snapshot),
            announcement.reachable_via.clone(),
            announcement.relay_candidates.clone(),
            allow_local_scope,
        )?;
        tracing::debug!(
            target: "x0x::discovery",
            announcement_kind = "machine_explicit",
            machine_prefix = %network::hex_prefix(&machine_announcement.machine_id.0, 4),
            addr_total = machine_announcement.addresses.len(),
            nat_type = machine_announcement.nat_type.as_deref().unwrap_or("unknown"),
            can_receive_direct = ?machine_announcement.can_receive_direct,
            relay_capable = ?machine_announcement.is_relay,
            coordinator_capable = ?machine_announcement.is_coordinator,
            reachable_via_count = machine_announcement.reachable_via.len(),
            relay_candidate_count = machine_announcement.relay_candidates.len(),
            "publishing machine announcement"
        );
        let machine_payload =
            bytes::Bytes::from(bincode::serialize(&machine_announcement).map_err(|e| {
                error::IdentityError::Serialization(format!(
                    "failed to serialize machine announcement: {e}"
                ))
            })?);
        runtime
            .pubsub()
            .publish(
                shard_topic_for_machine(&machine_announcement.machine_id),
                machine_payload.clone(),
            )
            .await
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "failed to publish machine announcement to shard topic: {e}"
                )))
            })?;
        runtime
            .pubsub()
            .publish(MACHINE_ANNOUNCE_TOPIC.to_string(), machine_payload)
            .await
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "failed to publish machine announcement: {e}"
                )))
            })?;

        let encoded = serialize_identity_announcement(&announcement).map_err(|e| {
            error::IdentityError::Serialization(format!(
                "failed to serialize identity announcement: {e}"
            ))
        })?;

        let payload = bytes::Bytes::from(encoded);

        // Publish to shard topic first (future-proof routing).
        let shard_topic = shard_topic_for_agent(&announcement.agent_id);
        runtime
            .pubsub()
            .publish(shard_topic, payload.clone())
            .await
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "failed to publish identity announcement to shard topic: {e}"
                )))
            })?;

        // Also publish to legacy broadcast topic for backward compatibility.
        runtime
            .pubsub()
            .publish(IDENTITY_ANNOUNCE_TOPIC.to_string(), payload)
            .await
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "failed to publish identity announcement: {e}"
                )))
            })?;

        let now = Self::unix_timestamp_secs();
        upsert_discovered_machine(
            &self.machine_discovery_cache,
            DiscoveredMachine::from_machine_announcement(
                &machine_announcement,
                machine_announcement.addresses.clone(),
                now,
            ),
        )
        .await;
        let discovered_agent = DiscoveredAgent {
            agent_id: announcement.agent_id,
            machine_id: announcement.machine_id,
            user_id: announcement.user_id,
            addresses: announcement.addresses.clone(),
            announced_at: announcement.announced_at,
            last_seen: now,
            machine_public_key: announcement.machine_public_key.clone(),
            nat_type: announcement.nat_type.clone(),
            can_receive_direct: announcement.can_receive_direct,
            is_relay: announcement.is_relay,
            is_coordinator: announcement.is_coordinator,
            reachable_via: announcement.reachable_via.clone(),
            relay_candidates: announcement.relay_candidates.clone(),
            cert_not_after: None,
            agent_certificate: None,
            agent_public_key: announcement.agent_public_key.clone(),
        };
        upsert_discovered_machine_from_agent(&self.machine_discovery_cache, &discovered_agent)
            .await;
        upsert_discovered_agent(&self.identity_discovery_cache, discovered_agent).await;

        // Record consent AFTER successful publish so heartbeats don't start
        // including user identity if this announcement never actually propagated.
        if include_user_identity && human_consent {
            self.user_identity_consented
                .store(true, std::sync::atomic::Ordering::Release);
        }

        Ok(())
    }

    /// Get all discovered agents from identity announcements.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn discovered_agents(&self) -> error::Result<Vec<DiscoveredAgent>> {
        self.start_identity_listener().await?;
        let cutoff = Self::unix_timestamp_secs().saturating_sub(self.identity_ttl_secs);
        let mut agents: Vec<_> = self
            .identity_discovery_cache
            .read()
            .await
            .values()
            .filter(|a| discovery_record_is_live(a.announced_at, a.last_seen, cutoff))
            .cloned()
            .collect();
        agents.sort_by_key(|a| a.agent_id.0);
        Ok(agents)
    }

    /// Get all currently-online agents from live presence beacons.
    ///
    /// This is the backing view for `/presence/online`: signed identity
    /// announcements provide the AgentId/MachineId binding, while presence
    /// beacons provide short-TTL liveness. Fresh identity-cache entries are
    /// included as a startup fallback before the first beacon poll converges.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn online_agents(&self) -> error::Result<Vec<DiscoveredAgent>> {
        self.start_identity_listener().await?;
        let cutoff = Self::unix_timestamp_secs().saturating_sub(self.identity_ttl_secs);
        let cache = self.identity_discovery_cache.read().await;
        let mut seen = std::collections::HashSet::new();
        let mut agents = Vec::new();

        for agent in cache
            .values()
            .filter(|agent| discovery_record_is_live(agent.announced_at, agent.last_seen, cutoff))
        {
            if seen.insert(agent.agent_id) {
                agents.push(agent.clone());
            }
        }

        if let Some(ref pw) = self.presence {
            let records = pw
                .manager()
                .get_group_presence(crate::presence::global_presence_topic())
                .await;
            for (peer_id, record) in records {
                if let Some(agent) =
                    crate::presence::presence_record_to_discovered_agent(peer_id, &record, &cache)
                {
                    if seen.insert(agent.agent_id) {
                        agents.push(agent);
                    }
                }
            }
        }

        agents.sort_by_key(|a| a.agent_id.0);
        Ok(agents)
    }

    /// Return all currently retained discovered agents, regardless of TTL.
    ///
    /// Unlike [`Self::discovered_agents`], this method skips read-time TTL
    /// filtering. After [`Self::join_network`] starts the background discovery
    /// cache reaper, stale entries may still be physically removed, so this is
    /// a retained-cache view rather than an "all agents ever seen" archive.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn discovered_agents_unfiltered(&self) -> error::Result<Vec<DiscoveredAgent>> {
        self.start_identity_listener().await?;
        let mut agents: Vec<_> = self
            .identity_discovery_cache
            .read()
            .await
            .values()
            .cloned()
            .collect();
        agents.sort_by_key(|a| a.agent_id.0);
        Ok(agents)
    }

    /// Get one discovered agent record by agent ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn discovered_agent(
        &self,
        agent_id: identity::AgentId,
    ) -> error::Result<Option<DiscoveredAgent>> {
        self.start_identity_listener().await?;
        Ok(self
            .identity_discovery_cache
            .read()
            .await
            .get(&agent_id)
            .cloned())
    }

    /// Get all discovered machine endpoints from machine announcements.
    ///
    /// The returned records are keyed by `machine_id`, which is the actual
    /// transport identity used for direct dials, hole-punching, and relay
    /// selection. Agent and user identities are link indexes over these
    /// machine records.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn discovered_machines(&self) -> error::Result<Vec<DiscoveredMachine>> {
        self.start_identity_listener().await?;
        let cutoff = Self::unix_timestamp_secs().saturating_sub(self.identity_ttl_secs);
        let mut machines: Vec<_> = self
            .machine_discovery_cache
            .read()
            .await
            .values()
            .filter(|m| discovery_record_is_live(m.announced_at, m.last_seen, cutoff))
            .cloned()
            .collect();
        machines.sort_by_key(|m| m.machine_id.0);
        Ok(machines)
    }

    /// Return all currently retained discovered machines, regardless of TTL.
    ///
    /// Unlike [`Self::discovered_machines`], this method skips read-time TTL
    /// filtering. After [`Self::join_network`] starts the background discovery
    /// cache reaper, stale entries may still be physically removed, so this is
    /// a retained-cache view rather than an "all machines ever seen" archive.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn discovered_machines_unfiltered(&self) -> error::Result<Vec<DiscoveredMachine>> {
        self.start_identity_listener().await?;
        let mut machines: Vec<_> = self
            .machine_discovery_cache
            .read()
            .await
            .values()
            .cloned()
            .collect();
        machines.sort_by_key(|m| m.machine_id.0);
        Ok(machines)
    }

    /// Get one discovered machine record by machine ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn discovered_machine(
        &self,
        machine_id: identity::MachineId,
    ) -> error::Result<Option<DiscoveredMachine>> {
        self.start_identity_listener().await?;
        Ok(self
            .machine_discovery_cache
            .read()
            .await
            .get(&machine_id)
            .cloned())
    }

    /// Resolve a known agent identity to its current machine endpoint.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn machine_for_agent(
        &self,
        agent_id: identity::AgentId,
    ) -> error::Result<Option<DiscoveredMachine>> {
        self.start_identity_listener().await?;
        let machine_id = {
            let agents = self.identity_discovery_cache.read().await;
            agents.get(&agent_id).map(|agent| agent.machine_id)
        };
        let Some(machine_id) = machine_id else {
            return Ok(None);
        };
        Ok(self
            .machine_discovery_cache
            .read()
            .await
            .get(&machine_id)
            .cloned())
    }

    /// Find all machine endpoints linked to a consented user identity.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn find_machines_by_user(
        &self,
        user_id: identity::UserId,
    ) -> error::Result<Vec<DiscoveredMachine>> {
        self.start_identity_listener().await?;
        let cutoff = Self::unix_timestamp_secs().saturating_sub(self.identity_ttl_secs);
        let mut machines: Vec<_> = self
            .machine_discovery_cache
            .read()
            .await
            .values()
            .filter(|m| {
                discovery_record_is_live(m.announced_at, m.last_seen, cutoff)
                    && m.user_ids.contains(&user_id)
            })
            .cloned()
            .collect();
        machines.sort_by_key(|m| m.machine_id.0);
        Ok(machines)
    }

    /// Publish a signed [`UserAnnouncement`] for this agent's user identity.
    ///
    /// Builds the roster from the agent certificates the user has issued for
    /// every agent visible through this `Agent` — at minimum, this agent's
    /// own certificate. Requires explicit human consent to avoid an unwary
    /// caller broadcasting user identity.
    ///
    /// # Errors
    ///
    /// Returns an error if no user keypair is configured, `human_consent` is
    /// false, no agent certificate is available, signing fails, or the
    /// gossip runtime is not initialised.
    pub async fn announce_user_identity(&self, human_consent: bool) -> error::Result<()> {
        if !human_consent {
            return Err(error::IdentityError::Storage(std::io::Error::other(
                "user announcement requires explicit human consent — set human_consent: true",
            )));
        }
        let user_kp = self.identity.user_keypair().ok_or_else(|| {
            error::IdentityError::Storage(std::io::Error::other(
                "user announcement requested but no user identity is configured",
            ))
        })?;
        let own_cert = self.identity.agent_certificate().cloned().ok_or_else(|| {
            error::IdentityError::Storage(std::io::Error::other(
                "user announcement requested but agent certificate is missing",
            ))
        })?;
        let runtime = self.gossip_runtime.as_ref().ok_or_else(|| {
            error::IdentityError::Storage(std::io::Error::other(
                "gossip runtime not initialized - configure agent with network first",
            ))
        })?;
        self.start_identity_listener().await?;

        let announced_at = Self::unix_timestamp_secs();
        let announcement = UserAnnouncement::sign(user_kp, vec![own_cert], announced_at)?;
        let payload = bytes::Bytes::from(bincode::serialize(&announcement).map_err(|e| {
            error::IdentityError::Serialization(format!(
                "failed to serialize user announcement: {e}"
            ))
        })?);
        runtime
            .pubsub()
            .publish(shard_topic_for_user(&announcement.user_id), payload.clone())
            .await
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "failed to publish user announcement to shard topic: {e}"
                )))
            })?;
        runtime
            .pubsub()
            .publish(USER_ANNOUNCE_TOPIC.to_string(), payload)
            .await
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "failed to publish user announcement: {e}"
                )))
            })?;

        let now = Self::unix_timestamp_secs();
        let incoming = DiscoveredUser::from_announcement(&announcement, now);
        self.user_discovery_cache
            .write()
            .await
            .insert(incoming.user_id, incoming);
        Ok(())
    }

    /// Get a discovered user by ID.
    ///
    /// Returns `Ok(None)` if the user has never announced or the cached
    /// entry is older than `identity_ttl_secs`.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn discovered_user(
        &self,
        user_id: identity::UserId,
    ) -> error::Result<Option<DiscoveredUser>> {
        self.start_identity_listener().await?;
        let cutoff = Self::unix_timestamp_secs().saturating_sub(self.identity_ttl_secs);
        Ok(self
            .user_discovery_cache
            .read()
            .await
            .get(&user_id)
            .filter(|u| discovery_record_is_live(u.announced_at, u.last_seen, cutoff))
            .cloned())
    }

    /// List all currently-discovered users (those with a fresh announcement).
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn discovered_users(&self) -> error::Result<Vec<DiscoveredUser>> {
        self.start_identity_listener().await?;
        let cutoff = Self::unix_timestamp_secs().saturating_sub(self.identity_ttl_secs);
        let mut users: Vec<_> = self
            .user_discovery_cache
            .read()
            .await
            .values()
            .filter(|u| discovery_record_is_live(u.announced_at, u.last_seen, cutoff))
            .cloned()
            .collect();
        users.sort_by_key(|u| u.user_id.0);
        Ok(users)
    }

    /// Return the current retained entry counts for the three discovery caches.
    ///
    /// Primarily intended for diagnostics and soak monitoring. The reaper
    /// (started by `join_network`) keeps these bounded by physically removing
    /// stale entries; without the reaper the counts grow monotonically with
    /// every unique agent/machine/user ever observed.
    #[must_use]
    pub async fn discovery_cache_entry_counts(&self) -> (usize, usize, usize) {
        let id = self.identity_discovery_cache.read().await.len();
        let mach = self.machine_discovery_cache.read().await.len();
        let usr = self.user_discovery_cache.read().await.len();
        (id, mach, usr)
    }

    async fn start_identity_listener(&self) -> error::Result<()> {
        let runtime = self.gossip_runtime.as_ref().ok_or_else(|| {
            error::IdentityError::Storage(std::io::Error::other(
                "gossip runtime not initialized - configure agent with network first",
            ))
        })?;

        if self
            .identity_listener_started
            .swap(true, std::sync::atomic::Ordering::AcqRel)
        {
            return Ok(());
        }

        let mut sub_legacy = runtime
            .pubsub()
            .subscribe(IDENTITY_ANNOUNCE_TOPIC.to_string())
            .await;
        let own_shard_topic = shard_topic_for_agent(&self.agent_id());
        let mut sub_shard = runtime.pubsub().subscribe(own_shard_topic).await;
        let mut sub_machine_legacy = runtime
            .pubsub()
            .subscribe(MACHINE_ANNOUNCE_TOPIC.to_string())
            .await;
        let own_machine_shard_topic = shard_topic_for_machine(&self.machine_id());
        let mut sub_machine_shard = runtime.pubsub().subscribe(own_machine_shard_topic).await;
        let mut sub_user_legacy = runtime
            .pubsub()
            .subscribe(USER_ANNOUNCE_TOPIC.to_string())
            .await;
        // Subscribe to our own user's shard (if we have a user identity) so
        // we receive announcements addressed to us as well as broadcasts.
        let mut sub_user_shard = match self.user_id() {
            Some(uid) => Some(runtime.pubsub().subscribe(shard_topic_for_user(&uid)).await),
            None => None,
        };
        let cache = std::sync::Arc::clone(&self.identity_discovery_cache);
        let authenticated_machine_bindings =
            std::sync::Arc::clone(&self.authenticated_machine_bindings);
        let machine_cache = std::sync::Arc::clone(&self.machine_discovery_cache);
        let user_cache = std::sync::Arc::clone(&self.user_discovery_cache);
        let bootstrap_cache = self.bootstrap_cache.clone();
        let contact_store = std::sync::Arc::clone(&self.contact_store);
        let direct_messaging = std::sync::Arc::clone(&self.direct_messaging);
        let network = self.network.as_ref().map(std::sync::Arc::clone);
        let allow_local_scope = network
            .as_ref()
            .is_some_and(|network| allow_local_discovery_addresses(network.config()));
        let own_agent_id = self.agent_id();
        let own_machine_id = self.machine_id();
        let own_user_id = self.user_id();
        let rebroadcast_pubsub = std::sync::Arc::clone(runtime.pubsub());
        let token = self.shutdown_token.clone();
        // Subscribe to revocation records so they are applied on receipt.
        let mut sub_revocation = runtime
            .pubsub()
            .subscribe(REVOCATION_TOPIC.to_string())
            .await;
        let revocation_set = std::sync::Arc::clone(&self.revocation_set);
        let identity_dir_for_listener = self.identity_dir.clone();
        let contact_store_for_evict = std::sync::Arc::clone(&self.contact_store);

        self.spawn_tracked(async move {
            enum DiscoveryMessage {
                Identity(crate::gossip::PubSubMessage),
                Machine(crate::gossip::PubSubMessage),
                User(crate::gossip::PubSubMessage),
                Revocation(crate::gossip::PubSubMessage),
            }

            // Track when we last initiated an auto-connect dial per agent.
            // Prevents duplicate attempts from concurrent announcements AND
            // rate-limits redials to an announcing-but-unreachable peer: every
            // failed dial accumulates ant-quic NAT-traversal/connection state,
            // so dialing on each received announcement copy leaks memory
            // without bound (see ANNOUNCEMENT_AUTO_CONNECT_RETRY_COOLDOWN).
            let mut auto_connect_attempts =
                std::collections::HashMap::<identity::AgentId, std::time::Instant>::new();

            // One-shot dedup for re-broadcast: (agent_id, announced_at)
            // → first-rebroadcast Instant. Bounds each fresh announcement to at
            // most one receiver-side re-publish per daemon. Repeating the same
            // payload every few seconds forms a PubSub feedback loop on the
            // bootstrap mesh and delays latency-sensitive user messages.
            let mut rebroadcast_state: std::collections::HashMap<
                (identity::AgentId, u64),
                std::time::Instant,
            > = std::collections::HashMap::new();
            let mut machine_rebroadcast_state: std::collections::HashMap<
                (identity::MachineId, u64),
                std::time::Instant,
            > = std::collections::HashMap::new();
            let mut seen_identity_payloads: std::collections::HashMap<
                blake3::Hash,
                std::time::Instant,
            > = std::collections::HashMap::new();
            let mut seen_machine_payloads: std::collections::HashMap<
                blake3::Hash,
                std::time::Instant,
            > = std::collections::HashMap::new();
            let mut user_rebroadcast_state: std::collections::HashMap<
                (identity::UserId, u64),
                std::time::Instant,
            > = std::collections::HashMap::new();
            const VERIFIED_PAYLOAD_TTL: std::time::Duration = std::time::Duration::from_secs(60);

            let has_recent_verified_payload =
                |seen: &std::collections::HashMap<blake3::Hash, std::time::Instant>,
                 payload: &[u8]| {
                    let key = blake3::hash(payload);
                    matches!(seen.get(&key), Some(last) if last.elapsed() < VERIFIED_PAYLOAD_TTL)
                };
            let remember_verified_payload =
                |seen: &mut std::collections::HashMap<blake3::Hash, std::time::Instant>,
                 payload: &[u8]| {
                    let now = std::time::Instant::now();
                    seen.insert(blake3::hash(payload), now);
                    if seen.len() > 4096 {
                        let cutoff = now - VERIFIED_PAYLOAD_TTL;
                        seen.retain(|_, t| *t >= cutoff);
                    }
                };

            loop {
                // Drain whichever subscription fires next; deduplicate by ID in cache.
                // The user-shard subscription is conditional on having a local
                // user identity; when absent, that arm yields a pending future
                // so select! skips it cleanly.
                let msg = tokio::select! {
                    Some(m) = sub_legacy.recv() => DiscoveryMessage::Identity(m),
                    Some(m) = sub_shard.recv() => DiscoveryMessage::Identity(m),
                    Some(m) = sub_machine_legacy.recv() => DiscoveryMessage::Machine(m),
                    Some(m) = sub_machine_shard.recv() => DiscoveryMessage::Machine(m),
                    Some(m) = sub_user_legacy.recv() => DiscoveryMessage::User(m),
                    Some(m) = async {
                        match sub_user_shard.as_mut() {
                            Some(s) => s.recv().await,
                            None => std::future::pending().await,
                        }
                    } => DiscoveryMessage::User(m),
                    Some(m) = sub_revocation.recv() => DiscoveryMessage::Revocation(m),
                    // Required for PROMPT shutdown: without this arm the listener
                    // only exits when every gossip subscription closes (the
                    // `else => break` path), forcing shutdown() to wait out its
                    // 3s grace-then-abort window. Cancelling the token here lets
                    // it break immediately. Adding this always-eligible-on-cancel
                    // branch only shifts tokio::select!'s pseudo-random tie-break
                    // distribution among the recv arms — behaviorally inert here
                    // because each per-topic message is handled independently
                    // with no cross-topic ordering guarantee.
                    _ = token.cancelled() => break,
                    else => break,
                };
                let msg = match msg {
                    DiscoveryMessage::Machine(msg) => {
                        let raw_payload = msg.payload.clone();
                        let already_verified =
                            has_recent_verified_payload(&seen_machine_payloads, &raw_payload);
                        let announcement = match deserialize_machine_announcement(&raw_payload) {
                            Ok(a) => a,
                            Err(e) => {
                                tracing::debug!(
                                    "Ignoring invalid machine announcement payload: {}",
                                    e
                                );
                                continue;
                            }
                        };

                        if !already_verified {
                            if let Err(e) = announcement.verify() {
                                tracing::warn!("Ignoring unverifiable machine announcement: {}", e);
                                continue;
                            }
                            remember_verified_payload(&mut seen_machine_payloads, &raw_payload);
                        }

                        let now = std::time::SystemTime::now()
                            .duration_since(std::time::UNIX_EPOCH)
                            .map_or(0, |d| d.as_secs());

                        let bootstrap_addresses = filter_publicly_advertisable_addrs(
                            announcement.addresses.iter().copied(),
                        );
                        if !bootstrap_addresses.is_empty() {
                            if let Some(ref bc) = &bootstrap_cache {
                                let peer_id = ant_quic::PeerId(announcement.machine_id.0);
                                bc.add_from_connection(peer_id, bootstrap_addresses.clone(), None)
                                    .await;
                            }
                        }

                        let discovery_addresses = filter_discovery_announcement_addrs(
                            announcement.addresses.iter().copied(),
                            allow_local_scope,
                        );
                        let filtered_addr_count = discovery_addresses.len();
                        upsert_discovered_machine(
                            &machine_cache,
                            DiscoveredMachine::from_machine_announcement(
                                &announcement,
                                discovery_addresses,
                                now,
                            ),
                        )
                        .await;
                        tracing::debug!(
                            target: "x0x::discovery",
                            announcement_kind = "machine_received",
                            machine_prefix = %network::hex_prefix(&announcement.machine_id.0, 4),
                            addr_total = announcement.addresses.len(),
                            filtered_addr_count,
                            nat_type = announcement.nat_type.as_deref().unwrap_or("unknown"),
                            can_receive_direct = ?announcement.can_receive_direct,
                            relay_capable = ?announcement.is_relay,
                            coordinator_capable = ?announcement.is_coordinator,
                            "cached verified machine announcement"
                        );

                        if announcement.machine_id != own_machine_id {
                            let key = (announcement.machine_id, announcement.announced_at);
                            if should_rebroadcast_discovery_once(
                                &mut machine_rebroadcast_state,
                                key,
                                std::time::Instant::now(),
                            ) {
                                let pubsub = std::sync::Arc::clone(&rebroadcast_pubsub);
                                tokio::spawn(async move {
                                    if let Err(e) = pubsub
                                        .publish(MACHINE_ANNOUNCE_TOPIC.to_string(), raw_payload)
                                        .await
                                    {
                                        tracing::debug!(
                                            "machine announcement re-broadcast failed: {e}"
                                        );
                                    }
                                });
                            }
                        }
                        continue;
                    }
                    DiscoveryMessage::User(msg) => {
                        let raw_payload = msg.payload.clone();
                        let announcement = match deserialize_user_announcement(&raw_payload) {
                            Ok(a) => a,
                            Err(e) => {
                                tracing::debug!(
                                    "Ignoring invalid user announcement payload: {}",
                                    e
                                );
                                continue;
                            }
                        };
                        if let Err(e) = announcement.verify() {
                            tracing::warn!("Ignoring unverifiable user announcement: {}", e);
                            continue;
                        }
                        let now = std::time::SystemTime::now()
                            .duration_since(std::time::UNIX_EPOCH)
                            .map_or(0, |d| d.as_secs());
                        let incoming = DiscoveredUser::from_announcement(&announcement, now);
                        {
                            let mut cache = user_cache.write().await;
                            match cache.get_mut(&incoming.user_id) {
                                Some(existing) if incoming.announced_at < existing.announced_at => {
                                    // Ignore stale announcement.
                                }
                                Some(existing) => {
                                    existing.user_public_key = incoming.user_public_key;
                                    existing.agent_certificates = incoming.agent_certificates;
                                    existing.agent_ids = incoming.agent_ids;
                                    existing.announced_at = incoming.announced_at;
                                    existing.last_seen = now;
                                }
                                None => {
                                    cache.insert(incoming.user_id, incoming);
                                }
                            }
                        }
                        tracing::debug!(
                            target: "x0x::discovery",
                            announcement_kind = "user_received",
                            user_prefix = %network::hex_prefix(&announcement.user_id.0, 4),
                            agent_count = announcement.agent_certificates.len(),
                            "cached verified user announcement"
                        );
                        // Rebroadcast non-self announcements once, matching
                        // identity / machine announcements.
                        if Some(announcement.user_id) != own_user_id {
                            let key = (announcement.user_id, announcement.announced_at);
                            if should_rebroadcast_discovery_once(
                                &mut user_rebroadcast_state,
                                key,
                                std::time::Instant::now(),
                            ) {
                                let pubsub = std::sync::Arc::clone(&rebroadcast_pubsub);
                                tokio::spawn(async move {
                                    if let Err(e) = pubsub
                                        .publish(USER_ANNOUNCE_TOPIC.to_string(), raw_payload)
                                        .await
                                    {
                                        tracing::debug!(
                                            "user announcement re-broadcast failed: {e}"
                                        );
                                    }
                                });
                            }
                        }
                        continue;
                    }
                    DiscoveryMessage::Identity(msg) => msg,
                    DiscoveryMessage::Revocation(msg) => {
                        // Size-limit: max 2 MiB for a revocation batch (records
                        // are ~5.3 KB each; 2 MiB ≈ 380 records, far beyond
                        // any realistic fleet size in v1).
                        const MAX_REVOCATION_PAYLOAD_BYTES: usize = 2 * 1024 * 1024;
                        if msg.payload.len() > MAX_REVOCATION_PAYLOAD_BYTES {
                            tracing::debug!(
                                "ignoring oversized revocation payload ({} bytes)",
                                msg.payload.len()
                            );
                            continue;
                        }
                        let records: Vec<revocation::RevocationRecord> =
                            match bincode::deserialize(&msg.payload) {
                                Ok(r) => r,
                                Err(e) => {
                                    tracing::debug!("ignoring invalid revocation payload: {e}");
                                    continue;
                                }
                            };
                        let mut newly_inserted = Vec::new();
                        // Resolve subject certificates from the discovery cache
                        // so gossiped issuer-revocations (a user un-vouching a
                        // certified agent) can be authority-verified on receipt
                        // (issue #191). `verify_authority` for an issuer-
                        // revocation requires the subject cert; self/machine
                        // revocations need none. A cert not in the local cache
                        // means the issuer-revocation is rejected fail-closed
                        // — the cert must have been announced first (EP1).
                        // Built before taking the revocation-set write lock so
                        // no two identity locks are held at once.
                        let subject_certs = collect_subject_certs(&*cache.read().await);
                        {
                            let mut set = revocation_set.write().await;
                            for record in records {
                                if set.contains_hash(&record.record_hash()) {
                                    continue; // already known — skip re-verification
                                }
                                let subject_cert = match &record.subject {
                                    revocation::RevokedSubject::Agent(agent_id) => {
                                        subject_certs.get(agent_id)
                                    }
                                    _ => None,
                                };
                                match set.verify_and_insert(record.clone(), subject_cert) {
                                    Ok(true) => newly_inserted.push(record),
                                    Ok(false) => {} // dup
                                    Err(e) => {
                                        tracing::debug!(
                                            "revocation record rejected: {e}"
                                        );
                                    }
                                }
                            }
                        }
                        if !newly_inserted.is_empty() {
                            // Persist asynchronously — best-effort; if it fails
                            // the revocation is still enforced in memory for this
                            // run. Snapshot the live set's encoded bytes under a
                            // brief read lock (issuer-revocations carry their
                            // authorizing cert in PersistedRevocation, which the
                            // encoder preserves); the disk write runs off-lock.
                            // The previous rebuild re-inserted records with
                            // `None` cert, silently dropping every issuer-
                            // revocation on save (issue #191).
                            let persisted_bytes = revocation_set.read().await.to_bytes();
                            let id_dir = identity_dir_for_listener.clone();
                            tokio::spawn(async move {
                                match persisted_bytes {
                                    Ok(bytes) => {
                                        if let Err(e) = storage::save_revocation_set_bytes(
                                            bytes,
                                            id_dir.as_deref(),
                                        )
                                        .await
                                        {
                                            tracing::warn!(
                                                "failed to persist revocation set: {e}"
                                            );
                                        }
                                    }
                                    Err(e) => tracing::warn!(
                                        "failed to encode revocation set for persistence: {e}"
                                    ),
                                }
                            });
                            // Evict revoked subjects from discovery caches.
                            for record in newly_inserted {
                                match &record.subject {
                                    revocation::RevokedSubject::Agent(agent_id) => {
                                        if let Some(entry) = cache.write().await.remove(agent_id) {
                                            machine_cache.write().await.remove(&entry.machine_id);
                                        }
                                        let mut cs = contact_store_for_evict.write().await;
                                        cs.set_trust(agent_id, contacts::TrustLevel::Blocked);
                                        tracing::info!(
                                            agent = %hex::encode(agent_id.as_bytes()),
                                            "evicted revoked agent (received via gossip)"
                                        );
                                    }
                                    revocation::RevokedSubject::Machine(machine_id) => {
                                        machine_cache.write().await.remove(machine_id);
                                        cache.write().await.retain(|_, a| a.machine_id != *machine_id);
                                        tracing::info!(
                                            machine = %hex::encode(machine_id.as_bytes()),
                                            "evicted revoked machine (received via gossip)"
                                        );
                                    }
                                }
                            }
                        }
                        continue;
                    }
                };
                let raw_payload = msg.payload.clone();
                let already_verified =
                    has_recent_verified_payload(&seen_identity_payloads, &raw_payload);
                let announcement = match deserialize_identity_announcement(&raw_payload) {
                    Ok(a) => a,
                    Err(e) => {
                        tracing::debug!("Ignoring invalid identity announcement payload: {}", e);
                        continue;
                    }
                };

                if !already_verified {
                    if let Err(e) = announcement.verify() {
                        tracing::warn!("Ignoring unverifiable identity announcement: {}", e);
                        continue;
                    }
                    remember_verified_payload(&mut seen_identity_payloads, &raw_payload);
                }

                let now = Agent::unix_timestamp_secs();
                if !identity_announcement_timestamp_is_acceptable(announcement.announced_at, now) {
                    tracing::warn!(
                        agent = %hex::encode(announcement.agent_id.as_bytes()),
                        announced_at = announcement.announced_at,
                        now,
                        max_future_skew_secs = IDENTITY_ANNOUNCEMENT_CLOCK_SKEW_SECS,
                        "ignoring far-future identity announcement"
                    );
                    continue;
                }

                // Evaluate trust for this (agent, machine) pair.
                // Blocked or machine-pinning violations are silently dropped.
                {
                    let store = contact_store.read().await;
                    let evaluator = trust::TrustEvaluator::new(&store);
                    let decision = evaluator.evaluate(&trust::TrustContext {
                        agent_id: &announcement.agent_id,
                        machine_id: &announcement.machine_id,
                    });
                    match decision {
                        trust::TrustDecision::RejectBlocked => {
                            tracing::debug!(
                                "Dropping identity announcement from blocked agent {:?}",
                                hex::encode(&announcement.agent_id.0[..8]),
                            );
                            continue;
                        }
                        trust::TrustDecision::RejectMachineMismatch => {
                            tracing::warn!(
                                "Dropping identity announcement from agent {}: machine {} not in pinned list",
                                crate::logging::LogAgentId::from(&announcement.agent_id),
                                crate::logging::LogMachineId::from(&announcement.machine_id),
                            );
                            continue;
                        }
                        _ => {}
                    }
                }

                // Enforcement point 1 — revocation gate.
                // Fail-closed: a revoked agent or machine is silently dropped
                // even if the trust store says otherwise.  This check must come
                // BEFORE inserting into the discovery cache so a revoked peer
                // never gets a `verified` annotation.
                {
                    let revoked = revocation_set.read().await;
                    if revoked.is_agent_revoked(&announcement.agent_id) {
                        tracing::debug!(
                            "Dropping identity announcement from revoked agent {:?}",
                            hex::encode(&announcement.agent_id.0[..8]),
                        );
                        continue;
                    }
                    if revoked.is_machine_revoked(&announcement.machine_id) {
                        tracing::debug!(
                            "Dropping identity announcement from revoked machine {:?}",
                            hex::encode(&announcement.machine_id.0[..8]),
                        );
                        continue;
                    }
                }

                // Enforcement point 1b — cert expiry gate.
                // Drop announcements whose embedded cert is expired (fail-closed).
                // Announcements without a cert (cert == None) are fail-open:
                // they just won't carry a user binding and cert_not_after will be None.
                if let Some(cert) = &announcement.agent_certificate {
                    if identity::is_expired(cert.not_after(), Agent::unix_timestamp_secs()) {
                        tracing::debug!(
                            "Dropping identity announcement with expired cert from agent {:?}",
                            hex::encode(&announcement.agent_id.0[..8]),
                        );
                        continue;
                    }
                }

                // Update machine records in the contact store.
                //
                // The daemon never registers its own agent as a contact: a self
                // entry would be noise on the `/contacts` projection and pollute
                // contact-set assertions (issue #145). The rebroadcast and
                // auto-connect branches below already self-skip on
                // `announcement.agent_id != own_agent_id`; the machine-record
                // upsert was the sole outlier. Foreign observation still
                // registers normally.
                register_announced_machine(
                    &contact_store,
                    own_agent_id,
                    announcement.agent_id,
                    announcement.machine_id,
                )
                .await;


                // Add only globally-advertisable addresses to the persistent
                // bootstrap cache. Legacy peers may still ship LAN, CGNAT,
                // loopback, or port-zero entries, but those are not useful
                // outside link-local discovery and must not become dial
                // candidates for globally propagated announcements.
                let bootstrap_addresses =
                    filter_publicly_advertisable_addrs(announcement.addresses.iter().copied());
                let discovery_addresses = filter_discovery_announcement_addrs(
                    announcement.addresses.iter().copied(),
                    allow_local_scope,
                );
                let filtered_addr_count = discovery_addresses.len();
                let auto_connect_addresses = discovery_addresses.clone();
                {
                    if !bootstrap_addresses.is_empty() {
                        if let Some(ref bc) = &bootstrap_cache {
                            let peer_id = ant_quic::PeerId(announcement.machine_id.0);
                            bc.add_from_connection(peer_id, bootstrap_addresses.clone(), None)
                                .await;
                            tracing::debug!(
                                "Added {} public addresses to bootstrap cache for agent {:?} (machine {:?})",
                                bootstrap_addresses.len(),
                                announcement.agent_id,
                                hex::encode(&announcement.machine_id.0[..8]),
                            );
                        }
                    }
                }

                // Cache public addresses on global partitions, but keep
                // LAN/loopback hints on explicit local/testnet partitions.
                // Empty address lists are preserved (the `AlreadyConnected`
                // path in `connect_to_agent` handles gossip peers we only reach
                // by an existing QUIC connection).
                let cert_not_after = announcement
                    .agent_certificate
                    .as_ref()
                    .and_then(|c| c.not_after());
                let discovered_agent = DiscoveredAgent {
                    agent_id: announcement.agent_id,
                    machine_id: announcement.machine_id,
                    user_id: announcement.user_id,
                    addresses: discovery_addresses,
                    announced_at: announcement.announced_at,
                    last_seen: now,
                    machine_public_key: announcement.machine_public_key.clone(),
                    nat_type: announcement.nat_type.clone(),
                    can_receive_direct: announcement.can_receive_direct,
                    is_relay: announcement.is_relay,
                    is_coordinator: announcement.is_coordinator,
                    reachable_via: announcement.reachable_via.clone(),
                    relay_candidates: announcement.relay_candidates.clone(),
                    cert_not_after,
                    agent_certificate: announcement.agent_certificate.clone(),
                    agent_public_key: announcement.agent_public_key.clone(),
                };
                record_authenticated_machine_binding_from_message(
                    &authenticated_machine_bindings,
                    &msg,
                    &announcement,
                    now,
                )
                .await;
                upsert_discovered_machine_from_agent(&machine_cache, &discovered_agent).await;
                upsert_discovered_agent(&cache, discovered_agent).await;
                tracing::debug!(
                    target: "x0x::discovery",
                    announcement_kind = "received",
                    agent_prefix = %network::hex_prefix(&announcement.agent_id.0, 4),
                    machine_prefix = %network::hex_prefix(&announcement.machine_id.0, 4),
                    addr_total = announcement.addresses.len(),
                    filtered_addr_count,
                    nat_type = announcement.nat_type.as_deref().unwrap_or("unknown"),
                    can_receive_direct = ?announcement.can_receive_direct,
                    relay_capable = ?announcement.is_relay,
                    coordinator_capable = ?announcement.is_coordinator,
                    reachable_via_count = announcement.reachable_via.len(),
                    relay_candidate_count = announcement.relay_candidates.len(),
                    "cached verified identity announcement"
                );

                // Identity announcements are the strongest agent↔machine binding we have.
                // Register the mapping immediately so reverse direct-send can resolve the
                // machine even before the first inbound direct payload arrives.
                direct_messaging
                    .register_agent(announcement.agent_id, announcement.machine_id)
                    .await;

                // Epidemic re-broadcast — mirrors the release-manifest
                // re-broadcast pattern. Bootstrap-node meshes have patchy
                // PlumTree overlap for the identity-announce topic: the
                // origin's tree only reaches 1–2 hops reliably. Making
                // every verified recipient re-publish guarantees flood
                // convergence across the mesh. One-shot dedup on
                // (agent_id, announced_at) bounds amplification. Pub/Sub
                // v2 re-signs each publish with a new message ID so
                // PlumTree's own dedup cannot suppress repeated forwards;
                // therefore each daemon forwards a given announcement at most
                // once.
                if announcement.agent_id != own_agent_id {
                    let key = (announcement.agent_id, announcement.announced_at);
                    if should_rebroadcast_discovery_once(
                        &mut rebroadcast_state,
                        key,
                        std::time::Instant::now(),
                    ) {
                        let pubsub = std::sync::Arc::clone(&rebroadcast_pubsub);
                        let payload = raw_payload.clone();
                        tokio::spawn(async move {
                            if let Err(e) = pubsub
                                .publish(IDENTITY_ANNOUNCE_TOPIC.to_string(), payload)
                                .await
                            {
                                tracing::debug!("identity announcement re-broadcast failed: {e}");
                            }
                        });
                    }
                }

                // Reconcile the agent-level direct-message registry if the transport peer
                // is already connected (for example an inbound accept that happened before
                // this announcement reached us).
                if let Some(ref net) = &network {
                    let ant_peer_id = ant_quic::PeerId(announcement.machine_id.0);
                    if net.is_connected(&ant_peer_id).await {
                        direct_messaging
                            .mark_connected(announcement.agent_id, announcement.machine_id)
                            .await;
                    }
                }

                // Auto-connect to discovered agents so pub/sub messages can route
                // between peers that share bootstrap nodes but aren't directly connected.
                // The gossip topology refresh (every 1s) will add the new peer to
                // PlumTree topic trees once the QUIC connection is established.
                if announcement.agent_id != own_agent_id
                    && !auto_connect_addresses.is_empty()
                    && announcement_auto_connect_retry_allowed(
                        auto_connect_attempts.get(&announcement.agent_id).copied(),
                        std::time::Instant::now(),
                    )
                {
                    if let Some(net) = &network {
                        let ant_peer = ant_quic::PeerId(announcement.machine_id.0);
                        // Security gate: a peer that was revoked, policy-rejected,
                        // admin-disconnected, or capacity-evicted carries a
                        // reconnect-suppression tombstone. Such a peer may keep
                        // broadcasting identity announcements over gossip; if we
                        // auto-connected on those, we would silently undo the
                        // security/eviction decision. Skip the dial (and do not
                        // record an attempt) while the tombstone is live.
                        let suppressed = net.is_reconnect_suppressed(announcement.machine_id.0);
                        let connected = net.is_connected(&ant_peer).await;
                        if announcement_should_auto_connect(suppressed, connected) {
                            auto_connect_attempts
                                .insert(announcement.agent_id, std::time::Instant::now());
                            let net = std::sync::Arc::clone(net);
                            let addresses = auto_connect_addresses.clone();
                            tokio::spawn(async move {
                                for addr in &addresses {
                                    match net.connect_addr(*addr).await {
                                        Ok(_) => {
                                            tracing::info!(
                                                "Auto-connected to discovered agent at {addr}",
                                            );
                                            return;
                                        }
                                        Err(e) => {
                                            tracing::debug!("Auto-connect to {addr} failed: {e}",);
                                        }
                                    }
                                }
                                tracing::debug!(
                                    "Auto-connect exhausted all {} addresses for discovered agent",
                                    addresses.len(),
                                );
                            });
                        } else if suppressed {
                            tracing::debug!(
                                target: "x0x::connect",
                                peer_id_prefix = %network::hex_prefix(&announcement.machine_id.0, 4),
                                "skipping announcement auto-connect for reconnect-suppressed peer",
                            );
                        }
                    }
                }
            }
        });

        Ok(())
    }

    fn unix_timestamp_secs() -> u64 {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_secs())
    }

    fn announcement_addresses(&self) -> Vec<std::net::SocketAddr> {
        match self.network.as_ref().and_then(|n| n.local_addr()) {
            Some(addr) if addr.port() > 0 => filter_discovery_announcement_addrs(
                collect_local_interface_addrs(addr.port()),
                self.network
                    .as_ref()
                    .is_some_and(|network| allow_local_discovery_addresses(network.config())),
            ),
            _ => Vec::new(),
        }
    }

    fn build_identity_announcement(
        &self,
        include_user_identity: bool,
        human_consent: bool,
    ) -> error::Result<IdentityAnnouncement> {
        self.build_identity_announcement_with_addrs(IdentityAnnouncementBuildOptions {
            include_user_identity,
            human_consent,
            addresses: self.announcement_addresses(),
            assist_snapshot: None,
            reachable_via: Vec::new(),
            relay_candidates: Vec::new(),
            allow_local_scope: false,
        })
    }

    fn build_identity_announcement_with_addrs(
        &self,
        options: IdentityAnnouncementBuildOptions<'_>,
    ) -> error::Result<IdentityAnnouncement> {
        let IdentityAnnouncementBuildOptions {
            include_user_identity,
            human_consent,
            addresses,
            assist_snapshot,
            reachable_via,
            relay_candidates,
            allow_local_scope,
        } = options;
        if include_user_identity && !human_consent {
            return Err(error::IdentityError::Storage(std::io::Error::other(
                "human identity disclosure requires explicit human consent — set human_consent: true in the request body",
            )));
        }
        let addresses = filter_discovery_announcement_addrs(addresses, allow_local_scope);

        let (user_id, agent_certificate) = if include_user_identity {
            let user_id = self.user_id().ok_or_else(|| {
                error::IdentityError::Storage(std::io::Error::other(
                    "human identity disclosure requested but no user identity is configured — set user_key_path in your config.toml to point at your user keypair file",
                ))
            })?;
            let cert = self.agent_certificate().cloned().ok_or_else(|| {
                error::IdentityError::Storage(std::io::Error::other(
                    "human identity disclosure requested but agent certificate is missing",
                ))
            })?;
            (Some(user_id), Some(cert))
        } else {
            (None, None)
        };

        let machine_public_key = self
            .identity
            .machine_keypair()
            .public_key()
            .as_bytes()
            .to_vec();

        let unsigned = IdentityAnnouncementUnsigned {
            agent_id: self.agent_id(),
            machine_id: self.machine_id(),
            user_id,
            agent_certificate: agent_certificate.clone(),
            machine_public_key: machine_public_key.clone(),
            addresses,
            announced_at: Self::unix_timestamp_secs(),
            nat_type: assist_snapshot.and_then(|snapshot| snapshot.nat_type.clone()),
            can_receive_direct: assist_snapshot.and_then(|snapshot| snapshot.can_receive_direct),
            is_relay: assist_snapshot.and_then(|snapshot| snapshot.relay_capable),
            is_coordinator: assist_snapshot.and_then(|snapshot| snapshot.coordinator_capable),
            reachable_via,
            relay_candidates,
        };
        let unsigned_bytes = bincode::serialize(&unsigned).map_err(|e| {
            error::IdentityError::Serialization(format!(
                "failed to serialize unsigned identity announcement: {e}"
            ))
        })?;
        let machine_signature = ant_quic::crypto::raw_public_keys::pqc::sign_with_ml_dsa(
            self.identity.machine_keypair().secret_key(),
            &unsigned_bytes,
        )
        .map_err(|e| {
            error::IdentityError::Storage(std::io::Error::other(format!(
                "failed to sign identity announcement with machine key: {:?}",
                e
            )))
        })?
        .as_bytes()
        .to_vec();

        Ok(IdentityAnnouncement {
            agent_id: unsigned.agent_id,
            machine_id: unsigned.machine_id,
            user_id: unsigned.user_id,
            agent_certificate: unsigned.agent_certificate,
            machine_public_key,
            machine_signature,
            addresses: unsigned.addresses,
            announced_at: unsigned.announced_at,
            nat_type: unsigned.nat_type,
            can_receive_direct: unsigned.can_receive_direct,
            is_relay: unsigned.is_relay,
            is_coordinator: unsigned.is_coordinator,
            reachable_via: unsigned.reachable_via,
            relay_candidates: unsigned.relay_candidates,
            agent_public_key: self
                .identity
                .agent_keypair()
                .public_key()
                .as_bytes()
                .to_vec(),
        })
    }

    /// Join the x0x gossip network.
    ///
    /// Connects to bootstrap peers in parallel with automatic retries.
    /// Failed connections are retried after a delay to allow stale
    /// connections on remote nodes to expire.
    ///
    /// If the agent was not configured with a network, this method
    /// succeeds gracefully (nothing to join).
    pub async fn join_network(&self) -> error::Result<()> {
        let Some(network) = self.network.as_ref() else {
            tracing::debug!("join_network called but no network configured");
            return Ok(());
        };

        if let Some(ref runtime) = self.gossip_runtime {
            runtime.start().await.map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "failed to start gossip runtime: {e}"
                )))
            })?;
            tracing::info!("Gossip runtime started");
        }
        // Race guard (issue #116): if shutdown() already fired (token cancelled),
        // do not start the listeners. Combined with spawn_tracked's closed-check,
        // a shutdown that races mid-bootstrap cannot leave a listener running.
        if self.shutdown_token.is_cancelled() {
            tracing::info!("join_network aborted: shutdown already in progress");
            return Ok(());
        }
        self.start_identity_listener().await?;
        self.start_network_event_listener();
        self.start_direct_listener();
        self.start_stream_accept_loop();

        let bootstrap_nodes = network.config().bootstrap_nodes.clone();

        let min_connected = 3;
        let mut all_connected: Vec<std::net::SocketAddr> = Vec::new();

        // ant-quic now owns first-party mDNS discovery and auto-connect.
        // x0x keeps bootstrap/cache orchestration here, while the transport
        // layer handles zero-config LAN discovery internally.

        // Phase 0: Try quality-scored coordinator peers from bootstrap cache.
        // The bootstrap cache learns about coordinator-capable peers passively
        // through normal connections — no coordinator gossip topic needed.
        if let Some(ref cache) = self.bootstrap_cache {
            let coordinators = cache.select_coordinators(6).await;
            let coordinator_addrs: Vec<std::net::SocketAddr> = coordinators
                .iter()
                .flat_map(|peer| peer.preferred_addresses())
                .collect();

            if !coordinator_addrs.is_empty() {
                tracing::info!(
                    "Phase 0: Trying {} addresses from {} cached coordinators",
                    coordinator_addrs.len(),
                    coordinators.len()
                );
                let (succeeded, _failed) = self
                    .connect_peers_parallel_tracked(network, &coordinator_addrs)
                    .await;
                all_connected.extend(&succeeded);
                tracing::info!(
                    "Phase 0: {}/{} coordinator addresses connected",
                    succeeded.len(),
                    coordinator_addrs.len()
                );
            }
        }

        // Phase 1: Try cached peers first using the real ant-quic peer IDs.
        if all_connected.len() < min_connected {
            if let Some(ref cache) = self.bootstrap_cache {
                const PHASE1_PEER_CANDIDATES: usize = 12;
                let cached_peers = cache.select_peers(PHASE1_PEER_CANDIDATES).await;
                if !cached_peers.is_empty() {
                    tracing::info!("Phase 1: Trying {} cached peers", cached_peers.len());
                    let (succeeded, _failed) = self
                        .connect_cached_peers_parallel_tracked(network, &cached_peers)
                        .await;
                    all_connected.extend(&succeeded);
                    tracing::info!(
                        "Phase 1: {}/{} cached peers connected",
                        succeeded.len(),
                        cached_peers.len()
                    );
                }
            }
        } // end Phase 1 min_connected check

        // Phase 2: Connect to hardcoded bootstrap nodes if we need more peers.
        // This is the fallback for when coordinator cache and cached peers aren't enough.
        if all_connected.len() < min_connected && !bootstrap_nodes.is_empty() {
            let remaining: Vec<std::net::SocketAddr> = bootstrap_nodes
                .iter()
                .filter(|addr| !all_connected.contains(addr))
                .copied()
                .collect();

            // Round 1: Connect to all bootstrap peers in parallel
            let (succeeded, mut failed) = self
                .connect_peers_parallel_tracked(network, &remaining)
                .await;
            all_connected.extend(&succeeded);
            tracing::info!(
                "Phase 2 round 1: {}/{} bootstrap peers connected",
                succeeded.len(),
                remaining.len()
            );

            // Retry rounds for failed peers
            for round in 2..=3 {
                if failed.is_empty() {
                    break;
                }
                let delay = std::time::Duration::from_secs(if round == 2 { 10 } else { 15 });
                tracing::info!(
                    "Retrying {} failed peers in {}s (round {})",
                    failed.len(),
                    delay.as_secs(),
                    round
                );
                tokio::time::sleep(delay).await;

                let (succeeded, still_failed) =
                    self.connect_peers_parallel_tracked(network, &failed).await;
                all_connected.extend(&succeeded);
                failed = still_failed;
                tracing::info!(
                    "Phase 2 round {}: {} total peers connected",
                    round,
                    all_connected.len()
                );
            }

            if !failed.is_empty() {
                tracing::warn!(
                    "Could not connect to {} bootstrap peers: {:?}",
                    failed.len(),
                    failed
                );
            }
        }

        tracing::info!(
            "Network join complete. Connected to {} peers.",
            all_connected.len()
        );

        // Join the HyParView membership overlay via connected peers.
        if let Some(ref runtime) = self.gossip_runtime {
            let seeds: Vec<String> = all_connected.iter().map(|addr| addr.to_string()).collect();
            if !seeds.is_empty() {
                if let Err(e) = runtime.membership().join(seeds).await {
                    tracing::warn!("HyParView membership join failed: {e}");
                }
            }
        }

        // Start presence beacons after membership overlay is established.
        if let Some(ref pw) = self.presence {
            // Seed broadcast peers from both HyParView and ant-quic's live
            // connection table so beacons propagate even when HyParView's
            // active view lags behind the transport mesh.
            if let Some(ref runtime) = self.gossip_runtime {
                let active = runtime.membership().active_view();
                let active_view_count = active.len();
                let mut broadcast_peers = active;

                let mut connected_peer_count = 0usize;
                if let Some(ref net) = self.network {
                    let connected = net.connected_peers().await;
                    connected_peer_count = connected.len();
                    broadcast_peers.extend(
                        connected
                            .into_iter()
                            .map(|peer| saorsa_gossip_types::PeerId::new(peer.0)),
                    );
                }

                pw.manager().replace_broadcast_peers(broadcast_peers).await;
                let broadcast_peer_count = pw.manager().broadcast_peer_count().await;
                tracing::info!(
                    active_view_count,
                    connected_peer_count,
                    broadcast_peer_count,
                    "Presence seeded broadcast peers"
                );

                // Refresh broadcast_peers from HyParView and the live ant-quic
                // connection table every 30 s. Without this, agents that finish
                // join_network() before the mesh has formed can end up with an
                // empty/stale broadcast set forever. The 2026-04-26 live mesh
                // had full QUIC peer connectivity while HyParView active_view()
                // stayed at <= 1 peer, so the transport table is the source of
                // truth for presence fanout. Replace the fanout set each tick so
                // stale/disconnected peers do not accumulate and later wedge
                // presence delivery behind failed reconnect attempts.
                let pw_clone = pw.clone();
                let runtime_clone = runtime.clone();
                let network_clone = self.network.as_ref().map(std::sync::Arc::clone);
                let token = self.shutdown_token.clone();
                self.spawn_tracked(async move {
                    let mut interval = tokio::time::interval(std::time::Duration::from_secs(30));
                    interval.tick().await; // first tick fires immediately; startup already seeded
                    loop {
                        tokio::select! {
                            _ = interval.tick() => {}
                            // Inert until shutdown; then the 30s timer loop exits
                            // instead of being merely aborted.
                            _ = token.cancelled() => break,
                        }

                        let active = runtime_clone.membership().active_view();
                        let active_view_count = active.len();
                        let mut broadcast_peers = active;

                        let mut connected_peer_count = 0usize;
                        if let Some(ref net) = network_clone {
                            let connected = net.connected_peers().await;
                            connected_peer_count = connected.len();
                            broadcast_peers.extend(
                                connected
                                    .into_iter()
                                    .map(|peer| saorsa_gossip_types::PeerId::new(peer.0)),
                            );
                        }

                        pw_clone
                            .manager()
                            .replace_broadcast_peers(broadcast_peers)
                            .await;
                        let broadcast_peer_count = pw_clone.manager().broadcast_peer_count().await;
                        tracing::info!(
                            active_view_count,
                            connected_peer_count,
                            broadcast_peer_count,
                            "Presence broadcast peer refresh"
                        );
                    }
                });
            }

            // Populate address hints from network status for beacon metadata.
            //
            // Presence beacons propagate over global gossip — filter to only
            // globally-advertisable addresses. LAN discovery is ant-quic's
            // mDNS job, not ours. Also exclude `status.local_addr` which is
            // typically the wildcard `[::]:5483` and never a dialable target.
            if let Some(ref net) = self.network {
                if let Some(status) = net.node_status().await {
                    let hints: Vec<String> = status
                        .external_addrs
                        .iter()
                        .filter(|a| is_publicly_advertisable(**a))
                        .map(|a| a.to_string())
                        .collect();
                    pw.manager().set_addr_hints(hints).await;
                }
            }

            // Shutdown race (issue #116): skip starting presence beacons / event
            // loop if shutdown began mid-bootstrap; Agent::shutdown() runs
            // pw.shutdown() AFTER cancel(), so checking here ensures we never
            // start beacons that pw.shutdown() already stopped.
            if !self.shutdown_token.is_cancelled() {
                if pw.config().enable_beacons {
                    if let Err(e) = pw
                        .manager()
                        .start_beacons(pw.config().beacon_interval_secs)
                        .await
                    {
                        tracing::warn!("Failed to start presence beacons: {e}");
                    } else {
                        tracing::info!(
                            "Presence beacons started (interval={}s)",
                            pw.config().beacon_interval_secs
                        );
                    }
                }

                // Start the presence event-emission loop so that subscribers
                // automatically receive AgentOnline/AgentOffline events after
                // join_network() returns.
                pw.start_event_loop(std::sync::Arc::clone(&self.identity_discovery_cache))
                    .await;
                tracing::debug!("Presence event loop started");
            }
        }

        if let Err(e) = self.announce_identity(false, false).await {
            tracing::warn!("Initial identity announcement failed: {}", e);
        }
        if let Err(e) = self.start_identity_heartbeat().await {
            tracing::warn!("Failed to start identity heartbeat: {e}");
        }
        if let Err(e) = self.start_discovery_cache_reaper().await {
            tracing::warn!("Failed to start discovery cache reaper: {e}");
        }

        // Schedule a fresh re-announcement after gossip topology stabilizes.
        // The initial publish fires before PlumTree has formed eager-push links,
        // so peers that connected after the first announce won't see it.
        // A fresh announcement (new message ID) is required because PlumTree
        // deduplicates by message ID — replaying identical bytes would be silently
        // dropped by peers that already received the first announcement.
        if let (Some(ref runtime), Some(ref network)) = (&self.gossip_runtime, &self.network) {
            let ctx = HeartbeatContext {
                identity: std::sync::Arc::clone(&self.identity),
                runtime: std::sync::Arc::clone(runtime),
                network: std::sync::Arc::clone(network),
                interval_secs: self.heartbeat_interval_secs,
                cache: std::sync::Arc::clone(&self.identity_discovery_cache),
                machine_cache: std::sync::Arc::clone(&self.machine_discovery_cache),
                user_identity_consented: std::sync::Arc::clone(&self.user_identity_consented),
                allow_local_discovery_addrs: allow_local_discovery_addresses(network.config()),
                revocation_set: std::sync::Arc::clone(&self.revocation_set),
            };
            // Routed through spawn_tracked (issue #116) so a shutdown racing
            // bootstrap refuses to start it once the registry is closed; it is
            // a one-shot self-completing task so no token arm is needed.
            self.spawn_tracked(async move {
                tokio::time::sleep(std::time::Duration::from_secs(3)).await;
                if let Err(e) = ctx.announce().await {
                    tracing::warn!("Delayed identity re-announcement failed: {e}");
                } else {
                    tracing::info!(
                        "Delayed identity re-announcement sent (gossip mesh stabilized)"
                    );
                }
            });
        }

        if let Err(e) = self.start_capability_advert_service().await {
            tracing::warn!("failed to start capability advert service: {e}");
        }

        Ok(())
    }

    /// Clone the shared capability store.
    #[must_use]
    pub fn capability_store(&self) -> std::sync::Arc<dm_capability::CapabilityStore> {
        std::sync::Arc::clone(&self.capability_store)
    }

    /// Start or restart the mesh-wide DM capability advert service.
    ///
    /// The service publishes this agent's current DM capability and subscribes
    /// to peer adverts. It is idempotent: a fresh service replaces any previous
    /// one. Daemons call this independently of `join_network()` completion so
    /// a slow bootstrap pass cannot leave DM capability discovery disabled.
    ///
    /// # Errors
    ///
    /// Returns an error if no gossip runtime is configured yet or the advert
    /// service cannot subscribe/publish on its topic.
    pub async fn start_capability_advert_service(&self) -> error::Result<()> {
        let runtime = self.gossip_runtime.as_ref().ok_or_else(|| {
            error::IdentityError::Storage(std::io::Error::other(
                "cannot start capability advert service: no gossip runtime configured",
            ))
        })?;

        let signing = std::sync::Arc::new(gossip::SigningContext::from_keypair(
            self.identity.agent_keypair(),
        ));
        let caps_rx = self.dm_capabilities_tx.subscribe();
        let service = dm_capability_service::CapabilityAdvertService::spawn_default(
            std::sync::Arc::clone(runtime.pubsub()),
            signing,
            self.identity.agent_id(),
            self.identity.machine_id(),
            caps_rx,
            std::sync::Arc::clone(&self.capability_store),
        )
        .await
        .map_err(|e| {
            error::IdentityError::Storage(std::io::Error::other(format!(
                "capability advert service spawn failed: {e}"
            )))
        })?;

        let mut guard = self.capability_advert_service.lock().await;
        // Shutdown race (issue #116): if shutdown began while we were spawning,
        // abort the freshly-spawned service instead of storing it. Checked under
        // the same lock shutdown() takes the service from, so it can't leak.
        if self.shutdown_token.is_cancelled() {
            service.abort();
            return Ok(());
        }
        if let Some(prev) = guard.take() {
            prev.abort();
        }
        *guard = Some(service);
        tracing::info!("Capability advert service started");
        Ok(())
    }

    /// Clone the shared DM in-flight ACK registry.
    #[must_use]
    pub fn dm_inflight_acks(&self) -> std::sync::Arc<dm::InFlightAcks> {
        std::sync::Arc::clone(&self.dm_inflight_acks)
    }

    /// Clone the shared recent-delivery dedupe cache.
    #[must_use]
    pub fn recent_delivery_cache(&self) -> std::sync::Arc<dm::RecentDeliveryCache> {
        std::sync::Arc::clone(&self.recent_delivery_cache)
    }

    /// Spawn the DM inbox service backed by the given KEM keypair.
    /// Idempotent — the prior service is aborted before spawning new.
    ///
    /// # Errors
    ///
    /// Returns an error if no gossip runtime is configured.
    pub async fn start_dm_inbox(
        &self,
        kem_keypair: std::sync::Arc<groups::kem_envelope::AgentKemKeypair>,
        config: dm_inbox::DmInboxConfig,
    ) -> error::Result<()> {
        let runtime = self.gossip_runtime.as_ref().ok_or_else(|| {
            error::IdentityError::Storage(std::io::Error::other(
                "cannot start DM inbox: no gossip runtime configured",
            ))
        })?;
        let signing = std::sync::Arc::new(gossip::SigningContext::from_keypair(
            self.identity.agent_keypair(),
        ));
        let service = dm_inbox::DmInboxService::spawn(
            std::sync::Arc::clone(runtime.pubsub()),
            signing,
            self.identity.agent_id(),
            self.identity.machine_id(),
            std::sync::Arc::clone(&kem_keypair),
            std::sync::Arc::clone(&self.direct_messaging),
            std::sync::Arc::clone(&self.contact_store),
            std::sync::Arc::clone(&self.dm_inflight_acks),
            std::sync::Arc::clone(&self.recent_delivery_cache),
            config,
            std::sync::Arc::clone(&self.revocation_set),
            std::sync::Arc::clone(&self.authenticated_machine_bindings),
        )
        .await
        .map_err(|e| {
            error::IdentityError::Storage(std::io::Error::other(format!(
                "DM inbox spawn failed: {e}"
            )))
        })?;
        let mut guard = self.dm_inbox_service.lock().await;
        // Shutdown race (issue #116): if shutdown began while we were spawning,
        // abort the freshly-spawned service instead of storing it (and skip the
        // capability upgrade below). Checked under the same lock stop_dm_inbox
        // takes the service from, so it can't leak.
        if self.shutdown_token.is_cancelled() {
            service.abort();
            return Ok(());
        }
        if let Some(prev) = guard.take() {
            prev.abort();
        }
        *guard = Some(service);

        // Upgrade our advertised capabilities so peers stop falling back
        // to the raw-QUIC path. The capability advert service watches
        // this channel and republishes immediately on change.
        let upgraded =
            dm::DmCapabilities::pending().with_kem_public_key(kem_keypair.public_bytes.clone());
        // send_replace stores the value even when no receiver is subscribed
        // yet; a plain send() drops the upgrade if this runs before the
        // capability advert service subscribes, leaving peers cached on
        // gossip_inbox=false and forcing the raw-QUIC fallback that fails
        // across NAT (issue #101).
        self.dm_capabilities_tx.send_replace(upgraded);
        tracing::info!("DM inbox service started");
        Ok(())
    }

    /// Stop the DM inbox service, if running. Idempotent.
    pub async fn stop_dm_inbox(&self) {
        let mut guard = self.dm_inbox_service.lock().await;
        if let Some(service) = guard.take() {
            service.abort();
        }
    }

    /// Connect to cached peers in parallel, returning (succeeded, failed) peer lists.
    async fn connect_cached_peers_parallel_tracked(
        &self,
        network: &std::sync::Arc<network::NetworkNode>,
        peers: &[ant_quic::CachedPeer],
    ) -> (Vec<std::net::SocketAddr>, Vec<ant_quic::PeerId>) {
        use tokio::time::{timeout, Duration};
        const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);

        let handles: Vec<_> = peers
            .iter()
            .map(|peer| {
                let net = network.clone();
                let peer_id = peer.peer_id;
                tokio::spawn(async move {
                    tracing::debug!("Connecting to cached peer: {:?}", peer_id);
                    match timeout(CONNECT_TIMEOUT, net.connect_cached_peer(peer_id)).await {
                        Ok(Ok(addr)) => {
                            tracing::info!("Connected to cached peer {:?} at {}", peer_id, addr);
                            Ok(addr)
                        }
                        Ok(Err(e)) => {
                            tracing::warn!("Failed to connect to cached peer {:?}: {}", peer_id, e);
                            Err(peer_id)
                        }
                        Err(_) => {
                            tracing::warn!(
                                "Connection to cached peer {:?} timed out after {}s",
                                peer_id,
                                CONNECT_TIMEOUT.as_secs()
                            );
                            Err(peer_id)
                        }
                    }
                })
            })
            .collect();

        let mut succeeded = Vec::new();
        let mut failed = Vec::new();
        for handle in handles {
            match handle.await {
                Ok(Ok(addr)) => succeeded.push(addr),
                Ok(Err(peer_id)) => failed.push(peer_id),
                Err(e) => tracing::error!("Connection task panicked: {}", e),
            }
        }
        (succeeded, failed)
    }

    /// Connect to multiple peers in parallel, returning (succeeded, failed) address lists.
    async fn connect_peers_parallel_tracked(
        &self,
        network: &std::sync::Arc<network::NetworkNode>,
        addrs: &[std::net::SocketAddr],
    ) -> (Vec<std::net::SocketAddr>, Vec<std::net::SocketAddr>) {
        use tokio::time::{timeout, Duration};

        // Per-connection timeout prevents hanging when connecting to
        // ourselves or to unreachable addresses.
        const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);

        let handles: Vec<_> = addrs
            .iter()
            .map(|addr| {
                let net = network.clone();
                let addr = *addr;
                tokio::spawn(async move {
                    tracing::debug!("Connecting to peer: {}", addr);
                    match timeout(CONNECT_TIMEOUT, net.connect_addr(addr)).await {
                        Ok(Ok(_)) => {
                            tracing::info!("Connected to peer: {}", addr);
                            Ok(addr)
                        }
                        Ok(Err(e)) => {
                            tracing::warn!("Failed to connect to {}: {}", addr, e);
                            Err(addr)
                        }
                        Err(_) => {
                            tracing::warn!(
                                "Connection to {} timed out after {}s",
                                addr,
                                CONNECT_TIMEOUT.as_secs()
                            );
                            Err(addr)
                        }
                    }
                })
            })
            .collect();

        let mut succeeded = Vec::new();
        let mut failed = Vec::new();
        for handle in handles {
            match handle.await {
                Ok(Ok(addr)) => succeeded.push(addr),
                Ok(Err(addr)) => failed.push(addr),
                Err(e) => tracing::error!("Connection task panicked: {}", e),
            }
        }
        (succeeded, failed)
    }

    /// Subscribe to messages on a given topic.
    ///
    /// Returns a [`gossip::Subscription`] that yields messages as they arrive
    /// through the gossip network.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Gossip runtime is not initialized (configure agent with network first)
    pub async fn subscribe(&self, topic: &str) -> error::Result<Subscription> {
        let runtime = self.gossip_runtime.as_ref().ok_or_else(|| {
            error::IdentityError::Storage(std::io::Error::other(
                "gossip runtime not initialized - configure agent with network first",
            ))
        })?;
        Ok(runtime.pubsub().subscribe(topic.to_string()).await)
    }

    /// Publish a message to a topic.
    ///
    /// The message will propagate through the gossip network via
    /// epidemic broadcast — every agent that receives it will
    /// relay it to its neighbours.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Gossip runtime is not initialized (configure agent with network first)
    /// - Message encoding or broadcast fails
    pub async fn publish(&self, topic: &str, payload: Vec<u8>) -> error::Result<()> {
        let runtime = self.gossip_runtime.as_ref().ok_or_else(|| {
            error::IdentityError::Storage(std::io::Error::other(
                "gossip runtime not initialized - configure agent with network first",
            ))
        })?;
        runtime
            .pubsub()
            .publish(topic.to_string(), bytes::Bytes::from(payload))
            .await
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "publish failed: {}",
                    e
                )))
            })
    }

    /// Get connected peer IDs.
    ///
    /// Returns the list of peers currently connected via the gossip network.
    ///
    /// # Errors
    ///
    /// Returns an error if the network is not initialized.
    pub async fn peers(&self) -> error::Result<Vec<saorsa_gossip_types::PeerId>> {
        let network = self.network.as_ref().ok_or_else(|| {
            error::IdentityError::Storage(std::io::Error::other(
                "network not initialized - configure agent with network first",
            ))
        })?;
        let ant_peers = network.connected_peers().await;
        Ok(ant_peers
            .into_iter()
            .map(|p| saorsa_gossip_types::PeerId::new(p.0))
            .collect())
    }

    /// Get online agents.
    ///
    /// Returns agent IDs discovered from signed identity announcements.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn presence(&self) -> error::Result<Vec<identity::AgentId>> {
        self.start_identity_listener().await?;
        let cutoff = Self::unix_timestamp_secs().saturating_sub(self.identity_ttl_secs);
        let mut agents: Vec<_> = self
            .identity_discovery_cache
            .read()
            .await
            .values()
            .filter(|a| discovery_record_is_live(a.announced_at, a.last_seen, cutoff))
            .map(|a| a.agent_id)
            .collect();
        agents.sort_by_key(|a| a.0);
        Ok(agents)
    }

    /// Subscribe to presence events (agent online/offline notifications).
    ///
    /// Returns a [`tokio::sync::broadcast::Receiver<PresenceEvent>`] that yields
    /// [`presence::PresenceEvent`] values as agents come online or go offline.
    ///
    /// The diff-based event emission loop is started lazily on the first call to this
    /// method (or when [`join_network`](Agent::join_network) is called). Subsequent
    /// calls return independent receivers on the same broadcast channel.
    ///
    /// # Errors
    ///
    /// Returns [`error::NetworkError::NodeError`] if this agent was built
    /// without a network configuration (i.e. no `with_network_config` on the builder).
    pub async fn subscribe_presence(
        &self,
    ) -> error::NetworkResult<tokio::sync::broadcast::Receiver<presence::PresenceEvent>> {
        let pw = self.presence.as_ref().ok_or_else(|| {
            error::NetworkError::NodeError("presence system not initialized".to_string())
        })?;
        // Ensure the event loop is running.
        pw.start_event_loop(std::sync::Arc::clone(&self.identity_discovery_cache))
            .await;
        Ok(pw.subscribe_events())
    }

    /// Look up a single agent in the local discovery cache.
    ///
    /// Returns `None` if the agent is not currently cached.  No network I/O is
    /// performed — use [`discover_agent_by_id`](Agent::discover_agent_by_id) for
    /// an active lookup that queries the network.
    pub async fn cached_agent(&self, id: &identity::AgentId) -> Option<DiscoveredAgent> {
        self.identity_discovery_cache.read().await.get(id).cloned()
    }

    /// Check whether a claimed `AgentId` is verified as belonging to the
    /// given `MachineId` in the identity discovery cache.
    ///
    /// Returns `true` if the cache contains a signed identity announcement
    /// binding this agent to this machine.  Returns `false` if:
    /// - the agent is unknown or bound to a different machine, OR
    /// - the agent or its bound machine has been revoked, OR
    /// - the cached agent certificate has expired (past `not_after` + 300 s
    ///   clock skew).
    ///
    /// Revocation is fail-closed: a revoked peer is always refused, even if
    /// a certificate mismatch or race condition has cleared the cache entry.
    /// Absent expiry (`cert_not_after == None`) is fail-open: treated as
    /// "never expires" to preserve compatibility with pre-#130 peers.
    pub async fn is_agent_machine_verified(
        &self,
        agent_id: &identity::AgentId,
        machine_id: &identity::MachineId,
    ) -> bool {
        // Fail-closed on revocation: check before touching the discovery cache
        // so a racing cache-eviction cannot create a window where a revoked
        // peer appears verified.
        {
            let revoked = self.revocation_set.read().await;
            if revoked.is_agent_revoked(agent_id) || revoked.is_machine_revoked(machine_id) {
                return false;
            }
        }

        let cache = self.identity_discovery_cache.read().await;
        let Some(entry) = cache.get(agent_id) else {
            return false;
        };
        if entry.machine_id != *machine_id {
            return false;
        }
        // Fail-open on absent expiry (pre-#130 peers have no cert / no not_after).
        if identity::is_expired(entry.cert_not_after, Self::unix_timestamp_secs()) {
            return false;
        }
        true
    }

    /// Return the shared revocation set.
    ///
    /// Callers that need to publish a new revocation record should call
    /// [`revoke`](Agent::revoke) instead; this accessor is for gate checks
    /// and diagnostics.
    pub fn revocation_set(&self) -> std::sync::Arc<tokio::sync::RwLock<revocation::RevocationSet>> {
        std::sync::Arc::clone(&self.revocation_set)
    }

    /// Return the shared identity discovery cache (`pub(crate)` — used by the
    /// forwarder to look up cached agent public keys for `ForwardV2`
    /// attestation verification, #204).
    pub(crate) fn identity_discovery_cache(
        &self,
    ) -> std::sync::Arc<
        tokio::sync::RwLock<std::collections::HashMap<identity::AgentId, DiscoveredAgent>>,
    > {
        std::sync::Arc::clone(&self.identity_discovery_cache)
    }

    /// Return the shared contact store (`pub(crate)` — used by the forwarder
    /// to evaluate trust for ForwardV2 attestation, #204 must-fix 3).
    pub(crate) fn contact_store(
        &self,
    ) -> std::sync::Arc<tokio::sync::RwLock<contacts::ContactStore>> {
        std::sync::Arc::clone(&self.contact_store)
    }

    /// Return a snapshot of all known revocation records.
    ///
    /// This is a read-only snapshot; the in-memory set grows only (no un-revocation).
    pub async fn revocation_records(&self) -> Vec<revocation::RevocationRecord> {
        self.revocation_set.read().await.all_records()
    }

    /// Sign and publish a revocation for the given subject, then persist it
    /// locally and apply it immediately.
    ///
    /// The issuer keypair must satisfy one of the two authority rules in
    /// [`revocation::RevocationRecord::verify_authority`]:
    /// - **Self-revocation**: the issuer keypair's AgentId equals the subject's AgentId.
    /// - **Issuer-revocation**: the issuer is the user who signed the subject
    ///   agent's certificate (the certificate must be passed as `subject_cert`).
    ///
    /// On success, the record is inserted into the local revocation set,
    /// persisted to `revocations.bin`, published on [`REVOCATION_TOPIC`], and
    /// the subject is evicted from all discovery caches.
    ///
    /// # Errors
    ///
    /// Returns an error if signing fails, the authority check fails, or the
    /// gossip publish fails.
    pub async fn revoke(
        &self,
        issuer_keypair: &identity::AgentKeypair,
        subject: revocation::RevokedSubject,
        reason: Option<String>,
        subject_cert: Option<&identity::AgentCertificate>,
    ) -> error::Result<revocation::RevocationRecord> {
        let now = Self::unix_timestamp_secs();
        let record = revocation::RevocationRecord::sign(
            subject,
            issuer_keypair.public_key(),
            issuer_keypair.secret_key(),
            now,
            reason,
        )?;
        self.apply_and_publish_revocation(record.clone(), subject_cert)
            .await?;
        Ok(record)
    }

    /// Apply a revocation record to the local set, persist, publish, and evict.
    ///
    /// Used both by [`revoke`](Agent::revoke) (self-issued) and the gossip
    /// subscription loop (received from a peer).
    async fn apply_and_publish_revocation(
        &self,
        record: revocation::RevocationRecord,
        subject_cert: Option<&identity::AgentCertificate>,
    ) -> error::Result<()> {
        // 1. Verify and insert.
        {
            let mut set = self.revocation_set.write().await;
            if let Err(e) = set.verify_and_insert(record.clone(), subject_cert) {
                return Err(error::IdentityError::CertificateVerification(format!(
                    "revocation rejected: {e}"
                )));
            }
        }

        // 2. Persist.
        storage::save_revocation_set(
            &*self.revocation_set.read().await,
            self.identity_dir.as_deref(),
        )
        .await?;

        // 3. Evict from caches.
        self.evict_revoked_subject(&record.subject).await;

        // 4. Publish on gossip (best-effort — local enforcement happens regardless).
        if let Some(rt) = &self.gossip_runtime {
            let records = self.revocation_set.read().await.all_records();
            match bincode::serialize(&records) {
                Ok(bytes) if !bytes.is_empty() => {
                    let _ = rt
                        .pubsub()
                        .publish(REVOCATION_TOPIC.to_string(), bytes::Bytes::from(bytes))
                        .await;
                }
                _ => {}
            }
        }

        Ok(())
    }

    /// Evict a revoked subject from all discovery caches.
    async fn evict_revoked_subject(&self, subject: &revocation::RevokedSubject) {
        // NOTE: this evicts the identity/machine discovery caches and the
        // contact store, but does NOT purge the ant-quic bootstrap cache. A
        // revoked peer's address can therefore linger there; this is a residual
        // (not a hole) because EP1 re-rejects the peer's announcement on every
        // ingest, so it can never re-enter the verified path. Bootstrap-cache
        // purge on eviction is tracked as a follow-up.
        match subject {
            revocation::RevokedSubject::Agent(agent_id) => {
                // Remove from identity cache, which also starves the verified annotation.
                let revoked_machine = {
                    let mut cache = self.identity_discovery_cache.write().await;
                    let m = cache.remove(agent_id).map(|entry| entry.machine_id);
                    drop(cache);
                    m
                };
                if let Some(machine_id) = revoked_machine {
                    // Also evict the linked machine so it cannot be dialed.
                    let mut mcache = self.machine_discovery_cache.write().await;
                    mcache.remove(&machine_id);
                    drop(mcache);
                    // Suppress redial and tear down any live connection to the
                    // revoked machine (final review P1: never redial
                    // revocation). disconnect_with_reason records the tombstone
                    // regardless of connect state, so a later transport close
                    // or stale lifecycle Closed cannot redial it either.
                    if let Some(net) = &self.network {
                        let _ = net
                            .disconnect_with_reason(
                                &ant_quic::PeerId(machine_id.0),
                                network::DisconnectReason::Revocation,
                            )
                            .await;
                    }
                }
                // Best-effort: mark as Blocked in the contact store so that
                // trust evaluation also refuses the agent on any late-arriving path.
                {
                    let mut cs = self.contact_store.write().await;
                    cs.set_trust(agent_id, contacts::TrustLevel::Blocked);
                }
                tracing::info!(
                    agent = %hex::encode(agent_id.as_bytes()),
                    "evicted revoked agent from discovery cache"
                );
            }
            revocation::RevokedSubject::Machine(machine_id) => {
                let mut mcache = self.machine_discovery_cache.write().await;
                mcache.remove(machine_id);
                drop(mcache);
                // Also evict any agents linked to this machine.
                let mut cache = self.identity_discovery_cache.write().await;
                cache.retain(|_, agent| agent.machine_id != *machine_id);
                drop(cache);
                // Suppress redial and tear down any live connection (final
                // review P1: never redial revocation). The tombstone is set
                // inside disconnect_with_reason regardless of connect state.
                if let Some(net) = &self.network {
                    let _ = net
                        .disconnect_with_reason(
                            &ant_quic::PeerId(machine_id.0),
                            network::DisconnectReason::Revocation,
                        )
                        .await;
                }
                tracing::info!(
                    machine = %hex::encode(machine_id.as_bytes()),
                    "evicted revoked machine from discovery cache"
                );
            }
        }
    }

    /// Discover agents via Friend-of-a-Friend (FOAF) random walk.
    ///
    /// Initiates a FOAF query on the global presence topic with the given `ttl`
    /// (maximum hop count) and `timeout_ms` (response collection window).
    ///
    /// Returned entries are resolved against the local identity discovery cache
    /// so that known agents are returned with full identity data.  Unknown peers
    /// are included with a minimal entry (addresses only) that will be enriched
    /// once their identity heartbeat arrives.
    ///
    /// # Arguments
    ///
    /// * `ttl` — Maximum hop count for the random walk (`1`–`5`). Typical: `2`.
    /// * `timeout_ms` — Query timeout in milliseconds. Typical: `5000`.
    ///
    /// # Errors
    ///
    /// Returns [`error::NetworkError::NodeError`] if no network config was provided.
    pub async fn discover_agents_foaf(
        &self,
        ttl: u8,
        timeout_ms: u64,
    ) -> error::NetworkResult<Vec<DiscoveredAgent>> {
        let pw = self.presence.as_ref().ok_or_else(|| {
            error::NetworkError::NodeError("presence system not initialized".to_string())
        })?;

        let topic = presence::global_presence_topic();
        let raw_results: Vec<(
            saorsa_gossip_types::PeerId,
            saorsa_gossip_types::PresenceRecord,
        )> = pw
            .manager()
            .initiate_foaf_query(topic, ttl, timeout_ms)
            .await
            .map_err(|e| error::NetworkError::NodeError(e.to_string()))?;

        let cache = self.identity_discovery_cache.read().await;

        // Convert and deduplicate by agent_id.
        let mut seen: std::collections::HashSet<identity::AgentId> =
            std::collections::HashSet::new();
        let mut agents: Vec<DiscoveredAgent> = Vec::with_capacity(raw_results.len());

        for (peer_id, record) in &raw_results {
            if let Some(agent) =
                presence::presence_record_to_discovered_agent(*peer_id, record, &cache)
            {
                if seen.insert(agent.agent_id) {
                    agents.push(agent);
                }
            }
        }

        Ok(agents)
    }

    /// Discover a specific agent by their [`identity::AgentId`] via FOAF random walk.
    ///
    /// Fast-path: checks the local identity discovery cache first and returns
    /// immediately if the agent is already known.
    ///
    /// Slow-path: performs a FOAF random walk (see [`discover_agents_foaf`](Agent::discover_agents_foaf))
    /// and searches the results for a matching `AgentId`.
    ///
    /// Returns `None` if the agent is not found within the given `ttl` and `timeout_ms`.
    ///
    /// # Errors
    ///
    /// Returns [`error::NetworkError::NodeCreation`] if no network config was provided.
    pub async fn discover_agent_by_id(
        &self,
        target_id: identity::AgentId,
        ttl: u8,
        timeout_ms: u64,
    ) -> error::NetworkResult<Option<DiscoveredAgent>> {
        // Fast path: already in local cache.
        {
            let cache = self.identity_discovery_cache.read().await;
            if let Some(agent) = cache.get(&target_id) {
                return Ok(Some(agent.clone()));
            }
        }

        // Slow path: FOAF random walk.
        let agents = self.discover_agents_foaf(ttl, timeout_ms).await?;
        Ok(agents.into_iter().find(|a| a.agent_id == target_id))
    }

    /// Find an agent by ID, returning its known addresses.
    ///
    /// Performs a three-stage lookup:
    /// 1. **Cache hit** — return addresses immediately if the agent has already
    ///    been discovered.
    /// 2. **Shard subscription** — subscribe to the agent's identity shard topic
    ///    and wait up to 5 seconds for a heartbeat announcement.
    /// 3. **Rendezvous** — subscribe to the agent's rendezvous shard topic and
    ///    wait up to 5 seconds for a `ProviderSummary` advertisement.  This
    ///    works even when the two agents are on different gossip overlay clusters.
    ///
    /// Returns `None` if the agent is not found within the combined deadline.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn find_agent(
        &self,
        agent_id: identity::AgentId,
    ) -> error::Result<Option<Vec<std::net::SocketAddr>>> {
        self.start_identity_listener().await?;

        // Stage 1: cache hit.
        if let Some(addrs) = self
            .identity_discovery_cache
            .read()
            .await
            .get(&agent_id)
            .map(|e| e.addresses.clone())
        {
            return Ok(Some(addrs));
        }

        // Stage 2: subscribe to the agent's identity shard topic and wait up to 5 s.
        let runtime = match self.gossip_runtime.as_ref() {
            Some(r) => r,
            None => return Ok(None),
        };
        let shard_topic = shard_topic_for_agent(&agent_id);
        let mut sub = runtime.pubsub().subscribe(shard_topic).await;
        let cache = std::sync::Arc::clone(&self.identity_discovery_cache);
        let machine_cache = std::sync::Arc::clone(&self.machine_discovery_cache);
        let allow_local_scope = self
            .network
            .as_ref()
            .is_some_and(|network| allow_local_discovery_addresses(network.config()));
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);

        loop {
            if tokio::time::Instant::now() >= deadline {
                break;
            }
            let timeout = tokio::time::sleep_until(deadline);
            tokio::select! {
                Some(msg) = sub.recv() => {
                    if let Ok(ann) = deserialize_identity_announcement(&msg.payload) {
                        if ann.verify().is_ok() && ann.agent_id == agent_id {
                            let now = std::time::SystemTime::now()
                                .duration_since(std::time::UNIX_EPOCH)
                                .map_or(0, |d| d.as_secs());
                            let filtered = filter_discovery_announcement_addrs(
                                ann.addresses.iter().copied(),
                                allow_local_scope,
                            );
                            let addrs = filtered.clone();
                            let discovered_agent = DiscoveredAgent {
                                agent_id: ann.agent_id,
                                machine_id: ann.machine_id,
                                user_id: ann.user_id,
                                addresses: filtered,
                                announced_at: ann.announced_at,
                                last_seen: now,
                                machine_public_key: ann.machine_public_key.clone(),
                                nat_type: ann.nat_type.clone(),
                                can_receive_direct: ann.can_receive_direct,
                                is_relay: ann.is_relay,
                                is_coordinator: ann.is_coordinator,
                                reachable_via: ann.reachable_via.clone(),
                                relay_candidates: ann.relay_candidates.clone(),
                                cert_not_after: ann
                                    .agent_certificate
                                    .as_ref()
                                    .and_then(|c| c.not_after()),
                                agent_certificate: ann.agent_certificate.clone(),
                                agent_public_key: ann.agent_public_key.clone(),
                            };
                            upsert_discovered_machine_from_agent(&machine_cache, &discovered_agent)
                                .await;
                            upsert_discovered_agent(&cache, discovered_agent).await;
                            return Ok(Some(addrs));
                        }
                    }
                }
                _ = timeout => break,
            }
        }

        // Stage 3: rendezvous shard subscription — wait up to 5 s.
        // Cache the result so subsequent connect_to_agent / send_direct can find it.
        if let Some(addrs) = self.find_agent_rendezvous(agent_id, 5).await? {
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_or(0, |d| d.as_secs());
            upsert_discovered_agent(
                &cache,
                DiscoveredAgent {
                    agent_id,
                    machine_id: identity::MachineId([0u8; 32]),
                    user_id: None,
                    addresses: addrs.clone(),
                    announced_at: now,
                    last_seen: now,
                    machine_public_key: Vec::new(),
                    nat_type: None,
                    can_receive_direct: None,
                    is_relay: None,
                    is_coordinator: None,
                    reachable_via: Vec::new(),
                    relay_candidates: Vec::new(),
                    cert_not_after: None,
                    agent_certificate: None,
                    agent_public_key: Vec::new(),
                },
            )
            .await;
            return Ok(Some(addrs));
        }

        Ok(None)
    }

    /// Find a machine by ID and return its current endpoint record.
    ///
    /// Performs a cache lookup first, then subscribes to the machine's shard
    /// topic and waits up to `timeout_secs` for a signed machine announcement.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn find_machine(
        &self,
        machine_id: identity::MachineId,
        timeout_secs: u64,
    ) -> error::Result<Option<DiscoveredMachine>> {
        self.start_identity_listener().await?;

        if let Some(machine) = self
            .machine_discovery_cache
            .read()
            .await
            .get(&machine_id)
            .cloned()
        {
            return Ok(Some(machine));
        }

        let runtime = match self.gossip_runtime.as_ref() {
            Some(r) => r,
            None => return Ok(None),
        };
        let shard_topic = shard_topic_for_machine(&machine_id);
        let mut sub = runtime.pubsub().subscribe(shard_topic).await;
        let machine_cache = std::sync::Arc::clone(&self.machine_discovery_cache);
        let allow_local_scope = self
            .network
            .as_ref()
            .is_some_and(|network| allow_local_discovery_addresses(network.config()));
        let deadline =
            tokio::time::Instant::now() + std::time::Duration::from_secs(timeout_secs.clamp(1, 60));

        loop {
            if tokio::time::Instant::now() >= deadline {
                break;
            }
            let timeout = tokio::time::sleep_until(deadline);
            tokio::select! {
                Some(msg) = sub.recv() => {
                    if let Ok(ann) = deserialize_machine_announcement(&msg.payload) {
                        if ann.verify().is_ok() && ann.machine_id == machine_id {
                            let now = std::time::SystemTime::now()
                                .duration_since(std::time::UNIX_EPOCH)
                                .map_or(0, |d| d.as_secs());
                            let filtered = filter_discovery_announcement_addrs(
                                ann.addresses.iter().copied(),
                                allow_local_scope,
                            );
                            let discovered = DiscoveredMachine::from_machine_announcement(
                                &ann,
                                filtered,
                                now,
                            );
                            upsert_discovered_machine(&machine_cache, discovered).await;
                            return Ok(machine_cache.read().await.get(&machine_id).cloned());
                        }
                    }
                }
                _ = timeout => break,
            }
        }

        Ok(None)
    }

    /// Find all discovered agents claiming ownership by the given [`identity::UserId`].
    ///
    /// Only returns agents that announced with `include_user_identity: true`
    /// (i.e., agents whose [`DiscoveredAgent::user_id`] is `Some`).
    ///
    /// # Arguments
    ///
    /// * `user_id` - The user identity to search for
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn find_agents_by_user(
        &self,
        user_id: identity::UserId,
    ) -> error::Result<Vec<DiscoveredAgent>> {
        self.start_identity_listener().await?;
        let cutoff = Self::unix_timestamp_secs().saturating_sub(self.identity_ttl_secs);
        Ok(self
            .identity_discovery_cache
            .read()
            .await
            .values()
            .filter(|a| {
                discovery_record_is_live(a.announced_at, a.last_seen, cutoff)
                    && a.user_id == Some(user_id)
            })
            .cloned()
            .collect())
    }

    /// Return the local socket address this agent's network node is bound to, if any.
    ///
    /// Returns `None` if no network has been configured or if the bind address is
    /// not yet known.
    ///
    /// **Note:** If the node was configured with port 0, this returns port 0.
    /// Use [`bound_addr()`](Self::bound_addr) to get the OS-assigned port.
    #[must_use]
    pub fn local_addr(&self) -> Option<std::net::SocketAddr> {
        self.network.as_ref().and_then(|n| n.local_addr())
    }

    /// Return the actual bound address from the QUIC endpoint.
    ///
    /// Unlike [`local_addr()`](Self::local_addr) which returns the configured value
    /// (possibly port 0), this queries the running endpoint for the real OS-assigned
    /// address. Returns `None` if no network has been configured.
    pub async fn bound_addr(&self) -> Option<std::net::SocketAddr> {
        if let Some(ref network) = self.network {
            let addr = network.bound_addr().await;
            // On dual-stack systems, bound_addr may return [::]:port even when
            // we bound to 127.0.0.1. Normalize to IPv4 if the original config
            // was IPv4.
            match (addr, self.local_addr()) {
                (Some(bound), Some(config)) if config.is_ipv4() && bound.is_ipv6() => {
                    Some(std::net::SocketAddr::new(config.ip(), bound.port()))
                }
                (Some(bound), _) => Some(bound),
                _ => None,
            }
        } else {
            None
        }
    }

    /// Build a signed [`IdentityAnnouncement`] for this agent.
    ///
    /// Delegates to the internal `build_identity_announcement` method.
    ///
    /// # Errors
    ///
    /// Returns an error if key signing fails or human consent is required but not given.
    pub fn build_announcement(
        &self,
        include_user: bool,
        consent: bool,
    ) -> error::Result<IdentityAnnouncement> {
        self.build_identity_announcement(include_user, consent)
    }

    /// Build a signed [`MachineAnnouncement`] for this daemon's transport
    /// endpoint.
    ///
    /// This sync helper uses currently known local interface addresses and
    /// leaves async NAT/reachability fields as `None`; live network announces
    /// populate those fields from `NetworkNode::node_status()`.
    ///
    /// # Errors
    ///
    /// Returns an error if key signing fails.
    pub fn build_machine_announcement(&self) -> error::Result<MachineAnnouncement> {
        build_machine_announcement_for_identity(
            &self.identity,
            self.announcement_addresses(),
            Self::unix_timestamp_secs(),
            None,
            Vec::new(),
            Vec::new(),
            self.network
                .as_ref()
                .is_some_and(|network| allow_local_discovery_addresses(network.config())),
        )
    }

    /// Start the background identity heartbeat task.
    ///
    /// Idempotent — if the heartbeat is already running, returns `Ok(())` immediately.
    /// The heartbeat re-announces this agent's identity at `heartbeat_interval_secs`
    /// intervals so that late-joining peers can discover it without waiting for a
    /// Start the network event reconciliation listener.
    ///
    /// This bridges transport-level peer connect/disconnect events into the
    /// agent-level direct messaging registry so inbound accepted connections are
    /// usable for reverse direct sends before the first inbound direct payload.
    fn start_network_event_listener(&self) {
        if self
            .network_event_listener_started
            .swap(true, std::sync::atomic::Ordering::AcqRel)
        {
            return;
        }

        let Some(network) = self.network.as_ref().map(std::sync::Arc::clone) else {
            return;
        };
        let cache = std::sync::Arc::clone(&self.identity_discovery_cache);
        let dm = std::sync::Arc::clone(&self.direct_messaging);

        let lifecycle_network = std::sync::Arc::clone(&network);
        let lifecycle_dm = std::sync::Arc::clone(&dm);
        let event_token = self.shutdown_token.clone();
        let lifecycle_token = self.shutdown_token.clone();
        let machine_cache = std::sync::Arc::clone(&self.machine_discovery_cache);
        let active_reconnects: ReconnectTracker =
            std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
        // Clones for the lifecycle watcher task (Task 1 moves the originals).
        let lifecycle_machine_cache = std::sync::Arc::clone(&machine_cache);
        let lifecycle_reconnects = std::sync::Arc::clone(&active_reconnects);
        self.spawn_tracked(async move {
            let mut rx = network.subscribe();
            tracing::info!("Network event reconciliation listener started");

            loop {
                let event = tokio::select! {
                    // event_sender is a NetworkNode struct field that outlives
                    // network.shutdown(), so this loop never ended on shutdown
                    // before; the token is what stops it now.
                    _ = event_token.cancelled() => break,
                    recv = rx.recv() => match recv {
                        Ok(event) => event,
                        Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => {
                            tracing::warn!("Network event listener lagged by {skipped} events");
                            continue;
                        }
                        Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                    },
                };

                match event {
                    network::NetworkEvent::PeerConnected { peer_id, .. } => {
                        let machine_id = identity::MachineId(peer_id);
                        let cached_agent_id = {
                            let cache = cache.read().await;
                            cache
                                .values()
                                .find(|entry| entry.machine_id == machine_id)
                                .map(|entry| entry.agent_id)
                        };
                        let agent_id = match cached_agent_id {
                            Some(agent_id) => Some(agent_id),
                            None => dm.lookup_agent(&machine_id).await,
                        };
                        if let Some(agent_id) = agent_id {
                            dm.mark_connected(agent_id, machine_id).await;
                        }
                        // Cancel any pending proactive reconnect for this peer
                        // — the connection is back, no need to keep trying.
                        if let Ok(mut tracker) = active_reconnects.lock() {
                            if let Some(handle) = tracker.remove(&peer_id) {
                                handle.abort();
                            }
                        }
                    }
                    network::NetworkEvent::PeerDisconnected { peer_id, reason } => {
                        let machine_id = identity::MachineId(peer_id);
                        let cached_agent_id = {
                            let cache = cache.read().await;
                            cache
                                .values()
                                .find(|entry| entry.machine_id == machine_id)
                                .map(|entry| entry.agent_id)
                        };
                        let agent_id = match cached_agent_id {
                            Some(agent_id) => Some(agent_id),
                            None => dm.lookup_agent(&machine_id).await,
                        };
                        if let Some(agent_id) = agent_id {
                            dm.mark_disconnected(&agent_id).await;
                        }
                        // Schedule a bounded backoff reconnect only for
                        // transport-level disconnects (idle timeout, remote
                        // daemon restart, network failure). Policy rejection,
                        // pool eviction, admin teardown, revocation, and
                        // shutdown carry a non-transport reason and must never
                        // be redialed — otherwise proactive reconnect undoes a
                        // security/eviction decision (final review P1).
                        if reason.reconnect_eligible() {
                            schedule_reconnect(
                                std::sync::Arc::clone(&network),
                                std::sync::Arc::clone(&machine_cache),
                                event_token.clone(),
                                peer_id,
                                std::sync::Arc::clone(&active_reconnects),
                            );
                        }
                    }
                    _ => {}
                }
            }
        });

        self.spawn_tracked(async move {
            let Some(mut rx) = lifecycle_network.subscribe_all_peer_events().await else {
                tracing::debug!(
                    "Peer lifecycle listener unavailable: network node not initialised"
                );
                return;
            };
            tracing::info!("Peer lifecycle watcher started for direct messaging");
            loop {
                let (peer_id, event) = tokio::select! {
                    _ = lifecycle_token.cancelled() => break,
                    recv = rx.recv() => match recv {
                        Ok(event) => event,
                        Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => {
                            tracing::warn!("Peer lifecycle watcher lagged by {skipped} events");
                            continue;
                        }
                        Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                    },
                };
                let machine_id = identity::MachineId(peer_id.0);
                match event {
                    ant_quic::PeerLifecycleEvent::Established { generation } => {
                        lifecycle_dm.record_lifecycle_established(machine_id, Some(generation));
                    }
                    ant_quic::PeerLifecycleEvent::Replaced { new_generation, .. } => {
                        lifecycle_dm.record_lifecycle_replaced(machine_id, new_generation);
                    }
                    ant_quic::PeerLifecycleEvent::Closing { generation, reason } => {
                        lifecycle_dm.record_lifecycle_blocked(
                            machine_id,
                            Some(generation),
                            format!("closing: {reason}"),
                        );
                    }
                    ant_quic::PeerLifecycleEvent::Closed { generation, reason } => {
                        lifecycle_dm.record_lifecycle_blocked(
                            machine_id,
                            Some(generation),
                            format!("closed: {reason}"),
                        );
                        // Transport-level close (e.g. remote daemon restart, QUIC
                        // idle timeout). Schedule a bounded backoff reconnect so
                        // a known/mDNS-discovered peer is re-dialed without
                        // waiting for a new external trigger. This is the
                        // primary fix for the post-restart transport failure.
                        //
                        // A non-transport disconnect (policy rejection, LRU/idle
                        // eviction, admin, revocation) records a suppression
                        // tombstone *before* it closes the connection, so the
                        // `Closed` event fired by that close must not redial —
                        // this is the second event stream the review flagged.
                        // Genuine transport closes leave no tombstone and are
                        // reconnect-eligible (the named-node restart path).
                        if !lifecycle_network.is_reconnect_suppressed(peer_id.0) {
                            schedule_reconnect(
                                std::sync::Arc::clone(&lifecycle_network),
                                std::sync::Arc::clone(&lifecycle_machine_cache),
                                lifecycle_token.clone(),
                                peer_id.0,
                                std::sync::Arc::clone(&lifecycle_reconnects),
                            );
                        }
                    }
                    ant_quic::PeerLifecycleEvent::ReaderExited { generation } => {
                        tracing::debug!(
                            machine_prefix = %network::hex_prefix(machine_id.as_bytes(), 4),
                            generation,
                            "peer reader exited; waiting for Closed/Established before blocking direct DM"
                        );
                    }
                }
            }
        });
    }

    /// Start the direct message listener background task.
    ///
    /// This task reads raw direct messages from the network layer and
    /// dispatches them to `DirectMessaging::handle_incoming()`, which
    /// fans out to all `subscribe_direct()` receiver queues.
    ///
    /// Called automatically by [`Agent::join_network`].
    fn start_direct_listener(&self) {
        if self
            .direct_listener_started
            .swap(true, std::sync::atomic::Ordering::AcqRel)
        {
            return;
        }

        let Some(network) = self.network.as_ref().map(std::sync::Arc::clone) else {
            return;
        };
        let dm = std::sync::Arc::clone(&self.direct_messaging);
        let discovery_cache = std::sync::Arc::clone(&self.identity_discovery_cache);
        let contact_store = std::sync::Arc::clone(&self.contact_store);
        let revocation_set = std::sync::Arc::clone(&self.revocation_set);
        let token = self.shutdown_token.clone();

        self.spawn_tracked(async move {
            tracing::info!(target: "x0x::direct", stage = "listener", "direct message listener started");
            loop {
                // direct_tx is a NetworkNode struct field that outlives
                // network.shutdown(), so recv_direct() does not return None on
                // shutdown; the token is what stops this loop now.
                let recv = tokio::select! {
                    _ = token.cancelled() => break,
                    r = network.recv_direct() => r,
                };
                let Some((ant_peer_id, payload)) = recv else {
                    tracing::warn!(
                        target: "x0x::direct",
                        stage = "listener",
                        "network.recv_direct channel closed — listener exiting"
                    );
                    break;
                };

                let raw_bytes = payload.len();

                // Parse: first 32 bytes = sender AgentId, rest = payload
                if payload.len() < 32 {
                    tracing::warn!(
                        target: "x0x::direct",
                        stage = "listener",
                        machine_prefix = %crate::logging::LogTransportPeerId::from(&ant_peer_id),
                        raw_bytes,
                        outcome = "drop_too_short",
                        "direct message too short to contain sender id"
                    );
                    continue;
                }

                let mut sender_bytes = [0u8; 32];
                sender_bytes.copy_from_slice(&payload[..32]);
                let sender = identity::AgentId(sender_bytes);
                let machine_id = identity::MachineId(ant_peer_id.0);
                let data = payload[32..].to_vec();
                let payload_bytes = data.len();
                let digest = direct::dm_payload_digest_hex(&data);

                tracing::debug!(
                    target: "dm.trace",
                    stage = "inbound_envelope_received",
                    sender = %hex::encode(sender.as_bytes()),
                    machine_id = %hex::encode(machine_id.as_bytes()),
                    path = "raw_quic",
                    bytes = payload_bytes,
                    raw_bytes,
                    digest = %digest,
                );

                // Verify AgentId→MachineId binding against identity discovery cache.
                let (verified, cert_not_after) = {
                    let cache = discovery_cache.read().await;
                    cache
                        .get(&sender)
                        .map(|entry| (entry.machine_id == machine_id, entry.cert_not_after))
                        .unwrap_or((false, None))
                };

                // Evaluate trust for the (AgentId, MachineId) pair.
                let trust_decision = {
                    let contacts = contact_store.read().await;
                    let evaluator = trust::TrustEvaluator::new(&contacts);
                    let ctx = trust::TrustContext {
                        agent_id: &sender,
                        machine_id: &machine_id,
                    };
                    Some(evaluator.evaluate(&ctx))
                };

                tracing::debug!(
                    target: "dm.trace",
                    stage = "inbound_trust_evaluated",
                    sender = %hex::encode(sender.as_bytes()),
                    machine_id = %hex::encode(machine_id.as_bytes()),
                    path = "raw_quic",
                    verified,
                    decision = ?trust_decision,
                    digest = %digest,
                );

                tracing::info!(
                    target: "x0x::direct",
                    stage = "recv",
                    sender_prefix = %network::hex_prefix(&sender.0, 4),
                    machine_prefix = %network::hex_prefix(&machine_id.0, 4),
                    raw_bytes,
                    payload_bytes,
                    verified,
                    trust_decision = ?trust_decision,
                    "direct message received; dispatching to subscribers"
                );

                // Enforcement point — direct path revocation gate (issue #179).
                // Mirrors EP3 (dm_inbox) + the relay gate (peer_relay). EP5
                // (evict_revoked_subject) purges caches + sets trust=Blocked
                // but does NOT close the live QUIC connection, so without this
                // per-message check a revoked peer on an established direct
                // connection would keep delivering (annotated unverified, but
                // delivered). Fail closed: drop + count, never reach
                // mark_connected/handle_incoming. Read lock is held only for
                // the boolean — no await under it (same contract as EP4).
                let peer_revoked = {
                    let revoked = revocation_set.read().await;
                    direct::inbound_peer_revoked(&revoked, &sender, &machine_id)
                };
                if peer_revoked {
                    dm.record_incoming_dropped_revoked();
                    tracing::info!(
                        target: "x0x::direct",
                        stage = "recv",
                        sender_prefix = %network::hex_prefix(&sender.0, 4),
                        machine_prefix = %network::hex_prefix(&machine_id.0, 4),
                        outcome = "drop_revoked",
                        "direct message from revoked sender dropped (direct-path revocation gate, mirrors EP3)"
                    );
                    continue;
                }
                // Enforcement — runtime cert-expiry gate (issue #191). EP1
                // drops expired announcements at ingest, but a previously
                // cached entry is never re-checked on the live path; without
                // this an expired peer stays trusted until TTL eviction. Fail
                // closed: drop + count, mirroring the revoked EP above.
                // Absent expiry (None) is fail-open — is_expired returns false
                // for pre-#130 peers that carry no not_after.
                if identity::is_expired(cert_not_after, Agent::unix_timestamp_secs()) {
                    dm.record_incoming_dropped_expired();
                    tracing::info!(
                        target: "x0x::direct",
                        stage = "recv",
                        sender_prefix = %network::hex_prefix(&sender.0, 4),
                        machine_prefix = %network::hex_prefix(&machine_id.0, 4),
                        outcome = "drop_expired",
                        "direct message from sender with expired cert dropped (runtime expiry gate, issue #191)"
                    );
                    continue;
                }

                // Register and mark the sender as connected for future reverse direct sends.
                dm.mark_connected(sender, machine_id).await;

                // Fan out to all subscribe_direct() receivers with verification info.
                let delivered = dm
                    .handle_incoming(machine_id, sender, data, verified, trust_decision)
                    .await;

                tracing::debug!(
                    target: "dm.trace",
                    stage = "inbound_broadcast_published",
                    sender = %hex::encode(sender.as_bytes()),
                    machine_id = %hex::encode(machine_id.as_bytes()),
                    path = "raw_quic",
                    delivered,
                    subscribers = dm.subscriber_count(),
                    digest = %digest,
                );

                tracing::debug!(
                    target: "x0x::direct",
                    stage = "recv",
                    sender_prefix = %network::hex_prefix(&sender.0, 4),
                    payload_bytes,
                    subscriber_count = dm.subscriber_count(),
                    "direct message dispatched"
                );
            }
        });
    }

    // === Tailnet byte-streams (#132 T1) ===

    /// Open a bidirectional byte-stream to a verified, trusted peer.
    ///
    /// Resolves `agent_id` → machine via the identity discovery cache, then
    /// enforces the identity gate (verified binding → not revoked → trust
    /// `Accept`) before asking ant-quic to open the stream. The protocol
    /// prefix is written immediately after `open_bi` so the accept side can
    /// demux. Returns a [`streams::PeerStream`] ready for application I/O.
    pub async fn open_peer_stream(
        &self,
        agent_id: &identity::AgentId,
        protocol: streams::StreamProtocol,
    ) -> error::NetworkResult<streams::PeerStream> {
        let (machine_id, cert_not_after) = {
            let cache = self.identity_discovery_cache.read().await;
            cache
                .get(agent_id)
                .map(|entry| (entry.machine_id, entry.cert_not_after))
                .ok_or(error::NetworkError::PeerNotVerified {
                    agent_id: agent_id.0,
                })?
        };
        // Runtime cert-expiry gate (issue #191): EP1 drops expired
        // announcements at ingest but never re-checks a cached entry on the
        // live path. Absent expiry (None) is fail-open — is_expired returns
        // false, preserving compatibility with pre-#130 peers.
        let expired = identity::is_expired(cert_not_after, Self::unix_timestamp_secs());

        let trust_decision = {
            let contacts = self.contact_store.read().await;
            let evaluator = trust::TrustEvaluator::new(&contacts);
            Some(evaluator.evaluate(&trust::TrustContext {
                agent_id,
                machine_id: &machine_id,
            }))
        };
        let (revoked_agent, revoked_machine) = {
            let revoked = self.revocation_set.read().await;
            (
                revoked.is_agent_revoked(agent_id),
                revoked.is_machine_revoked(&machine_id),
            )
        };
        streams::stream_gate(
            agent_id,
            trust_decision,
            revoked_agent,
            revoked_machine,
            expired,
        )?;

        let network = self
            .network
            .as_ref()
            .ok_or_else(|| error::NetworkError::NodeError("network not initialized".to_string()))?;
        let peer = ant_quic::PeerId(machine_id.0);
        let (mut send, recv) = network.open_bi(&peer).await?;
        streams::write_protocol_prefix(&mut send, protocol).await?;
        tracing::info!(
            target: "x0x::streams",
            agent = %hex::encode(agent_id.as_bytes()),
            machine = %hex::encode(machine_id.as_bytes()),
            protocol = ?protocol,
            "outbound peer stream opened (identity gate cleared)"
        );
        Ok(streams::PeerStream::new(
            vec![*agent_id],
            machine_id,
            protocol,
            send,
            recv,
        ))
    }

    /// Await the next inbound byte-stream that has cleared the identity gate.
    ///
    /// Returns `None` when the accept loop has stopped (e.g. after shutdown).
    /// The T4 forwarder consumes accepted streams through this method.
    pub async fn next_incoming_stream(&self) -> Option<streams::PeerStream> {
        let mut rx = self.stream_accept.receiver().lock().await;
        rx.recv().await
    }

    /// Start the inbound byte-stream accept loop (idempotent).
    ///
    /// Called automatically by [`Agent::join_network`]. The loop is the SOLE
    /// consumer of [`network::NetworkNode::accept_bi`]; every inbound stream
    /// clears the identity gate (machine has a known agent → not revoked →
    /// trust `Accept`) and the protocol handshake before being surfaced via
    /// [`Self::next_incoming_stream`]. A stream that fails the gate is reset
    /// (its halves are dropped) with zero application bytes exchanged.
    fn start_stream_accept_loop(&self) {
        if !self.stream_accept.start_once() {
            return;
        }
        let Some(network) = self.network.as_ref().map(std::sync::Arc::clone) else {
            return;
        };
        let discovery_cache = std::sync::Arc::clone(&self.identity_discovery_cache);
        let contact_store = std::sync::Arc::clone(&self.contact_store);
        let revocation_set = std::sync::Arc::clone(&self.revocation_set);
        let incoming = std::sync::Arc::clone(&self.stream_accept);
        let token = self.shutdown_token.clone();

        self.spawn_tracked(async move {
            tracing::info!(target: "x0x::streams", "byte-stream accept loop started");
            loop {
                let accepted = tokio::select! {
                    _ = token.cancelled() => break,
                    r = network.accept_bi() => r,
                };
                let (ant_peer_id, send, mut recv) = match accepted {
                    Ok(triple) => triple,
                    Err(e) => {
                        tracing::warn!(target: "x0x::streams", error=%e, "accept_bi failed; continuing");
                        continue;
                    }
                };
                let machine_id = identity::MachineId(ant_peer_id.0);

                // Identity gate — resolve ALL agents on this machine from
                // the discovery cache, then check each (revoked → trust).
                // The QUIC transport authenticates the machine, not the
                // specific agent, so every agent on the machine must clear
                // the gate — a single revoked or untrusted agent denies the
                // stream (fail-closed, #192). Each lock is taken in its own
                // scope so no two identity locks are held at once
                // (evict_revoked_subject takes them in a different order).
                let agents: Vec<(identity::AgentId, Option<u64>)> = {
                    let cache = discovery_cache.read().await;
                    let mut found: Vec<(identity::AgentId, Option<u64>)> = cache
                        .values()
                        .filter(|a| a.machine_id == machine_id)
                        .map(|a| (a.agent_id, a.cert_not_after))
                        .collect();
                    // Deterministic order so logging / per-peer concurrency
                    // keying are stable across HashMap iteration orders.
                    found.sort_by_key(|(a, _)| a.0);
                    found
                };
                if agents.is_empty() {
                    tracing::info!(
                        target: "x0x::streams",
                        machine = %hex::encode(machine_id.as_bytes()),
                        outcome = "deny_not_verified",
                        "inbound stream from machine with no known agent — denied"
                    );
                    continue;
                }
                let now_secs = Agent::unix_timestamp_secs();
                let mut gate_denied: Option<(identity::AgentId, error::NetworkError)> = None;
                for (agent_id, cert_not_after) in &agents {
                    // Runtime cert-expiry gate (issue #191): a cached entry
                    // whose cert has expired must be refused on the live path.
                    let expired = identity::is_expired(*cert_not_after, now_secs);
                    let trust_decision = {
                        let contacts = contact_store.read().await;
                        let evaluator = trust::TrustEvaluator::new(&contacts);
                        Some(evaluator.evaluate(&trust::TrustContext {
                            agent_id,
                            machine_id: &machine_id,
                        }))
                    };
                    let (revoked_agent, revoked_machine) = {
                        let revoked = revocation_set.read().await;
                        (
                            revoked.is_agent_revoked(agent_id),
                            revoked.is_machine_revoked(&machine_id),
                        )
                    };
                    if let Err(e) = streams::stream_gate(
                        agent_id,
                        trust_decision,
                        revoked_agent,
                        revoked_machine,
                        expired,
                    ) {
                        gate_denied = Some((*agent_id, e));
                        break;
                    }
                }
                if let Some((agent_id, e)) = gate_denied {
                    tracing::info!(
                        target: "x0x::streams",
                        agent = %hex::encode(agent_id.as_bytes()),
                        machine = %hex::encode(machine_id.as_bytes()),
                        agent_count = agents.len(),
                        outcome = "deny_gate",
                        error = %e,
                        "inbound stream denied at identity gate (one agent on the machine failed)"
                    );
                    continue;
                }

                // Gate cleared for every agent — drop the expiry metadata and
                // keep the ordered agent list for the stream handle.
                let agents: Vec<identity::AgentId> =
                    agents.into_iter().map(|(a, _)| a).collect();

                // DISPATCH (DoS hardening, issue #132): the protocol-prefix
                // read + surfacing run in a per-stream task so a peer that
                // opens a stream and never sends the prefix cannot block this
                // accept loop (and thus every other peer's inbound streams).
                // The identity gate above already cleared; this task owns the
                // stream halves and drops them (→ QUIC reset) on any failure.
                let incoming_for_task = std::sync::Arc::clone(&incoming);
                tokio::spawn(async move {
                    // Belt-and-braces: bound the prefix read so a silent peer
                    // holds the task/stream for at most PREFIX_READ_TIMEOUT.
                    let protocol = match tokio::time::timeout(
                        streams::PREFIX_READ_TIMEOUT,
                        streams::read_protocol_prefix(&mut recv),
                    )
                    .await
                    {
                        Ok(Ok(p)) => p,
                        Ok(Err(e)) => {
                            tracing::info!(
                                target: "x0x::streams",
                                machine = %hex::encode(machine_id.as_bytes()),
                                outcome = "deny_protocol",
                                error = %e,
                                "inbound stream protocol prefix rejected"
                            );
                            return;
                        }
                        Err(_) => {
                            tracing::info!(
                                target: "x0x::streams",
                                machine = %hex::encode(machine_id.as_bytes()),
                                outcome = "deny_prefix_timeout",
                                "inbound stream prefix byte timed out — resetting"
                            );
                            return;
                        }
                    };
                    let peer_stream =
                        streams::PeerStream::new(agents, machine_id, protocol, send, recv);
                    // try_send so a slow consumer cannot pile up accepted
                    // streams in memory; a full channel drops the stream.
                    if incoming_for_task.sender().try_send(peer_stream).is_err() {
                        tracing::debug!(
                            target: "x0x::streams",
                            "incoming-stream channel full; dropping accepted stream"
                        );
                    }
                });
            }
        });
    }

    /// new announcement.
    ///
    /// Called automatically by [`Agent::join_network`].
    ///
    /// # Errors
    ///
    /// Returns an error if a required network or gossip component is missing.
    pub async fn start_identity_heartbeat(&self) -> error::Result<()> {
        let mut handle_guard = self.heartbeat_handle.lock().await;
        // Shutdown race (issue #116): a still-bootstrapping join_network can call
        // this after shutdown() began. Checking under the SAME lock that
        // stop_identity_heartbeat takes the handle from makes it TOCTOU-free:
        // stop_X runs after cancel(), so a handle stored before stop_X runs is
        // taken+aborted, and a store attempted after sees cancelled → refused.
        if self.shutdown_token.is_cancelled() {
            return Ok(());
        }
        if handle_guard.is_some() {
            return Ok(());
        }
        let Some(runtime) = self.gossip_runtime.as_ref().map(std::sync::Arc::clone) else {
            return Err(error::IdentityError::Storage(std::io::Error::other(
                "gossip runtime not initialized — cannot start heartbeat",
            )));
        };
        let Some(network) = self.network.as_ref().map(std::sync::Arc::clone) else {
            return Err(error::IdentityError::Storage(std::io::Error::other(
                "network not initialized — cannot start heartbeat",
            )));
        };
        let allow_local_discovery_addrs = allow_local_discovery_addresses(network.config());
        let ctx = HeartbeatContext {
            identity: std::sync::Arc::clone(&self.identity),
            runtime,
            network,
            interval_secs: self.heartbeat_interval_secs,
            cache: std::sync::Arc::clone(&self.identity_discovery_cache),
            machine_cache: std::sync::Arc::clone(&self.machine_discovery_cache),
            user_identity_consented: std::sync::Arc::clone(&self.user_identity_consented),
            allow_local_discovery_addrs,
            revocation_set: std::sync::Arc::clone(&self.revocation_set),
        };
        let handle = tokio::task::spawn(async move {
            let mut ticker =
                tokio::time::interval(std::time::Duration::from_secs(ctx.interval_secs));
            ticker.tick().await; // skip first immediate tick
            loop {
                ticker.tick().await;
                if let Err(e) = ctx.announce().await {
                    tracing::warn!("identity heartbeat announce failed: {e}");
                }
            }
        });
        *handle_guard = Some(handle);
        Ok(())
    }

    /// Publish a rendezvous `ProviderSummary` for this agent.
    ///
    /// Enables global findability across gossip overlay partitions.  Seekers
    /// that have never been on the same partition as this agent can still
    /// discover it by subscribing to the rendezvous shard topic and waiting
    /// for the next heartbeat advertisement.
    ///
    /// The summary is signed with this agent's machine key and contains the
    /// agent's reachability addresses in the `extensions` field (bincode-encoded
    /// `Vec<SocketAddr>`).
    ///
    /// # Re-advertisement contract
    ///
    /// Rendezvous summaries expire after `validity_ms` milliseconds.  **Callers
    /// are responsible for calling `advertise_identity` again before expiry** so
    /// that seekers can always find a fresh record.  A common strategy is to
    /// re-advertise every `validity_ms / 2`.  The `x0xd` daemon does this
    /// automatically via its background re-advertisement task.
    ///
    /// # Arguments
    ///
    /// * `validity_ms` — How long (milliseconds) before the summary expires.
    ///   After this time, seekers will no longer discover this agent via rendezvous
    ///   unless a fresh `advertise_identity` call is made.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized, serialization
    /// fails, or signing fails.
    pub async fn advertise_identity(&self, validity_ms: u64) -> error::Result<()> {
        use saorsa_gossip_rendezvous::{Capability, ProviderSummary};

        let runtime = self.gossip_runtime.as_ref().ok_or_else(|| {
            error::IdentityError::Storage(std::io::Error::other(
                "gossip runtime not initialized — cannot advertise identity",
            ))
        })?;

        let peer_id = runtime.peer_id();
        let addresses = self.announcement_addresses();
        let addr_bytes = bincode::serialize(&addresses).map_err(|e| {
            error::IdentityError::Serialization(format!(
                "failed to serialize addresses for rendezvous: {e}"
            ))
        })?;

        let mut summary = ProviderSummary::new(
            self.agent_id().0,
            peer_id,
            vec![Capability::Identity],
            validity_ms,
        )
        .with_extensions(addr_bytes);

        summary
            .sign_raw(self.identity.machine_keypair().secret_key().as_bytes())
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "failed to sign rendezvous summary: {e}"
                )))
            })?;

        let cbor_bytes = summary.to_cbor().map_err(|e| {
            error::IdentityError::Serialization(format!(
                "failed to CBOR-encode rendezvous summary: {e}"
            ))
        })?;

        let topic = rendezvous_shard_topic_for_agent(&self.agent_id());
        runtime
            .pubsub()
            .publish(topic, bytes::Bytes::from(cbor_bytes))
            .await
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "failed to publish rendezvous summary: {e}"
                )))
            })?;

        self.rendezvous_advertised
            .store(true, std::sync::atomic::Ordering::Relaxed);
        Ok(())
    }

    /// Search for an agent via rendezvous shard subscription.
    ///
    /// Subscribes to the rendezvous shard topic for `agent_id` and waits up to
    /// `timeout_secs` for a matching [`saorsa_gossip_rendezvous::ProviderSummary`].
    /// On success the addresses encoded in the summary `extensions` field are
    /// returned.
    ///
    /// This is Stage 3 of [`Agent::find_agent`]'s lookup cascade.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn find_agent_rendezvous(
        &self,
        agent_id: identity::AgentId,
        timeout_secs: u64,
    ) -> error::Result<Option<Vec<std::net::SocketAddr>>> {
        use saorsa_gossip_rendezvous::ProviderSummary;

        let runtime = match self.gossip_runtime.as_ref() {
            Some(r) => r,
            None => return Ok(None),
        };

        let topic = rendezvous_shard_topic_for_agent(&agent_id);
        let mut sub = runtime.pubsub().subscribe(topic).await;
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);

        loop {
            if tokio::time::Instant::now() >= deadline {
                break;
            }
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            tokio::select! {
                Some(msg) = sub.recv() => {
                    let summary = match ProviderSummary::from_cbor(&msg.payload) {
                        Ok(s) => s,
                        Err(_) => continue,
                    };
                    if summary.target != agent_id.0 {
                        continue;
                    }
                    // Verify the summary signature when the advertiser's machine
                    // public key is cached from a prior identity announcement.
                    // Without a cached key we still accept the addresses — they
                    // are connection hints only; the subsequent QUIC handshake will
                    // fail cryptographically if the endpoint is not the genuine agent.
                    let cached_pub = self
                        .identity_discovery_cache
                        .read()
                        .await
                        .get(&agent_id)
                        .map(|e| e.machine_public_key.clone());
                    if let Some(pub_bytes) = cached_pub {
                        if !pub_bytes.is_empty()
                            && !summary.verify_raw(&pub_bytes).unwrap_or(false)
                        {
                            tracing::warn!(
                                "Rendezvous summary signature verification failed for agent {:?}; discarding",
                                agent_id
                            );
                            continue;
                        }
                    }
                    // Decode addresses from the extensions field.
                    let addrs: Vec<std::net::SocketAddr> = summary
                        .extensions
                        .as_deref()
                        .and_then(|b| {
                            use bincode::Options;
                            bincode::DefaultOptions::new()
                                .with_fixint_encoding()
                                .with_limit(crate::network::MAX_MESSAGE_DESERIALIZE_SIZE)
                                .deserialize(b)
                                .ok()
                        })
                        .unwrap_or_default();
                    if !addrs.is_empty() {
                        return Ok(Some(addrs));
                    }
                }
                _ = tokio::time::sleep(remaining) => break,
            }
        }

        Ok(None)
    }

    /// Insert a discovered agent into the cache (for testing only).
    ///
    /// Insert a [`dm::DmCapabilities`] entry for `agent_id` / `machine_id`
    /// into the local capability store, bypassing the gossip-advert pipeline.
    ///
    /// # Visibility
    ///
    /// `#[doc(hidden)]` - tests-only seam. Production callers must rely on
    /// the live capability-advert subscription so the store mirrors what
    /// the network actually advertises.
    ///
    /// # Arguments
    ///
    /// * `agent_id` - Subject agent the capabilities apply to.
    /// * `machine_id` - Subject machine. Used by the store's lookup path
    ///   to disambiguate when an agent is reachable via multiple machines.
    /// * `capabilities` - The [`dm::DmCapabilities`] record (KEM public
    ///   key, gossip-inbox readiness, envelope-size cap, etc.) the sender
    ///   should treat as authoritative.
    #[doc(hidden)]
    pub fn insert_capability_for_testing(
        &self,
        agent_id: identity::AgentId,
        machine_id: identity::MachineId,
        capabilities: dm::DmCapabilities,
    ) {
        self.capability_store
            .insert(agent_id, machine_id, capabilities, dm::now_unix_ms());
    }

    /// # Arguments
    ///
    /// * `agent` - The agent entry to insert.
    #[doc(hidden)]
    pub async fn insert_discovered_agent_for_testing(&self, agent: DiscoveredAgent) {
        let agent_id = agent.agent_id;
        let machine_id = agent.machine_id;
        upsert_discovered_machine_from_agent(&self.machine_discovery_cache, &agent).await;
        upsert_discovered_agent(&self.identity_discovery_cache, agent).await;

        if machine_id.0 != [0u8; 32] {
            self.direct_messaging
                .register_agent(agent_id, machine_id)
                .await;
            if let Some(ref network) = self.network {
                let ant_peer_id = ant_quic::PeerId(machine_id.0);
                if network.is_connected(&ant_peer_id).await {
                    self.direct_messaging
                        .mark_connected(agent_id, machine_id)
                        .await;
                }
            }
        }
    }

    /// Test-only: mark `agent_id` as a `Trusted` contact so
    /// [`TrustEvaluator`] returns [`trust::TrustDecision::Accept`] for it.
    /// Used by the tailnet stream tests to clear the outbound/inbound trust
    /// gate without driving the full contact-import REST flow. The
    /// AgentId→MachineId *binding* still has to come from the discovery cache
    /// (see [`Self::insert_discovered_agent_for_testing`]).
    #[doc(hidden)]
    pub async fn set_contact_trusted_for_testing(&self, agent_id: identity::AgentId) {
        let mut store = self.contact_store.write().await;
        store.add(contacts::Contact {
            agent_id,
            trust_level: contacts::TrustLevel::Trusted,
            label: None,
            added_at: 0,
            last_seen: None,
            identity_type: contacts::IdentityType::Anonymous,
            machines: Vec::new(),
            dm_capabilities: None,
        });
    }

    /// Push a synthetic [`peer_relay::RelayedDm`] onto this Agent's inbound
    /// relay-DM channel, exactly as the wire demuxer would after receiving a
    /// [`network::RELAYED_DM_STREAM_TYPE`] frame. Drives the
    /// `spawn_relay_dm_listener` dispatch path (revocation gate →
    /// deliver-locally / forward / refuse) without a second live QUIC peer.
    ///
    /// `#[doc(hidden)]` - tests-only seam. The production inbound path is the
    /// network receiver task; this exists only because
    /// [`network::NetworkNode::send_direct_typed`] and the relay-DM channel
    /// sender are `pub(crate)`, so an out-of-crate integration test cannot
    /// otherwise exercise the recipient-side listener.
    ///
    /// # Arguments
    ///
    /// * `from_peer` - the QUIC peer the frame nominally arrived on (the
    ///   relay hop, or the origin for a self-addressed `RelayedDm`).
    /// * `relayed` - the fully-formed relayed envelope to dispatch.
    ///
    /// Returns `false` when no network is configured (nothing to receive on).
    #[doc(hidden)]
    pub async fn push_relayed_dm_for_testing(
        &self,
        from_peer: ant_quic::PeerId,
        relayed: peer_relay::RelayedDm,
    ) -> bool {
        let Some(ref network) = self.network else {
            return false;
        };
        let sender_agent_id = relayed.header.sender_agent_id;
        network
            .test_relayed_dm_sender()
            .send((from_peer, sender_agent_id, relayed))
            .await
            .is_ok()
    }

    /// Create a new collaborative task list bound to a topic.
    ///
    /// Creates a new `TaskList` and binds it to the specified gossip topic
    /// for automatic synchronization with other agents on the same topic.
    ///
    /// # Arguments
    ///
    /// * `name` - Human-readable name for the task list
    /// * `topic` - Gossip topic for synchronization
    ///
    /// # Returns
    ///
    /// A `TaskListHandle` for interacting with the task list.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let list = agent.create_task_list("Sprint Planning", "team-sprint").await?;
    /// ```
    pub async fn create_task_list(&self, name: &str, topic: &str) -> error::Result<TaskListHandle> {
        let runtime = self.gossip_runtime.as_ref().ok_or_else(|| {
            error::IdentityError::Storage(std::io::Error::other(
                "gossip runtime not initialized - configure agent with network first",
            ))
        })?;

        let peer_id = runtime.peer_id();
        // The id MUST derive from the shared topic alone (not name/agent_id) so
        // every replica of this list agrees on it — it is the attestation scope
        // bound into claim/complete signatures. See TaskListId::from_topic.
        let list_id = crdt::TaskListId::from_topic(topic);
        let task_list = crdt::TaskList::new(list_id, name.to_string(), peer_id);

        let sync = crdt::TaskListSync::new(
            task_list,
            std::sync::Arc::clone(runtime.pubsub()),
            topic.to_string(),
            peer_id,
        )
        .map_err(|e| {
            error::IdentityError::Storage(std::io::Error::other(format!(
                "task list sync creation failed: {}",
                e
            )))
        })?;

        let sync = std::sync::Arc::new(sync);
        sync.start_with_spawner(|fut| self.spawn_tracked(fut))
            .await
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "task list sync start failed: {}",
                    e
                )))
            })?;

        Ok(TaskListHandle {
            sync,
            agent_id: self.agent_id(),
            peer_id,
            replica_epoch: TaskListHandle::fresh_epoch(),
            signing: std::sync::Arc::new(gossip::SigningContext::from_keypair(
                self.identity.agent_keypair(),
            )),
        })
    }

    /// Join an existing task list by topic.
    ///
    /// Connects to a task list that was created by another agent on the
    /// specified topic. The local replica will sync with peers automatically.
    ///
    /// # Arguments
    ///
    /// * `topic` - Gossip topic for the task list
    ///
    /// # Returns
    ///
    /// A `TaskListHandle` for interacting with the task list.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let list = agent.join_task_list("team-sprint").await?;
    /// ```
    pub async fn join_task_list(&self, topic: &str) -> error::Result<TaskListHandle> {
        let runtime = self.gossip_runtime.as_ref().ok_or_else(|| {
            error::IdentityError::Storage(std::io::Error::other(
                "gossip runtime not initialized - configure agent with network first",
            ))
        })?;

        let peer_id = runtime.peer_id();
        // Create empty task list; it will be populated via delta sync. The id
        // MUST match the creator's — derive it from the shared topic alone (see
        // create_task_list / TaskListId::from_topic), otherwise the scope bound
        // into remote claim attestations won't verify and claims never converge.
        let list_id = crdt::TaskListId::from_topic(topic);
        let task_list = crdt::TaskList::new(list_id, String::new(), peer_id);

        let sync = crdt::TaskListSync::new(
            task_list,
            std::sync::Arc::clone(runtime.pubsub()),
            topic.to_string(),
            peer_id,
        )
        .map_err(|e| {
            error::IdentityError::Storage(std::io::Error::other(format!(
                "task list sync creation failed: {}",
                e
            )))
        })?;

        let sync = std::sync::Arc::new(sync);
        sync.start_with_spawner(|fut| self.spawn_tracked(fut))
            .await
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "task list sync start failed: {}",
                    e
                )))
            })?;

        Ok(TaskListHandle {
            sync,
            agent_id: self.agent_id(),
            peer_id,
            replica_epoch: TaskListHandle::fresh_epoch(),
            signing: std::sync::Arc::new(gossip::SigningContext::from_keypair(
                self.identity.agent_keypair(),
            )),
        })
    }
}

// ─── Proactive peer reconnect (post-disconnect / post-restart) ──────────────

/// Exponential backoff delays for proactive reconnect attempts after a known
/// peer disconnects. Each delay is the wait *before* the attempt, so the first
/// attempt fires after 1 s — fast enough for a daemon restart on the same host
/// while avoiding a tight retry loop on a genuinely-down peer.
const RECONNECT_BACKOFF_DELAYS: &[std::time::Duration] = &[
    std::time::Duration::from_secs(1),
    std::time::Duration::from_secs(2),
    std::time::Duration::from_secs(4),
    std::time::Duration::from_secs(8),
    std::time::Duration::from_secs(16),
];

/// After a reconnect sequence exhausts all attempts WITHOUT reconnecting, hold
/// the single-flight tracker slot for this long before releasing it. A
/// genuinely dead/unreachable peer keeps emitting transport-close lifecycle
/// events; without this cooldown each one immediately re-triggers a new
/// reconnect sequence, and every attempt drives ant-quic NAT
/// traversal/hole-punch to the dead endpoint — a tight loop that accumulates
/// connection state and leaks memory (~1 MB/s observed on a churning mesh).
/// Holding the slot means the existing single-flight guard suppresses
/// re-scheduling for the cooldown window. A real recovery (PeerConnected)
/// removes+aborts the entry, ending the cooldown immediately.
const RECONNECT_FAILURE_COOLDOWN: std::time::Duration = std::time::Duration::from_secs(60);

/// Whether a discovered peer's identity announcement should trigger an
/// auto-connect dial.
///
/// Returns `false` when the peer's reconnect is suppressed — it was revoked,
/// policy-rejected, admin-disconnected, or capacity-evicted — so that a
/// suppressed peer which keeps broadcasting identity announcements is not
/// silently reconnected (which would undo the security/eviction decision), and
/// `false` when the peer is already connected. Extracted as a pure predicate so
/// the security invariant is unit-testable independently of the gossip stack.
fn announcement_should_auto_connect(reconnect_suppressed: bool, already_connected: bool) -> bool {
    !reconnect_suppressed && !already_connected
}

/// Minimum interval between auto-connect dials to the same announcing agent.
///
/// A peer that announces but is unreachable (behind NAT, blackholed, or dead
/// with its announcements still circulating) would otherwise be redialed on
/// EVERY received announcement copy — and rebroadcast fan-out delivers each
/// fresh announcement many times within seconds. Every failed dial drives
/// ant-quic NAT traversal/hole-punch and accumulates connection state
/// (~2.5 MB per failed dial measured on a loopback replay repro), which is
/// unbounded growth on a churning mesh. One dial per cooldown window per agent
/// bounds that; a first-ever announcement still dials immediately.
const ANNOUNCEMENT_AUTO_CONNECT_RETRY_COOLDOWN: std::time::Duration =
    std::time::Duration::from_secs(60);

/// Whether the per-agent auto-connect rate limit allows another dial attempt.
///
/// Pure so the anti-storm invariant (at most one dial per
/// [`ANNOUNCEMENT_AUTO_CONNECT_RETRY_COOLDOWN`] per agent) is unit-testable
/// independently of the gossip stack.
fn announcement_auto_connect_retry_allowed(
    last_attempt: Option<std::time::Instant>,
    now: std::time::Instant,
) -> bool {
    last_attempt.is_none_or(|last| {
        now.saturating_duration_since(last) >= ANNOUNCEMENT_AUTO_CONNECT_RETRY_COOLDOWN
    })
}

/// Apply bounded ±20% random jitter to a reconnect backoff delay.
///
/// Fixed backoff delays cause N peers that disconnected together (e.g. a shared
/// bootstrap node restart) to redial in lockstep, producing synchronized
/// connection storms. Scaling each delay by a random factor in `[0.8, 1.2)`
/// decorrelates those redials while preserving the intended exponential
/// backoff shape. The jitter is for load-spreading only, so a fast non-crypto
/// RNG is sufficient.
fn jittered_backoff_delay(delay: std::time::Duration) -> std::time::Duration {
    // factor ∈ [0.8, 1.2): rand::random::<f64>() yields [0.0, 1.0).
    let factor = 0.8 + rand::random::<f64>() * 0.4;
    delay.mul_f64(factor)
}

/// Type alias for the single-flight reconnect tracker shared between the
/// network-event listener and the peer-lifecycle watcher.
type ReconnectTracker = std::sync::Arc<
    std::sync::Mutex<std::collections::HashMap<[u8; 32], tokio::task::JoinHandle<()>>>,
>;

/// Schedule a bounded, backoff reconnect for a peer that just disconnected.
///
/// This closes the gap identified in the post-restart transport failure: when a
/// known/mDNS-discovered peer's direct QUIC connection drops (daemon restart,
/// transport idle timeout), x0x previously observed the disconnect and did
/// nothing — no redial. CRDT state requests then exhausted against a peer that
/// was still mDNS-visible.
///
/// The spawned task:
/// - Tries **discovery-cache addresses** first (these include LAN/loopback
///   when `allow_local_scope`, which the public-only bootstrap cache drops).
/// - Falls back to **bootstrap-cache addresses** via `connect_cached_peer`.
///   The bootstrap cache retains the raw connection address (including
///   LAN/loopback) from every successful connect/accept, so Phase 2 covers
///   the default global-bootstrap config where `allow_local_scope=FALSE`
///   filters loopback out of the discovery cache (CR-HOST-1).
/// - Self-cancels when the peer reconnects (checked via `is_connected` on each
///   attempt) or when the shutdown token fires.
/// - Is **single-flight** per peer: only one reconnect task runs at a time,
///   tracked in `active_reconnects`. A `PeerConnected` event aborts the pending
///   task.
/// - Is **bounded** to `RECONNECT_BACKOFF_DELAYS.len()` attempts with
///   exponential backoff, preventing reconnect storms.
fn schedule_reconnect(
    network: std::sync::Arc<network::NetworkNode>,
    machine_cache: std::sync::Arc<
        tokio::sync::RwLock<std::collections::HashMap<identity::MachineId, DiscoveredMachine>>,
    >,
    shutdown_token: tokio_util::sync::CancellationToken,
    peer_id_bytes: [u8; 32],
    active_reconnects: ReconnectTracker,
) {
    // Defense in depth: never schedule a reconnect for a peer whose redial is
    // suppressed (revocation, policy rejection, admin teardown, capacity
    // eviction). The call sites already gate on this, but re-checking here
    // keeps the scheduler authoritative if a future call site forgets — a
    // suppressed peer must never be proactively redialed.
    if network.is_reconnect_suppressed(peer_id_bytes) {
        return;
    }

    // Single-flight: hold the lock across check + spawn + insert so two
    // concurrent callers cannot both start a reconnect for the same peer.
    let mut tracker = match active_reconnects.lock() {
        Ok(t) => t,
        Err(_) => return,
    };
    if tracker.contains_key(&peer_id_bytes) {
        return;
    }

    let tracker_clone = std::sync::Arc::clone(&active_reconnects);
    let handle = tokio::spawn(async move {
        let peer_id = ant_quic::PeerId(peer_id_bytes);
        let machine_id = identity::MachineId(peer_id_bytes);
        let prefix = network::hex_prefix(&peer_id_bytes, 4);

        // Candidate discovery-cache addresses are refreshed on every attempt
        // (see the per-attempt read inside the loop) so a named daemon that
        // restarted on a different ephemeral port is rediscovered once it
        // re-announces, rather than pinned to a stale one-time snapshot.
        tracing::info!(
            target: "x0x::connect",
            peer_id_prefix = %prefix,
            "scheduling proactive reconnect for disconnected peer",
        );

        'attempts: for (attempt, &delay) in RECONNECT_BACKOFF_DELAYS.iter().enumerate() {
            // Wait with cancellation before each attempt. Apply bounded jitter
            // so peers that disconnected together do not redial in lockstep.
            tokio::select! {
                _ = shutdown_token.cancelled() => break,
                _ = tokio::time::sleep(jittered_backoff_delay(delay)) => {}
            }

            // Re-check suppression on every attempt: a peer that was revoked,
            // policy-rejected, admin-disconnected, or evicted *during* the
            // backoff sequence must stop being redialed mid-flight. Re-checked
            // again immediately before each dial below, since the intervening
            // `is_connected`/cache-read awaits give a concurrent
            // `disconnect_with_reason` a window to set the tombstone.
            if network.is_reconnect_suppressed(peer_id_bytes) {
                tracing::debug!(
                    target: "x0x::connect",
                    peer_id_prefix = %prefix,
                    attempt,
                    "reconnect cancelled: peer reconnect-suppressed",
                );
                break;
            }

            // Another path (mDNS auto-connect, inbound dial, announcement
            // auto-connect) may have already recovered the connection.
            if network.is_connected(&peer_id).await {
                tracing::debug!(
                    target: "x0x::connect",
                    peer_id_prefix = %prefix,
                    attempt,
                    "reconnect cancelled: peer already connected",
                );
                break;
            }

            // Refresh discovery-cache candidate addresses on EVERY attempt
            // (not a one-time snapshot). These include LAN/loopback addresses
            // when allow_local_scope is active (same-host scenario). A named
            // daemon that restarted on a different ephemeral port re-announces;
            // its new address is merged into the cache (upsert_discovered_
            // machine is append-only) and picked up on this backoff tick. A
            // one-time snapshot would pin the stale old port and never
            // rediscover the peer (final review: named restart on a new port).
            let candidate_addrs = {
                let cache = machine_cache.read().await;
                cache
                    .get(&machine_id)
                    .map(|m| m.addresses.clone())
                    .unwrap_or_default()
            };

            tracing::info!(
                target: "x0x::connect",
                peer_id_prefix = %prefix,
                attempt = attempt + 1,
                max_attempts = RECONNECT_BACKOFF_DELAYS.len(),
                candidate_addrs = candidate_addrs.len(),
                "proactive reconnect attempt",
            );

            let mut connected = false;

            // Phase 1: discovery-cache addresses (LAN/loopback for same-host).
            for addr in &candidate_addrs {
                // Final suppression gate immediately before the dial: closes the
                // TOCTOU window left open by the awaits above (and by prior dials
                // in this same loop), so a peer revoked/evicted mid-backoff is
                // never actually redialed.
                if network.is_reconnect_suppressed(peer_id_bytes) {
                    tracing::debug!(
                        target: "x0x::connect",
                        peer_id_prefix = %prefix,
                        "reconnect aborted before dial: peer reconnect-suppressed",
                    );
                    break 'attempts;
                }
                match tokio::time::timeout(
                    std::time::Duration::from_secs(5),
                    network.connect_addr(*addr),
                )
                .await
                {
                    Ok(Ok(connected_peer)) if connected_peer == peer_id => {
                        tracing::info!(
                            target: "x0x::connect",
                            peer_id_prefix = %prefix,
                            attempt = attempt + 1,
                            addr = %addr,
                            "proactive reconnect succeeded via discovery address",
                        );
                        connected = true;
                        break;
                    }
                    Ok(Ok(other)) => {
                        tracing::warn!(
                            target: "x0x::connect",
                            peer_id_prefix = %prefix,
                            addr = %addr,
                            "reconnect resolved to unexpected peer {:?}",
                            other,
                        );
                    }
                    Ok(Err(e)) => {
                        tracing::debug!(
                            target: "x0x::connect",
                            peer_id_prefix = %prefix,
                            addr = %addr,
                            error = %e,
                            "reconnect attempt at discovery address failed",
                        );
                    }
                    Err(_) => {
                        tracing::debug!(
                            target: "x0x::connect",
                            peer_id_prefix = %prefix,
                            addr = %addr,
                            "reconnect attempt at discovery address timed out",
                        );
                    }
                }
            }

            // Phase 2: bootstrap-cache fallback (public addresses for remote
            // peers that may have NAT-stable endpoints).
            if !connected {
                // Final suppression gate before the fallback dial (see Phase 1).
                if network.is_reconnect_suppressed(peer_id_bytes) {
                    tracing::debug!(
                        target: "x0x::connect",
                        peer_id_prefix = %prefix,
                        "reconnect aborted before bootstrap-cache dial: peer reconnect-suppressed",
                    );
                    break 'attempts;
                }
                match network.connect_cached_peer(peer_id).await {
                    Ok(_) => {
                        tracing::info!(
                            target: "x0x::connect",
                            peer_id_prefix = %prefix,
                            attempt = attempt + 1,
                            "proactive reconnect succeeded via bootstrap cache",
                        );
                        connected = true;
                    }
                    Err(e) => {
                        tracing::debug!(
                            target: "x0x::connect",
                            peer_id_prefix = %prefix,
                            error = %e,
                            "reconnect via bootstrap cache failed",
                        );
                    }
                }
            }

            if connected {
                break;
            }
        }

        // Circuit breaker: if every attempt failed (peer genuinely
        // dead/unreachable), hold the single-flight tracker slot for a cooldown
        // before releasing it. A dead peer keeps emitting transport-close
        // lifecycle events; each would otherwise immediately re-trigger a new
        // reconnect sequence, and every attempt drives ant-quic NAT
        // traversal/hole-punch to the dead endpoint — a tight loop that
        // accumulates connection state and leaks memory. Keeping the entry
        // present makes the existing single-flight guard suppress re-scheduling
        // for the window. A genuine recovery via any path (PeerConnected aborts
        // this task and removes the entry) ends the cooldown early.
        if !network.is_connected(&peer_id).await {
            tokio::select! {
                _ = shutdown_token.cancelled() => {}
                _ = tokio::time::sleep(RECONNECT_FAILURE_COOLDOWN) => {}
            }
        }

        // Remove ourselves from the single-flight tracker. If a PeerConnected
        // event already aborted us and removed the entry, this is a no-op.
        if let Ok(mut t) = tracker_clone.lock() {
            t.remove(&peer_id_bytes);
        }
    });

    tracker.insert(peer_id_bytes, handle);
}

impl AgentBuilder {
    /// Set a custom path for the machine keypair.
    ///
    /// If not set, the machine keypair is stored in `~/.x0x/machine.key`.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to store the machine keypair.
    ///
    /// # Returns
    ///
    /// Self for chaining.
    pub fn with_machine_key<P: AsRef<std::path::Path>>(mut self, path: P) -> Self {
        self.machine_key_path = Some(path.as_ref().to_path_buf());
        self
    }

    /// Import an agent keypair.
    ///
    /// If not set, the agent keypair is loaded from storage (or generated fresh
    /// if no stored key exists).
    ///
    /// This enables running the same agent on multiple machines by importing
    /// the same agent keypair (but with different machine keypairs).
    ///
    /// Note: When an explicit keypair is provided via this method, it takes
    /// precedence over `with_agent_key_path()`.
    ///
    /// # Arguments
    ///
    /// * `keypair` - The agent keypair to import.
    ///
    /// # Returns
    ///
    /// Self for chaining.
    pub fn with_agent_key(mut self, keypair: identity::AgentKeypair) -> Self {
        self.agent_keypair = Some(keypair);
        self
    }

    /// Set a custom path for the agent keypair.
    ///
    /// If not set, the agent keypair is stored in `~/.x0x/agent.key`.
    /// If no stored key is found at the path, a fresh one is generated and saved.
    ///
    /// This is ignored when `with_agent_key()` provides an explicit keypair.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to store/load the agent keypair.
    ///
    /// # Returns
    ///
    /// Self for chaining.
    pub fn with_agent_key_path<P: AsRef<std::path::Path>>(mut self, path: P) -> Self {
        self.agent_key_path = Some(path.as_ref().to_path_buf());
        self
    }

    /// Set a custom path for the agent certificate (`agent.cert`).
    ///
    /// Required for multi-daemon setups that share a host — the default
    /// path (`~/.x0x/agent.cert`) is shared across daemons, causing
    /// last-writer-wins trampling that makes peers reject identity
    /// announcements as `agent certificate agent_id mismatch`.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to use for the agent certificate file.
    ///
    /// # Returns
    ///
    /// Self for chaining.
    #[must_use]
    pub fn with_agent_cert_path<P: AsRef<std::path::Path>>(mut self, path: P) -> Self {
        self.agent_cert_path = Some(path.as_ref().to_path_buf());
        self
    }

    /// Set network configuration for P2P communication.
    ///
    /// If not set, the agent is built without a network node or gossip
    /// runtime. Use `NetworkConfig::default()` to connect through the default
    /// bootstrap nodes.
    ///
    /// # Arguments
    ///
    /// * `config` - The network configuration to use.
    ///
    /// # Returns
    ///
    /// Self for chaining.
    pub fn with_network_config(mut self, config: network::NetworkConfig) -> Self {
        self.network_config = Some(config);
        self
    }

    /// Set gossip overlay configuration.
    ///
    /// This is primarily used by x0xd to expose operational knobs such as
    /// `gossip.dispatch_workers`. If the agent is built without a network
    /// configuration, the value is retained by the builder but has no runtime
    /// effect.
    #[must_use]
    pub fn with_gossip_config(mut self, config: gossip::GossipConfig) -> Self {
        self.gossip_config = Some(config);
        self
    }

    /// Set the directory for the bootstrap peer cache.
    ///
    /// The cache persists peer quality metrics across restarts, enabling
    /// cache-first join strategy. Defaults to `~/.x0x/peers/` if not set.
    /// Falls back to `./.x0x/peers/` (relative to CWD) if `$HOME` is unset.
    pub fn with_peer_cache_dir<P: AsRef<std::path::Path>>(mut self, path: P) -> Self {
        self.peer_cache_dir = Some(path.as_ref().to_path_buf());
        self
    }

    /// Disable bootstrap peer cache persistence.
    ///
    /// When set, the cache is in-memory only for this session: no cached
    /// peers are loaded on startup and nothing is written to disk (no
    /// cache directory is created). This ensures complete network
    /// isolation from previously seen peers for embedders and dedicated
    /// test harnesses, while the transport keeps its normal in-session
    /// reconnection behaviour.
    ///
    /// Note: the x0xd daemon's `--no-hard-coded-bootstrap` flag does
    /// not call this; it clears only the embedded global bootstrap
    /// network (config-provided peers are honored verbatim).
    pub fn with_peer_cache_disabled(mut self) -> Self {
        self.disable_peer_cache = true;
        self
    }

    /// Import a user keypair for three-layer identity.
    ///
    /// This binds a human identity to this agent. When provided, an
    /// [`identity::AgentCertificate`] is automatically issued (if one
    /// doesn't already exist in storage) to cryptographically attest
    /// that this agent belongs to the user.
    ///
    /// Note: When an explicit keypair is provided via this method, it takes
    /// precedence over `with_user_key_path()`.
    ///
    /// # Arguments
    ///
    /// * `keypair` - The user keypair to import.
    ///
    /// # Returns
    ///
    /// Self for chaining.
    pub fn with_user_key(mut self, keypair: identity::UserKeypair) -> Self {
        self.user_keypair = Some(keypair);
        self
    }

    /// Set a custom path for the user keypair.
    ///
    /// Unlike machine and agent keys, user keys are **not** auto-generated.
    /// If the file at this path doesn't exist, no user identity is set
    /// (the agent operates with two-layer identity).
    ///
    /// This is ignored when `with_user_key()` provides an explicit keypair.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to load the user keypair from.
    ///
    /// # Returns
    ///
    /// Self for chaining.
    pub fn with_user_key_path<P: AsRef<std::path::Path>>(mut self, path: P) -> Self {
        self.user_key_path = Some(path.as_ref().to_path_buf());
        self
    }

    /// Set the identity heartbeat re-announcement interval.
    ///
    /// Defaults to [`IDENTITY_HEARTBEAT_INTERVAL_SECS`] (300 seconds).
    ///
    /// # Arguments
    ///
    /// * `secs` - Interval in seconds between identity re-announcements.
    #[must_use]
    pub fn with_heartbeat_interval(mut self, secs: u64) -> Self {
        self.heartbeat_interval_secs = Some(secs);
        self
    }

    /// Set the identity cache TTL.
    ///
    /// Cache entries with `last_seen` older than this threshold are filtered
    /// from [`Agent::presence`] and [`Agent::discovered_agents`].
    ///
    /// Defaults to [`IDENTITY_TTL_SECS`] (900 seconds).
    ///
    /// # Arguments
    ///
    /// * `secs` - Time-to-live in seconds for discovered agent entries.
    #[must_use]
    pub fn with_identity_ttl(mut self, secs: u64) -> Self {
        self.identity_ttl_secs = Some(secs);
        self
    }

    /// Override the presence beacon broadcast interval in seconds.
    #[must_use]
    pub fn with_presence_beacon_interval(mut self, secs: u64) -> Self {
        self.presence_beacon_interval_secs = Some(secs);
        self
    }

    /// Override the presence event poll interval in seconds.
    #[must_use]
    pub fn with_presence_event_poll_interval(mut self, secs: u64) -> Self {
        self.presence_event_poll_interval_secs = Some(secs);
        self
    }

    /// Override the fallback offline timeout used by presence events.
    #[must_use]
    pub fn with_presence_offline_timeout(mut self, secs: u64) -> Self {
        self.presence_offline_timeout_secs = Some(secs);
        self
    }

    /// Set a custom path for the contacts file.
    ///
    /// The contacts file persists trust levels and machine records for known
    /// agents. Defaults to `~/.x0x/contacts.json` if not set.
    ///
    /// # Arguments
    ///
    /// * `path` - The path for the contacts file.
    #[must_use]
    pub fn with_contact_store_path<P: AsRef<std::path::Path>>(mut self, path: P) -> Self {
        self.contact_store_path = Some(path.as_ref().to_path_buf());
        self
    }

    /// Set the directory used for all identity-scoped files (keys, certificate,
    /// and the revocation set `revocations.bin`).
    ///
    /// When set, the revocation set is loaded from / saved to
    /// `<identity_dir>/revocations.bin` instead of `~/.x0x/revocations.bin`.
    /// This mirrors how `with_machine_key`, `with_agent_key_path`, and
    /// `with_agent_cert_path` scope their respective files.
    ///
    /// Callers that already configure all three key paths individually do not
    /// need to set this — it is primarily a convenience for the x0xd server
    /// which builds the agent with an explicit identity directory.
    #[must_use]
    pub fn with_identity_dir<P: AsRef<std::path::Path>>(mut self, path: P) -> Self {
        self.identity_dir = Some(path.as_ref().to_path_buf());
        self
    }

    /// Build and initialise the agent.
    ///
    /// This performs the following:
    /// 1. Loads or generates the machine keypair (stored in `~/.x0x/machine.key` by default)
    /// 2. Uses provided agent keypair or generates a fresh one
    /// 3. Combines both into a unified Identity
    ///
    /// The machine keypair is automatically persisted to storage.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Machine keypair generation fails
    /// - Storage I/O fails
    /// - Keypair deserialization fails
    pub async fn build(self) -> error::Result<Agent> {
        // Determine machine keypair source
        let machine_keypair = if let Some(path) = self.machine_key_path {
            // Try to load from custom path
            match storage::load_machine_keypair_from(&path).await {
                Ok(kp) => kp,
                Err(_) => {
                    // Generate fresh keypair and save to custom path
                    let kp = identity::MachineKeypair::generate()?;
                    storage::save_machine_keypair_to(&kp, &path).await?;
                    kp
                }
            }
        } else if storage::machine_keypair_exists().await {
            // Load default machine keypair
            storage::load_machine_keypair().await?
        } else {
            // Generate and save default machine keypair
            let kp = identity::MachineKeypair::generate()?;
            storage::save_machine_keypair(&kp).await?;
            kp
        };

        // Resolve agent keypair: explicit > path-based > default storage > generate
        let agent_keypair = if let Some(kp) = self.agent_keypair {
            // Explicit keypair takes highest precedence
            kp
        } else if let Some(path) = self.agent_key_path {
            // Custom path: load or generate+save
            match storage::load_agent_keypair_from(&path).await {
                Ok(kp) => kp,
                Err(_) => {
                    let kp = identity::AgentKeypair::generate()?;
                    storage::save_agent_keypair_to(&kp, &path).await?;
                    kp
                }
            }
        } else if storage::agent_keypair_exists().await {
            // Default path exists: load it
            storage::load_agent_keypair_default().await?
        } else {
            // No stored key: generate and persist
            let kp = identity::AgentKeypair::generate()?;
            storage::save_agent_keypair_default(&kp).await?;
            kp
        };

        // Resolve user keypair: explicit > path-based > default storage > None (opt-in)
        let user_keypair = if let Some(kp) = self.user_keypair {
            Some(kp)
        } else if let Some(path) = self.user_key_path {
            // Custom path: load if exists, otherwise None (don't auto-generate)
            storage::load_user_keypair_from(&path).await.ok()
        } else if storage::user_keypair_exists().await {
            // Default path exists: load it
            storage::load_user_keypair().await.ok()
        } else {
            None
        };

        // Build identity with optional user layer.
        //
        // The agent certificate binds (user_id, agent_id). On load we must
        // verify BOTH halves of the binding match the current identity —
        // user_id AND agent_id — and re-issue if either diverges. A mismatch
        // happens in two practical scenarios:
        //   1. The user key was replaced (cert's user_id no longer ours).
        //   2. Multi-daemon-per-host setups where the cert path is shared
        //      and a peer daemon overwrote it with their own cert (cert's
        //      agent_id no longer ours).
        // Without the agent_id half of the check, scenario (2) produces an
        // announcement whose cert binds another daemon's agent_id, and peers
        // reject it as "agent certificate agent_id mismatch".
        //
        // The per-daemon `agent_cert_path` (set by `with_agent_cert_path()`)
        // is the structural fix for scenario (2); the agent_id check is the
        // defensive net in case two processes still land on the same path.
        let identity = if let Some(user_kp) = user_keypair {
            let cert_path = self.agent_cert_path.clone();
            let existing_cert = if let Some(ref p) = cert_path {
                if tokio::fs::try_exists(p).await.unwrap_or(false) {
                    storage::load_agent_certificate_from(p).await.ok()
                } else {
                    None
                }
            } else if storage::agent_certificate_exists().await {
                storage::load_agent_certificate().await.ok()
            } else {
                None
            };

            let cert_still_valid = existing_cert.as_ref().is_some_and(|c| {
                let user_match = c
                    .user_id()
                    .map(|uid| uid == user_kp.user_id())
                    .unwrap_or(false);
                let agent_match = c
                    .agent_id()
                    .map(|aid| aid == agent_keypair.agent_id())
                    .unwrap_or(false);
                user_match && agent_match
            });

            let cert = if cert_still_valid {
                existing_cert.ok_or_else(|| {
                    error::IdentityError::Storage(std::io::Error::other(
                        "agent certificate validity check succeeded with no certificate loaded",
                    ))
                })?
            } else {
                let new_cert = identity::AgentCertificate::issue(&user_kp, &agent_keypair)?;
                if let Some(ref p) = cert_path {
                    storage::save_agent_certificate_to(&new_cert, p).await?;
                } else {
                    storage::save_agent_certificate(&new_cert).await?;
                }
                new_cert
            };
            identity::Identity::new_with_user(machine_keypair, agent_keypair, user_kp, cert)
        } else {
            identity::Identity::new(machine_keypair, agent_keypair)
        };

        // Configure the bootstrap peer cache. The cache *instance* is owned
        // by the ant-quic endpoint (one cache per node, shared by transport
        // reconnection, x0x join phases and presence enrichment) — x0x only
        // chooses where it lives and whether it persists, then borrows the
        // endpoint's instance after node creation. `disable_peer_cache`
        // yields a session-only in-memory cache: nothing is loaded from
        // previous runs and nothing is written to disk.
        let bootstrap_cache_config = if self.network_config.is_some() {
            let cache_dir = self.peer_cache_dir.unwrap_or_else(|| {
                dirs::home_dir()
                    .unwrap_or_else(|| std::path::PathBuf::from("."))
                    .join(".x0x")
                    .join("peers")
            });
            Some(
                ant_quic::BootstrapCacheConfig::builder()
                    .cache_dir(cache_dir)
                    .min_peers_to_save(1)
                    .persist(!self.disable_peer_cache)
                    .build(),
            )
        } else {
            None
        };

        // Create network node if configured
        // Pass the machine keypair so ant-quic PeerId == MachineId (identity unification)
        let machine_keypair = {
            let pk = ant_quic::MlDsaPublicKey::from_bytes(
                identity.machine_keypair().public_key().as_bytes(),
            )
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "invalid machine public key: {e}"
                )))
            })?;
            let sk = ant_quic::MlDsaSecretKey::from_bytes(
                identity.machine_keypair().secret_key().as_bytes(),
            )
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "invalid machine secret key: {e}"
                )))
            })?;
            Some((pk, sk))
        };

        // X0X-0070b: extract the relay policy + seed candidate list before
        // `self.network_config` is moved into `NetworkNode::new`. With no
        // network config the relay engine is built from `PeerRelayConfig::default()`,
        // which is `enabled = false` - the engine is then inert.
        let peer_relay_config = self
            .network_config
            .as_ref()
            .map(|cfg| cfg.peer_relay.clone())
            .unwrap_or_default();
        let mut parsed_relay_candidates = Vec::with_capacity(peer_relay_config.candidates.len());
        for hex_str in &peer_relay_config.candidates {
            let trimmed = hex_str.trim();
            let bytes = hex::decode(trimmed).map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "invalid relay candidate hex {trimmed:?}: {e}"
                )))
            })?;
            let arr: [u8; 32] = bytes.try_into().map_err(|v: Vec<u8>| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "relay candidate must be 32 bytes (got {} bytes)",
                    v.len()
                )))
            })?;
            parsed_relay_candidates.push(identity::AgentId(arr));
        }
        let peer_relay = std::sync::Arc::new(peer_relay::PeerRelay::with_policy(
            peer_relay_config.to_policy(),
        ));
        let relay_candidates =
            std::sync::Arc::new(tokio::sync::RwLock::new(parsed_relay_candidates));

        // X0X-0070b: discovery cache is hoisted out of the `Agent` literal so
        // the relay-DM listener (spawned below) can hold an `Arc` clone of it
        // without going through `&self` - the listener is a sibling task to
        // the network receiver, not an `Agent` method.
        let identity_discovery_cache: std::sync::Arc<
            tokio::sync::RwLock<std::collections::HashMap<identity::AgentId, DiscoveredAgent>>,
        > = std::sync::Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new()));

        let network = if let Some(config) = self.network_config {
            let node = network::NetworkNode::new(config, bootstrap_cache_config, machine_keypair)
                .await
                .map_err(|e| {
                    error::IdentityError::Storage(std::io::Error::other(format!(
                        "network initialization failed: {}",
                        e
                    )))
                })?;

            // Verify identity unification: ant-quic PeerId must equal MachineId
            debug_assert_eq!(
                node.peer_id().0,
                identity.machine_id().0,
                "ant-quic PeerId must equal MachineId after identity unification"
            );

            Some(std::sync::Arc::new(node))
        } else {
            None
        };

        // Borrow the endpoint-owned cache so every layer (transport
        // reconnection, join phases, presence enrichment, gossip adapter)
        // reads and writes one instance. The endpoint runs maintenance —
        // do not start it again here.
        let bootstrap_cache = network.as_ref().and_then(|n| n.bootstrap_cache());

        // Load the local revocation set now (shared Arc) so the relay-DM
        // listener can enforce revocation on inbound relayed envelopes. The
        // same Arc is moved into the Agent below, so the listener and the
        // Agent's `/identity/revoke` writes observe one shared set.
        let revocation_set = std::sync::Arc::new(tokio::sync::RwLock::new(
            storage::load_revocation_set(self.identity_dir.as_deref()).await,
        ));

        // Initialise contact store now (hoisted before the relay-DM
        // listener spawn so the listener can resolve the #193 contact
        // gate against the same shared store the Agent mutates).
        let contacts_path = self.contact_store_path.unwrap_or_else(|| {
            dirs::home_dir()
                .unwrap_or_else(|| std::path::PathBuf::from("."))
                .join(".x0x")
                .join("contacts.json")
        });
        let contact_store = std::sync::Arc::new(tokio::sync::RwLock::new(
            contacts::ContactStore::new(contacts_path),
        ));

        // X0X-0070b: spawn the inbound RelayedDm listener so this Agent can
        // serve as either the final recipient (DeliverLocally) or the
        // intermediate relay (Forward) for peers that fell back to the
        // relay path. Only meaningful when a network is configured -
        // without one there is nothing to receive on and nothing to
        // forward to.
        if let Some(ref net) = network {
            spawn_relay_dm_listener(
                std::sync::Arc::clone(net),
                std::sync::Arc::clone(&peer_relay),
                std::sync::Arc::clone(&identity_discovery_cache),
                std::sync::Arc::clone(&revocation_set),
                std::sync::Arc::clone(&contact_store),
                identity.agent_id(),
            );
        }

        // Create signing context from agent keypair for message authentication
        let signing_ctx = std::sync::Arc::new(gossip::SigningContext::from_keypair(
            identity.agent_keypair(),
        ));

        // Create gossip runtime if network exists
        let gossip_runtime = if let Some(ref net) = network {
            let runtime = gossip::GossipRuntime::new(
                self.gossip_config.unwrap_or_default(),
                std::sync::Arc::clone(net),
                Some(signing_ctx),
            )
            .await
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "gossip runtime initialization failed: {}",
                    e
                )))
            })?;
            Some(std::sync::Arc::new(runtime))
        } else {
            None
        };

        // Wrap bootstrap cache with gossip coordinator adapter (zero duplication).
        let gossip_cache_adapter = bootstrap_cache.as_ref().map(|cache| {
            saorsa_gossip_coordinator::GossipCacheAdapter::new(std::sync::Arc::clone(cache))
        });

        // Initialize direct messaging infrastructure
        let direct_messaging = std::sync::Arc::new(direct::DirectMessaging::new());

        // Create presence wrapper if network exists
        let presence = if let Some(ref net) = network {
            let peer_id = saorsa_gossip_transport::GossipTransport::local_peer_id(net.as_ref());
            let mut presence_config = presence::PresenceConfig::default();
            if let Some(secs) = self.presence_beacon_interval_secs {
                presence_config.beacon_interval_secs = secs;
            }
            if let Some(secs) = self.presence_event_poll_interval_secs {
                presence_config.event_poll_interval_secs = secs;
            }
            if let Some(secs) = self.presence_offline_timeout_secs {
                presence_config.adaptive_timeout_fallback_secs = secs;
            }
            // Sign presence beacons with the machine keypair that backs
            // `peer_id` (= net.local_peer_id()). The presence layer binds the
            // signer key to the claimed sender, so a beacon signed by any
            // other key would be rejected by every receiver (including this
            // node's own loopback path).
            let pw = presence::PresenceWrapper::new(
                peer_id,
                identity.machine_keypair().to_bytes(),
                std::sync::Arc::clone(net),
                presence_config,
                bootstrap_cache.clone(),
            )
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "presence initialization failed: {}",
                    e
                )))
            })?;
            let pw_arc = std::sync::Arc::new(pw);
            // Wire presence into gossip runtime for Bulk dispatch
            if let Some(ref rt) = gossip_runtime {
                rt.set_presence(std::sync::Arc::clone(&pw_arc));
            }
            Some(pw_arc)
        } else {
            None
        };

        // Load the revocation set from disk so enforcement takes effect
        // immediately on restart, even before the next gossip heartbeat.
        Ok(Agent {
            identity: std::sync::Arc::new(identity),
            network,
            gossip_runtime,
            bootstrap_cache,
            gossip_cache_adapter,
            identity_discovery_cache,
            authenticated_machine_bindings: std::sync::Arc::new(tokio::sync::RwLock::new(
                dm_inbox::AuthenticatedMachineBindingCache::default(),
            )),
            machine_discovery_cache: std::sync::Arc::new(tokio::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
            user_discovery_cache: std::sync::Arc::new(tokio::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
            identity_listener_started: std::sync::atomic::AtomicBool::new(false),
            heartbeat_interval_secs: self
                .heartbeat_interval_secs
                .unwrap_or(IDENTITY_HEARTBEAT_INTERVAL_SECS),
            identity_ttl_secs: self.identity_ttl_secs.unwrap_or(IDENTITY_TTL_SECS),
            heartbeat_handle: tokio::sync::Mutex::new(None),
            discovery_cache_reaper_handle: tokio::sync::Mutex::new(None),
            rendezvous_advertised: std::sync::atomic::AtomicBool::new(false),
            contact_store,
            direct_messaging,
            network_event_listener_started: std::sync::atomic::AtomicBool::new(false),
            direct_listener_started: std::sync::atomic::AtomicBool::new(false),
            presence,
            user_identity_consented: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
            capability_store: std::sync::Arc::new(dm_capability::CapabilityStore::new()),
            dm_capabilities_tx: std::sync::Arc::new({
                let (tx, _rx) = tokio::sync::watch::channel(dm::DmCapabilities::pending());
                tx
            }),
            dm_inflight_acks: std::sync::Arc::new(dm::InFlightAcks::new()),
            recent_delivery_cache: std::sync::Arc::new(dm::RecentDeliveryCache::with_defaults()),
            capability_advert_service: tokio::sync::Mutex::new(None),
            dm_inbox_service: tokio::sync::Mutex::new(None),
            revocation_set,
            identity_dir: self.identity_dir,
            shutdown_token: tokio_util::sync::CancellationToken::new(),
            tracked_tasks: std::sync::Arc::new(std::sync::Mutex::new(TrackedTasks {
                closed: false,
                handles: Vec::new(),
            })),
            peer_relay,
            relay_candidates,
            stream_accept: std::sync::Arc::new(streams::StreamAccept::new(256)),
        })
    }
}

/// Handle for interacting with a collaborative task list.
///
/// Provides a safe, concurrent interface to a TaskList backed by
/// CRDT synchronization. All operations are async and return Results.
///
/// # Example
///
/// ```ignore
/// let handle = agent.create_task_list("My List", "topic").await?;
/// let task_id = handle.add_task("Write docs".to_string(), "API docs".to_string()).await?;
/// handle.claim_task(task_id).await?;
/// handle.complete_task(task_id).await?;
/// ```
#[derive(Clone)]
pub struct TaskListHandle {
    sync: std::sync::Arc<crdt::TaskListSync>,
    agent_id: identity::AgentId,
    peer_id: saorsa_gossip_types::PeerId,
    /// Per-replica fencing epoch. Regenerated when the handle is (re)built —
    /// i.e. on daemon restart — so a numeric fence token captured before a
    /// restart can never ABA-match a post-restart token (the epoch differs).
    /// See [`FenceToken`].
    replica_epoch: u64,
    /// Signing context for self-signing claim/complete operations
    /// (authenticated operation provenance). Threaded from the agent's
    /// keypair at construction; the secret key never leaves the handle.
    signing: std::sync::Arc<crate::gossip::SigningContext>,
}

impl std::fmt::Debug for TaskListHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TaskListHandle")
            .field("agent_id", &self.agent_id)
            .field("peer_id", &self.peer_id)
            .finish_non_exhaustive()
    }
}

impl TaskListHandle {
    /// Generate a fresh per-replica epoch at handle construction.
    ///
    /// Uses a CSPRNG incarnation nonce (64-bit random from `OsRng`) so a
    /// pre-restart fence token can never ABA-match a post-restart one (the
    /// epoch component differs with overwhelming probability). Unlike
    /// wall-clock nanoseconds, a random nonce is not predictable and does not
    /// depend on monotonic clock behaviour across restarts. `OsRng` never
    /// blocks on a functioning system; if it fails (catastrophic entropy
    /// failure), we fall back to wall-clock nanoseconds (still advances across
    /// restart). Epoch 0 is reserved as "uninitialized" and is never returned.
    fn fresh_epoch() -> u64 {
        use rand::RngCore;
        let mut bytes = [0u8; 8];
        match rand::rngs::OsRng.try_fill_bytes(&mut bytes) {
            Ok(()) => {
                let epoch = u64::from_le_bytes(bytes);
                if epoch == 0 {
                    1
                } else {
                    epoch
                }
            }
            Err(_) => std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos() as u64)
                .unwrap_or(1)
                .max(1),
        }
    }

    /// Build the current fence token for this replica at the given revision.
    fn current_fence(&self, revision: u64) -> FenceToken {
        FenceToken {
            epoch: self.replica_epoch,
            revision,
        }
    }

    /// Set the authorized-member set for group-scoped task lists.
    ///
    /// When set, remote CRDT admission rejects checkbox elements (claims/
    /// completions) whose attesting agent is not in this set — applying group
    /// authorization at replication admission, not just at REST. The server
    /// layer should call this when creating/joining a group-scoped list and
    /// when group membership changes.
    ///
    /// This is a best-effort consistency measure: the set is not persisted and
    /// must be re-established after a restart (before the sync listener starts
    /// to avoid a race window).
    pub async fn set_authorized_agents(
        &self,
        agents: std::collections::HashSet<identity::AgentId>,
    ) {
        let mut list = self.sync.write().await;
        list.set_authorized_agents(agents);
    }

    /// Clear the authorized-member set (revert to open admission for all
    /// validly-attested operations).
    pub async fn clear_authorized_agents(&self) {
        let mut list = self.sync.write().await;
        list.clear_authorized_agents();
    }

    /// Test-only: override the per-replica epoch so a pre-restart fence token
    /// can be simulated in-process without a real daemon restart.
    ///
    /// Two handles sharing the same `Arc<TaskListSync>` but with different
    /// epochs exercise the restart-ABA rejection: a token captured at epoch E1
    /// is rejected when the handle's epoch is E2.
    #[cfg(test)]
    pub fn set_replica_epoch_for_testing(&mut self, epoch: u64) {
        self.replica_epoch = epoch;
    }
}

impl TaskListHandle {
    /// Add a new task to the list.
    ///
    /// # Arguments
    ///
    /// * `title` - Task title
    /// * `description` - Task description
    ///
    /// # Returns
    ///
    /// The TaskId of the created task.
    ///
    /// # Errors
    ///
    /// Returns an error if the task cannot be added.
    pub async fn add_task(
        &self,
        title: String,
        description: String,
    ) -> error::Result<crdt::TaskId> {
        let (task_id, _version) = self.add_task_versioned(title, description).await?;
        Ok(task_id)
    }

    /// Add a new task and report the task list's post-mutation version.
    ///
    /// Same as [`TaskListHandle::add_task`] but additionally returns the
    /// list's version counter after the add, read atomically under the same
    /// write lock as the mutation.
    ///
    /// # Errors
    ///
    /// Returns an error if the task cannot be added.
    pub async fn add_task_versioned(
        &self,
        title: String,
        description: String,
    ) -> error::Result<(crdt::TaskId, u64)> {
        let (task_id, version, delta) = {
            let mut list = self.sync.write().await;
            let seq = list.next_seq();
            let task_id = crdt::TaskId::new(&title, &self.agent_id, seq);
            let metadata = crdt::TaskMetadata::new(title, description, 128, self.agent_id, seq);
            let task = crdt::TaskItem::new(task_id, metadata, self.peer_id);
            list.add_task(task.clone(), self.peer_id, seq)
                .map_err(|e| {
                    error::IdentityError::Storage(std::io::Error::other(format!(
                        "add_task failed: {}",
                        e
                    )))
                })?;
            let tag = (self.peer_id, seq);
            let version = list.current_version();
            let delta = crdt::TaskListDelta::for_add(task_id, task, tag, version);
            (task_id, version, delta)
        };
        // Best-effort replication: local mutation succeeded regardless
        if let Err(e) = self.sync.publish_delta(self.peer_id, delta).await {
            tracing::warn!("failed to publish add_task delta: {}", e);
        }
        Ok((task_id, version))
    }

    /// Claim a task in the list.
    ///
    /// # Arguments
    ///
    /// * `task_id` - ID of the task to claim
    ///
    /// # Errors
    ///
    /// Returns an error if the task cannot be claimed.
    pub async fn claim_task(&self, task_id: crdt::TaskId) -> error::Result<()> {
        // No local-version guard ⇒ unconditional (still advisory; concurrent
        // remote claims coexist in the CRDT regardless).
        self.claim_task_versioned(task_id, None).await.map(|_| ())
    }

    /// Claim a task, optionally guarded by an expected list version.
    ///
    /// `expected_version` is a **local-replica fencing precondition**, not a
    /// distributed compare-and-swap: when `Some(v)` and this replica's local
    /// version counter is not `v`, nothing is mutated and
    /// [`TaskMutationOutcome::StaleLocalVersion`] is returned. Two replicas
    /// that both happen to be at version `v` will BOTH pass — this guard
    /// cannot provide cross-replica exclusion. The check and the mutation
    /// happen under a single local write lock.
    ///
    /// The claim itself is **advisory**: it records a `Claimed` candidate in
    /// the OR-Set and publishes a delta. Concurrent claims (on this or other
    /// replicas) coexist; the deterministic winner resolves at convergence.
    /// The returned [`AdvisoryOwnership`] reports the local snapshot at commit
    /// time and is provisional.
    ///
    /// `Committed` means applied to the local replica + best-effort delta
    /// publish — not that any peer observed it, nor that the caller won
    /// exclusively.
    ///
    /// # Errors
    ///
    /// Returns an error if the task does not exist or the state transition
    /// is invalid (e.g. the task is already done).
    pub async fn claim_task_versioned(
        &self,
        task_id: crdt::TaskId,
        expected: Option<FenceToken>,
    ) -> error::Result<TaskMutationOutcome> {
        let (fence, delta, advisory) = {
            let mut list = self.sync.write().await;
            if let Some(expected) = expected {
                let current = list.current_version();
                // Reject if either the epoch (restart-ABA) or the revision
                // (stale local snapshot) mismatches. Both are local-only.
                if expected.epoch != self.replica_epoch || expected.revision != current {
                    return Ok(TaskMutationOutcome::StaleLocalVersion {
                        current: self.current_fence(current),
                    });
                }
            }
            let seq = list.next_seq();
            list.claim_task(&task_id, self.agent_id, self.peer_id, seq, &self.signing)
                .map_err(|e| {
                    error::IdentityError::Storage(std::io::Error::other(format!(
                        "claim_task failed: {}",
                        e
                    )))
                })?;
            // Read back the task once (under the same lock) to compute the
            // advisory ownership snapshot and the delta payload atomically.
            let task = list.get_task(&task_id).ok_or_else(|| {
                error::IdentityError::Storage(std::io::Error::other("task disappeared after claim"))
            })?;
            let winner = task.claim_record();
            let advisory = AdvisoryOwnership {
                agent: self.agent_id,
                locally_winning: winner.is_some_and(|(a, _)| a == self.agent_id),
                current_winner: winner,
            };
            // Include full task so receivers can upsert if add hasn't arrived yet
            let full_task = task.clone();
            let version = list.current_version();
            (
                self.current_fence(version),
                crdt::TaskListDelta::for_state_change(task_id, full_task, version),
                advisory,
            )
        };
        if let Err(e) = self.sync.publish_delta(self.peer_id, delta).await {
            tracing::warn!("failed to publish claim_task delta: {}", e);
        }
        Ok(TaskMutationOutcome::Committed { fence, advisory })
    }

    /// Complete a task in the list.
    ///
    /// # Arguments
    ///
    /// * `task_id` - ID of the task to complete
    ///
    /// # Errors
    ///
    /// Returns an error if the task cannot be completed.
    pub async fn complete_task(&self, task_id: crdt::TaskId) -> error::Result<()> {
        // No local-version guard ⇒ unconditional (still advisory).
        self.complete_task_versioned(task_id, None)
            .await
            .map(|_| ())
    }

    /// Complete a task, optionally guarded by an expected list version.
    ///
    /// Semantics mirror [`TaskListHandle::claim_task_versioned`]:
    /// `expected_version` is a **local-replica** fencing precondition (not a
    /// distributed CAS); a mismatch returns
    /// [`TaskMutationOutcome::StaleLocalVersion`] with no mutation. The
    /// completion is advisory; the returned [`AdvisoryOwnership`] reports the
    /// local `completion_record()` snapshot at commit time and is provisional.
    ///
    /// # Errors
    ///
    /// Returns an error if the task does not exist or the state transition
    /// is invalid (e.g. the task was never claimed).
    pub async fn complete_task_versioned(
        &self,
        task_id: crdt::TaskId,
        expected: Option<FenceToken>,
    ) -> error::Result<TaskMutationOutcome> {
        let (fence, delta, advisory) = {
            let mut list = self.sync.write().await;
            if let Some(expected) = expected {
                let current = list.current_version();
                if expected.epoch != self.replica_epoch || expected.revision != current {
                    return Ok(TaskMutationOutcome::StaleLocalVersion {
                        current: self.current_fence(current),
                    });
                }
            }
            let seq = list.next_seq();
            list.complete_task(&task_id, self.agent_id, self.peer_id, seq, &self.signing)
                .map_err(|e| {
                    error::IdentityError::Storage(std::io::Error::other(format!(
                        "complete_task failed: {}",
                        e
                    )))
                })?;
            let task = list.get_task(&task_id).ok_or_else(|| {
                error::IdentityError::Storage(std::io::Error::other(
                    "task disappeared after complete",
                ))
            })?;
            let winner = task.completion_record();
            let advisory = AdvisoryOwnership {
                agent: self.agent_id,
                locally_winning: winner.is_some_and(|(a, _)| a == self.agent_id),
                current_winner: winner,
            };
            let full_task = task.clone();
            let version = list.current_version();
            (
                self.current_fence(version),
                crdt::TaskListDelta::for_state_change(task_id, full_task, version),
                advisory,
            )
        };
        if let Err(e) = self.sync.publish_delta(self.peer_id, delta).await {
            tracing::warn!("failed to publish complete_task delta: {}", e);
        }
        Ok(TaskMutationOutcome::Committed { fence, advisory })
    }

    /// List all tasks in their current order.
    ///
    /// # Returns
    ///
    /// A vector of `TaskSnapshot` representing the current state.
    ///
    /// # Errors
    ///
    /// Returns an error if the task list cannot be read.
    pub async fn list_tasks(&self) -> error::Result<Vec<TaskSnapshot>> {
        let (tasks, _version) = self.list_tasks_with_version().await?;
        Ok(tasks)
    }

    /// List all tasks together with the task list's current version.
    ///
    /// The snapshots and the version are read atomically under a single read
    /// lock, so the returned version is consistent with the returned tasks —
    /// suitable as the `expected_version` (a local-replica fencing
    /// precondition, not a distributed CAS) for a subsequent mutation via
    /// [`TaskListHandle::claim_task_versioned`].
    ///
    /// # Errors
    ///
    /// Returns an error if the task list cannot be read.
    pub async fn list_tasks_with_version(&self) -> error::Result<(Vec<TaskSnapshot>, FenceToken)> {
        let list = self.sync.read().await;
        let version = list.current_version();
        let tasks = list.tasks_ordered();
        let snapshots = tasks
            .into_iter()
            .map(|task| {
                let claim = task.claim_record();
                let completion = task.completion_record();
                TaskSnapshot {
                    id: *task.id(),
                    title: task.title().to_string(),
                    description: task.description().to_string(),
                    state: task.current_state(),
                    assignee: task.assignee().copied(),
                    owner: None,
                    priority: task.priority(),
                    claimed_by: claim.map(|(agent, _)| agent),
                    claimed_at: claim.map(|(_, ts)| ts),
                    completed_by: completion.map(|(agent, _)| agent),
                    completed_at: completion.map(|(_, ts)| ts),
                }
            })
            .collect();
        Ok((snapshots, self.current_fence(version)))
    }

    /// The task list's current version counter.
    ///
    /// Incremented on every local or merged mutation. Useful as the
    /// `expected_version` (a local-replica fencing precondition, not a
    /// distributed CAS) for mutations; prefer
    /// [`TaskListHandle::list_tasks_with_version`] when the tasks are also
    /// needed, to read both atomically.
    pub async fn version(&self) -> FenceToken {
        let revision = self.sync.read().await.current_version();
        self.current_fence(revision)
    }

    /// Reorder tasks in the list.
    ///
    /// # Arguments
    ///
    /// * `task_ids` - New ordering of task IDs
    ///
    /// # Errors
    ///
    /// Returns an error if reordering fails.
    pub async fn reorder(&self, task_ids: Vec<crdt::TaskId>) -> error::Result<()> {
        let delta = {
            let mut list = self.sync.write().await;
            list.reorder(task_ids.clone(), self.peer_id).map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "reorder failed: {}",
                    e
                )))
            })?;
            // Carry the post-reorder ordering register (value + clock) so the
            // change merges by causality on receivers.
            crdt::TaskListDelta::for_reorder(
                list.ordering_register().clone(),
                list.current_version(),
            )
        };
        if let Err(e) = self.sync.publish_delta(self.peer_id, delta).await {
            tracing::warn!("failed to publish reorder delta: {}", e);
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// KvStore API
// ---------------------------------------------------------------------------

impl Agent {
    /// Create a new key-value store.
    ///
    /// The store is automatically synchronized to all peers subscribed
    /// to the same `topic` via gossip delta propagation.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn create_kv_store(&self, name: &str, topic: &str) -> error::Result<KvStoreHandle> {
        let runtime = self.gossip_runtime.as_ref().ok_or_else(|| {
            error::IdentityError::Storage(std::io::Error::other(
                "gossip runtime not initialized - configure agent with network first",
            ))
        })?;

        let peer_id = runtime.peer_id();
        let store_id = kv::KvStoreId::for_topic_owner(topic, &self.agent_id());
        let store = kv::KvStore::new(
            store_id,
            name.to_string(),
            self.agent_id(),
            kv::AccessPolicy::Signed,
        );

        let sync = kv::KvStoreSync::new(
            store,
            std::sync::Arc::clone(runtime.pubsub()),
            topic.to_string(),
            peer_id,
            Some(self.agent_id()),
        )
        .map_err(|e| {
            error::IdentityError::Storage(std::io::Error::other(format!(
                "kv store sync creation failed: {e}",
            )))
        })?;

        let sync = std::sync::Arc::new(sync);
        sync.start_with_spawner(|fut| self.spawn_tracked(fut))
            .await
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "kv store sync start failed: {e}",
                )))
            })?;

        // The creator is the owner: capture signing material so each write
        // produces an owner-signed content checkpoint (cold-recovery provenance).
        let (pk_bytes, sk_bytes) = self.identity().agent_keypair().to_bytes();
        Ok(KvStoreHandle {
            sync,
            agent_id: self.agent_id(),
            peer_id,
            owner_signing: Some(std::sync::Arc::new(OwnerSigningMaterial {
                public_key_bytes: pk_bytes,
                secret_key_bytes: sk_bytes,
            })),
        })
    }

    /// Join an existing key-value store by topic, anchoring ownership on the
    /// trusted out-of-band `owner`.
    ///
    /// The owner anchor is **required** on every public join path: a replica
    /// with no anchor can never accept policy-restricted data, so an unanchored
    /// join is a dead replica, not a successful join. Callers MUST supply the
    /// authoritative owner (an Agent Card, invite, explicit REST/CLI param, or
    /// persisted manifest entry). The replica is anchored on `owner`: it accepts
    /// `owner`'s deltas and (if this node *is* `owner`) its own local writes,
    /// converging against any owner version — including a v0.30.1 owner that
    /// never announces — because the data path never consults an announce.
    ///
    /// `channel` records how the anchor was supplied (audit metadata); pass
    /// [`kv::store::AnchorChannel::RestParam`] for client-initiated joins and
    /// [`kv::store::AnchorChannel::Persistence`] for manifest replay.
    ///
    /// # Errors
    ///
    /// Returns an error if the gossip runtime is not initialized.
    pub async fn join_kv_store(
        &self,
        topic: &str,
        owner: identity::AgentId,
        channel: kv::store::AnchorChannel,
    ) -> error::Result<KvStoreHandle> {
        let runtime = self.gossip_runtime.as_ref().ok_or_else(|| {
            error::IdentityError::Storage(std::io::Error::other(
                "gossip runtime not initialized - configure agent with network first",
            ))
        })?;

        let peer_id = runtime.peer_id();
        // The store id is the verifiable topic→owner binding; it agrees with
        // the creator's id (both derive for_topic_owner(topic, owner)).
        let store_id = kv::KvStoreId::for_topic_owner(topic, &owner);
        let store = kv::KvStore::new_replica(store_id, String::new(), Some(owner), channel);

        let sync = kv::KvStoreSync::new(
            store,
            std::sync::Arc::clone(runtime.pubsub()),
            topic.to_string(),
            peer_id,
            Some(self.agent_id()),
        )
        .map_err(|e| {
            error::IdentityError::Storage(std::io::Error::other(format!(
                "kv store sync creation failed: {e}",
            )))
        })?;

        let sync = std::sync::Arc::new(sync);
        sync.start_with_spawner(|fut| self.spawn_tracked(fut))
            .await
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "kv store sync start failed: {e}",
                )))
            })?;

        Ok(KvStoreHandle {
            sync,
            agent_id: self.agent_id(),
            peer_id,
            // A joiner is not the owner and never produces checkpoints; it
            // only caches + relays owner-produced ones.
            owner_signing: None,
        })
    }
}

/// Handle for interacting with a replicated key-value store.
///
/// Provides async methods for putting, getting, and removing entries.
/// Changes are automatically replicated to peers via gossip.
#[derive(Clone)]
pub struct KvStoreHandle {
    sync: std::sync::Arc<kv::KvStoreSync>,
    agent_id: identity::AgentId,
    peer_id: saorsa_gossip_types::PeerId,
    /// Owner signing material, present only when this node is the store owner
    /// (creator path). Used to produce owner-signed content checkpoints on
    /// each write so replicas can cold-recover while the owner is offline.
    owner_signing: Option<std::sync::Arc<OwnerSigningMaterial>>,
}

/// Serialized owner keypair for checkpoint signing (held only by the owner's
/// handle). The bytes are reconstructed into keys at sign time.
#[derive(Clone)]
pub struct OwnerSigningMaterial {
    /// ML-DSA-65 public key bytes.
    pub public_key_bytes: Vec<u8>,
    /// ML-DSA-65 secret key bytes.
    pub secret_key_bytes: Vec<u8>,
}

impl std::fmt::Debug for KvStoreHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("KvStoreHandle")
            .field("agent_id", &self.agent_id)
            .field("peer_id", &self.peer_id)
            .finish_non_exhaustive()
    }
}

impl KvStoreHandle {
    /// Return this handle's gossip peer id.
    #[must_use]
    pub fn peer_id(&self) -> saorsa_gossip_types::PeerId {
        self.peer_id
    }

    /// Return the store's ownership/policy/version metadata for auditability.
    ///
    /// Reads are never gated on ownership — only writes are — so this always
    /// succeeds and surfaces the anchored owner (or `None` for a read-only
    /// no-anchor replica), the policy, the freshness version, and the derived
    /// [`kv::OwnershipSource`].
    pub async fn ownership_info(&self) -> KvStoreOwnershipInfo {
        let s = self.sync.read().await;
        let src = s.ownership_source();
        let (status, announced) = match &src {
            kv::OwnershipSource::Anchored { .. } => (kv::OwnershipStatus::Anchored, None),
            kv::OwnershipSource::Unknown => (kv::OwnershipStatus::Unknown, None),
            kv::OwnershipSource::Conflict { announced, .. } => (
                kv::OwnershipStatus::Conflict,
                Some(hex::encode(announced.as_bytes())),
            ),
        };
        KvStoreOwnershipInfo {
            owner: s.owner().map(|o| hex::encode(o.as_bytes())),
            policy: s.policy().to_string(),
            version: s.current_version(),
            // The owner-announce freshness counter — distinct from the general
            // mutation `version`. Surfaced so callers can observe the policy
            // freshness invariant (not just store churn).
            policy_version: s.policy_version(),
            ownership_status: status,
            announced_owner: announced,
        }
    }

    /// Produce and install an owner-signed content checkpoint, returning it
    /// for attachment to the published delta.
    ///
    /// Only the owner produces checkpoints (it holds the signing key). The
    /// checkpoint binds the post-write content root so replicas can
    /// cold-recover this state from a non-owner relay while the owner is
    /// offline. Returns `None` for non-owners or if signing is unavailable.
    fn produce_checkpoint(&self, store: &mut kv::KvStore) -> Option<kv::store::OwnerCheckpoint> {
        let signing = self.owner_signing.as_ref()?;
        // Only the owner signs; a joiner (even one anchored on itself, which is
        // unusual) without signing material does not produce checkpoints.
        if store.owner() != Some(&self.agent_id) {
            return None;
        }
        let topic = self.sync.topic();
        let id = *store.id();
        let pairs = store.checkpoint_pairs();
        let root = kv::store::content_root(&id, store.name(), &pairs);
        let seq = store.highest_checkpoint_seq.checked_add(1)?;
        let policy_version = store.policy_version();
        let policy = store.policy().clone();
        let ts = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0);
        let pubkey = ant_quic::MlDsaPublicKey::from_bytes(&signing.public_key_bytes).ok()?;
        let seckey = ant_quic::MlDsaSecretKey::from_bytes(&signing.secret_key_bytes).ok()?;
        let cp = kv::store::make_owner_checkpoint(kv::store::OwnerCheckpointParams {
            topic,
            store_id: &id,
            secret_key: &seckey,
            public_key: &pubkey,
            policy: &policy,
            policy_version,
            checkpoint_seq: seq,
            content_root: root,
            timestamp: ts,
        })
        .ok()?;
        store.latest_checkpoint = Some(cp.clone());
        store.highest_checkpoint_seq = seq;
        Some(cp)
    }

    /// Enforce the store's access policy for a local mutation.
    ///
    /// Applies the same authorization rule as the inbound delta path
    /// (`KvStore::merge_delta`), so a local write that peers would reject
    /// never mutates this replica (no local fork).
    fn check_local_write(store: &kv::KvStore, writer: &identity::AgentId) -> error::Result<()> {
        store.authorize_local_write(writer).map_err(|e| match e {
            kv::KvError::Unauthorized(msg) => error::IdentityError::Unauthorized(msg),
            other => error::IdentityError::Unauthorized(other.to_string()),
        })
    }

    /// Put a key-value pair into the store.
    ///
    /// If the key already exists, the value is updated. Changes are
    /// automatically replicated to peers via gossip.
    ///
    /// # Errors
    ///
    /// Returns an error if the value exceeds the maximum inline size (64 KB).
    pub async fn put(
        &self,
        key: String,
        value: Vec<u8>,
        content_type: String,
    ) -> error::Result<()> {
        let _ = self.put_with_delta(key, value, content_type).await?;
        Ok(())
    }

    /// Put a key-value pair and return the CRDT delta that was published.
    ///
    /// This is used by API-layer delivery fallbacks that need to carry the
    /// exact same mutation over a side channel when pub/sub is congested.
    ///
    /// # Errors
    ///
    /// Returns an error if the value exceeds the maximum inline size (64 KB),
    /// or [`error::IdentityError::Unauthorized`] if this agent is not
    /// permitted to write under the store's access policy (including a
    /// joined replica whose authoritative owner is not yet known).
    pub async fn put_with_delta(
        &self,
        key: String,
        value: Vec<u8>,
        content_type: String,
    ) -> error::Result<kv::KvStoreDelta> {
        let delta = {
            let mut store = self.sync.write().await;
            Self::check_local_write(&store, &self.agent_id)?;
            store
                .put(
                    key.clone(),
                    value.clone(),
                    content_type.clone(),
                    self.peer_id,
                )
                .map_err(|e| {
                    error::IdentityError::Storage(std::io::Error::other(format!(
                        "kv put failed: {e}",
                    )))
                })?;
            let entry = store.get(&key).cloned();
            let version = store.current_version();
            let mut delta = match entry {
                Some(e) => {
                    kv::KvStoreDelta::for_put(key, e, (self.peer_id, store.next_seq()), version)
                }
                None => {
                    return Err(error::IdentityError::Storage(std::io::Error::other(
                        "kv put succeeded but entry was not readable",
                    )));
                }
            };
            // Owner: attach an owner-signed checkpoint for relay-based recovery.
            if let Some(cp) = self.produce_checkpoint(&mut store) {
                delta.owner_checkpoint = Some(cp);
                // Carry the authoritative owner name so a relay whose local
                // name hasn't synced yet can still cache the checkpoint
                // (content_root binds the store name).
                delta.name_update = Some(store.name_register().clone());
            }
            delta
        };
        if let Err(e) = self.sync.publish_delta(self.peer_id, delta.clone()).await {
            tracing::warn!("failed to publish kv put delta: {e}");
        }
        Ok(delta)
    }

    /// Get a value by key.
    ///
    /// Returns `None` if the key does not exist or has been removed.
    ///
    /// # Errors
    ///
    /// Returns an error if the store cannot be read.
    pub async fn get(&self, key: &str) -> error::Result<Option<KvEntrySnapshot>> {
        let store = self.sync.read().await;
        Ok(store.get(key).map(|e| KvEntrySnapshot {
            key: e.key.clone(),
            value: e.value.clone(),
            content_hash: hex::encode(e.content_hash),
            content_type: e.content_type.clone(),
            metadata: e.metadata.clone(),
            created_at: e.created_at,
            updated_at: e.updated_at,
        }))
    }

    /// Remove a key from the store.
    ///
    /// # Errors
    ///
    /// Returns an error if the key does not exist.
    pub async fn remove(&self, key: &str) -> error::Result<()> {
        let _ = self.remove_with_delta(key).await?;
        Ok(())
    }

    /// Remove a key and return the CRDT delta that was published.
    ///
    /// # Errors
    ///
    /// Returns an error if the key does not exist, or
    /// [`error::IdentityError::Unauthorized`] if this agent is not permitted
    /// to write under the store's access policy.
    pub async fn remove_with_delta(&self, key: &str) -> error::Result<kv::KvStoreDelta> {
        let delta = {
            let mut store = self.sync.write().await;
            Self::check_local_write(&store, &self.agent_id)?;
            store.remove(key).map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "kv remove failed: {e}",
                )))
            })?;
            let mut d = kv::KvStoreDelta::new(store.current_version());
            d.removed
                .insert(key.to_string(), std::collections::HashSet::new());
            // Owner: attach an owner-signed checkpoint for the post-remove state.
            if let Some(cp) = self.produce_checkpoint(&mut store) {
                d.owner_checkpoint = Some(cp);
                // Carry the authoritative owner name alongside the checkpoint
                // so a relay can cache it regardless of local name state.
                d.name_update = Some(store.name_register().clone());
            }
            d
        };
        if let Err(e) = self.sync.publish_delta(self.peer_id, delta.clone()).await {
            tracing::warn!("failed to publish kv remove delta: {e}");
        }
        Ok(delta)
    }

    /// Apply a verified remote delta received through a non-pubsub channel.
    ///
    /// # Errors
    ///
    /// Returns an error if the delta fails to merge into the local store.
    pub async fn apply_remote_delta(
        &self,
        peer_id: saorsa_gossip_types::PeerId,
        delta: &kv::KvStoreDelta,
        writer: Option<identity::AgentId>,
    ) -> error::Result<()> {
        let mut store = self.sync.write().await;
        store
            .merge_delta(delta, peer_id, writer.as_ref())
            .map_err(|e| {
                error::IdentityError::Storage(std::io::Error::other(format!(
                    "kv direct delta merge failed: {e}",
                )))
            })
    }

    /// List all active keys in the store.
    ///
    /// # Errors
    ///
    /// Returns an error if the store cannot be read.
    pub async fn keys(&self) -> error::Result<Vec<KvEntrySnapshot>> {
        let store = self.sync.read().await;
        Ok(store
            .active_entries()
            .into_iter()
            .map(|e| KvEntrySnapshot {
                key: e.key.clone(),
                value: e.value.clone(),
                content_hash: hex::encode(e.content_hash),
                content_type: e.content_type.clone(),
                metadata: e.metadata.clone(),
                created_at: e.created_at,
                updated_at: e.updated_at,
            })
            .collect())
    }

    /// Get the store name.
    ///
    /// # Errors
    ///
    /// Returns an error if the store cannot be read.
    pub async fn name(&self) -> error::Result<String> {
        let store = self.sync.read().await;
        Ok(store.name().to_string())
    }
}

/// Read-only snapshot of a KvStore entry.
#[derive(Debug, Clone, serde::Serialize)]
pub struct KvEntrySnapshot {
    /// The key.
    pub key: String,
    /// The value bytes.
    pub value: Vec<u8>,
    /// BLAKE3 hash of the value (hex-encoded).
    pub content_hash: String,
    /// Content type (MIME).
    pub content_type: String,
    /// User metadata.
    pub metadata: std::collections::HashMap<String, String>,
    /// Unix milliseconds when created.
    pub created_at: u64,
    /// Unix milliseconds when last updated.
    pub updated_at: u64,
}

/// Ownership/policy/version metadata for a store, for auditability.
///
/// Returned by [`KvStoreHandle::ownership_info`]. `owner` is the hex-encoded
/// anchored owner, or `None` for a read-only no-anchor replica.
#[derive(Debug, Clone, serde::Serialize)]
pub struct KvStoreOwnershipInfo {
    /// Hex-encoded anchored owner, or `None` when no owner is anchored
    /// (read-only by design).
    pub owner: Option<String>,
    /// Access policy (`"signed"` / `"allowlisted"` / `"encrypted"`).
    pub policy: String,
    /// Store version (monotonic, bumped on every mutation).
    pub version: u64,
    /// Owner-announce policy freshness counter (distinct from `version`).
    pub policy_version: u64,
    /// Strongly-typed ownership discriminant (`"anchored"` / `"unknown"` /
    /// `"conflict"`).
    pub ownership_status: kv::OwnershipStatus,
    /// Hex-encoded owner claimed by a rejected announce (`conflict` only).
    pub announced_owner: Option<String>,
}

/// Read-only snapshot of a task's current state.
///
/// This is returned by `TaskListHandle::list_tasks()` and hides CRDT
/// internals, providing a clean API surface.
#[derive(Debug, Clone)]
pub struct TaskSnapshot {
    /// Unique task identifier.
    pub id: crdt::TaskId,
    /// Task title.
    pub title: String,
    /// Task description.
    pub description: String,
    /// Current checkbox state (Empty, Claimed, or Done).
    pub state: crdt::CheckboxState,
    /// Agent assigned to this task (if any).
    pub assignee: Option<identity::AgentId>,
    /// Human owner of the agent that created this task (if known).
    pub owner: Option<identity::UserId>,
    /// Task priority (0-255, higher = more important).
    pub priority: u8,
    /// The agent whose claim won (deterministic OR-Set winner), if claimed.
    /// Remains set after the task transitions to Done.
    pub claimed_by: Option<identity::AgentId>,
    /// Unix-millisecond timestamp of the winning claim, if claimed.
    pub claimed_at: Option<u64>,
    /// The agent whose completion won (deterministic OR-Set winner), if done.
    pub completed_by: Option<identity::AgentId>,
    /// Unix-millisecond timestamp of the winning completion, if done.
    pub completed_at: Option<u64>,
}

/// Outcome of a task-list mutation (claim or complete).
///
/// Returned by [`TaskListHandle::claim_task_versioned`] and
/// [`TaskListHandle::complete_task_versioned`].
///
/// `Committed` means the mutation was applied to the **local** replica and a
/// delta was best-effort published — it does NOT mean any peer has observed
/// the change, and it does NOT grant exclusive ownership. Claims and
/// completions are **advisory**: concurrent operations on other replicas
/// coexist in the CRDT and resolve to a single deterministic winner (earliest
/// timestamp, then lexicographic agent id) only after convergence.
///
/// `StaleLocalVersion` means the caller's fence token did not match this
/// replica's current `(epoch, revision)` — a LOCAL fencing signal. It is NOT
/// a distributed conflict: two replicas at the same token both pass, so the
/// fence cannot provide cross-replica exclusion. A mismatch may be a stale
/// revision (the local snapshot moved) OR a stale epoch (the daemon restarted
/// and the caller's token predates it — the restart-ABA case).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaskMutationOutcome {
    /// The mutation was committed locally; `fence` is the new local token.
    Committed {
        /// The task list's fence token after this mutation (epoch + revision).
        fence: FenceToken,
        /// Advisory ownership snapshot computed from the local OR-Set at
        /// commit time. Advisory — see [`AdvisoryOwnership`].
        advisory: AdvisoryOwnership,
    },
    /// The caller's fence token did not match this replica's current token;
    /// nothing was mutated. Local staleness guard (stale revision) or a
    /// restart-epoch mismatch — never a distributed conflict.
    StaleLocalVersion {
        /// The task list's current (unchanged) local fence token.
        current: FenceToken,
    },
}

/// Opaque local-replica fencing token.
///
/// Combines a per-replica `epoch` (regenerated when the handle is rebuilt —
/// i.e. on daemon restart) with the local `revision` (the TaskList version
/// counter, which advances on every effective local snapshot change,
/// including remote merges). The token is **opaque** over the wire: clients
/// must echo it verbatim and MUST NOT interpret or construct it.
///
/// ABA safety: because the epoch changes across restart, a token captured
/// before a restart can never match a post-restart token even if the revision
/// counter later reaches the same value. This closes the restart-ABA window
/// without persisting task state.
///
/// This is a LOCAL fence only (per-replica): two replicas at the same
/// `(epoch, revision)` can both accept. It is not a distributed CAS.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FenceToken {
    /// Per-replica epoch; regenerated on restart.
    pub epoch: u64,
    /// Local revision = TaskList version counter.
    pub revision: u64,
}

impl FenceToken {
    /// Opaque wire encoding: `"epoch:revision"`. Clients echo this verbatim.
    #[must_use]
    pub fn to_wire(&self) -> String {
        format!("{}:{}", self.epoch, self.revision)
    }

    /// Parse an opaque wire token.
    ///
    /// Returns `Ok(token)` for a well-formed `"epoch:revision"` string, or
    /// `Err(&'static str)` if the token is malformed (missing colon,
    /// non-numeric, or integer overflow). Callers MUST distinguish **absent**
    /// (`fence_token: None` → unconditional advisory commit) from **present but
    /// malformed** (`Err` → reject with 400/409 without mutation). Collapsing
    /// the two into `None` would let a corrupt/legacy/attacker token silently
    /// downgrade a fenced request to an unfenced one.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the string is not exactly two colon-separated `u64`
    /// fields.
    pub fn from_wire(s: &str) -> Result<Self, &'static str> {
        let (epoch, revision) = s
            .split_once(':')
            .ok_or("malformed fence token: expected 'epoch:revision'")?;
        let epoch = epoch
            .parse()
            .map_err(|_| "malformed fence token: epoch is not a valid u64")?;
        let revision = revision
            .parse()
            .map_err(|_| "malformed fence token: revision is not a valid u64")?;
        Ok(Self { epoch, revision })
    }
}

/// Advisory ownership snapshot reported after a local claim/complete commit.
///
/// "Advisory" means this reflects the local replica's CRDT resolution at the
/// instant of commit. It is **not** a distributed lock and **not** a promise
/// of final ownership:
///
/// - `locally_winning` is provisional. A strictly-earlier-timestamp candidate
///   arriving via a later merge will flip it to `false` (the resolved winner
///   timestamp is monotone non-increasing).
/// - Final ownership is only determinable after all replicas have converged,
///   and is always non-exclusive — every candidate remains recorded in the
///   OR-Set (see [`crdt::TaskItem::claims`]).
///
/// `current_winner` lets a superseded caller see who currently beats them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AdvisoryOwnership {
    /// The agent that performed this mutation (the caller's own candidate).
    pub agent: identity::AgentId,
    /// Whether `agent` is the local OR-Set's current deterministic winner for
    /// this operation (claim → [`crdt::TaskItem::claim_record`], complete →
    /// [`crdt::TaskItem::completion_record`]). Provisional; may flip on merge.
    pub locally_winning: bool,
    /// The local OR-Set's current deterministic winner `(agent, unix_ms)`, or
    /// `None` if no candidate exists. When `!locally_winning`, this is the
    /// agent that currently beats `agent`.
    pub current_winner: Option<(identity::AgentId, u64)>,
}

/// The x0x protocol version.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// The name. Three bytes. A palindrome. A philosophy.
pub const NAME: &str = "x0x";

/// X0X-0070b: drain inbound [`peer_relay::RelayedDm`] envelopes from
/// the [`network::NetworkNode`] and dispatch via the
/// [`peer_relay::PeerRelay`] engine. Spawned once per network-configured
/// [`Agent`] from [`AgentBuilder::build`].
///
/// # Per-arm behavior
///
/// * [`peer_relay::RelayDisposition::DeliverLocally`] - synthesises the
///   *original* sender's `MachineId`-as-`PeerId` from
///   `relayed.inner.sender_machine_id` and re-injects the inner
///   [`dm::DmEnvelope`] onto the canonical direct-DM channel via
///   [`network::NetworkNode::inject_inbound_direct`]. The downstream
///   direct-DM listener cannot distinguish a relayed packet from a
///   direct one.
/// * [`peer_relay::RelayDisposition::Forward`] - resolves `dst_agent_id`
///   to a `MachineId` via the identity-discovery cache, re-encodes the
///   inner envelope with postcard, and sends it on the standard
///   direct-DM stream ([`network::DIRECT_MESSAGE_STREAM_TYPE`]). The
///   wire prefix stamps *our* (the relay's) `AgentId` so the receiving
///   Agent's binding check at its direct listener (wire `sender_agent_id`
///   must match the QUIC peer's `MachineId`) passes - trust on the
///   inner envelope still flows from its embedded ML-DSA-65 signature.
///   If the destination is not in the discovery cache the forward
///   drops with a `warn!`.
/// * [`peer_relay::RelayDisposition::Refuse`] - `debug!` log only.
///   [`peer_relay::PeerRelay::disposition_for`] already incremented the
///   appropriate `relay_refused_*` counter as a side effect.
///
/// # Revocation gate
///
/// Before delivering locally or forwarding, the listener checks the
/// inner envelope's *origin* `sender_agent_id` against `revocation_set`.
/// This is required because the local-delivery path re-injects the inner
/// envelope onto the direct-DM channel
/// ([`network::NetworkNode::inject_inbound_direct`]), which does **not**
/// run the `dm_inbox` gossip-path revocation gate (#130). Without this
/// check a revoked agent that cannot direct-connect (e.g. NAT-blocked)
/// could still reach the recipient via a relay, bypassing revocation.
/// A revoked origin is dropped and counted as `relay_dropped_revoked`.
fn spawn_relay_dm_listener(
    network: std::sync::Arc<network::NetworkNode>,
    peer_relay: std::sync::Arc<peer_relay::PeerRelay>,
    identity_discovery_cache: std::sync::Arc<
        tokio::sync::RwLock<std::collections::HashMap<identity::AgentId, DiscoveredAgent>>,
    >,
    revocation_set: std::sync::Arc<tokio::sync::RwLock<revocation::RevocationSet>>,
    contact_store: std::sync::Arc<tokio::sync::RwLock<contacts::ContactStore>>,
    local_agent_id: identity::AgentId,
) {
    tokio::spawn(async move {
        tracing::info!(target: "x0x::relay", stage = "listener", "relay-DM listener started");
        loop {
            let Some((relay_peer_id, _relay_sender_agent_id, relayed)) =
                network.recv_relayed_dm().await
            else {
                tracing::warn!(
                    target: "x0x::relay",
                    stage = "listener",
                    "network.recv_relayed_dm channel closed - listener exiting"
                );
                break;
            };
            let now_ms = dm::now_unix_ms();
            // #193 contact gate: resolve the relay header's authenticated
            // sender against the contact store before classifying. The
            // gate itself is enforced inside `disposition_for`; this async
            // resolution belongs here (the contact store is an async
            // RwLock, and `disposition_for` is sync).
            //
            // Trust semantics: only *explicitly-trusted* contacts
            // (Known/Trusted) pass the gate — a merely-discovered
            // `Unknown` entry (auto-created by `register_announced_machine`
            // → `add_machine`, lib.rs ~576) does NOT, so the gate means
            // "my contacts", not "anyone I've seen". A `Blocked` entry is
            // refused unconditionally (see RelayRefusal::Blocked).
            //
            // TOCTOU: membership is snapshotted per message here and passed
            // as bools, so a contact removed/blocked mid-flight can have one
            // forward slip through before the next relay frame re-snapshots.
            // Acceptable — the inner DmEnvelope is end-to-end encrypted and
            // origin-signed, and the per-frame snapshot bounds the window to
            // a single hop.
            let sender_agent_id = identity::AgentId(relayed.header.sender_agent_id);
            let (is_sender_contact, is_sender_blocked) = {
                let store = contact_store.read().await;
                match store.get(&sender_agent_id) {
                    Some(c) => (
                        matches!(
                            c.trust_level,
                            contacts::TrustLevel::Known | contacts::TrustLevel::Trusted
                        ),
                        c.trust_level == contacts::TrustLevel::Blocked,
                    ),
                    None => (false, false),
                }
            };
            let disposition = peer_relay.disposition_for(
                &relayed,
                &local_agent_id,
                now_ms,
                is_sender_contact,
                is_sender_blocked,
            );

            // Revocation gate (PR #177 review, fix 1): the inner envelope's
            // ML-DSA-65 origin signature is the trust anchor, but a revoked
            // origin must be dropped even when it arrives via a relay. The
            // deliver/forward paths do not traverse the dm_inbox revocation
            // gate, so enforce it here for both, before any delivery.
            if matches!(
                disposition,
                peer_relay::RelayDisposition::DeliverLocally
                    | peer_relay::RelayDisposition::Forward { .. }
            ) {
                let origin = identity::AgentId(relayed.inner.sender_agent_id);
                let revoked = { revocation_set.read().await.is_agent_revoked(&origin) };
                if revoked {
                    peer_relay.record_relay_dropped_revoked();
                    tracing::info!(
                        target: "x0x::relay",
                        stage = "revoked_drop",
                        relay_peer = ?relay_peer_id,
                        origin = %hex::encode(origin.as_bytes()),
                        "relayed DM dropped: origin agent is revoked"
                    );
                    continue;
                }
            }

            match disposition {
                peer_relay::RelayDisposition::DeliverLocally => {
                    let sender_machine_id = relayed.inner.sender_machine_id;
                    let sender_peer_id = ant_quic::PeerId(sender_machine_id);
                    let inner_wire = match postcard::to_allocvec(&relayed.inner) {
                        Ok(b) => b,
                        Err(e) => {
                            tracing::warn!(
                                target: "x0x::relay",
                                stage = "deliver_local",
                                relay_peer = ?relay_peer_id,
                                error = %e,
                                "failed to re-encode inner envelope for local delivery"
                            );
                            continue;
                        }
                    };
                    // Wire shape mirrors the direct-DM listener's parse:
                    //   [sender_agent_id: 32][postcard(DmEnvelope)]
                    let mut payload = Vec::with_capacity(32 + inner_wire.len());
                    payload.extend_from_slice(&relayed.inner.sender_agent_id);
                    payload.extend_from_slice(&inner_wire);
                    if let Err(e) = network
                        .inject_inbound_direct(sender_peer_id, bytes::Bytes::from(payload))
                        .await
                    {
                        tracing::warn!(
                            target: "x0x::relay",
                            stage = "deliver_local",
                            relay_peer = ?relay_peer_id,
                            error = %e,
                            "DeliverLocally inject onto direct channel failed"
                        );
                    }
                }
                peer_relay::RelayDisposition::Forward { dst_agent_id } => {
                    let dst = identity::AgentId(dst_agent_id);
                    let dst_machine_id = {
                        let cache = identity_discovery_cache.read().await;
                        cache.get(&dst).map(|d| d.machine_id)
                    };
                    let Some(dst_machine_id) = dst_machine_id else {
                        tracing::warn!(
                            target: "x0x::relay",
                            stage = "forward",
                            dst = %hex::encode(dst.as_bytes()),
                            "Forward dropped: dst not in identity-discovery cache"
                        );
                        continue;
                    };
                    let inner_wire = match postcard::to_allocvec(&relayed.inner) {
                        Ok(b) => b,
                        Err(e) => {
                            tracing::warn!(
                                target: "x0x::relay",
                                stage = "forward",
                                dst = %hex::encode(dst.as_bytes()),
                                error = %e,
                                "failed to re-encode inner envelope for forward"
                            );
                            continue;
                        }
                    };
                    let forward_bytes = u64::try_from(inner_wire.len()).unwrap_or(u64::MAX);
                    let reservation = match peer_relay
                        .reserve_forward(relayed.header.sender_agent_id, forward_bytes)
                    {
                        Ok(reservation) => reservation,
                        Err(reason) => {
                            tracing::debug!(
                                target: "x0x::relay",
                                stage = "refuse",
                                relay_peer = ?relay_peer_id,
                                reason = ?reason,
                                "RelayedDm forward refused by quota admission"
                            );
                            continue;
                        }
                    };
                    let dst_peer_id = ant_quic::PeerId(dst_machine_id.0);
                    match network
                        .send_direct_typed(
                            &dst_peer_id,
                            local_agent_id.as_bytes(),
                            network::DIRECT_MESSAGE_STREAM_TYPE,
                            &inner_wire,
                        )
                        .await
                    {
                        Ok(()) => reservation.commit(),
                        Err(e) => {
                            tracing::warn!(
                                target: "x0x::relay",
                                stage = "forward",
                                dst = %hex::encode(dst.as_bytes()),
                                error = %e,
                                "Forward send_direct_typed failed"
                            );
                        }
                    }
                }
                peer_relay::RelayDisposition::Refuse(reason) => {
                    tracing::debug!(
                        target: "x0x::relay",
                        stage = "refuse",
                        relay_peer = ?relay_peer_id,
                        reason = ?reason,
                        "RelayedDm refused"
                    );
                }
            }
        }
    });
}

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

    fn sa(s: &str) -> std::net::SocketAddr {
        s.parse().expect("valid SocketAddr literal in test")
    }

    #[test]
    fn discovery_rebroadcast_is_one_shot_per_announcement_key() {
        let now = std::time::Instant::now();
        let mut state = std::collections::HashMap::new();

        assert!(should_rebroadcast_discovery_once(
            &mut state,
            (7_u8, 42_u64),
            now
        ));
        assert!(!should_rebroadcast_discovery_once(
            &mut state,
            (7_u8, 42_u64),
            now + std::time::Duration::from_secs(20),
        ));
        assert!(should_rebroadcast_discovery_once(
            &mut state,
            (7_u8, 43_u64),
            now + std::time::Duration::from_secs(20),
        ));
    }

    #[test]
    fn discovery_ttl_uses_local_last_seen_not_sender_timestamp() {
        let cutoff = 900;

        assert!(discovery_record_is_live(100, 1_000, cutoff));
        assert!(discovery_record_is_live(10_000, cutoff, cutoff));
        assert!(!discovery_record_is_live(10_000, cutoff - 1, cutoff));
    }

    #[test]
    fn is_publicly_advertisable_rejects_lan_and_special_scopes() {
        // v4 non-global scopes
        assert!(
            !is_publicly_advertisable(sa("127.0.0.1:5483")),
            "loopback v4"
        );
        assert!(!is_publicly_advertisable(sa("10.1.2.3:5483")), "rfc1918 /8");
        assert!(
            !is_publicly_advertisable(sa("172.20.0.5:5483")),
            "rfc1918 /12"
        );
        assert!(
            !is_publicly_advertisable(sa("192.168.1.5:5483")),
            "rfc1918 /16"
        );
        assert!(
            !is_publicly_advertisable(sa("169.254.1.1:5483")),
            "link-local v4"
        );
        assert!(
            !is_publicly_advertisable(sa("100.64.1.1:5483")),
            "CGNAT (unreachable outside carrier)"
        );
        assert!(
            !is_publicly_advertisable(sa("0.0.0.0:5483")),
            "unspecified v4"
        );

        // v6 non-global scopes
        assert!(!is_publicly_advertisable(sa("[::1]:5483")), "loopback v6");
        assert!(
            !is_publicly_advertisable(sa("[fe80::1]:5483")),
            "link-local v6"
        );
        assert!(!is_publicly_advertisable(sa("[fd00::1]:5483")), "ULA v6");

        // port 0 never advertisable regardless of ip scope
        assert!(
            !is_publicly_advertisable(sa("1.2.3.4:0")),
            "port 0 on global v4"
        );

        // Globally-routable positives
        assert!(is_publicly_advertisable(sa("1.2.3.4:5483")), "global v4");
        assert!(
            is_publicly_advertisable(sa("[2001:db8::1]:5483")),
            "global v6 (documentation doc but is_globally_routable permits)",
        );
        assert!(
            is_publicly_advertisable(sa("8.8.8.8:9000")),
            "global v4 on non-default port",
        );

        // Reserved documentation ranges are correctly rejected by
        // is_globally_routable even though they are not RFC1918.
        assert!(
            !is_publicly_advertisable(sa("192.0.2.1:5483")),
            "TEST-NET-1 documentation range"
        );
        assert!(
            !is_publicly_advertisable(sa("203.0.113.10:5483")),
            "TEST-NET-3 documentation range"
        );
    }

    #[test]
    fn public_address_filter_drops_global_discovery_unsafe_candidates() {
        let filtered = filter_publicly_advertisable_addrs(vec![
            sa("127.0.0.1:5483"),
            sa("10.1.2.3:5483"),
            sa("100.64.1.1:5483"),
            sa("169.254.1.1:5483"),
            sa("1.2.3.4:0"),
            sa("[::1]:5483"),
            sa("[fd00::1]:5483"),
            sa("8.8.8.8:5483"),
            sa("[2001:db8::1]:5483"),
        ]);

        assert_eq!(filtered, vec![sa("8.8.8.8:5483"), sa("[2001:db8::1]:5483")]);
    }

    #[test]
    fn local_discovery_filter_keeps_same_partition_candidates() {
        let filtered = filter_discovery_announcement_addrs(
            vec![
                sa("127.0.0.1:5483"),
                sa("10.1.2.3:5483"),
                sa("100.64.1.1:5483"),
                sa("169.254.1.1:5483"),
                sa("1.2.3.4:0"),
                sa("[::1]:5483"),
                sa("[fd00::1]:5483"),
                sa("8.8.8.8:5483"),
            ],
            true,
        );

        assert_eq!(
            filtered,
            vec![
                sa("127.0.0.1:5483"),
                sa("10.1.2.3:5483"),
                sa("100.64.1.1:5483"),
                sa("[::1]:5483"),
                sa("[fd00::1]:5483"),
                sa("8.8.8.8:5483"),
            ],
        );
    }

    #[test]
    fn local_discovery_scope_tracks_bootstrap_partition() {
        let mut config = network::NetworkConfig {
            bootstrap_nodes: Vec::new(),
            ..network::NetworkConfig::default()
        };
        assert!(allow_local_discovery_addresses(&config));

        config.bootstrap_nodes = vec![sa("127.0.0.1:5483"), sa("192.168.1.10:5483")];
        assert!(allow_local_discovery_addresses(&config));

        config.bootstrap_nodes = vec![sa("127.0.0.1:5483"), sa("8.8.8.8:5483")];
        assert!(!allow_local_discovery_addresses(&config));
    }

    #[test]
    fn local_direct_probe_addrs_prioritizes_same_lan_ipv4() {
        let local = [std::net::Ipv4Addr::new(192, 168, 1, 212)];
        let ranked = local_direct_probe_addrs_with_local_v4s(
            &[
                sa("100.118.167.101:27749"),
                sa("192.168.0.1:27749"),
                sa("192.168.1.108:27749"),
                sa("[2a0d:3344:32d:2e10::1]:27749"),
                sa("[fd7a:115c:a1e0::b01:a7ac]:27749"),
            ],
            &local,
        );

        assert_eq!(
            ranked,
            vec![
                sa("192.168.1.108:27749"),
                sa("192.168.0.1:27749"),
                sa("100.118.167.101:27749"),
            ],
        );
    }

    #[tokio::test]
    async fn announcement_builders_filter_global_discovery_addresses() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .build()
            .await
            .expect("agent");
        let addresses = vec![
            sa("192.168.1.5:5483"),
            sa("100.64.1.1:5483"),
            sa("1.2.3.4:0"),
            sa("8.8.8.8:5483"),
            sa("[fd00::1]:5483"),
            sa("[2001:db8::1]:5483"),
        ];
        let expected = vec![sa("8.8.8.8:5483"), sa("[2001:db8::1]:5483")];

        let identity_announcement = agent
            .build_identity_announcement_with_addrs(IdentityAnnouncementBuildOptions {
                include_user_identity: false,
                human_consent: false,
                addresses: addresses.clone(),
                assist_snapshot: None,
                reachable_via: Vec::new(),
                relay_candidates: Vec::new(),
                allow_local_scope: false,
            })
            .expect("identity announcement");
        assert_eq!(identity_announcement.addresses, expected);
        identity_announcement
            .verify()
            .expect("filtered identity announcement verifies");

        let machine_announcement = build_machine_announcement_for_identity(
            &agent.identity,
            addresses,
            1,
            None,
            Vec::new(),
            Vec::new(),
            false,
        )
        .expect("machine announcement");
        assert_eq!(machine_announcement.addresses, expected);
        machine_announcement
            .verify()
            .expect("filtered machine announcement verifies");
    }

    #[test]
    fn presence_parse_addr_hints_drops_private_scopes() {
        // Older peers ship a mix of scopes. parse_addr_hints should return only
        // globally-advertisable entries so our dial loop never burns budget on
        // unreachable candidates.
        let hints = vec![
            "127.0.0.1:5483".to_string(),
            "10.200.0.1:5483".to_string(),
            "[fd00::1]:5483".to_string(),
            "1.2.3.4:5483".to_string(),
            "[2001:db8::1]:5483".to_string(),
            "not-an-address".to_string(),
        ];
        let parsed = presence::parse_addr_hints(&hints);
        let got: Vec<String> = parsed.iter().map(|a| a.to_string()).collect();
        assert_eq!(
            got,
            vec!["1.2.3.4:5483".to_string(), "[2001:db8::1]:5483".to_string()],
            "only globally-advertisable addresses survive inbound parsing"
        );
    }

    #[test]
    fn name_is_palindrome() {
        let name = NAME;
        let reversed: String = name.chars().rev().collect();
        assert_eq!(name, reversed, "x0x must be a palindrome");
    }

    #[test]
    fn name_is_three_bytes() {
        assert_eq!(NAME.len(), 3, "x0x must be exactly three bytes");
    }

    #[test]
    fn name_is_ai_native() {
        // No uppercase, no spaces, no special chars that conflict
        // with shell, YAML, Markdown, or URL encoding
        assert!(NAME.chars().all(|c| c.is_ascii_alphanumeric()));
    }

    #[test]
    fn raw_quic_receive_ack_failure_falls_back_when_gossip_available() {
        let err = error::NetworkError::ConnectionFailed(
            "send_with_receive_ack failed: Connection closed: Superseded".to_string(),
        );
        assert!(
            !Agent::raw_quic_error_should_stop_fallback(&err, true),
            "transient raw ACK lifecycle churn should not suppress gossip fallback"
        );
        assert!(
            Agent::raw_quic_error_should_stop_fallback(&err, false),
            "without a gossip capability, the raw ACK failure remains terminal"
        );
    }

    #[test]
    fn raw_quic_receive_backpressure_falls_back_when_gossip_available() {
        let err = error::NetworkError::RemoteReceiveBackpressured(
            "send_with_receive_ack failed: Remote receive pipeline rejected payload: Backpressured"
                .to_string(),
        );
        assert!(
            !Agent::raw_quic_error_should_stop_fallback(&err, true),
            "receiver congestion should allow gossip fallback"
        );
        assert!(
            Agent::raw_quic_error_should_stop_fallback(&err, false),
            "without a gossip capability, receiver congestion remains terminal"
        );
        assert!(matches!(
            Agent::map_raw_quic_dm_error(err),
            dm::DmError::ReceiverBackpressured { .. }
        ));
    }

    #[test]
    fn raw_quic_payload_errors_still_stop_fallback() {
        let err = error::NetworkError::PayloadTooLarge { size: 2, max: 1 };
        assert!(Agent::raw_quic_error_should_stop_fallback(&err, true));
    }

    #[tokio::test]
    async fn unusable_capability_advert_falls_back_to_contact_card() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .build()
            .await
            .expect("agent");
        let target = identity::AgentId([7_u8; 32]);
        let target_machine = identity::MachineId([9_u8; 32]);

        agent.capability_store().insert(
            target,
            target_machine,
            dm::DmCapabilities::pending(),
            dm_capability::now_unix_ms(),
        );
        agent.contacts().write().await.add(contacts::Contact {
            agent_id: target,
            trust_level: contacts::TrustLevel::Trusted,
            label: None,
            added_at: 0,
            last_seen: None,
            identity_type: contacts::IdentityType::Known,
            machines: Vec::new(),
            dm_capabilities: Some(dm::DmCapabilities::v1_gossip_ready(vec![42_u8; 1184])),
        });

        let err = agent
            .send_direct_with_config(
                &target,
                b"contact-card-capability".to_vec(),
                dm::DmSendConfig {
                    require_gossip: true,
                    ..dm::DmSendConfig::default()
                },
            )
            .await
            .expect_err("contact-card capability should be used before gossip runtime fails");

        assert!(
            matches!(err, dm::DmError::LocalGossipUnavailable(_)),
            "unexpected error: {err:?}"
        );
    }

    #[tokio::test]
    async fn self_dm_uses_loopback_and_delivers_to_subscribers() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .build()
            .await
            .expect("agent");
        let mut rx = agent.subscribe_direct();
        let payload = b"loopback-self-dm".to_vec();

        let receipt = agent
            .send_direct_with_config(
                &agent.agent_id(),
                payload.clone(),
                dm::DmSendConfig::default(),
            )
            .await
            .expect("self-DM should use loopback path");

        assert_eq!(receipt.path, dm::DmPath::Loopback);
        let msg = tokio::time::timeout(std::time::Duration::from_secs(1), rx.recv())
            .await
            .expect("self-DM should be delivered promptly")
            .expect("subscriber should remain open");
        assert_eq!(msg.sender, agent.agent_id());
        assert_eq!(msg.machine_id, agent.machine_id());
        assert_eq!(msg.payload, payload);
        assert!(msg.verified);
        assert_eq!(msg.trust_decision, Some(trust::TrustDecision::Accept));

        let diagnostics = agent.direct_messaging().diagnostics_snapshot();
        assert_eq!(diagnostics.stats.outgoing_send_succeeded, 1);
        assert_eq!(diagnostics.stats.outgoing_path_loopback, 1);
        assert_eq!(diagnostics.stats.incoming_envelopes_total, 1);
        assert_eq!(diagnostics.stats.incoming_delivered_to_subscribe, 1);
    }

    fn loopback_network_config() -> network::NetworkConfig {
        network::NetworkConfig {
            bind_addr: Some("127.0.0.1:0".parse().expect("loopback addr")),
            bootstrap_nodes: Vec::new(),
            ..network::NetworkConfig::default()
        }
    }

    fn normalize_loopback_addr(addr: std::net::SocketAddr) -> std::net::SocketAddr {
        if addr.ip().is_unspecified() {
            std::net::SocketAddr::new(
                std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
                addr.port(),
            )
        } else {
            addr
        }
    }

    #[tokio::test]
    async fn shutdown_aborts_identity_heartbeat_task() {
        struct DropFlag(std::sync::Arc<std::sync::atomic::AtomicBool>);

        impl Drop for DropFlag {
            fn drop(&mut self) {
                self.0.store(true, std::sync::atomic::Ordering::Release);
            }
        }

        let dir = tempfile::tempdir().expect("tmpdir");
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .build()
            .await
            .expect("agent");

        let dropped = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let dropped_for_task = std::sync::Arc::clone(&dropped);
        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
        let handle = tokio::spawn(async move {
            let _drop_flag = DropFlag(dropped_for_task);
            let _ = started_tx.send(());
            std::future::pending::<()>().await;
        });
        started_rx.await.expect("heartbeat task started");

        *agent.heartbeat_handle.lock().await = Some(handle);
        assert!(agent.heartbeat_handle.lock().await.is_some());

        agent.shutdown().await;
        assert!(agent.heartbeat_handle.lock().await.is_none());
        assert!(dropped.load(std::sync::atomic::Ordering::Acquire));
    }

    /// Issue #126 / WS1.5: the delta-merge + state-request subscription loops
    /// spawned by `create_kv_store` / `create_task_list` must be routed through
    /// `spawn_tracked` so `Agent::shutdown()` drains and aborts them. Previously
    /// they detached via bare `tokio::spawn` and only ended when the gossip
    /// runtime later dropped its topic sender.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn shutdown_drains_crdt_kv_sync_tasks() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .with_peer_cache_disabled()
            .with_network_config(loopback_network_config())
            .build()
            .await
            .expect("agent");

        // Build() constructs the gossip runtime, so creating a store + a list
        // works without join_network. Each creation spawns the delta-merge and
        // state-request subscription loops (plus a bounded bootstrap requester
        // for an empty store/list).
        let baseline = agent
            .tracked_tasks
            .lock()
            .expect("tracked_tasks")
            .handles
            .len();

        agent
            .create_kv_store("ws15-store", "ws15-store-topic")
            .await
            .expect("create kv store");
        agent
            .create_task_list("ws15-list", "ws15-list-topic")
            .await
            .expect("create task list");

        // The loops must now be registered with spawn_tracked. With the old bare
        // tokio::spawn this count would NOT have moved.
        let (registered, abort_handles): (usize, Vec<tokio::task::AbortHandle>) = {
            let guard = agent.tracked_tasks.lock().expect("tracked_tasks");
            let aborts = guard.handles.iter().map(|h| h.abort_handle()).collect();
            (guard.handles.len(), aborts)
        };
        assert!(
            registered > baseline,
            "CRDT/KV sync loops must register with spawn_tracked \
             (registry {registered}, baseline {baseline})"
        );

        agent.shutdown().await;

        // shutdown() closes the registry and drains it (handles taken, grace-
        // awaited, stragglers aborted).
        let after = agent.tracked_tasks.lock().expect("tracked_tasks");
        assert!(
            after.closed,
            "tracked-task registry must be closed after shutdown"
        );
        assert!(
            after.handles.is_empty(),
            "tracked-task registry must be drained after shutdown ({} left)",
            after.handles.len()
        );
        drop(after);

        // Every formerly-tracked sync loop terminated.
        for handle in &abort_handles {
            assert!(
                handle.is_finished(),
                "a CRDT/KV sync task did not terminate after shutdown"
            );
        }
    }

    /// P1 fence (restart-ABA): a fence token captured before an incarnation
    /// change (daemon restart) must be rejected even when submitted at the
    /// SAME revision afterwards — the per-replica epoch component differs, so
    /// the token cannot ABA-match the post-restart one. A token captured after
    /// the epoch change at the same revision is accepted (teeth: the gate
    /// rejects the stale epoch, not everything).
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn pre_restart_fence_token_rejected_at_same_revision_after_epoch_change() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .with_peer_cache_disabled()
            .with_network_config(loopback_network_config())
            .build()
            .await
            .expect("agent");

        let mut handle = agent
            .create_task_list("restart-fence", "restart-fence-topic")
            .await
            .expect("create task list");
        let (task_id, _added_version) = handle
            .add_task_versioned("task".to_string(), "d".to_string())
            .await
            .expect("add task");

        // Token captured at epoch E1, revision R (before the "restart").
        let pre_restart_token = handle.version().await;
        let revision = pre_restart_token.revision;

        // Simulate a restart: a new incarnation epoch, revision UNCHANGED.
        handle.set_replica_epoch_for_testing(pre_restart_token.epoch.wrapping_add(1));

        // The pre-restart token at the same revision MUST be rejected — the
        // epoch differs, so it cannot ABA-match. Nothing mutates.
        let outcome = handle
            .claim_task_versioned(task_id, Some(pre_restart_token))
            .await
            .expect("claim call");
        match outcome {
            crate::TaskMutationOutcome::StaleLocalVersion { current } => {
                assert_eq!(
                    current.revision, revision,
                    "a rejected fence must not change the revision"
                );
                assert_ne!(
                    current.epoch, pre_restart_token.epoch,
                    "the echoed current token carries the new (post-restart) epoch"
                );
            }
            other => panic!("expected StaleLocalVersion, got {other:?}"),
        }

        // Non-mutation: the task is still unclaimed.
        let tasks = handle.list_tasks().await.expect("list tasks");
        let t = tasks
            .iter()
            .find(|t| t.id == task_id)
            .expect("task present after rejection");
        assert!(
            t.state.is_empty(),
            "a rejected fence must not mutate the task: {:?}",
            t.state
        );

        // Teeth: a token captured AFTER the epoch change, at the same revision,
        // is accepted — the gate rejects the stale epoch specifically.
        let post_restart_token = handle.version().await;
        assert_ne!(
            post_restart_token.epoch, pre_restart_token.epoch,
            "post-restart token carries the new epoch"
        );
        let outcome2 = handle
            .claim_task_versioned(task_id, Some(post_restart_token))
            .await
            .expect("claim call 2");
        assert!(
            matches!(outcome2, crate::TaskMutationOutcome::Committed { .. }),
            "a post-restart token at the current revision must commit"
        );

        agent.shutdown().await;
    }

    // ========================================================================
    // #124 / WS1.3 tranche 4 — shutdown ordering invariants.
    //
    // `shutdown()` and `begin_shutdown()` carry ordering guarantees that are
    // themselves correctness properties (a still-running join_network must not
    // leak a task past shutdown; a second shutdown must never panic; a token-
    // respecting task must be graced, not force-aborted). These pin them as
    // fast, daemon-free unit tests. The WS/SSE close-on-shutdown notification
    // path is already covered at integration tier by
    // `daemon_api_shutdown_with_sse_client` and is not re-duplicated here
    // (avoiding a src/server/mod.rs touch during Eng B's #125 window).
    // ========================================================================

    /// `begin_shutdown()` is the synchronous shutdown prefix: it cancels the
    /// token AND closes the tracked-task registry, without draining. After it
    /// returns, `spawn_tracked` must refuse (next test) and a subsequent
    /// `shutdown()` must still complete cleanly. Pins that the two halves of
    /// the shutdown signal — token + closed-flag — move together.
    #[tokio::test]
    async fn begin_shutdown_closes_registry_and_cancels_token() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .build()
            .await
            .expect("agent");

        assert!(
            !agent.shutdown_token.is_cancelled(),
            "token must not be cancelled before shutdown begins"
        );
        assert!(
            !agent.tracked_tasks.lock().expect("tracked_tasks").closed,
            "registry must be open before shutdown begins"
        );

        agent.begin_shutdown();

        assert!(
            agent.shutdown_token.is_cancelled(),
            "begin_shutdown must cancel the shutdown token"
        );
        assert!(
            agent.tracked_tasks.lock().expect("tracked_tasks").closed,
            "begin_shutdown must close the tracked-task registry"
        );

        // begin_shutdown does NOT drain — that is shutdown()'s job. The handles
        // must still be present (untouched) until shutdown() runs.
        // (None were spawned here, so the registry is empty-but-closed.)
    }

    /// Once `begin_shutdown()` has closed the registry, `spawn_tracked` must be
    /// a no-op: the handle is NOT pushed. This is the invariant that defeats a
    /// racing `join_network` from leaking heartbeat/reaper/presence tasks past
    /// the subsequent `shutdown()` (the registry drains empty because nothing
    // new can enter after close).
    #[tokio::test]
    async fn spawn_tracked_refuses_after_begin_shutdown() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .build()
            .await
            .expect("agent");

        // Before begin_shutdown: spawn_tracked accepts.
        agent.spawn_tracked(async {});
        let before = agent
            .tracked_tasks
            .lock()
            .expect("tracked_tasks")
            .handles
            .len();
        assert_eq!(
            before, 1,
            "spawn_tracked must register a task before begin_shutdown"
        );

        // Close the registry, then attempt another spawn.
        agent.begin_shutdown();
        agent.spawn_tracked(async {});

        {
            let after = agent.tracked_tasks.lock().expect("tracked_tasks");
            assert_eq!(
                after.handles.len(),
                before,
                "spawn_tracked must be a no-op (handle NOT pushed) after begin_shutdown \
                 closed the registry — a racing join_network would otherwise leak a task"
            );
            assert!(after.closed, "registry must remain closed");
        }

        // Clean up the one task we did register so it does not outlive the test.
        agent.shutdown().await;
    }

    /// `shutdown()` is documented idempotent: `cancel()` is idempotent, the
    /// registry drains empty on a second call, and the `Option<JoinHandle>`
    /// `stop_*` helpers use `Option::take` (a second take is None). Pin that a
    /// double shutdown never panics and leaves the registry drained.
    #[tokio::test]
    async fn shutdown_is_idempotent_and_never_panics_on_second_call() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .build()
            .await
            .expect("agent");

        agent.shutdown().await;
        // The invariant: a second shutdown must be a safe no-op, never panic
        // (an embedder re-entering shutdown on an error path must not crash).
        agent.shutdown().await;

        let registry = agent.tracked_tasks.lock().expect("tracked_tasks");
        assert!(
            registry.closed,
            "registry must remain closed after a double shutdown"
        );
        assert!(
            registry.handles.is_empty(),
            "registry must be drained after a double shutdown"
        );
        assert!(
            agent.shutdown_token.is_cancelled(),
            "token must remain cancelled after a double shutdown"
        );
    }

    /// Shutdown ordering: the registry grace-awaits tracked tasks BEFORE any
    /// straggler is force-aborted. So a task that RESPECTS the token (awaits
    /// `shutdown_token.cancelled()`) must run to its natural end and set its
    /// completed-flag — it is graced, not aborted. This is the positive arm of
    /// the grace/abort policy.
    ///
    /// NOTE: we deliberately do NOT assert what the task observes for
    /// `is_cancelled()` at first-poll. On a multi-thread runtime `tokio::spawn`
    /// may schedule the task onto another worker that polls it BEFORE
    /// `shutdown()` runs on this thread, so first-poll-observes-cancelled is a
    /// race, not an invariant. The robust, non-racy claim is grace-before-abort:
    /// the well-behaved task completes naturally (sets its flag) rather than
    /// being force-aborted by the 3s-straggler path.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn shutdown_graces_a_token_respecting_tracked_task() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .build()
            .await
            .expect("agent");

        // A token-respecting task: it records that it reached its natural end
        // (graceful completion, never aborted). If the grace-await path broke
        // (e.g. the task were force-aborted), this flag would stay false.
        let completed_gracefully = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let token = agent.shutdown_token.clone();
        let cg = std::sync::Arc::clone(&completed_gracefully);
        agent.spawn_tracked(async move {
            // Graceful: stop as soon as the token fires, without being aborted.
            token.cancelled().await;
            cg.store(true, std::sync::atomic::Ordering::SeqCst);
        });

        agent.shutdown().await;

        assert!(
            completed_gracefully.load(std::sync::atomic::Ordering::SeqCst),
            "token-respecting task must complete GRACEFULLY (set its flag before \
             returning) — proves the grace-await precedes any force-abort"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn connected_peer_clears_stale_lifecycle_block_before_raw_send() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let alice = Agent::builder()
            .with_machine_key(dir.path().join("alice-machine.key"))
            .with_agent_key_path(dir.path().join("alice-agent.key"))
            .with_contact_store_path(dir.path().join("alice-contacts.json"))
            .with_peer_cache_disabled()
            .with_network_config(loopback_network_config())
            .build()
            .await
            .expect("alice");
        let bob = Agent::builder()
            .with_machine_key(dir.path().join("bob-machine.key"))
            .with_agent_key_path(dir.path().join("bob-agent.key"))
            .with_contact_store_path(dir.path().join("bob-contacts.json"))
            .with_peer_cache_disabled()
            .with_network_config(loopback_network_config())
            .build()
            .await
            .expect("bob");

        let bob_network = bob.network().expect("bob network");
        let bob_addr = normalize_loopback_addr(bob_network.bound_addr().await.expect("bob bound"));
        let alice_network = alice.network().expect("alice network");
        let connected_peer = alice_network
            .connect_addr(bob_addr)
            .await
            .expect("alice connects to bob");
        assert_eq!(connected_peer.0, bob.machine_id().0);

        let bob_peer = ant_quic::PeerId(bob.machine_id().0);
        let connected_deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
        while tokio::time::Instant::now() < connected_deadline {
            if alice_network.is_connected(&bob_peer).await {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }
        assert!(alice_network.is_connected(&bob_peer).await);

        alice
            .direct_messaging()
            .mark_connected(bob.agent_id(), bob.machine_id())
            .await;
        alice.direct_messaging().record_lifecycle_blocked(
            bob.machine_id(),
            Some(1),
            "closed: stale test block",
        );
        assert!(alice
            .direct_messaging()
            .lifecycle_block_reason(&bob.machine_id())
            .is_some());

        let receipt = alice
            .send_direct_with_config(
                &bob.agent_id(),
                b"stale-block-clear".to_vec(),
                dm::DmSendConfig {
                    prefer_raw_quic_if_connected: true,
                    ..dm::DmSendConfig::default()
                },
            )
            .await
            .expect("raw send should ignore and clear stale lifecycle block");
        assert_eq!(receipt.path, dm::DmPath::RawQuic);
        assert!(alice
            .direct_messaging()
            .lifecycle_block_reason(&bob.machine_id())
            .is_none());
    }

    /// Proactive reconnect: after a known peer's connection is dropped
    /// (simulating a daemon restart / transport idle timeout), x0x must
    /// schedule bounded backoff reconnect attempts and recover a direct
    /// connection without a new external trigger.
    ///
    /// This is the focused test for the post-restart transport failure fix:
    /// GAP 1-4 (mDNS discovery never feeds the dialer, announcement
    /// auto-connect is one-shot, PeerDisconnected does not reconnect,
    /// send-path reconnect dials public-only addresses).
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn proactive_reconnect_recovers_dropped_same_host_peer() {
        let dir = tempfile::tempdir().expect("tmpdir");

        let alice = Agent::builder()
            .with_machine_key(dir.path().join("alice-machine.key"))
            .with_agent_key_path(dir.path().join("alice-agent.key"))
            .with_contact_store_path(dir.path().join("alice-contacts.json"))
            .with_peer_cache_dir(dir.path().join("alice-peers"))
            .with_network_config(loopback_network_config())
            .build()
            .await
            .expect("alice");
        let bob = Agent::builder()
            .with_machine_key(dir.path().join("bob-machine.key"))
            .with_agent_key_path(dir.path().join("bob-agent.key"))
            .with_contact_store_path(dir.path().join("bob-contacts.json"))
            .with_peer_cache_dir(dir.path().join("bob-peers"))
            .with_network_config(loopback_network_config())
            .build()
            .await
            .expect("bob");

        // Start the network event listener so the proactive reconnect
        // scheduler is active. In production this is started by
        // join_network(); here we invoke it directly for a focused test.
        alice.start_network_event_listener();

        let bob_network = bob.network().expect("bob network");
        let bob_addr = normalize_loopback_addr(bob_network.bound_addr().await.expect("bob bound"));
        let alice_network = alice.network().expect("alice network");
        let bob_peer = ant_quic::PeerId(bob.machine_id().0);

        // Phase 1: connect alice → bob.
        let connected_peer = alice_network
            .connect_addr(bob_addr)
            .await
            .expect("alice connects to bob");
        assert_eq!(connected_peer.0, bob.machine_id().0);

        // Wait for the connection to register on both sides.
        let connected_deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
        while tokio::time::Instant::now() < connected_deadline {
            if alice_network.is_connected(&bob_peer).await {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }
        assert!(
            alice_network.is_connected(&bob_peer).await,
            "alice should be connected to bob after initial dial"
        );

        // Phase 2: force a disconnect (simulates the QUIC transport drop
        // that occurs when the remote daemon restarts or the idle timeout
        // fires). This emits PeerDisconnected, which triggers
        // schedule_reconnect.
        alice_network
            .disconnect(&bob_peer)
            .await
            .expect("disconnect bob");

        // Give the disconnect time to propagate.
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        assert!(
            !alice_network.is_connected(&bob_peer).await,
            "alice should be disconnected after explicit disconnect"
        );

        // Phase 3: wait for the proactive reconnect to recover the
        // connection. The first backoff delay is 1 s; allow generous
        // headroom for CI scheduling jitter.
        let reconnect_deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(20);
        while tokio::time::Instant::now() < reconnect_deadline {
            if alice_network.is_connected(&bob_peer).await {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        }
        assert!(
            alice_network.is_connected(&bob_peer).await,
            "alice should have proactively reconnected to bob \
             within the backoff window"
        );

        // Phase 4: verify a subsequent DM succeeds over the recovered
        // connection. Mark connected (the PeerConnected handler does this
        // in production, but may race with our assertion in the test).
        alice
            .direct_messaging()
            .mark_connected(bob.agent_id(), bob.machine_id())
            .await;

        let receipt = alice
            .send_direct_with_config(
                &bob.agent_id(),
                b"post-reconnect-probe".to_vec(),
                dm::DmSendConfig {
                    prefer_raw_quic_if_connected: true,
                    ..dm::DmSendConfig::default()
                },
            )
            .await
            .expect("DM should succeed over the recovered connection");
        assert_eq!(
            receipt.path,
            dm::DmPath::RawQuic,
            "DM should use the raw QUIC path over the recovered connection"
        );
    }

    /// Default global-bootstrap config (allow_local_scope=FALSE): same-host
    /// reconnect must still work because the bootstrap cache retains the raw
    /// loopback address from the initial connection and Phase 2 of
    /// `schedule_reconnect` dials it via `connect_cached_peer` (CR-HOST-1).
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn proactive_reconnect_default_global_bootstrap_same_host() {
        let dir = tempfile::tempdir().expect("tmpdir");

        // A non-local bootstrap node forces allow_local_scope=FALSE so the
        // discovery cache will NOT retain LAN/loopback addresses. The reconnect
        // must therefore rely on Phase 2 (bootstrap cache), which stores the
        // raw connection address unfiltered.
        let global_cfg = network::NetworkConfig {
            bind_addr: Some("127.0.0.1:0".parse().expect("loopback addr")),
            bootstrap_nodes: vec!["142.93.199.50:5483".parse().expect("wan seed")],
            ..network::NetworkConfig::default()
        };
        assert!(
            !allow_local_discovery_addresses(&global_cfg),
            "test precondition: config must have allow_local_scope=FALSE"
        );

        let alice = Agent::builder()
            .with_machine_key(dir.path().join("alice-machine.key"))
            .with_agent_key_path(dir.path().join("alice-agent.key"))
            .with_contact_store_path(dir.path().join("alice-contacts.json"))
            .with_peer_cache_dir(dir.path().join("alice-peers"))
            .with_network_config(global_cfg.clone())
            .build()
            .await
            .expect("alice");
        let bob = Agent::builder()
            .with_machine_key(dir.path().join("bob-machine.key"))
            .with_agent_key_path(dir.path().join("bob-agent.key"))
            .with_contact_store_path(dir.path().join("bob-contacts.json"))
            .with_peer_cache_dir(dir.path().join("bob-peers"))
            .with_network_config(global_cfg)
            .build()
            .await
            .expect("bob");

        alice.start_network_event_listener();

        let bob_network = bob.network().expect("bob network");
        let bob_addr = normalize_loopback_addr(bob_network.bound_addr().await.expect("bob bound"));
        let alice_network = alice.network().expect("alice network");
        let bob_peer = ant_quic::PeerId(bob.machine_id().0);

        // Connect alice → bob.
        let connected = alice_network
            .connect_addr(bob_addr)
            .await
            .expect("alice connects to bob");
        assert_eq!(connected.0, bob.machine_id().0);

        // Wait for connection to register.
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
        while tokio::time::Instant::now() < deadline {
            if alice_network.is_connected(&bob_peer).await {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }
        assert!(
            alice_network.is_connected(&bob_peer).await,
            "alice should be connected to bob"
        );

        // CR-HOST-1 assertion: the bootstrap cache retains the raw loopback
        // address from the successful connection. connect_cached_peer must
        // return that address, proving Phase 2 can redial it after a drop.
        let cached_addr = alice_network
            .connect_cached_peer(bob_peer)
            .await
            .expect("bootstrap cache should retain bob's loopback address");
        // CR-HOST-1 assertion: the bootstrap cache retains the raw loopback
        // address from the successful connection. connect_cached_peer must
        // return a loopback address at bob's port, proving Phase 2 can redial
        // it after a drop. (Dual-stack QUIC may report IPv4-mapped IPv6, so we
        // compare port + loopback-ness rather than exact address equality.)
        assert_eq!(
            cached_addr.port(),
            bob_addr.port(),
            "connect_cached_peer must return bob's port — \
             confirms bootstrap cache retains the connection address"
        );
        assert!(
            match cached_addr.ip() {
                std::net::IpAddr::V4(v4) => v4.is_loopback(),
                std::net::IpAddr::V6(v6) => {
                    v6.is_loopback() || v6.to_ipv4().is_some_and(|v4| v4.is_loopback())
                }
            },
            "connect_cached_peer must return a loopback address — \
             confirms bootstrap cache does not scope-filter (got {cached_addr})"
        );

        // Force disconnect (simulates transport drop / restart).
        alice_network
            .disconnect(&bob_peer)
            .await
            .expect("disconnect bob");
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        assert!(
            !alice_network.is_connected(&bob_peer).await,
            "alice should be disconnected"
        );

        // Wait for proactive reconnect via Phase 2 (bootstrap cache).
        let reconnect_deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(20);
        while tokio::time::Instant::now() < reconnect_deadline {
            if alice_network.is_connected(&bob_peer).await {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        }
        assert!(
            alice_network.is_connected(&bob_peer).await,
            "alice should have reconnected to bob via bootstrap cache \
             even with allow_local_scope=FALSE"
        );

        // Verify DM succeeds over the recovered connection.
        alice
            .direct_messaging()
            .mark_connected(bob.agent_id(), bob.machine_id())
            .await;
        let receipt = alice
            .send_direct_with_config(
                &bob.agent_id(),
                b"post-reconnect-global-bootstrap".to_vec(),
                dm::DmSendConfig {
                    prefer_raw_quic_if_connected: true,
                    ..dm::DmSendConfig::default()
                },
            )
            .await
            .expect("DM should succeed over the recovered connection");
        assert_eq!(receipt.path, dm::DmPath::RawQuic);
    }
    // ─── Reconnect-policy suppression regression tests ─────────────────────
    //
    // These defend the invariant from the final independent review: a peer
    // disconnected for a NON-transport reason (policy rejection, pool
    // eviction, admin teardown, revocation, shutdown) must never be
    // proactively redialed. Pre-fix every `PeerDisconnected` was generic and
    // `schedule_reconnect` restored the peer via the bootstrap-cache fallback
    // within the first backoff attempt (~1 s), undoing the security/eviction
    // decision. `DisconnectReason` now carries reconnect eligibility through
    // both event streams and records a suppression tombstone.

    /// Positive control: a Transport-level disconnect (QUIC idle timeout /
    /// remote restart) is reconnect-eligible — the suppression machinery must
    /// not over-fire and starve genuine transport recovery. `disconnect()`
    /// defaults to Transport, preserving the existing happy-path semantics.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn transport_disconnect_is_reconnect_eligible_and_recovers() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let alice = Agent::builder()
            .with_machine_key(dir.path().join("alice-machine.key"))
            .with_agent_key_path(dir.path().join("alice-agent.key"))
            .with_contact_store_path(dir.path().join("alice-contacts.json"))
            .with_peer_cache_dir(dir.path().join("alice-peers"))
            .with_network_config(loopback_network_config())
            .build()
            .await
            .expect("alice");
        alice.start_network_event_listener();
        let alice_network = alice.network().expect("alice network");

        let bob = Agent::builder()
            .with_machine_key(dir.path().join("bob-machine.key"))
            .with_agent_key_path(dir.path().join("bob-agent.key"))
            .with_contact_store_path(dir.path().join("bob-contacts.json"))
            .with_peer_cache_dir(dir.path().join("bob-peers"))
            .with_network_config(loopback_network_config())
            .build()
            .await
            .expect("bob");
        let bob_addr = normalize_loopback_addr(
            bob.network()
                .expect("bob net")
                .bound_addr()
                .await
                .expect("bob bound"),
        );
        let bob_peer = ant_quic::PeerId(bob.machine_id().0);

        let connected = alice_network
            .connect_addr(bob_addr)
            .await
            .expect("alice connects to bob");
        assert_eq!(connected.0, bob.machine_id().0);
        let reg = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
        while tokio::time::Instant::now() < reg {
            if alice_network.is_connected(&bob_peer).await {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }
        assert!(
            alice_network.is_connected(&bob_peer).await,
            "bob connected before transport disconnect"
        );

        assert!(
            network::DisconnectReason::Transport.reconnect_eligible(),
            "Transport is the only reconnect-eligible reason"
        );

        alice_network
            .disconnect_with_reason(&bob_peer, network::DisconnectReason::Transport)
            .await
            .expect("transport disconnect");
        assert!(
            !alice_network.is_reconnect_suppressed(bob.machine_id().0),
            "Transport disconnect must NOT set a tombstone"
        );
        assert!(
            !alice_network.is_connected(&bob_peer).await,
            "bob disconnected after transport disconnect"
        );

        // Proactive reconnect must recover bob within the backoff window.
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(20);
        while tokio::time::Instant::now() < deadline {
            if alice_network.is_connected(&bob_peer).await {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        }
        assert!(
            alice_network.is_connected(&bob_peer).await,
            "Transport disconnect must be redialed within the backoff window"
        );
    }

    /// Admin teardown, revocation, and shutdown must suppress proactive
    /// reconnect. For each reason: alice connects bob (so bob is in alice's
    /// bootstrap cache — the Phase-2 fallback path that restored rejected
    /// peers pre-fix), issues the disconnect with the reason, and asserts the
    /// tombstone is set immediately AND bob stays disconnected past the first
    /// two backoff attempts (1 s + 2 s), which is where the pre-fix
    /// cache-fallback redial would have re-established the connection.
    /// `PolicyRejection` (full backoff window) and `PoolEviction` (real
    /// eviction) have dedicated tests below.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn admin_revocation_shutdown_disconnect_suppresses_proactive_reconnect() {
        let reasons = [
            network::DisconnectReason::Admin,
            network::DisconnectReason::Revocation,
            network::DisconnectReason::Shutdown,
        ];

        let dir = tempfile::tempdir().expect("tmpdir");
        let alice = Agent::builder()
            .with_machine_key(dir.path().join("alice-machine.key"))
            .with_agent_key_path(dir.path().join("alice-agent.key"))
            .with_contact_store_path(dir.path().join("alice-contacts.json"))
            .with_peer_cache_dir(dir.path().join("alice-peers"))
            .with_network_config(loopback_network_config())
            .build()
            .await
            .expect("alice");
        // Arm the proactive-reconnect scheduler so the gating is exercised for
        // real, not just the tombstone lookup.
        alice.start_network_event_listener();
        let alice_network = alice.network().expect("alice network");

        for reason in reasons {
            // Fresh bob per reason: Revocation/Shutdown tombstones are
            // permanent, so a suppressed bob can never be reused.
            let tag = format!("{reason:?}");
            let bob = Agent::builder()
                .with_machine_key(dir.path().join(format!("{tag}-machine.key")))
                .with_agent_key_path(dir.path().join(format!("{tag}-agent.key")))
                .with_contact_store_path(dir.path().join(format!("{tag}-contacts.json")))
                .with_peer_cache_dir(dir.path().join(format!("{tag}-peers")))
                .with_network_config(loopback_network_config())
                .build()
                .await
                .expect("bob");
            let bob_network = bob.network().expect("bob network");
            let bob_addr =
                normalize_loopback_addr(bob_network.bound_addr().await.expect("bob bound"));
            let bob_peer = ant_quic::PeerId(bob.machine_id().0);
            let bob_id = bob.machine_id().0;

            // Establish a real connection so bob lands in alice's bootstrap
            // cache — the exact fallback that restored rejected peers pre-fix.
            let connected = alice_network
                .connect_addr(bob_addr)
                .await
                .expect("alice connects to bob");
            assert_eq!(connected.0, bob.machine_id().0, "{tag}: connected to bob");
            let reg = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
            while tokio::time::Instant::now() < reg {
                if alice_network.is_connected(&bob_peer).await {
                    break;
                }
                tokio::time::sleep(std::time::Duration::from_millis(25)).await;
            }
            assert!(
                alice_network.is_connected(&bob_peer).await,
                "{tag}: alice connected to bob before disconnect"
            );
            assert!(
                !alice_network.is_reconnect_suppressed(bob_id),
                "{tag}: no tombstone before disconnect"
            );
            assert!(
                !reason.reconnect_eligible(),
                "{tag}: non-transport reasons are not reconnect-eligible"
            );

            // The security/lifecycle teardown — the single production seam.
            alice_network
                .disconnect_with_reason(&bob_peer, reason)
                .await
                .expect("disconnect_with_reason");

            assert!(
                !alice_network.is_connected(&bob_peer).await,
                "{tag}: bob disconnected immediately"
            );
            assert!(
                alice_network.is_reconnect_suppressed(bob_id),
                "{tag}: suppression tombstone set"
            );

            // Teeth: poll past the first two backoff attempts (1 s + 2 s).
            // Pre-fix the generic PeerDisconnected fired schedule_reconnect
            // and restored bob via the bootstrap cache within ~1 s. bob is
            // still listening, so a redial WOULD succeed if the gate failed.
            let guard = tokio::time::Instant::now() + std::time::Duration::from_secs(6);
            let mut redialed = false;
            while tokio::time::Instant::now() < guard {
                if alice_network.is_connected(&bob_peer).await {
                    redialed = true;
                    break;
                }
                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            }
            assert!(
                !redialed,
                "{tag}: suppressed peer must not be redialed within the backoff window"
            );
            // bob dropped here; the next iteration builds a fresh bob.
        }
    }

    /// The announcement auto-connect gate must refuse to dial a peer whose
    /// reconnect is suppressed. WHY: a revoked / policy-rejected / admin-
    /// disconnected / evicted peer can keep broadcasting identity announcements
    /// over gossip. If the auto-connect path dialed on those, it would silently
    /// undo the security/eviction decision (the ungated hole). This exercises
    /// the exact production predicate (`announcement_should_auto_connect`) with
    /// live network state: a real revocation tombstone set via the production
    /// `disconnect_with_reason` seam.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn suppressed_peer_announcement_is_not_auto_connected() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let alice = Agent::builder()
            .with_machine_key(dir.path().join("alice-machine.key"))
            .with_agent_key_path(dir.path().join("alice-agent.key"))
            .with_contact_store_path(dir.path().join("alice-contacts.json"))
            .with_peer_cache_dir(dir.path().join("alice-peers"))
            .with_network_config(loopback_network_config())
            .build()
            .await
            .expect("alice");
        let alice_network = alice.network().expect("alice network");

        let bob = Agent::builder()
            .with_machine_key(dir.path().join("bob-machine.key"))
            .with_agent_key_path(dir.path().join("bob-agent.key"))
            .with_contact_store_path(dir.path().join("bob-contacts.json"))
            .with_peer_cache_dir(dir.path().join("bob-peers"))
            .with_network_config(loopback_network_config())
            .build()
            .await
            .expect("bob");
        let bob_network = bob.network().expect("bob network");
        let bob_addr = normalize_loopback_addr(bob_network.bound_addr().await.expect("bob bound"));
        let bob_peer = ant_quic::PeerId(bob.machine_id().0);
        let bob_id = bob.machine_id().0;

        // Connect so bob is known, then revoke him. The tombstone is what the
        // announcement gate consults.
        alice_network
            .connect_addr(bob_addr)
            .await
            .expect("alice connects bob");
        let reg = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
        while tokio::time::Instant::now() < reg {
            if alice_network.is_connected(&bob_peer).await {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }
        alice_network
            .disconnect_with_reason(&bob_peer, network::DisconnectReason::Revocation)
            .await
            .expect("revoke bob");
        assert!(
            alice_network.is_reconnect_suppressed(bob_id),
            "revoked bob must carry a suppression tombstone"
        );

        // The exact production decision an inbound announcement from bob would
        // reach: suppressed=true, so no auto-connect regardless of connect
        // state. Compute both inputs from live network state (not literals).
        let suppressed = alice_network.is_reconnect_suppressed(bob_id);
        let connected = alice_network.is_connected(&bob_peer).await;
        assert!(
            !announcement_should_auto_connect(suppressed, connected),
            "a suppressed peer's announcement must not trigger auto-connect"
        );
    }

    /// The auto-connect predicate only dials an un-suppressed, not-yet-connected
    /// peer. Encodes the security invariant directly: suppression always wins,
    /// and an already-connected peer is never redundantly dialed.
    #[test]
    fn announcement_auto_connect_predicate_truth_table() {
        // (suppressed, connected) -> should_dial
        assert!(announcement_should_auto_connect(false, false));
        assert!(!announcement_should_auto_connect(false, true));
        assert!(!announcement_should_auto_connect(true, false));
        assert!(!announcement_should_auto_connect(true, true));
    }

    /// The per-agent auto-connect rate limit must allow a first-ever dial
    /// immediately, refuse a redial inside the cooldown window, and allow it
    /// again once the window has elapsed. WHY: an announcing-but-unreachable
    /// peer is redialed per received announcement copy; every failed dial
    /// accumulates ant-quic NAT-traversal state (~2.5 MB measured), so an
    /// unbounded dial rate is an unbounded memory leak (v0.31 testnet OOM).
    #[test]
    fn announcement_auto_connect_retry_cooldown_gates_redials() {
        let now = std::time::Instant::now();
        // First-ever announcement: dial immediately.
        assert!(announcement_auto_connect_retry_allowed(None, now));
        // Same instant as the last attempt: refuse.
        assert!(!announcement_auto_connect_retry_allowed(Some(now), now));
        // Just inside the window: refuse.
        let inside =
            now + ANNOUNCEMENT_AUTO_CONNECT_RETRY_COOLDOWN - std::time::Duration::from_millis(1);
        assert!(!announcement_auto_connect_retry_allowed(Some(now), inside));
        // At/after the window boundary: allow.
        let at_boundary = now + ANNOUNCEMENT_AUTO_CONNECT_RETRY_COOLDOWN;
        assert!(announcement_auto_connect_retry_allowed(
            Some(now),
            at_boundary
        ));
        // Clock going backwards (last_attempt in the "future") must not panic
        // and must refuse the dial.
        assert!(!announcement_auto_connect_retry_allowed(
            Some(at_boundary),
            now
        ));
    }

    /// Jittered backoff must stay within ±20% of each base delay. WHY: the
    /// jitter decorrelates synchronized redials, but it must not shrink or
    /// inflate the exponential backoff beyond the intended envelope, or a
    /// genuinely-down peer would be hammered (too small) or recovery would lag
    /// (too large). Sampled across all base delays.
    #[test]
    fn jittered_backoff_stays_within_bounds() {
        for &base in RECONNECT_BACKOFF_DELAYS {
            let lower = base.mul_f64(0.8);
            let upper = base.mul_f64(1.2);
            for _ in 0..10_000 {
                let j = jittered_backoff_delay(base);
                assert!(
                    j >= lower && j <= upper,
                    "jittered delay {j:?} out of [{lower:?}, {upper:?}] for base {base:?}"
                );
            }
        }
    }

    /// A peer rejected by pinned-bootstrap policy must stay disconnected for
    /// the ENTIRE proactive-reconnect backoff window (1+2+4+8+16 s), even
    /// though it remains in the bootstrap cache and would be restored by the
    /// cache-fallback redial under the pre-fix generic-event code. This is the
    /// acceptance gate from the final independent review: "Test a wrong pinned
    /// peer for the full backoff window."
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn wrong_pinned_peer_stays_disconnected_for_full_backoff_window() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let alice = Agent::builder()
            .with_machine_key(dir.path().join("alice-machine.key"))
            .with_agent_key_path(dir.path().join("alice-agent.key"))
            .with_contact_store_path(dir.path().join("alice-contacts.json"))
            .with_peer_cache_dir(dir.path().join("alice-peers"))
            .with_network_config(loopback_network_config())
            .build()
            .await
            .expect("alice");
        alice.start_network_event_listener();
        let alice_network = alice.network().expect("alice network");

        // The imposter: alice connects it first so it lands in alice's
        // bootstrap cache — the exact Phase-2 fallback path that restored a
        // policy-rejected peer pre-fix.
        let imposter = Agent::builder()
            .with_machine_key(dir.path().join("imp-machine.key"))
            .with_agent_key_path(dir.path().join("imp-agent.key"))
            .with_contact_store_path(dir.path().join("imp-contacts.json"))
            .with_peer_cache_dir(dir.path().join("imp-peers"))
            .with_network_config(loopback_network_config())
            .build()
            .await
            .expect("imposter");
        let imp_network = imposter.network().expect("imposter network");
        let imp_addr = normalize_loopback_addr(imp_network.bound_addr().await.expect("imp bound"));
        let imp_peer = ant_quic::PeerId(imposter.machine_id().0);

        let connected = alice_network
            .connect_addr(imp_addr)
            .await
            .expect("alice connects to imposter");
        assert_eq!(connected.0, imposter.machine_id().0);
        let reg = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
        while tokio::time::Instant::now() < reg {
            if alice_network.is_connected(&imp_peer).await {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }
        assert!(
            alice_network.is_connected(&imp_peer).await,
            "imposter connected before rejection"
        );

        // Reject the imposter for pinned-bootstrap policy — the exact seam the
        // real dial_bootstrap / peer-mismatch paths call.
        alice_network
            .disconnect_with_reason(&imp_peer, network::DisconnectReason::PolicyRejection)
            .await
            .expect("policy reject");
        assert!(
            !alice_network.is_connected(&imp_peer).await,
            "imposter disconnected after policy rejection"
        );
        assert!(
            alice_network.is_reconnect_suppressed(imposter.machine_id().0),
            "PolicyRejection sets a permanent tombstone"
        );

        // Poll the FULL backoff window. The imposter is still listening (so a
        // redial WOULD succeed) and still in the bootstrap cache; under the
        // pre-fix code schedule_reconnect's Phase 2 (connect_cached_peer)
        // restored it within the first attempt (~1 s). It must never reappear.
        // Sum of RECONNECT_BACKOFF_DELAYS (1+2+4+8+16) = 31 s; add margin.
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(34);
        while tokio::time::Instant::now() < deadline {
            assert!(
                !alice_network.is_connected(&imp_peer).await,
                "wrong pinned peer must stay disconnected for the full backoff \
                 window despite being in the bootstrap cache"
            );
            tokio::time::sleep(std::time::Duration::from_millis(250)).await;
        }
    }

    /// A connection-pool eviction (LRU over `max_connections`) must not
    /// trigger a redial that immediately reconnects the evicted peer — the
    /// evict/redial churn loop flagged in the final review. This exercises the
    /// GENUINE eviction path: alice's pool is capped at one connection, so
    /// connecting charlie evicts bob via the real `disconnect_pool_candidates`
    /// path with a `PoolEviction` reason. The tombstone must keep bob from
    /// being redialed while alice holds charlie — pre-fix the eviction emitted
    /// a generic `PeerDisconnected`, schedule_reconnect redialed bob, the pool
    /// re-evicted charlie to readmit bob, and the cycle repeated.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn pool_cap_eviction_does_not_churn_redial() {
        let dir = tempfile::tempdir().expect("tmpdir");
        // Cap the pool at one connection so a second peer forces a real LRU
        // eviction through disconnect_pool_candidates (PoolEviction).
        let mut one_conn_cfg = loopback_network_config();
        one_conn_cfg.max_connections = 1;

        let alice = Agent::builder()
            .with_machine_key(dir.path().join("alice-machine.key"))
            .with_agent_key_path(dir.path().join("alice-agent.key"))
            .with_contact_store_path(dir.path().join("alice-contacts.json"))
            .with_peer_cache_dir(dir.path().join("alice-peers"))
            .with_network_config(one_conn_cfg)
            .build()
            .await
            .expect("alice");
        alice.start_network_event_listener();
        let alice_network = alice.network().expect("alice network");

        let bob = Agent::builder()
            .with_machine_key(dir.path().join("bob-machine.key"))
            .with_agent_key_path(dir.path().join("bob-agent.key"))
            .with_contact_store_path(dir.path().join("bob-contacts.json"))
            .with_peer_cache_dir(dir.path().join("bob-peers"))
            .with_network_config(loopback_network_config())
            .build()
            .await
            .expect("bob");
        let charlie = Agent::builder()
            .with_machine_key(dir.path().join("charlie-machine.key"))
            .with_agent_key_path(dir.path().join("charlie-agent.key"))
            .with_contact_store_path(dir.path().join("charlie-contacts.json"))
            .with_peer_cache_dir(dir.path().join("charlie-peers"))
            .with_network_config(loopback_network_config())
            .build()
            .await
            .expect("charlie");

        let bob_addr = normalize_loopback_addr(
            bob.network()
                .expect("bob net")
                .bound_addr()
                .await
                .expect("bob bound"),
        );
        let charlie_addr = normalize_loopback_addr(
            charlie
                .network()
                .expect("charlie net")
                .bound_addr()
                .await
                .expect("charlie bound"),
        );
        let bob_peer = ant_quic::PeerId(bob.machine_id().0);
        let charlie_peer = ant_quic::PeerId(charlie.machine_id().0);

        // alice → bob fills the single pool slot.
        let cb = alice_network
            .connect_addr(bob_addr)
            .await
            .expect("connect bob");
        assert_eq!(cb.0, bob.machine_id().0);
        let reg = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
        while tokio::time::Instant::now() < reg {
            if alice_network.is_connected(&bob_peer).await {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }
        assert!(
            alice_network.is_connected(&bob_peer).await,
            "bob connected before eviction"
        );

        // alice → charlie: the real LRU eviction path fires — bob is evicted
        // with PoolEviction via note_connection_pool_activity.
        let cc = alice_network
            .connect_addr(charlie_addr)
            .await
            .expect("connect charlie");
        assert_eq!(cc.0, charlie.machine_id().0);

        // Wait for the eviction to land (bob disconnected + tombstoned).
        let evict_dl = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
        while tokio::time::Instant::now() < evict_dl {
            if !alice_network.is_connected(&bob_peer).await
                && alice_network.is_reconnect_suppressed(bob.machine_id().0)
            {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
        assert!(
            alice_network.is_reconnect_suppressed(bob.machine_id().0),
            "evicted bob must carry a PoolEviction tombstone"
        );
        assert!(
            !alice_network.is_connected(&bob_peer).await,
            "evicted bob must be disconnected"
        );

        // Teeth: bob must NOT be redialed (which would evict charlie and
        // churn). charlie stays put — proof the loop is broken. Poll past the
        // first two backoff attempts.
        let guard = tokio::time::Instant::now() + std::time::Duration::from_secs(6);
        while tokio::time::Instant::now() < guard {
            assert!(
                !alice_network.is_connected(&bob_peer).await,
                "evicted bob must not be redialed (churn)"
            );
            assert!(
                alice_network.is_connected(&charlie_peer).await,
                "charlie must stay connected — no churn displacement"
            );
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        }
    }

    #[tokio::test]
    async fn agent_peer_relay_defaults_to_disabled_when_unconfigured() {
        // Why: X0X-0070b's relay engine is opt-in. An Agent built without
        // any `[peer_relay]` TOML section must come up with the engine
        // disabled and an empty candidate list - anything else would
        // engage the fallback for operators who never asked for it.
        let dir = tempfile::tempdir().expect("tmpdir");
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .build()
            .await
            .expect("agent");
        assert!(
            !agent.peer_relay().policy().enabled,
            "default Agent must have the relay engine disabled"
        );
        assert!(
            agent.relay_candidates().await.is_empty(),
            "default Agent must have no relay candidates"
        );
    }

    #[tokio::test]
    async fn agent_peer_relay_honors_configured_policy_and_candidates() {
        // Why: a TOML-configured `[peer_relay]` block must flow through to
        // a live `PeerRelay` instance on the Agent - enabled flag, fail
        // trigger, and the seeded candidate list. This is the single
        // integration seam where an operator's config first takes effect.
        let dir = tempfile::tempdir().expect("tmpdir");
        let candidate_a = [0xAA_u8; 32];
        let candidate_b = [0xBB_u8; 32];
        let mut net_cfg = loopback_network_config();
        net_cfg.peer_relay = network::PeerRelayConfig {
            enabled: true,
            require_contact_to_relay: false,
            fail_threshold: 7,
            fail_window_ms: 90_000,
            candidates: vec![hex::encode(candidate_a), hex::encode(candidate_b)],
            ..Default::default()
        };
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .with_peer_cache_disabled()
            .with_network_config(net_cfg)
            .build()
            .await
            .expect("agent");

        let policy = agent.peer_relay().policy();
        assert!(policy.enabled, "configured `enabled = true` must propagate");
        assert_eq!(policy.fail_threshold, 7);
        assert_eq!(policy.fail_window, std::time::Duration::from_millis(90_000));

        let candidates = agent.relay_candidates().await;
        assert_eq!(candidates.len(), 2, "both TOML candidates seeded");
        assert!(candidates.iter().any(|c| c.0 == candidate_a));
        assert!(candidates.iter().any(|c| c.0 == candidate_b));
    }

    #[tokio::test]
    async fn send_direct_failure_records_failure_on_peer_relay() {
        // Why: the bookkeeping hook in `send_direct_with_config` is the
        // single feed into `PeerRelay::needs_relay`. If a transport
        // failure does not increment the per-peer failure count, the
        // engine can never decide to engage the relay - the fallback is
        // dead-on-arrival. With no network configured every raw-QUIC
        // attempt fails fast, which gives a deterministic test signal.
        let dir = tempfile::tempdir().expect("tmpdir");
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .build()
            .await
            .expect("agent");
        let unreachable = identity::AgentId([0x42; 32]);

        let result = agent
            .send_direct_with_config(
                &unreachable,
                b"x0x-0070b-bookkeeping".to_vec(),
                dm::DmSendConfig::default(),
            )
            .await;
        assert!(
            result.is_err(),
            "no network configured - direct send must fail"
        );
        assert_eq!(
            agent.peer_relay().tracked_peer_count(),
            1,
            "failure must have produced a per-peer relay-engine entry"
        );
    }

    #[tokio::test]
    async fn send_direct_self_loopback_does_not_disturb_peer_relay() {
        // Why: the loopback short-circuit at the top of
        // `send_direct_with_config` returns before the bookkeeping arm.
        // A self-DM must not count as a "direct success" against the
        // sender's own AgentId - that would conflate local delivery
        // with the cross-peer path that actually exercises NAT.
        let dir = tempfile::tempdir().expect("tmpdir");
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .build()
            .await
            .expect("agent");
        let _receipt = agent
            .send_direct_with_config(
                &agent.agent_id(),
                b"loopback".to_vec(),
                dm::DmSendConfig::default(),
            )
            .await
            .expect("loopback self-DM");
        assert_eq!(
            agent.peer_relay().tracked_peer_count(),
            0,
            "loopback path must not register with the relay engine"
        );
    }

    #[tokio::test]
    async fn try_relay_fallback_returns_no_candidate_when_list_empty() {
        // Why: with an enabled policy but zero seeded candidates,
        // `select_relay` returns `None` and the helper must short-circuit
        // to `NoRelayCandidate`. Falling through to envelope construction
        // would burn KEM/AEAD cycles for nothing.
        let dir = tempfile::tempdir().expect("tmpdir");
        let mut net_cfg = loopback_network_config();
        net_cfg.peer_relay = network::PeerRelayConfig {
            enabled: true,
            require_contact_to_relay: false,
            fail_threshold: 3,
            fail_window_ms: 60_000,
            candidates: Vec::new(),
            ..Default::default()
        };
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .with_peer_cache_disabled()
            .with_network_config(net_cfg)
            .build()
            .await
            .expect("agent");
        let to = identity::AgentId([0xCD; 32]);

        let err = agent
            .try_relay_fallback(&to, b"payload".to_vec(), &[0u8; 32])
            .await
            .expect_err("empty candidate list must short-circuit");
        assert!(
            matches!(err, dm::DmError::NoRelayCandidate),
            "expected NoRelayCandidate, got {err:?}"
        );
    }

    #[tokio::test]
    async fn try_relay_fallback_returns_no_candidate_when_machine_id_uncached() {
        // Why: a seeded candidate AgentId is useless if its MachineId is
        // not in the identity-discovery cache - we need it to address
        // the QUIC peer at the wire layer. The helper must treat this
        // as "no usable candidate" and let the caller surface the
        // original direct error.
        let dir = tempfile::tempdir().expect("tmpdir");
        let candidate_hex = hex::encode([0xEE_u8; 32]);
        let mut net_cfg = loopback_network_config();
        net_cfg.peer_relay = network::PeerRelayConfig {
            enabled: true,
            require_contact_to_relay: false,
            fail_threshold: 3,
            fail_window_ms: 60_000,
            candidates: vec![candidate_hex],
            ..Default::default()
        };
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .with_peer_cache_disabled()
            .with_network_config(net_cfg)
            .build()
            .await
            .expect("agent");
        let to = identity::AgentId([0xCD; 32]);

        let err = agent
            .try_relay_fallback(&to, b"payload".to_vec(), &[0u8; 32])
            .await
            .expect_err("uncached candidate must short-circuit");
        assert!(
            matches!(err, dm::DmError::NoRelayCandidate),
            "expected NoRelayCandidate, got {err:?}"
        );
    }

    #[tokio::test]
    async fn send_direct_below_threshold_does_not_attempt_relay() {
        // Why: the engine must wait until the sliding-window failure
        // count reaches `fail_threshold` before engaging the relay.
        // A single transport failure must surface the original direct
        // error AND must not register `relay_sent` on the engine
        // (proves no fallback attempt fired underneath).
        let dir = tempfile::tempdir().expect("tmpdir");
        let mut net_cfg = loopback_network_config();
        net_cfg.peer_relay = network::PeerRelayConfig {
            enabled: true,
            require_contact_to_relay: false,
            fail_threshold: 5,
            fail_window_ms: 60_000,
            candidates: vec![hex::encode([0xEE_u8; 32])],
            ..Default::default()
        };
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .with_peer_cache_disabled()
            .with_network_config(net_cfg)
            .build()
            .await
            .expect("agent");
        let to = identity::AgentId([0xCD; 32]);

        let result = agent
            .send_direct_with_config(&to, b"first-attempt".to_vec(), dm::DmSendConfig::default())
            .await;
        assert!(result.is_err(), "no usable transport - direct send fails");
        let snap = agent.peer_relay().stats().snapshot();
        assert_eq!(
            snap.relay_sent, 0,
            "below threshold must not engage the relay path"
        );
    }

    #[tokio::test]
    async fn send_direct_above_threshold_without_candidates_surfaces_direct_err() {
        // Why: the contract for relay-fallback failure is that the
        // caller sees the ORIGINAL direct error, never the relay-side
        // bookkeeping error. Pre-load the engine past threshold, then
        // send to a peer with no usable candidate - the result must
        // be a direct-transport error, not `NoRelayCandidate`.
        let dir = tempfile::tempdir().expect("tmpdir");
        let mut net_cfg = loopback_network_config();
        net_cfg.peer_relay = network::PeerRelayConfig {
            enabled: true,
            require_contact_to_relay: false,
            fail_threshold: 3,
            fail_window_ms: 60_000,
            candidates: Vec::new(),
            ..Default::default()
        };
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .with_peer_cache_disabled()
            .with_network_config(net_cfg)
            .build()
            .await
            .expect("agent");
        let to = identity::AgentId([0xCD; 32]);

        // Pre-load the engine past threshold without waiting for live
        // transport retries.
        for _ in 0..agent.peer_relay().policy().fail_threshold {
            agent.peer_relay().record_direct_failure(&to);
        }
        assert!(
            agent.peer_relay().needs_relay(&to),
            "engine must say the peer now needs a relay"
        );

        let err = agent
            .send_direct_with_config(&to, b"x0x-0070b".to_vec(), dm::DmSendConfig::default())
            .await
            .expect_err("send must still fail when the relay path has no candidates");
        assert!(
            !matches!(err, dm::DmError::NoRelayCandidate),
            "relay-side errors must not leak - original direct error must surface, got {err:?}"
        );
    }

    #[tokio::test]
    async fn send_direct_disabled_policy_does_not_engage_relay_seed() {
        // Why: with the default disabled policy the relay-seed clone
        // must not happen - the happy path pays nothing. Even with the
        // peer manually driven past `fail_threshold` (which would never
        // happen under a disabled policy in practice, but is a
        // belt-and-braces check), the engine's `needs_relay` stays
        // `false` and no fallback fires.
        let dir = tempfile::tempdir().expect("tmpdir");
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .build()
            .await
            .expect("agent");
        let to = identity::AgentId([0xCD; 32]);
        for _ in 0..10 {
            agent.peer_relay().record_direct_failure(&to);
        }
        assert!(
            !agent.peer_relay().needs_relay(&to),
            "disabled policy must never trigger needs_relay"
        );

        let err = agent
            .send_direct_with_config(&to, b"x0x-0070b".to_vec(), dm::DmSendConfig::default())
            .await
            .expect_err("no network - direct send must fail");
        assert!(
            !matches!(err, dm::DmError::NoRelayCandidate),
            "disabled policy must not surface any relay-side error, got {err:?}"
        );
        assert_eq!(
            agent.peer_relay().stats().snapshot().relay_sent,
            0,
            "disabled policy must not advance relay_sent"
        );
    }

    #[tokio::test]
    async fn relay_dm_listener_refuses_bad_signature_and_ticks_counter() {
        // Why: the receiver-side surface for X0X-0070b - a single
        // demux arm + a listener loop that runs `disposition_for` and
        // dispatches the three arms - depends on the listener actually
        // draining `network.recv_relayed_dm`. If the spawn ever drops
        // (forgotten in `AgentBuilder::build`, or the wire/channel
        // shape drifts) the engine silently stops refusing replays
        // and forwards, and the bug presents as "relay path is
        // configured but nothing happens." Pin the end-to-end
        // channel + loop liveness with the cheapest fully-typed
        // signal we have: a `RelayedDm` with an obviously-broken
        // header signature flows through the channel, the listener
        // consumes it, `disposition_for` returns
        // `Refuse(BadSignature)`, and the
        // `relay_refused_bad_signature` counter ticks. Catches any
        // future channel-rename / spawn-drop / wire-type regression.
        let dir = tempfile::tempdir().expect("tmpdir");
        let mut net_cfg = loopback_network_config();
        net_cfg.peer_relay = network::PeerRelayConfig {
            enabled: true,
            require_contact_to_relay: false,
            fail_threshold: 3,
            fail_window_ms: 60_000,
            candidates: Vec::new(),
            ..Default::default()
        };
        let agent = Agent::builder()
            .with_machine_key(dir.path().join("machine.key"))
            .with_agent_key_path(dir.path().join("agent.key"))
            .with_contact_store_path(dir.path().join("contacts.json"))
            .with_peer_cache_disabled()
            .with_network_config(net_cfg)
            .build()
            .await
            .expect("agent");

        let network = agent
            .network
            .as_ref()
            .expect("agent built with network config");
        let sender = network.test_relayed_dm_sender();

        let relayed = peer_relay::RelayedDm {
            header: peer_relay::RelayHeader {
                version: peer_relay::RelayHeader::VERSION,
                dst_agent_id: agent.agent_id().0,
                sender_agent_id: [0x42; 32],
                // Empty pubkey + signature: header.verify() must fail.
                sender_public_key: Vec::new(),
                originated_at_unix_ms: dm::now_unix_ms(),
                signature: Vec::new(),
            },
            inner: dm::DmEnvelope {
                protocol_version: 1,
                request_id: [0u8; 16],
                sender_agent_id: [0x42; 32],
                sender_machine_id: [0x43; 32],
                recipient_agent_id: agent.agent_id().0,
                created_at_unix_ms: 0,
                expires_at_unix_ms: 0,
                body: dm::DmBody::Payload(dm::DmPayload {
                    kem_ciphertext: Vec::new(),
                    body_nonce: [0u8; 12],
                    body_ciphertext: Vec::new(),
                }),
                signature: Vec::new(),
            },
        };

        let relay_peer = ant_quic::PeerId([0xEE; 32]);
        let relay_wire_sender = [0xEE; 32];
        sender
            .send((relay_peer, relay_wire_sender, relayed))
            .await
            .expect("relayed_dm channel must accept push");

        // Spin until the listener observes the refusal - bounded so a
        // regression fails fast rather than timing out the suite.
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
        loop {
            let snap = agent.peer_relay().stats().snapshot();
            if snap.relay_refused_bad_signature == 1 {
                break;
            }
            if std::time::Instant::now() >= deadline {
                panic!(
                    "relay-DM listener did not tick relay_refused_bad_signature within 2s - \
                     snapshot: {snap:?}"
                );
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }

        let snap = agent.peer_relay().stats().snapshot();
        assert_eq!(snap.relay_refused_bad_signature, 1);
        assert_eq!(snap.relay_received, 0, "bad-sig path must not deliver");
        assert_eq!(snap.relay_forwarded, 0, "bad-sig path must not forward");
    }

    #[tokio::test]
    async fn agent_creates() {
        let agent = Agent::new().await;
        assert!(agent.is_ok());
    }

    #[tokio::test]
    async fn agent_joins_network() {
        let agent = Agent::new().await.unwrap();
        assert!(agent.join_network().await.is_ok());
    }

    #[tokio::test]
    async fn agent_subscribes() {
        let agent = Agent::new().await.unwrap();
        // Currently returns error - will be implemented in Task 3
        assert!(agent.subscribe("test-topic").await.is_err());
    }

    #[tokio::test]
    async fn identity_announcement_machine_signature_verifies() {
        let agent = Agent::builder()
            .with_network_config(network::NetworkConfig::default())
            .build()
            .await
            .unwrap();

        let announcement = agent.build_identity_announcement(false, false).unwrap();
        assert_eq!(announcement.agent_id, agent.agent_id());
        assert_eq!(announcement.machine_id, agent.machine_id());
        assert!(announcement.user_id.is_none());
        assert!(announcement.agent_certificate.is_none());
        assert!(announcement.verify().is_ok());
    }

    #[tokio::test]
    async fn identity_announcement_requires_human_consent() {
        let agent = Agent::builder()
            .with_network_config(network::NetworkConfig::default())
            .build()
            .await
            .unwrap();

        let err = agent.build_identity_announcement(true, false).unwrap_err();
        assert!(
            err.to_string().contains("explicit human consent"),
            "unexpected error: {err}"
        );
    }

    #[tokio::test]
    async fn identity_announcement_with_user_requires_user_identity() {
        let agent = Agent::builder()
            .with_network_config(network::NetworkConfig::default())
            .build()
            .await
            .unwrap();

        let err = agent.build_identity_announcement(true, true).unwrap_err();
        assert!(
            err.to_string().contains("no user identity is configured"),
            "unexpected error: {err}"
        );
    }

    #[tokio::test]
    async fn announce_identity_populates_discovery_cache() {
        let user_key = identity::UserKeypair::generate().unwrap();
        let agent = Agent::builder()
            .with_network_config(network::NetworkConfig::default())
            .with_user_key(user_key)
            .build()
            .await
            .unwrap();

        agent.announce_identity(true, true).await.unwrap();
        let discovered = agent.discovered_agent(agent.agent_id()).await.unwrap();
        let entry = discovered.expect("agent should discover its own announcement");

        assert_eq!(entry.agent_id, agent.agent_id());
        assert_eq!(entry.machine_id, agent.machine_id());
        assert_eq!(entry.user_id, agent.user_id());
    }

    /// Enforcement point 2 (issue #130): a revoked agent MUST fail
    /// `is_agent_machine_verified` even when its signed identity announcement
    /// is still sitting verified in the discovery cache. This is the DM/gate
    /// denial property — a revoked peer is refused everywhere the daemon asks
    /// "is this (agent, machine) binding trustworthy?". The revocation is
    /// applied via the real `verify_and_insert` receive path (the same call
    /// the gossip subscription makes on receipt), and the subject is
    /// self-revoked (issuer key == subject agent-id, valid authority).
    #[tokio::test]
    async fn revoked_agent_fails_machine_verification_even_when_cached() {
        let user_key = identity::UserKeypair::generate().unwrap();
        let agent = Agent::builder()
            .with_network_config(network::NetworkConfig::default())
            .with_user_key(user_key)
            .build()
            .await
            .unwrap();

        // Seed the discovery cache with our own signed announcement so the
        // (agent, machine) binding verifies true BEFORE revocation.
        agent.announce_identity(true, true).await.unwrap();
        let agent_id = agent.agent_id();
        let machine_id = agent.machine_id();
        assert!(
            agent
                .is_agent_machine_verified(&agent_id, &machine_id)
                .await,
            "a cached, signed self-announcement must verify before revocation"
        );

        // Apply a valid SELF-revocation of our own agent-id via the real
        // receive path. verify_and_insert re-checks the ML-DSA signature and
        // the self-revocation authority rule, exactly as on gossip receipt.
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let record = revocation::RevocationRecord::sign(
            revocation::RevokedSubject::Agent(agent_id),
            agent.identity().agent_keypair().public_key(),
            agent.identity().agent_keypair().secret_key(),
            now,
            Some("ep2 test: key compromised".to_string()),
        )
        .unwrap();
        {
            let set = agent.revocation_set();
            let mut set = set.write().await;
            set.verify_and_insert(record, None)
                .expect("self-revocation must verify and insert");
        }

        // Fail-closed: the verified gate must now refuse the revoked agent,
        // even though its announcement is still cached and otherwise valid.
        assert!(
            !agent
                .is_agent_machine_verified(&agent_id, &machine_id)
                .await,
            "a revoked agent must never pass machine verification while cached"
        );
    }

    /// Issue #191 gap 2: a gossiped **issuer-revocation** (a user un-vouching
    /// a certified agent) MUST propagate over gossip. The gossip wire carries
    /// bare `RevocationRecord`s (no certs), so the receiver resolves the
    /// subject cert from its discovery cache — via `collect_subject_certs`,
    /// the exact lookup the gossip-receive loop now performs — and passes it
    /// to `verify_and_insert`. Pre-fix the loop passed `None`, and
    /// `verify_authority` rejects an issuer-revocation without a cert, so only
    /// self-revocations ever propagated network-wide.
    #[test]
    fn issuer_revocation_propagates_over_gossip_via_cache_cert_lookup() {
        let user = identity::UserKeypair::generate().unwrap();
        let issued_agent = identity::AgentKeypair::generate().unwrap();
        let agent_id = issued_agent.agent_id();
        // The user vouches for the agent — this cert is what authorizes a
        // later issuer-revocation (verify_authority checks the issuer key is
        // the certifying user).
        let cert = identity::AgentCertificate::issue(&user, &issued_agent).unwrap();

        // Seed the discovery cache exactly as EP1 does on a real announcement:
        // the cert is retained so a gossiped issuer-revocation can be verified.
        let mut cache = std::collections::HashMap::new();
        cache.insert(
            agent_id,
            DiscoveredAgent {
                agent_id,
                machine_id: identity::MachineId([0u8; 32]),
                user_id: None,
                addresses: Vec::new(),
                announced_at: 0,
                last_seen: 0,
                machine_public_key: Vec::new(),
                nat_type: None,
                can_receive_direct: None,
                is_relay: None,
                is_coordinator: None,
                reachable_via: Vec::new(),
                relay_candidates: Vec::new(),
                cert_not_after: cert.not_after(),
                agent_certificate: Some(cert.clone()),
                agent_public_key: cert.agent_public_key().to_vec(),
            },
        );

        // The gossip-receive path resolves subject certs from the cache.
        let subject_certs = collect_subject_certs(&cache);
        let looked_up = subject_certs
            .get(&agent_id)
            .expect("the cache lookup must find the subject cert");

        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        // The user revokes the agent it vouched for (issuer-revocation).
        let record = revocation::RevocationRecord::sign(
            revocation::RevokedSubject::Agent(agent_id),
            user.public_key(),
            user.secret_key(),
            now,
            Some("issuer revokes compromised agent".to_string()),
        )
        .unwrap();

        // With the cache-resolved cert, the issuer-revocation verifies +
        // inserts (the post-fix gossip behavior).
        let mut set = revocation::RevocationSet::new();
        assert!(
            set.verify_and_insert(record.clone(), Some(looked_up))
                .unwrap(),
            "issuer-revocation must verify and insert with the cache-resolved cert"
        );
        assert!(
            set.is_agent_revoked(&agent_id),
            "the agent must now be revoked network-wide"
        );

        // Pre-fix proof: without the cert (the old `None` gossip path), an
        // issuer-revocation is REJECTED by verify_authority — which is exactly
        // why issuer-revocations were inert over gossip before this fix.
        assert!(
            revocation::RevocationSet::new()
                .verify_and_insert(record, None)
                .is_err(),
            "an issuer-revocation must be rejected without the subject cert \
             (the pre-fix gossip behavior this closes)"
        );
    }

    /// An announcement without NAT fields (as produced by old nodes) should still
    /// deserialise correctly via bincode — new fields are `Option` so `None` (0x00)
    /// is a valid encoding.
    #[test]
    fn identity_announcement_backward_compat_no_nat_fields() {
        use identity::{AgentId, MachineId};

        // Build an announcement that omits the nat_* fields by serializing an old-style
        // struct that matches the pre-1.3 wire format.
        #[derive(serde::Serialize, serde::Deserialize)]
        struct OldIdentityAnnouncementUnsigned {
            agent_id: AgentId,
            machine_id: MachineId,
            user_id: Option<identity::UserId>,
            agent_certificate: Option<identity::AgentCertificate>,
            machine_public_key: Vec<u8>,
            addresses: Vec<std::net::SocketAddr>,
            announced_at: u64,
        }

        let agent_id = AgentId([1u8; 32]);
        let machine_id = MachineId([2u8; 32]);
        let old = OldIdentityAnnouncementUnsigned {
            agent_id,
            machine_id,
            user_id: None,
            agent_certificate: None,
            machine_public_key: vec![0u8; 10],
            addresses: Vec::new(),
            announced_at: 1234,
        };
        let bytes = bincode::serialize(&old).expect("serialize old announcement");

        // Attempt to deserialize as the new struct — this tests that the new fields
        // (which are Option<T>) do NOT break deserialization of the old format.
        // Note: bincode 1.x is not self-describing, so adding fields to a struct DOES
        // change the wire format.  This test documents the expected behavior.
        // Old format -> new struct: will fail because new struct has more fields.
        // New format -> old struct: will have trailing bytes.
        // This is acceptable — we document the protocol change.
        let result = bincode::deserialize::<IdentityAnnouncementUnsigned>(&bytes);
        // Old nodes produce shorter messages; new nodes cannot decode them as new structs.
        // This confirms the protocol is not transparent — nodes must upgrade together.
        assert!(
            result.is_err(),
            "Old-format announcement should not decode as new struct (protocol upgrade required)"
        );
    }

    #[tokio::test]
    async fn register_announced_machine_skips_self_agent() {
        // The daemon must never create a contact entry for its own agent: a
        // self record is noise on `/contacts` and makes contact-set
        // assertions racy (issue #145). A self-announcement is refused even
        // though it carries a valid (agent, machine) pair.
        let dir = tempfile::tempdir().expect("tmpdir");
        let store = std::sync::Arc::new(tokio::sync::RwLock::new(contacts::ContactStore::new(
            dir.path().join("contacts.json"),
        )));
        let own = identity::AgentId([1u8; 32]);
        let own_machine = identity::MachineId([2u8; 32]);

        let added = super::register_announced_machine(&store, own, own, own_machine).await;

        assert!(!added, "self-announcement must not register a machine");
        let store = store.read().await;
        assert!(
            store.machines(&own).is_empty(),
            "self-agent must have no machine record after a self-announcement"
        );
        // Stronger invariant: the daemon must have NO contact entry at all
        // for its own agent, not merely an empty machine list. add_machine
        // creates the Contact shell on first sight (contacts.rs:423), so this
        // confirms the self-skip happens before that insertion (#145).
        assert!(
            store.list().iter().all(|contact| contact.agent_id != own),
            "self-agent must not appear in the contact store at all after a \
             self-announcement"
        );
    }

    #[tokio::test]
    async fn register_announced_machine_registers_foreign_agent() {
        // Foreign observation must keep registering a machine record so peers
        // remain observable in the contact surface — the self-skip must not be
        // over-broad. A second announcement of the same (agent, machine) is
        // idempotent (returns false, no duplicate record).
        let dir = tempfile::tempdir().expect("tmpdir");
        let store = std::sync::Arc::new(tokio::sync::RwLock::new(contacts::ContactStore::new(
            dir.path().join("contacts.json"),
        )));
        let own = identity::AgentId([1u8; 32]);
        let peer = identity::AgentId([9u8; 32]);
        let peer_machine = identity::MachineId([7u8; 32]);

        let added = super::register_announced_machine(&store, own, peer, peer_machine).await;
        assert!(added, "foreign announcement must register a new machine");

        let added_again = super::register_announced_machine(&store, own, peer, peer_machine).await;
        assert!(
            !added_again,
            "re-announcing the same machine must be idempotent"
        );

        let store = store.read().await;
        let machines = store.machines(&peer);
        assert_eq!(machines.len(), 1, "exactly one machine record");
        assert_eq!(machines[0].machine_id, peer_machine);
        assert!(
            store.machines(&own).is_empty(),
            "own agent must still have no contact entry"
        );
    }

    #[test]
    fn announcement_assist_snapshot_uses_capabilities_not_activity() {
        let status = ant_quic::NodeStatus {
            nat_type: ant_quic::NatType::FullCone,
            can_receive_direct: true,
            relay_service_enabled: true,
            coordinator_service_enabled: true,
            is_relaying: false,
            is_coordinating: false,
            ..Default::default()
        };

        let snapshot = AnnouncementAssistSnapshot::from_node_status(&status);
        assert_eq!(snapshot.nat_type.as_deref(), Some("Full Cone"));
        assert_eq!(snapshot.can_receive_direct, Some(true));
        assert_eq!(snapshot.relay_capable, Some(true));
        assert_eq!(snapshot.coordinator_capable, Some(true));
        assert_eq!(snapshot.relay_active, Some(false));
        assert_eq!(snapshot.coordinator_active, Some(false));
    }

    /// A new announcement with all NAT fields set round-trips through bincode.
    #[test]
    fn identity_announcement_nat_fields_round_trip() {
        use identity::{AgentId, MachineId};

        let unsigned = IdentityAnnouncementUnsigned {
            agent_id: AgentId([1u8; 32]),
            machine_id: MachineId([2u8; 32]),
            user_id: None,
            agent_certificate: None,
            machine_public_key: vec![0u8; 10],
            addresses: Vec::new(),
            announced_at: 9999,
            nat_type: Some("FullCone".to_string()),
            can_receive_direct: Some(true),
            is_relay: Some(false),
            is_coordinator: Some(true),
            reachable_via: vec![MachineId([5u8; 32])],
            relay_candidates: vec![MachineId([6u8; 32])],
        };
        let bytes = bincode::serialize(&unsigned).expect("serialize");
        let decoded: IdentityAnnouncementUnsigned =
            bincode::deserialize(&bytes).expect("deserialize");
        assert_eq!(decoded.nat_type.as_deref(), Some("FullCone"));
        assert_eq!(decoded.can_receive_direct, Some(true));
        assert_eq!(decoded.is_relay, Some(false));
        assert_eq!(decoded.is_coordinator, Some(true));
        assert_eq!(decoded.reachable_via, vec![MachineId([5u8; 32])]);
        assert_eq!(decoded.relay_candidates, vec![MachineId([6u8; 32])]);
    }

    #[tokio::test]
    async fn announcement_decode_helpers_match_bincode_serialize_wire_format() {
        let temp = tempfile::tempdir().unwrap();
        let agent = Agent::builder()
            .with_machine_key(temp.path().join("machine.key"))
            .with_agent_key_path(temp.path().join("agent.key"))
            .with_agent_cert_path(temp.path().join("agent.cert"))
            .with_contact_store_path(temp.path().join("contacts.json"))
            .build()
            .await
            .unwrap();

        let identity = agent.build_identity_announcement(false, false).unwrap();
        let identity_bytes = serialize_identity_announcement(&identity).unwrap();
        let decoded_identity = deserialize_identity_announcement(&identity_bytes).unwrap();
        assert_eq!(decoded_identity.agent_id, identity.agent_id);
        assert_eq!(decoded_identity.machine_id, identity.machine_id);
        // The v2 envelope must carry the agent public key (#204).
        assert_eq!(decoded_identity.agent_public_key, identity.agent_public_key);
        assert!(
            !decoded_identity.agent_public_key.is_empty(),
            "v2 announcement must carry the agent public key"
        );
        let machine = agent.build_machine_announcement().unwrap();
        let machine_bytes = bincode::serialize(&machine).unwrap();
        let decoded_machine = deserialize_machine_announcement(&machine_bytes).unwrap();
        assert_eq!(decoded_machine.machine_id, machine.machine_id);
        assert_eq!(decoded_machine.addresses, machine.addresses);
    }

    #[tokio::test]
    async fn deserialize_identity_announcement_rejects_trailing_bytes() {
        let temp = tempfile::tempdir().unwrap();
        let agent = Agent::builder()
            .with_machine_key(temp.path().join("machine.key"))
            .with_agent_key_path(temp.path().join("agent.key"))
            .with_agent_cert_path(temp.path().join("agent.cert"))
            .with_contact_store_path(temp.path().join("contacts.json"))
            .build()
            .await
            .unwrap();

        let announcement = agent.build_identity_announcement(false, false).unwrap();
        let mut bytes = bincode::serialize(&announcement).unwrap();
        bytes.extend_from_slice(&[0xde, 0xad, 0xbe, 0xef]);

        assert!(
            deserialize_identity_announcement(&bytes).is_err(),
            "identity announcements with trailing bytes must be rejected"
        );
    }

    /// An announcement with None for all NAT fields (e.g. network not started)
    /// round-trips correctly.
    #[test]
    fn identity_announcement_no_nat_fields_round_trip() {
        use identity::{AgentId, MachineId};

        let unsigned = IdentityAnnouncementUnsigned {
            agent_id: AgentId([3u8; 32]),
            machine_id: MachineId([4u8; 32]),
            user_id: None,
            agent_certificate: None,
            machine_public_key: vec![0u8; 10],
            addresses: Vec::new(),
            announced_at: 42,
            nat_type: None,
            can_receive_direct: None,
            is_relay: None,
            is_coordinator: None,
            reachable_via: Vec::new(),
            relay_candidates: Vec::new(),
        };
        let bytes = bincode::serialize(&unsigned).expect("serialize");
        let decoded: IdentityAnnouncementUnsigned =
            bincode::deserialize(&bytes).expect("deserialize");
        assert!(decoded.nat_type.is_none());
        assert!(decoded.can_receive_direct.is_none());
        assert!(decoded.is_relay.is_none());
        assert!(decoded.is_coordinator.is_none());
        assert!(decoded.reachable_via.is_empty());
        assert!(decoded.relay_candidates.is_empty());
    }

    /// Wire format v2 populates coordinator-hint fields: full round-trip and
    /// deterministic signing.
    #[test]
    fn identity_announcement_reachable_via_round_trip() {
        use identity::{AgentId, MachineId};

        let coord_a = MachineId([0xAAu8; 32]);
        let coord_b = MachineId([0xBBu8; 32]);
        let unsigned = IdentityAnnouncementUnsigned {
            agent_id: AgentId([9u8; 32]),
            machine_id: MachineId([8u8; 32]),
            user_id: None,
            agent_certificate: None,
            machine_public_key: vec![0u8; 10],
            addresses: Vec::new(),
            announced_at: 555,
            nat_type: Some("Symmetric".to_string()),
            can_receive_direct: Some(false),
            is_relay: Some(false),
            is_coordinator: Some(false),
            reachable_via: vec![coord_a, coord_b],
            relay_candidates: vec![coord_a],
        };
        let bytes = bincode::serialize(&unsigned).expect("serialize");
        let decoded: IdentityAnnouncementUnsigned =
            bincode::deserialize(&bytes).expect("deserialize");
        assert_eq!(decoded.reachable_via, vec![coord_a, coord_b]);
        assert_eq!(decoded.relay_candidates, vec![coord_a]);

        // Mutating reachable_via MUST invalidate the outer sig — signing over
        // the unsigned form guarantees integrity. Here we only verify the
        // bincode is stable; cryptographic coverage lives in the existing
        // `identity_announcement_machine_signature_verifies` tests.
        let re_encoded = bincode::serialize(&decoded).expect("re-serialize");
        assert_eq!(
            bytes, re_encoded,
            "canonical bincode round-trip must be stable"
        );
    }

    #[test]
    fn user_announcement_sign_and_verify() {
        let user_kp = identity::UserKeypair::generate().unwrap();
        let agent_kp_a = identity::AgentKeypair::generate().unwrap();
        let agent_kp_b = identity::AgentKeypair::generate().unwrap();
        let cert_a = identity::AgentCertificate::issue(&user_kp, &agent_kp_a).unwrap();
        let cert_b = identity::AgentCertificate::issue(&user_kp, &agent_kp_b).unwrap();

        let announcement = UserAnnouncement::sign(&user_kp, vec![cert_a, cert_b], 1234).unwrap();
        announcement.verify().expect("freshly-signed must verify");
        assert_eq!(announcement.user_id, user_kp.user_id());
        assert_eq!(announcement.agent_certificates.len(), 2);
    }

    #[test]
    fn deserialize_user_announcement_rejects_trailing_bytes() {
        let user_kp = identity::UserKeypair::generate().unwrap();
        let agent_kp = identity::AgentKeypair::generate().unwrap();
        let cert = identity::AgentCertificate::issue(&user_kp, &agent_kp).unwrap();
        let announcement = UserAnnouncement::sign(&user_kp, vec![cert], 1234).unwrap();
        let mut bytes = bincode::serialize(&announcement).unwrap();
        bytes.extend_from_slice(&[0xde, 0xad, 0xbe, 0xef]);

        assert!(
            deserialize_user_announcement(&bytes).is_err(),
            "user announcements with trailing bytes must be rejected"
        );
    }

    #[test]
    fn user_announcement_rejects_foreign_certificate() {
        let user_kp = identity::UserKeypair::generate().unwrap();
        let other_user = identity::UserKeypair::generate().unwrap();
        let agent_kp = identity::AgentKeypair::generate().unwrap();
        // Certificate issued by `other_user` — we should refuse to include it
        // in a roster signed by `user_kp`.
        let foreign_cert = identity::AgentCertificate::issue(&other_user, &agent_kp).unwrap();
        let err = UserAnnouncement::sign(&user_kp, vec![foreign_cert], 0).unwrap_err();
        assert!(
            err.to_string().contains("different user"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn user_announcement_tampered_agent_cert_list_fails() {
        let user_kp = identity::UserKeypair::generate().unwrap();
        let agent_kp = identity::AgentKeypair::generate().unwrap();
        let cert = identity::AgentCertificate::issue(&user_kp, &agent_kp).unwrap();

        let mut announcement = UserAnnouncement::sign(&user_kp, vec![cert], 10).unwrap();
        // Forge an additional certificate from a different user into the list.
        let other_user = identity::UserKeypair::generate().unwrap();
        let other_agent = identity::AgentKeypair::generate().unwrap();
        let foreign_cert = identity::AgentCertificate::issue(&other_user, &other_agent).unwrap();
        announcement.agent_certificates.push(foreign_cert);
        assert!(
            announcement.verify().is_err(),
            "announcement with appended foreign cert must fail verification"
        );
    }

    #[test]
    fn user_announcement_tampered_user_public_key_fails() {
        let user_kp = identity::UserKeypair::generate().unwrap();
        let agent_kp = identity::AgentKeypair::generate().unwrap();
        let cert = identity::AgentCertificate::issue(&user_kp, &agent_kp).unwrap();
        let mut announcement = UserAnnouncement::sign(&user_kp, vec![cert], 10).unwrap();
        let other = identity::UserKeypair::generate().unwrap();
        announcement.user_public_key = other.public_key().as_bytes().to_vec();
        assert!(announcement.verify().is_err());
    }

    #[test]
    fn user_shard_topic_is_deterministic() {
        let user_id = identity::UserId([5u8; 32]);
        let topic_a = shard_topic_for_user(&user_id);
        let topic_b = shard_topic_for_user(&user_id);
        assert_eq!(topic_a, topic_b);
        assert!(topic_a.starts_with("x0x.user.shard.v2."));
    }
}
#[test]
fn agent_shard_topic_is_deterministic() {
    let agent_id = identity::AgentId([6u8; 32]);
    let topic_a = shard_topic_for_agent(&agent_id);
    let topic_b = shard_topic_for_agent(&agent_id);
    assert_eq!(topic_a, topic_b);
    assert!(topic_a.starts_with("x0x.identity.shard.v2."));
}

#[test]
fn machine_shard_topic_is_deterministic() {
    let machine_id = identity::MachineId([7u8; 32]);
    let topic_a = shard_topic_for_machine(&machine_id);
    let topic_b = shard_topic_for_machine(&machine_id);
    assert_eq!(topic_a, topic_b);
    assert!(topic_a.starts_with("x0x.machine.shard.v2."));
}

#[test]
fn rendezvous_shard_topic_is_deterministic() {
    let agent_id = identity::AgentId([8u8; 32]);
    let topic_a = rendezvous_shard_topic_for_agent(&agent_id);
    let topic_b = rendezvous_shard_topic_for_agent(&agent_id);
    assert_eq!(topic_a, topic_b);
    assert!(topic_a.starts_with("x0x.rendezvous.shard."));
}

#[test]
fn different_ids_produce_different_shard_topics() {
    let agent_a = identity::AgentId([1u8; 32]);
    let agent_b = identity::AgentId([2u8; 32]);
    let topic_a = shard_topic_for_agent(&agent_a);
    let topic_b = shard_topic_for_agent(&agent_b);
    assert_ne!(
        topic_a, topic_b,
        "different agent IDs should produce different shard topics"
    );
}

#[test]
fn collect_local_interface_addrs_returns_non_empty() {
    let addrs = collect_local_interface_addrs(5483);
    assert!(!addrs.is_empty(), "should find at least one interface");
    for addr in &addrs {
        assert_eq!(addr.port(), 5483, "all addrs should use port 5483");
    }
}

#[test]
fn collect_local_interface_addrs_returns_reasonable_results() {
    let addrs = collect_local_interface_addrs(9000);
    assert!(!addrs.is_empty(), "should find at least one interface");
    for addr in &addrs {
        assert_eq!(addr.port(), 9000, "all addrs should use port 9000");
    }
}

#[test]
fn is_globally_routable_v4_private() {
    assert!(!is_globally_routable(std::net::IpAddr::V4(
        std::net::Ipv4Addr::new(10, 0, 0, 1)
    )));
    assert!(!is_globally_routable(std::net::IpAddr::V4(
        std::net::Ipv4Addr::new(172, 16, 0, 1)
    )));
    assert!(!is_globally_routable(std::net::IpAddr::V4(
        std::net::Ipv4Addr::new(192, 168, 1, 1)
    )));
}

#[test]
fn is_globally_routable_v4_global() {
    assert!(is_globally_routable(std::net::IpAddr::V4(
        std::net::Ipv4Addr::new(8, 8, 8, 8)
    )));
    assert!(is_globally_routable(std::net::IpAddr::V4(
        std::net::Ipv4Addr::new(1, 2, 3, 4)
    )));
}

#[test]
fn is_globally_routable_v6_private() {
    assert!(!is_globally_routable(std::net::IpAddr::V6(
        std::net::Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1)
    )));
    assert!(!is_globally_routable(std::net::IpAddr::V6(
        std::net::Ipv6Addr::new(0xfc00, 0, 0, 0, 0, 0, 0, 1)
    )));
    assert!(!is_globally_routable(std::net::IpAddr::V6(
        std::net::Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)
    )));
}

#[test]
fn is_globally_routable_v6_global() {
    assert!(is_globally_routable(std::net::IpAddr::V6(
        std::net::Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1)
    )));
    assert!(is_globally_routable(std::net::IpAddr::V6(
        std::net::Ipv6Addr::new(0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8888)
    )));
}

#[test]
fn is_globally_routable_v4_cgnat() {
    assert!(!is_globally_routable(std::net::IpAddr::V4(
        std::net::Ipv4Addr::new(100, 64, 0, 1)
    )));
    assert!(!is_globally_routable(std::net::IpAddr::V4(
        std::net::Ipv4Addr::new(100, 127, 255, 255)
    )));
}

#[test]
fn is_globally_routable_v4_documentation() {
    assert!(!is_globally_routable(std::net::IpAddr::V4(
        std::net::Ipv4Addr::new(192, 0, 2, 1)
    )));
    assert!(!is_globally_routable(std::net::IpAddr::V4(
        std::net::Ipv4Addr::new(198, 51, 100, 1)
    )));
    assert!(!is_globally_routable(std::net::IpAddr::V4(
        std::net::Ipv4Addr::new(203, 0, 113, 1)
    )));
}

#[test]
fn is_globally_routable_v4_broadcast() {
    assert!(!is_globally_routable(std::net::IpAddr::V4(
        std::net::Ipv4Addr::new(255, 255, 255, 255)
    )));
}

#[test]
fn is_globally_routable_v4_unspecified() {
    assert!(!is_globally_routable(std::net::IpAddr::V4(
        std::net::Ipv4Addr::new(0, 0, 0, 0)
    )));
}

#[test]
fn is_globally_routable_v6_unspecified() {
    assert!(!is_globally_routable(std::net::IpAddr::V6(
        std::net::Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)
    )));
}

#[test]
fn is_globally_routable_v6_unique_local() {
    assert!(!is_globally_routable(std::net::IpAddr::V6(
        std::net::Ipv6Addr::new(0xfd00, 0, 0, 0, 0, 0, 0, 1)
    )));
}

#[test]
fn is_globally_routable_v6_site_local() {
    assert!(!is_globally_routable(std::net::IpAddr::V6(
        std::net::Ipv6Addr::new(0xfec0, 0, 0, 0, 0, 0, 0, 1)
    )));
}

#[test]
fn push_unique_adds_new_item() {
    let mut items = vec![1, 2, 3];
    push_unique(&mut items, 4);
    assert_eq!(items, vec![1, 2, 3, 4]);
}

#[test]
fn push_unique_skips_existing_item() {
    let mut items = vec![1, 2, 3];
    push_unique(&mut items, 2);
    assert_eq!(items, vec![1, 2, 3]);
}

#[test]
fn push_unique_works_with_empty() {
    let mut items: Vec<i32> = vec![];
    push_unique(&mut items, 42);
    assert_eq!(items, vec![42]);
}

#[cfg(test)]
fn discovered_agent_fixture(
    tag: u8,
    announced_at: u64,
    addrs: &[&str],
    user_id: Option<identity::UserId>,
) -> DiscoveredAgent {
    DiscoveredAgent {
        agent_id: identity::AgentId([tag; 32]),
        machine_id: identity::MachineId([tag; 32]),
        user_id,
        addresses: addrs
            .iter()
            .map(|a| a.parse().expect("valid socket addr"))
            .collect(),
        announced_at,
        last_seen: announced_at,
        machine_public_key: vec![tag],
        nat_type: None,
        can_receive_direct: None,
        is_relay: None,
        is_coordinator: None,
        reachable_via: Vec::new(),
        relay_candidates: Vec::new(),
        cert_not_after: None,
        agent_certificate: None,
        agent_public_key: Vec::new(),
    }
}

#[cfg(test)]
fn signed_identity_announcement_fixture(
    agent_id: identity::AgentId,
    machine: &identity::MachineKeypair,
    announced_at: u64,
) -> IdentityAnnouncement {
    let machine_public_key = machine.public_key().as_bytes().to_vec();
    let unsigned = IdentityAnnouncementUnsigned {
        agent_id,
        machine_id: machine.machine_id(),
        user_id: None,
        agent_certificate: None,
        machine_public_key: machine_public_key.clone(),
        addresses: Vec::new(),
        announced_at,
        nat_type: None,
        can_receive_direct: None,
        is_relay: None,
        is_coordinator: None,
        reachable_via: Vec::new(),
        relay_candidates: Vec::new(),
    };
    let unsigned_bytes = bincode::serialize(&unsigned).expect("serialize announcement");
    let machine_signature = ant_quic::crypto::raw_public_keys::pqc::sign_with_ml_dsa(
        machine.secret_key(),
        &unsigned_bytes,
    )
    .expect("sign announcement")
    .as_bytes()
    .to_vec();
    IdentityAnnouncement {
        agent_id,
        machine_id: machine.machine_id(),
        user_id: None,
        agent_certificate: None,
        machine_public_key,
        machine_signature,
        addresses: Vec::new(),
        announced_at,
        nat_type: None,
        can_receive_direct: None,
        is_relay: None,
        is_coordinator: None,
        reachable_via: Vec::new(),
        relay_candidates: Vec::new(),
        agent_public_key: Vec::new(),
    }
}

#[cfg(test)]
fn verified_identity_origin_message(sender: &identity::AgentKeypair) -> gossip::PubSubMessage {
    gossip::PubSubMessage {
        topic: "identity-ingest-test".to_string(),
        payload: bytes::Bytes::new(),
        sender: Some(sender.agent_id()),
        sender_public_key: Some(sender.public_key().as_bytes().to_vec()),
        verified: true,
        trust_level: None,
    }
}

#[tokio::test]
async fn direct_origin_identity_ingest_populates_authenticated_binding() {
    let sender = identity::AgentKeypair::generate().expect("sender keygen");
    let machine = identity::MachineKeypair::generate().expect("machine keygen");
    let now = 1_000;
    let announcement = signed_identity_announcement_fixture(sender.agent_id(), &machine, now);
    announcement.verify().expect("valid machine announcement");
    let message = verified_identity_origin_message(&sender);
    let bindings = std::sync::Arc::new(tokio::sync::RwLock::new(
        dm_inbox::AuthenticatedMachineBindingCache::default(),
    ));

    assert!(
        record_authenticated_machine_binding_from_message(&bindings, &message, &announcement, now,)
            .await
    );
    assert_eq!(
        dm_inbox::authenticated_machine_binding_for_testing(&bindings, &sender.agent_id()).await,
        Some(machine.machine_id())
    );
}

#[tokio::test]
async fn wrong_origin_machine_announcement_cannot_populate_or_overwrite_binding() {
    let victim = identity::AgentKeypair::generate().expect("victim keygen");
    let attacker = identity::AgentKeypair::generate().expect("attacker keygen");
    let trusted_machine = identity::MachineKeypair::generate().expect("trusted machine keygen");
    let attacker_machine = identity::MachineKeypair::generate().expect("attacker machine keygen");
    let now = 2_000;
    let trusted = signed_identity_announcement_fixture(victim.agent_id(), &trusted_machine, now);
    let trusted_message = verified_identity_origin_message(&victim);
    let bindings = std::sync::Arc::new(tokio::sync::RwLock::new(
        dm_inbox::AuthenticatedMachineBindingCache::default(),
    ));
    assert!(
        record_authenticated_machine_binding_from_message(
            &bindings,
            &trusted_message,
            &trusted,
            now,
        )
        .await
    );

    let poisoned =
        signed_identity_announcement_fixture(victim.agent_id(), &attacker_machine, now + 1);
    poisoned.verify().expect("valid attacker machine signature");
    let attacker_message = verified_identity_origin_message(&attacker);
    assert!(
        !record_authenticated_machine_binding_from_message(
            &bindings,
            &attacker_message,
            &poisoned,
            now + 1,
        )
        .await
    );
    assert_eq!(
        dm_inbox::authenticated_machine_binding_for_testing(&bindings, &victim.agent_id()).await,
        Some(trusted_machine.machine_id())
    );
}

#[tokio::test]
async fn verified_rebroadcast_cannot_populate_or_overwrite_authenticated_binding() {
    let origin = identity::AgentKeypair::generate().expect("origin keygen");
    let relay = identity::AgentKeypair::generate().expect("relay keygen");
    let machine_a = identity::MachineKeypair::generate().expect("machine A keygen");
    let machine_b = identity::MachineKeypair::generate().expect("machine B keygen");
    let now = 3_000;
    let bindings = std::sync::Arc::new(tokio::sync::RwLock::new(
        dm_inbox::AuthenticatedMachineBindingCache::default(),
    ));
    let direct = signed_identity_announcement_fixture(origin.agent_id(), &machine_a, now);
    assert!(
        record_authenticated_machine_binding_from_message(
            &bindings,
            &verified_identity_origin_message(&origin),
            &direct,
            now,
        )
        .await
    );

    let rebroadcast = signed_identity_announcement_fixture(origin.agent_id(), &machine_b, now + 1);
    let relay_message = verified_identity_origin_message(&relay);
    assert!(
        !record_authenticated_machine_binding_from_message(
            &bindings,
            &relay_message,
            &rebroadcast,
            now + 1,
        )
        .await
    );
    assert_eq!(
        dm_inbox::authenticated_machine_binding_for_testing(&bindings, &origin.agent_id()).await,
        Some(machine_a.machine_id())
    );
}

#[tokio::test]
async fn missing_or_invalid_sender_key_cannot_populate_authenticated_binding() {
    let origin = identity::AgentKeypair::generate().expect("origin keygen");
    let machine = identity::MachineKeypair::generate().expect("machine keygen");
    let now = 4_000;
    let announcement = signed_identity_announcement_fixture(origin.agent_id(), &machine, now);
    let bindings = std::sync::Arc::new(tokio::sync::RwLock::new(
        dm_inbox::AuthenticatedMachineBindingCache::default(),
    ));

    let mut missing = verified_identity_origin_message(&origin);
    missing.sender_public_key = None;
    assert!(
        !record_authenticated_machine_binding_from_message(
            &bindings,
            &missing,
            &announcement,
            now,
        )
        .await
    );
    let mut invalid = verified_identity_origin_message(&origin);
    invalid.sender_public_key = Some(vec![0xFF; 8]);
    assert!(
        !record_authenticated_machine_binding_from_message(
            &bindings,
            &invalid,
            &announcement,
            now,
        )
        .await
    );
    assert_eq!(
        dm_inbox::authenticated_machine_binding_for_testing(&bindings, &origin.agent_id()).await,
        None
    );
}

#[tokio::test]
async fn far_future_direct_origin_cannot_poison_portable_move_ordering() {
    let origin = identity::AgentKeypair::generate().expect("origin keygen");
    let machine_a = identity::MachineKeypair::generate().expect("machine A keygen");
    let machine_b = identity::MachineKeypair::generate().expect("machine B keygen");
    let now = 5_000;
    let message = verified_identity_origin_message(&origin);
    let bindings = std::sync::Arc::new(tokio::sync::RwLock::new(
        dm_inbox::AuthenticatedMachineBindingCache::default(),
    ));
    let current = signed_identity_announcement_fixture(origin.agent_id(), &machine_a, now);
    assert!(
        record_authenticated_machine_binding_from_message(&bindings, &message, &current, now,)
            .await
    );

    let far_future = signed_identity_announcement_fixture(origin.agent_id(), &machine_b, u64::MAX);
    assert!(
        !record_authenticated_machine_binding_from_message(&bindings, &message, &far_future, now,)
            .await
    );
    assert_eq!(
        dm_inbox::authenticated_machine_binding_for_testing(&bindings, &origin.agent_id()).await,
        Some(machine_a.machine_id())
    );

    let normal_move = signed_identity_announcement_fixture(origin.agent_id(), &machine_b, now + 1);
    assert!(
        record_authenticated_machine_binding_from_message(
            &bindings,
            &message,
            &normal_move,
            now + 1,
        )
        .await
    );
    assert_eq!(
        dm_inbox::authenticated_machine_binding_for_testing(&bindings, &origin.agent_id()).await,
        Some(machine_b.machine_id())
    );
}

#[tokio::test]
async fn revocation_discovery_eviction_preserves_authenticated_binding() {
    let tempdir = tempfile::tempdir().expect("tempdir");
    let receiver = Agent::builder()
        .with_identity_dir(tempdir.path())
        .build()
        .await
        .expect("receiver agent");
    let origin = identity::AgentKeypair::generate().expect("origin keygen");
    let machine = identity::MachineKeypair::generate().expect("machine keygen");
    let now = 6_000;
    let announcement = signed_identity_announcement_fixture(origin.agent_id(), &machine, now);
    assert!(
        record_authenticated_machine_binding_from_message(
            &receiver.authenticated_machine_bindings,
            &verified_identity_origin_message(&origin),
            &announcement,
            now,
        )
        .await
    );
    let mut discovered = discovered_agent_fixture(0x66, now, &[], None);
    discovered.agent_id = origin.agent_id();
    discovered.machine_id = machine.machine_id();
    discovered.machine_public_key = machine.public_key().as_bytes().to_vec();
    receiver
        .insert_discovered_agent_for_testing(discovered)
        .await;
    assert!(receiver.cached_agent(&origin.agent_id()).await.is_some());

    receiver
        .evict_revoked_subject(&revocation::RevokedSubject::Machine(machine.machine_id()))
        .await;

    assert!(receiver.cached_agent(&origin.agent_id()).await.is_none());
    assert_eq!(
        dm_inbox::authenticated_machine_binding_for_testing(
            &receiver.authenticated_machine_bindings,
            &origin.agent_id(),
        )
        .await,
        Some(machine.machine_id())
    );
}

#[tokio::test]
async fn upsert_discovered_agent_replaces_addresses_on_fresher_announcement() {
    let cache = std::sync::Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new()));
    let id = identity::AgentId([7; 32]);

    upsert_discovered_agent(
        &cache,
        discovered_agent_fixture(7, 100, &["10.0.0.1:5483", "8.8.8.8:5483"], None),
    )
    .await;
    // A fresher announcement advertising a NEW address set must REPLACE, not
    // accumulate — otherwise a roaming agent grows an unbounded list of dead
    // endpoints that each cost a dial timeout.
    upsert_discovered_agent(
        &cache,
        discovered_agent_fixture(7, 200, &["1.2.3.4:5483"], None),
    )
    .await;

    let guard = cache.read().await;
    let entry = guard.get(&id).expect("entry present");
    assert_eq!(
        entry.addresses,
        vec!["1.2.3.4:5483".parse().expect("addr")],
        "fresher announcement must replace the address set, not union it"
    );
}

#[tokio::test]
async fn upsert_discovered_agent_ignores_stale_announcement_addresses() {
    let cache = std::sync::Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new()));
    let id = identity::AgentId([8; 32]);

    upsert_discovered_agent(
        &cache,
        discovered_agent_fixture(8, 200, &["1.2.3.4:5483"], None),
    )
    .await;
    // A stale (lower announced_at) announcement must not inject its old
    // addresses into the fresher cached record.
    upsert_discovered_agent(
        &cache,
        discovered_agent_fixture(8, 100, &["10.0.0.9:5483"], None),
    )
    .await;

    let guard = cache.read().await;
    let entry = guard.get(&id).expect("entry present");
    assert_eq!(
        entry.addresses,
        vec!["1.2.3.4:5483".parse().expect("addr")],
        "stale announcement must not add addresses"
    );
    assert_eq!(
        entry.announced_at, 200,
        "stale announcement must not regress announced_at"
    );
}

#[tokio::test]
async fn upsert_discovered_agent_preserves_known_user_id() {
    let cache = std::sync::Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new()));
    let id = identity::AgentId([9; 32]);
    let user = identity::UserId([9; 32]);

    upsert_discovered_agent(
        &cache,
        discovered_agent_fixture(9, 100, &["1.2.3.4:5483"], Some(user)),
    )
    .await;
    // A fresher but anonymous announcement must not erase a known user_id.
    upsert_discovered_agent(
        &cache,
        discovered_agent_fixture(9, 200, &["1.2.3.4:5483"], None),
    )
    .await;

    let guard = cache.read().await;
    let entry = guard.get(&id).expect("entry present");
    assert_eq!(
        entry.user_id,
        Some(user),
        "a fresher anonymous announcement must not erase a disclosed user_id"
    );
}

#[test]
fn sort_discovered_machine_sorts_fields() {
    let mut machine = DiscoveredMachine {
        machine_id: identity::MachineId([3u8; 32]),
        addresses: vec![
            "10.0.0.2:5483".parse::<std::net::SocketAddr>().unwrap(),
            "10.0.0.1:5483".parse::<std::net::SocketAddr>().unwrap(),
        ],
        announced_at: 100,
        last_seen: 100,
        machine_public_key: vec![],
        nat_type: None,
        can_receive_direct: None,
        is_relay: None,
        is_coordinator: None,
        reachable_via: vec![
            identity::MachineId([2u8; 32]),
            identity::MachineId([1u8; 32]),
        ],
        relay_candidates: vec![
            identity::MachineId([4u8; 32]),
            identity::MachineId([3u8; 32]),
        ],
        agent_ids: vec![identity::AgentId([2u8; 32]), identity::AgentId([1u8; 32])],
        user_ids: vec![identity::UserId([2u8; 32]), identity::UserId([1u8; 32])],
    };
    sort_discovered_machine(&mut machine);
    assert_eq!(
        machine.addresses[0],
        "10.0.0.1:5483".parse::<std::net::SocketAddr>().unwrap()
    );
    assert_eq!(
        machine.addresses[1],
        "10.0.0.2:5483".parse::<std::net::SocketAddr>().unwrap()
    );
    assert_eq!(machine.reachable_via[0], identity::MachineId([1u8; 32]));
    assert_eq!(machine.reachable_via[1], identity::MachineId([2u8; 32]));
    assert_eq!(machine.relay_candidates[0], identity::MachineId([3u8; 32]));
    assert_eq!(machine.relay_candidates[1], identity::MachineId([4u8; 32]));
    assert_eq!(machine.agent_ids[0], identity::AgentId([1u8; 32]));
    assert_eq!(machine.agent_ids[1], identity::AgentId([2u8; 32]));
    assert_eq!(machine.user_ids[0], identity::UserId([1u8; 32]));
    assert_eq!(machine.user_ids[1], identity::UserId([2u8; 32]));
}

#[tokio::test]
async fn dm_inbox_capability_upgrade_visible_to_late_subscriber() {
    // Regression test for issue #101: x0xd starts the DM inbox before the
    // capability advert service subscribes to the capabilities watch. The
    // upgrade must be stored in the channel (send_replace), not merely
    // broadcast to current receivers (send) — otherwise a late subscriber
    // observes the stale pending state, advertises gossip_inbox=false for
    // the process lifetime, and cross-NAT DMs fall back to the raw-QUIC
    // path that black-holes.
    let dir = tempfile::tempdir().expect("tmpdir");
    let agent = Agent::builder()
        .with_machine_key(dir.path().join("machine.key"))
        .with_agent_key_path(dir.path().join("agent.key"))
        .with_peer_cache_dir(dir.path().join("peers"))
        .with_network_config(network::NetworkConfig::default())
        .build()
        .await
        .expect("agent");

    let kem = std::sync::Arc::new(
        groups::kem_envelope::AgentKemKeypair::generate().expect("kem keypair"),
    );
    agent
        .start_dm_inbox(kem, dm_inbox::DmInboxConfig::default())
        .await
        .expect("start dm inbox");

    // Subscribe only AFTER the inbox started — mirrors the x0xd startup
    // order (start_dm_inbox_when_gossip_ready runs before
    // start_capability_advert_service).
    let late_rx = agent.dm_capabilities_tx.subscribe();
    let caps = late_rx.borrow().clone();
    assert!(
        caps.gossip_inbox,
        "DM capability upgrade must be visible to subscribers that attach after start_dm_inbox (issue #101)"
    );
    assert!(
        !caps.kem_public_key.is_empty(),
        "upgraded capabilities must carry the KEM public key"
    );
    agent.stop_dm_inbox().await;
}

#[test]
fn deserialize_identity_announcement_rejects_empty() {
    let result = deserialize_identity_announcement(&[]);
    assert!(result.is_err());
}

#[test]
fn deserialize_machine_announcement_rejects_empty() {
    let result = deserialize_machine_announcement(&[]);
    assert!(result.is_err());
}

#[test]
fn deserialize_identity_announcement_rejects_garbage() {
    let result = deserialize_identity_announcement(b"not-a-valid-bincode");
    assert!(result.is_err());
}

#[test]
fn deserialize_machine_announcement_rejects_garbage() {
    let result = deserialize_machine_announcement(b"not-a-valid-bincode");
    assert!(result.is_err());
}

// ---------------------------------------------------------------------------
// Restart-safe FenceToken: restart-epoch ABA fence (unit tests)
// ---------------------------------------------------------------------------
//
// FenceToken combines a per-replica epoch (regenerated on daemon restart via
// `fresh_epoch`) with the local revision. The handle accepts a caller's token
// only when BOTH match its current `(epoch, revision)` — i.e. exactly when
// `expected == current`. These tests pin that equality contract: an identical
// revision under a DIFFERENT epoch is rejected (closes the restart-ABA window
// without persisting task state), and a moved revision at the same epoch is
// rejected (stale local snapshot). The wire encoding is opaque to clients.

#[cfg(test)]
mod fence_token_tests {
    use crate::FenceToken;

    #[test]
    fn wire_roundtrip_preserves_epoch_and_revision() {
        let token = FenceToken {
            epoch: 123,
            revision: 456,
        };
        let wire = token.to_wire();
        let back = FenceToken::from_wire(&wire).expect("roundtrip parses");
        assert_eq!(back, token);
    }

    #[test]
    fn from_wire_returns_err_for_malformed_and_overflow_tokens() {
        // `from_wire` returns Result: a present-but-malformed/overflow token is
        // `Err`, which the PATCH handler maps to 400 BAD_REQUEST (non-mutating).
        // This is distinct from an ABSENT token (still a valid unfenced advisory
        // commit). A corrupt/legacy/overflow token can never bypass the guard or
        // silently downgrade to "no fence".
        assert!(FenceToken::from_wire("").is_err());
        assert!(FenceToken::from_wire("no-colon").is_err());
        assert!(FenceToken::from_wire(":5").is_err(), "missing epoch");
        assert!(FenceToken::from_wire("1:").is_err(), "missing revision");
        assert!(FenceToken::from_wire("1:2:3").is_err(), "too many parts");
        assert!(FenceToken::from_wire("abc:2").is_err(), "non-numeric epoch");
        assert!(
            FenceToken::from_wire("1:xyz").is_err(),
            "non-numeric revision"
        );
        // Integer overflow beyond u64 must be Err, not wrapped/truncated to a
        // bogus token that could ABA-match a real one.
        assert!(
            FenceToken::from_wire("999999999999999999999999999999:1").is_err(),
            "epoch overflow must be rejected"
        );
        assert!(
            FenceToken::from_wire("1:999999999999999999999999999999").is_err(),
            "revision overflow must be rejected"
        );
        // Teeth check: a well-formed token still parses to Ok, so the parser
        // rejects malformed input specifically, not all input.
        let ok = FenceToken::from_wire("123:456");
        assert!(ok.is_ok(), "well-formed token must parse");
        assert_eq!(
            ok.unwrap(),
            FenceToken {
                epoch: 123,
                revision: 456
            }
        );
    }

    #[test]
    fn same_revision_different_epoch_is_stale_the_restart_aba_breaker() {
        // The handle regenerates its epoch on restart (fresh_epoch). A token
        // captured BEFORE a restart carries the pre-restart epoch; even if the
        // revision counter later reaches the SAME value post-restart, the
        // epoch differs ⇒ the token is rejected. This is the restart-ABA fence.
        let pre_restart = FenceToken {
            epoch: 100,
            revision: 42,
        };
        let post_restart_same_revision = FenceToken {
            epoch: 999,
            revision: 42,
        };
        assert_ne!(
            pre_restart, post_restart_same_revision,
            "epoch differs ⇒ stale even at an identical revision (ABA safe)"
        );
        // An exact (epoch, revision) match is accepted.
        let current = FenceToken {
            epoch: 999,
            revision: 42,
        };
        assert_eq!(post_restart_same_revision, current, "exact match accepts");
    }

    #[test]
    fn stale_revision_at_same_epoch_is_stale() {
        // Within one epoch (no restart), a moved local snapshot (revision
        // advanced) also rejects the caller's stale token.
        let stale = FenceToken {
            epoch: 7,
            revision: 3,
        };
        let current = FenceToken {
            epoch: 7,
            revision: 4,
        };
        assert_ne!(stale, current, "revision moved ⇒ token is stale");
    }
}